1 # -*- coding: utf-8 -*-
3 import book_base as BookBase
9 from subprocess import Popen, PIPE
11 progress = ly.progress
19 ####################################################################
20 # Snippet option handling
21 ####################################################################
25 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
28 ADDVERSION = 'addversion'
33 EXAMPLEINDENT = 'exampleindent'
37 LANG = 'lang' ## TODO: This is handled nowhere!
39 LILYQUOTE = 'lilyquote'
40 LINE_WIDTH = 'line-width'
41 NOFRAGMENT = 'nofragment'
42 NOGETTEXT = 'nogettext'
46 NORAGGED_RIGHT = 'noragged-right'
50 OUTPUTIMAGE = 'outputimage'
53 PRINTFILENAME = 'printfilename'
55 RAGGED_RIGHT = 'ragged-right'
57 STAFFSIZE = 'staffsize'
60 VERSION = 'lilypondversion'
64 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
66 # NOQUOTE is used internally only.
72 # Options that have no impact on processing by lilypond (or --process
74 PROCESSING_INDEPENDENT_OPTIONS = (
75 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
76 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
80 # Options without a pattern in snippet_options.
99 ####################################################################
100 # LilyPond templates for the snippets
101 ####################################################################
106 RELATIVE: r'''\relative c%(relative_quotes)s''',
111 INDENT: r'''indent = %(indent)s''',
112 LINE_WIDTH: r'''line-width = %(line-width)s''',
113 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
114 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
115 RAGGED_RIGHT: r'''ragged-right = ##t''',
116 NORAGGED_RIGHT: r'''ragged-right = ##f''',
128 \remove "Time_signature_engraver"
134 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
147 %% ****************************************************************
148 %% ly snippet contents follows:
149 %% ****************************************************************
153 %% ****************************************************************
155 %% ****************************************************************
159 def classic_lilypond_book_compatibility (key, value):
160 if key == 'singleline' and value == None:
161 return (RAGGED_RIGHT, None)
163 m = re.search ('relative\s*([-0-9])', key)
165 return ('relative', m.group (1))
167 m = re.match ('([0-9]+)pt', key)
169 return ('staffsize', m.group (1))
171 if key == 'indent' or key == 'line-width':
172 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
174 f = float (m.group (1))
175 return (key, '%f\\%s' % (f, m.group (2)))
180 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
181 %%%% Options: [%(option_string)s]
182 \\include "lilypond-book-preamble.ly"
185 %% ****************************************************************
186 %% Start cut-&-pastable-section
187 %% ****************************************************************
193 force-assignment = #""
194 line-width = #(- line-width (* mm %(padding_mm)f))
206 %% ****************************************************************
208 %% ****************************************************************
212 %% ****************************************************************
214 %% ****************************************************************
224 ####################################################################
226 ####################################################################
228 def ps_page_count (ps_name):
229 header = file (ps_name).read (1024)
230 m = re.search ('\n%%Pages: ([0-9]+)', header)
232 return int (m.group (1))
235 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
236 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
237 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
238 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
240 def ly_comment_gettext (t, m):
241 return m.group (1) + t (m.group (2))
245 class CompileError(Exception):
250 ####################################################################
252 ####################################################################
255 def replacement_text (self):
258 def filter_text (self):
259 return self.replacement_text ()
264 class Substring (Chunk):
265 """A string that does not require extra memory."""
266 def __init__ (self, source, start, end, line_number):
270 self.line_number = line_number
271 self.override_text = None
276 def replacement_text (self):
277 if self.override_text:
278 return self.override_text
280 return self.source[self.start:self.end]
284 class Snippet (Chunk):
285 def __init__ (self, type, match, formatter, line_number, global_options):
289 self.option_dict = {}
290 self.formatter = formatter
291 self.line_number = line_number
292 self.global_options = global_options
293 self.replacements = {'program_version': ly.program_version,
294 'program_name': ly.program_name}
296 # return a shallow copy of the replacements, so the caller can modify
297 # it locally without interfering with other snippet operations
298 def get_replacements (self):
299 return copy.copy (self.replacements)
301 def replacement_text (self):
302 return self.match.group ('match')
304 def substring (self, s):
305 return self.match.group (s)
308 return `self.__class__` + ' type = ' + self.type
312 class IncludeSnippet (Snippet):
313 def processed_filename (self):
314 f = self.substring ('filename')
315 return os.path.splitext (f)[0] + self.formatter.default_extension
317 def replacement_text (self):
318 s = self.match.group ('match')
319 f = self.substring ('filename')
320 return re.sub (f, self.processed_filename (), s)
324 class LilypondSnippet (Snippet):
325 def __init__ (self, type, match, formatter, line_number, global_options):
326 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
327 os = match.group ('options')
328 self.do_options (os, self.type)
331 def verb_ly_gettext (self, s):
332 lang = self.formatter.document_language
336 t = langdefs.translation[lang]
340 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
342 if langdefs.LANGDICT[lang].enable_ly_identifier_l10n:
343 for v in ly_var_def_re.findall (s):
344 s = re.sub (r"(?m)(?<!\\clef)(^|[' \\#])%s([^a-zA-Z])" % v,
345 "\\1" + t (v) + "\\2",
347 for id in ly_context_id_re.findall (s):
348 s = re.sub (r'(\s+|")%s(\s+|")' % id,
349 "\\1" + t (id) + "\\2",
354 verb_text = self.substring ('code')
355 if not NOGETTEXT in self.option_dict:
356 verb_text = self.verb_ly_gettext (verb_text)
357 if not verb_text.endswith ('\n'):
362 contents = self.substring ('code')
363 return ('\\sourcefileline %d\n%s'
364 % (self.line_number - 1, contents))
369 return self.compose_ly (s)
372 def split_options (self, option_string):
373 return self.formatter.split_snippet_options (option_string);
375 def do_options (self, option_string, type):
376 self.option_dict = {}
378 options = self.split_options (option_string)
380 for option in options:
382 (key, value) = re.split ('\s*=\s*', option)
383 self.option_dict[key] = value
385 if option in no_options:
386 if no_options[option] in self.option_dict:
387 del self.option_dict[no_options[option]]
389 self.option_dict[option] = None
392 # If LINE_WIDTH is used without parameter, set it to default.
393 has_line_width = self.option_dict.has_key (LINE_WIDTH)
394 if has_line_width and self.option_dict[LINE_WIDTH] == None:
395 has_line_width = False
396 del self.option_dict[LINE_WIDTH]
398 # TODO: Can't we do that more efficiently (built-in python func?)
399 for k in self.formatter.default_snippet_options:
400 if k not in self.option_dict:
401 self.option_dict[k] = self.formatter.default_snippet_options[k]
403 # RELATIVE does not work without FRAGMENT;
404 # make RELATIVE imply FRAGMENT
405 has_relative = self.option_dict.has_key (RELATIVE)
406 if has_relative and not self.option_dict.has_key (FRAGMENT):
407 self.option_dict[FRAGMENT] = None
409 if not has_line_width:
410 if type == 'lilypond' or FRAGMENT in self.option_dict:
411 self.option_dict[RAGGED_RIGHT] = None
413 if type == 'lilypond':
414 if LINE_WIDTH in self.option_dict:
415 del self.option_dict[LINE_WIDTH]
417 if RAGGED_RIGHT in self.option_dict:
418 if LINE_WIDTH in self.option_dict:
419 del self.option_dict[LINE_WIDTH]
421 if QUOTE in self.option_dict or type == 'lilypond':
422 if LINE_WIDTH in self.option_dict:
423 del self.option_dict[LINE_WIDTH]
425 if not INDENT in self.option_dict:
426 self.option_dict[INDENT] = '0\\mm'
428 # Set a default line-width if there is none. We need this, because
429 # lilypond-book has set left-padding by default and therefore does
430 # #(define line-width (- line-width (* 3 mm)))
431 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
432 # all settings before writing them in the \paper block.
433 if not LINE_WIDTH in self.option_dict:
434 if not QUOTE in self.option_dict:
435 if not LILYQUOTE in self.option_dict:
436 self.option_dict[LINE_WIDTH] = "#(- paper-width \
437 left-margin-default right-margin-default)"
439 def get_option_list (self):
440 if not 'option_list' in self.__dict__:
442 for (key, value) in self.option_dict.items ():
444 option_list.append (key)
446 option_list.append (key + '=' + value)
448 self.option_list = option_list
449 return self.option_list
451 def compose_ly (self, code):
452 if FRAGMENT in self.option_dict:
460 # The original concept of the `exampleindent' option is broken.
461 # It is not possible to get a sane value for @exampleindent at all
462 # without processing the document itself. Saying
470 # causes ugly results with the DVI backend of texinfo since the
471 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
472 # value). Executing the above code changes the environment
473 # indentation to an unknown value because we don't know the amount
474 # of 1em in advance since it is font-dependent. Modifying
475 # @exampleindent in the middle of a document is simply not
476 # supported within texinfo.
478 # As a consequence, the only function of @exampleindent is now to
479 # specify the amount of indentation for the `quote' option.
481 # To set @exampleindent locally to zero, we use the @format
482 # environment for non-quoted snippets.
483 override[EXAMPLEINDENT] = r'0.4\in'
484 override[LINE_WIDTH] = '5\\in' # = texinfo_line_widths['@smallbook']
485 override.update (self.formatter.default_snippet_options)
488 for option in self.get_option_list ():
489 for name in PROCESSING_INDEPENDENT_OPTIONS:
490 if option.startswith (name):
493 option_list.append (option)
494 option_string = ','.join (option_list)
496 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
497 for a in compose_types:
500 option_names = self.option_dict.keys ()
502 for key in option_names:
503 value = self.option_dict[key]
504 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
508 _ ("deprecated ly-option used: %s=%s") % (key, value))
510 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
513 _ ("deprecated ly-option used: %s") % key)
515 _ ("compatibility mode translation: %s") % c_key)
517 (key, value) = (c_key, c_value)
520 override[key] = value
522 if not override.has_key (key):
526 for typ in compose_types:
527 if snippet_options[typ].has_key (key):
528 compose_dict[typ].append (snippet_options[typ][key])
532 if not found and key not in simple_options:
533 warning (_ ("ignoring unknown ly option: %s") % key)
536 if RELATIVE in override and override[RELATIVE]:
537 relative = int (override[RELATIVE])
543 relative_quotes += ',' * (- relative)
545 relative_quotes += "'" * relative
547 paper_string = '\n '.join (compose_dict[PAPER]) % override
548 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
549 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
550 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
551 padding_mm = self.global_options.padding_mm
555 d.update (self.global_options.information)
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 = '%s/lily-%s' % (cs[:2], 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 diff_against_existing = self.filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
598 if diff_against_existing:
599 warning ("%s: duplicate filename but different contents of orginal file,\n\
600 printing diff against existing file." % filename)
601 ly.stderr_write (diff_against_existing)
603 out = file (filename, 'w')
604 out.write (self.full_ly ())
605 file (path + '.txt', 'w').write ('image of music')
607 def relevant_contents (self, ly):
608 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
610 def link_all_output_files (self, output_dir, output_dir_files, destination):
611 existing, missing = self.all_output_files (output_dir, output_dir_files)
613 print '\nMissing', missing
614 raise CompileError(self.basename())
615 for name in existing:
616 if (self.global_options.use_source_file_names
617 and isinstance (self, LilypondFileSnippet)):
618 base, ext = os.path.splitext (name)
619 components = base.split ('-')
620 # ugh, assume filenames with prefix with one dash (lily-xxxx)
621 if len (components) > 2:
622 base_suffix = '-' + components[-1]
625 final_name = self.final_basename () + base_suffix + ext
629 os.unlink (os.path.join (destination, final_name))
633 src = os.path.join (output_dir, name)
634 dst = os.path.join (destination, final_name)
635 dst_path = os.path.split(dst)[0]
636 if not os.path.isdir (dst_path):
637 os.makedirs (dst_path)
641 def all_output_files (self, output_dir, output_dir_files):
642 """Return all files generated in lily_output_dir, a set.
644 output_dir_files is the list of files in the output directory.
648 base = self.basename()
649 full = os.path.join (output_dir, base)
650 def consider_file (name):
651 if name in output_dir_files:
654 def require_file (name):
655 if name in output_dir_files:
660 # UGH - junk self.global_options
661 skip_lily = self.global_options.skip_lilypond_run
662 for required in [base + '.ly',
664 require_file (required)
666 require_file (base + '-systems.count')
668 if 'ddump-profile' in self.global_options.process_cmd:
669 require_file (base + '.profile')
670 if 'dseparate-log-file' in self.global_options.process_cmd:
671 require_file (base + '.log')
673 map (consider_file, [base + '.tex',
677 base + '-systems.texi',
678 base + '-systems.tex',
679 base + '-systems.pdftexi'])
680 if self.formatter.document_language:
682 [base + '.texidoc' + self.formatter.document_language,
683 base + '.doctitle' + self.formatter.document_language])
685 required_files = self.formatter.required_files (self, base, full, result)
686 for f in required_files:
690 if not skip_lily and not missing:
691 system_count = int(file (full + '-systems.count').read())
693 for number in range(1, system_count + 1):
694 systemfile = '%s-%d' % (base, number)
695 require_file (systemfile + '.eps')
696 consider_file (systemfile + '.pdf')
698 # We can't require signatures, since books and toplevel
699 # markups do not output a signature.
700 if 'ddump-signature' in self.global_options.process_cmd:
701 consider_file (systemfile + '.signature')
704 return (result, missing)
706 def is_outdated (self, output_dir, current_files):
707 found, missing = self.all_output_files (output_dir, current_files)
710 def filter_pipe (self, input, cmd):
711 """Pass input through cmd, and return the result."""
713 if self.global_options.verbose:
714 progress (_ ("Opening filter `%s'\n") % cmd)
716 #(stdin, stdout, stderr) = os.popen3 (cmd)
718 p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
719 (stdin, stdout, stderr) = (p.stdin, p.stdout, p.stderr)
721 status = stdin.close ()
725 output = stdout.read ()
726 status = stdout.close ()
727 error = stderr.read ()
731 signal = 0x0f & status
732 if status or (not output and error):
733 exit_status = status >> 8
734 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
735 error (_ ("The error log is as follows:"))
736 ly.stderr_write (error)
737 ly.stderr_write (stderr.read ())
740 if self.global_options.verbose:
745 def get_snippet_code (self):
746 return self.substring ('code');
748 def filter_text (self):
749 """Run snippet bodies through a command (say: convert-ly).
751 This functionality is rarely used, and this code must have bitrot.
753 code = self.get_snippet_code ();
754 s = self.filter_pipe (code, self.global_options.filter_cmd)
757 'options': self.match.group ('options')
759 return self.formatter.output_simple_replacements (FILTER, d)
761 def replacement_text (self):
762 base = self.final_basename ()
763 return self.formatter.snippet_output (base, self)
765 def get_images (self):
766 rep = {'base': self.final_basename ()}
768 single = '%(base)s.png' % rep
769 multiple = '%(base)s-page1.png' % rep
771 if (os.path.exists (multiple)
772 and (not os.path.exists (single)
773 or (os.stat (multiple)[stat.ST_MTIME]
774 > os.stat (single)[stat.ST_MTIME]))):
775 count = ps_page_count ('%(base)s.eps' % rep)
776 images = ['%s-page%d.png' % (rep['base'], page) for page in range (1, count+1)]
777 images = tuple (images)
783 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
784 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
786 class LilypondFileSnippet (LilypondSnippet):
787 def __init__ (self, type, match, formatter, line_number, global_options):
788 LilypondSnippet.__init__ (self, type, match, formatter, line_number, global_options)
789 self.contents = file (BookBase.find_file (self.substring ('filename'), global_options.include_path)).read ()
791 def get_snippet_code (self):
792 return self.contents;
796 s = re_begin_verbatim.split (s)[-1]
797 s = re_end_verbatim.split (s)[0]
798 if not NOGETTEXT in self.option_dict:
799 s = self.verb_ly_gettext (s)
800 if not s.endswith ('\n'):
805 name = self.substring ('filename')
806 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
807 % (name, self.contents))
809 def final_basename (self):
810 if self.global_options.use_source_file_names:
811 base = os.path.splitext (os.path.basename (self.substring ('filename')))[0]
814 return self.basename ()
817 class LilyPondVersionString (Snippet):
818 """A string that does not require extra memory."""
819 def __init__ (self, type, match, formatter, line_number, global_options):
820 Snippet.__init__ (self, type, match, formatter, line_number, global_options)
822 def replacement_text (self):
823 return self.formatter.output_simple (self.type, self)
826 snippet_type_to_class = {
827 'lilypond_file': LilypondFileSnippet,
828 'lilypond_block': LilypondSnippet,
829 'lilypond': LilypondSnippet,
830 'include': IncludeSnippet,
831 'lilypondversion': LilyPondVersionString,