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\s+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="%(image)s" alt="[image 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}
250 @image{%(base)s,,,[image of music],%(ext)s}
252 PRINTFILENAME: '''@file{%(filename)s}
255 VERBATIM: r'''@example
261 PREAMBLE_LY = r'''%% Generated by %(program_name)s
262 %% Options: [%(option_string)s]
264 \paper {%(paper_string)s
268 FRAGMENT_LY = r'''\score{
269 \notes%(notes_string)s{
274 texinfo_linewidths = {
275 '@afourpaper': '160 \\mm',
276 '@afourwide': '6.5 \\in',
277 '@afourlatex': '150 \\mm',
278 '@smallbook': '5 \\in' ,
279 '@letterpaper': '6\\in',
282 def classic_lilypond_book_compatibility (o):
283 if o == 'singleline':
285 m = re.search ('relative\s*([-0-9])', o)
287 return 'relative=%s' % m.group (1)
288 m = re.match ('([0-9]+)pt', o)
290 return 'staffsize=%s' % m.group (1)
291 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
293 f = float (m.group (1))
294 return 'indent=%f\\%s' % (f, m.group (2))
295 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
297 f = float (m.group (1))
298 return 'linewidth=%f\\%s' % (f, m.group (2))
301 def compose_ly (code, options):
303 for i in default_ly_options.keys ():
307 m = re.search (r'''\\score''', code)
308 if not m and (not options \
309 or not NOFRAGMENT in options or FRAGMENT in options):
310 if RAGGEDRIGHT not in options:
311 options.append (RAGGEDRIGHT)
320 override.update (default_ly_options)
322 option_string = string.join (options, ',')
325 preamble_options = []
327 c = classic_lilypond_book_compatibility (i)
329 ly.warning (_ ("deprecated ly-option used: %s" % i))
330 ly.warning (_ ("compatibility mode translation: %s" \
334 if string.find (i, '=') > 0:
335 key, value = string.split (i, '=')
336 override[key] = value
339 if i not in override.keys ():
342 if key in ly_options[NOTES].keys ():
343 notes_options.append (ly_options[NOTES][key])
344 elif key in ly_options[PREAMBLE].keys ():
345 preamble_options.append (ly_options[PREAMBLE][key])
346 elif key in ly_options[PAPER].keys ():
347 paper_options.append (ly_options[PAPER][key])
348 elif key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
349 RELATIVE, VERBATIM, TEXIDOC):
350 ly.warning (_("ignoring unknown ly option: %s") % i)
353 if RELATIVE in override.keys () and override[RELATIVE]:
354 relative = string.atoi (override[RELATIVE])
360 relative_quotes += ',' * (- relative - 1)
362 relative_quotes += "'" * relative
364 program_name = __main__.program_name
365 paper_string = string.join (paper_options, '\n ') % override
366 preamble_string = string.join (preamble_options, '\n ') % override
367 notes_string = string.join (notes_options, '\n ') % vars ()
368 return (PREAMBLE_LY + body) % vars ()
371 # use lilypond-bin for latex (.lytex) books,
372 # and lilypond --preview for html, texinfo books?
374 cmd = r'latex "\nonstopmode \input %s"' % file
375 # Ugh. (La)TeX writes progress and error messages on stdout
377 cmd = '(( %s >&2 ) >&- )' % cmd
379 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
382 def find_file (name):
383 for i in include_path:
384 full = os.path.join (i, name)
385 if os.path.exists (full):
387 ly.error (_ ('file not found: %s\n' % name))
391 def verbatim_html (s):
392 return re.sub ('>', '>',
394 re.sub ('&', '&', s)))
396 def verbatim_texinfo (s):
397 return re.sub ('{', '@{',
399 re.sub ('@', '@@', s)))
401 def split_options (option_string):
402 return re.split (format_res[format]['option-sep'], option_string)
406 def replacement_text (self):
409 def is_outdated (self):
412 class Substring (Chunk):
413 def __init__ (self, source, start, end):
418 def replacement_text (self):
419 return self.source [self.start:self.end]
421 class Snippet (Chunk):
422 def __init__ (self, type, match, format):
429 def replacement_text (self):
430 return self.match.group (0)
432 def substring (self, s):
433 return self.match.group (s)
435 def filter_code (self):
439 return `self.__class__` + " type = " + self.type
441 class Include_snippet (Snippet):
442 def processed_filename (self):
443 f = self.substring ('filename')
444 return os.path.splitext (f)[0] + format2ext[format]
446 def replacement_text (self):
447 s = self.match.group (0)
448 f = self.substring ('filename')
450 return re.sub (f, self.processed_filename (), s)
452 class Lilypond_snippet (Snippet):
453 def __init__ (self, type, match, format):
454 Snippet.__init__ (self, type, match, format)
455 os = match.group ('options')
457 self.options = split_options (os)
460 if self.type == 'lilypond_file':
461 name = self.substring ('filename')
462 return '\\renameinput \"%s\"\n' % name\
463 + open (find_file (name)).read ()
465 return self.substring ('code')
470 return compose_ly (s, self.options)
475 self.hash = abs (hash (self.full_ly ()))
480 return 'lily-%d' % self.get_hash ()
484 outf = open (self.basename () + '.ly', 'w')
485 outf.write (self.full_ly ())
487 def is_outdated (self):
488 base = self.basename ()
489 ## FIXME: adding PNG to is_outdated test fixes
490 ## interrupted (web) builds.
491 ## should only do this if PNG is actually target
492 if os.path.exists (base + '.ly') \
493 and os.path.exists (base + '.tex') \
494 and os.path.exists (base + '.png') \
496 or self.ly () == open (base + '.ly').read ()):
497 # TODO: something smart with target formats
498 # (ps, png) and m/ctimes
502 def replacement_text (self):
503 func = Lilypond_snippet.__dict__ ['output_' + self.format]
506 def get_images (self):
507 base = self.basename ()
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 images = glob.glob ('%(base)s-page*.png' % vars ())
519 def output_html (self):
520 base = self.basename ()
523 str = self.output_print_filename (HTML)
524 if VERBATIM in self.options:
525 verb = verbatim_html (self.substring ('code'))
526 str += write (output[HTML][VERBATIM] % vars ())
528 str += output[HTML][BEFORE] % vars ()
529 for image in self.get_images ():
530 base, ext = os.path.splitext (image)
531 str += output[HTML][OUTPUT] % vars ()
532 str += output[HTML][AFTER] % vars ()
535 def output_info (self):
536 str = output[TEXINFO][BEFORE] % vars ()
537 for image in self.get_images ():
538 base, ext = os.path.splitext (image)
539 # URG, makeinfo implicitely prepends dot to ext
540 # specifying no extension is most robust
542 str += output[TEXINFO][OUTPUT] % vars ()
543 str += output[TEXINFO][AFTER] % vars ()
546 def output_latex (self):
548 base = self.basename ()
550 str = self.output_print_filename (LATEX)
551 if VERBATIM in self.options:
552 verb = self.substring ('code')
553 str += (output[LATEX][VERBATIM] % vars ())
554 str += (output[LATEX][BEFORE]
555 + (output[LATEX][OUTPUT] % vars ())
556 + output[LATEX][AFTER])
559 def output_print_filename (self,format):
561 if PRINTFILENAME in self.options:
562 base = self.basename ()
563 filename = self.substring ('filename')
564 str = output[format][PRINTFILENAME] % vars ()
567 def output_texinfo (self):
569 base = self.basename ()
570 if TEXIDOC in self.options:
571 texidoc = base + '.texidoc'
572 if os.path.exists (texidoc):
573 str += '@include %(texidoc)s\n' % vars ()
575 if VERBATIM in self.options:
576 verb = verbatim_texinfo (self.substring ('code'))
577 str += (output[TEXINFO][VERBATIM] % vars ())
579 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
580 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
581 str += ('@html\n' + self.output_html () + '\n@end html\n')
582 # need par after image
587 snippet_type_to_class = {
588 'lilypond_file' : Lilypond_snippet,
589 'lilypond_block' : Lilypond_snippet,
590 'lilypond' : Lilypond_snippet,
591 'include' : Include_snippet,
594 def find_toplevel_snippets (s, types):
597 res[i] = ly.re.compile (snippet_res[format][i])
601 ## found = dict (map (lambda x: (x, None), types))
604 map (lambda x, f=found: f.setdefault (x, None), types)
606 # We want to search for multiple regexes, without searching
607 # the string multiple times for one regex.
608 # Hence, we use earlier results to limit the string portion
610 # Since every part of the string is traversed at most once for
611 # every type of snippet, this is linear.
617 if not found[type] or found[type][0] < index:
619 m = res[type].search (s[index:endex])
624 if snippet_type_to_class.has_key (type):
625 cl = snippet_type_to_class[type]
626 snip = cl (type, m, format)
627 start = index + m.start (0)
628 found[type] = (start, snip)
631 and (not first or found[type][0] < found[first][0]):
636 # Limiting the search space is a cute
637 # idea, but this *requires* to search
638 # for possible containing blocks
639 # first, at least long as we do not
640 # search for the start of blocks, but
641 # always/directly for the entire
642 # @block ... @end block.
644 endex = found[first][0]
647 snippets.append (Substring (s, index, len (s)))
650 (start , snip) = found[first]
651 snippets.append (Substring (s, index, start))
652 snippets.append (snip)
654 index = start + len (snip.match.group (0))
658 def filter_pipe (input, cmd):
660 ly.progress (_ ("Opening filter `%s\'") % cmd)
662 stdin, stdout, stderr = os.popen3 (cmd)
664 status = stdin.close ()
668 output = stdout.read ()
669 status = stdout.close ()
670 error = stderr.read ()
674 signal = 0x0f & status
675 if status or (not output and error):
676 exit_status = status >> 8
677 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
678 ly.error (_ ("The error log is as follows:"))
679 sys.stderr.write (error)
680 sys.stderr.write (stderr.read ())
689 return filter_pipe (s, filter_cmd)
691 def process_snippets (cmd, snippets):
692 names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
694 ly.system (string.join ([cmd] + names))
696 if format == HTML or format == TEXINFO:
698 if os.path.exists (i + '.tex'):
700 ly.make_ps_images (i + '.eps', resolution=110)
702 LATEX_DOCUMENT = r'''
705 \typeout{textwidth=\the\textwidth}
706 \typeout{columnsep=\the\columnsep}
707 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
710 #need anything else besides textwidth?
711 def get_latex_textwidth (source):
712 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
713 preamble = source[:m.start (0)]
714 latex_document = LATEX_DOCUMENT % vars ()
715 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
718 m = re.search ('columns=([0-9.]*)', parameter_string)
720 columns = string.atoi (m.group (1))
723 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
725 columnsep = string.atof (m.group (1))
728 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
730 textwidth = string.atof (m.group (1))
732 textwidth = (textwidth - columnsep) / columns
743 '.texinfo' : TEXINFO,
749 #TEXINFO: '.texinfo',
754 def do_file (input_filename):
758 e = os.path.splitext (input_filename)[1]
759 if e in ext2format.keys ():
761 format = ext2format[e]
763 ly.error (_ ("cannot determine format for: %s" \
766 if not input_filename or input_filename == '-':
767 in_handle = sys.stdin
768 input_fullname = '<stdin>'
770 if os.path.exists (input_filename):
771 input_fullname = input_filename
772 elif format == LATEX:
773 # urg python interface to libkpathsea?
774 input_fullname = ly.read_pipe ('kpsewhich '
775 + input_filename)[:-1]
777 input_fullname = find_file (input_filename)
778 in_handle = open (input_fullname)
780 if input_filename == '-':
783 input_base = os.path.basename \
784 (os.path.splitext (input_filename)[0])
786 # only default to stdout when filtering
787 if output_name == '-' or (not output_name and filter_cmd):
788 output_filename = '-'
789 output_file = sys.stdout
792 output_filename = input_base + format2ext[format]
794 if not os.path.isdir (output_name):
795 os.mkdir (output_name, 0777)
796 output_filename = (output_name
798 + format2ext[format])
801 if (os.path.exists (input_filename) and
802 os.path.exists (output_filename) and
803 os.path.samefile (output_filename, input_fullname)):
804 ly.error (_("Output would overwrite input file; use --output."))
807 output_file = open (output_filename, 'w')
809 os.chdir (output_name)
811 ly.progress (_ ("Reading %s...") % input_fullname)
812 source = in_handle.read ()
815 # FIXME: containing blocks must be first, see find_toplevel_snippets
821 'singleline_comment',
825 ly.progress (_ ("Dissecting..."))
826 chunks = find_toplevel_snippets (source, snippet_types)
829 global default_ly_options
831 if LINEWIDTH not in default_ly_options.keys ():
833 textwidth = get_latex_textwidth (source)
834 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
836 elif format == TEXINFO:
837 for (k, v) in texinfo_linewidths.items ():
838 # FIXME: @paper is usually not in chunk #0:
839 # \input texinfo @c -*-texinfo-*-
840 # bluntly search first K of source
841 # s = chunks[0].replacement_text ()
842 if re.search (k, source[:1024]):
843 default_ly_options[LINEWIDTH] = v
849 outdated = filter (lambda x: x.__class__ == Lilypond_snippet \
850 and x.is_outdated (), chunks)
851 ly.progress (_ ("Writing snippets..."))
852 map (Lilypond_snippet.write_ly, outdated)
856 ly.progress (_ ("Processing..."))
857 process_snippets (process_cmd, outdated)
859 ly.progress (_ ("All snippets are up to date..."))
862 ly.progress (_ ("Compiling %s...") % output_filename)
863 output_file.writelines ([s.replacement_text () \
867 def process_include (snippet):
868 os.chdir (original_dir)
869 name = snippet.substring ('filename')
870 ly.progress (_ ('Processing include: %s') % name)
874 map (process_include,
875 filter (lambda x: x.__class__ == Include_snippet, chunks))
878 global format, output_name
879 global filter_cmd, process_cmd, verbose_p
881 (sh, long) = ly.getopt_args (option_definitions)
883 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
884 except getopt.error, s:
885 sys.stderr.write ('\n')
886 ly.error (_ ("getopt says: `%s\'" % s))
887 sys.stderr.write ('\n')
897 elif o == '--filter' or o == '-F':
900 elif o == '--format' or o == '-f':
902 if a == 'texi-html' or a == 'texi':
904 elif o == '--help' or o == '-h':
907 elif o == '--include' or o == '-I':
908 include_path.append (os.path.join (original_dir,
910 elif o == '--output' or o == '-o':
912 elif o == '--outdir':
914 elif o == '--process' or o == '-P':
917 elif o == '--version' or o == '-v':
918 ly.identify (sys.stdout)
920 elif o == '--verbose' or o == '-V':
922 elif o == '--warranty' or o == '-w':
929 files = do_options ()
932 process_cmd += string.join ([(' -I %s' % p)
933 for p in include_path])
935 ly.identify (sys.stderr)
936 ly.setup_environment ()
940 if __name__ == '__main__':