1 # -*- coding: utf-8 -*-
3 import book_base as BookBase
13 progress = ly.progress
16 debug = ly.debug_output
22 ####################################################################
23 # Snippet option handling
24 ####################################################################
28 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
31 ADDVERSION = 'addversion'
36 EXAMPLEINDENT = 'exampleindent'
41 LINE_WIDTH = 'line-width'
42 NOFRAGMENT = 'nofragment'
43 NOGETTEXT = 'nogettext'
46 NORAGGED_RIGHT = 'noragged-right'
51 OUTPUTIMAGE = 'outputimage'
53 PAPERSIZE = 'papersize'
55 PRINTFILENAME = 'printfilename'
57 RAGGED_RIGHT = 'ragged-right'
59 STAFFSIZE = 'staffsize'
62 VERSION = 'lilypondversion'
66 # NOTIME, NOSTAFF and NOGETTEXT have no opposite so they aren't part of
73 # Options that have no impact on processing by lilypond (or --process
75 PROCESSING_INDEPENDENT_OPTIONS = (
76 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
77 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
81 # Options without a pattern in snippet_options.
99 ####################################################################
100 # LilyPond templates for the snippets
101 ####################################################################
106 RELATIVE: r'''\relative c%(relative_quotes)s''',
110 # TODO: Remove the 1mm additional padding in the line-width
111 # once lilypond creates tighter cropped images!
113 PAPERSIZE: r'''#(set-paper-size "%(papersize)s")''',
114 INDENT: r'''indent = %(indent)s''',
115 LINE_WIDTH: r'''line-width = %(line-width)s
116 %% offset the left padding, also add 1mm as lilypond creates cropped
117 %% images with a little space on the right
118 line-width = #(- line-width (* mm %(padding_mm)f) (* mm 1))''',
119 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s
120 %% offset the left padding, also add 1mm as lilypond creates cropped
121 %% images with a little space on the right
122 line-width = #(- line-width (* mm %(padding_mm)f) (* mm 1))''',
123 RAGGED_RIGHT: r'''ragged-right = ##t''',
124 NORAGGED_RIGHT: r'''ragged-right = ##f''',
136 \remove "Time_signature_engraver"
145 \remove "Time_signature_engraver"
146 \remove "Clef_engraver"
147 \remove "Staff_symbol_engraver"
153 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
161 def classic_lilypond_book_compatibility (key, value):
162 if key == 'lilyquote':
163 return (QUOTE, value)
164 if key == 'singleline' and value == None:
165 return (RAGGED_RIGHT, None)
167 m = re.search ('relative\s*([-0-9])', key)
169 return ('relative', m.group (1))
171 m = re.match ('([0-9]+)pt', key)
173 return ('staffsize', m.group (1))
175 if key == 'indent' or key == 'line-width':
176 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
178 f = float (m.group (1))
179 return (key, '%f\\%s' % (f, m.group (2)))
184 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
185 %%%% Options: [%(option_string)s]
186 \\include "lilypond-book-preamble.ly"
189 %% ****************************************************************
190 %% Start cut-&-pastable-section
191 %% ****************************************************************
210 %% ****************************************************************
212 %% ****************************************************************
216 %% ****************************************************************
218 %% ****************************************************************
226 %% ****************************************************************
227 %% ly snippet contents follows:
228 %% ****************************************************************
232 %% ****************************************************************
234 %% ****************************************************************
241 ####################################################################
243 ####################################################################
245 def ps_page_count (ps_name):
246 header = file (ps_name).read (1024)
247 m = re.search ('\n%%Pages: ([0-9]+)', header)
249 return int (m.group (1))
252 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
253 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
254 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
255 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
257 def ly_comment_gettext (t, m):
258 return m.group (1) + t (m.group (2))
262 class CompileError(Exception):
267 ####################################################################
269 ####################################################################
272 def replacement_text (self):
275 def filter_text (self):
276 return self.replacement_text ()
281 class Substring (Chunk):
282 """A string that does not require extra memory."""
283 def __init__ (self, source, start, end, line_number):
287 self.line_number = line_number
288 self.override_text = None
293 def replacement_text (self):
294 if self.override_text:
295 return self.override_text
297 return self.source[self.start:self.end]
301 class Snippet (Chunk):
302 def __init__ (self, type, match, formatter, line_number, global_options):
306 self.option_dict = {}
307 self.formatter = formatter
308 self.line_number = line_number
309 self.global_options = global_options
310 self.replacements = {'program_version': ly.program_version,
311 'program_name': ly.program_name}
313 # return a shallow copy of the replacements, so the caller can modify
314 # it locally without interfering with other snippet operations
315 def get_replacements (self):
316 return copy.copy (self.replacements)
318 def replacement_text (self):
319 return self.match.group ('match')
321 def substring (self, s):
322 return self.match.group (s)
325 return `self.__class__` + ' type = ' + self.type
329 class IncludeSnippet (Snippet):
330 def processed_filename (self):
331 f = self.substring ('filename')
332 return os.path.splitext (f)[0] + self.formatter.default_extension
334 def replacement_text (self):
335 s = self.match.group ('match')
336 f = self.substring ('filename')
337 return re.sub (f, self.processed_filename (), s)
341 class LilypondSnippet (Snippet):
342 def __init__ (self, type, match, formatter, line_number, global_options):
343 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
346 os = match.group ('options')
347 self.parse_snippet_options (os, self.type)
350 def snippet_options (self):
353 def verb_ly_gettext (self, s):
354 lang = self.formatter.document_language
358 t = langdefs.translation[lang]
362 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
364 if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
365 for v in ly_var_def_re.findall (s):
366 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
367 "\\1" + t (v) + "\\2",
369 for id in ly_context_id_re.findall (s):
370 s = re.sub (r'(\s+|")%s(\s+|")' % id,
371 "\\1" + t (id) + "\\2",
376 verb_text = self.substring ('code')
377 if not NOGETTEXT in self.option_dict:
378 verb_text = self.verb_ly_gettext (verb_text)
379 if not verb_text.endswith ('\n'):
384 contents = self.substring ('code')
385 return ('\\sourcefileline %d\n%s'
386 % (self.line_number - 1, contents))
391 return self.compose_ly (s)
394 def split_options (self, option_string):
395 return self.formatter.split_snippet_options (option_string);
397 def parse_snippet_options (self, option_string, type):
398 self.snippet_option_dict = {}
400 # Split option string and create raw option_dict from it
401 options = self.split_options (option_string)
403 for option in options:
404 (key, value) = (option, None)
406 (key, value) = re.split ('\s*=\s*', option)
408 # a no... option removes a previous option if present!
409 if key in no_options:
410 if no_options[key] in self.option_dict:
411 del self.snippet_option_dict[no_options[key]]
413 # Check for deprecated options, replace them by new ones
414 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
418 _ ("deprecated ly-option used: %s=%s") % (key, value))
420 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
423 _ ("deprecated ly-option used: %s") % key)
425 _ ("compatibility mode translation: %s") % c_key)
426 (key, value) = (c_key, c_value)
427 # Finally, insert the option:
429 self.snippet_option_dict[key] = value
431 # If LINE_WIDTH is used without parameter, set it to default.
432 has_line_width = self.snippet_option_dict.has_key (LINE_WIDTH)
433 if has_line_width and self.snippet_option_dict[LINE_WIDTH] == None:
434 del self.snippet_option_dict[LINE_WIDTH]
436 # RELATIVE does not work without FRAGMENT, so imply that
437 if self.snippet_option_dict.has_key (RELATIVE):
438 self.snippet_option_dict[FRAGMENT] = None
440 # Now get the default options from the formatter object (HTML, latex,
441 # texinfo, etc.) and insert the explicit snippet options to get the
442 # list of all options for this snippet
443 # first, make sure we have an INDENT value as a fallback
444 self.option_dict = {INDENT: '0\\mm'};
445 self.option_dict.update (self.formatter.default_snippet_options);
446 self.option_dict.update (self.snippet_option_dict);
448 # also construct a list of all options (as strings) that influence the
449 # visual appearance of the snippet
450 lst = filter (lambda (x,y): x not in PROCESSING_INDEPENDENT_OPTIONS,
451 self.option_dict.iteritems ());
453 for (key, value) in lst:
455 option_list.append (key)
457 option_list.append (key + "=" + value)
459 self.outputrelevant_option_list = option_list
460 #print ("self.outputrelevant_option_list: %s\n" % self.outputrelevant_option_list);
463 # Set a default line-width if there is none. We need this, because
464 # lilypond-book has set left-padding by default and therefore does
465 # #(define line-width (- line-width (* 3 mm)))
466 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
467 # all settings before writing them in the \paper block.
468 #if not LINE_WIDTH in self.option_dict:
469 #if not QUOTE in self.option_dict:
470 #self.option_dict[LINE_WIDTH] = "#(- paper-width \
471 #left-margin-default right-margin-default)"
473 # Get a list of all options (as string) that influence the snippet appearance
474 def get_outputrelevant_option_strings (self):
475 return self.outputrelevant_option_list
477 def compose_ly (self, code):
482 # The original concept of the `exampleindent' option is broken.
483 # It is not possible to get a sane value for @exampleindent at all
484 # without processing the document itself. Saying
492 # causes ugly results with the DVI backend of texinfo since the
493 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
494 # value). Executing the above code changes the environment
495 # indentation to an unknown value because we don't know the amount
496 # of 1em in advance since it is font-dependent. Modifying
497 # @exampleindent in the middle of a document is simply not
498 # supported within texinfo.
500 # As a consequence, the only function of @exampleindent is now to
501 # specify the amount of indentation for the `quote' option.
503 # To set @exampleindent locally to zero, we use the @format
504 # environment for non-quoted snippets.
506 # Update: since July 2011 we are running texinfo on a test file
507 # to detect the default exampleindent, so we might reintroduce
508 # further usage of exampleindent again.
510 # First, make sure we have some falback default value, auto-detected
511 # values and explicitly specified values will always override them:
512 override[EXAMPLEINDENT] = r'0.4\in'
513 override[LINE_WIDTH] = '5\\in'
514 override.update (self.formatter.default_snippet_options)
515 override['padding_mm'] = self.global_options.padding_mm
517 option_string = ','.join (self.get_outputrelevant_option_strings ())
519 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
520 for a in compose_types:
523 option_names = self.option_dict.keys ()
525 for key in option_names:
526 value = self.option_dict[key]
529 override[key] = value
531 if not override.has_key (key):
535 for typ in compose_types:
536 if snippet_options[typ].has_key (key):
537 compose_dict[typ].append (snippet_options[typ][key])
541 if not found and key not in simple_options and key not in self.snippet_options ():
542 warning (_ ("ignoring unknown ly option: %s") % key)
545 if RELATIVE in override and override[RELATIVE]:
546 relative = int (override[RELATIVE])
552 relative_quotes += ',' * (- relative)
554 relative_quotes += "'" * relative
556 # put paper-size first, if it exists
557 for i,elem in enumerate(compose_dict[PAPER]):
558 if elem.startswith("#(set-paper-size"):
559 compose_dict[PAPER].insert(0, compose_dict[PAPER].pop(i))
562 paper_string = '\n '.join (compose_dict[PAPER]) % override
563 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
564 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
565 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
566 padding_mm = self.global_options.padding_mm
567 if self.global_options.safe_mode:
568 safe_mode_string = "#(ly:set-option 'safe #t)"
570 safe_mode_string = ""
574 d.update (self.global_options.information)
575 if FRAGMENT in self.option_dict:
579 return (PREAMBLE_LY + body) % d
581 def get_checksum (self):
582 if not self.checksum:
583 # Work-around for md5 module deprecation warning in python 2.5+:
585 from hashlib import md5
589 # We only want to calculate the hash based on the snippet
590 # code plus fragment options relevant to processing by
591 # lilypond, not the snippet + preamble
592 hash = md5 (self.relevant_contents (self.ly ()))
593 for option in self.get_outputrelevant_option_strings ():
596 ## let's not create too long names.
597 self.checksum = hash.hexdigest ()[:10]
602 cs = self.get_checksum ()
603 name = os.path.join (cs[:2], 'lily-%s' % cs[2:])
606 final_basename = basename
609 base = self.basename ()
610 path = os.path.join (self.global_options.lily_output_dir, base)
611 directory = os.path.split(path)[0]
612 if not os.path.isdir (directory):
613 os.makedirs (directory)
614 filename = path + '.ly'
615 if os.path.exists (filename):
616 existing = open (filename, 'r').read ()
618 if self.relevant_contents (existing) != self.relevant_contents (self.full_ly ()):
619 warning ("%s: duplicate filename but different contents of original file,\n\
620 printing diff against existing file." % filename)
621 ly.stderr_write (self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename))
623 out = file (filename, 'w')
624 out.write (self.full_ly ())
625 file (path + '.txt', 'w').write ('image of music')
627 def relevant_contents (self, ly):
628 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
630 def link_all_output_files (self, output_dir, output_dir_files, destination):
631 existing, missing = self.all_output_files (output_dir, output_dir_files)
633 error (_ ('Missing files: %s') % ', '.join (missing))
634 raise CompileError(self.basename())
635 for name in existing:
636 if (self.global_options.use_source_file_names
637 and isinstance (self, LilypondFileSnippet)):
638 base, ext = os.path.splitext (name)
639 components = base.split ('-')
640 # ugh, assume filenames with prefix with one dash (lily-xxxx)
641 if len (components) > 2:
642 base_suffix = '-' + components[-1]
645 final_name = self.final_basename () + base_suffix + ext
649 os.unlink (os.path.join (destination, final_name))
653 src = os.path.join (output_dir, name)
654 dst = os.path.join (destination, final_name)
655 dst_path = os.path.split(dst)[0]
656 if not os.path.isdir (dst_path):
657 os.makedirs (dst_path)
660 except AttributeError:
661 shutil.copyfile (src, dst)
663 error (_ ('Could not overwrite file %s') % dst)
664 raise CompileError(self.basename())
666 def additional_files_to_consider (self, base, full):
668 def additional_files_required (self, base, full):
670 if self.ext != '.ly':
671 result.append (base + self.ext)
675 def all_output_files (self, output_dir, output_dir_files):
676 """Return all files generated in lily_output_dir, a set.
678 output_dir_files is the list of files in the output directory.
682 base = self.basename()
683 full = os.path.join (output_dir, base)
684 def consider_file (name):
685 if name in output_dir_files:
688 def require_file (name):
689 if name in output_dir_files:
694 # UGH - junk self.global_options
695 skip_lily = self.global_options.skip_lilypond_run
696 for required in [base + '.ly',
698 require_file (required)
700 require_file (base + '-systems.count')
702 if 'ddump-profile' in self.global_options.process_cmd:
703 require_file (base + '.profile')
704 if 'dseparate-log-file' in self.global_options.process_cmd:
705 require_file (base + '.log')
707 map (consider_file, [base + '.tex',
712 base + '-systems.texi',
713 base + '-systems.tex',
714 base + '-systems.pdftexi'])
715 if self.formatter.document_language:
717 [base + '.texidoc' + self.formatter.document_language,
718 base + '.doctitle' + self.formatter.document_language])
720 required_files = self.formatter.required_files (self, base, full, result)
721 for f in required_files:
725 if not skip_lily and not missing:
726 system_count = int(file (full + '-systems.count').read())
728 for number in range(1, system_count + 1):
729 systemfile = '%s-%d' % (base, number)
730 require_file (systemfile + '.eps')
731 consider_file (systemfile + '.pdf')
733 # We can't require signatures, since books and toplevel
734 # markups do not output a signature.
735 if 'ddump-signature' in self.global_options.process_cmd:
736 consider_file (systemfile + '.signature')
738 map (consider_file, self.additional_files_to_consider (base, full))
739 map (require_file, self.additional_files_required (base, full))
741 return (result, missing)
743 def is_outdated (self, output_dir, current_files):
744 found, missing = self.all_output_files (output_dir, current_files)
747 def filter_pipe (self, input, cmd):
748 """Pass input through cmd, and return the result."""
750 debug (_ ("Running through filter `%s'") % cmd, True)
753 if (sys.platform == "mingw32"):
755 p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=closefds)
756 (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
758 status = stdin.close ()
762 output = stdout.read ()
763 status = stdout.close ()
768 signal = 0x0f & status
769 if status or (not output and err):
770 exit_status = status >> 8
771 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
772 ly.error (_ ("The error log is as follows:"))
773 ly.stderr_write (err)
774 ly.stderr_write (stderr.read ())
781 def get_snippet_code (self):
782 return self.substring ('code');
784 def filter_text (self):
785 """Run snippet bodies through a command (say: convert-ly).
787 This functionality is rarely used, and this code must have bitrot.
789 code = self.get_snippet_code ();
790 s = self.filter_pipe (code, self.global_options.filter_cmd)
793 'options': self.match.group ('options')
795 return self.formatter.output_simple_replacements (FILTER, d)
797 def replacement_text (self):
798 base = self.final_basename ()
799 return self.formatter.snippet_output (base, self)
801 def get_images (self):
802 rep = {'base': self.final_basename ()}
804 single = '%(base)s.png' % rep
805 multiple = '%(base)s-page1.png' % rep
807 if (os.path.exists (multiple)
808 and (not os.path.exists (single)
809 or (os.stat (multiple)[stat.ST_MTIME]
810 > os.stat (single)[stat.ST_MTIME]))):
811 count = ps_page_count ('%(base)s.eps' % rep)
812 images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
813 images = tuple (images)
819 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
820 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
822 class LilypondFileSnippet (LilypondSnippet):
823 def __init__ (self, type, match, formatter, line_number, global_options):
824 LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
825 self.filename = self.substring ('filename')
826 self.contents = file (BookBase.find_file (self.filename,
827 global_options.include_path, global_options.original_dir)).read ()
829 def get_snippet_code (self):
830 return self.contents;
834 s = re_begin_verbatim.split (s)[-1]
835 s = re_end_verbatim.split (s)[0]
836 if not NOGETTEXT in self.option_dict:
837 s = self.verb_ly_gettext (s)
838 if not s.endswith ('\n'):
844 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
845 % (name, self.contents))
847 def final_basename (self):
848 if self.global_options.use_source_file_names:
849 base = os.path.splitext (os.path.basename (self.filename))[0]
852 return self.basename ()
855 class MusicXMLFileSnippet (LilypondFileSnippet):
856 def __init__ (self, type, match, formatter, line_number, global_options):
857 LilypondFileSnippet.__init__ (self, type, match, formatter, line_number, global_options)
858 self.compressed = False
859 self.converted_ly = None
860 self.ext = os.path.splitext (os.path.basename (self.filename))[1]
861 self.musicxml_options_dict = {
862 'verbose': '--verbose',
864 'compressed': '--compressed',
865 'relative': '--relative',
866 'absolute': '--absolute',
867 'no-articulation-directions': '--no-articulation-directions',
868 'no-rest-positions': '--no-rest-positions',
869 'no-page-layout': '--no-page-layout',
870 'no-beaming': '--no-beaming',
871 'language': '--language',
874 def snippet_options (self):
875 return self.musicxml_options_dict.keys ()
877 def convert_from_musicxml (self):
879 xml2ly_option_list = []
880 for (key, value) in self.option_dict.items ():
881 cmd_key = self.musicxml_options_dict.get (key, None)
885 xml2ly_option_list.append (cmd_key)
887 xml2ly_option_list.append (cmd_key + '=' + value)
888 if ('.mxl' in name) and ('--compressed' not in xml2ly_option_list):
889 xml2ly_option_list.append ('--compressed')
890 self.compressed = True
891 opts = " ".join (xml2ly_option_list)
892 progress (_ ("Converting MusicXML file `%s'...\n") % self.filename)
894 ly_code = self.filter_pipe (self.contents, 'musicxml2ly %s --out=- - ' % opts)
898 if self.converted_ly == None:
899 self.converted_ly = self.convert_from_musicxml ()
901 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
902 % (name, self.converted_ly))
905 base = self.basename ()
906 path = os.path.join (self.global_options.lily_output_dir, base)
907 directory = os.path.split(path)[0]
908 if not os.path.isdir (directory):
909 os.makedirs (directory)
911 # First write the XML to a file (so we can link it!)
913 xmlfilename = path + '.mxl'
915 xmlfilename = path + '.xml'
916 if os.path.exists (xmlfilename):
917 diff_against_existing = self.filter_pipe (self.contents, 'diff -u %s - ' % xmlfilename)
918 if diff_against_existing:
919 warning (_ ("%s: duplicate filename but different contents of original file,\n\
920 printing diff against existing file.") % xmlfilename)
921 ly.stderr_write (diff_against_existing)
923 out = file (xmlfilename, 'w')
924 out.write (self.contents)
927 # also write the converted lilypond
928 filename = path + '.ly'
929 if os.path.exists (filename):
930 diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
931 if diff_against_existing:
932 warning (_ ("%s: duplicate filename but different contents of converted lilypond file,\n\
933 printing diff against existing file.") % filename)
934 ly.stderr_write (diff_against_existing)
936 out = file (filename, 'w')
937 out.write (self.full_ly ())
939 file (path + '.txt', 'w').write ('image of music')
943 class LilyPondVersionString (Snippet):
944 """A string that does not require extra memory."""
945 def __init__ (self, type, match, formatter, line_number, global_options):
946 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
948 def replacement_text (self):
949 return self.formatter.output_simple (self.type, self)
952 snippet_type_to_class = {
953 'lilypond_file': LilypondFileSnippet,
954 'lilypond_block': LilypondSnippet,
955 'lilypond': LilypondSnippet,
956 'include': IncludeSnippet,
957 'lilypondversion': LilyPondVersionString,
958 'musicxml_file': MusicXMLFileSnippet,