5 ly-options: intertext, quote ?
8 check latex parameters, twocolumn
16 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
19 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
21 classic lilypond-book:
22 lilypond-book --process="lilypond-bin" BOOK.tely
25 @mbinclude foo.itely -> @include foo.itely
33 ################################################################
34 # Users of python modules should include this snippet
35 # and customize variables below.
37 # We'll suffer this path init stuff as long as we don't install our
38 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
39 # it as we do with teTeX on Red Hat Linux: set some environment var
40 # (PYTHONPATH) in profile)
42 # If set, LILYPONDPREFIX must take prevalence
43 # if datadir is not set, we're doing a build and LILYPONDPREFIX
44 import getopt, os, sys
45 datadir = '@local_lilypond_datadir@'
46 if not os.path.isdir (datadir):
47 datadir = '@lilypond_datadir@'
48 if os.environ.has_key ('LILYPONDPREFIX') :
49 datadir = os.environ['LILYPONDPREFIX']
50 while datadir[-1] == os.sep:
53 sys.path.insert (0, os.path.join (datadir, 'python'))
56 #if __name__ == '__main__':
64 program_version = '@TOPLEVEL_VERSION@'
65 program_name = 'lilypond-book'
68 original_dir = os.getcwd ()
71 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document. Example usage:
73 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
74 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
75 lilypond-book --process='lilypond-bin -I include' BOOK
79 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>>',
80 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
82 option_definitions = [
83 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
84 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
85 ('', 'h', 'help', _ ("print this help")),
86 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
87 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
88 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
89 ('', 'V', 'verbose', _ ("be verbose")),
90 ('', 'v', 'version', _ ("print version information")),
91 ('', 'w', 'warranty', _ ("show warranty and copyright")),
94 include_path = [ly.abspath (os.getcwd ())]
95 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
97 # only use installed binary when we're installed too.
98 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
99 lilypond_binary = 'lilypond-bin'
105 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
107 process_cmd = lilypond_binary
108 default_ly_options = { }
114 LINEWIDTH = 'linewidth'
118 PREAMBLE = 'preamble'
120 VERBATIM = 'verbatim'
123 # Recognize special sequences in the input
125 # (?P<name>regex) -- assign result of REGEX to NAME
126 # *? -- match non-greedily.
127 # (?m) -- multiline regex: make ^ and $ match at each line
128 # (?s) -- make the dot match all characters including newline
133 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
134 'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
135 'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
136 'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
137 'singleline_comment': no_match,
138 'verb': r'''(?P<code><pre>.*?</pre>)''',
139 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
143 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
144 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
145 'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
146 'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
147 'multiline_comment': no_match,
148 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
149 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
150 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
154 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S*))',
155 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
156 'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
157 'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
158 'multiline_comment': r"(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end ignore)\s",
159 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>@c([ \t][^\n]*|)\n))",
160 'verb': r'''(?P<code>@code{.*?})''',
161 'verbatim': r'''(?s)(?P<code>@example\s.*?@end example\s)''',
167 'option-sep' : '\s*',
168 'intertext': r',?\s*intertext=\".*?\"',
171 'intertext': r',?\s*intertext=\".*?\"',
172 'option-sep' : ',\s*',
175 'intertext': r',?\s*intertext=\".*?\"',
176 'option-sep' : ',\s*',
182 'relative': r'''\relative c%(relative_quotes)s''',
186 indent = %(indent)s''',
188 linewidth = %(linewidth)s''',
194 \remove Time_signature_engraver
198 raggedright = ##t''',
202 #(set-global-staff-size %(staffsize)s)''',
210 OUTPUT: r'''<img align="center" valign="center"
211 border="0" src="%(base)s.png" alt="[picture of music]">''',
219 OUTPUT: r'''{\parindent 0pt
221 \ifx\preLilyPondExample\preLilyPondExample\fi
224 \ifx\preLilyPondExample\postLilyPondExample\fi
226 VERBATIM: r'''\begin{verbatim}
227 %(verb)s\end{verbatim}
234 VERBATIM: r'''@example
235 %(verb)s@end example''',
241 PREAMBLE_LY = r'''%% Generated by %(program_name)s
242 %% Options: [%(option_string)s]
244 \paper {%(paper_string)s
248 FRAGMENT_LY = r'''\score{
249 \notes%(notes_string)s{
254 def classic_lilypond_book_compatibility (o):
255 if o == 'singleline':
257 m = re.search ('relative\s*([-0-9])', o)
259 return 'relative=%s' % m.group (1)
260 m = re.match ('([0-9]+)pt', o)
262 return 'staffsize=%s' % m.group (1)
263 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt)', o)
265 f = float (m.group (1))
266 return 'indent=%f\\%s' % (f, m.group (2))
267 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt)', o)
269 f = float (m.group (1))
270 return 'linewidth=%f\\%s' % (f, m.group (2))
273 def compose_ly (code, option_string):
276 for i in default_ly_options.keys ():
278 vars ()[i] = default_ly_options[i]
281 options = options + split_options (option_string)
283 m = re.search (r'''\\score''', code)
284 if not m and (not options \
285 or not 'nofragment' in options \
286 or 'fragment' in options):
287 options.append ('raggedright')
298 preamble_options = []
300 c = classic_lilypond_book_compatibility (i)
302 ly.warning (_ ("deprecated ly-option used: %s" % i))
303 ly.warning (_ ("compatibility mode translation: %s" \
307 if string.find (i, '=') > 0:
308 key, value = string.split (i, '=')
314 if key in ly_options[NOTES].keys ():
315 notes_options.append (ly_options[NOTES][key])
316 elif key in ly_options[PREAMBLE].keys ():
317 preamble_options.append (ly_options[PREAMBLE][key])
318 elif key in ly_options[PAPER].keys ():
319 paper_options.append (ly_options[PAPER][key])
320 elif key not in ('fragment', 'nofragment',
321 'relative', 'verbatim'):
322 ly.warning (_("ignoring unknown ly option: %s") % i)
324 relative_quotes = (",,,", ",,", ",", "", "'", "''", "'''")[relative-3]
325 program_name = __main__.program_name
326 notes_string = string.join (notes_options, '\n ') % vars ()
327 paper_string = string.join (paper_options, '\n ') % vars ()
328 preamble_string = string.join (preamble_options, '\n ') % vars ()
329 return (PREAMBLE_LY + body) % vars ()
333 # use lilypond-bin for latex (.lytex) books,
334 # and lilypond --preview for html, texinfo books?
336 cmd = r'latex "\nonstopmode \input %s"' % file
337 # Ugh. (La)TeX writes progress and error messages on stdout
339 cmd = '(( %s >&2 ) >&- )' % cmd
341 ly.system ('dvips -Ppdf -u+lilypond.map -E -o %s.eps %s' \
344 def find_file (name):
345 for i in include_path:
346 full = os.path.join (i, name)
347 if os.path.exists (full):
349 ly.error (_ ('file not found: %s\n' % name))
353 def verbatim_html (s):
354 return re.sub ('>', '>',
356 re.sub ('&', '&', s)))
358 def verbatim_texinfo (s):
359 return re.sub ('{', '@{',
361 re.sub ('@', '@@', s)))
363 def split_options (option_string):
364 return re.split (format_res[format]['option-sep'], option_string)
367 ## make index static of Snippet?
372 ## huh? index is redundant? --hwn
373 def __init__ (self, type, source, index, match):
381 return self.index + self.match.start (s)
384 return self.index + self.match.end (s)
386 def substring (self, s):
387 return self.source[self.start (s):self.end (s)]
391 if self.type == 'lilypond_block' or self.type == 'lilypond':
392 s = self.substring ('code')
393 elif self.type == 'lilypond_file':
394 name = self.substring ('filename')
395 s = open (find_file (name)).read ()
401 return compose_ly (s, self.match.group ('options'))
406 self.hash = abs (hash (self.ly ()))
411 return 'lily-%d' % self.get_hash ()
415 if self.type == 'lilypond_block' or self.type == 'lilypond'\
416 or self.type == 'lilypond_file':
417 h = open (self.basename () + '.ly', 'w')
418 h.write (self.full_ly ())
420 def output_html (self):
421 base = self.basename ()
422 option_string = self.match.group ('options')
423 if option_string and VERBATIM in split_options (option_string)\
425 verb = verbatim_html (self.substring ('code'))
426 h.write (output[HTML][VERBATIM] % vars ())
427 h.write (output[HTML][BEFORE])
428 h.write (output[HTML][OUTPUT] % vars ())
429 h.write (output[HTML][AFTER])
431 def output_latex (self):
432 option_string = self.match.group ('options')
433 if option_string and VERBATIM in split_options (option_string)\
435 verb = self.substring ('code')
436 h.write (output[LATEX][VERBATIM] % vars ())
437 h.write (output[LATEX][BEFORE])
438 base = self.basename ()
439 h.write (output[LATEX][OUTPUT] % vars ())
440 h.write (output[LATEX][AFTER])
442 def output_texinfo (self):
443 option_string = self.match.group ('options')
444 if option_string and VERBATIM in split_options (option_string):
445 verb = verbatim_texinfo (self.substring ('code'))
446 h.write (output[TEXINFO][VERBATIM] % vars ())
449 h.write ('\n@end tex\n')
451 h.write ('\n@html\n')
453 h.write ('\n@end html\n')
455 def outdated_p (self):
456 if self.type != 'lilypond_block' and self.type != 'lilypond'\
457 and self.type != 'lilypond_file':
459 base = self.basename ()
460 if os.path.exists (base + '.ly') \
461 and os.path.exists (base + '.tex') \
463 or self.ly () == open (base + '.ly').read ()):
464 # TODO: something smart with target formats
465 # (ps, png) and m/ctimes
469 def filter_code (self):
471 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
472 #if snippet.match.group ('code'):
474 if self.type == 'lilypond' or self.type == 'lilypond_block':
475 h.write (self.source[index:self.start ('code')])
476 h.write (run_filter (self.substring ('code')))
477 h.write (self.source[self.end ('code'):self.end (0)])
479 h.write (self.source[index:self.end (0)])
482 def compile_output (self):
484 # Hmm, why is verbatim's group called 'code'; rename to 'verb'?
485 # if snippet.match.group ('code'):
487 if self.type == 'lilypond' \
488 or self.type == 'lilypond_block'\
489 or self.type == 'lilypond_file':
490 h.write (self.source[index:self.start (0)])
491 snippet_output = eval ("Snippet.output_" + format)
492 snippet_output (self)
493 elif self.type == 'include':
494 h.write (self.source[index:self.start ('filename')])
495 base = os.path.splitext (self.substring ('filename'))[0]
496 h.write (base + format2ext[format])
497 h.write (self.source[self.end ('filename'):self.end (0)])
499 h.write (self.source[index:self.end (0)])
503 # this isn't working - <params> are doubly used.
504 # a solution is to strip P<> from the regexes,
505 # and redo the match with the original in notice_snippet
506 def other_toplevel_snippets (str, types):
507 res = ['(?P<regex%s>%s)' % (t, snippet_res[format][t])
510 big_re = re.compile (string.join (res, '|'))
513 def notice_snippet (match, snips = snippets, types = types):
518 gr = match.group (key)
519 snip =Snippet (t, str, match.start (key), match)
528 return match.group (0)
530 str = big_re.sub (notice_snippet, str)
534 def simple_toplevel_snippets (str, types):
537 regex = re.compile (snippet_res[format][t])
539 # ugh, this can be done nicer in python 2.x
540 def notice_snippet (match, snippets = snippets,
542 s = Snippet (t, str, 0, match)
546 regex.sub (notice_snippet, str)
549 def find_toplevel_snippets (s, types):
552 res[i] = ly.re.compile (snippet_res[format][i])
556 found = {}.fromkeys (types)
561 if not found[i] or found[i].start (0) < index:
563 m = res[i].search (s[index:endex])
565 found[i] = Snippet (i, s, index, m)
568 or found[i].start (0) < found[first].start (0)):
570 endex = found[first].start (0)
573 snippets.append (found[first])
574 index = found[first].end (0)
578 def filter_pipe (input, cmd):
580 ly.progress (_ ("Opening filter `%s\'") % cmd)
582 stdin, stdout, stderr = os.popen3 (cmd)
584 status = stdin.close ()
588 output = stdout.read ()
589 status = stdout.close ()
590 error = stderr.read ()
594 signal = 0x0f & status
595 if status or (not output and error):
596 exit_status = status >> 8
597 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
598 ly.error (_ ("The error log is as follows:"))
599 sys.stderr.write (error)
600 sys.stderr.write (stderr.read ())
609 return filter_pipe (s, filter_cmd)
611 def process_snippets (cmd, snippets):
612 names = filter (lambda x:x, map (Snippet.basename, snippets))
614 ly.system (string.join ([cmd] + names))
616 if format == HTML or format == TEXINFO:
618 if os.path.exists (i + '.tex'):
620 ly.make_ps_images (i + '.eps', resolution=110)
622 LATEX_DOCUMENT = r'''
625 \typeout{textwidth=\the\textwidth}
626 \typeout{columnsep=\the\columnsep}
627 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
630 #need anything else besides textwidth?
631 def get_latex_textwidth (source):
632 m = re.search (r'''(?P<preabmle>\\begin\s*{document})''', source)
633 preamble = source[:m.start (0)]
634 latex_document = LATEX_DOCUMENT % vars ()
635 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
638 m = re.search ('columns=([0-9.]*)', parameter_string)
640 columns = string.atoi (m.group (1))
643 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
645 columnsep = string.atof (m.group (1))
648 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
650 textwidth = string.atof (m.group (1))
652 textwidth = (textwidth - columnsep) / columns
664 '.texinfo' : TEXINFO,
670 #TEXINFO: '.texinfo',
675 def do_file (input_filename):
679 e = os.path.splitext (input_filename)[1]
680 if e in ext2format.keys ():
682 format = ext2format[e]
684 ly.error (_ ("cannot determine format for: %s" \
687 ly.progress (_ ("Reading %s...") % input_filename)
688 if not input_filename or input_filename == '-':
691 ih = open (input_filename)
695 ly.progress (_ ("Dissecting..."))
696 #snippets = find_toplevel_snippets (source, snippet_res[format].keys ())
701 'singleline_comment',
707 snippets = simple_toplevel_snippets (source, snippet_types)
711 if output_name == '-' or not output_name:
713 output_filename = '-'
715 if not os.path.isdir (output_name):
716 os.mkdir (output_name, 0777)
717 if input_filename == '-':
720 input_base = os.path.splitext (input_filename)[0]
721 output_filename = output_name + '/' + input_base \
723 h = open (output_filename, 'w')
724 os.chdir (output_name)
726 global default_ly_options
728 if format == LATEX and LINEWIDTH not in default_ly_options.keys ():
729 textwidth = get_latex_textwidth (source)
730 default_ly_options[LINEWIDTH] = '''%.0f\pt''' % textwidth
735 map (Snippet.filter_code, snippets)
736 h.write (source[index:])
738 outdated = filter (lambda x:x,
739 map (Snippet.outdated_p, snippets))
740 ly.progress (_ ("Writing snippets..."))
741 map (Snippet.write_ly, snippets)
745 ly.progress (_ ("Processing..."))
746 process_snippets (process_cmd, outdated)
748 ly.progress (_ ("All snippets are up to date..."))
751 ly.progress (_ ("Compiling %s...") % output_filename)
753 map (Snippet.compile_output, snippets)
754 h.write (source[index:])
760 def process_include (snippet):
761 os.chdir (original_dir)
762 name = snippet.substring ('filename')
763 ly.progress (_ ('Processing include: %s') % name)
767 map (process_include, filter (lambda x: x.type == 'include', snippets))
770 global format, output_name
771 global filter_cmd, process_cmd, verbose_p
773 (sh, long) = ly.getopt_args (option_definitions)
775 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
776 except getopt.error, s:
777 sys.stderr.write ('\n')
778 ly.error (_ ("getopt says: `%s\'" % s))
779 sys.stderr.write ('\n')
789 elif o == '--filter' or o == '-F':
792 elif o == '--format' or o == '-f':
794 if a == 'texi-html' or a == 'texi':
796 elif o == '--help' or o == '-h':
799 elif o == '--include' or o == '-I':
800 include_path.append (os.path.join (original_dir,
802 elif o == '--output' or o == '-o':
804 elif o == '--outdir':
806 elif o == '--process' or o == '-P':
809 elif o == '--version' or o == '-v':
810 ly.identify (sys.stdout)
812 elif o == '--verbose' or o == '-V':
814 elif o == '--warranty' or o == '-w':
821 files = do_options ()
822 ly.identify (sys.stderr)
823 ly.setup_environment ()
827 if __name__ == '__main__':