7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
16 * ly-options: intertext ?
18 * eps in latex / eps by lilypond -fps ?
19 * check latex parameters, twocolumn, multicolumn?
21 * Converting from lilypond-book source, substitute:
22 @mbinclude foo.itely -> @include foo.itely
35 # * use --png --ps --pdf for making images?
38 ################################################################
39 # Users of python modules should include this snippet
40 # and customize variables below.
42 # We'll suffer this path init stuff as long as we don't install our
43 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
44 # it as we do with teTeX on Red Hat Linux: set some environment var
45 # (PYTHONPATH) in profile)
47 # If set, LILYPONDPREFIX must take prevalence
48 # if datadir is not set, we're doing a build and LILYPONDPREFIX
49 import getopt, os, sys
50 datadir = '@local_lilypond_datadir@'
51 if not os.path.isdir (datadir):
52 datadir = '@lilypond_datadir@'
53 if os.environ.has_key ('LILYPONDPREFIX') :
54 datadir = os.environ['LILYPONDPREFIX']
55 while datadir[-1] == os.sep:
58 sys.path.insert (0, os.path.join (datadir, 'python'))
61 #if __name__ == '__main__':
69 program_version = '@TOPLEVEL_VERSION@'
70 program_name = sys.argv[0]
73 original_dir = os.getcwd ()
76 help_summary = _ ("""Process LilyPond snippets in hybrid HTML, LaTeX or texinfo document.
79 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
80 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
81 lilypond-book --process='lilypond -I include' BOOK
85 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
86 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
88 option_definitions = [
89 (_ ("EXT"), 'f', 'format', _ ("use output format EXT (texi [default], texi-html, latex, html)")),
90 (_ ("FILTER"), 'F', 'filter', _ ("pipe snippets through FILTER [convert-ly -n -]")),
91 ('', 'h', 'help', _ ("print this help")),
92 (_ ("DIR"), 'I', 'include', _ ("add DIR to include path")),
93 (_ ("COMMAND"), 'P', 'process', _ ("process ly_files using COMMAND FILE...")),
94 (_ ("DIR"), 'o', 'output', _ ("write output to DIR")),
95 ('', 'V', 'verbose', _ ("be verbose")),
96 ('', 'v', 'version', _ ("print version information")),
97 ('', 'w', 'warranty', _ ("show warranty and copyright")),
100 include_path = [ly.abspath (os.getcwd ())]
101 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
103 # only use installed binary when we're installed too.
104 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
105 lilypond_binary = 'lilypond'
111 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
114 default_ly_options = {}
117 # is this pythonic? Personally, I find this rather #define-nesque. --hwn
121 EXAMPLEINDENT = 'exampleindent'
123 FRAGMENT = 'fragment'
128 LINEWIDTH = 'linewidth'
129 NOFRAGMENT = 'nofragment'
130 NOINDENT = 'noindent'
135 PREAMBLE = 'preamble'
136 PRINTFILENAME = 'printfilename'
138 RAGGEDRIGHT = 'raggedright'
139 RELATIVE = 'relative'
140 STAFFSIZE = 'staffsize'
143 VERBATIM = 'verbatim'
145 # Recognize special sequences in the input
147 # (?P<name>regex) -- assign result of REGEX to NAME
148 # *? -- match non-greedily.
149 # (?m) -- multiline regex: make ^ and $ match at each line
150 # (?s) -- make the dot match all characters including newline
155 'lilypond' : '(?m)(?P<match><lilypond((?P<options>[^:]*):)(?P<code>.*?)/>)',
156 'lilypond_block': r'''(?ms)(?P<match><lilypond(?P<options>[^>]+)?>(?P<code>.*?)</lilypond>)''',
157 'lilypond_file': r'(?m)(?P<match><lilypondfile(?P<options>[^>]+)?>\s*(?P<filename>[^<]+)\s*</lilypondfile>)',
158 'multiline_comment': r"(?sm)\s*(?!@c\s+)(?P<code><!--\s.*?!-->)\s",
159 'singleline_comment': no_match,
160 'verb': r'''(?P<code><pre>.*?</pre>)''',
161 'verbatim': r'''(?s)(?P<code><pre>\s.*?</pre>\s)''',
165 'include': r'(?m)^[^%\n]*?(?P<match>\\input{(?P<filename>[^}]+)})',
166 'lilypond' : r'(?m)^[^%\n]*?(?P<match>\\lilypond\s*(\[(?P<options>.*?)\])?\s*{(?P<code>.*?)})',
167 'lilypond_block': r"(?sm)^[^%\n]*?(?P<match>\\begin\s*(\[(?P<options>.*?)\])?\s*{lilypond}(?P<code>.*?)\\end{lilypond})",
168 'lilypond_file': r'(?m)^[^%\n]*?(?P<match>\\lilypondfile\s*(\[(?P<options>.*?)\])?\s*\{(?P<filename>.+)})',
169 'multiline_comment': no_match,
170 'singleline_comment': r"(?m)^.*?(?P<match>(?P<code>^%.*$\n+))",
171 'verb': r"(?P<code>\\verb(?P<del>.).*?(?P=del))",
172 'verbatim': r"(?s)(?P<code>\\begin\s*{verbatim}.*?\\end{verbatim})",
176 'include': '(?m)^[^%\n]*?(?P<match>@include\s+(?P<filename>\S+))',
177 'lilypond' : '(?m)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?{(?P<code>.*?)})',
178 'lilypond_block': r'''(?ms)^(?P<match>@lilypond(\[(?P<options>[^]]*)\])?\s(?P<code>.*?)@end lilypond)\s''',
179 'lilypond_file': '(?m)^(?P<match>@lilypondfile(\[(?P<options>[^]]*)\])?{(?P<filename>[^}]+)})',
180 'multiline_comment': r'(?sm)^\s*(?!@c\s+)(?P<code>@ignore\s.*?@end\s+ignore)\s',
181 'singleline_comment': r'(?m)^.*(?P<match>(?P<code>@c([ \t][^\n]*|)\n))',
183 # don't do this: fucks up with @code{@{}
184 # 'verb': r'''(?P<code>@code{.*?})''',
185 'verbatim': r'''(?s)(?P<code>@example\s.*?@end\s+example\s)''',
191 'option-sep' : '\s*',
192 'intertext': r',?\s*intertext=\".*?\"',
195 'intertext': r',?\s*intertext=\".*?\"',
196 'option-sep' : ',\s*',
199 'intertext': r',?\s*intertext=\".*?\"',
200 'option-sep' : ',\s*',
206 RELATIVE: r'''\relative c%(relative_quotes)s''',
210 indent = %(indent)s''',
212 linewidth = %(linewidth)s''',
216 linewidth = %(linewidth)s - 2.0 * %(exampleindent)s
220 raggedright = ##t''',
230 \remove Time_signature_engraver
237 #(set-global-staff-size %(staffsize)s)''',
243 FILTER: r'''<lilypond %(options)s>
253 <a href="%(base)s.ly">''',
255 <img align="center" valign="center"
256 border="0" src="%(image)s" alt="[image of music]">''',
257 PRINTFILENAME:'<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
258 QUOTE: r'''<blockquote>
269 OUTPUT: r'''{\parindent 0pt
271 \ifx\preLilyPondExample\undefined\relax\else\preLilyPondExample\fi
274 \ifx\postLilyPondExample\undefined\relax\else\postLilyPondExample\fi
276 PRINTFILENAME: '''\\texttt{%(filename)s}
279 QUOTE: r'''\begin{quotation}
283 VERBATIM: r'''\noindent
285 %(verb)s\end{verbatim}
287 FILTER: r'''\begin{lilypond}[%(options)s]
293 FILTER: r'''@lilypond[%(options)s]
298 OUTPUT: r'''@noindent
299 @image{%(base)s,,,[image of music],%(ext)s}
301 PRINTFILENAME: '''@file{%(filename)s}
304 QUOTE: r'''@quotation
308 # FIXME: @exampleindent 5 is the default...
309 VERBATIM: r'''@exampleindent 0
317 PREAMBLE_LY = r"""%%%% Generated by %(program_name)s
318 %%%% Options: [%(option_string)s]
319 #(set! toplevel-score-handler ly:parser-print-score)
320 #(set! toplevel-music-handler (lambda (p m)
321 (ly:parser-print-score
322 p (ly:music-scorify m p))
326 #(define dump-extents #t)
329 \layout { %(layout_string)s
340 texinfo_linewidths = {
341 '@afourpaper': '160 \\mm',
342 '@afourwide': '6.5 \\in',
343 '@afourlatex': '150 \\mm',
344 '@smallbook': '5 \\in' ,
345 '@letterpaper': '6\\in',
348 def classic_lilypond_book_compatibility (o):
349 if o == 'singleline':
351 m = re.search ('relative\s*([-0-9])', o)
353 return 'relative=%s' % m.group (1)
354 m = re.match ('([0-9]+)pt', o)
356 return 'staffsize=%s' % m.group (1)
357 m = re.match ('indent=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
359 f = float (m.group (1))
360 return 'indent=%f\\%s' % (f, m.group (2))
361 m = re.match ('linewidth=([-.0-9]+)(cm|in|mm|pt|staffspace)', o)
363 f = float (m.group (1))
364 return 'linewidth=%f\\%s' % (f, m.group (2))
367 def compose_ly (code, options):
369 for i in default_ly_options.keys ():
374 if QUOTE in options and LINEWIDTH in options:
375 options.remove (LINEWIDTH)
377 if FRAGMENT in options:
378 if RAGGEDRIGHT not in options:
379 options.append (RAGGEDRIGHT)
388 #FIXME: where to get sane value for exampleindent?
389 override[EXAMPLEINDENT] = r'9.0 \mm'
390 override[LINEWIDTH] = None
391 override.update (default_ly_options)
393 option_string = string.join (options, ',')
396 option_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
397 for a in option_types:
401 c = classic_lilypond_book_compatibility (i)
403 ly.warning (_ ("deprecated ly-option used: %s" % i))
404 ly.warning (_ ("compatibility mode translation: %s" \
408 if string.find (i, '=') > 0:
409 key, value = string.split (i, '=')
410 override[key] = value
413 if not override.has_key (i):
417 for type in option_types:
418 if ly_options[type].has_key (key):
420 options_dict[type].append (ly_options[type][key])
424 if not found and key not in (FRAGMENT, NOFRAGMENT, PRINTFILENAME,
425 RELATIVE, VERBATIM, TEXIDOC):
426 ly.warning (_("ignoring unknown ly option: %s") % i)
429 if RELATIVE in override.keys () and override[RELATIVE]:
430 relative = string.atoi (override[RELATIVE])
436 relative_quotes += ',' * (- relative)
438 relative_quotes += "'" * relative
440 program_name = __main__.program_name
442 paper_string = string.join (options_dict[PAPER], '\n ') % override
443 layout_string = string.join (options_dict[LAYOUT], '\n ') % override
444 notes_string = string.join (options_dict[NOTES], '\n ') % vars ()
445 preamble_string = string.join (options_dict[PREAMBLE], '\n ') % override
446 return (PREAMBLE_LY + body) % vars ()
450 # use lilypond for latex (.lytex) books,
451 # and lilypond --preview for html, texinfo books?
453 cmd = r'latex "\nonstopmode \input %s"' % file
454 # Ugh. (La)TeX writes progress and error messages on stdout
456 cmd = '(( %s >&2 ) >&- )' % cmd
458 ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
462 # check if it really is EPS.
463 # Otherwise music glyphs disappear from 2nd and following pages.
465 # TODO: should run dvips -pp -E per page, then we get proper
468 f = open ('%s.eps' % file)
469 for x in range(0,10) :
470 if re.search ("^%%Pages: ", f.readline ()):
473 ly.system ('dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
478 def find_file (name):
479 for i in include_path:
480 full = os.path.join (i, name)
481 if os.path.exists (full):
483 ly.error (_ ('file not found: %s') % name + '\n')
487 def verbatim_html (s):
488 return re.sub ('>', '>',
490 re.sub ('&', '&', s)))
492 def verbatim_texinfo (s):
493 return re.sub ('{', '@{',
495 re.sub ('@', '@@', s)))
497 def split_options (option_string):
498 return re.split (format_res[format]['option-sep'], option_string)
502 def replacement_text (self):
505 def filter_text (self):
506 return self.replacement_text ()
509 def ly_is_outdated (self):
512 def png_is_outdated (self):
515 class Substring (Chunk):
516 def __init__ (self, source, start, end):
521 def replacement_text (self):
522 return self.source [self.start:self.end]
524 class Snippet (Chunk):
525 def __init__ (self, type, match, format):
532 def replacement_text (self):
533 return self.match.group (0)
535 def substring (self, s):
536 return self.match.group (s)
539 return `self.__class__` + " type = " + self.type
541 class Include_snippet (Snippet):
542 def processed_filename (self):
543 f = self.substring ('filename')
544 return os.path.splitext (f)[0] + format2ext[format]
546 def replacement_text (self):
547 s = self.match.group (0)
548 f = self.substring ('filename')
550 return re.sub (f, self.processed_filename (), s)
552 class Lilypond_snippet (Snippet):
553 def __init__ (self, type, match, format):
554 Snippet.__init__ (self, type, match, format)
555 os = match.group ('options')
557 self.options = split_options (os)
560 return self.substring ('code')
565 return compose_ly (s, self.options)
571 self.hash = abs (hash (self.full_ly ()))
576 return 'lily-%d' % self.get_hash ()
580 outf = open (self.basename () + '.ly', 'w')
581 outf.write (self.full_ly ())
583 open (self.basename() + '.txt', 'w').write("image of music")
586 def ly_is_outdated (self):
587 base = self.basename ()
589 tex_file = '%s.tex' % base
590 ly_file = '%s.ly' % base
591 ok = os.path.exists (ly_file) and os.path.exists (tex_file)\
592 and os.stat (tex_file)[stat.ST_SIZE] \
593 and open (tex_file).readlines ()[-1][1:-1] \
596 if ok and (use_hash_p or self.ly () == open (ly_file).read ()):
597 # TODO: something smart with target formats
598 # (ps, png) and m/ctimes
602 def png_is_outdated (self):
603 base = self.basename ()
604 ok = self.ly_is_outdated ()
605 if format == HTML or format == TEXINFO:
606 ok = ok and (os.path.exists (base + '.png')
607 or glob.glob (base + '-page*.png'))
610 def filter_text (self):
611 code = self.substring ('code')
612 s = run_filter (code)
614 'options': self.match.group ('options')
617 return output[self.format][FILTER] % d
619 def replacement_text (self):
620 func = Lilypond_snippet.__dict__ ['output_' + self.format]
623 def get_images (self):
624 base = self.basename ()
626 single = '%(base)s.png' % vars ()
627 multiple = '%(base)s-page1.png' % vars ()
629 if os.path.exists (multiple) \
630 and (not os.path.exists (single)\
631 or (os.stat (multiple)[stat.ST_MTIME] \
632 > os.stat (single)[stat.ST_MTIME])):
633 images = glob.glob ('%(base)s-page*.png' % vars ())
636 def output_html (self):
638 base = self.basename ()
640 str += self.output_print_filename (HTML)
641 if VERBATIM in self.options:
642 verb = verbatim_html (self.substring ('code'))
643 str += write (output[HTML][VERBATIM] % vars ())
644 if QUOTE in self.options:
645 str = output[HTML][QUOTE] % vars ()
647 str += output[HTML][BEFORE] % vars ()
648 for image in self.get_images ():
649 base, ext = os.path.splitext (image)
650 str += output[HTML][OUTPUT] % vars ()
651 str += output[HTML][AFTER] % vars ()
654 def output_info (self):
655 str = self.output_print_filename (HTML)
656 str = output[TEXINFO][BEFORE] % vars ()
657 for image in self.get_images ():
658 base, ext = os.path.splitext (image)
660 # URG, makeinfo implicitely prepends dot to ext
661 # specifying no extension is most robust
663 str += output[TEXINFO][OUTPUT] % vars ()
664 str += output[TEXINFO][AFTER] % vars ()
667 def output_latex (self):
669 base = self.basename ()
671 str += self.output_print_filename (LATEX)
672 if VERBATIM in self.options:
673 verb = self.substring ('code')
674 str += (output[LATEX][VERBATIM] % vars ())
675 if QUOTE in self.options:
676 str = output[LATEX][QUOTE] % vars ()
678 str += (output[LATEX][BEFORE]
679 + (output[LATEX][OUTPUT] % vars ())
680 + output[LATEX][AFTER])
683 def output_print_filename (self,format):
685 if PRINTFILENAME in self.options:
686 base = self.basename ()
687 filename = self.substring ('filename')
688 str = output[format][PRINTFILENAME] % vars ()
691 def output_texinfo (self):
693 # self.output_print_filename (TEXINFO)
694 str += ('@html\n' + self.output_print_filename (HTML)
696 str += ('@tex\n' + self.output_print_filename (LATEX)
698 base = self.basename ()
699 if TEXIDOC in self.options:
700 texidoc = base + '.texidoc'
701 if os.path.exists (texidoc):
702 str += '@include %(texidoc)s\n\n' % vars ()
704 if VERBATIM in self.options:
705 verb = verbatim_texinfo (self.substring ('code'))
706 str += (output[TEXINFO][VERBATIM] % vars ())
708 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
709 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
710 str += ('@html\n' + self.output_html () + '\n@end html\n')
712 if QUOTE in self.options:
713 str = output[TEXINFO][QUOTE] % vars ()
715 # need par after image
720 class Lilypond_file_snippet (Lilypond_snippet):
722 name = self.substring ('filename')
723 return '\\renameinput \"%s\"\n%s' % (name, open (find_file (name)).read ())
725 snippet_type_to_class = {
726 'lilypond_file' : Lilypond_file_snippet,
727 'lilypond_block' : Lilypond_snippet,
728 'lilypond' : Lilypond_snippet,
729 'include' : Include_snippet,
732 def find_toplevel_snippets (s, types):
735 res[i] = ly.re.compile (snippet_res[format][i])
739 ## found = dict (map (lambda x: (x, None), types))
742 map (lambda x, f=found: f.setdefault (x, None), types)
744 # We want to search for multiple regexes, without searching
745 # the string multiple times for one regex.
746 # Hence, we use earlier results to limit the string portion
748 # Since every part of the string is traversed at most once for
749 # every type of snippet, this is linear.
755 if not found[type] or found[type][0] < index:
757 m = res[type].search (s[index:endex])
762 if snippet_type_to_class.has_key (type):
763 cl = snippet_type_to_class[type]
764 snip = cl (type, m, format)
765 start = index + m.start (0)
766 found[type] = (start, snip)
769 and (not first or found[type][0] < found[first][0]):
774 # Limiting the search space is a cute
775 # idea, but this *requires* to search
776 # for possible containing blocks
777 # first, at least long as we do not
778 # search for the start of blocks, but
779 # always/directly for the entire
780 # @block ... @end block.
782 endex = found[first][0]
785 snippets.append (Substring (s, index, len (s)))
788 (start , snip) = found[first]
789 snippets.append (Substring (s, index, start))
790 snippets.append (snip)
792 index = start + len (snip.match.group (0))
796 def filter_pipe (input, cmd):
798 ly.progress (_ ("Opening filter `%s\'") % cmd)
800 stdin, stdout, stderr = os.popen3 (cmd)
802 status = stdin.close ()
806 output = stdout.read ()
807 status = stdout.close ()
808 error = stderr.read ()
812 signal = 0x0f & status
813 if status or (not output and error):
814 exit_status = status >> 8
815 ly.error (_ ("`%s\' failed (%d)") % (cmd, exit_status))
816 ly.error (_ ("The error log is as follows:"))
817 sys.stderr.write (error)
818 sys.stderr.write (stderr.read ())
827 return filter_pipe (s, filter_cmd)
829 def is_derived_class (cl, baseclass):
832 for b in cl.__bases__:
833 if is_derived_class (b, baseclass):
838 def process_snippets (cmd, ly_snippets, png_snippets):
839 ly_names = filter (lambda x: x, map (Lilypond_snippet.basename, ly_snippets))
840 png_names = filter (lambda x: x, map (Lilypond_snippet.basename, png_snippets))
845 status = ly.system (string.join ([cmd] + ly_names),
846 ignore_error = 1, progress_p = 1)
850 ly.error( 'Process %s exited unsuccessfully.' % cmd )
853 if format == HTML or format == TEXINFO:
855 if not os.path.exists (i + '.eps') and os.path.exists (i + '.tex'):
857 ly.make_ps_images (i + '.eps', resolution=110)
859 # elif os.path.exists (i + '.ps'):
860 # ly.make_ps_images (i + '.ps', resolution=110)
863 LATEX_DOCUMENT = r'''
866 \typeout{textwidth=\the\textwidth}
867 \typeout{columnsep=\the\columnsep}
868 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
871 #need anything else besides textwidth?
872 def get_latex_textwidth (source):
873 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
874 preamble = source[:m.start (0)]
875 latex_document = LATEX_DOCUMENT % vars ()
876 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
879 m = re.search ('columns=([0-9.]*)', parameter_string)
881 columns = string.atoi (m.group (1))
884 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
886 columnsep = string.atof (m.group (1))
889 m = re.search('textwidth=([0-9.]*)pt', parameter_string)
891 textwidth = string.atof (m.group (1))
893 textwidth = (textwidth - columnsep) / columns
905 '.texinfo' : TEXINFO,
911 #TEXINFO: '.texinfo',
919 def do_process_cmd (chunks):
920 ly_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
921 and x.ly_is_outdated (), chunks)
922 png_outdated = filter (lambda x: is_derived_class (x.__class__, Lilypond_snippet) \
923 and x.png_is_outdated (), chunks)
925 ly.progress (_ ("Writing snippets..."))
926 map (Lilypond_snippet.write_ly, ly_outdated)
930 ly.progress (_ ("Processing..."))
931 process_snippets (process_cmd, ly_outdated, png_outdated)
933 ly.progress (_ ("All snippets are up to date..."))
937 def do_file (input_filename):
941 e = os.path.splitext (input_filename)[1]
942 if e in ext2format.keys ():
944 format = ext2format[e]
946 ly.error (_ ("cannot determine format for: %s" \
950 if not input_filename or input_filename == '-':
951 in_handle = sys.stdin
952 input_fullname = '<stdin>'
954 if os.path.exists (input_filename):
955 input_fullname = input_filename
956 elif format == LATEX:
957 # urg python interface to libkpathsea?
958 input_fullname = ly.read_pipe ('kpsewhich '
959 + input_filename)[:-1]
961 input_fullname = find_file (input_filename)
962 in_handle = open (input_fullname)
964 if input_filename == '-':
967 input_base = os.path.basename \
968 (os.path.splitext (input_filename)[0])
970 # only default to stdout when filtering
971 if output_name == '-' or (not output_name and filter_cmd):
972 output_filename = '-'
973 output_file = sys.stdout
976 output_filename = input_base + format2ext[format]
978 if not os.path.isdir (output_name):
979 os.mkdir (output_name, 0777)
980 output_filename = (output_name
982 + format2ext[format])
985 if (os.path.exists (input_filename) and
986 os.path.exists (output_filename) and
987 os.path.samefile (output_filename, input_fullname)):
988 ly.error (_("Output would overwrite input file; use --output."))
991 output_file = open (output_filename, 'w')
993 os.chdir (output_name)
995 ly.progress (_ ("Reading %s...") % input_fullname)
996 source = in_handle.read ()
999 # FIXME: containing blocks must be first, see find_toplevel_snippets
1001 'multiline_comment',
1005 'singleline_comment',
1009 ly.progress (_ ("Dissecting..."))
1010 chunks = find_toplevel_snippets (source, snippet_types)
1013 global default_ly_options
1015 if not default_ly_options.has_key (LINEWIDTH):
1017 textwidth = get_latex_textwidth (source)
1018 default_ly_options[LINEWIDTH] = '''%.0f\\pt''' \
1020 elif format == TEXINFO:
1021 for (k, v) in texinfo_linewidths.items ():
1022 # FIXME: @layout is usually not in chunk #0:
1023 # \input texinfo @c -*-texinfo-*-
1024 # bluntly search first K of source
1025 # s = chunks[0].replacement_text ()
1026 if re.search (k, source[:1024]):
1027 default_ly_options[LINEWIDTH] = v
1031 output_file.writelines ([c.filter_text () for c in chunks])
1035 do_process_cmd (chunks)
1036 ly.progress (_ ("Compiling %s...") % output_filename)
1037 output_file.writelines ([s.replacement_text () \
1041 def process_include (snippet):
1042 os.chdir (original_dir)
1043 name = snippet.substring ('filename')
1044 ly.progress (_ ('Processing include: %s') % name)
1048 map (process_include,
1049 filter (lambda x: is_derived_class (x.__class__, Include_snippet), chunks))
1050 except Compile_error:
1051 os.chdir (original_dir)
1052 ly.progress (_('Removing `%s\'') % output_filename)
1055 os.unlink (output_filename)
1060 global format, output_name
1061 global filter_cmd, process_cmd, verbose_p
1063 (sh, long) = ly.getopt_args (option_definitions)
1065 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1066 except getopt.error, s:
1067 sys.stderr.write ('\n')
1068 ly.error (_ ("getopt says: `%s\'" % s))
1069 sys.stderr.write ('\n')
1079 elif o == '--filter' or o == '-F':
1082 elif o == '--format' or o == '-f':
1084 if a == 'texi-html' or a == 'texi':
1086 elif o == '--help' or o == '-h':
1089 elif o == '--include' or o == '-I':
1090 include_path.append (os.path.join (original_dir,
1092 elif o == '--output' or o == '-o':
1094 elif o == '--outdir':
1096 elif o == '--process' or o == '-P':
1099 elif o == '--version' or o == '-v':
1100 ly.identify (sys.stdout)
1102 elif o == '--verbose' or o == '-V':
1104 elif o == '--warranty' or o == '-w':
1111 files = do_options ()
1113 if process_cmd == '':
1114 process_cmd = lilypond_binary + " -f tex "
1117 process_cmd += string.join ([(' -I %s' % p)
1118 for p in include_path])
1120 ly.identify (sys.stderr)
1121 ly.setup_environment ()
1125 except Compile_error:
1128 if __name__ == '__main__':