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])
353 relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative+4]
354 program_name = __main__.program_name
355 paper_string = string.join (paper_options, '\n ') % override
356 preamble_string = string.join (preamble_options, '\n ') % override
357 notes_string = string.join (notes_options, '\n ') % vars ()
358 return (PREAMBLE_LY + body) % vars ()
361 # use lilypond-bin for latex (.lytex) books,
362 # and lilypond --preview for html, texinfo books?
364 cmd = r'latex "\nonstopmode \input %s"' % file
365 # Ugh. (La)TeX writes progress and error messages on stdout
367 cmd = '(( %s >&2 ) >&- )' % cmd
369 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
372 def find_file (name):
373 for i in include_path:
374 full = os.path.join (i, name)
375 if os.path.exists (full):
377 ly.error (_ ('file not found: %s\n' % name))
381 def verbatim_html (s):
382 return re.sub ('>', '>',
384 re.sub ('&', '&', s)))
386 def verbatim_texinfo (s):
387 return re.sub ('{', '@{',
389 re.sub ('@', '@@', s)))
391 def split_options (option_string):
392 return re.split (format_res[format]['option-sep'], option_string)
396 def replacement_text (self):
399 def is_outdated (self):
402 class Substring (Chunk):
403 def __init__ (self, source, start, end):
408 def replacement_text (self):
409 return self.source [self.start:self.end]
411 class Snippet (Chunk):
412 def __init__ (self, type, match, format):
419 def replacement_text (self):
420 return self.match.group (0)
422 def substring (self, s):
423 return self.match.group (s)
425 def filter_code (self):
429 return `self.__class__` + " type = " + self.type
431 class Include_snippet (Snippet):
432 def processed_filename (self):
433 f = self.substring ('filename')
434 return os.path.splitext (f)[0] + format2ext[format]
436 def replacement_text (self):
437 s = self.match.group (0)
438 f = self.substring ('filename')
440 return re.sub (f, self.processed_filename (), s)
442 class Lilypond_snippet (Snippet):
443 def __init__ (self, type, match, format):
444 Snippet.__init__ (self, type, match, format)
445 os = match.group ('options')
447 self.options = split_options (os)
450 if self.type == 'lilypond_file':
451 name = self.substring ('filename')
452 return '\\renameinput \"%s\"\n' % name\
453 + open (find_file (name)).read ()
455 return self.substring ('code')
460 return compose_ly (s, self.options)
465 self.hash = abs (hash (self.full_ly ()))
470 return 'lily-%d' % self.get_hash ()
474 outf = open (self.basename () + '.ly', 'w')
475 outf.write (self.full_ly ())
477 def is_outdated (self):
478 base = self.basename ()
479 if os.path.exists (base + '.ly') \
480 and os.path.exists (base + '.tex') \
482 or self.ly () == open (base + '.ly').read ()):
483 # TODO: something smart with target formats
484 # (ps, png) and m/ctimes
488 def replacement_text (self):
489 func = Lilypond_snippet.__dict__ ['output_' + self.format]
492 def output_html (self):
493 base = self.basename ()
496 str = self.output_print_filename (HTML)
497 if VERBATIM in self.options:
498 verb = verbatim_html (self.substring ('code'))
499 str += write (output[HTML][VERBATIM] % vars ())
502 single = '%(base)s.png' % vars ()
503 multiple = '%(base)s-page1.png' % vars ()
505 if os.path.exists (multiple) \
506 and (not os.path.exists (single)\
507 or (os.stat (multiple)[stat.ST_MTIME] \
508 > os.stat (single)[stat.ST_MTIME])):
509 pictures = glob.glob ('%(base)s-page*.png' % vars ())
511 str += output[HTML][BEFORE] % vars ()
512 for picture in pictures:
513 str += output[HTML][OUTPUT] % vars ()
514 str += output[HTML][AFTER] % vars ()
517 def output_latex (self):
519 base = self.basename ()
521 str = self.output_print_filename (LATEX)
522 if VERBATIM in self.options:
523 verb = self.substring ('code')
524 str += (output[LATEX][VERBATIM] % vars ())
525 str += (output[LATEX][BEFORE]
526 + (output[LATEX][OUTPUT] % vars ())
527 + output[LATEX][AFTER])
530 def output_print_filename (self,format):
532 if PRINTFILENAME in self.options:
533 base = self.basename ()
534 filename = self.substring ('filename')
535 str = output[format][PRINTFILENAME] % vars ()
538 def output_texinfo (self):
540 base = self.basename ()
541 if TEXIDOC in self.options:
542 texidoc = base + '.texidoc'
543 if os.path.exists (texidoc):
544 str += '@include %(texidoc)s\n' % vars ()
546 if VERBATIM in self.options:
547 verb = verbatim_texinfo (self.substring ('code'))
548 str += (output[TEXINFO][VERBATIM] % vars ())
550 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
551 str += ('@html\n' + self.output_html () + '\n@end html\n')
552 # need par after picture
557 snippet_type_to_class = {
558 'lilypond_file' : Lilypond_snippet,
559 'lilypond_block' : Lilypond_snippet,
560 'lilypond' : Lilypond_snippet,
561 'include' : Include_snippet,
564 def find_toplevel_snippets (s, types):
567 res[i] = ly.re.compile (snippet_res[format][i])
571 ## found = dict (map (lambda x: (x, None), types))
574 map (lambda x, f=found: f.setdefault (x, None), types)
576 # We want to search for multiple regexes, without searching
577 # the string multiple times for one regex.
578 # Hence, we use earlier results to limit the string portion
580 # Since every part of the string is traversed at most once for
581 # every type of snippet, this is linear.
587 if not found[type] or found[type][0] < index:
589 m = res[type].search (s[index:endex])
594 if snippet_type_to_class.has_key (type):
595 cl = snippet_type_to_class[type]
596 snip = cl (type, m, format)
597 start = index + m.start (0)
598 found[type] = (start, snip)
601 and (not first or found[type][0] < found[first][0]):
603 endex = found[first][0]
606 snippets.append (Substring (s, index, len (s)))
609 (start , snip) = found[first]
610 snippets.append (Substring (s, index, start))
611 snippets.append (snip)
612 index = start + len (snip.match.group (0))
616 def filter_pipe (input, cmd):
618 ly.progress (_ ("Opening filter `%s\'") % cmd)
620 stdin, stdout, stderr = os.popen3 (cmd)
622 status = stdin.close ()
626 output = stdout.read ()
627 status = stdout.close ()
628 error = stderr.read ()
632 signal = 0x0f & status
633 if status or (not output and error):
634 exit_status = status >> 8
635 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
636 ly.error (_ ("The error log is as follows:"))
637 sys.stderr.write (error)
638 sys.stderr.write (stderr.read ())
647 return filter_pipe (s, filter_cmd)
649 def process_snippets (cmd, snippets):
650 names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
652 ly.system (string.join ([cmd] + names))
654 if format == HTML or format == TEXINFO:
656 if os.path.exists (i + '.tex'):
658 ly.make_ps_images (i + '.eps', resolution=110)
660 LATEX_DOCUMENT = r'''
663 \typeout{textwidth=\the\textwidth}
664 \typeout{columnsep=\the\columnsep}
665 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
668 #need anything else besides textwidth?
669 def get_latex_textwidth (source):
670 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
671 preamble = source[:m.start (0)]
672 latex_document = LATEX_DOCUMENT % vars ()
673 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
676 m = re.search ('columns=([0-9.]*)', parameter_string)
678 columns = string.atoi (m.group (1))
681 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
683 columnsep = string.atof (m.group (1))
686 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
688 textwidth = string.atof (m.group (1))
690 textwidth = (textwidth - columnsep) / columns
701 '.texinfo' : TEXINFO,
707 #TEXINFO: '.texinfo',
712 def do_file (input_filename):
716 e = os.path.splitext (input_filename)[1]
717 if e in ext2format.keys ():
719 format = ext2format[e]
721 ly.error (_ ("cannot determine format for: %s" \
724 if not input_filename or input_filename == '-':
725 in_handle = sys.stdin
726 input_fullname = '<stdin>'
728 if os.path.exists (input_filename):
729 input_fullname = input_filename
730 elif format == LATEX:
731 # urg python interface to libkpathsea?
732 input_fullname = ly.read_pipe ('kpsewhich '
733 + input_filename)[:-1]
735 input_fullname = find_file (input_filename)
736 in_handle = open (input_fullname)
738 if input_filename == '-':
741 input_base = os.path.basename \
742 (os.path.splitext (input_filename)[0])
744 # only default to stdout when filtering
745 if output_name == '-' or (not output_name and filter_cmd):
746 output_filename = '-'
747 output_file = sys.stdout
750 output_filename = input_base + format2ext[format]
752 if not os.path.isdir (output_name):
753 os.mkdir (output_name, 0777)
754 output_filename = (output_name
756 + format2ext[format])
757 output_file = open (output_filename, 'w')
759 os.chdir (output_name)
761 ly.progress (_ ("Reading %s...") % input_fullname)
762 source = in_handle.read ()
769 'singleline_comment',
774 ly.progress (_ ("Dissecting..."))
775 chunks = find_toplevel_snippets (source, snippet_types)
778 global default_ly_options
780 if LINEWIDTH not in default_ly_options.keys ():
782 textwidth = get_latex_textwidth (source)
783 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
785 elif format == TEXINFO:
786 for (k, v) in texi_linewidths.items ():
787 s = chunks[0].replacement_text ()
789 default_ly_options[LINEWIDTH] = v
795 outdated = filter (lambda x: x.__class__ == Lilypond_snippet \
796 and x.is_outdated (), chunks)
797 ly.progress (_ ("Writing snippets..."))
798 map (Lilypond_snippet.write_ly, outdated)
802 ly.progress (_ ("Processing..."))
803 process_snippets (process_cmd, outdated)
805 ly.progress (_ ("All snippets are up to date..."))
808 ly.progress (_ ("Compiling %s...") % output_filename)
809 output_file.writelines ([s.replacement_text () \
813 def process_include (snippet):
814 os.chdir (original_dir)
815 name = snippet.substring ('filename')
816 ly.progress (_ ('Processing include: %s') % name)
820 map (process_include,
821 filter (lambda x: x.__class__ == Include_snippet, chunks))
824 global format, output_name
825 global filter_cmd, process_cmd, verbose_p
827 (sh, long) = ly.getopt_args (option_definitions)
829 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
830 except getopt.error, s:
831 sys.stderr.write ('\n')
832 ly.error (_ ("getopt says: `%s\'" % s))
833 sys.stderr.write ('\n')
843 elif o == '--filter' or o == '-F':
846 elif o == '--format' or o == '-f':
848 if a == 'texi-html' or a == 'texi':
850 elif o == '--help' or o == '-h':
853 elif o == '--include' or o == '-I':
854 include_path.append (os.path.join (original_dir,
856 elif o == '--output' or o == '-o':
858 elif o == '--outdir':
860 elif o == '--process' or o == '-P':
863 elif o == '--version' or o == '-v':
864 ly.identify (sys.stdout)
866 elif o == '--verbose' or o == '-V':
868 elif o == '--warranty' or o == '-w':
875 files = do_options ()
878 process_cmd += string.join ([(' -I %s' % p)
879 for p in include_path])
881 ly.identify (sys.stderr)
882 ly.setup_environment ()
886 if __name__ == '__main__':