1 # -*- coding: utf-8 -*-
3 import book_base as BookBase
10 # TODO: We are using os.popen3, which has been deprecated since python 2.6. The
11 # suggested replacement is the Popen function of the subprocess module.
12 # Unfortunately, on windows this needs the msvcrt module, which doesn't seem
13 # to be available in GUB?!?!?!
14 # from subprocess import Popen, PIPE
16 progress = ly.progress
19 debug = ly.debug_output
25 ####################################################################
26 # Snippet option handling
27 ####################################################################
31 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
34 ADDVERSION = 'addversion'
39 EXAMPLEINDENT = 'exampleindent'
44 LINE_WIDTH = 'line-width'
45 NOFRAGMENT = 'nofragment'
46 NOGETTEXT = 'nogettext'
49 NORAGGED_RIGHT = 'noragged-right'
53 OUTPUTIMAGE = 'outputimage'
55 PAPERSIZE = 'papersize'
57 PRINTFILENAME = 'printfilename'
59 RAGGED_RIGHT = 'ragged-right'
61 STAFFSIZE = 'staffsize'
64 VERSION = 'lilypondversion'
68 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
75 # Options that have no impact on processing by lilypond (or --process
77 PROCESSING_INDEPENDENT_OPTIONS = (
78 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
79 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
83 # Options without a pattern in snippet_options.
101 ####################################################################
102 # LilyPond templates for the snippets
103 ####################################################################
108 RELATIVE: r'''\relative c%(relative_quotes)s''',
113 PAPERSIZE: r'''#(set-paper-size "%(papersize)s")''',
114 INDENT: r'''indent = %(indent)s''',
115 LINE_WIDTH: r'''line-width = %(line-width)s''',
116 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
117 RAGGED_RIGHT: r'''ragged-right = ##t''',
118 NORAGGED_RIGHT: r'''ragged-right = ##f''',
130 \remove "Time_signature_engraver"
136 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
144 def classic_lilypond_book_compatibility (key, value):
145 if key == 'lilyquote':
146 return (QUOTE, value)
147 if key == 'singleline' and value == None:
148 return (RAGGED_RIGHT, None)
150 m = re.search ('relative\s*([-0-9])', key)
152 return ('relative', m.group (1))
154 m = re.match ('([0-9]+)pt', key)
156 return ('staffsize', m.group (1))
158 if key == 'indent' or key == 'line-width':
159 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
161 f = float (m.group (1))
162 return (key, '%f\\%s' % (f, m.group (2)))
167 # TODO: Remove the 1mm additional padding in the line-width, once lilypond
168 # creates tighter cropped images!
169 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
170 %%%% Options: [%(option_string)s]
171 \\include "lilypond-book-preamble.ly"
174 %% ****************************************************************
175 %% Start cut-&-pastable-section
176 %% ****************************************************************
182 %% offset the left padding, also add 1mm as lilypond creates cropped
183 %% images with a little space on the right
184 line-width = #(- line-width (* mm %(padding_mm)f) (* mm 1))
198 %% ****************************************************************
200 %% ****************************************************************
204 %% ****************************************************************
206 %% ****************************************************************
214 %% ****************************************************************
215 %% ly snippet contents follows:
216 %% ****************************************************************
220 %% ****************************************************************
222 %% ****************************************************************
229 ####################################################################
231 ####################################################################
233 def ps_page_count (ps_name):
234 header = file (ps_name).read (1024)
235 m = re.search ('\n%%Pages: ([0-9]+)', header)
237 return int (m.group (1))
240 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
241 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
242 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
243 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
245 def ly_comment_gettext (t, m):
246 return m.group (1) + t (m.group (2))
250 class CompileError(Exception):
255 ####################################################################
257 ####################################################################
260 def replacement_text (self):
263 def filter_text (self):
264 return self.replacement_text ()
269 class Substring (Chunk):
270 """A string that does not require extra memory."""
271 def __init__ (self, source, start, end, line_number):
275 self.line_number = line_number
276 self.override_text = None
281 def replacement_text (self):
282 if self.override_text:
283 return self.override_text
285 return self.source[self.start:self.end]
289 class Snippet (Chunk):
290 def __init__ (self, type, match, formatter, line_number, global_options):
294 self.option_dict = {}
295 self.formatter = formatter
296 self.line_number = line_number
297 self.global_options = global_options
298 self.replacements = {'program_version': ly.program_version,
299 'program_name': ly.program_name}
301 # return a shallow copy of the replacements, so the caller can modify
302 # it locally without interfering with other snippet operations
303 def get_replacements (self):
304 return copy.copy (self.replacements)
306 def replacement_text (self):
307 return self.match.group ('match')
309 def substring (self, s):
310 return self.match.group (s)
313 return `self.__class__` + ' type = ' + self.type
317 class IncludeSnippet (Snippet):
318 def processed_filename (self):
319 f = self.substring ('filename')
320 return os.path.splitext (f)[0] + self.formatter.default_extension
322 def replacement_text (self):
323 s = self.match.group ('match')
324 f = self.substring ('filename')
325 return re.sub (f, self.processed_filename (), s)
329 class LilypondSnippet (Snippet):
330 def __init__ (self, type, match, formatter, line_number, global_options):
331 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
334 os = match.group ('options')
335 self.parse_snippet_options (os, self.type)
338 def snippet_options (self):
341 def verb_ly_gettext (self, s):
342 lang = self.formatter.document_language
346 t = langdefs.translation[lang]
350 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
352 if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
353 for v in ly_var_def_re.findall (s):
354 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
355 "\\1" + t (v) + "\\2",
357 for id in ly_context_id_re.findall (s):
358 s = re.sub (r'(\s+|")%s(\s+|")' % id,
359 "\\1" + t (id) + "\\2",
364 verb_text = self.substring ('code')
365 if not NOGETTEXT in self.option_dict:
366 verb_text = self.verb_ly_gettext (verb_text)
367 if not verb_text.endswith ('\n'):
372 contents = self.substring ('code')
373 return ('\\sourcefileline %d\n%s'
374 % (self.line_number - 1, contents))
379 return self.compose_ly (s)
382 def split_options (self, option_string):
383 return self.formatter.split_snippet_options (option_string);
385 def parse_snippet_options (self, option_string, type):
386 self.snippet_option_dict = {}
388 # Split option string and create raw option_dict from it
389 options = self.split_options (option_string)
391 for option in options:
392 (key, value) = (option, None)
394 (key, value) = re.split ('\s*=\s*', option)
396 # a no... option removes a previous option if present!
397 if key in no_options:
398 if no_options[key] in self.option_dict:
399 del self.snippet_option_dict[no_options[key]]
401 # Check for deprecated options, replace them by new ones
402 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
406 _ ("deprecated ly-option used: %s=%s") % (key, value))
408 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
411 _ ("deprecated ly-option used: %s") % key)
413 _ ("compatibility mode translation: %s") % c_key)
414 (key, value) = (c_key, c_value)
415 # Finally, insert the option:
417 self.snippet_option_dict[key] = value
419 # If LINE_WIDTH is used without parameter, set it to default.
420 has_line_width = self.snippet_option_dict.has_key (LINE_WIDTH)
421 if has_line_width and self.snippet_option_dict[LINE_WIDTH] == None:
422 del self.snippet_option_dict[LINE_WIDTH]
424 # RELATIVE does not work without FRAGMENT, so imply that
425 if self.snippet_option_dict.has_key (RELATIVE):
426 self.snippet_option_dict[FRAGMENT] = None
428 # Now get the default options from the formatter object (HTML, latex,
429 # texinfo, etc.) and insert the explicit snippet options to get the
430 # list of all options for this snippet
431 # first, make sure we have an INDENT value as a fallback
432 self.option_dict = {INDENT: '0\\mm'};
433 self.option_dict.update (self.formatter.default_snippet_options);
434 self.option_dict.update (self.snippet_option_dict);
436 # also construct a list of all options (as strings) that influence the
437 # visual appearance of the snippet
438 lst = filter (lambda (x,y): x not in PROCESSING_INDEPENDENT_OPTIONS,
439 self.option_dict.iteritems ());
441 for (key, value) in lst:
443 option_list.append (key)
445 option_list.append (key + "=" + value)
447 self.outputrelevant_option_list = option_list
448 #print ("self.outputrelevant_option_list: %s\n" % self.outputrelevant_option_list);
451 # Set a default line-width if there is none. We need this, because
452 # lilypond-book has set left-padding by default and therefore does
453 # #(define line-width (- line-width (* 3 mm)))
454 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
455 # all settings before writing them in the \paper block.
456 #if not LINE_WIDTH in self.option_dict:
457 #if not QUOTE in self.option_dict:
458 #self.option_dict[LINE_WIDTH] = "#(- paper-width \
459 #left-margin-default right-margin-default)"
461 # Get a list of all options (as string) that influence the snippet appearance
462 def get_outputrelevant_option_strings (self):
463 return self.outputrelevant_option_list
465 def compose_ly (self, code):
470 # The original concept of the `exampleindent' option is broken.
471 # It is not possible to get a sane value for @exampleindent at all
472 # without processing the document itself. Saying
480 # causes ugly results with the DVI backend of texinfo since the
481 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
482 # value). Executing the above code changes the environment
483 # indentation to an unknown value because we don't know the amount
484 # of 1em in advance since it is font-dependent. Modifying
485 # @exampleindent in the middle of a document is simply not
486 # supported within texinfo.
488 # As a consequence, the only function of @exampleindent is now to
489 # specify the amount of indentation for the `quote' option.
491 # To set @exampleindent locally to zero, we use the @format
492 # environment for non-quoted snippets.
494 # Update: since July 2011 we are running texinfo on a test file
495 # to detect the default exampleindent, so we might reintroduce
496 # further usage of exampleindent again.
498 # First, make sure we have some falback default value, auto-detected
499 # values and explicitly specified values will always override them:
500 override[EXAMPLEINDENT] = r'0.4\in'
501 override[LINE_WIDTH] = '5\\in'
502 override.update (self.formatter.default_snippet_options)
504 option_string = ','.join (self.get_outputrelevant_option_strings ())
506 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
507 for a in compose_types:
510 option_names = self.option_dict.keys ()
512 for key in option_names:
513 value = self.option_dict[key]
516 override[key] = value
518 if not override.has_key (key):
522 for typ in compose_types:
523 if snippet_options[typ].has_key (key):
524 compose_dict[typ].append (snippet_options[typ][key])
528 if not found and key not in simple_options and key not in self.snippet_options ():
529 warning (_ ("ignoring unknown ly option: %s") % key)
532 if RELATIVE in override and override[RELATIVE]:
533 relative = int (override[RELATIVE])
539 relative_quotes += ',' * (- relative)
541 relative_quotes += "'" * relative
543 # put paper-size first, if it exists
544 for i,elem in enumerate(compose_dict[PAPER]):
545 if elem.startswith("#(set-paper-size"):
546 compose_dict[PAPER].insert(0, compose_dict[PAPER].pop(i))
549 paper_string = '\n '.join (compose_dict[PAPER]) % override
550 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
551 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
552 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
553 padding_mm = self.global_options.padding_mm
554 if self.global_options.safe_mode:
555 safe_mode_string = "#(ly:set-option 'safe #t)"
557 safe_mode_string = ""
561 d.update (self.global_options.information)
562 if FRAGMENT in self.option_dict:
566 return (PREAMBLE_LY + body) % d
568 def get_checksum (self):
569 if not self.checksum:
570 # Work-around for md5 module deprecation warning in python 2.5+:
572 from hashlib import md5
576 # We only want to calculate the hash based on the snippet
577 # code plus fragment options relevant to processing by
578 # lilypond, not the snippet + preamble
579 hash = md5 (self.relevant_contents (self.ly ()))
580 for option in self.get_outputrelevant_option_strings ():
583 ## let's not create too long names.
584 self.checksum = hash.hexdigest ()[:10]
589 cs = self.get_checksum ()
590 name = os.path.join (cs[:2], 'lily-%s' % cs[2:])
593 final_basename = basename
596 base = self.basename ()
597 path = os.path.join (self.global_options.lily_output_dir, base)
598 directory = os.path.split(path)[0]
599 if not os.path.isdir (directory):
600 os.makedirs (directory)
601 filename = path + '.ly'
602 if os.path.exists (filename):
603 existing = open (filename, 'r').read ()
605 if self.relevant_contents (existing) != self.relevant_contents (self.full_ly ()):
606 warning ("%s: duplicate filename but different contents of original file,\n\
607 printing diff against existing file." % filename)
608 ly.stderr_write (self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename))
610 out = file (filename, 'w')
611 out.write (self.full_ly ())
612 file (path + '.txt', 'w').write ('image of music')
614 def relevant_contents (self, ly):
615 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
617 def link_all_output_files (self, output_dir, output_dir_files, destination):
618 existing, missing = self.all_output_files (output_dir, output_dir_files)
620 print '\nMissing', missing
621 raise CompileError(self.basename())
622 for name in existing:
623 if (self.global_options.use_source_file_names
624 and isinstance (self, LilypondFileSnippet)):
625 base, ext = os.path.splitext (name)
626 components = base.split ('-')
627 # ugh, assume filenames with prefix with one dash (lily-xxxx)
628 if len (components) > 2:
629 base_suffix = '-' + components[-1]
632 final_name = self.final_basename () + base_suffix + ext
636 os.unlink (os.path.join (destination, final_name))
640 src = os.path.join (output_dir, name)
641 dst = os.path.join (destination, final_name)
642 dst_path = os.path.split(dst)[0]
643 if not os.path.isdir (dst_path):
644 os.makedirs (dst_path)
647 except AttributeError:
648 shutil.copyfile (src, dst)
650 print '\nCould not overwrite file', dst
651 raise CompileError(self.basename())
653 def additional_files_to_consider (self, base, full):
655 def additional_files_required (self, base, full):
657 if self.ext != '.ly':
658 result.append (base + self.ext)
662 def all_output_files (self, output_dir, output_dir_files):
663 """Return all files generated in lily_output_dir, a set.
665 output_dir_files is the list of files in the output directory.
669 base = self.basename()
670 full = os.path.join (output_dir, base)
671 def consider_file (name):
672 if name in output_dir_files:
675 def require_file (name):
676 if name in output_dir_files:
681 # UGH - junk self.global_options
682 skip_lily = self.global_options.skip_lilypond_run
683 for required in [base + '.ly',
685 require_file (required)
687 require_file (base + '-systems.count')
689 if 'ddump-profile' in self.global_options.process_cmd:
690 require_file (base + '.profile')
691 if 'dseparate-log-file' in self.global_options.process_cmd:
692 require_file (base + '.log')
694 map (consider_file, [base + '.tex',
698 base + '-systems.texi',
699 base + '-systems.tex',
700 base + '-systems.pdftexi'])
701 if self.formatter.document_language:
703 [base + '.texidoc' + self.formatter.document_language,
704 base + '.doctitle' + self.formatter.document_language])
706 required_files = self.formatter.required_files (self, base, full, result)
707 for f in required_files:
711 if not skip_lily and not missing:
712 system_count = int(file (full + '-systems.count').read())
714 for number in range(1, system_count + 1):
715 systemfile = '%s-%d' % (base, number)
716 require_file (systemfile + '.eps')
717 consider_file (systemfile + '.pdf')
719 # We can't require signatures, since books and toplevel
720 # markups do not output a signature.
721 if 'ddump-signature' in self.global_options.process_cmd:
722 consider_file (systemfile + '.signature')
724 map (consider_file, self.additional_files_to_consider (base, full))
725 map (require_file, self.additional_files_required (base, full))
727 return (result, missing)
729 def is_outdated (self, output_dir, current_files):
730 found, missing = self.all_output_files (output_dir, current_files)
733 def filter_pipe (self, input, cmd):
734 """Pass input through cmd, and return the result."""
736 debug (_ ("Running through filter `%s'") % cmd, True)
738 # TODO: Use Popen once we resolve the problem with msvcrt in Windows:
739 (stdin, stdout, stderr) = os.popen3 (cmd)
740 # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
741 # (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
743 status = stdin.close ()
747 output = stdout.read ()
748 status = stdout.close ()
753 signal = 0x0f & status
754 if status or (not output and err):
755 exit_status = status >> 8
756 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
757 ly.error (_ ("The error log is as follows:"))
758 ly.stderr_write (err)
759 ly.stderr_write (stderr.read ())
766 def get_snippet_code (self):
767 return self.substring ('code');
769 def filter_text (self):
770 """Run snippet bodies through a command (say: convert-ly).
772 This functionality is rarely used, and this code must have bitrot.
774 code = self.get_snippet_code ();
775 s = self.filter_pipe (code, self.global_options.filter_cmd)
778 'options': self.match.group ('options')
780 return self.formatter.output_simple_replacements (FILTER, d)
782 def replacement_text (self):
783 base = self.final_basename ()
784 return self.formatter.snippet_output (base, self)
786 def get_images (self):
787 rep = {'base': self.final_basename ()}
789 single = '%(base)s.png' % rep
790 multiple = '%(base)s-page1.png' % rep
792 if (os.path.exists (multiple)
793 and (not os.path.exists (single)
794 or (os.stat (multiple)[stat.ST_MTIME]
795 > os.stat (single)[stat.ST_MTIME]))):
796 count = ps_page_count ('%(base)s.eps' % rep)
797 images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
798 images = tuple (images)
804 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
805 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
807 class LilypondFileSnippet (LilypondSnippet):
808 def __init__ (self, type, match, formatter, line_number, global_options):
809 LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
810 self.filename = self.substring ('filename')
811 self.contents = file (BookBase.find_file (self.filename,
812 global_options.include_path, global_options.original_dir)).read ()
814 def get_snippet_code (self):
815 return self.contents;
819 s = re_begin_verbatim.split (s)[-1]
820 s = re_end_verbatim.split (s)[0]
821 if not NOGETTEXT in self.option_dict:
822 s = self.verb_ly_gettext (s)
823 if not s.endswith ('\n'):
829 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
830 % (name, self.contents))
832 def final_basename (self):
833 if self.global_options.use_source_file_names:
834 base = os.path.splitext (os.path.basename (self.filename))[0]
837 return self.basename ()
840 class MusicXMLFileSnippet (LilypondFileSnippet):
841 def __init__ (self, type, match, formatter, line_number, global_options):
842 LilypondFileSnippet.__init__ (self, type, match, formatter, line_number, global_options)
843 self.compressed = False
844 self.converted_ly = None
845 self.ext = os.path.splitext (os.path.basename (self.filename))[1]
846 self.musicxml_options_dict = {
847 'verbose': '--verbose',
849 'compressed': '--compressed',
850 'relative': '--relative',
851 'absolute': '--absolute',
852 'no-articulation-directions': '--no-articulation-directions',
853 'no-rest-positions': '--no-rest-positions',
854 'no-page-layout': '--no-page-layout',
855 'no-beaming': '--no-beaming',
856 'language': '--language',
859 def snippet_options (self):
860 return self.musicxml_options_dict.keys ()
862 def convert_from_musicxml (self):
864 xml2ly_option_list = []
865 for (key, value) in self.option_dict.items ():
866 cmd_key = self.musicxml_options_dict.get (key, None)
870 xml2ly_option_list.append (cmd_key)
872 xml2ly_option_list.append (cmd_key + '=' + value)
873 if ('.mxl' in name) and ('--compressed' not in xml2ly_option_list):
874 xml2ly_option_list.append ('--compressed')
875 self.compressed = True
876 opts = " ".join (xml2ly_option_list)
877 progress (_ ("Converting MusicXML file `%s'...\n") % self.filename)
879 ly_code = self.filter_pipe (self.contents, 'musicxml2ly %s --out=- - ' % opts)
883 if self.converted_ly == None:
884 self.converted_ly = self.convert_from_musicxml ()
886 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
887 % (name, self.converted_ly))
890 base = self.basename ()
891 path = os.path.join (self.global_options.lily_output_dir, base)
892 directory = os.path.split(path)[0]
893 if not os.path.isdir (directory):
894 os.makedirs (directory)
896 # First write the XML to a file (so we can link it!)
898 xmlfilename = path + '.mxl'
900 xmlfilename = path + '.xml'
901 if os.path.exists (xmlfilename):
902 diff_against_existing = self.filter_pipe (self.contents, 'diff -u %s - ' % xmlfilename)
903 if diff_against_existing:
904 warning (_ ("%s: duplicate filename but different contents of original file,\n\
905 printing diff against existing file.") % xmlfilename)
906 ly.stderr_write (diff_against_existing)
908 out = file (xmlfilename, 'w')
909 out.write (self.contents)
912 # also write the converted lilypond
913 filename = path + '.ly'
914 if os.path.exists (filename):
915 diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
916 if diff_against_existing:
917 warning (_ ("%s: duplicate filename but different contents of converted lilypond file,\n\
918 printing diff against existing file.") % filename)
919 ly.stderr_write (diff_against_existing)
921 out = file (filename, 'w')
922 out.write (self.full_ly ())
924 file (path + '.txt', 'w').write ('image of music')
928 class LilyPondVersionString (Snippet):
929 """A string that does not require extra memory."""
930 def __init__ (self, type, match, formatter, line_number, global_options):
931 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
933 def replacement_text (self):
934 return self.formatter.output_simple (self.type, self)
937 snippet_type_to_class = {
938 'lilypond_file': LilypondFileSnippet,
939 'lilypond_block': LilypondSnippet,
940 'lilypond': LilypondSnippet,
941 'include': IncludeSnippet,
942 'lilypondversion': LilyPondVersionString,
943 'musicxml_file': MusicXMLFileSnippet,