1 # -*- coding: utf-8 -*-
3 import book_base as BookBase
9 # TODO: We are using os.popen3, which has been deprecated since python 2.6. The
10 # suggested replacement is the Popen function of the subprocess module.
11 # Unfortunately, on windows this needs the msvcrt module, which doesn't seem
12 # to be available in GUB?!?!?!
13 # from subprocess import Popen, PIPE
15 progress = ly.progress
23 ####################################################################
24 # Snippet option handling
25 ####################################################################
29 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
32 ADDVERSION = 'addversion'
37 EXAMPLEINDENT = 'exampleindent'
42 LILYQUOTE = 'lilyquote'
43 LINE_WIDTH = 'line-width'
44 NOFRAGMENT = 'nofragment'
45 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
70 # NOQUOTE is used internally only.
76 # Options that have no impact on processing by lilypond (or --process
78 PROCESSING_INDEPENDENT_OPTIONS = (
79 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
80 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
84 # Options without a pattern in snippet_options.
102 ####################################################################
103 # LilyPond templates for the snippets
104 ####################################################################
109 RELATIVE: r'''\relative c%(relative_quotes)s''',
114 PAPERSIZE: r'''#(set-paper-size "%(papersize)s")''',
115 INDENT: r'''indent = %(indent)s''',
116 LINE_WIDTH: r'''line-width = %(line-width)s''',
117 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
118 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
119 RAGGED_RIGHT: r'''ragged-right = ##t''',
120 NORAGGED_RIGHT: r'''ragged-right = ##f''',
132 \remove "Time_signature_engraver"
138 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
151 %% ****************************************************************
152 %% ly snippet contents follows:
153 %% ****************************************************************
157 %% ****************************************************************
159 %% ****************************************************************
163 def classic_lilypond_book_compatibility (key, 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 %% ****************************************************************
197 line-width = #(- line-width (* mm %(padding_mm)f))
211 %% ****************************************************************
213 %% ****************************************************************
217 %% ****************************************************************
219 %% ****************************************************************
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)
332 os = match.group ('options')
333 self.do_options (os, self.type)
336 def snippet_options (self):
339 def verb_ly_gettext (self, s):
340 lang = self.formatter.document_language
344 t = langdefs.translation[lang]
348 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
350 if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
351 for v in ly_var_def_re.findall (s):
352 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
353 "\\1" + t (v) + "\\2",
355 for id in ly_context_id_re.findall (s):
356 s = re.sub (r'(\s+|")%s(\s+|")' % id,
357 "\\1" + t (id) + "\\2",
362 verb_text = self.substring ('code')
363 if not NOGETTEXT in self.option_dict:
364 verb_text = self.verb_ly_gettext (verb_text)
365 if not verb_text.endswith ('\n'):
370 contents = self.substring ('code')
371 return ('\\sourcefileline %d\n%s'
372 % (self.line_number - 1, contents))
377 return self.compose_ly (s)
380 def split_options (self, option_string):
381 return self.formatter.split_snippet_options (option_string);
383 def do_options (self, option_string, type):
384 self.option_dict = {}
386 options = self.split_options (option_string)
388 for option in options:
390 (key, value) = re.split ('\s*=\s*', option)
391 self.option_dict[key] = value
393 if option in no_options:
394 if no_options[option] in self.option_dict:
395 del self.option_dict[no_options[option]]
397 self.option_dict[option] = None
400 # If LINE_WIDTH is used without parameter, set it to default.
401 has_line_width = self.option_dict.has_key (LINE_WIDTH)
402 if has_line_width and self.option_dict[LINE_WIDTH] == None:
403 has_line_width = False
404 del self.option_dict[LINE_WIDTH]
406 # TODO: Can't we do that more efficiently (built-in python func?)
407 for k in self.formatter.default_snippet_options:
408 if k not in self.option_dict:
409 self.option_dict[k] = self.formatter.default_snippet_options[k]
411 # RELATIVE does not work without FRAGMENT;
412 # make RELATIVE imply FRAGMENT
413 has_relative = self.option_dict.has_key (RELATIVE)
414 if has_relative and not self.option_dict.has_key (FRAGMENT):
415 self.option_dict[FRAGMENT] = None
417 if not has_line_width:
418 if type == 'lilypond' or FRAGMENT in self.option_dict:
419 self.option_dict[RAGGED_RIGHT] = None
421 if type == 'lilypond':
422 if LINE_WIDTH in self.option_dict:
423 del self.option_dict[LINE_WIDTH]
425 if RAGGED_RIGHT in self.option_dict:
426 if LINE_WIDTH in self.option_dict:
427 del self.option_dict[LINE_WIDTH]
429 if QUOTE in self.option_dict or type == 'lilypond':
430 if LINE_WIDTH in self.option_dict:
431 del self.option_dict[LINE_WIDTH]
433 if not INDENT in self.option_dict:
434 self.option_dict[INDENT] = '0\\mm'
436 # Set a default line-width if there is none. We need this, because
437 # lilypond-book has set left-padding by default and therefore does
438 # #(define line-width (- line-width (* 3 mm)))
439 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
440 # all settings before writing them in the \paper block.
441 if not LINE_WIDTH in self.option_dict:
442 if not QUOTE in self.option_dict:
443 if not LILYQUOTE in self.option_dict:
444 self.option_dict[LINE_WIDTH] = "#(- paper-width \
445 left-margin-default right-margin-default)"
447 def get_option_list (self):
448 if not 'option_list' in self.__dict__:
450 for (key, value) in self.option_dict.items ():
452 option_list.append (key)
454 option_list.append (key + '=' + value)
456 self.option_list = option_list
457 return self.option_list
459 def compose_ly (self, code):
460 if FRAGMENT in self.option_dict:
468 # The original concept of the `exampleindent' option is broken.
469 # It is not possible to get a sane value for @exampleindent at all
470 # without processing the document itself. Saying
478 # causes ugly results with the DVI backend of texinfo since the
479 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
480 # value). Executing the above code changes the environment
481 # indentation to an unknown value because we don't know the amount
482 # of 1em in advance since it is font-dependent. Modifying
483 # @exampleindent in the middle of a document is simply not
484 # supported within texinfo.
486 # As a consequence, the only function of @exampleindent is now to
487 # specify the amount of indentation for the `quote' option.
489 # To set @exampleindent locally to zero, we use the @format
490 # environment for non-quoted snippets.
491 override[EXAMPLEINDENT] = r'0.4\in'
492 override[LINE_WIDTH] = '5\\in' # = texinfo_line_widths['@smallbook']
493 override.update (self.formatter.default_snippet_options)
496 for option in self.get_option_list ():
497 for name in PROCESSING_INDEPENDENT_OPTIONS:
498 if option.startswith (name):
501 option_list.append (option)
502 option_string = ','.join (option_list)
504 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
505 for a in compose_types:
508 option_names = self.option_dict.keys ()
510 for key in option_names:
511 value = self.option_dict[key]
512 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
516 _ ("deprecated ly-option used: %s=%s") % (key, value))
518 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
521 _ ("deprecated ly-option used: %s") % key)
523 _ ("compatibility mode translation: %s") % c_key)
525 (key, value) = (c_key, c_value)
528 override[key] = value
530 if not override.has_key (key):
534 for typ in compose_types:
535 if snippet_options[typ].has_key (key):
536 compose_dict[typ].append (snippet_options[typ][key])
540 if not found and key not in simple_options and key not in self.snippet_options ():
541 warning (_ ("ignoring unknown ly option: %s") % key)
544 if RELATIVE in override and override[RELATIVE]:
545 relative = int (override[RELATIVE])
551 relative_quotes += ',' * (- relative)
553 relative_quotes += "'" * relative
555 # put paper-size first, if it exists
556 for i,elem in enumerate(compose_dict[PAPER]):
557 if elem.startswith("#(set-paper-size"):
558 compose_dict[PAPER].insert(0, compose_dict[PAPER].pop(i))
561 paper_string = '\n '.join (compose_dict[PAPER]) % override
562 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
563 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
564 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
565 padding_mm = self.global_options.padding_mm
566 if self.global_options.safe_mode:
567 safe_mode_string = "#(ly:set-option 'safe #t)"
569 safe_mode_string = ""
573 d.update (self.global_options.information)
574 return (PREAMBLE_LY + body) % d
576 def get_checksum (self):
577 if not self.checksum:
578 # Work-around for md5 module deprecation warning in python 2.5+:
580 from hashlib import md5
584 # We only want to calculate the hash based on the snippet
585 # code plus fragment options relevant to processing by
586 # lilypond, not the snippet + preamble
587 hash = md5 (self.relevant_contents (self.ly ()))
588 for option in self.get_option_list ():
589 for name in PROCESSING_INDEPENDENT_OPTIONS:
590 if option.startswith (name):
595 ## let's not create too long names.
596 self.checksum = hash.hexdigest ()[:10]
601 cs = self.get_checksum ()
602 name = '%s/lily-%s' % (cs[:2], cs[2:])
605 final_basename = basename
608 base = self.basename ()
609 path = os.path.join (self.global_options.lily_output_dir, base)
610 directory = os.path.split(path)[0]
611 if not os.path.isdir (directory):
612 os.makedirs (directory)
613 filename = path + '.ly'
614 if os.path.exists (filename):
615 existing = open (filename, 'r').read ()
617 if self.relevant_contents (existing) != self.relevant_contents (self.full_ly ()):
618 warning ("%s: duplicate filename but different contents of orginal file,\n\
619 printing diff against existing file." % filename)
620 ly.stderr_write (self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename))
622 out = file (filename, 'w')
623 out.write (self.full_ly ())
624 file (path + '.txt', 'w').write ('image of music')
626 def relevant_contents (self, ly):
627 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
629 def link_all_output_files (self, output_dir, output_dir_files, destination):
630 existing, missing = self.all_output_files (output_dir, output_dir_files)
632 print '\nMissing', missing
633 raise CompileError(self.basename())
634 for name in existing:
635 if (self.global_options.use_source_file_names
636 and isinstance (self, LilypondFileSnippet)):
637 base, ext = os.path.splitext (name)
638 components = base.split ('-')
639 # ugh, assume filenames with prefix with one dash (lily-xxxx)
640 if len (components) > 2:
641 base_suffix = '-' + components[-1]
644 final_name = self.final_basename () + base_suffix + ext
648 os.unlink (os.path.join (destination, final_name))
652 src = os.path.join (output_dir, name)
653 dst = os.path.join (destination, final_name)
654 dst_path = os.path.split(dst)[0]
655 if not os.path.isdir (dst_path):
656 os.makedirs (dst_path)
659 def additional_files_to_consider (self, base, full):
661 def additional_files_required (self, base, full):
665 def all_output_files (self, output_dir, output_dir_files):
666 """Return all files generated in lily_output_dir, a set.
668 output_dir_files is the list of files in the output directory.
672 base = self.basename()
673 full = os.path.join (output_dir, base)
674 def consider_file (name):
675 if name in output_dir_files:
678 def require_file (name):
679 if name in output_dir_files:
684 # UGH - junk self.global_options
685 skip_lily = self.global_options.skip_lilypond_run
686 for required in [base + '.ly',
688 require_file (required)
690 require_file (base + '-systems.count')
692 if 'ddump-profile' in self.global_options.process_cmd:
693 require_file (base + '.profile')
694 if 'dseparate-log-file' in self.global_options.process_cmd:
695 require_file (base + '.log')
697 map (consider_file, [base + '.tex',
701 base + '-systems.texi',
702 base + '-systems.tex',
703 base + '-systems.pdftexi'])
704 if self.formatter.document_language:
706 [base + '.texidoc' + self.formatter.document_language,
707 base + '.doctitle' + self.formatter.document_language])
709 required_files = self.formatter.required_files (self, base, full, result)
710 for f in required_files:
714 if not skip_lily and not missing:
715 system_count = int(file (full + '-systems.count').read())
717 for number in range(1, system_count + 1):
718 systemfile = '%s-%d' % (base, number)
719 require_file (systemfile + '.eps')
720 consider_file (systemfile + '.pdf')
722 # We can't require signatures, since books and toplevel
723 # markups do not output a signature.
724 if 'ddump-signature' in self.global_options.process_cmd:
725 consider_file (systemfile + '.signature')
727 map (consider_file, self.additional_files_to_consider (base, full))
728 map (require_file, self.additional_files_required (base, full))
730 return (result, missing)
732 def is_outdated (self, output_dir, current_files):
733 found, missing = self.all_output_files (output_dir, current_files)
736 def filter_pipe (self, input, cmd):
737 """Pass input through cmd, and return the result."""
739 if self.global_options.verbose:
740 progress (_ ("Running through filter `%s'\n") % cmd)
742 # TODO: Use Popen once we resolve the problem with msvcrt in Windows:
743 (stdin, stdout, stderr) = os.popen3 (cmd)
744 # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
745 # (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
747 status = stdin.close ()
751 output = stdout.read ()
752 status = stdout.close ()
757 signal = 0x0f & status
758 if status or (not output and err):
759 exit_status = status >> 8
760 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
761 ly.error (_ ("The error log is as follows:"))
762 ly.stderr_write (err)
763 ly.stderr_write (stderr.read ())
766 if self.global_options.verbose:
771 def get_snippet_code (self):
772 return self.substring ('code');
774 def filter_text (self):
775 """Run snippet bodies through a command (say: convert-ly).
777 This functionality is rarely used, and this code must have bitrot.
779 code = self.get_snippet_code ();
780 s = self.filter_pipe (code, self.global_options.filter_cmd)
783 'options': self.match.group ('options')
785 return self.formatter.output_simple_replacements (FILTER, d)
787 def replacement_text (self):
788 base = self.final_basename ()
789 return self.formatter.snippet_output (base, self)
791 def get_images (self):
792 rep = {'base': self.final_basename ()}
794 single = '%(base)s.png' % rep
795 multiple = '%(base)s-page1.png' % rep
797 if (os.path.exists (multiple)
798 and (not os.path.exists (single)
799 or (os.stat (multiple)[stat.ST_MTIME]
800 > os.stat (single)[stat.ST_MTIME]))):
801 count = ps_page_count ('%(base)s.eps' % rep)
802 images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
803 images = tuple (images)
809 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
810 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
812 class LilypondFileSnippet (LilypondSnippet):
813 def __init__ (self, type, match, formatter, line_number, global_options):
814 LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
815 self.filename = self.substring ('filename')
816 self.ext = os.path.splitext (os.path.basename (self.filename))[1]
817 self.contents = file (BookBase.find_file (self.filename, global_options.include_path)).read ()
819 def get_snippet_code (self):
820 return self.contents;
824 s = re_begin_verbatim.split (s)[-1]
825 s = re_end_verbatim.split (s)[0]
826 if not NOGETTEXT in self.option_dict:
827 s = self.verb_ly_gettext (s)
828 if not s.endswith ('\n'):
834 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
835 % (name, self.contents))
837 def final_basename (self):
838 if self.global_options.use_source_file_names:
839 base = os.path.splitext (os.path.basename (self.filename))[0]
842 return self.basename ()
845 class MusicXMLFileSnippet (LilypondFileSnippet):
846 def __init__ (self, type, match, formatter, line_number, global_options):
847 LilypondFileSnippet.__init__ (self, type, match, formatter, line_number, global_options)
848 self.compressed = False
849 self.converted_ly = None
850 self.musicxml_options_dict = {
851 'verbose': '--verbose',
853 'compressed': '--compressed',
854 'relative': '--relative',
855 'absolute': '--absolute',
856 'no-articulation-directions': '--no-articulation-directions',
857 'no-rest-positions': '--no-rest-positions',
858 'no-page-layout': '--no-page-layout',
859 'no-beaming': '--no-beaming',
860 'language': '--language',
863 def snippet_options (self):
864 return self.musicxml_options_dict.keys ()
866 def convert_from_musicxml (self):
869 for (key, value) in self.option_dict.items ():
870 cmd_key = self.musicxml_options_dict.get (key, None)
874 option_list.append (cmd_key)
876 option_list.append (cmd_key + '=' + value)
877 if ('.mxl' in name) and ('--compressed' not in option_list):
878 option_list.append ('--compressed')
879 self.compressed = True
880 opts = " ".join (option_list)
881 progress (_ ("Converting MusicXML file `%s'...\n") % self.filename)
883 ly_code = self.filter_pipe (self.contents, 'musicxml2ly %s --out=- - ' % opts)
887 if self.converted_ly == None:
888 self.converted_ly = self.convert_from_musicxml ()
890 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
891 % (name, self.converted_ly))
893 def additional_files_required (self, base, full):
896 result.append (base + '.mxl')
898 result.append (base + '.xml')
902 base = self.basename ()
903 path = os.path.join (self.global_options.lily_output_dir, base)
904 directory = os.path.split(path)[0]
905 if not os.path.isdir (directory):
906 os.makedirs (directory)
908 # First write the XML to a file (so we can link it!)
910 xmlfilename = path + '.mxl'
912 xmlfilename = path + '.xml'
913 if os.path.exists (xmlfilename):
914 diff_against_existing = self.filter_pipe (self.contents, 'diff -u %s - ' % xmlfilename)
915 if diff_against_existing:
916 warning (_ ("%s: duplicate filename but different contents of orginal file,\n\
917 printing diff against existing file.") % xmlfilename)
918 ly.stderr_write (diff_against_existing)
920 out = file (xmlfilename, 'w')
921 out.write (self.contents)
924 # also write the converted lilypond
925 filename = path + '.ly'
926 if os.path.exists (filename):
927 diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
928 if diff_against_existing:
929 warning (_ ("%s: duplicate filename but different contents of converted lilypond file,\n\
930 printing diff against existing file.") % filename)
931 ly.stderr_write (diff_against_existing)
933 out = file (filename, 'w')
934 out.write (self.full_ly ())
936 file (path + '.txt', 'w').write ('image of music')
940 class LilyPondVersionString (Snippet):
941 """A string that does not require extra memory."""
942 def __init__ (self, type, match, formatter, line_number, global_options):
943 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
945 def replacement_text (self):
946 return self.formatter.output_simple (self.type, self)
949 snippet_type_to_class = {
950 'lilypond_file': LilypondFileSnippet,
951 'lilypond_block': LilypondSnippet,
952 'lilypond': LilypondSnippet,
953 'include': IncludeSnippet,
954 'lilypondversion': LilyPondVersionString,
955 'musicxml_file': MusicXMLFileSnippet,