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
496 OUTPUTIMAGE: r'''@noindent
498 @image{%(base)s,,,[image of music],%(ext)s}
502 PRINTFILENAME: '''@file{%(filename)s}
505 QUOTE: r'''@quotation
506 %(str)s@end quotation
513 VERBATIM: r'''@exampleindent 0
520 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
521 %%%% Options: [%(option_string)s]
523 #(set! toplevel-score-handler ly:parser-print-score)
524 #(set! toplevel-music-handler (lambda (p m)
525 (ly:parser-print-score
526 p (ly:music-scorify m p))))
528 #(define version-seen? #t)
532 #(define dump-extents #t)
544 %% ly snippet contents follows:
556 texinfo_linewidths = {
557 '@afourpaper': '160\\mm',
558 '@afourwide': '6.5\\in',
559 '@afourlatex': '150\\mm',
560 '@smallbook': '5\\in',
561 '@letterpaper': '6\\in',
564 def classic_lilypond_book_compatibility (key, value):
565 if key == 'singleline' and value == None:
566 return (RAGGEDRIGHT, None)
568 m = re.search ('relative\s*([-0-9])', key)
570 return ('relative', m.group (1))
572 m = re.match ('([0-9]+)pt', key)
574 return ('staffsize', m.group (1))
576 if key == 'indent' or key == 'linewidth':
577 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
579 f = float (m.group (1))
580 return (key, '%f\\%s' % (f, m.group (2)))
584 def compose_ly (code, options, type):
588 if string.find (i, '=') > 0:
589 (key, value) = re.split ('\s*=\s*', i)
590 option_dict[key] = value
592 if i in no_options.keys ():
593 if no_options[i] in option_dict.keys ():
594 del option_dict[no_options[i]]
596 option_dict[i] = None
598 has_linewidth = option_dict.has_key (LINEWIDTH)
599 no_linewidth_value = 0
601 # If LINEWIDTH is used without parameter, set it to default.
602 if has_linewidth and option_dict[LINEWIDTH] == None:
603 no_linewidth_value = 1
604 del option_dict[LINEWIDTH]
606 for i in default_ly_options.keys ():
607 if i not in option_dict.keys ():
608 option_dict[i] = default_ly_options[i]
610 if not has_linewidth:
611 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
612 option_dict[RAGGEDRIGHT] = None
614 if type == 'lilypond':
615 if LINEWIDTH in option_dict.keys ():
616 del option_dict[LINEWIDTH]
618 if RAGGEDRIGHT in option_dict.keys ():
619 if LINEWIDTH in option_dict.keys ():
620 del option_dict[LINEWIDTH]
622 if QUOTE in option_dict.keys () or type == 'lilypond':
623 if LINEWIDTH in option_dict.keys ():
624 del option_dict[LINEWIDTH]
626 if not INDENT in option_dict.keys ():
627 option_dict[INDENT] = '0\\mm'
629 # The QUOTE pattern from ly_options only emits the `linewidth'
631 if has_linewidth and QUOTE in option_dict.keys ():
632 if no_linewidth_value:
633 del option_dict[LINEWIDTH]
635 del option_dict[QUOTE]
637 if FRAGMENT in option_dict.keys ():
645 # The original concept of the `exampleindent' option is broken.
646 # It is not possible to get a sane value for @exampleindent at all
647 # without processing the document itself. Saying
655 # causes ugly results with the DVI backend of texinfo since the
656 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
657 # value). Executing the above code changes the environment
658 # indentation to an unknown value because we don't know the amount
659 # of 1em in advance since it is font-dependent. Modifying
660 # @exampleindent in the middle of a document is simply not
661 # supported within texinfo.
663 # As a consequence, the only function of @exampleindent is now to
664 # specify the amount of indentation for the `quote' option.
666 # To set @exampleindent locally to zero, we use the @format
667 # environment for non-quoted snippets.
668 override[EXAMPLEINDENT] = r'0.4\in'
669 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
670 override.update (default_ly_options)
673 for (key, value) in option_dict.items ():
675 option_list.append (key)
677 option_list.append (key + '=' + value)
678 option_string = string.join (option_list, ',')
681 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
682 for a in compose_types:
685 for (key, value) in option_dict.items():
687 classic_lilypond_book_compatibility (key, value)
691 (_ ("deprecated ly-option used: %s=%s" \
694 (_ ("compatibility mode translation: %s=%s" \
698 (_ ("deprecated ly-option used: %s" \
701 (_ ("compatibility mode translation: %s" \
704 (key, value) = (c_key, c_value)
707 override[key] = value
709 if not override.has_key (key):
713 for type in compose_types:
714 if ly_options[type].has_key (key):
715 compose_dict[type].append (ly_options[type][key])
719 if not found and key not in simple_options:
720 ly.warning (_ ("ignoring unknown ly option: %s") % i)
723 if RELATIVE in override.keys () and override[RELATIVE]:
724 relative = string.atoi (override[RELATIVE])
730 relative_quotes += ',' * (- relative)
732 relative_quotes += "'" * relative
734 program_name = __main__.program_name
737 string.join (compose_dict[PAPER], '\n ') % override
739 string.join (compose_dict[LAYOUT], '\n ') % override
741 string.join (compose_dict[NOTES], '\n ') % vars ()
743 string.join (compose_dict[PREAMBLE], '\n ') % override
745 return (PREAMBLE_LY + body) % vars ()
748 def find_file (name):
749 for i in include_path:
750 full = os.path.join (i, name)
751 if os.path.exists (full):
753 ly.error (_ ("file not found: %s") % name + '\n')
757 def verbatim_html (s):
758 return re.sub ('>', '>',
760 re.sub ('&', '&', s)))
762 def verbatim_texinfo (s):
763 return re.sub ('{', '@{',
765 re.sub ('@', '@@', s)))
767 def split_options (option_string):
768 return re.split (format_res[format]['option_sep'], option_string)
771 def replacement_text (self):
774 def filter_text (self):
775 return self.replacement_text ()
777 def ly_is_outdated (self):
780 def png_is_outdated (self):
783 class Substring (Chunk):
784 def __init__ (self, source, start, end):
789 def replacement_text (self):
790 return self.source[self.start:self.end]
792 class Snippet (Chunk):
793 def __init__ (self, type, match, format):
800 def replacement_text (self):
801 return self.match.group ('match')
803 def substring (self, s):
804 return self.match.group (s)
807 return `self.__class__` + ' type = ' + self.type
809 class Include_snippet (Snippet):
810 def processed_filename (self):
811 f = self.substring ('filename')
812 return os.path.splitext (f)[0] + format2ext[format]
814 def replacement_text (self):
815 s = self.match.group ('match')
816 f = self.substring ('filename')
818 return re.sub (f, self.processed_filename (), s)
820 class Lilypond_snippet (Snippet):
821 def __init__ (self, type, match, format):
822 Snippet.__init__ (self, type, match, format)
823 os = match.group ('options')
825 self.options = split_options (os)
828 return self.substring ('code')
833 return compose_ly (s, self.options, self.type)
839 self.hash = abs (hash (self.full_ly ()))
844 return 'lily-%d' % self.get_hash ()
848 outf = open (self.basename () + '.ly', 'w')
849 outf.write (self.full_ly ())
851 open (self.basename () + '.txt', 'w').write ('image of music')
853 def ly_is_outdated (self):
854 base = self.basename ()
856 tex_file = '%s.tex' % base
857 eps_file = '%s.eps' % base
858 system_file = '%s-systems.tex' % base
859 ly_file = '%s.ly' % base
860 ok = os.path.exists (ly_file) \
861 and os.path.exists (system_file)\
862 and os.stat (system_file)[stat.ST_SIZE] \
863 and re.match ('% eof', open (system_file).readlines ()[-1])
864 if ok and (use_hash_p \
865 or self.ly () == open (ly_file).read ()):
866 # TODO: Do something smart with target formats
867 # (ps, png) and m/ctimes.
871 def png_is_outdated (self):
872 base = self.basename ()
873 ok = self.ly_is_outdated ()
874 if format == HTML or format == TEXINFO:
875 ok = ok and (os.path.exists (base + '.png')
876 or glob.glob (base + '-page*.png'))
878 def texstr_is_outdated (self):
882 base = self.basename ()
883 ok = self.ly_is_outdated ()
884 ok = ok and (os.path.exists (base + '.texstr'))
887 def filter_text (self):
888 code = self.substring ('code')
889 s = run_filter (code)
892 'options': self.match.group ('options')
895 return output[self.format][FILTER] % d
897 def replacement_text (self):
898 func = Lilypond_snippet.__dict__['output_' + self.format]
901 def get_images (self):
902 base = self.basename ()
904 single = '%(base)s.png' % vars ()
905 multiple = '%(base)s-page1.png' % vars ()
907 if os.path.exists (multiple) \
908 and (not os.path.exists (single) \
909 or (os.stat (multiple)[stat.ST_MTIME] \
910 > os.stat (single)[stat.ST_MTIME])):
911 images = glob.glob ('%(base)s-page*.png' % vars ())
914 def output_html (self):
916 base = self.basename ()
918 str += self.output_print_filename (HTML)
919 if VERBATIM in self.options:
920 verb = verbatim_html (self.substring ('code'))
921 str += write (output[HTML][VERBATIM] % vars ())
922 if QUOTE in self.options:
923 str = output[HTML][QUOTE] % vars ()
925 str += output[HTML][BEFORE] % vars ()
926 for image in self.get_images ():
927 (base, ext) = os.path.splitext (image)
928 str += output[HTML][OUTPUT] % vars ()
929 str += output[HTML][AFTER] % vars ()
932 def output_info (self):
934 for image in self.get_images ():
935 (base, ext) = os.path.splitext (image)
937 # URG, makeinfo implicitly prepends dot to extension.
938 # Specifying no extension is most robust.
940 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
942 base = self.basename()
943 str += output[format][OUTPUT] % vars()
946 def output_latex (self):
948 base = self.basename ()
950 str += self.output_print_filename (LATEX)
951 if VERBATIM in self.options:
952 verb = self.substring ('code')
953 str += (output[LATEX][VERBATIM] % vars ())
954 if QUOTE in self.options:
955 str = output[LATEX][QUOTE] % vars ()
957 str += (output[LATEX][OUTPUT] % vars ())
960 def output_print_filename (self, format):
962 if PRINTFILENAME in self.options:
963 base = self.basename ()
964 filename = self.substring ('filename')
965 str = output[format][PRINTFILENAME] % vars ()
969 def output_texinfo (self):
971 if self.output_print_filename (TEXINFO):
973 + self.output_print_filename (HTML)
976 + self.output_print_filename (LATEX)
978 base = self.basename ()
979 if TEXIDOC in self.options:
980 texidoc = base + '.texidoc'
981 if os.path.exists (texidoc):
982 str += '@include %(texidoc)s\n\n' % vars ()
984 if VERBATIM in self.options:
985 verb = verbatim_texinfo (self.substring ('code'))
986 str += (output[TEXINFO][VERBATIM] % vars ())
987 if not QUOTE in self.options:
988 str = output[TEXINFO][NOQUOTE] % vars()
990 str += self.output_info ()
992 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
993 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
994 # str += ('@html\n' + self.output_html () + '\n@end html\n')
996 if QUOTE in self.options:
997 str = output[TEXINFO][QUOTE] % vars ()
999 # need par after image
1004 class Lilypond_file_snippet (Lilypond_snippet):
1006 name = self.substring ('filename')
1007 return '\\renameinput \"%s\"\n%s' \
1008 % (name, open (find_file (name)).read ())
1010 snippet_type_to_class = {
1011 'lilypond_file': Lilypond_file_snippet,
1012 'lilypond_block': Lilypond_snippet,
1013 'lilypond': Lilypond_snippet,
1014 'include': Include_snippet,
1017 def find_toplevel_snippets (s, types):
1020 res[i] = ly.re.compile (snippet_res[format][i])
1024 ## found = dict (map (lambda x: (x, None),
1028 map (lambda x, f = found: f.setdefault (x, None),
1031 # We want to search for multiple regexes, without searching
1032 # the string multiple times for one regex.
1033 # Hence, we use earlier results to limit the string portion
1035 # Since every part of the string is traversed at most once for
1036 # every type of snippet, this is linear.
1042 if not found[type] or found[type][0] < index:
1044 m = res[type].search (s[index:endex])
1049 if snippet_type_to_class.has_key (type):
1050 cl = snippet_type_to_class[type]
1051 snip = cl (type, m, format)
1052 start = index + m.start ('match')
1053 found[type] = (start, snip)
1057 or found[type][0] < found[first][0]):
1062 # Limiting the search space is a cute
1063 # idea, but this *requires* to search
1064 # for possible containing blocks
1065 # first, at least as long as we do not
1066 # search for the start of blocks, but
1067 # always/directly for the entire
1068 # @block ... @end block.
1070 endex = found[first][0]
1073 snippets.append (Substring (s, index, len (s)))
1076 (start, snip) = found[first]
1077 snippets.append (Substring (s, index, start))
1078 snippets.append (snip)
1080 index = start + len (snip.match.group ('match'))
1084 def filter_pipe (input, cmd):
1086 ly.progress (_ ("Opening filter `%s'") % cmd)
1088 (stdin, stdout, stderr) = os.popen3 (cmd)
1090 status = stdin.close ()
1094 output = stdout.read ()
1095 status = stdout.close ()
1096 error = stderr.read ()
1100 signal = 0x0f & status
1101 if status or (not output and error):
1102 exit_status = status >> 8
1103 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1104 ly.error (_ ("The error log is as follows:"))
1105 sys.stderr.write (error)
1106 sys.stderr.write (stderr.read ())
1115 return filter_pipe (s, filter_cmd)
1117 def is_derived_class (cl, baseclass):
1120 for b in cl.__bases__:
1121 if is_derived_class (b, baseclass):
1125 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1126 ly_names = filter (lambda x: x,
1127 map (Lilypond_snippet.basename, ly_snippets))
1128 texstr_names = filter (lambda x: x,
1129 map (Lilypond_snippet.basename, texstr_snippets))
1130 png_names = filter (lambda x: x,
1131 map (Lilypond_snippet.basename, png_snippets))
1134 def my_system (cmd):
1135 status = ly.system (cmd,
1136 ignore_error = 1, progress_p = 1)
1139 ly.error ('Process %s exited unsuccessfully.' % cmd)
1143 # the --process=CMD switch is a bad idea
1144 # it is too generic for lilypond-book.
1145 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1147 my_system (string.join ([cmd + ' --backend texstr ' ] + texstr_names))
1148 for l in texstr_names:
1149 my_system ('latex %s.texstr' % l)
1152 my_system (string.join ([cmd] + ly_names))
1154 LATEX_DOCUMENT = r'''
1157 \typeout{textwidth=\the\textwidth}
1158 \typeout{columnsep=\the\columnsep}
1159 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1163 # Do we need anything else besides `textwidth'?
1164 def get_latex_textwidth (source):
1165 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1166 preamble = source[:m.start (0)]
1167 latex_document = LATEX_DOCUMENT % vars ()
1168 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1171 m = re.search ('columns=([0-9.]*)', parameter_string)
1173 columns = string.atoi (m.group (1))
1176 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1178 columnsep = string.atof (m.group (1))
1181 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1183 textwidth = string.atof (m.group (1))
1185 textwidth = (textwidth - columnsep) / columns
1197 '.texinfo': TEXINFO,
1203 # TEXINFO: '.texinfo',
1208 class Compile_error:
1211 def do_process_cmd (chunks):
1213 filter (lambda x: is_derived_class (x.__class__,
1215 and x.ly_is_outdated (),
1218 filter (lambda x: is_derived_class (x.__class__,
1220 and x.texstr_is_outdated (),
1223 filter (lambda x: is_derived_class (x.__class__,
1225 and x.png_is_outdated (),
1228 ly.progress (_ ("Writing snippets..."))
1229 map (Lilypond_snippet.write_ly, ly_outdated)
1233 ly.progress (_ ("Processing...\n"))
1234 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1236 ly.progress (_ ("All snippets are up to date..."))
1239 def guess_format (input_filename):
1241 e = os.path.splitext (input_filename)[1]
1242 if e in ext2format.keys ():
1244 format = ext2format[e]
1246 ly.error (_ ("cannot determine format for: %s" \
1251 def do_file (input_filename):
1253 if not input_filename or input_filename == '-':
1254 in_handle = sys.stdin
1255 input_fullname = '<stdin>'
1257 if os.path.exists (input_filename):
1258 input_fullname = input_filename
1259 elif format == LATEX:
1260 # urg python interface to libkpathsea?
1261 input_fullname = ly.read_pipe ('kpsewhich '
1262 + input_filename)[:-1]
1264 input_fullname = find_file (input_filename)
1265 in_handle = open (input_fullname)
1267 if input_filename == '-':
1268 input_base = 'stdin'
1270 input_base = os.path.basename \
1271 (os.path.splitext (input_filename)[0])
1273 # Only default to stdout when filtering.
1274 if output_name == '-' or (not output_name and filter_cmd):
1275 output_filename = '-'
1276 output_file = sys.stdout
1279 output_filename = input_base + format2ext[format]
1281 if not os.path.isdir (output_name):
1282 os.mkdir (output_name, 0777)
1283 output_filename = (output_name
1285 + format2ext[format])
1287 if os.path.exists (input_filename) \
1288 and os.path.exists (output_filename) \
1289 and os.path.samefile (output_filename, input_fullname):
1291 _ ("Output would overwrite input file; use --output."))
1294 output_file = open (output_filename, 'w')
1296 os.chdir (output_name)
1298 ly.progress (_ ("Reading %s...") % input_fullname)
1299 source = in_handle.read ()
1302 # FIXME: Containing blocks must be first, see
1303 # find_toplevel_snippets.
1305 'multiline_comment',
1309 'singleline_comment',
1314 ly.progress (_ ("Dissecting..."))
1315 chunks = find_toplevel_snippets (source, snippet_types)
1318 global default_ly_options
1320 if not default_ly_options.has_key (LINEWIDTH):
1322 textwidth = get_latex_textwidth (source)
1323 default_ly_options[LINEWIDTH] = \
1324 '''%.0f\\pt''' % textwidth
1325 elif format == TEXINFO:
1326 for (k, v) in texinfo_linewidths.items ():
1327 # FIXME: @layout is usually not in
1330 # \input texinfo @c -*-texinfo-*-
1332 # Bluntly search first K items of
1334 # s = chunks[0].replacement_text ()
1335 if re.search (k, source[:1024]):
1336 default_ly_options[LINEWIDTH] = v
1340 output_file.writelines ([c.filter_text () \
1344 do_process_cmd (chunks)
1345 ly.progress (_ ("Compiling %s...") % output_filename)
1346 output_file.writelines ([s.replacement_text () \
1350 def process_include (snippet):
1351 os.chdir (original_dir)
1352 name = snippet.substring ('filename')
1353 ly.progress (_ ("Processing include: %s") % name)
1357 map (process_include,
1358 filter (lambda x: is_derived_class (x.__class__,
1361 except Compile_error:
1362 os.chdir (original_dir)
1363 ly.progress (_ ("Removing `%s'") % output_filename)
1366 os.unlink (output_filename)
1370 global format, output_name
1371 global filter_cmd, process_cmd, verbose_p
1373 (sh, long) = ly.getopt_args (option_definitions)
1375 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1376 except getopt.error, s:
1377 sys.stderr.write ('\n')
1378 ly.error (_ ("getopt says: `%s'" % s))
1379 sys.stderr.write ('\n')
1389 elif o == '--filter' or o == '-F':
1392 elif o == '--format' or o == '-f':
1394 if a == 'texi-html' or a == 'texi':
1396 elif o == '--tex-backend ':
1398 elif o == '--help' or o == '-h':
1401 elif o == '--include' or o == '-I':
1402 include_path.append (os.path.join (original_dir,
1404 elif o == '--output' or o == '-o':
1406 elif o == '--outdir':
1408 elif o == '--process' or o == '-P':
1411 elif o == '--version' or o == '-v':
1412 ly.identify (sys.stdout)
1414 elif o == '--verbose' or o == '-V':
1416 elif o == '--warranty' or o == '-w':
1423 files = do_options ()
1425 ly.warning ("Need to have command line option")
1429 global process_cmd, format
1430 format = guess_format (files[0])
1433 if format == TEXINFO:
1435 if process_cmd == '':
1436 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1439 process_cmd += string.join ([(' -I %s' % p)
1440 for p in include_path])
1442 ly.identify (sys.stderr)
1443 ly.setup_environment ()
1447 except Compile_error:
1451 if __name__ == '__main__':