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'
140 PREAMBLE = 'preamble'
141 PRINTFILENAME = 'printfilename'
143 RAGGEDRIGHT = 'raggedright'
144 RELATIVE = 'relative'
145 STAFFSIZE = 'staffsize'
148 VERBATIM = 'verbatim'
149 FONTLOAD = 'fontload'
152 # NOTIME has no opposite so it isn't part of this dictionary.
153 # NOQUOTE is used internally only.
155 NOFRAGMENT: FRAGMENT,
159 # Recognize special sequences in the input.
161 # (?P<name>regex) -- Assign result of REGEX to NAME.
162 # *? -- Match non-greedily.
163 # (?m) -- Multiline regex: Make ^ and $ match at each line.
164 # (?s) -- Make the dot match all characters including newline.
165 # (?x) -- Ignore whitespace in patterns.
177 (\s*(?P<options>.*?)\s*:)?\s*
185 \s*(?P<options>.*?)\s*
194 \s*(?P<options>.*?)\s*
196 \s*(?P<filename>.*?)\s*
203 (?P<code><!--\s.*?!-->)
206 'singleline_comment':
212 (?P<code><pre>.*?</pre>))''',
218 (?P<code><pre>\s.*?</pre>\s))''',
237 \s*(?P<options>.*?)\s*
248 \s*(?P<options>.*?)\s*
252 \\end\s*{lilypond})''',
260 \s*(?P<options>.*?)\s*
268 'singleline_comment':
291 \\end\s*{verbatim}))''',
300 (?P<filename>\S+))''',
304 ^[^\n]*?(?!@c\s+)[^\n]*?
308 \s*(?P<options>.*?)\s*
318 \s*(?P<options>.*?)\s*
321 ^@end\s+lilypond)\s''',
328 \s*(?P<options>.*?)\s*
339 @end\s+ignore))\s''',
341 'singleline_comment':
346 @c([ \t][^\n]*|)\n))''',
348 # Don't do this: It interferes with @code{@{}.
349 # 'verb': r'''(?P<code>@code{.*?})''',
357 @end\s+example\s))''',
363 'intertext': r',?\s*intertext=\".*?\"',
368 'intertext': r',?\s*intertext=\".*?\"',
369 'option_sep': '\s*,\s*',
373 'intertext': r',?\s*intertext=\".*?\"',
374 'option_sep': '\s*,\s*',
378 # Options without a pattern in ly_options.
393 RELATIVE: r'''\relative c%(relative_quotes)s''',
398 INDENT: r'''indent = %(indent)s''',
400 LINEWIDTH: r'''linewidth = %(linewidth)s''',
402 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
404 RAGGEDRIGHT: r'''raggedright = ##t''',
406 PACKED: r'''packed = ##t''',
411 NOTIME: r'''\context {
413 \remove Time_signature_engraver
419 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
426 FILTER: r'''<lilypond %(options)s>
436 <a href="%(base)s.ly">''',
439 <img align="center" valign="center"
440 border="0" src="%(image)s" alt="[image of music]">''',
442 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
444 QUOTE: r'''<blockquote>
458 \ifx\preLilyPondExample \undefined
463 \def\lilypondbook{}%%
464 \input %(base)s-systems.tex
465 \ifx\postLilyPondExample \undefined
472 PRINTFILENAME: '''\\texttt{%(filename)s}
475 QUOTE: r'''\begin{quotation}
480 VERBATIM: r'''\noindent
482 %(verb)s\end{verbatim}
485 FILTER: r'''\begin{lilypond}[%(options)s]
492 FILTER: r'''@lilypond[%(options)s]
498 @include %(base)s-systems.texi
502 OUTPUTIMAGE: r'''@noindent
504 @image{%(base)s,,,[image of music],%(ext)s}
508 <a href="%(base)s.ly">
509 <img align="center" valign="center"
510 border="0" src="%(image)s" alt="[image of music]">
516 PRINTFILENAME: '''@file{%(filename)s}
519 QUOTE: r'''@quotation
520 %(str)s@end quotation
527 VERBATIM: r'''@exampleindent 0
534 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
535 %%%% Options: [%(option_string)s]
537 #(set! toplevel-score-handler ly:parser-print-score)
538 #(set! toplevel-music-handler (lambda (p m)
539 (ly:parser-print-score
540 p (ly:music-scorify m p))))
542 #(define version-seen? #t)
546 #(define dump-extents #t)
547 %(font_dump_setting)s
559 %% ly snippet contents follows:
571 texinfo_linewidths = {
572 '@afourpaper': '160\\mm',
573 '@afourwide': '6.5\\in',
574 '@afourlatex': '150\\mm',
575 '@smallbook': '5\\in',
576 '@letterpaper': '6\\in',
579 def classic_lilypond_book_compatibility (key, value):
580 if key == 'singleline' and value == None:
581 return (RAGGEDRIGHT, None)
583 m = re.search ('relative\s*([-0-9])', key)
585 return ('relative', m.group (1))
587 m = re.match ('([0-9]+)pt', key)
589 return ('staffsize', m.group (1))
591 if key == 'indent' or key == 'linewidth':
592 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
594 f = float (m.group (1))
595 return (key, '%f\\%s' % (f, m.group (2)))
599 def compose_ly (code, options, type):
603 if string.find (i, '=') > 0:
604 (key, value) = re.split ('\s*=\s*', i)
605 option_dict[key] = value
607 if i in no_options.keys ():
608 if no_options[i] in option_dict.keys ():
609 del option_dict[no_options[i]]
611 option_dict[i] = None
613 has_linewidth = option_dict.has_key (LINEWIDTH)
614 no_linewidth_value = 0
616 # If LINEWIDTH is used without parameter, set it to default.
617 if has_linewidth and option_dict[LINEWIDTH] == None:
618 no_linewidth_value = 1
619 del option_dict[LINEWIDTH]
621 for i in default_ly_options.keys ():
622 if i not in option_dict.keys ():
623 option_dict[i] = default_ly_options[i]
625 if not has_linewidth:
626 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
627 option_dict[RAGGEDRIGHT] = None
629 if type == 'lilypond':
630 if LINEWIDTH in option_dict.keys ():
631 del option_dict[LINEWIDTH]
633 if RAGGEDRIGHT in option_dict.keys ():
634 if LINEWIDTH in option_dict.keys ():
635 del option_dict[LINEWIDTH]
637 if QUOTE in option_dict.keys () or type == 'lilypond':
638 if LINEWIDTH in option_dict.keys ():
639 del option_dict[LINEWIDTH]
641 if not INDENT in option_dict.keys ():
642 option_dict[INDENT] = '0\\mm'
644 # The QUOTE pattern from ly_options only emits the `linewidth'
646 if has_linewidth and QUOTE in option_dict.keys ():
647 if no_linewidth_value:
648 del option_dict[LINEWIDTH]
650 del option_dict[QUOTE]
652 if FRAGMENT in option_dict.keys ():
660 # The original concept of the `exampleindent' option is broken.
661 # It is not possible to get a sane value for @exampleindent at all
662 # without processing the document itself. Saying
670 # causes ugly results with the DVI backend of texinfo since the
671 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
672 # value). Executing the above code changes the environment
673 # indentation to an unknown value because we don't know the amount
674 # of 1em in advance since it is font-dependent. Modifying
675 # @exampleindent in the middle of a document is simply not
676 # supported within texinfo.
678 # As a consequence, the only function of @exampleindent is now to
679 # specify the amount of indentation for the `quote' option.
681 # To set @exampleindent locally to zero, we use the @format
682 # environment for non-quoted snippets.
683 override[EXAMPLEINDENT] = r'0.4\in'
684 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
685 override.update (default_ly_options)
688 for (key, value) in option_dict.items ():
690 option_list.append (key)
692 option_list.append (key + '=' + value)
693 option_string = string.join (option_list, ',')
696 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
697 for a in compose_types:
700 for (key, value) in option_dict.items():
702 classic_lilypond_book_compatibility (key, value)
706 (_ ("deprecated ly-option used: %s=%s" \
709 (_ ("compatibility mode translation: %s=%s" \
713 (_ ("deprecated ly-option used: %s" \
716 (_ ("compatibility mode translation: %s" \
719 (key, value) = (c_key, c_value)
722 override[key] = value
724 if not override.has_key (key):
728 for type in compose_types:
729 if ly_options[type].has_key (key):
730 compose_dict[type].append (ly_options[type][key])
734 if not found and key not in simple_options:
735 ly.warning (_ ("ignoring unknown ly option: %s") % i)
738 if RELATIVE in override.keys () and override[RELATIVE]:
739 relative = string.atoi (override[RELATIVE])
745 relative_quotes += ',' * (- relative)
747 relative_quotes += "'" * relative
749 program_name = __main__.program_name
752 string.join (compose_dict[PAPER], '\n ') % override
754 string.join (compose_dict[LAYOUT], '\n ') % override
756 string.join (compose_dict[NOTES], '\n ') % vars ()
758 string.join (compose_dict[PREAMBLE], '\n ') % override
760 font_dump_setting = ''
761 if FONTLOAD in options:
762 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
764 return (PREAMBLE_LY + body) % vars ()
767 def find_file (name):
768 for i in include_path:
769 full = os.path.join (i, name)
770 if os.path.exists (full):
772 ly.error (_ ("file not found: %s") % name + '\n')
776 def verbatim_html (s):
777 return re.sub ('>', '>',
779 re.sub ('&', '&', s)))
781 def verbatim_texinfo (s):
782 return re.sub ('{', '@{',
784 re.sub ('@', '@@', s)))
786 def split_options (option_string):
787 return re.split (format_res[format]['option_sep'], option_string)
790 def replacement_text (self):
793 def filter_text (self):
794 return self.replacement_text ()
796 def ly_is_outdated (self):
799 def png_is_outdated (self):
802 class Substring (Chunk):
803 def __init__ (self, source, start, end):
808 def replacement_text (self):
809 return self.source[self.start:self.end]
811 class Snippet (Chunk):
812 def __init__ (self, type, match, format):
819 def replacement_text (self):
820 return self.match.group ('match')
822 def substring (self, s):
823 return self.match.group (s)
826 return `self.__class__` + ' type = ' + self.type
828 class Include_snippet (Snippet):
829 def processed_filename (self):
830 f = self.substring ('filename')
831 return os.path.splitext (f)[0] + format2ext[format]
833 def replacement_text (self):
834 s = self.match.group ('match')
835 f = self.substring ('filename')
837 return re.sub (f, self.processed_filename (), s)
839 class Lilypond_snippet (Snippet):
840 def __init__ (self, type, match, format):
841 Snippet.__init__ (self, type, match, format)
842 os = match.group ('options')
844 self.options = split_options (os)
847 return self.substring ('code')
852 return compose_ly (s, self.options, self.type)
858 self.hash = abs (hash (self.full_ly ()))
863 return 'lily-%d' % self.get_hash ()
867 outf = open (self.basename () + '.ly', 'w')
868 outf.write (self.full_ly ())
870 open (self.basename () + '.txt', 'w').write ('image of music')
872 def ly_is_outdated (self):
873 base = self.basename ()
875 tex_file = '%s.tex' % base
876 eps_file = '%s.eps' % base
877 system_file = '%s-systems.tex' % base
878 ly_file = '%s.ly' % base
879 ok = os.path.exists (ly_file) \
880 and os.path.exists (system_file)\
881 and os.stat (system_file)[stat.ST_SIZE] \
882 and re.match ('% eof', open (system_file).readlines ()[-1])
883 if ok and (use_hash_p \
884 or self.ly () == open (ly_file).read ()):
885 # TODO: Do something smart with target formats
886 # (ps, png) and m/ctimes.
890 def png_is_outdated (self):
891 base = self.basename ()
892 ok = self.ly_is_outdated ()
893 if format == HTML or format == TEXINFO:
894 ok = ok and (os.path.exists (base + '.png')
895 or glob.glob (base + '-page*.png'))
897 def texstr_is_outdated (self):
901 base = self.basename ()
902 ok = self.ly_is_outdated ()
903 ok = ok and (os.path.exists (base + '.texstr'))
906 def filter_text (self):
907 code = self.substring ('code')
908 s = run_filter (code)
911 'options': self.match.group ('options')
914 return output[self.format][FILTER] % d
916 def replacement_text (self):
917 func = Lilypond_snippet.__dict__['output_' + self.format]
920 def get_images (self):
921 base = self.basename ()
923 single = '%(base)s.png' % vars ()
924 multiple = '%(base)s-page1.png' % vars ()
926 if os.path.exists (multiple) \
927 and (not os.path.exists (single) \
928 or (os.stat (multiple)[stat.ST_MTIME] \
929 > os.stat (single)[stat.ST_MTIME])):
930 images = glob.glob ('%(base)s-page*.png' % vars ())
933 def output_html (self):
935 base = self.basename ()
937 str += self.output_print_filename (HTML)
938 if VERBATIM in self.options:
939 verb = verbatim_html (self.substring ('code'))
940 str += write (output[HTML][VERBATIM] % vars ())
941 if QUOTE in self.options:
942 str = output[HTML][QUOTE] % vars ()
944 str += output[HTML][BEFORE] % vars ()
945 for image in self.get_images ():
946 (base, ext) = os.path.splitext (image)
947 str += output[HTML][OUTPUT] % vars ()
948 str += output[HTML][AFTER] % vars ()
951 def output_info (self):
953 for image in self.get_images ():
954 (base, ext) = os.path.splitext (image)
956 # URG, makeinfo implicitly prepends dot to extension.
957 # Specifying no extension is most robust.
959 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
961 base = self.basename ()
962 str += output[format][OUTPUT] % vars ()
965 def output_latex (self):
967 base = self.basename ()
969 str += self.output_print_filename (LATEX)
970 if VERBATIM in self.options:
971 verb = self.substring ('code')
972 str += (output[LATEX][VERBATIM] % vars ())
973 if QUOTE in self.options:
974 str = output[LATEX][QUOTE] % vars ()
976 str += (output[LATEX][OUTPUT] % vars ())
979 def output_print_filename (self, format):
981 if PRINTFILENAME in self.options:
982 base = self.basename ()
983 filename = self.substring ('filename')
984 str = output[format][PRINTFILENAME] % vars ()
988 def output_texinfo (self):
990 if self.output_print_filename (TEXINFO):
992 + self.output_print_filename (HTML)
995 + self.output_print_filename (LATEX)
997 base = self.basename ()
998 if TEXIDOC in self.options:
999 texidoc = base + '.texidoc'
1000 if os.path.exists (texidoc):
1001 str += '@include %(texidoc)s\n\n' % vars ()
1003 if VERBATIM in self.options:
1004 verb = verbatim_texinfo (self.substring ('code'))
1005 str += (output[TEXINFO][VERBATIM] % vars ())
1006 if not QUOTE in self.options:
1007 str = output[TEXINFO][NOQUOTE] % vars ()
1009 str += self.output_info ()
1011 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1012 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1013 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1015 if QUOTE in self.options:
1016 str = output[TEXINFO][QUOTE] % vars ()
1018 # need par after image
1023 class Lilypond_file_snippet (Lilypond_snippet):
1025 name = self.substring ('filename')
1026 return '\\renameinput \"%s\"\n%s' \
1027 % (name, open (find_file (name)).read ())
1029 snippet_type_to_class = {
1030 'lilypond_file': Lilypond_file_snippet,
1031 'lilypond_block': Lilypond_snippet,
1032 'lilypond': Lilypond_snippet,
1033 'include': Include_snippet,
1036 def find_toplevel_snippets (s, types):
1039 res[i] = ly.re.compile (snippet_res[format][i])
1043 ## found = dict (map (lambda x: (x, None),
1047 map (lambda x, f = found: f.setdefault (x, None),
1050 # We want to search for multiple regexes, without searching
1051 # the string multiple times for one regex.
1052 # Hence, we use earlier results to limit the string portion
1054 # Since every part of the string is traversed at most once for
1055 # every type of snippet, this is linear.
1061 if not found[type] or found[type][0] < index:
1063 m = res[type].search (s[index:endex])
1068 if snippet_type_to_class.has_key (type):
1069 cl = snippet_type_to_class[type]
1070 snip = cl (type, m, format)
1071 start = index + m.start ('match')
1072 found[type] = (start, snip)
1076 or found[type][0] < found[first][0]):
1081 # Limiting the search space is a cute
1082 # idea, but this *requires* to search
1083 # for possible containing blocks
1084 # first, at least as long as we do not
1085 # search for the start of blocks, but
1086 # always/directly for the entire
1087 # @block ... @end block.
1089 endex = found[first][0]
1092 snippets.append (Substring (s, index, len (s)))
1095 (start, snip) = found[first]
1096 snippets.append (Substring (s, index, start))
1097 snippets.append (snip)
1099 index = start + len (snip.match.group ('match'))
1103 def filter_pipe (input, cmd):
1105 ly.progress (_ ("Opening filter `%s'") % cmd)
1107 (stdin, stdout, stderr) = os.popen3 (cmd)
1109 status = stdin.close ()
1113 output = stdout.read ()
1114 status = stdout.close ()
1115 error = stderr.read ()
1119 signal = 0x0f & status
1120 if status or (not output and error):
1121 exit_status = status >> 8
1122 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1123 ly.error (_ ("The error log is as follows:"))
1124 sys.stderr.write (error)
1125 sys.stderr.write (stderr.read ())
1134 return filter_pipe (s, filter_cmd)
1136 def is_derived_class (cl, baseclass):
1139 for b in cl.__bases__:
1140 if is_derived_class (b, baseclass):
1144 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1145 ly_names = filter (lambda x: x,
1146 map (Lilypond_snippet.basename, ly_snippets))
1147 texstr_names = filter (lambda x: x,
1148 map (Lilypond_snippet.basename, texstr_snippets))
1149 png_names = filter (lambda x: x,
1150 map (Lilypond_snippet.basename, png_snippets))
1153 def my_system (cmd):
1154 status = ly.system (cmd,
1155 ignore_error = 1, progress_p = 1)
1158 ly.error ('Process %s exited unsuccessfully.' % cmd)
1162 # the --process=CMD switch is a bad idea
1163 # it is too generic for lilypond-book.
1164 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1166 my_system (string.join ([cmd + ' --backend texstr ' ] + texstr_names))
1167 for l in texstr_names:
1168 my_system ('latex %s.texstr' % l)
1171 my_system (string.join ([cmd] + ly_names))
1173 LATEX_DOCUMENT = r'''
1176 \typeout{textwidth=\the\textwidth}
1177 \typeout{columnsep=\the\columnsep}
1178 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1182 # Do we need anything else besides `textwidth'?
1183 def get_latex_textwidth (source):
1184 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1185 preamble = source[:m.start (0)]
1186 latex_document = LATEX_DOCUMENT % vars ()
1187 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1190 m = re.search ('columns=([0-9.]*)', parameter_string)
1192 columns = string.atoi (m.group (1))
1195 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1197 columnsep = string.atof (m.group (1))
1200 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1202 textwidth = string.atof (m.group (1))
1204 textwidth = (textwidth - columnsep) / columns
1216 '.texinfo': TEXINFO,
1222 # TEXINFO: '.texinfo',
1227 class Compile_error:
1230 def do_process_cmd (chunks):
1232 filter (lambda x: is_derived_class (x.__class__,
1234 and x.ly_is_outdated (),
1237 filter (lambda x: is_derived_class (x.__class__,
1239 and x.texstr_is_outdated (),
1242 filter (lambda x: is_derived_class (x.__class__,
1244 and x.png_is_outdated (),
1247 ly.progress (_ ("Writing snippets..."))
1248 map (Lilypond_snippet.write_ly, ly_outdated)
1252 ly.progress (_ ("Processing..."))
1254 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1256 ly.progress (_ ("All snippets are up to date..."))
1259 def guess_format (input_filename):
1261 e = os.path.splitext (input_filename)[1]
1262 if e in ext2format.keys ():
1264 format = ext2format[e]
1266 ly.error (_ ("cannot determine format for: %s" \
1271 def do_file (input_filename):
1273 if not input_filename or input_filename == '-':
1274 in_handle = sys.stdin
1275 input_fullname = '<stdin>'
1277 if os.path.exists (input_filename):
1278 input_fullname = input_filename
1279 elif format == LATEX:
1280 # urg python interface to libkpathsea?
1281 input_fullname = ly.read_pipe ('kpsewhich '
1282 + input_filename)[:-1]
1284 input_fullname = find_file (input_filename)
1285 in_handle = open (input_fullname)
1287 if input_filename == '-':
1288 input_base = 'stdin'
1290 input_base = os.path.basename \
1291 (os.path.splitext (input_filename)[0])
1293 # Only default to stdout when filtering.
1294 if output_name == '-' or (not output_name and filter_cmd):
1295 output_filename = '-'
1296 output_file = sys.stdout
1299 output_filename = input_base + format2ext[format]
1301 if not os.path.isdir (output_name):
1302 os.mkdir (output_name, 0777)
1303 output_filename = (output_name
1305 + format2ext[format])
1307 if os.path.exists (input_filename) \
1308 and os.path.exists (output_filename) \
1309 and os.path.samefile (output_filename, input_fullname):
1311 _ ("Output would overwrite input file; use --output."))
1314 output_file = open (output_filename, 'w')
1316 os.chdir (output_name)
1318 ly.progress (_ ("Reading %s...") % input_fullname)
1319 source = in_handle.read ()
1322 # FIXME: Containing blocks must be first, see
1323 # find_toplevel_snippets.
1325 'multiline_comment',
1329 'singleline_comment',
1334 ly.progress (_ ("Dissecting..."))
1335 chunks = find_toplevel_snippets (source, snippet_types)
1338 global default_ly_options
1340 if not default_ly_options.has_key (LINEWIDTH):
1342 textwidth = get_latex_textwidth (source)
1343 default_ly_options[LINEWIDTH] = \
1344 '''%.0f\\pt''' % textwidth
1345 elif format == TEXINFO:
1346 for (k, v) in texinfo_linewidths.items ():
1347 # FIXME: @layout is usually not in
1350 # \input texinfo @c -*-texinfo-*-
1352 # Bluntly search first K items of
1354 # s = chunks[0].replacement_text ()
1355 if re.search (k, source[:1024]):
1356 default_ly_options[LINEWIDTH] = v
1360 output_file.writelines ([c.filter_text () \
1364 do_process_cmd (chunks)
1365 ly.progress (_ ("Compiling %s...") % output_filename)
1366 output_file.writelines ([s.replacement_text () \
1370 def process_include (snippet):
1371 os.chdir (original_dir)
1372 name = snippet.substring ('filename')
1373 ly.progress (_ ("Processing include: %s") % name)
1377 map (process_include,
1378 filter (lambda x: is_derived_class (x.__class__,
1381 except Compile_error:
1382 os.chdir (original_dir)
1383 ly.progress (_ ("Removing `%s'") % output_filename)
1386 os.unlink (output_filename)
1390 global format, output_name
1391 global filter_cmd, process_cmd, verbose_p
1393 (sh, long) = ly.getopt_args (option_definitions)
1395 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1396 except getopt.error, s:
1397 sys.stderr.write ('\n')
1398 ly.error (_ ("getopt says: `%s'" % s))
1399 sys.stderr.write ('\n')
1409 elif o == '--filter' or o == '-F':
1412 elif o == '--format' or o == '-f':
1414 if a == 'texi-html' or a == 'texi':
1416 elif o == '--tex-backend ':
1418 elif o == '--help' or o == '-h':
1421 elif o == '--include' or o == '-I':
1422 include_path.append (os.path.join (original_dir,
1424 elif o == '--output' or o == '-o':
1426 elif o == '--outdir':
1428 elif o == '--process' or o == '-P':
1431 elif o == '--version' or o == '-v':
1432 ly.identify (sys.stdout)
1434 elif o == '--verbose' or o == '-V':
1436 elif o == '--warranty' or o == '-w':
1443 files = do_options ()
1445 ly.warning ("Need to have command line option")
1449 global process_cmd, format
1451 format = guess_format (files[0])
1454 if format == TEXINFO or format == HTML:
1456 if process_cmd == '':
1457 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1460 process_cmd += string.join ([(' -I %s' % p)
1461 for p in include_path])
1463 ly.identify (sys.stderr)
1464 ly.setup_environment ()
1468 except Compile_error:
1472 if __name__ == '__main__':