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'
138 PREAMBLE = 'preamble'
139 PRINTFILENAME = 'printfilename'
141 RAGGEDRIGHT = 'raggedright'
142 RELATIVE = 'relative'
143 STAFFSIZE = 'staffsize'
146 VERBATIM = 'verbatim'
148 # NOTIME has no opposite so it isn't part of this dictionary.
149 # NOQUOTE is used internally only.
151 NOFRAGMENT: FRAGMENT,
155 # Recognize special sequences in the input.
157 # (?P<name>regex) -- Assign result of REGEX to NAME.
158 # *? -- Match non-greedily.
159 # (?m) -- Multiline regex: Make ^ and $ match at each line.
160 # (?s) -- Make the dot match all characters including newline.
161 # (?x) -- Ignore whitespace in patterns.
173 (\s*(?P<options>.*?)\s*:)?\s*
181 \s*(?P<options>.*?)\s*
190 \s*(?P<options>.*?)\s*
192 \s*(?P<filename>.*?)\s*
199 (?P<code><!--\s.*?!-->)
202 'singleline_comment':
208 (?P<code><pre>.*?</pre>))''',
214 (?P<code><pre>\s.*?</pre>\s))''',
233 \s*(?P<options>.*?)\s*
244 \s*(?P<options>.*?)\s*
248 \\end\s*{lilypond})''',
256 \s*(?P<options>.*?)\s*
264 'singleline_comment':
287 \\end\s*{verbatim}))''',
296 (?P<filename>\S+))''',
300 ^[^\n]*?(?!@c\s+)[^\n]*?
304 \s*(?P<options>.*?)\s*
314 \s*(?P<options>.*?)\s*
317 ^@end\s+lilypond)\s''',
324 \s*(?P<options>.*?)\s*
335 @end\s+ignore))\s''',
337 'singleline_comment':
342 @c([ \t][^\n]*|)\n))''',
344 # Don't do this: It interferes with @code{@{}.
345 # 'verb': r'''(?P<code>@code{.*?})''',
353 @end\s+example\s))''',
359 'intertext': r',?\s*intertext=\".*?\"',
364 'intertext': r',?\s*intertext=\".*?\"',
365 'option_sep': '\s*,\s*',
369 'intertext': r',?\s*intertext=\".*?\"',
370 'option_sep': '\s*,\s*',
374 # Options without a pattern in ly_options.
388 RELATIVE: r'''\relative c%(relative_quotes)s''',
393 INDENT: r'''indent = %(indent)s''',
395 LINEWIDTH: r'''linewidth = %(linewidth)s''',
397 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
399 RAGGEDRIGHT: r'''raggedright = ##t''',
404 NOTIME: r'''\context {
406 \remove Time_signature_engraver
412 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
419 FILTER: r'''<lilypond %(options)s>
429 <a href="%(base)s.ly">''',
432 <img align="center" valign="center"
433 border="0" src="%(image)s" alt="[image of music]">''',
435 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
437 QUOTE: r'''<blockquote>
451 \ifx\preLilyPondExample \undefined
456 \def\lilypondbook{}%%
457 \input %(base)s-systems.tex
458 \ifx\postLilyPondExample \undefined
465 PRINTFILENAME: '''\\texttt{%(filename)s}
468 QUOTE: r'''\begin{quotation}
473 VERBATIM: r'''\noindent
475 %(verb)s\end{verbatim}
478 FILTER: r'''\begin{lilypond}[%(options)s]
485 FILTER: r'''@lilypond[%(options)s]
489 OUTPUT: r'''@noindent
491 @include %(base)s-systems.texi
494 @image{%(base)s,,,[image of music],%(ext)s}
498 PRINTFILENAME: '''@file{%(filename)s}
501 QUOTE: r'''@quotation
502 %(str)s@end quotation
509 VERBATIM: r'''@exampleindent 0
516 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
517 %%%% Options: [%(option_string)s]
519 #(set! toplevel-score-handler ly:parser-print-score)
520 #(set! toplevel-music-handler (lambda (p m)
521 (ly:parser-print-score
522 p (ly:music-scorify m p))))
524 #(define version-seen? #t)
528 #(define dump-extents #t)
540 %% ly snippet contents follows:
552 texinfo_linewidths = {
553 '@afourpaper': '160\\mm',
554 '@afourwide': '6.5\\in',
555 '@afourlatex': '150\\mm',
556 '@smallbook': '5\\in',
557 '@letterpaper': '6\\in',
560 def classic_lilypond_book_compatibility (key, value):
561 if key == 'singleline' and value == None:
562 return (RAGGEDRIGHT, None)
564 m = re.search ('relative\s*([-0-9])', key)
566 return ('relative', m.group (1))
568 m = re.match ('([0-9]+)pt', key)
570 return ('staffsize', m.group (1))
572 if key == 'indent' or key == 'linewidth':
573 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
575 f = float (m.group (1))
576 return (key, '%f\\%s' % (f, m.group (2)))
580 def compose_ly (code, options, type):
584 if string.find (i, '=') > 0:
585 (key, value) = re.split ('\s*=\s*', i)
586 option_dict[key] = value
588 if i in no_options.keys ():
589 if no_options[i] in option_dict.keys ():
590 del option_dict[no_options[i]]
592 option_dict[i] = None
594 has_linewidth = option_dict.has_key (LINEWIDTH)
595 no_linewidth_value = 0
597 # If LINEWIDTH is used without parameter, set it to default.
598 if has_linewidth and option_dict[LINEWIDTH] == None:
599 no_linewidth_value = 1
600 del option_dict[LINEWIDTH]
602 for i in default_ly_options.keys ():
603 if i not in option_dict.keys ():
604 option_dict[i] = default_ly_options[i]
606 if not has_linewidth:
607 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
608 option_dict[RAGGEDRIGHT] = None
610 if type == 'lilypond':
611 if LINEWIDTH in option_dict.keys ():
612 del option_dict[LINEWIDTH]
614 if RAGGEDRIGHT in option_dict.keys ():
615 if LINEWIDTH in option_dict.keys ():
616 del option_dict[LINEWIDTH]
618 if QUOTE in option_dict.keys () or type == 'lilypond':
619 if LINEWIDTH in option_dict.keys ():
620 del option_dict[LINEWIDTH]
622 if not INDENT in option_dict.keys ():
623 option_dict[INDENT] = '0\\mm'
625 # The QUOTE pattern from ly_options only emits the `linewidth'
627 if has_linewidth and QUOTE in option_dict.keys ():
628 if no_linewidth_value:
629 del option_dict[LINEWIDTH]
631 del option_dict[QUOTE]
633 if FRAGMENT in option_dict.keys ():
641 # The original concept of the `exampleindent' option is broken.
642 # It is not possible to get a sane value for @exampleindent at all
643 # without processing the document itself. Saying
651 # causes ugly results with the DVI backend of texinfo since the
652 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
653 # value). Executing the above code changes the environment
654 # indentation to an unknown value because we don't know the amount
655 # of 1em in advance since it is font-dependent. Modifying
656 # @exampleindent in the middle of a document is simply not
657 # supported within texinfo.
659 # As a consequence, the only function of @exampleindent is now to
660 # specify the amount of indentation for the `quote' option.
662 # To set @exampleindent locally to zero, we use the @format
663 # environment for non-quoted snippets.
664 override[EXAMPLEINDENT] = r'0.4\in'
665 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
666 override.update (default_ly_options)
669 for (key, value) in option_dict.items ():
671 option_list.append (key)
673 option_list.append (key + '=' + value)
674 option_string = string.join (option_list, ',')
677 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
678 for a in compose_types:
681 for (key, value) in option_dict.items():
683 classic_lilypond_book_compatibility (key, value)
687 (_ ("deprecated ly-option used: %s=%s" \
690 (_ ("compatibility mode translation: %s=%s" \
694 (_ ("deprecated ly-option used: %s" \
697 (_ ("compatibility mode translation: %s" \
700 (key, value) = (c_key, c_value)
703 override[key] = value
705 if not override.has_key (key):
709 for type in compose_types:
710 if ly_options[type].has_key (key):
711 compose_dict[type].append (ly_options[type][key])
715 if not found and key not in simple_options:
716 ly.warning (_ ("ignoring unknown ly option: %s") % i)
719 if RELATIVE in override.keys () and override[RELATIVE]:
720 relative = string.atoi (override[RELATIVE])
726 relative_quotes += ',' * (- relative)
728 relative_quotes += "'" * relative
730 program_name = __main__.program_name
733 string.join (compose_dict[PAPER], '\n ') % override
735 string.join (compose_dict[LAYOUT], '\n ') % override
737 string.join (compose_dict[NOTES], '\n ') % vars ()
739 string.join (compose_dict[PREAMBLE], '\n ') % override
741 return (PREAMBLE_LY + body) % vars ()
744 def find_file (name):
745 for i in include_path:
746 full = os.path.join (i, name)
747 if os.path.exists (full):
749 ly.error (_ ("file not found: %s") % name + '\n')
753 def verbatim_html (s):
754 return re.sub ('>', '>',
756 re.sub ('&', '&', s)))
758 def verbatim_texinfo (s):
759 return re.sub ('{', '@{',
761 re.sub ('@', '@@', s)))
763 def split_options (option_string):
764 return re.split (format_res[format]['option_sep'], option_string)
767 def replacement_text (self):
770 def filter_text (self):
771 return self.replacement_text ()
773 def ly_is_outdated (self):
776 def png_is_outdated (self):
779 class Substring (Chunk):
780 def __init__ (self, source, start, end):
785 def replacement_text (self):
786 return self.source[self.start:self.end]
788 class Snippet (Chunk):
789 def __init__ (self, type, match, format):
796 def replacement_text (self):
797 return self.match.group ('match')
799 def substring (self, s):
800 return self.match.group (s)
803 return `self.__class__` + ' type = ' + self.type
805 class Include_snippet (Snippet):
806 def processed_filename (self):
807 f = self.substring ('filename')
808 return os.path.splitext (f)[0] + format2ext[format]
810 def replacement_text (self):
811 s = self.match.group ('match')
812 f = self.substring ('filename')
814 return re.sub (f, self.processed_filename (), s)
816 class Lilypond_snippet (Snippet):
817 def __init__ (self, type, match, format):
818 Snippet.__init__ (self, type, match, format)
819 os = match.group ('options')
821 self.options = split_options (os)
824 return self.substring ('code')
829 return compose_ly (s, self.options, self.type)
835 self.hash = abs (hash (self.full_ly ()))
840 return 'lily-%d' % self.get_hash ()
844 outf = open (self.basename () + '.ly', 'w')
845 outf.write (self.full_ly ())
847 open (self.basename () + '.txt', 'w').write ('image of music')
849 def ly_is_outdated (self):
850 base = self.basename ()
852 tex_file = '%s.tex' % base
853 eps_file = '%s.eps' % base
854 system_file = '%s-systems.tex' % base
855 ly_file = '%s.ly' % base
856 ok = os.path.exists (ly_file) \
857 and os.path.exists (system_file)\
858 and os.stat (system_file)[stat.ST_SIZE] \
859 and re.match ('% eof', open (system_file).readlines ()[-1])
861 if ok and (use_hash_p \
862 or self.ly () == open (ly_file).read ()):
863 # TODO: Do something smart with target formats
864 # (ps, png) and m/ctimes.
868 def png_is_outdated (self):
869 base = self.basename ()
870 ok = self.ly_is_outdated ()
871 if format == HTML or format == TEXINFO:
872 ok = ok and (os.path.exists (base + '.png')
873 or glob.glob (base + '-page*.png'))
875 def texstr_is_outdated (self):
879 base = self.basename ()
880 ok = self.ly_is_outdated ()
881 ok = ok and (os.path.exists (base + '.texstr'))
884 def filter_text (self):
885 code = self.substring ('code')
886 s = run_filter (code)
889 'options': self.match.group ('options')
892 return output[self.format][FILTER] % d
894 def replacement_text (self):
895 func = Lilypond_snippet.__dict__['output_' + self.format]
898 def get_images (self):
899 base = self.basename ()
901 single = '%(base)s.png' % vars ()
902 multiple = '%(base)s-page1.png' % vars ()
904 if os.path.exists (multiple) \
905 and (not os.path.exists (single) \
906 or (os.stat (multiple)[stat.ST_MTIME] \
907 > os.stat (single)[stat.ST_MTIME])):
908 images = glob.glob ('%(base)s-page*.png' % vars ())
911 def output_html (self):
913 base = self.basename ()
915 str += self.output_print_filename (HTML)
916 if VERBATIM in self.options:
917 verb = verbatim_html (self.substring ('code'))
918 str += write (output[HTML][VERBATIM] % vars ())
919 if QUOTE in self.options:
920 str = output[HTML][QUOTE] % vars ()
922 str += output[HTML][BEFORE] % vars ()
923 for image in self.get_images ():
924 (base, ext) = os.path.splitext (image)
925 str += output[HTML][OUTPUT] % vars ()
926 str += output[HTML][AFTER] % vars ()
929 def output_info (self):
930 str = self.output_print_filename (HTML)
931 for image in self.get_images ():
932 (base, ext) = os.path.splitext (image)
934 # URG, makeinfo implicitly prepends dot to extension.
935 # Specifying no extension is most robust.
937 str += output[TEXINFO][OUTPUT] % vars ()
940 def output_latex (self):
942 base = self.basename ()
944 str += self.output_print_filename (LATEX)
945 if VERBATIM in self.options:
946 verb = self.substring ('code')
947 str += (output[LATEX][VERBATIM] % vars ())
948 if QUOTE in self.options:
949 str = output[LATEX][QUOTE] % vars ()
951 str += (output[LATEX][OUTPUT] % vars ())
954 def output_print_filename (self, format):
956 if PRINTFILENAME in self.options:
957 base = self.basename ()
958 filename = self.substring ('filename')
959 str = output[format][PRINTFILENAME] % vars ()
962 def output_texinfo (self):
964 if self.output_print_filename (TEXINFO):
966 + self.output_print_filename (HTML)
969 + self.output_print_filename (LATEX)
971 base = self.basename ()
972 if TEXIDOC in self.options:
973 texidoc = base + '.texidoc'
974 if os.path.exists (texidoc):
975 str += '@include %(texidoc)s\n\n' % vars ()
977 if VERBATIM in self.options:
978 verb = verbatim_texinfo (self.substring ('code'))
979 str += (output[TEXINFO][VERBATIM] % vars ())
980 if not QUOTE in self.options:
981 str = output[TEXINFO][NOQUOTE] % vars()
983 str += self.output_info ()
984 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
985 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
986 # str += ('@html\n' + self.output_html () + '\n@end html\n')
988 if QUOTE in self.options:
989 str = output[TEXINFO][QUOTE] % vars ()
991 # need par after image
996 class Lilypond_file_snippet (Lilypond_snippet):
998 name = self.substring ('filename')
999 return '\\renameinput \"%s\"\n%s' \
1000 % (name, open (find_file (name)).read ())
1002 snippet_type_to_class = {
1003 'lilypond_file': Lilypond_file_snippet,
1004 'lilypond_block': Lilypond_snippet,
1005 'lilypond': Lilypond_snippet,
1006 'include': Include_snippet,
1009 def find_toplevel_snippets (s, types):
1012 res[i] = ly.re.compile (snippet_res[format][i])
1016 ## found = dict (map (lambda x: (x, None),
1020 map (lambda x, f = found: f.setdefault (x, None),
1023 # We want to search for multiple regexes, without searching
1024 # the string multiple times for one regex.
1025 # Hence, we use earlier results to limit the string portion
1027 # Since every part of the string is traversed at most once for
1028 # every type of snippet, this is linear.
1034 if not found[type] or found[type][0] < index:
1036 m = res[type].search (s[index:endex])
1041 if snippet_type_to_class.has_key (type):
1042 cl = snippet_type_to_class[type]
1043 snip = cl (type, m, format)
1044 start = index + m.start ('match')
1045 found[type] = (start, snip)
1049 or found[type][0] < found[first][0]):
1054 # Limiting the search space is a cute
1055 # idea, but this *requires* to search
1056 # for possible containing blocks
1057 # first, at least as long as we do not
1058 # search for the start of blocks, but
1059 # always/directly for the entire
1060 # @block ... @end block.
1062 endex = found[first][0]
1065 snippets.append (Substring (s, index, len (s)))
1068 (start, snip) = found[first]
1069 snippets.append (Substring (s, index, start))
1070 snippets.append (snip)
1072 index = start + len (snip.match.group ('match'))
1076 def filter_pipe (input, cmd):
1078 ly.progress (_ ("Opening filter `%s'") % cmd)
1080 (stdin, stdout, stderr) = os.popen3 (cmd)
1082 status = stdin.close ()
1086 output = stdout.read ()
1087 status = stdout.close ()
1088 error = stderr.read ()
1092 signal = 0x0f & status
1093 if status or (not output and error):
1094 exit_status = status >> 8
1095 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1096 ly.error (_ ("The error log is as follows:"))
1097 sys.stderr.write (error)
1098 sys.stderr.write (stderr.read ())
1107 return filter_pipe (s, filter_cmd)
1109 def is_derived_class (cl, baseclass):
1112 for b in cl.__bases__:
1113 if is_derived_class (b, baseclass):
1117 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1118 ly_names = filter (lambda x: x,
1119 map (Lilypond_snippet.basename, ly_snippets))
1120 texstr_names = filter (lambda x: x,
1121 map (Lilypond_snippet.basename, texstr_snippets))
1122 png_names = filter (lambda x: x,
1123 map (Lilypond_snippet.basename, png_snippets))
1126 def my_system (cmd):
1127 status = ly.system (cmd,
1128 ignore_error = 1, progress_p = 1)
1131 ly.error ('Process %s exited unsuccessfully.' % cmd)
1135 # the --process=CMD switch is a bad idea
1136 # it is too generic for lilypond-book.
1137 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1139 my_system (string.join ([cmd + ' --backend texstr ' ] + texstr_names))
1140 for l in texstr_names:
1141 my_system ('latex %s.texstr' % l)
1144 my_system (string.join ([cmd] + ly_names))
1146 LATEX_DOCUMENT = r'''
1149 \typeout{textwidth=\the\textwidth}
1150 \typeout{columnsep=\the\columnsep}
1151 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1155 # Do we need anything else besides `textwidth'?
1156 def get_latex_textwidth (source):
1157 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1158 preamble = source[:m.start (0)]
1159 latex_document = LATEX_DOCUMENT % vars ()
1160 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1163 m = re.search ('columns=([0-9.]*)', parameter_string)
1165 columns = string.atoi (m.group (1))
1168 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1170 columnsep = string.atof (m.group (1))
1173 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1175 textwidth = string.atof (m.group (1))
1177 textwidth = (textwidth - columnsep) / columns
1189 '.texinfo': TEXINFO,
1195 # TEXINFO: '.texinfo',
1200 class Compile_error:
1203 def do_process_cmd (chunks):
1205 filter (lambda x: is_derived_class (x.__class__,
1207 and x.ly_is_outdated (),
1210 filter (lambda x: is_derived_class (x.__class__,
1212 and x.texstr_is_outdated (),
1215 filter (lambda x: is_derived_class (x.__class__,
1217 and x.png_is_outdated (),
1220 ly.progress (_ ("Writing snippets..."))
1221 map (Lilypond_snippet.write_ly, ly_outdated)
1225 ly.progress (_ ("Processing...\n"))
1226 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1228 ly.progress (_ ("All snippets are up to date..."))
1231 def do_file (input_filename):
1235 e = os.path.splitext (input_filename)[1]
1236 if e in ext2format.keys ():
1238 format = ext2format[e]
1240 ly.error (_ ("cannot determine format for: %s" \
1244 if not input_filename or input_filename == '-':
1245 in_handle = sys.stdin
1246 input_fullname = '<stdin>'
1248 if os.path.exists (input_filename):
1249 input_fullname = input_filename
1250 elif format == LATEX:
1251 # urg python interface to libkpathsea?
1252 input_fullname = ly.read_pipe ('kpsewhich '
1253 + input_filename)[:-1]
1255 input_fullname = find_file (input_filename)
1256 in_handle = open (input_fullname)
1258 if input_filename == '-':
1259 input_base = 'stdin'
1261 input_base = os.path.basename \
1262 (os.path.splitext (input_filename)[0])
1264 # Only default to stdout when filtering.
1265 if output_name == '-' or (not output_name and filter_cmd):
1266 output_filename = '-'
1267 output_file = sys.stdout
1270 output_filename = input_base + format2ext[format]
1272 if not os.path.isdir (output_name):
1273 os.mkdir (output_name, 0777)
1274 output_filename = (output_name
1276 + format2ext[format])
1278 if os.path.exists (input_filename) \
1279 and os.path.exists (output_filename) \
1280 and os.path.samefile (output_filename, input_fullname):
1282 _ ("Output would overwrite input file; use --output."))
1285 output_file = open (output_filename, 'w')
1287 os.chdir (output_name)
1289 ly.progress (_ ("Reading %s...") % input_fullname)
1290 source = in_handle.read ()
1293 # FIXME: Containing blocks must be first, see
1294 # find_toplevel_snippets.
1296 'multiline_comment',
1300 'singleline_comment',
1305 ly.progress (_ ("Dissecting..."))
1306 chunks = find_toplevel_snippets (source, snippet_types)
1309 global default_ly_options
1311 if not default_ly_options.has_key (LINEWIDTH):
1313 textwidth = get_latex_textwidth (source)
1314 default_ly_options[LINEWIDTH] = \
1315 '''%.0f\\pt''' % textwidth
1316 elif format == TEXINFO:
1317 for (k, v) in texinfo_linewidths.items ():
1318 # FIXME: @layout is usually not in
1321 # \input texinfo @c -*-texinfo-*-
1323 # Bluntly search first K items of
1325 # s = chunks[0].replacement_text ()
1326 if re.search (k, source[:1024]):
1327 default_ly_options[LINEWIDTH] = v
1331 output_file.writelines ([c.filter_text () \
1335 do_process_cmd (chunks)
1336 ly.progress (_ ("Compiling %s...") % output_filename)
1337 output_file.writelines ([s.replacement_text () \
1341 def process_include (snippet):
1342 os.chdir (original_dir)
1343 name = snippet.substring ('filename')
1344 ly.progress (_ ("Processing include: %s") % name)
1348 map (process_include,
1349 filter (lambda x: is_derived_class (x.__class__,
1352 except Compile_error:
1353 os.chdir (original_dir)
1354 ly.progress (_ ("Removing `%s'") % output_filename)
1357 os.unlink (output_filename)
1361 global format, output_name
1362 global filter_cmd, process_cmd, verbose_p
1364 (sh, long) = ly.getopt_args (option_definitions)
1366 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1367 except getopt.error, s:
1368 sys.stderr.write ('\n')
1369 ly.error (_ ("getopt says: `%s'" % s))
1370 sys.stderr.write ('\n')
1380 elif o == '--filter' or o == '-F':
1383 elif o == '--format' or o == '-f':
1385 if a == 'texi-html' or a == 'texi':
1387 elif o == '--tex-backend ':
1389 elif o == '--help' or o == '-h':
1392 elif o == '--include' or o == '-I':
1393 include_path.append (os.path.join (original_dir,
1395 elif o == '--output' or o == '-o':
1397 elif o == '--outdir':
1399 elif o == '--process' or o == '-P':
1402 elif o == '--version' or o == '-v':
1403 ly.identify (sys.stdout)
1405 elif o == '--verbose' or o == '-V':
1407 elif o == '--warranty' or o == '-w':
1414 files = do_options ()
1418 if format == TEXINFO:
1420 if process_cmd == '':
1421 process_cmd = lilypond_binary + ' --formats=%s --backend ps ' % formats
1424 process_cmd += string.join ([(' -I %s' % p)
1425 for p in include_path])
1427 ly.identify (sys.stderr)
1428 ly.setup_environment ()
1432 except Compile_error:
1435 if __name__ == '__main__':