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 texi_linewidths = { 'afourpaper': '160 \\mm',
275 'afourwide': '6.5\\in',
276 'afourlatex': '150 \\mm',
277 'smallbook': '5 \\in' ,
278 'letterpaper': '6\\in'}
280 def classic_lilypond_book_compatibility (o):
281 if o == 'singleline':
283 m = re.search ('relative\s*([-0-9])', o)
285 return 'relative=%s' % m.group (1)
286 m = re.match ('([0-9]+)pt', o)
288 return 'staffsize=%s' % m.group (1)
289 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
291 f = float (m.group (1))
292 return 'indent=%f\\%s' % (f, m.group (2))
293 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
295 f = float (m.group (1))
296 return 'linewidth=%f\\%s' % (f, m.group (2))
299 def compose_ly (code, options):
301 for i in default_ly_options.keys ():
305 m = re.search (r'''\\score''', code)
306 if not m and (not options \
307 or not NOFRAGMENT in options or FRAGMENT in options):
308 if RAGGEDRIGHT not in options:
309 options.append (RAGGEDRIGHT)
318 override.update (default_ly_options)
320 option_string = string.join (options, ',')
323 preamble_options = []
325 c = classic_lilypond_book_compatibility (i)
327 ly.warning (_ ("deprecated ly-option used: %s" % i))
328 ly.warning (_ ("compatibility mode translation: %s" \
332 if string.find (i, '=') > 0:
333 key, value = string.split (i, '=')
334 override[key] = value
337 if i not in override.keys ():
340 if key in ly_options[NOTES].keys ():
341 notes_options.append (ly_options[NOTES][key])
342 elif key in ly_options[PREAMBLE].keys ():
343 preamble_options.append (ly_options[PREAMBLE][key])
344 elif key in ly_options[PAPER].keys ():
345 paper_options.append (ly_options[PAPER][key])
346 elif key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
347 RELATIVE, VERBATIM, TEXIDOC):
348 ly.warning (_("ignoring unknown ly option: %s") % i)
351 if RELATIVE in override.keys () and override[RELATIVE]:
352 relative = string.atoi (override[RELATIVE])
358 relative_quotes += ',' * (- relative - 1)
360 relative_quotes += "'" * relative
362 program_name = __main__.program_name
363 paper_string = string.join (paper_options, '\n ') % override
364 preamble_string = string.join (preamble_options, '\n ') % override
365 notes_string = string.join (notes_options, '\n ') % vars ()
366 return (PREAMBLE_LY + body) % vars ()
369 # use lilypond-bin for latex (.lytex) books,
370 # and lilypond --preview for html, texinfo books?
372 cmd = r'latex "\nonstopmode \input %s"' % file
373 # Ugh. (La)TeX writes progress and error messages on stdout
375 cmd = '(( %s >&2 ) >&- )' % cmd
377 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
380 def find_file (name):
381 for i in include_path:
382 full = os.path.join (i, name)
383 if os.path.exists (full):
385 ly.error (_ ('file not found: %s\n' % name))
389 def verbatim_html (s):
390 return re.sub ('>', '>',
392 re.sub ('&', '&', s)))
394 def verbatim_texinfo (s):
395 return re.sub ('{', '@{',
397 re.sub ('@', '@@', s)))
399 def split_options (option_string):
400 return re.split (format_res[format]['option-sep'], option_string)
404 def replacement_text (self):
407 def is_outdated (self):
410 class Substring (Chunk):
411 def __init__ (self, source, start, end):
416 def replacement_text (self):
417 return self.source [self.start:self.end]
419 class Snippet (Chunk):
420 def __init__ (self, type, match, format):
427 def replacement_text (self):
428 return self.match.group (0)
430 def substring (self, s):
431 return self.match.group (s)
433 def filter_code (self):
437 return `self.__class__` + " type = " + self.type
439 class Include_snippet (Snippet):
440 def processed_filename (self):
441 f = self.substring ('filename')
442 return os.path.splitext (f)[0] + format2ext[format]
444 def replacement_text (self):
445 s = self.match.group (0)
446 f = self.substring ('filename')
448 return re.sub (f, self.processed_filename (), s)
450 class Lilypond_snippet (Snippet):
451 def __init__ (self, type, match, format):
452 Snippet.__init__ (self, type, match, format)
453 os = match.group ('options')
455 self.options = split_options (os)
458 if self.type == 'lilypond_file':
459 name = self.substring ('filename')
460 return '\\renameinput \"%s\"\n' % name\
461 + open (find_file (name)).read ()
463 return self.substring ('code')
468 return compose_ly (s, self.options)
473 self.hash = abs (hash (self.full_ly ()))
478 return 'lily-%d' % self.get_hash ()
482 outf = open (self.basename () + '.ly', 'w')
483 outf.write (self.full_ly ())
485 def is_outdated (self):
486 base = self.basename ()
487 if os.path.exists (base + '.ly') \
488 and os.path.exists (base + '.tex') \
490 or self.ly () == open (base + '.ly').read ()):
491 # TODO: something smart with target formats
492 # (ps, png) and m/ctimes
496 def replacement_text (self):
497 func = Lilypond_snippet.__dict__ ['output_' + self.format]
500 def get_images (self):
501 base = self.basename ()
503 single = '%(base)s.png' % vars ()
504 multiple = '%(base)s-page1.png' % vars ()
506 if os.path.exists (multiple) \
507 and (not os.path.exists (single)\
508 or (os.stat (multiple)[stat.ST_MTIME] \
509 > os.stat (single)[stat.ST_MTIME])):
510 images = glob.glob ('%(base)s-page*.png' % vars ())
513 def output_html (self):
514 base = self.basename ()
517 str = self.output_print_filename (HTML)
518 if VERBATIM in self.options:
519 verb = verbatim_html (self.substring ('code'))
520 str += write (output[HTML][VERBATIM] % vars ())
522 str += output[HTML][BEFORE] % vars ()
523 for image in self.get_images ():
524 base, ext = os.path.splitext (image)
525 str += output[HTML][OUTPUT] % vars ()
526 str += output[HTML][AFTER] % vars ()
529 def output_info (self):
530 str = output[TEXINFO][BEFORE] % vars ()
531 for image in self.get_images ():
532 base, ext = os.path.splitext (image)
533 # URG, makeinfo implicitely prepends dot to ext
534 # specifying no extension is most robust
536 str += output[TEXINFO][OUTPUT] % vars ()
537 str += output[TEXINFO][AFTER] % vars ()
540 def output_latex (self):
542 base = self.basename ()
544 str = self.output_print_filename (LATEX)
545 if VERBATIM in self.options:
546 verb = self.substring ('code')
547 str += (output[LATEX][VERBATIM] % vars ())
548 str += (output[LATEX][BEFORE]
549 + (output[LATEX][OUTPUT] % vars ())
550 + output[LATEX][AFTER])
553 def output_print_filename (self,format):
555 if PRINTFILENAME in self.options:
556 base = self.basename ()
557 filename = self.substring ('filename')
558 str = output[format][PRINTFILENAME] % vars ()
561 def output_texinfo (self):
563 base = self.basename ()
564 if TEXIDOC in self.options:
565 texidoc = base + '.texidoc'
566 if os.path.exists (texidoc):
567 str += '@include %(texidoc)s\n' % vars ()
569 if VERBATIM in self.options:
570 verb = verbatim_texinfo (self.substring ('code'))
571 str += (output[TEXINFO][VERBATIM] % vars ())
573 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
574 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
575 str += ('@html\n' + self.output_html () + '\n@end html\n')
576 # need par after image
581 snippet_type_to_class = {
582 'lilypond_file' : Lilypond_snippet,
583 'lilypond_block' : Lilypond_snippet,
584 'lilypond' : Lilypond_snippet,
585 'include' : Include_snippet,
588 def find_toplevel_snippets (s, types):
591 res[i] = ly.re.compile (snippet_res[format][i])
595 ## found = dict (map (lambda x: (x, None), types))
598 map (lambda x, f=found: f.setdefault (x, None), types)
600 # We want to search for multiple regexes, without searching
601 # the string multiple times for one regex.
602 # Hence, we use earlier results to limit the string portion
604 # Since every part of the string is traversed at most once for
605 # every type of snippet, this is linear.
611 if not found[type] or found[type][0] < index:
613 m = res[type].search (s[index:endex])
618 if snippet_type_to_class.has_key (type):
619 cl = snippet_type_to_class[type]
620 snip = cl (type, m, format)
621 start = index + m.start (0)
622 found[type] = (start, snip)
625 and (not first or found[type][0] < found[first][0]):
630 # Limiting the search space is a cute
631 # idea, but this *requires* to search
632 # for possible containing blocks
633 # first, at least long as we do not
634 # search for the start of blocks, but
635 # always/directly for the entire
636 # @block ... @end block.
638 endex = found[first][0]
641 snippets.append (Substring (s, index, len (s)))
644 (start , snip) = found[first]
645 snippets.append (Substring (s, index, start))
646 snippets.append (snip)
648 index = start + len (snip.match.group (0))
652 def filter_pipe (input, cmd):
654 ly.progress (_ ("Opening filter `%s\'") % cmd)
656 stdin, stdout, stderr = os.popen3 (cmd)
658 status = stdin.close ()
662 output = stdout.read ()
663 status = stdout.close ()
664 error = stderr.read ()
668 signal = 0x0f & status
669 if status or (not output and error):
670 exit_status = status >> 8
671 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
672 ly.error (_ ("The error log is as follows:"))
673 sys.stderr.write (error)
674 sys.stderr.write (stderr.read ())
683 return filter_pipe (s, filter_cmd)
685 def process_snippets (cmd, snippets):
686 names = filter (lambda x: x, map (Lilypond_snippet.basename, snippets))
688 ly.system (string.join ([cmd] + names))
690 if format == HTML or format == TEXINFO:
692 if os.path.exists (i + '.tex'):
694 ly.make_ps_images (i + '.eps', resolution=110)
696 LATEX_DOCUMENT = r'''
699 \typeout{textwidth=\the\textwidth}
700 \typeout{columnsep=\the\columnsep}
701 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
704 #need anything else besides textwidth?
705 def get_latex_textwidth (source):
706 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
707 preamble = source[:m.start (0)]
708 latex_document = LATEX_DOCUMENT % vars ()
709 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
712 m = re.search ('columns=([0-9.]*)', parameter_string)
714 columns = string.atoi (m.group (1))
717 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
719 columnsep = string.atof (m.group (1))
722 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
724 textwidth = string.atof (m.group (1))
726 textwidth = (textwidth - columnsep) / columns
737 '.texinfo' : TEXINFO,
743 #TEXINFO: '.texinfo',
748 def do_file (input_filename):
752 e = os.path.splitext (input_filename)[1]
753 if e in ext2format.keys ():
755 format = ext2format[e]
757 ly.error (_ ("cannot determine format for: %s" \
760 if not input_filename or input_filename == '-':
761 in_handle = sys.stdin
762 input_fullname = '<stdin>'
764 if os.path.exists (input_filename):
765 input_fullname = input_filename
766 elif format == LATEX:
767 # urg python interface to libkpathsea?
768 input_fullname = ly.read_pipe ('kpsewhich '
769 + input_filename)[:-1]
771 input_fullname = find_file (input_filename)
772 in_handle = open (input_fullname)
774 if input_filename == '-':
777 input_base = os.path.basename \
778 (os.path.splitext (input_filename)[0])
780 # only default to stdout when filtering
781 if output_name == '-' or (not output_name and filter_cmd):
782 output_filename = '-'
783 output_file = sys.stdout
786 output_filename = input_base + format2ext[format]
788 if not os.path.isdir (output_name):
789 os.mkdir (output_name, 0777)
790 output_filename = (output_name
792 + format2ext[format])
795 if (os.path.exists (input_filename) and
796 os.path.exists (output_filename) and
797 os.path.samefile (output_filename, input_fullname)):
798 ly.error (_("Output would overwrite input file; use --output."))
801 output_file = open (output_filename, 'w')
803 os.chdir (output_name)
805 ly.progress (_ ("Reading %s...") % input_fullname)
806 source = in_handle.read ()
809 # FIXME: containing blocks must be first, see find_toplevel_snippets
815 'singleline_comment',
819 ly.progress (_ ("Dissecting..."))
820 chunks = find_toplevel_snippets (source, snippet_types)
823 global default_ly_options
825 if LINEWIDTH not in default_ly_options.keys ():
827 textwidth = get_latex_textwidth (source)
828 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
830 elif format == TEXINFO:
831 for (k, v) in texi_linewidths.items ():
832 s = chunks[0].replacement_text ()
834 default_ly_options[LINEWIDTH] = v
840 outdated = filter (lambda x: x.__class__ == Lilypond_snippet \
841 and x.is_outdated (), chunks)
842 ly.progress (_ ("Writing snippets..."))
843 map (Lilypond_snippet.write_ly, outdated)
847 ly.progress (_ ("Processing..."))
848 process_snippets (process_cmd, outdated)
850 ly.progress (_ ("All snippets are up to date..."))
853 ly.progress (_ ("Compiling %s...") % output_filename)
854 output_file.writelines ([s.replacement_text () \
858 def process_include (snippet):
859 os.chdir (original_dir)
860 name = snippet.substring ('filename')
861 ly.progress (_ ('Processing include: %s') % name)
865 map (process_include,
866 filter (lambda x: x.__class__ == Include_snippet, chunks))
869 global format, output_name
870 global filter_cmd, process_cmd, verbose_p
872 (sh, long) = ly.getopt_args (option_definitions)
874 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
875 except getopt.error, s:
876 sys.stderr.write ('\n')
877 ly.error (_ ("getopt says: `%s\'" % s))
878 sys.stderr.write ('\n')
888 elif o == '--filter' or o == '-F':
891 elif o == '--format' or o == '-f':
893 if a == 'texi-html' or a == 'texi':
895 elif o == '--help' or o == '-h':
898 elif o == '--include' or o == '-I':
899 include_path.append (os.path.join (original_dir,
901 elif o == '--output' or o == '-o':
903 elif o == '--outdir':
905 elif o == '--process' or o == '-P':
908 elif o == '--version' or o == '-v':
909 ly.identify (sys.stdout)
911 elif o == '--verbose' or o == '-V':
913 elif o == '--warranty' or o == '-w':
920 files = do_options ()
923 process_cmd += string.join ([(' -I %s' % p)
924 for p in include_path])
926 ly.identify (sys.stderr)
927 ly.setup_environment ()
931 if __name__ == '__main__':