5 ly-options: intertext, quote ?
7 check latex parameters, twocolumn
15 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
18 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
20 classic lilypond-book (WIP):
21 filter-lilypond-book --process="lilypond-bin" BOOK.tely
23 options in .tely/.lytex must be converted (or grokked by me :-)
24 (([0-9][0-9])*pt) -> staffsize=\2
25 @mbinclude foo.itely -> @include foo.itely
27 relative X -> relative=X
28 singleline -> raggedright
35 ################################################################
36 # Users of python modules should include this snippet
37 # and customize variables below.
39 # We'll suffer this path init stuff as long as we don't install our
40 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
41 # it as we do with teTeX on Red Hat Linux: set some environment var
42 # (PYTHONPATH) in profile)
44 # If set, LILYPONDPREFIX must take prevalence
45 # if datadir is not set, we're doing a build and LILYPONDPREFIX
46 import getopt, os, sys
47 datadir = '@local_lilypond_datadir@'
48 if not os.path.isdir (datadir):
49 datadir = '@lilypond_datadir@'
50 if os.environ.has_key ('LILYPONDPREFIX') :
51 datadir = os.environ['LILYPONDPREFIX']
52 while datadir[-1] == os.sep:
55 sys.path.insert (0, os.path.join (datadir, 'python'))
58 #if __name__ == '__main__':
65 program_version = '@TOPLEVEL_VERSION@'
66 #program_name = 'new-book'
67 program_name = 'filter-lilypond-book'
70 original_dir = os.getcwd ()
73 # help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
74 help_summary = _ ("""Process ly snippets from lilypond-book source. Example usage:
76 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
77 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
80 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
81 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
83 option_definitions = [
84 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
85 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
86 ('', 'h', 'help', _ ("print this help")),
87 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
88 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
89 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
90 ('', 'V', 'verbose', _ ("be verbose")),
91 ('', 'v', 'version', _ ("print version information")),
92 ('', 'w', 'warranty', _ ("show warranty and copyright")),
93 ('', 'M', 'dependencies', _ ("TODO")),
94 (_ ("DIR"), '', 'outdir', _ ("DEPRECATED, use --output")),
97 include_path = [ly.abspath (os.getcwd ())]
99 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
101 # only use installed binary when we're installed too.
102 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
103 lilypond_binary = 'lilypond-bin'
109 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
110 ##filter_cmd = 'convert-ly --no-version --from=2.0.0 -'
113 #process_cmd = 'convert-ly --no-version --from=2.0.0'
115 # process_cmd = 'lilypond-bin'
116 process_cmd = 'lilypond-bin -I ../../../input/test'
117 default_ly_options = { }
125 VERBATIM = 'verbatim'
126 LINEWIDTH = 'linewidth'
128 ## lilypond-book heritage. to be cleaned
130 ################################################################
131 # Recognize special sequences in the input
134 # Warning: This uses extended regular expressions. Tread with care.
138 # (?P<name>regex) -- assign result of REGEX to NAME
139 # *? -- match non-greedily.
140 # (?m) -- multiline regex: make ^ and $ match at each line
141 # (?s) -- make the dot match all characters including newline
147 #'landscape': no_match,
148 #'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
149 #'multicols': no_match,
150 #'numcols': no_match,
152 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
153 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
154 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
155 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
156 'singleline-comment': no_match,
157 'verb': r'''(?P<code><pre>.*?</pre>)''',
158 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
162 #'def-post-re': r"\\def\\postLilyPondExample",
163 #'def-pre-re': r"\\def\\preLilyPondExample",
164 #'header': r"\n*\\documentclass\s*(\[.*?\])?",
166 #'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
167 #'numcols': r"(?P<code>\\(?P<num>one|two)column)",
168 #'usepackage-graphics': r"\usepackage\s*{graphics}",
169 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
170 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
171 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
172 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
173 'multiline-comment': no_match,
174 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
175 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
176 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
181 #'landscape': no_match,
182 #'multicols': no_match,
183 #'numcols': no_match,
184 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
185 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
186 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
187 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
188 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
189 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
190 'verb': r'''(?P<code>@code{.*?})''',
191 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
197 'option-sep' : '\s*',
198 'intertext': r',?\s*intertext=\".*?\"',
201 'intertext': r',?\s*intertext=\".*?\"',
202 'option-sep' : ',\s*',
205 'intertext': r',?\s*intertext=\".*?\"',
206 'option-sep' : ',\s*',
211 PREAMBLE = 'preamble'
216 #'xrelative': r'''\relative #(ly:make-pitch %(relative)s 0 0)''',
217 'relative': r'''\relative c%(relative_quotes)s''',
221 indent = %(indent)s''',
223 linewidth = %(linewidth)s''',
229 \remove Time_signature_engraver
233 raggedright = ##t''',
237 #(set-global-staff-size %(staffsize)s)''',
245 OUTPUT: r'''<img align="center" valign="center"
246 border="0" src="%(base)s.png" alt="[picture of music]">''',
254 OUTPUT: r'''{\parindent 0pt
256 \ifx\preLilyPondExample\preLilyPondExample\fi
259 \ifx\preLilyPondExample\postLilyPondExample\fi
261 VERBATIM: r'''\begin{verbatim}
262 %(verb)s\end{verbatim}
269 VERBATIM: r'''@example
270 %(verb)s@end example''',
276 PREAMBLE_LY = r'''%% Generated by %(program_name)s
277 %% Options: [%(option_string)s]
279 \paper {%(paper_string)s
283 FRAGMENT_LY = r'''\score{
284 \notes%(notes_string)s{
290 def compose_ly (code, option_string):
293 for i in default_ly_options.keys ():
295 vars ()[i] = default_ly_options[i]
298 options = options + split_options (option_string)
300 m = re.search (r'''\\score''', code)
301 if not m and (not options \
302 or not 'nofragment' in options \
303 or 'fragment' in options):
304 options.append ('raggedright')
315 preamble_options = []
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',
331 'relative', 'verbatim'):
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)
377 ## make index static of Snippet?
381 def __init__ (self, type, source, index, match):
389 return self.index + self.match.start (s)
392 return self.index + self.match.end (s)
394 def substring (self, s):
395 return self.source[self.start (s):self.end (s)]
399 if self.type == 'lilypond-block' or self.type == 'lilypond':
400 s = self.substring ('code')
401 elif self.type == 'lilypond-file':
402 name = self.substring ('filename')
403 s = open (find_file (name)).read ()
409 return compose_ly (s, self.match.group ('options'))
414 self.hash = abs (hash (self.ly ()))
416 print 'TYPE:: ' + self.type
417 print 'CODE:: ' + self.substring (0)
423 return 'lily-%d' % self.get_hash ()
427 if self.type == 'lilypond-block' or self.type == 'lilypond'\
428 or self.type == 'lilypond-file':
429 h = open (self.basename () + '.ly', 'w')
430 h.write (self.full_ly ())
433 def output_html (self):
434 base = self.basename ()
435 option_string = self.match.group ('options')
436 if option_string and VERBATIM in split_options (option_string)\
438 verb = verbatim_html (self.substring ('code'))
439 h.write (output[HTML][VERBATIM] % vars ())
440 h.write (output[HTML][BEFORE])
441 h.write (output[HTML][OUTPUT] % vars ())
442 h.write (output[HTML][AFTER])
444 def output_latex (self):
445 option_string = self.match.group ('options')
446 if option_string and VERBATIM in split_options (option_string)\
448 verb = self.substring ('code')
449 h.write (output[LATEX][VERBATIM] % vars ())
450 h.write (output[LATEX][BEFORE])
451 base = self.basename ()
452 h.write (output[LATEX][OUTPUT] % vars ())
453 h.write (output[LATEX][AFTER])
455 def output_texinfo (self):
456 option_string = self.match.group ('options')
457 if option_string and VERBATIM in split_options (option_string):
458 verb = verbatim_texinfo (self.substring ('code'))
459 h.write (output[TEXINFO][VERBATIM] % vars ())
462 h.write ('\n@end tex\n')
464 h.write ('\n@html\n')
466 h.write ('\n@end html\n')
468 def outdated_p (self):
469 if self.type != 'lilypond-block' and self.type != 'lilypond'\
470 and self.type != 'lilypond-file':
472 base = self.basename ()
473 if os.path.exists (base + '.ly') \
474 and os.path.exists (base + '.tex') \
476 or self.ly () == open (base + '.ly').read ()):
477 # TODO: something smart with target formats
478 # (ps, png) and m/ctimes
482 def filter_code (self):
484 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
485 #if snippet.match.group ('code'):
487 if self.type == 'lilypond' or self.type == 'lilypond-block':
488 h.write (self.source[index:self.start ('code')])
489 h.write (run_filter (self.substring ('code')))
490 h.write (self.source[self.end ('code'):self.end (0)])
492 h.write (self.source[index:self.end (0)])
495 def compile_output (self):
497 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
498 # if snippet.match.group ('code'):
500 if self.type == 'lilypond' \
501 or self.type == 'lilypond-block'\
502 or self.type == 'lilypond-file':
503 h.write (self.source[index:self.start (0)])
504 snippet_output = eval ("Snippet.output_" + format)
505 snippet_output (self)
506 elif self.type == 'include':
507 h.write (self.source[index:self.start ('filename')])
508 base = os.path.splitext (self.substring ('filename'))[0]
509 h.write (base + format2ext[format])
510 h.write (self.source[self.end ('filename'):self.end (0)])
512 h.write (self.source[index:self.end (0)])
515 def find_toplevel_snippets (s, types):
518 res[i] = ly.re.compile (snippet_res[format][i])
527 matches[i] = res[i].search (s[index:index+endex])
529 start = matches[i].start (0)
533 or start < matches[first].start (0):
537 snippets.append (Snippet (first, s, index, matches[first]))
538 index = index + matches[first].end (0)
542 def filter_pipe (input, cmd):
544 ly.progress (_ ("Opening filter `%s\'") % cmd)
546 stdin, stdout, stderr = os.popen3 (cmd)
548 status = stdin.close ()
552 output = stdout.read ()
553 status = stdout.close ()
554 error = stderr.read ()
558 signal = 0x0f & status
559 if status or (not output and error):
560 exit_status = status >> 8
561 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
562 ly.error (_ ("The error log is as follows:"))
563 sys.stderr.write (error)
564 sys.stderr.write (stderr.read ())
573 return filter_pipe (s, filter_cmd)
575 def process_snippets (cmd, snippets):
576 names = filter (lambda x:x, map (Snippet.basename, snippets))
578 ly.system (string.join ([cmd] + names))
580 if format == HTML or format == TEXINFO:
583 ly.make_ps_images (i + '.eps', resolution=110)
585 LATEX_DOCUMENT = r'''
588 \typeout{textwidth=\the\textwidth}
589 \typeout{columnsep=\the\columnsep}
590 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
593 #need anything else besides textwidth?
594 def get_latex_textwidth (source):
595 m = re.search (r'''(?P<preabmle>\\begin\s*{document})''', source)
596 preamble = source[:m.start (0)]
597 latex_document = LATEX_DOCUMENT % vars ()
598 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
601 m = re.search ('columns=([0-9.]*)', parameter_string)
603 columns = string.atoi (m.group (1))
606 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
608 columnsep = string.atof (m.group (1))
611 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
613 textwidth = string.atof (m.group (1))
615 textwidth = (textwidth - columnsep) / columns
627 '.texinfo' : TEXINFO,
633 #TEXINFO: '.texinfo',
638 def do_file (input_filename):
640 print 'do_file: ' + input_filename
644 e = os.path.splitext (input_filename)[1]
645 if e in ext2format.keys ():
647 format = ext2format[e]
649 ly.error (_ ("cannot determine format for: %s" \
652 ly.progress (_ ("Reading %s...") % input_filename)
654 if not input_filename or input_filename == '-':
657 h = open (input_filename)
661 ly.progress (_ ("Dissecting..."))
662 snippets = find_toplevel_snippets (source, snippet_res[format].keys ())
665 if output_name == '-' or not output_name:
667 output_filename = '-'
669 if not os.path.isdir (output_name):
670 os.mkdir (output_name, 0777)
671 if input_filename == '-':
674 input_base = os.path.splitext (input_filename)[0]
675 output_filename = output_name + '/' + input_base \
677 h = open (output_filename, 'w')
678 os.chdir (output_name)
680 global default_ly_options
682 if format == LATEX and LINEWIDTH not in default_ly_options.keys ():
683 textwidth = get_latex_textwidth (source)
684 default_ly_options[LINEWIDTH] = '''%.0f\pt''' % textwidth
689 map (Snippet.filter_code, snippets)
690 h.write (source[index:])
692 outdated = filter (lambda x:x,
693 map (Snippet.outdated_p, snippets))
694 ly.progress (_ ("Writing snippets..."))
695 map (Snippet.write_ly, snippets)
699 ly.progress (_ ("Processing..."))
700 process_snippets (process_cmd, outdated)
702 ly.progress (_ ("All snippets are up to date..."))
705 ly.progress (_ ("Compiling %s...") % output_filename)
707 map (Snippet.compile_output, snippets)
708 h.write (source[index:])
714 def process_include (snippet):
715 print 'type: ' + snippet.type
716 os.chdir (original_dir)
717 name = snippet.substring ('filename')
718 ly.progress (_ ('Processing include: %s') % name)
722 map (process_include, filter (lambda x: x.type == 'include', snippets))
725 global format, output_name
726 global filter_cmd, process_cmd, verbose_p
728 (sh, long) = ly.getopt_args (option_definitions)
730 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
731 except getopt.error, s:
732 sys.stderr.write ('\n')
733 ly.error (_ ("getopt says: `%s\'" % s))
734 sys.stderr.write ('\n')
744 elif o == '--version' or o == '-v':
745 ly.identify (sys.stdout)
747 elif o == '--verbose' or o == '-V':
749 elif o == '--filter' or o == '-F':
752 elif o == '--format' or o == '-f':
754 if a == 'texi-html' or a == 'texi':
756 elif o == '--help' or o == '-h':
759 elif o == '--include' or o == '-I':
760 include_path.append (os.path.join (original_dir,
762 elif o == '--output' or o == '-o':
764 elif o == '--outdir':
766 elif o == '--process' or o == '-P':
769 elif o == '--warranty' or o == '-w':
776 files = do_options ()
777 ly.identify (sys.stderr)
778 ly.setup_environment ()
782 if __name__ == '__main__':