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'
148 FONTLOAD = 'fontload'
151 # NOTIME has no opposite so it isn't part of this dictionary.
152 # NOQUOTE is used internally only.
154 NOFRAGMENT: FRAGMENT,
158 # Recognize special sequences in the input.
160 # (?P<name>regex) -- Assign result of REGEX to NAME.
161 # *? -- Match non-greedily.
162 # (?m) -- Multiline regex: Make ^ and $ match at each line.
163 # (?s) -- Make the dot match all characters including newline.
164 # (?x) -- Ignore whitespace in patterns.
176 (\s*(?P<options>.*?)\s*:)?\s*
184 \s*(?P<options>.*?)\s*
193 \s*(?P<options>.*?)\s*
195 \s*(?P<filename>.*?)\s*
202 (?P<code><!--\s.*?!-->)
205 'singleline_comment':
211 (?P<code><pre>.*?</pre>))''',
217 (?P<code><pre>\s.*?</pre>\s))''',
236 \s*(?P<options>.*?)\s*
247 \s*(?P<options>.*?)\s*
251 \\end\s*{lilypond})''',
259 \s*(?P<options>.*?)\s*
267 'singleline_comment':
290 \\end\s*{verbatim}))''',
299 (?P<filename>\S+))''',
303 ^[^\n]*?(?!@c\s+)[^\n]*?
307 \s*(?P<options>.*?)\s*
317 \s*(?P<options>.*?)\s*
320 ^@end\s+lilypond)\s''',
327 \s*(?P<options>.*?)\s*
338 @end\s+ignore))\s''',
340 'singleline_comment':
345 @c([ \t][^\n]*|)\n))''',
347 # Don't do this: It interferes with @code{@{}.
348 # 'verb': r'''(?P<code>@code{.*?})''',
356 @end\s+example\s))''',
362 'intertext': r',?\s*intertext=\".*?\"',
367 'intertext': r',?\s*intertext=\".*?\"',
368 'option_sep': '\s*,\s*',
372 'intertext': r',?\s*intertext=\".*?\"',
373 'option_sep': '\s*,\s*',
377 # Options without a pattern in ly_options.
392 RELATIVE: r'''\relative c%(relative_quotes)s''',
397 INDENT: r'''indent = %(indent)s''',
399 LINEWIDTH: r'''linewidth = %(linewidth)s''',
401 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
403 RAGGEDRIGHT: r'''raggedright = ##t''',
408 NOTIME: r'''\context {
410 \remove Time_signature_engraver
416 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
423 FILTER: r'''<lilypond %(options)s>
433 <a href="%(base)s.ly">''',
436 <img align="center" valign="center"
437 border="0" src="%(image)s" alt="[image of music]">''',
439 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
441 QUOTE: r'''<blockquote>
455 \ifx\preLilyPondExample \undefined
460 \def\lilypondbook{}%%
461 \input %(base)s-systems.tex
462 \ifx\postLilyPondExample \undefined
469 PRINTFILENAME: '''\\texttt{%(filename)s}
472 QUOTE: r'''\begin{quotation}
477 VERBATIM: r'''\noindent
479 %(verb)s\end{verbatim}
482 FILTER: r'''\begin{lilypond}[%(options)s]
489 FILTER: r'''@lilypond[%(options)s]
495 @include %(base)s-systems.texi
499 OUTPUTIMAGE: r'''@noindent
501 @image{%(base)s,,,[image of music],%(ext)s}
505 <a href="%(base)s.ly">
506 <img align="center" valign="center"
507 border="0" src="%(image)s" alt="[image of music]">
513 PRINTFILENAME: '''@file{%(filename)s}
516 QUOTE: r'''@quotation
517 %(str)s@end quotation
524 VERBATIM: r'''@exampleindent 0
531 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
532 %%%% Options: [%(option_string)s]
534 #(set! toplevel-score-handler ly:parser-print-score)
535 #(set! toplevel-music-handler (lambda (p m)
536 (ly:parser-print-score
537 p (ly:music-scorify m p))))
539 #(define version-seen? #t)
543 #(define dump-extents #t)
544 %(font_dump_setting)s
556 %% ly snippet contents follows:
568 texinfo_linewidths = {
569 '@afourpaper': '160\\mm',
570 '@afourwide': '6.5\\in',
571 '@afourlatex': '150\\mm',
572 '@smallbook': '5\\in',
573 '@letterpaper': '6\\in',
576 def classic_lilypond_book_compatibility (key, value):
577 if key == 'singleline' and value == None:
578 return (RAGGEDRIGHT, None)
580 m = re.search ('relative\s*([-0-9])', key)
582 return ('relative', m.group (1))
584 m = re.match ('([0-9]+)pt', key)
586 return ('staffsize', m.group (1))
588 if key == 'indent' or key == 'linewidth':
589 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
591 f = float (m.group (1))
592 return (key, '%f\\%s' % (f, m.group (2)))
596 def compose_ly (code, options, type):
600 if string.find (i, '=') > 0:
601 (key, value) = re.split ('\s*=\s*', i)
602 option_dict[key] = value
604 if i in no_options.keys ():
605 if no_options[i] in option_dict.keys ():
606 del option_dict[no_options[i]]
608 option_dict[i] = None
610 has_linewidth = option_dict.has_key (LINEWIDTH)
611 no_linewidth_value = 0
613 # If LINEWIDTH is used without parameter, set it to default.
614 if has_linewidth and option_dict[LINEWIDTH] == None:
615 no_linewidth_value = 1
616 del option_dict[LINEWIDTH]
618 for i in default_ly_options.keys ():
619 if i not in option_dict.keys ():
620 option_dict[i] = default_ly_options[i]
622 if not has_linewidth:
623 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
624 option_dict[RAGGEDRIGHT] = None
626 if type == 'lilypond':
627 if LINEWIDTH in option_dict.keys ():
628 del option_dict[LINEWIDTH]
630 if RAGGEDRIGHT in option_dict.keys ():
631 if LINEWIDTH in option_dict.keys ():
632 del option_dict[LINEWIDTH]
634 if QUOTE in option_dict.keys () or type == 'lilypond':
635 if LINEWIDTH in option_dict.keys ():
636 del option_dict[LINEWIDTH]
638 if not INDENT in option_dict.keys ():
639 option_dict[INDENT] = '0\\mm'
641 # The QUOTE pattern from ly_options only emits the `linewidth'
643 if has_linewidth and QUOTE in option_dict.keys ():
644 if no_linewidth_value:
645 del option_dict[LINEWIDTH]
647 del option_dict[QUOTE]
649 if FRAGMENT in option_dict.keys ():
657 # The original concept of the `exampleindent' option is broken.
658 # It is not possible to get a sane value for @exampleindent at all
659 # without processing the document itself. Saying
667 # causes ugly results with the DVI backend of texinfo since the
668 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
669 # value). Executing the above code changes the environment
670 # indentation to an unknown value because we don't know the amount
671 # of 1em in advance since it is font-dependent. Modifying
672 # @exampleindent in the middle of a document is simply not
673 # supported within texinfo.
675 # As a consequence, the only function of @exampleindent is now to
676 # specify the amount of indentation for the `quote' option.
678 # To set @exampleindent locally to zero, we use the @format
679 # environment for non-quoted snippets.
680 override[EXAMPLEINDENT] = r'0.4\in'
681 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
682 override.update (default_ly_options)
685 for (key, value) in option_dict.items ():
687 option_list.append (key)
689 option_list.append (key + '=' + value)
690 option_string = string.join (option_list, ',')
693 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
694 for a in compose_types:
697 for (key, value) in option_dict.items():
699 classic_lilypond_book_compatibility (key, value)
703 (_ ("deprecated ly-option used: %s=%s" \
706 (_ ("compatibility mode translation: %s=%s" \
710 (_ ("deprecated ly-option used: %s" \
713 (_ ("compatibility mode translation: %s" \
716 (key, value) = (c_key, c_value)
719 override[key] = value
721 if not override.has_key (key):
725 for type in compose_types:
726 if ly_options[type].has_key (key):
727 compose_dict[type].append (ly_options[type][key])
731 if not found and key not in simple_options:
732 ly.warning (_ ("ignoring unknown ly option: %s") % i)
735 if RELATIVE in override.keys () and override[RELATIVE]:
736 relative = string.atoi (override[RELATIVE])
742 relative_quotes += ',' * (- relative)
744 relative_quotes += "'" * relative
746 program_name = __main__.program_name
749 string.join (compose_dict[PAPER], '\n ') % override
751 string.join (compose_dict[LAYOUT], '\n ') % override
753 string.join (compose_dict[NOTES], '\n ') % vars ()
755 string.join (compose_dict[PREAMBLE], '\n ') % override
757 font_dump_setting = ''
758 if FONTLOAD in options:
759 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
761 return (PREAMBLE_LY + body) % vars ()
764 def find_file (name):
765 for i in include_path:
766 full = os.path.join (i, name)
767 if os.path.exists (full):
769 ly.error (_ ("file not found: %s") % name + '\n')
773 def verbatim_html (s):
774 return re.sub ('>', '>',
776 re.sub ('&', '&', s)))
778 def verbatim_texinfo (s):
779 return re.sub ('{', '@{',
781 re.sub ('@', '@@', s)))
783 def split_options (option_string):
784 return re.split (format_res[format]['option_sep'], option_string)
787 def replacement_text (self):
790 def filter_text (self):
791 return self.replacement_text ()
793 def ly_is_outdated (self):
796 def png_is_outdated (self):
799 class Substring (Chunk):
800 def __init__ (self, source, start, end):
805 def replacement_text (self):
806 return self.source[self.start:self.end]
808 class Snippet (Chunk):
809 def __init__ (self, type, match, format):
816 def replacement_text (self):
817 return self.match.group ('match')
819 def substring (self, s):
820 return self.match.group (s)
823 return `self.__class__` + ' type = ' + self.type
825 class Include_snippet (Snippet):
826 def processed_filename (self):
827 f = self.substring ('filename')
828 return os.path.splitext (f)[0] + format2ext[format]
830 def replacement_text (self):
831 s = self.match.group ('match')
832 f = self.substring ('filename')
834 return re.sub (f, self.processed_filename (), s)
836 class Lilypond_snippet (Snippet):
837 def __init__ (self, type, match, format):
838 Snippet.__init__ (self, type, match, format)
839 os = match.group ('options')
841 self.options = split_options (os)
844 return self.substring ('code')
849 return compose_ly (s, self.options, self.type)
855 self.hash = abs (hash (self.full_ly ()))
860 return 'lily-%d' % self.get_hash ()
864 outf = open (self.basename () + '.ly', 'w')
865 outf.write (self.full_ly ())
867 open (self.basename () + '.txt', 'w').write ('image of music')
869 def ly_is_outdated (self):
870 base = self.basename ()
872 tex_file = '%s.tex' % base
873 eps_file = '%s.eps' % base
874 system_file = '%s-systems.tex' % base
875 ly_file = '%s.ly' % base
876 ok = os.path.exists (ly_file) \
877 and os.path.exists (system_file)\
878 and os.stat (system_file)[stat.ST_SIZE] \
879 and re.match ('% eof', open (system_file).readlines ()[-1])
880 if ok and (use_hash_p \
881 or self.ly () == open (ly_file).read ()):
882 # TODO: Do something smart with target formats
883 # (ps, png) and m/ctimes.
887 def png_is_outdated (self):
888 base = self.basename ()
889 ok = self.ly_is_outdated ()
890 if format == HTML or format == TEXINFO:
891 ok = ok and (os.path.exists (base + '.png')
892 or glob.glob (base + '-page*.png'))
894 def texstr_is_outdated (self):
898 base = self.basename ()
899 ok = self.ly_is_outdated ()
900 ok = ok and (os.path.exists (base + '.texstr'))
903 def filter_text (self):
904 code = self.substring ('code')
905 s = run_filter (code)
908 'options': self.match.group ('options')
911 return output[self.format][FILTER] % d
913 def replacement_text (self):
914 func = Lilypond_snippet.__dict__['output_' + self.format]
917 def get_images (self):
918 base = self.basename ()
920 single = '%(base)s.png' % vars ()
921 multiple = '%(base)s-page1.png' % vars ()
923 if os.path.exists (multiple) \
924 and (not os.path.exists (single) \
925 or (os.stat (multiple)[stat.ST_MTIME] \
926 > os.stat (single)[stat.ST_MTIME])):
927 images = glob.glob ('%(base)s-page*.png' % vars ())
930 def output_html (self):
932 base = self.basename ()
934 str += self.output_print_filename (HTML)
935 if VERBATIM in self.options:
936 verb = verbatim_html (self.substring ('code'))
937 str += write (output[HTML][VERBATIM] % vars ())
938 if QUOTE in self.options:
939 str = output[HTML][QUOTE] % vars ()
941 str += output[HTML][BEFORE] % vars ()
942 for image in self.get_images ():
943 (base, ext) = os.path.splitext (image)
944 str += output[HTML][OUTPUT] % vars ()
945 str += output[HTML][AFTER] % vars ()
948 def output_info (self):
950 for image in self.get_images ():
951 (base, ext) = os.path.splitext (image)
953 # URG, makeinfo implicitly prepends dot to extension.
954 # Specifying no extension is most robust.
956 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
958 base = self.basename ()
959 str += output[format][OUTPUT] % vars ()
962 def output_latex (self):
964 base = self.basename ()
966 str += self.output_print_filename (LATEX)
967 if VERBATIM in self.options:
968 verb = self.substring ('code')
969 str += (output[LATEX][VERBATIM] % vars ())
970 if QUOTE in self.options:
971 str = output[LATEX][QUOTE] % vars ()
973 str += (output[LATEX][OUTPUT] % vars ())
976 def output_print_filename (self, format):
978 if PRINTFILENAME in self.options:
979 base = self.basename ()
980 filename = self.substring ('filename')
981 str = output[format][PRINTFILENAME] % vars ()
985 def output_texinfo (self):
987 if self.output_print_filename (TEXINFO):
989 + self.output_print_filename (HTML)
992 + self.output_print_filename (LATEX)
994 base = self.basename ()
995 if TEXIDOC in self.options:
996 texidoc = base + '.texidoc'
997 if os.path.exists (texidoc):
998 str += '@include %(texidoc)s\n\n' % vars ()
1000 if VERBATIM in self.options:
1001 verb = verbatim_texinfo (self.substring ('code'))
1002 str += (output[TEXINFO][VERBATIM] % vars ())
1003 if not QUOTE in self.options:
1004 str = output[TEXINFO][NOQUOTE] % vars ()
1006 str += self.output_info ()
1008 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1009 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1010 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1012 if QUOTE in self.options:
1013 str = output[TEXINFO][QUOTE] % vars ()
1015 # need par after image
1020 class Lilypond_file_snippet (Lilypond_snippet):
1022 name = self.substring ('filename')
1023 return '\\renameinput \"%s\"\n%s' \
1024 % (name, open (find_file (name)).read ())
1026 snippet_type_to_class = {
1027 'lilypond_file': Lilypond_file_snippet,
1028 'lilypond_block': Lilypond_snippet,
1029 'lilypond': Lilypond_snippet,
1030 'include': Include_snippet,
1033 def find_toplevel_snippets (s, types):
1036 res[i] = ly.re.compile (snippet_res[format][i])
1040 ## found = dict (map (lambda x: (x, None),
1044 map (lambda x, f = found: f.setdefault (x, None),
1047 # We want to search for multiple regexes, without searching
1048 # the string multiple times for one regex.
1049 # Hence, we use earlier results to limit the string portion
1051 # Since every part of the string is traversed at most once for
1052 # every type of snippet, this is linear.
1058 if not found[type] or found[type][0] < index:
1060 m = res[type].search (s[index:endex])
1065 if snippet_type_to_class.has_key (type):
1066 cl = snippet_type_to_class[type]
1067 snip = cl (type, m, format)
1068 start = index + m.start ('match')
1069 found[type] = (start, snip)
1073 or found[type][0] < found[first][0]):
1078 # Limiting the search space is a cute
1079 # idea, but this *requires* to search
1080 # for possible containing blocks
1081 # first, at least as long as we do not
1082 # search for the start of blocks, but
1083 # always/directly for the entire
1084 # @block ... @end block.
1086 endex = found[first][0]
1089 snippets.append (Substring (s, index, len (s)))
1092 (start, snip) = found[first]
1093 snippets.append (Substring (s, index, start))
1094 snippets.append (snip)
1096 index = start + len (snip.match.group ('match'))
1100 def filter_pipe (input, cmd):
1102 ly.progress (_ ("Opening filter `%s'") % cmd)
1104 (stdin, stdout, stderr) = os.popen3 (cmd)
1106 status = stdin.close ()
1110 output = stdout.read ()
1111 status = stdout.close ()
1112 error = stderr.read ()
1116 signal = 0x0f & status
1117 if status or (not output and error):
1118 exit_status = status >> 8
1119 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1120 ly.error (_ ("The error log is as follows:"))
1121 sys.stderr.write (error)
1122 sys.stderr.write (stderr.read ())
1131 return filter_pipe (s, filter_cmd)
1133 def is_derived_class (cl, baseclass):
1136 for b in cl.__bases__:
1137 if is_derived_class (b, baseclass):
1141 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1142 ly_names = filter (lambda x: x,
1143 map (Lilypond_snippet.basename, ly_snippets))
1144 texstr_names = filter (lambda x: x,
1145 map (Lilypond_snippet.basename, texstr_snippets))
1146 png_names = filter (lambda x: x,
1147 map (Lilypond_snippet.basename, png_snippets))
1150 def my_system (cmd):
1151 status = ly.system (cmd,
1152 ignore_error = 1, progress_p = 1)
1155 ly.error ('Process %s exited unsuccessfully.' % cmd)
1159 # the --process=CMD switch is a bad idea
1160 # it is too generic for lilypond-book.
1161 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1163 my_system (string.join ([cmd + ' --backend texstr ' ] + texstr_names))
1164 for l in texstr_names:
1165 my_system ('latex %s.texstr' % l)
1168 my_system (string.join ([cmd] + ly_names))
1170 LATEX_DOCUMENT = r'''
1173 \typeout{textwidth=\the\textwidth}
1174 \typeout{columnsep=\the\columnsep}
1175 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1179 # Do we need anything else besides `textwidth'?
1180 def get_latex_textwidth (source):
1181 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1182 preamble = source[:m.start (0)]
1183 latex_document = LATEX_DOCUMENT % vars ()
1184 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1187 m = re.search ('columns=([0-9.]*)', parameter_string)
1189 columns = string.atoi (m.group (1))
1192 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1194 columnsep = string.atof (m.group (1))
1197 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1199 textwidth = string.atof (m.group (1))
1201 textwidth = (textwidth - columnsep) / columns
1213 '.texinfo': TEXINFO,
1219 # TEXINFO: '.texinfo',
1224 class Compile_error:
1227 def do_process_cmd (chunks):
1229 filter (lambda x: is_derived_class (x.__class__,
1231 and x.ly_is_outdated (),
1234 filter (lambda x: is_derived_class (x.__class__,
1236 and x.texstr_is_outdated (),
1239 filter (lambda x: is_derived_class (x.__class__,
1241 and x.png_is_outdated (),
1244 ly.progress (_ ("Writing snippets..."))
1245 map (Lilypond_snippet.write_ly, ly_outdated)
1249 ly.progress (_ ("Processing..."))
1251 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1253 ly.progress (_ ("All snippets are up to date..."))
1256 def guess_format (input_filename):
1258 e = os.path.splitext (input_filename)[1]
1259 if e in ext2format.keys ():
1261 format = ext2format[e]
1263 ly.error (_ ("cannot determine format for: %s" \
1268 def do_file (input_filename):
1270 if not input_filename or input_filename == '-':
1271 in_handle = sys.stdin
1272 input_fullname = '<stdin>'
1274 if os.path.exists (input_filename):
1275 input_fullname = input_filename
1276 elif format == LATEX:
1277 # urg python interface to libkpathsea?
1278 input_fullname = ly.read_pipe ('kpsewhich '
1279 + input_filename)[:-1]
1281 input_fullname = find_file (input_filename)
1282 in_handle = open (input_fullname)
1284 if input_filename == '-':
1285 input_base = 'stdin'
1287 input_base = os.path.basename \
1288 (os.path.splitext (input_filename)[0])
1290 # Only default to stdout when filtering.
1291 if output_name == '-' or (not output_name and filter_cmd):
1292 output_filename = '-'
1293 output_file = sys.stdout
1296 output_filename = input_base + format2ext[format]
1298 if not os.path.isdir (output_name):
1299 os.mkdir (output_name, 0777)
1300 output_filename = (output_name
1302 + format2ext[format])
1304 if os.path.exists (input_filename) \
1305 and os.path.exists (output_filename) \
1306 and os.path.samefile (output_filename, input_fullname):
1308 _ ("Output would overwrite input file; use --output."))
1311 output_file = open (output_filename, 'w')
1313 os.chdir (output_name)
1315 ly.progress (_ ("Reading %s...") % input_fullname)
1316 source = in_handle.read ()
1319 # FIXME: Containing blocks must be first, see
1320 # find_toplevel_snippets.
1322 'multiline_comment',
1326 'singleline_comment',
1331 ly.progress (_ ("Dissecting..."))
1332 chunks = find_toplevel_snippets (source, snippet_types)
1335 global default_ly_options
1337 if not default_ly_options.has_key (LINEWIDTH):
1339 textwidth = get_latex_textwidth (source)
1340 default_ly_options[LINEWIDTH] = \
1341 '''%.0f\\pt''' % textwidth
1342 elif format == TEXINFO:
1343 for (k, v) in texinfo_linewidths.items ():
1344 # FIXME: @layout is usually not in
1347 # \input texinfo @c -*-texinfo-*-
1349 # Bluntly search first K items of
1351 # s = chunks[0].replacement_text ()
1352 if re.search (k, source[:1024]):
1353 default_ly_options[LINEWIDTH] = v
1357 output_file.writelines ([c.filter_text () \
1361 do_process_cmd (chunks)
1362 ly.progress (_ ("Compiling %s...") % output_filename)
1363 output_file.writelines ([s.replacement_text () \
1367 def process_include (snippet):
1368 os.chdir (original_dir)
1369 name = snippet.substring ('filename')
1370 ly.progress (_ ("Processing include: %s") % name)
1374 map (process_include,
1375 filter (lambda x: is_derived_class (x.__class__,
1378 except Compile_error:
1379 os.chdir (original_dir)
1380 ly.progress (_ ("Removing `%s'") % output_filename)
1383 os.unlink (output_filename)
1387 global format, output_name
1388 global filter_cmd, process_cmd, verbose_p
1390 (sh, long) = ly.getopt_args (option_definitions)
1392 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1393 except getopt.error, s:
1394 sys.stderr.write ('\n')
1395 ly.error (_ ("getopt says: `%s'" % s))
1396 sys.stderr.write ('\n')
1406 elif o == '--filter' or o == '-F':
1409 elif o == '--format' or o == '-f':
1411 if a == 'texi-html' or a == 'texi':
1413 elif o == '--tex-backend ':
1415 elif o == '--help' or o == '-h':
1418 elif o == '--include' or o == '-I':
1419 include_path.append (os.path.join (original_dir,
1421 elif o == '--output' or o == '-o':
1423 elif o == '--outdir':
1425 elif o == '--process' or o == '-P':
1428 elif o == '--version' or o == '-v':
1429 ly.identify (sys.stdout)
1431 elif o == '--verbose' or o == '-V':
1433 elif o == '--warranty' or o == '-w':
1440 files = do_options ()
1442 ly.warning ("Need to have command line option")
1446 global process_cmd, format
1447 format = guess_format (files[0])
1450 if format == TEXINFO:
1452 if process_cmd == '':
1453 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1456 process_cmd += string.join ([(' -I %s' % p)
1457 for p in include_path])
1459 ly.identify (sys.stderr)
1460 ly.setup_environment ()
1464 except Compile_error:
1468 if __name__ == '__main__':