5 ly-options: intertext, quote ?
8 check latex parameters, twocolumn
16 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
19 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
21 classic lilypond-book:
22 lilypond-book --process="lilypond-bin" BOOK.tely
25 @mbinclude foo.itely -> @include foo.itely
33 ################################################################
34 # Users of python modules should include this snippet
35 # and customize variables below.
37 # We'll suffer this path init stuff as long as we don't install our
38 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
39 # it as we do with teTeX on Red Hat Linux: set some environment var
40 # (PYTHONPATH) in profile)
42 # If set, LILYPONDPREFIX must take prevalence
43 # if datadir is not set, we're doing a build and LILYPONDPREFIX
44 import getopt, os, sys
45 datadir = '@local_lilypond_datadir@'
46 if not os.path.isdir (datadir):
47 datadir = '@lilypond_datadir@'
48 if os.environ.has_key ('LILYPONDPREFIX') :
49 datadir = os.environ['LILYPONDPREFIX']
50 while datadir[-1] == os.sep:
53 sys.path.insert (0, os.path.join (datadir, 'python'))
56 #if __name__ == '__main__':
64 program_version = '@TOPLEVEL_VERSION@'
65 program_name = 'lilypond-book'
68 original_dir = os.getcwd ()
71 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document. Example usage:
73 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
74 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
75 lilypond-book --process='lilypond-bin -I include' BOOK
79 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
80 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
82 option_definitions = [
83 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
84 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
85 ('', 'h', 'help', _ ("print this help")),
86 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
87 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
88 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
89 ('', 'V', 'verbose', _ ("be verbose")),
90 ('', 'v', 'version', _ ("print version information")),
91 ('', 'w', 'warranty', _ ("show warranty and copyright")),
94 include_path = [ly.abspath (os.getcwd ())]
95 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
97 # only use installed binary when we're installed too.
98 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
99 lilypond_binary = 'lilypond-bin'
105 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
107 process_cmd = lilypond_binary
108 default_ly_options = { }
114 LINEWIDTH = 'linewidth'
118 PREAMBLE = 'preamble'
120 VERBATIM = 'verbatim'
121 PRINTFILENAME = 'printfilename'
123 # Recognize special sequences in the input
125 # (?P<name>regex) -- assign result of REGEX to NAME
126 # *? -- match non-greedily.
127 # (?m) -- multiline regex: make ^ and $ match at each line
128 # (?s) -- make the dot match all characters including newline
133 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
134 'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
135 'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
136 'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
137 'singleline_comment': no_match,
138 'verb': r'''(?P<code><pre>.*?</pre>)''',
139 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
143 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
144 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
145 'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
146 'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
147 'multiline_comment': no_match,
148 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
149 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
150 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
154 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
155 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
156 'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
157 'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
158 'multiline_comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
159 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>@c([ \t][^\n]*|)\n))",
160 'verb': r'''(?P<code>@code{.*?})''',
161 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
167 'option-sep' : '\s*',
168 'intertext': r',?\s*intertext=\".*?\"',
171 'intertext': r',?\s*intertext=\".*?\"',
172 'option-sep' : ',\s*',
175 'intertext': r',?\s*intertext=\".*?\"',
176 'option-sep' : ',\s*',
182 'relative': r'''\relative c%(relative_quotes)s''',
186 indent = %(indent)s''',
188 linewidth = %(linewidth)s''',
194 \remove Time_signature_engraver
198 raggedright = ##t''',
202 #(set-global-staff-size %(staffsize)s)''',
209 PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
212 <img align="center" valign="center"
213 border="0" src="%(base)s.png" alt="[picture of music]">''',
220 PRINTFILENAME: '''\\texttt{%(filename)s}
224 OUTPUT: r'''{\parindent 0pt
226 \ifx\preLilyPondExample\preLilyPondExample\fi
229 \ifx\preLilyPondExample\postLilyPondExample\fi
231 VERBATIM: r'''\begin{verbatim}
232 %(verb)s\end{verbatim}
237 PRINTFILENAME: '''@file{%(filename)s}
242 VERBATIM: r'''@example
250 PREAMBLE_LY = r'''%% Generated by %(program_name)s
251 %% Options: [%(option_string)s]
253 \paper {%(paper_string)s
257 FRAGMENT_LY = r'''\score{
258 \notes%(notes_string)s{
263 texi_linewidths = { 'afourpaper': '160 \\mm',
264 'afourwide': '6.5\\in',
265 'afourlatex': '150 \\mm',
266 'smallbook': '5 \\in' ,
267 'letterpaper': '6\\in'}
269 def classic_lilypond_book_compatibility (o):
270 if o == 'singleline':
272 m = re.search ('relative\s*([-0-9])', o)
274 return 'relative=%s' % m.group (1)
275 m = re.match ('([0-9]+)pt', o)
277 return 'staffsize=%s' % m.group (1)
278 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
280 f = float (m.group (1))
281 return 'indent=%f\\%s' % (f, m.group (2))
282 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
284 f = float (m.group (1))
285 return 'linewidth=%f\\%s' % (f, m.group (2))
288 def compose_ly (code, options):
290 options += default_ly_options.keys ()
291 vars ().update (default_ly_options)
293 m = re.search (r'''\\score''', code)
294 if not m and (not options \
295 or not 'nofragment' in options \
296 or 'fragment' in options):
297 options.append ('raggedright')
305 option_string = string.join (options, ',')
308 preamble_options = []
310 c = classic_lilypond_book_compatibility (i)
312 ly.warning (_ ("deprecated ly-option used: %s" % i))
313 ly.warning (_ ("compatibility mode translation: %s" \
317 if string.find (i, '=') > 0:
318 key, value = string.split (i, '=')
324 if key in ly_options[NOTES].keys ():
325 notes_options.append (ly_options[NOTES][key])
326 elif key in ly_options[PREAMBLE].keys ():
327 preamble_options.append (ly_options[PREAMBLE][key])
328 elif key in ly_options[PAPER].keys ():
329 paper_options.append (ly_options[PAPER][key])
330 elif key not in ('fragment', 'nofragment', 'printfilename',
331 'relative', 'verbatim', 'texidoc'):
332 ly.warning (_("ignoring unknown ly option: %s") % i)
334 relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
335 program_name = __main__.program_name
336 notes_string = string.join (notes_options, '\n ') % vars ()
337 paper_string = string.join (paper_options, '\n ') % vars ()
338 preamble_string = string.join (preamble_options, '\n ') % vars ()
339 return (PREAMBLE_LY + body) % vars ()
343 # use lilypond-bin for latex (.lytex) books,
344 # and lilypond --preview for html, texinfo books?
346 cmd = r'latex "\nonstopmode \input %s"' % file
347 # Ugh. (La)TeX writes progress and error messages on stdout
349 cmd = '(( %s >&2 ) >&- )' % cmd
351 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
354 def find_file (name):
355 for i in include_path:
356 full = os.path.join (i, name)
357 if os.path.exists (full):
359 ly.error (_ ('file not found: %s\n' % name))
363 def verbatim_html (s):
364 return re.sub ('>', '>',
366 re.sub ('&', '&', s)))
368 def verbatim_texinfo (s):
369 return re.sub ('{', '@{',
371 re.sub ('@', '@@', s)))
373 def split_options (option_string):
374 return re.split (format_res[format]['option-sep'], option_string)
378 def replacement_text (self):
382 class Substring (Chunk):
383 def __init__ (self, source, start, end):
387 def replacement_text (self):
388 return self.source [self.start:self.end]
389 def outdated_p (self):
392 class Snippet (Chunk):
393 def __init__ (self, type, match, format):
401 return self.match.start (s)
404 return self.match.end (s)
406 def substring (self, s):
407 return self.match.group (s)
408 def filter_code (self):
411 class Include_snippet (Snippet):
412 def replacement_text (self):
413 s = self.match.group (0)
414 f = self.substring ('filename')
415 nf = os.path.splitext (f)[0] + format2ext[format]
417 return re.sub (f, nf, s)
419 class Lilypond_snippet (Snippet):
420 def __init__ (self, type, match, format):
421 Snippet.__init__ (self, type, match, format)
422 os = match.group ('options')
424 self.options = split_options (os)
428 if self.type == 'lilypond_block' or self.type == 'lilypond':
429 return self.substring ('code')
431 name = self.substring ('filename')
432 return open (find_file (name)).read ()
437 return compose_ly (s, self.options)
442 self.hash = abs (hash (self.full_ly ()))
447 return 'lily-%d' % self.get_hash ()
451 if self.type == 'lilypond_block' or self.type == 'lilypond'\
452 or self.type == 'lilypond_file':
453 outf = open (self.basename () + '.ly', 'w')
454 outf.write (self.full_ly ())
456 def outdated_p (self):
457 base = self.basename ()
458 if os.path.exists (base + '.ly') \
459 and os.path.exists (base + '.tex') \
461 or self.ly () == open (base + '.ly').read ()):
462 # TODO: something smart with target formats
463 # (ps, png) and m/ctimes
468 def replacement_text (self):
469 func = Lilypond_snippet.__dict__ ['output_' + self.format]
472 def output_html (self):
473 base = self.basename ()
474 str = self.output_print_filename (HTML)
475 if VERBATIM in self.options and format == HTML:
476 verb = verbatim_html (self.substring ('code'))
477 str += write (output[HTML][VERBATIM] % vars ())
478 str += (output[HTML][BEFORE]
479 + (output[HTML][OUTPUT] % vars ())
480 + output[HTML][AFTER])
484 def output_latex (self):
486 str = self.output_print_filename (LATEX)
488 base = self.basename ()
489 if VERBATIM in self.options\
491 verb = self.substring ('code')
492 str += (output[LATEX][VERBATIM] % vars ())
494 str += (output[LATEX][BEFORE]
495 + (output[LATEX][OUTPUT] % vars ())
496 + output[LATEX][AFTER])
501 def output_print_filename (self,format):
503 if PRINTFILENAME in self.options:
504 base = self.basename ()
505 filename = self.substring ('filename')
506 str += output[format][PRINTFILENAME] % vars ()
510 def output_texinfo (self):
513 ## Ugh, this breaks texidoc.
514 str = self.output_print_filename (TEXINFO)
516 base = self.basename ()
519 if 'texidoc' in self.options :
520 texidoc = base + '.texidoc'
521 if os.path.exists (texidoc):
522 str += '@include %s\n' % texidoc
525 str += (output[LATEX][BEFORE]
526 + (output[LATEX][OUTPUT] % vars ())
527 + output[LATEX][AFTER])
528 str += ('\n@end tex\n')
531 str += (output[HTML][BEFORE]
532 + (output[HTML][OUTPUT] % vars ())
533 + output[HTML][AFTER])
534 str += ('\n@end html\n')
537 if VERBATIM in self.options:
538 verb = verbatim_texinfo (self.substring ('code'))
539 str += (output[TEXINFO][VERBATIM] % vars ())
544 snippet_type_to_class = {
545 'lilypond_file' : Lilypond_snippet,
546 'lilypond_block' : Lilypond_snippet,
547 'lilypond' : Lilypond_snippet,
548 'include' : Include_snippet
552 def find_toplevel_snippets (infile, types):
556 res[i] = ly.re.compile (snippet_res[format][i])
560 found = dict ([(t, None) for t in types] )
563 # We want to search for multiple regexes,
564 # without searching the string multiple times for one regex.
566 # Hence, we use earlier results to limit the string portion
568 # Since every part of the string is traversed at most once for
569 # every type of snippet, this is linear.
576 if not found[type] or found[type].start (0) < index:
578 m = res[type].search (s[index:endex])
581 if snippet_type_to_class.has_key (type):
582 cl = snippet_type_to_class[type]
584 found[type] = cl (type, m, format)
587 or found[type].start (0) < found[first].start (0)):
590 endex = found[first].start (0)
593 snippets.append (Substring (s, index, len (s)))
597 snippets.append (Substring (s, index, index + snip.start (0)))
598 snippets.append (snip)
599 index += snip.end (0)
605 def filter_pipe (input, cmd):
607 ly.progress (_ ("Opening filter `%s\'") % cmd)
609 stdin, stdout, stderr = os.popen3 (cmd)
611 status = stdin.close ()
615 output = stdout.read ()
616 status = stdout.close ()
617 error = stderr.read ()
621 signal = 0x0f & status
622 if status or (not output and error):
623 exit_status = status >> 8
624 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
625 ly.error (_ ("The error log is as follows:"))
626 sys.stderr.write (error)
627 sys.stderr.write (stderr.read ())
636 return filter_pipe (s, filter_cmd)
638 def process_snippets (cmd, snippets):
639 names = filter (lambda x:x, [y.basename () for y in snippets])
641 ly.system (string.join ([cmd] + names))
643 if format == HTML or format == TEXINFO:
645 if os.path.exists (i + '.tex'):
647 ly.make_ps_images (i + '.eps', resolution=110)
649 LATEX_DOCUMENT = r'''
652 \typeout{textwidth=\the\textwidth}
653 \typeout{columnsep=\the\columnsep}
654 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
657 #need anything else besides textwidth?
658 def get_latex_textwidth (source):
659 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
660 preamble = source[:m.start (0)]
661 latex_document = LATEX_DOCUMENT % vars ()
662 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
665 m = re.search ('columns=([0-9.]*)', parameter_string)
667 columns = string.atoi (m.group (1))
670 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
672 columnsep = string.atof (m.group (1))
675 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
677 textwidth = string.atof (m.group (1))
679 textwidth = (textwidth - columnsep) / columns
691 '.texinfo' : TEXINFO,
697 #TEXINFO: '.texinfo',
702 def do_file (input_filename):
706 e = os.path.splitext (input_filename)[1]
707 if e in ext2format.keys ():
709 format = ext2format[e]
711 ly.error (_ ("cannot determine format for: %s" \
714 ly.progress (_ ("Reading %s...") % input_filename)
715 if not input_filename or input_filename == '-':
718 ih = open (input_filename)
722 ly.progress (_ ("Dissecting..."))
727 'singleline_comment',
734 if output_name == '-' or not output_name:
735 output_file = sys.stdout
736 output_filename = '-'
738 if not os.path.isdir (output_name):
739 os.mkdir (output_name, 0777)
740 if input_filename == '-':
743 input_base = os.path.splitext (input_filename)[0]
744 input_base = os.path.basename (input_base)
746 output_filename = output_name + '/' + input_base \
748 output_file = open (output_filename, 'w')
749 os.chdir (output_name)
752 chunks = find_toplevel_snippets (ih, snippet_types)
755 global default_ly_options
757 if LINEWIDTH not in default_ly_options.keys ():
759 textwidth = get_latex_textwidth (source)
760 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' % textwidth
761 elif format == TEXINFO:
762 for (k,v) in texi_linewidths.items ():
763 s = chunks[0].replacement_text()
765 default_ly_options[LINEWIDTH] = v
771 outdated = filter (lambda x: x.__class__ == Lilypond_snippet and x.outdated_p (),
773 ly.progress (_ ("Writing snippets..."))
774 map (Lilypond_snippet.write_ly, outdated)
778 ly.progress (_ ("Processing..."))
779 process_snippets (process_cmd, outdated)
781 ly.progress (_ ("All snippets are up to date..."))
784 ly.progress (_ ("Compiling %s...") % output_filename)
787 def process_include (snippet):
788 os.chdir (original_dir)
789 name = snippet.substring ('filename')
790 ly.progress (_ ('Processing include: %s') % name)
796 output_file.writelines ([s.replacement_text () for s in chunks])
798 ## UGH. how do you do dynamic_cast/typecheck in Python?
799 map (process_include, filter (lambda x: x.__class__ == Snippet
800 and x.type == 'include', chunks))
803 global format, output_name
804 global filter_cmd, process_cmd, verbose_p
806 (sh, long) = ly.getopt_args (option_definitions)
808 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
809 except getopt.error, s:
810 sys.stderr.write ('\n')
811 ly.error (_ ("getopt says: `%s\'" % s))
812 sys.stderr.write ('\n')
822 elif o == '--filter' or o == '-F':
825 elif o == '--format' or o == '-f':
827 if a == 'texi-html' or a == 'texi':
829 elif o == '--help' or o == '-h':
832 elif o == '--include' or o == '-I':
833 include_path.append (os.path.join (original_dir,
835 elif o == '--output' or o == '-o':
837 elif o == '--outdir':
839 elif o == '--process' or o == '-P':
842 elif o == '--version' or o == '-v':
843 ly.identify (sys.stdout)
845 elif o == '--verbose' or o == '-V':
847 elif o == '--warranty' or o == '-w':
855 files = do_options ()
858 process_cmd += string.join ([(' -I %s' % p)
859 for p in include_path])
861 ly.identify (sys.stderr)
862 ly.setup_environment ()
866 if __name__ == '__main__':