5 ly-options: intertext, quote ?
8 check latex parameters, twocolumn, multicolumn?
13 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
16 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
18 classic lilypond-book:
19 lilypond-book --process="lilypond-bin" BOOK.tely
22 @mbinclude foo.itely -> @include foo.itely
31 ################################################################
32 # Users of python modules should include this snippet
33 # and customize variables below.
35 # We'll suffer this path init stuff as long as we don't install our
36 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
37 # it as we do with teTeX on Red Hat Linux: set some environment var
38 # (PYTHONPATH) in profile)
40 # If set, LILYPONDPREFIX must take prevalence
41 # if datadir is not set, we're doing a build and LILYPONDPREFIX
42 import getopt, os, sys
43 datadir = '@local_lilypond_datadir@'
44 if not os.path.isdir (datadir):
45 datadir = '@lilypond_datadir@'
46 if os.environ.has_key ('LILYPONDPREFIX') :
47 datadir = os.environ['LILYPONDPREFIX']
48 while datadir[-1] == os.sep:
51 sys.path.insert (0, os.path.join (datadir, 'python'))
54 #if __name__ == '__main__':
62 program_version = '@TOPLEVEL_VERSION@'
63 program_name = 'lilypond-book'
66 original_dir = os.getcwd ()
69 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document. Example usage:
71 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
72 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
73 lilypond-book --process='lilypond-bin -I include' BOOK
77 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
78 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
80 option_definitions = [
81 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
82 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
83 ('', 'h', 'help', _ ("print this help")),
84 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
85 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
86 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
87 ('', 'V', 'verbose', _ ("be verbose")),
88 ('', 'v', 'version', _ ("print version information")),
89 ('', 'w', 'warranty', _ ("show warranty and copyright")),
92 include_path = [ly.abspath (os.getcwd ())]
93 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
95 # only use installed binary when we're installed too.
96 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
97 lilypond_binary = 'lilypond-bin'
103 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
105 process_cmd = lilypond_binary
106 default_ly_options = {}
110 FRAGMENT = 'fragment'
113 LINEWIDTH = 'linewidth'
114 NOFRAGMENT = 'nofragment'
118 PREAMBLE = 'preamble'
119 PRINTFILENAME = 'printfilename'
120 RAGGEDRIGHT = 'raggedright'
121 RELATIVE = 'relative'
122 STAFFSIZE = 'staffsize'
125 VERBATIM = 'verbatim'
127 # Recognize special sequences in the input
129 # (?P<name>regex) -- assign result of REGEX to NAME
130 # *? -- match non-greedily.
131 # (?m) -- multiline regex: make ^ and $ match at each line
132 # (?s) -- make the dot match all characters including newline
137 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
138 'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
139 'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
140 'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
141 'singleline_comment': no_match,
142 'verb': r'''(?P<code><pre>.*?</pre>)''',
143 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
147 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
148 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
149 'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
150 'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
151 'multiline_comment': no_match,
152 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
153 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
154 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
158 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S+))',
159 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
160 'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
161 'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
162 'multiline_comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
163 'singleline_comment': r"(?m)^.*(?P<match>(?P<code>@c([ \t][^\n]*|)\n))",
165 # don't do this: fucks up with @code{@{}
166 # 'verb': r'''(?P<code>@code{.*?})''',
167 'verbatim': r'''(?s)(?P<code>@example\s.*?@end\s+example\s)''',
173 'option-sep' : '\s*',
174 'intertext': r',?\s*intertext=\".*?\"',
177 'intertext': r',?\s*intertext=\".*?\"',
178 'option-sep' : ',\s*',
181 'intertext': r',?\s*intertext=\".*?\"',
182 'option-sep' : ',\s*',
188 RELATIVE: r'''\relative c%(relative_quotes)s''',
192 indent = %(indent)s''',
194 linewidth = %(linewidth)s''',
200 \remove Time_signature_engraver
204 raggedright = ##t''',
208 #(set-global-staff-size %(staffsize)s)''',
219 <a href="%(base)s.ly">''',
221 <img align="center" valign="center"
222 border="0" src="%(picture)s" alt="[picture of music]">''',
223 PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
231 OUTPUT: r'''{\parindent 0pt
233 \ifx\preLilyPondExample\preLilyPondExample\fi
236 \ifx\preLilyPondExample\postLilyPondExample\fi
238 PRINTFILENAME: '''\\texttt{%(filename)s}
241 VERBATIM: r'''\begin{verbatim}
242 %(verb)s\end{verbatim}
249 PRINTFILENAME: '''@file{%(filename)s}
252 VERBATIM: r'''@example
260 PREAMBLE_LY = r'''%% Generated by %(program_name)s
261 %% Options: [%(option_string)s]
263 \paper {%(paper_string)s
267 FRAGMENT_LY = r'''\score{
268 \notes%(notes_string)s{
273 texi_linewidths = { 'afourpaper': '160 \\mm',
274 'afourwide': '6.5\\in',
275 'afourlatex': '150 \\mm',
276 'smallbook': '5 \\in' ,
277 'letterpaper': '6\\in'}
279 def classic_lilypond_book_compatibility (o):
280 if o == 'singleline':
282 m = re.search ('relative\s*([-0-9])', o)
284 return 'relative=%s' % m.group (1)
285 m = re.match ('([0-9]+)pt', o)
287 return 'staffsize=%s' % m.group (1)
288 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
290 f = float (m.group (1))
291 return 'indent=%f\\%s' % (f, m.group (2))
292 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
294 f = float (m.group (1))
295 return 'linewidth=%f\\%s' % (f, m.group (2))
298 def compose_ly (code, options):
300 for i in default_ly_options.keys ():
304 m = re.search (r'''\\score''', code)
305 if not m and (not options \
306 or not NOFRAGMENT in options or FRAGMENT in options):
307 if RAGGEDRIGHT not in options:
308 options.append (RAGGEDRIGHT)
317 override.update (default_ly_options)
319 option_string = string.join (options, ',')
322 preamble_options = []
324 c = classic_lilypond_book_compatibility (i)
326 ly.warning (_ ("deprecated ly-option used: %s" % i))
327 ly.warning (_ ("compatibility mode translation: %s" \
331 if string.find (i, '=') > 0:
332 key, value = string.split (i, '=')
333 override[key] = value
336 if i not in override.keys ():
339 if key in ly_options[NOTES].keys ():
340 notes_options.append (ly_options[NOTES][key])
341 elif key in ly_options[PREAMBLE].keys ():
342 preamble_options.append (ly_options[PREAMBLE][key])
343 elif key in ly_options[PAPER].keys ():
344 paper_options.append (ly_options[PAPER][key])
345 elif key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
346 RELATIVE, VERBATIM, TEXIDOC):
347 ly.warning (_("ignoring unknown ly option: %s") % i)
350 if RELATIVE in override.keys () and override[RELATIVE]:
351 relative = string.atoi (override[RELATIVE])
357 relative_quotes += ',' * (- relative - 1)
359 relative_quotes += "'" * relative
361 program_name = __main__.program_name
362 paper_string = string.join (paper_options, '\n ') % override
363 preamble_string = string.join (preamble_options, '\n ') % override
364 notes_string = string.join (notes_options, '\n ') % vars ()
365 return (PREAMBLE_LY + body) % vars ()
368 # use lilypond-bin for latex (.lytex) books,
369 # and lilypond --preview for html, texinfo books?
371 cmd = r'latex "\nonstopmode \input %s"' % file
372 # Ugh. (La)TeX writes progress and error messages on stdout
374 cmd = '(( %s >&2 ) >&- )' % cmd
376 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
379 def find_file (name):
380 for i in include_path:
381 full = os.path.join (i, name)
382 if os.path.exists (full):
384 ly.error (_ ('file not found: %s\n' % name))
388 def verbatim_html (s):
389 return re.sub ('>', '>',
391 re.sub ('&', '&', s)))
393 def verbatim_texinfo (s):
394 return re.sub ('{', '@{',
396 re.sub ('@', '@@', s)))
398 def split_options (option_string):
399 return re.split (format_res[format]['option-sep'], option_string)
403 def replacement_text (self):
406 def is_outdated (self):
409 class Substring (Chunk):
410 def __init__ (self, source, start, end):
415 def replacement_text (self):
416 return self.source [self.start:self.end]
418 class Snippet (Chunk):
419 def __init__ (self, type, match, format):
426 def replacement_text (self):
427 return self.match.group (0)
429 def substring (self, s):
430 return self.match.group (s)
432 def filter_code (self):
436 return `self.__class__` + " type = " + self.type
438 class Include_snippet (Snippet):
439 def processed_filename (self):
440 f = self.substring ('filename')
441 return os.path.splitext (f)[0] + format2ext[format]
443 def replacement_text (self):
444 s = self.match.group (0)
445 f = self.substring ('filename')
447 return re.sub (f, self.processed_filename (), s)
449 class Lilypond_snippet (Snippet):
450 def __init__ (self, type, match, format):
451 Snippet.__init__ (self, type, match, format)
452 os = match.group ('options')
454 self.options = split_options (os)
457 if self.type == 'lilypond_file':
458 name = self.substring ('filename')
459 return '\\renameinput \"%s\"\n' % name\
460 + open (find_file (name)).read ()
462 return self.substring ('code')
467 return compose_ly (s, self.options)
472 self.hash = abs (hash (self.full_ly ()))
477 return 'lily-%d' % self.get_hash ()
481 outf = open (self.basename () + '.ly', 'w')
482 outf.write (self.full_ly ())
484 def is_outdated (self):
485 base = self.basename ()
486 if os.path.exists (base + '.ly') \
487 and os.path.exists (base + '.tex') \
489 or self.ly () == open (base + '.ly').read ()):
490 # TODO: something smart with target formats
491 # (ps, png) and m/ctimes
495 def replacement_text (self):
496 func = Lilypond_snippet.__dict__ ['output_' + self.format]
499 def output_html (self):
500 base = self.basename ()
503 str = self.output_print_filename (HTML)
504 if VERBATIM in self.options:
505 verb = verbatim_html (self.substring ('code'))
506 str += write (output[HTML][VERBATIM] % vars ())
509 single = '%(base)s.png' % vars ()
510 multiple = '%(base)s-page1.png' % vars ()
512 if os.path.exists (multiple) \
513 and (not os.path.exists (single)\
514 or (os.stat (multiple)[stat.ST_MTIME] \
515 > os.stat (single)[stat.ST_MTIME])):
516 pictures = glob.glob ('%(base)s-page*.png' % vars ())
518 str += output[HTML][BEFORE] % vars ()
519 for picture in pictures:
520 str += output[HTML][OUTPUT] % vars ()
521 str += output[HTML][AFTER] % vars ()
524 def output_latex (self):
526 base = self.basename ()
528 str = self.output_print_filename (LATEX)
529 if VERBATIM in self.options:
530 verb = self.substring ('code')
531 str += (output[LATEX][VERBATIM] % vars ())
532 str += (output[LATEX][BEFORE]
533 + (output[LATEX][OUTPUT] % vars ())
534 + output[LATEX][AFTER])
537 def output_print_filename (self,format):
539 if PRINTFILENAME in self.options:
540 base = self.basename ()
541 filename = self.substring ('filename')
542 str = output[format][PRINTFILENAME] % vars ()
545 def output_texinfo (self):
547 base = self.basename ()
548 if TEXIDOC in self.options:
549 texidoc = base + '.texidoc'
550 if os.path.exists (texidoc):
551 str += '@include %(texidoc)s\n' % vars ()
553 if VERBATIM in self.options:
554 verb = verbatim_texinfo (self.substring ('code'))
555 str += (output[TEXINFO][VERBATIM] % vars ())
557 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
558 str += ('@html\n' + self.output_html () + '\n@end html\n')
559 # need par after picture
564 snippet_type_to_class = {
565 'lilypond_file' : Lilypond_snippet,
566 'lilypond_block' : Lilypond_snippet,
567 'lilypond' : Lilypond_snippet,
568 'include' : Include_snippet,
571 def find_toplevel_snippets (s, types):
574 res[i] = ly.re.compile (snippet_res[format][i])
578 ## found = dict (map (lambda x: (x, None), types))
581 map (lambda x, f=found: f.setdefault (x, None), types)
583 # We want to search for multiple regexes, without searching
584 # the string multiple times for one regex.
585 # Hence, we use earlier results to limit the string portion
587 # Since every part of the string is traversed at most once for
588 # every type of snippet, this is linear.
594 if not found[type] or found[type][0] < index:
596 m = res[type].search (s[index:endex])
601 if snippet_type_to_class.has_key (type):
602 cl = snippet_type_to_class[type]
603 snip = cl (type, m, format)
604 start = index + m.start (0)
605 found[type] = (start, snip)
608 and (not first or found[type][0] < found[first][0]):
610 endex = found[first][0]
613 snippets.append (Substring (s, index, len (s)))
616 (start , snip) = found[first]
617 snippets.append (Substring (s, index, start))
618 snippets.append (snip)
619 index = start + len (snip.match.group (0))
623 def filter_pipe (input, cmd):
625 ly.progress (_ ("Opening filter `%s\'") % cmd)
627 stdin, stdout, stderr = os.popen3 (cmd)
629 status = stdin.close ()
633 output = stdout.read ()
634 status = stdout.close ()
635 error = stderr.read ()
639 signal = 0x0f & status
640 if status or (not output and error):
641 exit_status = status >> 8
642 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
643 ly.error (_ ("The error log is as follows:"))
644 sys.stderr.write (error)
645 sys.stderr.write (stderr.read ())
654 return filter_pipe (s, filter_cmd)
656 def process_snippets (cmd, snippets):
657 names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
659 ly.system (string.join ([cmd] + names))
661 if format == HTML or format == TEXINFO:
663 if os.path.exists (i + '.tex'):
665 ly.make_ps_images (i + '.eps', resolution=110)
667 LATEX_DOCUMENT = r'''
670 \typeout{textwidth=\the\textwidth}
671 \typeout{columnsep=\the\columnsep}
672 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
675 #need anything else besides textwidth?
676 def get_latex_textwidth (source):
677 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
678 preamble = source[:m.start (0)]
679 latex_document = LATEX_DOCUMENT % vars ()
680 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
683 m = re.search ('columns=([0-9.]*)', parameter_string)
685 columns = string.atoi (m.group (1))
688 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
690 columnsep = string.atof (m.group (1))
693 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
695 textwidth = string.atof (m.group (1))
697 textwidth = (textwidth - columnsep) / columns
708 '.texinfo' : TEXINFO,
714 #TEXINFO: '.texinfo',
719 def do_file (input_filename):
723 e = os.path.splitext (input_filename)[1]
724 if e in ext2format.keys ():
726 format = ext2format[e]
728 ly.error (_ ("cannot determine format for: %s" \
731 if not input_filename or input_filename == '-':
732 in_handle = sys.stdin
733 input_fullname = '<stdin>'
735 if os.path.exists (input_filename):
736 input_fullname = input_filename
737 elif format == LATEX:
738 # urg python interface to libkpathsea?
739 input_fullname = ly.read_pipe ('kpsewhich '
740 + input_filename)[:-1]
742 input_fullname = find_file (input_filename)
743 in_handle = open (input_fullname)
745 if input_filename == '-':
748 input_base = os.path.basename \
749 (os.path.splitext (input_filename)[0])
751 # only default to stdout when filtering
752 if output_name == '-' or (not output_name and filter_cmd):
753 output_filename = '-'
754 output_file = sys.stdout
757 output_filename = input_base + format2ext[format]
759 if not os.path.isdir (output_name):
760 os.mkdir (output_name, 0777)
761 output_filename = (output_name
763 + format2ext[format])
766 if (os.path.exists (input_filename) and
767 os.path.exists (output_filename) and
768 os.path.samefile (output_filename, input_fullname)):
769 ly.error (_("Output would overwrite input file; use --output."))
772 output_file = open (output_filename, 'w')
774 os.chdir (output_name)
776 ly.progress (_ ("Reading %s...") % input_fullname)
777 source = in_handle.read ()
784 'singleline_comment',
789 ly.progress (_ ("Dissecting..."))
790 chunks = find_toplevel_snippets (source, snippet_types)
793 global default_ly_options
795 if LINEWIDTH not in default_ly_options.keys ():
797 textwidth = get_latex_textwidth (source)
798 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
800 elif format == TEXINFO:
801 for (k, v) in texi_linewidths.items ():
802 s = chunks[0].replacement_text ()
804 default_ly_options[LINEWIDTH] = v
810 outdated = filter (lambda x: x.__class__ == Lilypond_snippet \
811 and x.is_outdated (), chunks)
812 ly.progress (_ ("Writing snippets..."))
813 map (Lilypond_snippet.write_ly, outdated)
817 ly.progress (_ ("Processing..."))
818 process_snippets (process_cmd, outdated)
820 ly.progress (_ ("All snippets are up to date..."))
823 ly.progress (_ ("Compiling %s...") % output_filename)
824 output_file.writelines ([s.replacement_text () \
828 def process_include (snippet):
829 os.chdir (original_dir)
830 name = snippet.substring ('filename')
831 ly.progress (_ ('Processing include: %s') % name)
835 map (process_include,
836 filter (lambda x: x.__class__ == Include_snippet, chunks))
839 global format, output_name
840 global filter_cmd, process_cmd, verbose_p
842 (sh, long) = ly.getopt_args (option_definitions)
844 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
845 except getopt.error, s:
846 sys.stderr.write ('\n')
847 ly.error (_ ("getopt says: `%s\'" % s))
848 sys.stderr.write ('\n')
858 elif o == '--filter' or o == '-F':
861 elif o == '--format' or o == '-f':
863 if a == 'texi-html' or a == 'texi':
865 elif o == '--help' or o == '-h':
868 elif o == '--include' or o == '-I':
869 include_path.append (os.path.join (original_dir,
871 elif o == '--output' or o == '-o':
873 elif o == '--outdir':
875 elif o == '--process' or o == '-P':
878 elif o == '--version' or o == '-v':
879 ly.identify (sys.stdout)
881 elif o == '--verbose' or o == '-V':
883 elif o == '--warranty' or o == '-w':
890 files = do_options ()
893 process_cmd += string.join ([(' -I %s' % p)
894 for p in include_path])
896 ly.identify (sys.stderr)
897 ly.setup_environment ()
901 if __name__ == '__main__':