13 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
16 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
18 minimal classic lilypond-book (WIP):
19 filter-lilypond-book --process="lilypond-bin" BOOK.tely
21 (([0-9][0-9])*pt) -> staffsize=\2
28 ################################################################
29 # Users of python modules should include this snippet
30 # and customize variables below.
32 # We'll suffer this path init stuff as long as we don't install our
33 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
34 # it as we do with teTeX on Red Hat Linux: set some environment var
35 # (PYTHONPATH) in profile)
37 # If set, LILYPONDPREFIX must take prevalence
38 # if datadir is not set, we're doing a build and LILYPONDPREFIX
39 import getopt, os, sys
40 datadir = '@local_lilypond_datadir@'
41 if not os.path.isdir (datadir):
42 datadir = '@lilypond_datadir@'
43 if os.environ.has_key ('LILYPONDPREFIX') :
44 datadir = os.environ['LILYPONDPREFIX']
45 while datadir[-1] == os.sep:
48 sys.path.insert (0, os.path.join (datadir, 'python'))
51 #if __name__ == '__main__':
58 program_version = '@TOPLEVEL_VERSION@'
59 #program_name = 'new-book'
60 program_name = 'filter-lilypond-book'
63 original_dir = os.getcwd ()
66 # help_summary = _ ("Process LilyPond snippets in hybrid html, LaTeX or texinfo document")
67 help_summary = _ ("""Process ly snippets from lilypond-book source. Example usage:
69 filter-lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
70 filter-lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
73 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
74 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
76 option_definitions = [
77 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
78 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
79 ('', 'h', 'help', _ ("print this help")),
80 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
81 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
82 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
83 ('', 'V', 'verbose', _ ("be verbose")),
84 ('', 'v', 'version', _ ("print version information")),
85 ('', 'w', 'warranty', _ ("show warranty and copyright")),
86 ('', 'M', 'dependencies', _ ("TODO")),
87 (_ ("DIR"), '', 'outdir', _ ("DEPRECATED, use --output")),
90 include_path = [ly.abspath (os.getcwd ())]
92 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
94 # only use installed binary when we're installed too.
95 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
96 lilypond_binary = 'lilypond-bin'
102 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
103 ##filter_cmd = 'convert-ly --no-version --from=2.0.0 -'
105 #process_cmd = 'convert-ly --no-version --from=2.0.0'
107 process_cmd = 'lilypond-bin'
108 default_ly_options = { }
116 VERBATIM = 'verbatim'
117 LINEWIDTH = 'linewidth'
119 ## lilypond-book heritage. to be cleaned
121 ################################################################
122 # Recognize special sequences in the input
125 # Warning: This uses extended regular expressions. Tread with care.
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
139 'landscape': no_match,
140 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
141 'verb': r'''(?P<code><pre>.*?</pre>)''',
142 'lilypond-file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
143 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
144 'lilypond-block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
145 'option-sep' : '\s*',
146 'intertext': r',?\s*intertext=\".*?\"',
147 'multiline-comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
148 'singleline-comment': no_match,
150 'multicols': no_match,
151 'ly2dvi': r'(?m)(?P<match><ly2dvifile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</ly2dvifile>)',
155 'junkmeinput': r'(?m)^[^%\n]*?(?P<match>\\mbinput{?([^}\t \n}]*))',
156 'junkmeinclude': r'(?m)^[^%\n]*?(?P<match>\\mbinclude{(?P<filename>[^}]+)})',
157 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
158 'option-sep' : ',\s*',
159 'header': r"\n*\\documentclass\s*(\[.*?\])?",
160 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
161 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
162 'lilypond-file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
163 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
164 'lilypond-block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
165 'def-post-re': r"\\def\\postLilyPondExample",
166 'def-pre-re': r"\\def\\preLilyPondExample",
167 'usepackage-graphics': r"\usepackage\s*{graphics}",
168 'intertext': r',?\s*intertext=\".*?\"',
169 'multiline-comment': no_match,
170 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
171 'numcols': r"(?P<code>\\(?P<num>one|two)column)",
172 'multicols': r"(?P<code>\\(?P<be>begin|end)\s*{multicols}({(?P<num>\d+)?})?)",
177 # why do we have distinction between @mbinclude and @include?
180 'junkmeinclude': '(?m)^[^%\n]*?(?P<match>@mbinclude\s+(?P<filename>\S*))',
181 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
184 'landscape': no_match,
185 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
186 'verb': r'''(?P<code>@code{.*?})''',
187 'lilypond-file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
188 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
189 'lilypond-block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
190 'option-sep' : ',\s*',
191 'intertext': r',?\s*intertext=\".*?\"',
192 'multiline-comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
193 'singleline-comment': r"(?m)^.*?(?P<match>(?P<code>@c.*$\n+))",
195 'multicols': no_match,
201 PREAMBLE = 'preamble'
206 #'xrelative': r'''\relative #(ly:make-pitch %(relative)s 0 0)''',
207 'relative': r'''\relative c%(relative_quotes)s''',
211 indent = %(indent)s''',
213 linewidth = %(linewidth)s''',
219 \remove Time_signature_engraver
223 raggedright = ##t''',
227 #(set-global-staff-size %(staffsize)s)''',
236 OUTPUT: r'''<src image="%(base)s.png">''',
244 OUTPUT: r'''{\parindent 0pt
245 \ifx\preLilyPondExample\preLilyPondExample\fi
248 \ifx\preLilyPondExample\postLilyPondExample\fi}
250 VERBATIM: r'''\begin{verbatim}
251 %(code)s\end{verbatim}
262 PREAMBLE_LY = r'''%% Generated by %(program_name)s
263 %% Options: [%(option_string)s]
265 \paper {%(paper_string)s
269 FRAGMENT_LY = r'''\score{
270 \notes%(notes_string)s{
276 def compose_ly (code, option_string):
279 for i in default_ly_options.keys ():
281 vars ()[i] = default_ly_options[i]
284 options = options + string.split (option_string, ',')
286 m = re.search (r'''\\score''', code)
287 if not m and (not options \
288 or not 'nofragment' in options \
289 or 'fragment' in options):
300 preamble_options = []
302 if string.find (i, '=') > 0:
303 key, value = string.split (i, '=')
309 if key in ly_options[NOTES].keys ():
310 notes_options.append (ly_options[NOTES][key])
311 elif key in ly_options[PREAMBLE].keys ():
312 preamble_options.append (ly_options[PREAMBLE][key])
313 elif key in ly_options[PAPER].keys ():
314 paper_options.append (ly_options[PAPER][key])
316 relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
317 program_name = __main__.program_name
318 notes_string = string.join (notes_options, '\n ') % vars ()
319 paper_string = string.join (paper_options, '\n ') % vars ()
320 preamble_string = string.join (preamble_options, '\n ') % vars ()
321 return (PREAMBLE_LY + body) % vars ()
325 # use lilypond-bin for latex (.lytex) books,
326 # and lilypond --preview for html, texinfo books?
328 cmd = r'latex "\nonstopmode \input %s"' % file
329 # Ugh. (La)TeX writes progress and error messages on stdout
331 cmd = '(( %s >&2 ) >&- )' % cmd
333 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
336 ## make source, index statics of Snippet?
339 def find_file (name):
340 for i in include_path:
341 full = os.path.join (i, name)
342 if os.path.exists (full):
344 ly.error (_ ('file not found: %s\n' % name))
349 def __init__ (self, type, index, match):
356 return self.index + self.match.start (s)
359 return self.index + self.match.end (s)
361 def substring (self, source, s):
362 return source[self.start (s):self.end (s)]
364 def ly (self, source):
366 if self.type == 'lilypond-block' or self.type == 'lilypond':
367 s = self.substring (source, 'code')
368 elif self.type == 'lilypond-file':
369 name = self.substring (source, 'filename')
370 s = open (find_file (name)).read ()
373 def full_ly (self, source):
376 return compose_ly (s, self.match.group ('options'))
379 def get_hash (self, source):
381 self.hash = abs (hash (self.ly (source)))
383 print 'TYPE:: ' + self.type
384 print 'CODE:: ' + self.substring (source, 0)
388 def basename (self, source):
390 return 'lily-%d' % self.get_hash (source)
393 def write_ly (self, source):
394 if self.type == 'lilypond-block' or self.type == 'lilypond'\
395 or self.type == 'lilypond-file':
396 h = open (self.basename (source) + '.ly', 'w')
397 h.write (self.full_ly (source))
400 def output_html (self, source):
401 base = self.basename (source)
402 option_string = self.match.group ('options')
403 if option_string and VERBATIM in string.split (option_string):
404 code = self.substring (source, 'code')
405 h.write (output[HTML][VERBATIM] % vars ())
406 h.write (output[HTML][BEFORE])
407 h.write (output[HTML][OUTPUT] % vars ())
408 h.write (output[HTML][AFTER])
410 def output_latex (self, source):
411 option_string = self.match.group ('options')
412 if option_string and VERBATIM in string.split (option_string):
413 code = self.substring (source, 'code')
414 h.write (output[LATEX][VERBATIM] % vars ())
415 h.write (output[LATEX][BEFORE])
416 base = self.basename (source)
417 h.write (output[LATEX][OUTPUT] % vars ())
418 h.write (output[LATEX][AFTER])
420 def output_texinfo (self, source):
422 self.output_latex (source)
423 h.write ('\n@end tex\n')
425 h.write ('\n@html\n')
426 self.output_html (source)
427 h.write ('\n@end html\n')
429 def outdated_p (self, source):
430 if self.type != 'lilypond-block' and self.type != 'lilypond'\
431 and self.type != 'lilypond-file':
433 base = self.basename (source)
434 if os.path.exists (base + '.ly') \
435 and os.path.exists (base + '.tex') \
436 and (not use_hash_p \
437 or self.ly (source) == open (base + '.ly').read ()):
438 # TODO: something smart with target formats
439 # (ps, png) and m/ctimes
443 def find_snippets (s, type):
444 re = ly.re.compile (re_dict[format][type])
447 m = re.search (s[i:])
449 snippets.append (Snippet (type, i, m))
451 m = re.search (s[i:])
454 def filter_pipe (input, cmd):
456 ly.progress (_ ("Opening filter `%s\'") % cmd)
458 stdin, stdout, stderr = os.popen3 (cmd)
460 status = stdin.close ()
464 output = stdout.read ()
465 status = stdout.close ()
466 error = stderr.read ()
470 signal = 0x0f & status
471 if status or (not output and error):
472 exit_status = status >> 8
473 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
474 ly.error (_ ("The error log is as follows:"))
475 sys.stderr.write (error)
476 sys.stderr.write (stderr.read ())
485 return filter_pipe (s, filter_cmd)
487 def compare_index (a, b):
488 return a.start (0) - b.start (0)
490 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
491 # snippets are skipped. return list with all non-empty return values
494 # Hmm, do we need enclosed snippets at all? Maybe use MAP_SNIPPETS
495 # once and use simple filter/map on that resulting toplevel list iso
496 # silly map_snippets/do_snippets.
497 def map_snippets (source, snippets, func):
502 if i.start (0) < index:
504 # lst.append (func (i, source))
511 # apply FUNC to every toplevel block in SNIPPETS, ie, enclosed
512 # snippets are skipped. return last snippet's index
513 def do_snippets (source, snippets, func):
517 if i.start (0) < index:
521 #index = i.end ('code')
524 def process_snippets (source, snippets, cmd):
525 names = map_snippets (source, snippets, Snippet.basename)
527 ly.system (string.join ([cmd] + names))
529 if format == HTML or format == TEXINFO:
532 ly.make_ps_images (i + '.eps', resolution=110)
534 LATEX_DOCUMENT = r'''
537 \typeout{textwidth=\the\textwidth}
538 \typeout{columnsep=\the\columnsep}
539 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
542 #need anything else besides textwidth?
543 def get_latex_textwidth (source):
544 m = re.search (r'''(?P<preabmle>\\begin\s*{document})''', source)
545 preamble = source[:m.start (0)]
546 latex_document = LATEX_DOCUMENT % vars ()
547 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
550 m = re.search ('columns=([0-9.]*)', parameter_string)
552 columns = string.atoi (m.group (1))
555 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
557 columnsep = string.atof (m.group (1))
560 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
562 textwidth = string.atof (m.group (1))
564 textwidth = (textwidth - columnsep) / columns
569 def do_file (input_filename):
583 e = os.path.splitext (input_filename)[1]
584 if e in ext2format.keys ():
585 format = ext2format[e]
587 ly.error (_ ("cannot determine format for: %s" \
593 if input_filename != '-':
594 h = open (input_filename)
597 snippet_types = ('verbatim', 'verb', 'multiline-comment',
598 'lilypond', 'lilypond-block', 'lilypond-file',)
600 for i in snippet_types:
601 snippets += find_snippets (source, i)
603 snippets.sort (compare_index)
606 if output_name and output_name != '-':
607 if not os.path.isdir (output_name):
608 os.mkdir (output_name, 0777)
609 if input_filename != '-':
610 h = open (output_name + '/' \
611 + os.path.split (input_filename)[0] \
614 os.chdir (output_name)
616 def filter_source (snippet, source):
618 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
619 #if snippet.match.group ('code'):
621 if snippet.type == 'lilypond' or snippet.type == 'lilypond-block':
622 h.write (source[index:snippet.start ('code')])
623 h.write (run_filter (snippet.substring (source, 'code')))
624 h.write (source[snippet.end ('code'):snippet.end (0)])
626 h.write (source[index:snippet.end (0)])
627 index = snippet.end (0)
629 snippet_output = eval ("Snippet.output_" + format)
630 def compile_output (snippet, source):
632 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
633 # if snippet.match.group ('code'):
635 if snippet.type == 'lilypond' \
636 or snippet.type == 'lilypond-block'\
637 or snippet.type == 'lilypond-file':
638 h.write (source[index:snippet.start (0)])
639 snippet_output (snippet, source)
640 index = snippet.end (0)
642 global default_ly_options
643 if format == LATEX and LINEWIDTH not in default_ly_options.keys ():
644 textwidth = get_latex_textwidth (source)
645 default_ly_options[LINEWIDTH] = '''%.0f\pt''' % textwidth
649 index = do_snippets (source, snippets, filter_source)
650 h.write (source[index:])
652 outdated = map_snippets (source, snippets, Snippet.outdated_p)
653 do_snippets (source, snippets, Snippet.write_ly)
654 process_snippets (source, outdated, process_cmd)
655 do_snippets (source, snippets, compile_output)
656 h.write (source[index:])
658 # misusing snippet bit silly?
659 includes = find_snippets (source, 'include')
661 os.chdir (original_dir)
662 sys.stderr.write ('DO: ' + sys.argv[0] + ' OPTIONS ' + i.substring (source, 'filename') + '\n')
665 global format, output_name
666 global filter_cmd, process_cmd, verbose_p
668 (sh, long) = ly.getopt_args (option_definitions)
670 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
671 except getopt.error, s:
672 sys.stderr.write ('\n')
673 ly.error (_ ("getopt says: `%s\'" % s))
674 sys.stderr.write ('\n')
684 elif o == '--version' or o == '-v':
685 ly.identify (sys.stdout)
687 elif o == '--verbose' or o == '-V':
689 elif o == '--filter' or o == '-F':
692 elif o == '--format' or o == '-f':
694 if a == 'texi-html' or a == 'texi':
696 elif o == '--help' or o == '-h':
699 elif o == '--include' or o == '-I':
700 include_path.append (os.path.join (original_dir,
702 elif o == '--output' or o == '-o':
704 elif o == '--outdir':
706 elif o == '--process' or o == '-P':
709 elif o == '--warranty' or o == '-w':
716 files = do_options ()
717 ly.identify (sys.stderr)
718 ly.setup_environment ()
722 if __name__ == '__main__':