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
18 debug = ly.debug_output
24 ####################################################################
25 # Snippet option handling
26 ####################################################################
30 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
33 ADDVERSION = 'addversion'
38 EXAMPLEINDENT = 'exampleindent'
43 LINE_WIDTH = 'line-width'
44 NOFRAGMENT = 'nofragment'
45 NOGETTEXT = 'nogettext'
48 NORAGGED_RIGHT = 'noragged-right'
52 OUTPUTIMAGE = 'outputimage'
54 PAPERSIZE = 'papersize'
56 PRINTFILENAME = 'printfilename'
58 RAGGED_RIGHT = 'ragged-right'
60 STAFFSIZE = 'staffsize'
63 VERSION = 'lilypondversion'
67 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
74 # Options that have no impact on processing by lilypond (or --process
76 PROCESSING_INDEPENDENT_OPTIONS = (
77 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
78 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
82 # Options without a pattern in snippet_options.
100 ####################################################################
101 # LilyPond templates for the snippets
102 ####################################################################
107 RELATIVE: r'''\relative c%(relative_quotes)s''',
112 PAPERSIZE: r'''#(set-paper-size "%(papersize)s")''',
113 INDENT: r'''indent = %(indent)s''',
114 LINE_WIDTH: r'''line-width = %(line-width)s''',
115 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
116 RAGGED_RIGHT: r'''ragged-right = ##t''',
117 NORAGGED_RIGHT: r'''ragged-right = ##f''',
129 \remove "Time_signature_engraver"
135 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
143 def classic_lilypond_book_compatibility (key, value):
144 if key == 'lilyquote':
145 return (QUOTE, value)
146 if key == 'singleline' and value == None:
147 return (RAGGED_RIGHT, None)
149 m = re.search ('relative\s*([-0-9])', key)
151 return ('relative', m.group (1))
153 m = re.match ('([0-9]+)pt', key)
155 return ('staffsize', m.group (1))
157 if key == 'indent' or key == 'line-width':
158 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
160 f = float (m.group (1))
161 return (key, '%f\\%s' % (f, m.group (2)))
166 # TODO: Remove the 1mm additional padding in the line-width, once lilypond
167 # creates tighter cropped images!
168 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
169 %%%% Options: [%(option_string)s]
170 \\include "lilypond-book-preamble.ly"
173 %% ****************************************************************
174 %% Start cut-&-pastable-section
175 %% ****************************************************************
181 %% offset the left padding, also add 1mm as lilypond creates cropped
182 %% images with a little space on the right
183 line-width = #(- line-width (* mm %(padding_mm)f) (* mm 1))
197 %% ****************************************************************
199 %% ****************************************************************
203 %% ****************************************************************
205 %% ****************************************************************
213 %% ****************************************************************
214 %% ly snippet contents follows:
215 %% ****************************************************************
219 %% ****************************************************************
221 %% ****************************************************************
228 ####################################################################
230 ####################################################################
232 def ps_page_count (ps_name):
233 header = file (ps_name).read (1024)
234 m = re.search ('\n%%Pages: ([0-9]+)', header)
236 return int (m.group (1))
239 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
240 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
241 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
242 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
244 def ly_comment_gettext (t, m):
245 return m.group (1) + t (m.group (2))
249 class CompileError(Exception):
254 ####################################################################
256 ####################################################################
259 def replacement_text (self):
262 def filter_text (self):
263 return self.replacement_text ()
268 class Substring (Chunk):
269 """A string that does not require extra memory."""
270 def __init__ (self, source, start, end, line_number):
274 self.line_number = line_number
275 self.override_text = None
280 def replacement_text (self):
281 if self.override_text:
282 return self.override_text
284 return self.source[self.start:self.end]
288 class Snippet (Chunk):
289 def __init__ (self, type, match, formatter, line_number, global_options):
293 self.option_dict = {}
294 self.formatter = formatter
295 self.line_number = line_number
296 self.global_options = global_options
297 self.replacements = {'program_version': ly.program_version,
298 'program_name': ly.program_name}
300 # return a shallow copy of the replacements, so the caller can modify
301 # it locally without interfering with other snippet operations
302 def get_replacements (self):
303 return copy.copy (self.replacements)
305 def replacement_text (self):
306 return self.match.group ('match')
308 def substring (self, s):
309 return self.match.group (s)
312 return `self.__class__` + ' type = ' + self.type
316 class IncludeSnippet (Snippet):
317 def processed_filename (self):
318 f = self.substring ('filename')
319 return os.path.splitext (f)[0] + self.formatter.default_extension
321 def replacement_text (self):
322 s = self.match.group ('match')
323 f = self.substring ('filename')
324 return re.sub (f, self.processed_filename (), s)
328 class LilypondSnippet (Snippet):
329 def __init__ (self, type, match, formatter, line_number, global_options):
330 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
331 os = match.group ('options')
332 self.do_options (os, self.type)
335 def snippet_options (self):
338 def verb_ly_gettext (self, s):
339 lang = self.formatter.document_language
343 t = langdefs.translation[lang]
347 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
349 if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
350 for v in ly_var_def_re.findall (s):
351 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
352 "\\1" + t (v) + "\\2",
354 for id in ly_context_id_re.findall (s):
355 s = re.sub (r'(\s+|")%s(\s+|")' % id,
356 "\\1" + t (id) + "\\2",
361 verb_text = self.substring ('code')
362 if not NOGETTEXT in self.option_dict:
363 verb_text = self.verb_ly_gettext (verb_text)
364 if not verb_text.endswith ('\n'):
369 contents = self.substring ('code')
370 return ('\\sourcefileline %d\n%s'
371 % (self.line_number - 1, contents))
376 return self.compose_ly (s)
379 def split_options (self, option_string):
380 return self.formatter.split_snippet_options (option_string);
382 def do_options (self, option_string, type):
383 self.option_dict = {}
385 options = self.split_options (option_string)
387 for option in options:
389 (key, value) = re.split ('\s*=\s*', option)
390 self.option_dict[key] = value
392 if option in no_options:
393 if no_options[option] in self.option_dict:
394 del self.option_dict[no_options[option]]
396 self.option_dict[option] = None
399 # Store if we have an explicit line-width given
400 has_line_width = self.option_dict.has_key (LINE_WIDTH)
401 if has_line_width and self.option_dict[LINE_WIDTH] == None:
402 has_line_width = False
403 del self.option_dict[LINE_WIDTH]
405 # Use default options (i.e. auto-detected line-width, etc)
406 for k in self.formatter.default_snippet_options:
407 if k not in self.option_dict:
408 self.option_dict[k] = self.formatter.default_snippet_options[k]
410 # RELATIVE does not work without FRAGMENT;
411 # make RELATIVE imply FRAGMENT
412 has_relative = self.option_dict.has_key (RELATIVE)
413 if has_relative and not self.option_dict.has_key (FRAGMENT):
414 self.option_dict[FRAGMENT] = None
416 if not INDENT in self.option_dict:
417 self.option_dict[INDENT] = '0\\mm'
419 # Set a default line-width if there is none. We need this, because
420 # lilypond-book has set left-padding by default and therefore does
421 # #(define line-width (- line-width (* 3 mm)))
422 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
423 # all settings before writing them in the \paper block.
424 if not LINE_WIDTH in self.option_dict:
425 if not QUOTE in self.option_dict:
426 self.option_dict[LINE_WIDTH] = "#(- paper-width \
427 left-margin-default right-margin-default)"
429 def get_option_list (self):
430 if not 'option_list' in self.__dict__:
432 for (key, value) in self.option_dict.items ():
434 option_list.append (key)
436 option_list.append (key + '=' + value)
438 self.option_list = option_list
439 return self.option_list
441 def compose_ly (self, code):
446 # The original concept of the `exampleindent' option is broken.
447 # It is not possible to get a sane value for @exampleindent at all
448 # without processing the document itself. Saying
456 # causes ugly results with the DVI backend of texinfo since the
457 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
458 # value). Executing the above code changes the environment
459 # indentation to an unknown value because we don't know the amount
460 # of 1em in advance since it is font-dependent. Modifying
461 # @exampleindent in the middle of a document is simply not
462 # supported within texinfo.
464 # As a consequence, the only function of @exampleindent is now to
465 # specify the amount of indentation for the `quote' option.
467 # To set @exampleindent locally to zero, we use the @format
468 # environment for non-quoted snippets.
469 override[EXAMPLEINDENT] = r'0.4\in'
470 override[LINE_WIDTH] = '5\\in' # = texinfo_line_widths['@smallbook']
471 override.update (self.formatter.default_snippet_options)
474 for option in self.get_option_list ():
475 for name in PROCESSING_INDEPENDENT_OPTIONS:
476 if option.startswith (name):
479 option_list.append (option)
480 option_string = ','.join (option_list)
482 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
483 for a in compose_types:
486 option_names = self.option_dict.keys ()
488 for key in option_names:
489 value = self.option_dict[key]
490 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
494 _ ("deprecated ly-option used: %s=%s") % (key, value))
496 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
499 _ ("deprecated ly-option used: %s") % key)
501 _ ("compatibility mode translation: %s") % c_key)
503 (key, value) = (c_key, c_value)
506 override[key] = value
508 if not override.has_key (key):
512 for typ in compose_types:
513 if snippet_options[typ].has_key (key):
514 compose_dict[typ].append (snippet_options[typ][key])
518 if not found and key not in simple_options and key not in self.snippet_options ():
519 warning (_ ("ignoring unknown ly option: %s") % key)
522 if RELATIVE in override and override[RELATIVE]:
523 relative = int (override[RELATIVE])
529 relative_quotes += ',' * (- relative)
531 relative_quotes += "'" * relative
533 # put paper-size first, if it exists
534 for i,elem in enumerate(compose_dict[PAPER]):
535 if elem.startswith("#(set-paper-size"):
536 compose_dict[PAPER].insert(0, compose_dict[PAPER].pop(i))
539 paper_string = '\n '.join (compose_dict[PAPER]) % override
540 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
541 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
542 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
543 padding_mm = self.global_options.padding_mm
544 if self.global_options.safe_mode:
545 safe_mode_string = "#(ly:set-option 'safe #t)"
547 safe_mode_string = ""
551 d.update (self.global_options.information)
552 if FRAGMENT in self.option_dict:
556 return (PREAMBLE_LY + body) % d
558 def get_checksum (self):
559 if not self.checksum:
560 # Work-around for md5 module deprecation warning in python 2.5+:
562 from hashlib import md5
566 # We only want to calculate the hash based on the snippet
567 # code plus fragment options relevant to processing by
568 # lilypond, not the snippet + preamble
569 hash = md5 (self.relevant_contents (self.ly ()))
570 for option in self.get_option_list ():
571 for name in PROCESSING_INDEPENDENT_OPTIONS:
572 if option.startswith (name):
577 ## let's not create too long names.
578 self.checksum = hash.hexdigest ()[:10]
583 cs = self.get_checksum ()
584 name = os.path.join (cs[:2], 'lily-%s' % cs[2:])
587 final_basename = basename
590 base = self.basename ()
591 path = os.path.join (self.global_options.lily_output_dir, base)
592 directory = os.path.split(path)[0]
593 if not os.path.isdir (directory):
594 os.makedirs (directory)
595 filename = path + '.ly'
596 if os.path.exists (filename):
597 existing = open (filename, 'r').read ()
599 if self.relevant_contents (existing) != self.relevant_contents (self.full_ly ()):
600 warning ("%s: duplicate filename but different contents of orginal file,\n\
601 printing diff against existing file." % filename)
602 ly.stderr_write (self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename))
604 out = file (filename, 'w')
605 out.write (self.full_ly ())
606 file (path + '.txt', 'w').write ('image of music')
608 def relevant_contents (self, ly):
609 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
611 def link_all_output_files (self, output_dir, output_dir_files, destination):
612 existing, missing = self.all_output_files (output_dir, output_dir_files)
614 print '\nMissing', missing
615 raise CompileError(self.basename())
616 for name in existing:
617 if (self.global_options.use_source_file_names
618 and isinstance (self, LilypondFileSnippet)):
619 base, ext = os.path.splitext (name)
620 components = base.split ('-')
621 # ugh, assume filenames with prefix with one dash (lily-xxxx)
622 if len (components) > 2:
623 base_suffix = '-' + components[-1]
626 final_name = self.final_basename () + base_suffix + ext
630 os.unlink (os.path.join (destination, final_name))
634 src = os.path.join (output_dir, name)
635 dst = os.path.join (destination, final_name)
636 dst_path = os.path.split(dst)[0]
637 if not os.path.isdir (dst_path):
638 os.makedirs (dst_path)
641 def additional_files_to_consider (self, base, full):
643 def additional_files_required (self, base, full):
647 def all_output_files (self, output_dir, output_dir_files):
648 """Return all files generated in lily_output_dir, a set.
650 output_dir_files is the list of files in the output directory.
654 base = self.basename()
655 full = os.path.join (output_dir, base)
656 def consider_file (name):
657 if name in output_dir_files:
660 def require_file (name):
661 if name in output_dir_files:
666 # UGH - junk self.global_options
667 skip_lily = self.global_options.skip_lilypond_run
668 for required in [base + '.ly',
670 require_file (required)
672 require_file (base + '-systems.count')
674 if 'ddump-profile' in self.global_options.process_cmd:
675 require_file (base + '.profile')
676 if 'dseparate-log-file' in self.global_options.process_cmd:
677 require_file (base + '.log')
679 map (consider_file, [base + '.tex',
683 base + '-systems.texi',
684 base + '-systems.tex',
685 base + '-systems.pdftexi'])
686 if self.formatter.document_language:
688 [base + '.texidoc' + self.formatter.document_language,
689 base + '.doctitle' + self.formatter.document_language])
691 required_files = self.formatter.required_files (self, base, full, result)
692 for f in required_files:
696 if not skip_lily and not missing:
697 system_count = int(file (full + '-systems.count').read())
699 for number in range(1, system_count + 1):
700 systemfile = '%s-%d' % (base, number)
701 require_file (systemfile + '.eps')
702 consider_file (systemfile + '.pdf')
704 # We can't require signatures, since books and toplevel
705 # markups do not output a signature.
706 if 'ddump-signature' in self.global_options.process_cmd:
707 consider_file (systemfile + '.signature')
709 map (consider_file, self.additional_files_to_consider (base, full))
710 map (require_file, self.additional_files_required (base, full))
712 return (result, missing)
714 def is_outdated (self, output_dir, current_files):
715 found, missing = self.all_output_files (output_dir, current_files)
718 def filter_pipe (self, input, cmd):
719 """Pass input through cmd, and return the result."""
721 debug (_ ("Running through filter `%s'") % cmd, True)
723 # TODO: Use Popen once we resolve the problem with msvcrt in Windows:
724 (stdin, stdout, stderr) = os.popen3 (cmd)
725 # p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
726 # (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
728 status = stdin.close ()
732 output = stdout.read ()
733 status = stdout.close ()
738 signal = 0x0f & status
739 if status or (not output and err):
740 exit_status = status >> 8
741 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
742 ly.error (_ ("The error log is as follows:"))
743 ly.stderr_write (err)
744 ly.stderr_write (stderr.read ())
751 def get_snippet_code (self):
752 return self.substring ('code');
754 def filter_text (self):
755 """Run snippet bodies through a command (say: convert-ly).
757 This functionality is rarely used, and this code must have bitrot.
759 code = self.get_snippet_code ();
760 s = self.filter_pipe (code, self.global_options.filter_cmd)
763 'options': self.match.group ('options')
765 return self.formatter.output_simple_replacements (FILTER, d)
767 def replacement_text (self):
768 base = self.final_basename ()
769 return self.formatter.snippet_output (base, self)
771 def get_images (self):
772 rep = {'base': self.final_basename ()}
774 single = '%(base)s.png' % rep
775 multiple = '%(base)s-page1.png' % rep
777 if (os.path.exists (multiple)
778 and (not os.path.exists (single)
779 or (os.stat (multiple)[stat.ST_MTIME]
780 > os.stat (single)[stat.ST_MTIME]))):
781 count = ps_page_count ('%(base)s.eps' % rep)
782 images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
783 images = tuple (images)
789 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
790 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
792 class LilypondFileSnippet (LilypondSnippet):
793 def __init__ (self, type, match, formatter, line_number, global_options):
794 LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
795 self.filename = self.substring ('filename')
796 self.ext = os.path.splitext (os.path.basename (self.filename))[1]
797 self.contents = file (BookBase.find_file (self.filename, global_options.include_path)).read ()
799 def get_snippet_code (self):
800 return self.contents;
804 s = re_begin_verbatim.split (s)[-1]
805 s = re_end_verbatim.split (s)[0]
806 if not NOGETTEXT in self.option_dict:
807 s = self.verb_ly_gettext (s)
808 if not s.endswith ('\n'):
814 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
815 % (name, self.contents))
817 def final_basename (self):
818 if self.global_options.use_source_file_names:
819 base = os.path.splitext (os.path.basename (self.filename))[0]
822 return self.basename ()
825 class MusicXMLFileSnippet (LilypondFileSnippet):
826 def __init__ (self, type, match, formatter, line_number, global_options):
827 LilypondFileSnippet.__init__ (self, type, match, formatter, line_number, global_options)
828 self.compressed = False
829 self.converted_ly = None
830 self.musicxml_options_dict = {
831 'verbose': '--verbose',
833 'compressed': '--compressed',
834 'relative': '--relative',
835 'absolute': '--absolute',
836 'no-articulation-directions': '--no-articulation-directions',
837 'no-rest-positions': '--no-rest-positions',
838 'no-page-layout': '--no-page-layout',
839 'no-beaming': '--no-beaming',
840 'language': '--language',
843 def snippet_options (self):
844 return self.musicxml_options_dict.keys ()
846 def convert_from_musicxml (self):
848 xml2ly_option_list = []
849 for (key, value) in self.option_dict.items ():
850 cmd_key = self.musicxml_options_dict.get (key, None)
854 xml2ly_option_list.append (cmd_key)
856 xml2ly_option_list.append (cmd_key + '=' + value)
857 if ('.mxl' in name) and ('--compressed' not in xml2ly_option_list):
858 xml2ly_option_list.append ('--compressed')
859 self.compressed = True
860 opts = " ".join (xml2ly_option_list)
861 progress (_ ("Converting MusicXML file `%s'...\n") % self.filename)
863 ly_code = self.filter_pipe (self.contents, 'musicxml2ly %s --out=- - ' % opts)
867 if self.converted_ly == None:
868 self.converted_ly = self.convert_from_musicxml ()
870 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
871 % (name, self.converted_ly))
873 def additional_files_required (self, base, full):
876 result.append (base + '.mxl')
878 result.append (base + '.xml')
882 base = self.basename ()
883 path = os.path.join (self.global_options.lily_output_dir, base)
884 directory = os.path.split(path)[0]
885 if not os.path.isdir (directory):
886 os.makedirs (directory)
888 # First write the XML to a file (so we can link it!)
890 xmlfilename = path + '.mxl'
892 xmlfilename = path + '.xml'
893 if os.path.exists (xmlfilename):
894 diff_against_existing = self.filter_pipe (self.contents, 'diff -u %s - ' % xmlfilename)
895 if diff_against_existing:
896 warning (_ ("%s: duplicate filename but different contents of orginal file,\n\
897 printing diff against existing file.") % xmlfilename)
898 ly.stderr_write (diff_against_existing)
900 out = file (xmlfilename, 'w')
901 out.write (self.contents)
904 # also write the converted lilypond
905 filename = path + '.ly'
906 if os.path.exists (filename):
907 diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
908 if diff_against_existing:
909 warning (_ ("%s: duplicate filename but different contents of converted lilypond file,\n\
910 printing diff against existing file.") % filename)
911 ly.stderr_write (diff_against_existing)
913 out = file (filename, 'w')
914 out.write (self.full_ly ())
916 file (path + '.txt', 'w').write ('image of music')
920 class LilyPondVersionString (Snippet):
921 """A string that does not require extra memory."""
922 def __init__ (self, type, match, formatter, line_number, global_options):
923 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
925 def replacement_text (self):
926 return self.formatter.output_simple (self.type, self)
929 snippet_type_to_class = {
930 'lilypond_file': LilypondFileSnippet,
931 'lilypond_block': LilypondSnippet,
932 'lilypond': LilypondSnippet,
933 'include': IncludeSnippet,
934 'lilypondversion': LilyPondVersionString,
935 'musicxml_file': MusicXMLFileSnippet,