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 -b ps?
19 * check latex parameters, twocolumn, multicolumn?
20 * use --png --ps --pdf for making images?
22 * Converting from lilypond-book source, substitute:
23 @mbinclude foo.itely -> @include foo.itely
33 # Users of python modules should include this snippet
34 # and customize variables below.
36 # We'll suffer this path initialization stuff as long as we don't install
37 # our python packages in <prefix>/lib/pythonX.Y (and don't kludge around
38 # it as we do with teTeX on Red Hat Linux: set some environment variables
39 # (PYTHONPATH) in `etc/profile').
41 # If set, LILYPONDPREFIX must take prevalence.
42 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
43 import getopt, os, sys
44 datadir = '@local_lilypond_datadir@'
45 if not os.path.isdir (datadir):
46 datadir = '@lilypond_datadir@'
47 if os.environ.has_key ('LILYPONDPREFIX'):
48 datadir = os.environ['LILYPONDPREFIX']
49 while datadir[-1] == os.sep:
52 sys.path.insert (0, os.path.join (datadir, 'python'))
55 #if __name__ == '__main__':
62 program_version = '@TOPLEVEL_VERSION@'
63 program_name = sys.argv[0]
66 original_dir = os.getcwd ()
70 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
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 -I include' BOOK
78 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
79 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
81 option_definitions = [
82 (_ ("EXT"), 'f', 'format',
83 _ ('''use output format EXT (texi [default], texi-html,
85 (_ ("FILTER"), 'F', 'filter',
86 _ ("pipe snippets through FILTER [convert-ly -n -]")),
88 _ ("print this help")),
89 (_ ("DIR"), 'I', 'include',
90 _ ("add DIR to include path")),
91 (_ ("DIR"), 'o', 'output',
92 _ ("write output to DIR")),
93 (_ ("COMMAND"), 'P', 'process',
94 _ ("process ly_files using COMMAND FILE...")),
98 _ ("print version information")),
100 _ ("show warranty and copyright")),
103 include_path = [ly.abspath (os.getcwd ())]
104 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
106 # Only use installed binary when we are installed too.
107 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
108 lilypond_binary = 'lilypond'
113 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
116 default_ly_options = {}
119 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
123 EXAMPLEINDENT = 'exampleindent'
125 FRAGMENT = 'fragment'
130 LINEWIDTH = 'linewidth'
131 NOFRAGMENT = 'nofragment'
132 NOINDENT = 'noindent'
137 OUTPUTIMAGE = 'outputimage'
139 PREAMBLE = 'preamble'
140 PRINTFILENAME = 'printfilename'
142 RAGGEDRIGHT = 'raggedright'
143 RELATIVE = 'relative'
144 STAFFSIZE = 'staffsize'
147 VERBATIM = 'verbatim'
149 # NOTIME has no opposite so it isn't part of this dictionary.
150 # NOQUOTE is used internally only.
152 NOFRAGMENT: FRAGMENT,
156 # Recognize special sequences in the input.
158 # (?P<name>regex) -- Assign result of REGEX to NAME.
159 # *? -- Match non-greedily.
160 # (?m) -- Multiline regex: Make ^ and $ match at each line.
161 # (?s) -- Make the dot match all characters including newline.
162 # (?x) -- Ignore whitespace in patterns.
174 (\s*(?P<options>.*?)\s*:)?\s*
182 \s*(?P<options>.*?)\s*
191 \s*(?P<options>.*?)\s*
193 \s*(?P<filename>.*?)\s*
200 (?P<code><!--\s.*?!-->)
203 'singleline_comment':
209 (?P<code><pre>.*?</pre>))''',
215 (?P<code><pre>\s.*?</pre>\s))''',
234 \s*(?P<options>.*?)\s*
245 \s*(?P<options>.*?)\s*
249 \\end\s*{lilypond})''',
257 \s*(?P<options>.*?)\s*
265 'singleline_comment':
288 \\end\s*{verbatim}))''',
297 (?P<filename>\S+))''',
301 ^[^\n]*?(?!@c\s+)[^\n]*?
305 \s*(?P<options>.*?)\s*
315 \s*(?P<options>.*?)\s*
318 ^@end\s+lilypond)\s''',
325 \s*(?P<options>.*?)\s*
336 @end\s+ignore))\s''',
338 'singleline_comment':
343 @c([ \t][^\n]*|)\n))''',
345 # Don't do this: It interferes with @code{@{}.
346 # 'verb': r'''(?P<code>@code{.*?})''',
354 @end\s+example\s))''',
360 'intertext': r',?\s*intertext=\".*?\"',
365 'intertext': r',?\s*intertext=\".*?\"',
366 'option_sep': '\s*,\s*',
370 'intertext': r',?\s*intertext=\".*?\"',
371 'option_sep': '\s*,\s*',
375 # Options without a pattern in ly_options.
389 RELATIVE: r'''\relative c%(relative_quotes)s''',
394 INDENT: r'''indent = %(indent)s''',
396 LINEWIDTH: r'''linewidth = %(linewidth)s''',
398 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
400 RAGGEDRIGHT: r'''raggedright = ##t''',
405 NOTIME: r'''\context {
407 \remove Time_signature_engraver
413 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
420 FILTER: r'''<lilypond %(options)s>
430 <a href="%(base)s.ly">''',
433 <img align="center" valign="center"
434 border="0" src="%(image)s" alt="[image of music]">''',
436 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
438 QUOTE: r'''<blockquote>
452 \ifx\preLilyPondExample \undefined
457 \def\lilypondbook{}%%
458 \input %(base)s-systems.tex
459 \ifx\postLilyPondExample \undefined
466 PRINTFILENAME: '''\\texttt{%(filename)s}
469 QUOTE: r'''\begin{quotation}
474 VERBATIM: r'''\noindent
476 %(verb)s\end{verbatim}
479 FILTER: r'''\begin{lilypond}[%(options)s]
486 FILTER: r'''@lilypond[%(options)s]
492 @include %(base)s-systems.texi
495 OUTPUTIMAGE: r'''@noindent
497 @image{%(base)s,,,[image of music],%(ext)s}
501 PRINTFILENAME: '''@file{%(filename)s}
504 QUOTE: r'''@quotation
505 %(str)s@end quotation
512 VERBATIM: r'''@exampleindent 0
519 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
520 %%%% Options: [%(option_string)s]
522 #(set! toplevel-score-handler ly:parser-print-score)
523 #(set! toplevel-music-handler (lambda (p m)
524 (ly:parser-print-score
525 p (ly:music-scorify m p))))
527 #(define version-seen? #t)
531 #(define dump-extents #t)
543 %% ly snippet contents follows:
555 texinfo_linewidths = {
556 '@afourpaper': '160\\mm',
557 '@afourwide': '6.5\\in',
558 '@afourlatex': '150\\mm',
559 '@smallbook': '5\\in',
560 '@letterpaper': '6\\in',
563 def classic_lilypond_book_compatibility (key, value):
564 if key == 'singleline' and value == None:
565 return (RAGGEDRIGHT, None)
567 m = re.search ('relative\s*([-0-9])', key)
569 return ('relative', m.group (1))
571 m = re.match ('([0-9]+)pt', key)
573 return ('staffsize', m.group (1))
575 if key == 'indent' or key == 'linewidth':
576 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
578 f = float (m.group (1))
579 return (key, '%f\\%s' % (f, m.group (2)))
583 def compose_ly (code, options, type):
587 if string.find (i, '=') > 0:
588 (key, value) = re.split ('\s*=\s*', i)
589 option_dict[key] = value
591 if i in no_options.keys ():
592 if no_options[i] in option_dict.keys ():
593 del option_dict[no_options[i]]
595 option_dict[i] = None
597 has_linewidth = option_dict.has_key (LINEWIDTH)
598 no_linewidth_value = 0
600 # If LINEWIDTH is used without parameter, set it to default.
601 if has_linewidth and option_dict[LINEWIDTH] == None:
602 no_linewidth_value = 1
603 del option_dict[LINEWIDTH]
605 for i in default_ly_options.keys ():
606 if i not in option_dict.keys ():
607 option_dict[i] = default_ly_options[i]
609 if not has_linewidth:
610 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
611 option_dict[RAGGEDRIGHT] = None
613 if type == 'lilypond':
614 if LINEWIDTH in option_dict.keys ():
615 del option_dict[LINEWIDTH]
617 if RAGGEDRIGHT in option_dict.keys ():
618 if LINEWIDTH in option_dict.keys ():
619 del option_dict[LINEWIDTH]
621 if QUOTE in option_dict.keys () or type == 'lilypond':
622 if LINEWIDTH in option_dict.keys ():
623 del option_dict[LINEWIDTH]
625 if not INDENT in option_dict.keys ():
626 option_dict[INDENT] = '0\\mm'
628 # The QUOTE pattern from ly_options only emits the `linewidth'
630 if has_linewidth and QUOTE in option_dict.keys ():
631 if no_linewidth_value:
632 del option_dict[LINEWIDTH]
634 del option_dict[QUOTE]
636 if FRAGMENT in option_dict.keys ():
644 # The original concept of the `exampleindent' option is broken.
645 # It is not possible to get a sane value for @exampleindent at all
646 # without processing the document itself. Saying
654 # causes ugly results with the DVI backend of texinfo since the
655 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
656 # value). Executing the above code changes the environment
657 # indentation to an unknown value because we don't know the amount
658 # of 1em in advance since it is font-dependent. Modifying
659 # @exampleindent in the middle of a document is simply not
660 # supported within texinfo.
662 # As a consequence, the only function of @exampleindent is now to
663 # specify the amount of indentation for the `quote' option.
665 # To set @exampleindent locally to zero, we use the @format
666 # environment for non-quoted snippets.
667 override[EXAMPLEINDENT] = r'0.4\in'
668 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
669 override.update (default_ly_options)
672 for (key, value) in option_dict.items ():
674 option_list.append (key)
676 option_list.append (key + '=' + value)
677 option_string = string.join (option_list, ',')
680 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
681 for a in compose_types:
684 for (key, value) in option_dict.items():
686 classic_lilypond_book_compatibility (key, value)
690 (_ ("deprecated ly-option used: %s=%s" \
693 (_ ("compatibility mode translation: %s=%s" \
697 (_ ("deprecated ly-option used: %s" \
700 (_ ("compatibility mode translation: %s" \
703 (key, value) = (c_key, c_value)
706 override[key] = value
708 if not override.has_key (key):
712 for type in compose_types:
713 if ly_options[type].has_key (key):
714 compose_dict[type].append (ly_options[type][key])
718 if not found and key not in simple_options:
719 ly.warning (_ ("ignoring unknown ly option: %s") % i)
722 if RELATIVE in override.keys () and override[RELATIVE]:
723 relative = string.atoi (override[RELATIVE])
729 relative_quotes += ',' * (- relative)
731 relative_quotes += "'" * relative
733 program_name = __main__.program_name
736 string.join (compose_dict[PAPER], '\n ') % override
738 string.join (compose_dict[LAYOUT], '\n ') % override
740 string.join (compose_dict[NOTES], '\n ') % vars ()
742 string.join (compose_dict[PREAMBLE], '\n ') % override
744 return (PREAMBLE_LY + body) % vars ()
747 def find_file (name):
748 for i in include_path:
749 full = os.path.join (i, name)
750 if os.path.exists (full):
752 ly.error (_ ("file not found: %s") % name + '\n')
756 def verbatim_html (s):
757 return re.sub ('>', '>',
759 re.sub ('&', '&', s)))
761 def verbatim_texinfo (s):
762 return re.sub ('{', '@{',
764 re.sub ('@', '@@', s)))
766 def split_options (option_string):
767 return re.split (format_res[format]['option_sep'], option_string)
770 def replacement_text (self):
773 def filter_text (self):
774 return self.replacement_text ()
776 def ly_is_outdated (self):
779 def png_is_outdated (self):
782 class Substring (Chunk):
783 def __init__ (self, source, start, end):
788 def replacement_text (self):
789 return self.source[self.start:self.end]
791 class Snippet (Chunk):
792 def __init__ (self, type, match, format):
799 def replacement_text (self):
800 return self.match.group ('match')
802 def substring (self, s):
803 return self.match.group (s)
806 return `self.__class__` + ' type = ' + self.type
808 class Include_snippet (Snippet):
809 def processed_filename (self):
810 f = self.substring ('filename')
811 return os.path.splitext (f)[0] + format2ext[format]
813 def replacement_text (self):
814 s = self.match.group ('match')
815 f = self.substring ('filename')
817 return re.sub (f, self.processed_filename (), s)
819 class Lilypond_snippet (Snippet):
820 def __init__ (self, type, match, format):
821 Snippet.__init__ (self, type, match, format)
822 os = match.group ('options')
824 self.options = split_options (os)
827 return self.substring ('code')
832 return compose_ly (s, self.options, self.type)
838 self.hash = abs (hash (self.full_ly ()))
843 return 'lily-%d' % self.get_hash ()
847 outf = open (self.basename () + '.ly', 'w')
848 outf.write (self.full_ly ())
850 open (self.basename () + '.txt', 'w').write ('image of music')
852 def ly_is_outdated (self):
853 base = self.basename ()
855 tex_file = '%s.tex' % base
856 eps_file = '%s.eps' % base
857 system_file = '%s-systems.tex' % base
858 ly_file = '%s.ly' % base
859 ok = os.path.exists (ly_file) \
860 and os.path.exists (system_file)\
861 and os.stat (system_file)[stat.ST_SIZE] \
862 and re.match ('% eof', open (system_file).readlines ()[-1])
863 if ok and (use_hash_p \
864 or self.ly () == open (ly_file).read ()):
865 # TODO: Do something smart with target formats
866 # (ps, png) and m/ctimes.
870 def png_is_outdated (self):
871 base = self.basename ()
872 ok = self.ly_is_outdated ()
873 if format == HTML or format == TEXINFO:
874 ok = ok and (os.path.exists (base + '.png')
875 or glob.glob (base + '-page*.png'))
877 def texstr_is_outdated (self):
881 base = self.basename ()
882 ok = self.ly_is_outdated ()
883 ok = ok and (os.path.exists (base + '.texstr'))
886 def filter_text (self):
887 code = self.substring ('code')
888 s = run_filter (code)
891 'options': self.match.group ('options')
894 return output[self.format][FILTER] % d
896 def replacement_text (self):
897 func = Lilypond_snippet.__dict__['output_' + self.format]
900 def get_images (self):
901 base = self.basename ()
903 single = '%(base)s.png' % vars ()
904 multiple = '%(base)s-page1.png' % vars ()
906 if os.path.exists (multiple) \
907 and (not os.path.exists (single) \
908 or (os.stat (multiple)[stat.ST_MTIME] \
909 > os.stat (single)[stat.ST_MTIME])):
910 images = glob.glob ('%(base)s-page*.png' % vars ())
913 def output_html (self):
915 base = self.basename ()
917 str += self.output_print_filename (HTML)
918 if VERBATIM in self.options:
919 verb = verbatim_html (self.substring ('code'))
920 str += write (output[HTML][VERBATIM] % vars ())
921 if QUOTE in self.options:
922 str = output[HTML][QUOTE] % vars ()
924 str += output[HTML][BEFORE] % vars ()
925 for image in self.get_images ():
926 (base, ext) = os.path.splitext (image)
927 str += output[HTML][OUTPUT] % vars ()
928 str += output[HTML][AFTER] % vars ()
931 def output_info (self):
933 for image in self.get_images ():
934 (base, ext) = os.path.splitext (image)
936 # URG, makeinfo implicitly prepends dot to extension.
937 # Specifying no extension is most robust.
939 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
941 base = self.basename()
942 str += output[format][OUTPUT] % vars()
945 def output_latex (self):
947 base = self.basename ()
949 str += self.output_print_filename (LATEX)
950 if VERBATIM in self.options:
951 verb = self.substring ('code')
952 str += (output[LATEX][VERBATIM] % vars ())
953 if QUOTE in self.options:
954 str = output[LATEX][QUOTE] % vars ()
956 str += (output[LATEX][OUTPUT] % vars ())
959 def output_print_filename (self, format):
961 if PRINTFILENAME in self.options:
962 base = self.basename ()
963 filename = self.substring ('filename')
964 str = output[format][PRINTFILENAME] % vars ()
968 def output_texinfo (self):
970 if self.output_print_filename (TEXINFO):
972 + self.output_print_filename (HTML)
975 + self.output_print_filename (LATEX)
977 base = self.basename ()
978 if TEXIDOC in self.options:
979 texidoc = base + '.texidoc'
980 if os.path.exists (texidoc):
981 str += '@include %(texidoc)s\n\n' % vars ()
983 if VERBATIM in self.options:
984 verb = verbatim_texinfo (self.substring ('code'))
985 str += (output[TEXINFO][VERBATIM] % vars ())
986 if not QUOTE in self.options:
987 str = output[TEXINFO][NOQUOTE] % vars()
989 str += self.output_info ()
991 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
992 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
993 # str += ('@html\n' + self.output_html () + '\n@end html\n')
995 if QUOTE in self.options:
996 str = output[TEXINFO][QUOTE] % vars ()
998 # need par after image
1003 class Lilypond_file_snippet (Lilypond_snippet):
1005 name = self.substring ('filename')
1006 return '\\renameinput \"%s\"\n%s' \
1007 % (name, open (find_file (name)).read ())
1009 snippet_type_to_class = {
1010 'lilypond_file': Lilypond_file_snippet,
1011 'lilypond_block': Lilypond_snippet,
1012 'lilypond': Lilypond_snippet,
1013 'include': Include_snippet,
1016 def find_toplevel_snippets (s, types):
1019 res[i] = ly.re.compile (snippet_res[format][i])
1023 ## found = dict (map (lambda x: (x, None),
1027 map (lambda x, f = found: f.setdefault (x, None),
1030 # We want to search for multiple regexes, without searching
1031 # the string multiple times for one regex.
1032 # Hence, we use earlier results to limit the string portion
1034 # Since every part of the string is traversed at most once for
1035 # every type of snippet, this is linear.
1041 if not found[type] or found[type][0] < index:
1043 m = res[type].search (s[index:endex])
1048 if snippet_type_to_class.has_key (type):
1049 cl = snippet_type_to_class[type]
1050 snip = cl (type, m, format)
1051 start = index + m.start ('match')
1052 found[type] = (start, snip)
1056 or found[type][0] < found[first][0]):
1061 # Limiting the search space is a cute
1062 # idea, but this *requires* to search
1063 # for possible containing blocks
1064 # first, at least as long as we do not
1065 # search for the start of blocks, but
1066 # always/directly for the entire
1067 # @block ... @end block.
1069 endex = found[first][0]
1072 snippets.append (Substring (s, index, len (s)))
1075 (start, snip) = found[first]
1076 snippets.append (Substring (s, index, start))
1077 snippets.append (snip)
1079 index = start + len (snip.match.group ('match'))
1083 def filter_pipe (input, cmd):
1085 ly.progress (_ ("Opening filter `%s'") % cmd)
1087 (stdin, stdout, stderr) = os.popen3 (cmd)
1089 status = stdin.close ()
1093 output = stdout.read ()
1094 status = stdout.close ()
1095 error = stderr.read ()
1099 signal = 0x0f & status
1100 if status or (not output and error):
1101 exit_status = status >> 8
1102 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1103 ly.error (_ ("The error log is as follows:"))
1104 sys.stderr.write (error)
1105 sys.stderr.write (stderr.read ())
1114 return filter_pipe (s, filter_cmd)
1116 def is_derived_class (cl, baseclass):
1119 for b in cl.__bases__:
1120 if is_derived_class (b, baseclass):
1124 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1125 ly_names = filter (lambda x: x,
1126 map (Lilypond_snippet.basename, ly_snippets))
1127 texstr_names = filter (lambda x: x,
1128 map (Lilypond_snippet.basename, texstr_snippets))
1129 png_names = filter (lambda x: x,
1130 map (Lilypond_snippet.basename, png_snippets))
1133 def my_system (cmd):
1134 status = ly.system (cmd,
1135 ignore_error = 1, progress_p = 1)
1138 ly.error ('Process %s exited unsuccessfully.' % cmd)
1142 # the --process=CMD switch is a bad idea
1143 # it is too generic for lilypond-book.
1144 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1146 my_system (string.join ([cmd + ' --backend texstr ' ] + texstr_names))
1147 for l in texstr_names:
1148 my_system ('latex %s.texstr' % l)
1151 my_system (string.join ([cmd] + ly_names))
1153 LATEX_DOCUMENT = r'''
1156 \typeout{textwidth=\the\textwidth}
1157 \typeout{columnsep=\the\columnsep}
1158 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1162 # Do we need anything else besides `textwidth'?
1163 def get_latex_textwidth (source):
1164 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1165 preamble = source[:m.start (0)]
1166 latex_document = LATEX_DOCUMENT % vars ()
1167 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1170 m = re.search ('columns=([0-9.]*)', parameter_string)
1172 columns = string.atoi (m.group (1))
1175 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1177 columnsep = string.atof (m.group (1))
1180 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1182 textwidth = string.atof (m.group (1))
1184 textwidth = (textwidth - columnsep) / columns
1196 '.texinfo': TEXINFO,
1202 # TEXINFO: '.texinfo',
1207 class Compile_error:
1210 def do_process_cmd (chunks):
1212 filter (lambda x: is_derived_class (x.__class__,
1214 and x.ly_is_outdated (),
1217 filter (lambda x: is_derived_class (x.__class__,
1219 and x.texstr_is_outdated (),
1222 filter (lambda x: is_derived_class (x.__class__,
1224 and x.png_is_outdated (),
1227 ly.progress (_ ("Writing snippets..."))
1228 map (Lilypond_snippet.write_ly, ly_outdated)
1232 ly.progress (_ ("Processing...\n"))
1233 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1235 ly.progress (_ ("All snippets are up to date..."))
1238 def guess_format (input_filename):
1240 e = os.path.splitext (input_filename)[1]
1241 if e in ext2format.keys ():
1243 format = ext2format[e]
1245 ly.error (_ ("cannot determine format for: %s" \
1250 def do_file (input_filename):
1252 if not input_filename or input_filename == '-':
1253 in_handle = sys.stdin
1254 input_fullname = '<stdin>'
1256 if os.path.exists (input_filename):
1257 input_fullname = input_filename
1258 elif format == LATEX:
1259 # urg python interface to libkpathsea?
1260 input_fullname = ly.read_pipe ('kpsewhich '
1261 + input_filename)[:-1]
1263 input_fullname = find_file (input_filename)
1264 in_handle = open (input_fullname)
1266 if input_filename == '-':
1267 input_base = 'stdin'
1269 input_base = os.path.basename \
1270 (os.path.splitext (input_filename)[0])
1272 # Only default to stdout when filtering.
1273 if output_name == '-' or (not output_name and filter_cmd):
1274 output_filename = '-'
1275 output_file = sys.stdout
1278 output_filename = input_base + format2ext[format]
1280 if not os.path.isdir (output_name):
1281 os.mkdir (output_name, 0777)
1282 output_filename = (output_name
1284 + format2ext[format])
1286 if os.path.exists (input_filename) \
1287 and os.path.exists (output_filename) \
1288 and os.path.samefile (output_filename, input_fullname):
1290 _ ("Output would overwrite input file; use --output."))
1293 output_file = open (output_filename, 'w')
1295 os.chdir (output_name)
1297 ly.progress (_ ("Reading %s...") % input_fullname)
1298 source = in_handle.read ()
1301 # FIXME: Containing blocks must be first, see
1302 # find_toplevel_snippets.
1304 'multiline_comment',
1308 'singleline_comment',
1313 ly.progress (_ ("Dissecting..."))
1314 chunks = find_toplevel_snippets (source, snippet_types)
1317 global default_ly_options
1319 if not default_ly_options.has_key (LINEWIDTH):
1321 textwidth = get_latex_textwidth (source)
1322 default_ly_options[LINEWIDTH] = \
1323 '''%.0f\\pt''' % textwidth
1324 elif format == TEXINFO:
1325 for (k, v) in texinfo_linewidths.items ():
1326 # FIXME: @layout is usually not in
1329 # \input texinfo @c -*-texinfo-*-
1331 # Bluntly search first K items of
1333 # s = chunks[0].replacement_text ()
1334 if re.search (k, source[:1024]):
1335 default_ly_options[LINEWIDTH] = v
1339 output_file.writelines ([c.filter_text () \
1343 do_process_cmd (chunks)
1344 ly.progress (_ ("Compiling %s...") % output_filename)
1345 output_file.writelines ([s.replacement_text () \
1349 def process_include (snippet):
1350 os.chdir (original_dir)
1351 name = snippet.substring ('filename')
1352 ly.progress (_ ("Processing include: %s") % name)
1356 map (process_include,
1357 filter (lambda x: is_derived_class (x.__class__,
1360 except Compile_error:
1361 os.chdir (original_dir)
1362 ly.progress (_ ("Removing `%s'") % output_filename)
1365 os.unlink (output_filename)
1369 global format, output_name
1370 global filter_cmd, process_cmd, verbose_p
1372 (sh, long) = ly.getopt_args (option_definitions)
1374 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1375 except getopt.error, s:
1376 sys.stderr.write ('\n')
1377 ly.error (_ ("getopt says: `%s'" % s))
1378 sys.stderr.write ('\n')
1388 elif o == '--filter' or o == '-F':
1391 elif o == '--format' or o == '-f':
1393 if a == 'texi-html' or a == 'texi':
1395 elif o == '--tex-backend ':
1397 elif o == '--help' or o == '-h':
1400 elif o == '--include' or o == '-I':
1401 include_path.append (os.path.join (original_dir,
1403 elif o == '--output' or o == '-o':
1405 elif o == '--outdir':
1407 elif o == '--process' or o == '-P':
1410 elif o == '--version' or o == '-v':
1411 ly.identify (sys.stdout)
1413 elif o == '--verbose' or o == '-V':
1415 elif o == '--warranty' or o == '-w':
1422 files = do_options ()
1424 ly.warning ("Need to have command line option")
1428 global process_cmd, format
1429 format = guess_format (files[0])
1432 if format == TEXINFO:
1434 if process_cmd == '':
1435 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1438 process_cmd += string.join ([(' -I %s' % p)
1439 for p in include_path])
1441 ly.identify (sys.stderr)
1442 ly.setup_environment ()
1446 except Compile_error:
1450 if __name__ == '__main__':