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 -fps?
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 ()
69 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
72 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
73 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
74 lilypond-book --process='lilypond -I include' BOOK
77 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
78 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
80 option_definitions = [
81 (_ ("EXT"), 'f', 'format',
82 _ ('''use output format EXT (texi [default], texi-html,
84 (_ ("FILTER"), 'F', 'filter',
85 _ ("pipe snippets through FILTER [convert-ly -n -]")),
87 _ ("print this help")),
88 (_ ("DIR"), 'I', 'include',
89 _ ("add DIR to include path")),
90 (_ ("DIR"), 'o', 'output',
91 _ ("write output to DIR")),
92 (_ ("COMMAND"), 'P', 'process',
93 _ ("process ly_files using COMMAND FILE...")),
97 _ ("print version information")),
99 _ ("show warranty and copyright")),
102 include_path = [ly.abspath (os.getcwd ())]
103 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
105 # Only use installed binary when we are installed too.
106 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
107 lilypond_binary = 'lilypond'
112 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
115 default_ly_options = {}
118 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
122 EXAMPLEINDENT = 'exampleindent'
124 FRAGMENT = 'fragment'
129 LINEWIDTH = 'linewidth'
130 NOFRAGMENT = 'nofragment'
131 NOINDENT = 'noindent'
137 PREAMBLE = 'preamble'
138 PRINTFILENAME = 'printfilename'
140 RAGGEDRIGHT = 'raggedright'
141 RELATIVE = 'relative'
142 STAFFSIZE = 'staffsize'
145 VERBATIM = 'verbatim'
147 # NOTIME has no opposite so it isn't part of this dictionary.
148 # NOQUOTE is used internally only.
150 NOFRAGMENT: FRAGMENT,
154 # Recognize special sequences in the input.
156 # (?P<name>regex) -- Assign result of REGEX to NAME.
157 # *? -- Match non-greedily.
158 # (?m) -- Multiline regex: Make ^ and $ match at each line.
159 # (?s) -- Make the dot match all characters including newline.
160 # (?x) -- Ignore whitespace in patterns.
172 (\s*(?P<options>.*?)\s*:)?\s*
180 \s*(?P<options>.*?)\s*
189 \s*(?P<options>.*?)\s*
191 \s*(?P<filename>.*?)\s*
198 (?P<code><!--\s.*?!-->)
201 'singleline_comment':
207 (?P<code><pre>.*?</pre>))''',
213 (?P<code><pre>\s.*?</pre>\s))''',
232 \s*(?P<options>.*?)\s*
243 \s*(?P<options>.*?)\s*
247 \\end\s*{lilypond})''',
255 \s*(?P<options>.*?)\s*
263 'singleline_comment':
286 \\end\s*{verbatim}))''',
295 (?P<filename>\S+))''',
299 ^[^\n]*?(?!@c\s+)[^\n]*?
303 \s*(?P<options>.*?)\s*
313 \s*(?P<options>.*?)\s*
316 ^@end\s+lilypond)\s''',
323 \s*(?P<options>.*?)\s*
334 @end\s+ignore))\s''',
336 'singleline_comment':
341 @c([ \t][^\n]*|)\n))''',
343 # Don't do this: It interferes with @code{@{}.
344 # 'verb': r'''(?P<code>@code{.*?})''',
352 @end\s+example\s))''',
358 'intertext': r',?\s*intertext=\".*?\"',
363 'intertext': r',?\s*intertext=\".*?\"',
364 'option_sep': '\s*,\s*',
368 'intertext': r',?\s*intertext=\".*?\"',
369 'option_sep': '\s*,\s*',
373 # Options without a pattern in ly_options.
387 RELATIVE: r'''\relative c%(relative_quotes)s''',
392 INDENT: r'''indent = %(indent)s''',
394 LINEWIDTH: r'''linewidth = %(linewidth)s''',
396 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
398 RAGGEDRIGHT: r'''raggedright = ##t''',
403 NOTIME: r'''\context {
405 \remove Time_signature_engraver
411 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
418 FILTER: r'''<lilypond %(options)s>
428 <a href="%(base)s.ly">''',
431 <img align="center" valign="center"
432 border="0" src="%(image)s" alt="[image of music]">''',
434 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
436 QUOTE: r'''<blockquote>
450 \ifx\preLilyPondExample \undefined
455 \def\lilypondbook{}%%
457 \ifx\postLilyPondExample \undefined
464 PRINTFILENAME: '''\\texttt{%(filename)s}
467 QUOTE: r'''\begin{quotation}
472 VERBATIM: r'''\noindent
474 %(verb)s\end{verbatim}
477 FILTER: r'''\begin{lilypond}[%(options)s]
484 FILTER: r'''@lilypond[%(options)s]
488 OUTPUT: r'''@noindent
489 @image{%(base)s,,,[image of music],%(ext)s}''',
491 PRINTFILENAME: '''@file{%(filename)s}
494 QUOTE: r'''@quotation
495 %(str)s@end quotation
502 VERBATIM: r'''@exampleindent 0
509 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
510 %%%% Options: [%(option_string)s]
512 #(set! toplevel-score-handler ly:parser-print-score)
513 #(set! toplevel-music-handler (lambda (p m)
514 (ly:parser-print-score
515 p (ly:music-scorify m p))))
517 #(define version-seen? #t)
521 #(define dump-extents #t)
533 %% ly snippet contents follows:
545 texinfo_linewidths = {
546 '@afourpaper': '160\\mm',
547 '@afourwide': '6.5\\in',
548 '@afourlatex': '150\\mm',
549 '@smallbook': '5\\in',
550 '@letterpaper': '6\\in',
553 def classic_lilypond_book_compatibility (key, value):
554 if key == 'singleline' and value == None:
555 return (RAGGEDRIGHT, None)
557 m = re.search ('relative\s*([-0-9])', key)
559 return ('relative', m.group (1))
561 m = re.match ('([0-9]+)pt', key)
563 return ('staffsize', m.group (1))
565 if key == 'indent' or key == 'linewidth':
566 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
568 f = float (m.group (1))
569 return (key, '%f\\%s' % (f, m.group (2)))
573 def compose_ly (code, options, type):
577 if string.find (i, '=') > 0:
578 (key, value) = re.split ('\s*=\s*', i)
579 option_dict[key] = value
581 if i in no_options.keys ():
582 if no_options[i] in option_dict.keys ():
583 del option_dict[no_options[i]]
585 option_dict[i] = None
587 has_linewidth = option_dict.has_key (LINEWIDTH)
588 no_linewidth_value = 0
590 # If LINEWIDTH is used without parameter, set it to default.
591 if has_linewidth and option_dict[LINEWIDTH] == None:
592 no_linewidth_value = 1
593 del option_dict[LINEWIDTH]
595 for i in default_ly_options.keys ():
596 if i not in option_dict.keys ():
597 option_dict[i] = default_ly_options[i]
599 if not has_linewidth:
600 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
601 option_dict[RAGGEDRIGHT] = None
603 if type == 'lilypond':
604 if LINEWIDTH in option_dict.keys ():
605 del option_dict[LINEWIDTH]
607 if RAGGEDRIGHT in option_dict.keys ():
608 if LINEWIDTH in option_dict.keys ():
609 del option_dict[LINEWIDTH]
611 if QUOTE in option_dict.keys () or type == 'lilypond':
612 if LINEWIDTH in option_dict.keys ():
613 del option_dict[LINEWIDTH]
615 if not INDENT in option_dict.keys ():
616 option_dict[INDENT] = '0\\mm'
618 # The QUOTE pattern from ly_options only emits the `linewidth'
620 if has_linewidth and QUOTE in option_dict.keys ():
621 if no_linewidth_value:
622 del option_dict[LINEWIDTH]
624 del option_dict[QUOTE]
626 if FRAGMENT in option_dict.keys ():
634 # The original concept of the `exampleindent' option is broken.
635 # It is not possible to get a sane value for @exampleindent at all
636 # without processing the document itself. Saying
644 # causes ugly results with the DVI backend of texinfo since the
645 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
646 # value). Executing the above code changes the environment
647 # indentation to an unknown value because we don't know the amount
648 # of 1em in advance since it is font-dependent. Modifying
649 # @exampleindent in the middle of a document is simply not
650 # supported within texinfo.
652 # As a consequence, the only function of @exampleindent is now to
653 # specify the amount of indentation for the `quote' option.
655 # To set @exampleindent locally to zero, we use the @format
656 # environment for non-quoted snippets.
657 override[EXAMPLEINDENT] = r'0.4\in'
658 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
659 override.update (default_ly_options)
662 for (key, value) in option_dict.items ():
664 option_list.append (key)
666 option_list.append (key + '=' + value)
667 option_string = string.join (option_list, ',')
670 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
671 for a in compose_types:
674 for (key, value) in option_dict.items():
676 classic_lilypond_book_compatibility (key, value)
680 (_ ("deprecated ly-option used: %s=%s" \
683 (_ ("compatibility mode translation: %s=%s" \
687 (_ ("deprecated ly-option used: %s" \
690 (_ ("compatibility mode translation: %s" \
693 (key, value) = (c_key, c_value)
696 override[key] = value
698 if not override.has_key (key):
702 for type in compose_types:
703 if ly_options[type].has_key (key):
704 compose_dict[type].append (ly_options[type][key])
708 if not found and key not in simple_options:
709 ly.warning (_ ("ignoring unknown ly option: %s") % i)
712 if RELATIVE in override.keys () and override[RELATIVE]:
713 relative = string.atoi (override[RELATIVE])
719 relative_quotes += ',' * (- relative)
721 relative_quotes += "'" * relative
723 program_name = __main__.program_name
726 string.join (compose_dict[PAPER], '\n ') % override
728 string.join (compose_dict[LAYOUT], '\n ') % override
730 string.join (compose_dict[NOTES], '\n ') % vars ()
732 string.join (compose_dict[PREAMBLE], '\n ') % override
734 return (PREAMBLE_LY + body) % vars ()
737 # Use lilypond for latex (.lytex) books,
738 # and lilypond --preview for html, texinfo books?
740 cmd = r'latex "\nonstopmode \input %s"' % file
741 # Ugh. (La)TeX writes progress and error messages on stdout.
742 # Redirect to stderr.
743 cmd = '(( %s >&2 ) >&- )' % cmd
746 'dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -E -o %s.eps %s' \
749 # Check if it really is EPS.
750 # Otherwise music glyphs disappear from 2nd and following pages.
752 # TODO: Should run dvips -pp -E per page, then we get proper
755 f = open ('%s.eps' % file)
756 for x in range (0, 10):
757 if re.search ('^%%Pages: ', f.readline ()):
760 'dvips -Ppdf -u+ec-mftrace.map -u+lilypond.map -o %s.eps %s' \
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 ly_file = '%s.ly' % base
874 ok = os.path.exists (ly_file) \
875 and os.path.exists (tex_file)\
876 and os.stat (tex_file)[stat.ST_SIZE] \
877 and open (tex_file).readlines ()[-1][1:-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):
895 base = self.basename ()
896 ok = self.ly_is_outdated ()
897 ok = ok and (os.path.exists (base + '.texstr'))
900 def filter_text (self):
901 code = self.substring ('code')
902 s = run_filter (code)
905 'options': self.match.group ('options')
908 return output[self.format][FILTER] % d
910 def replacement_text (self):
911 func = Lilypond_snippet.__dict__['output_' + self.format]
914 def get_images (self):
915 base = self.basename ()
917 single = '%(base)s.png' % vars ()
918 multiple = '%(base)s-page1.png' % vars ()
920 if os.path.exists (multiple) \
921 and (not os.path.exists (single) \
922 or (os.stat (multiple)[stat.ST_MTIME] \
923 > os.stat (single)[stat.ST_MTIME])):
924 images = glob.glob ('%(base)s-page*.png' % vars ())
927 def output_html (self):
929 base = self.basename ()
931 str += self.output_print_filename (HTML)
932 if VERBATIM in self.options:
933 verb = verbatim_html (self.substring ('code'))
934 str += write (output[HTML][VERBATIM] % vars ())
935 if QUOTE in self.options:
936 str = output[HTML][QUOTE] % vars ()
938 str += output[HTML][BEFORE] % vars ()
939 for image in self.get_images ():
940 (base, ext) = os.path.splitext (image)
941 str += output[HTML][OUTPUT] % vars ()
942 str += output[HTML][AFTER] % vars ()
945 def output_info (self):
946 str = self.output_print_filename (HTML)
947 for image in self.get_images ():
948 (base, ext) = os.path.splitext (image)
950 # URG, makeinfo implicitly prepends dot to extension.
951 # Specifying no extension is most robust.
953 str += output[TEXINFO][OUTPUT] % vars ()
956 def output_latex (self):
958 base = self.basename ()
960 str += self.output_print_filename (LATEX)
961 if VERBATIM in self.options:
962 verb = self.substring ('code')
963 str += (output[LATEX][VERBATIM] % vars ())
964 if QUOTE in self.options:
965 str = output[LATEX][QUOTE] % vars ()
967 str += (output[LATEX][OUTPUT] % vars ())
970 def output_print_filename (self, format):
972 if PRINTFILENAME in self.options:
973 base = self.basename ()
974 filename = self.substring ('filename')
975 str = output[format][PRINTFILENAME] % vars ()
978 def output_texinfo (self):
980 if self.output_print_filename (TEXINFO):
982 + self.output_print_filename (HTML)
985 + self.output_print_filename (LATEX)
987 base = self.basename ()
988 if TEXIDOC in self.options:
989 texidoc = base + '.texidoc'
990 if os.path.exists (texidoc):
991 str += '@include %(texidoc)s\n\n' % vars ()
993 if VERBATIM in self.options:
994 verb = verbatim_texinfo (self.substring ('code'))
995 str += (output[TEXINFO][VERBATIM] % vars ())
996 if not QUOTE in self.options:
997 str = output[TEXINFO][NOQUOTE] % vars()
999 str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1000 str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1001 str += ('@html\n' + self.output_html () + '\n@end html\n')
1003 if QUOTE in self.options:
1004 str = output[TEXINFO][QUOTE] % vars ()
1006 # need par after image
1011 class Lilypond_file_snippet (Lilypond_snippet):
1013 name = self.substring ('filename')
1014 return '\\renameinput \"%s\"\n%s' \
1015 % (name, open (find_file (name)).read ())
1017 snippet_type_to_class = {
1018 'lilypond_file': Lilypond_file_snippet,
1019 'lilypond_block': Lilypond_snippet,
1020 'lilypond': Lilypond_snippet,
1021 'include': Include_snippet,
1024 def find_toplevel_snippets (s, types):
1027 res[i] = ly.re.compile (snippet_res[format][i])
1031 ## found = dict (map (lambda x: (x, None),
1035 map (lambda x, f = found: f.setdefault (x, None),
1038 # We want to search for multiple regexes, without searching
1039 # the string multiple times for one regex.
1040 # Hence, we use earlier results to limit the string portion
1042 # Since every part of the string is traversed at most once for
1043 # every type of snippet, this is linear.
1049 if not found[type] or found[type][0] < index:
1051 m = res[type].search (s[index:endex])
1056 if snippet_type_to_class.has_key (type):
1057 cl = snippet_type_to_class[type]
1058 snip = cl (type, m, format)
1059 start = index + m.start ('match')
1060 found[type] = (start, snip)
1064 or found[type][0] < found[first][0]):
1069 # Limiting the search space is a cute
1070 # idea, but this *requires* to search
1071 # for possible containing blocks
1072 # first, at least as long as we do not
1073 # search for the start of blocks, but
1074 # always/directly for the entire
1075 # @block ... @end block.
1077 endex = found[first][0]
1080 snippets.append (Substring (s, index, len (s)))
1083 (start, snip) = found[first]
1084 snippets.append (Substring (s, index, start))
1085 snippets.append (snip)
1087 index = start + len (snip.match.group ('match'))
1091 def filter_pipe (input, cmd):
1093 ly.progress (_ ("Opening filter `%s'") % cmd)
1095 (stdin, stdout, stderr) = os.popen3 (cmd)
1097 status = stdin.close ()
1101 output = stdout.read ()
1102 status = stdout.close ()
1103 error = stderr.read ()
1107 signal = 0x0f & status
1108 if status or (not output and error):
1109 exit_status = status >> 8
1110 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1111 ly.error (_ ("The error log is as follows:"))
1112 sys.stderr.write (error)
1113 sys.stderr.write (stderr.read ())
1122 return filter_pipe (s, filter_cmd)
1124 def is_derived_class (cl, baseclass):
1127 for b in cl.__bases__:
1128 if is_derived_class (b, baseclass):
1132 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1133 ly_names = filter (lambda x: x,
1134 map (Lilypond_snippet.basename, ly_snippets))
1135 texstr_names = filter (lambda x: x,
1136 map (Lilypond_snippet.basename, texstr_snippets))
1137 png_names = filter (lambda x: x,
1138 map (Lilypond_snippet.basename, png_snippets))
1141 def my_system (cmd):
1142 status = ly.system (cmd,
1143 ignore_error = 1, progress_p = 1)
1146 ly.error ('Process %s exited unsuccessfully.' % cmd)
1150 my_system (string.join ([cmd + ' -f texstr ' ] + texstr_names))
1151 for l in texstr_names:
1152 my_system ('latex %s.texstr' % l)
1156 my_system (string.join ([cmd] + ly_names))
1160 if format == HTML or format == TEXINFO:
1162 if not os.path.exists (i + '.eps') \
1163 and os.path.exists (i + '.tex'):
1165 ly.make_ps_images (i + '.eps',
1168 # elif os.path.exists (i + '.ps'):
1169 # ly.make_ps_images (i + '.ps', resolution = 110)
1171 LATEX_DOCUMENT = r'''
1174 \typeout{textwidth=\the\textwidth}
1175 \typeout{columnsep=\the\columnsep}
1176 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1180 # Do we need anything else besides `textwidth'?
1181 def get_latex_textwidth (source):
1182 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1183 preamble = source[:m.start (0)]
1184 latex_document = LATEX_DOCUMENT % vars ()
1185 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1188 m = re.search ('columns=([0-9.]*)', parameter_string)
1190 columns = string.atoi (m.group (1))
1193 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1195 columnsep = string.atof (m.group (1))
1198 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1200 textwidth = string.atof (m.group (1))
1202 textwidth = (textwidth - columnsep) / columns
1214 '.texinfo': TEXINFO,
1220 # TEXINFO: '.texinfo',
1225 class Compile_error:
1228 def do_process_cmd (chunks):
1230 filter (lambda x: is_derived_class (x.__class__,
1232 and x.ly_is_outdated (),
1235 filter (lambda x: is_derived_class (x.__class__,
1237 and x.texstr_is_outdated (),
1240 filter (lambda x: is_derived_class (x.__class__,
1242 and x.png_is_outdated (),
1245 ly.progress (_ ("Writing snippets..."))
1246 map (Lilypond_snippet.write_ly, ly_outdated)
1250 ly.progress (_ ("Processing...\n"))
1251 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1253 ly.progress (_ ("All snippets are up to date..."))
1256 def do_file (input_filename):
1260 e = os.path.splitext (input_filename)[1]
1261 if e in ext2format.keys ():
1263 format = ext2format[e]
1265 ly.error (_ ("cannot determine format for: %s" \
1269 if not input_filename or input_filename == '-':
1270 in_handle = sys.stdin
1271 input_fullname = '<stdin>'
1273 if os.path.exists (input_filename):
1274 input_fullname = input_filename
1275 elif format == LATEX:
1276 # urg python interface to libkpathsea?
1277 input_fullname = ly.read_pipe ('kpsewhich '
1278 + input_filename)[:-1]
1280 input_fullname = find_file (input_filename)
1281 in_handle = open (input_fullname)
1283 if input_filename == '-':
1284 input_base = 'stdin'
1286 input_base = os.path.basename \
1287 (os.path.splitext (input_filename)[0])
1289 # Only default to stdout when filtering.
1290 if output_name == '-' or (not output_name and filter_cmd):
1291 output_filename = '-'
1292 output_file = sys.stdout
1295 output_filename = input_base + format2ext[format]
1297 if not os.path.isdir (output_name):
1298 os.mkdir (output_name, 0777)
1299 output_filename = (output_name
1301 + format2ext[format])
1303 if os.path.exists (input_filename) \
1304 and os.path.exists (output_filename) \
1305 and os.path.samefile (output_filename, input_fullname):
1307 _ ("Output would overwrite input file; use --output."))
1310 output_file = open (output_filename, 'w')
1312 os.chdir (output_name)
1314 ly.progress (_ ("Reading %s...") % input_fullname)
1315 source = in_handle.read ()
1318 # FIXME: Containing blocks must be first, see
1319 # find_toplevel_snippets.
1321 'multiline_comment',
1325 'singleline_comment',
1330 ly.progress (_ ("Dissecting..."))
1331 chunks = find_toplevel_snippets (source, snippet_types)
1334 global default_ly_options
1336 if not default_ly_options.has_key (LINEWIDTH):
1338 textwidth = get_latex_textwidth (source)
1339 default_ly_options[LINEWIDTH] = \
1340 '''%.0f\\pt''' % textwidth
1341 elif format == TEXINFO:
1342 for (k, v) in texinfo_linewidths.items ():
1343 # FIXME: @layout is usually not in
1346 # \input texinfo @c -*-texinfo-*-
1348 # Bluntly search first K items of
1350 # s = chunks[0].replacement_text ()
1351 if re.search (k, source[:1024]):
1352 default_ly_options[LINEWIDTH] = v
1356 output_file.writelines ([c.filter_text () \
1360 do_process_cmd (chunks)
1361 ly.progress (_ ("Compiling %s...") % output_filename)
1362 output_file.writelines ([s.replacement_text () \
1366 def process_include (snippet):
1367 os.chdir (original_dir)
1368 name = snippet.substring ('filename')
1369 ly.progress (_ ("Processing include: %s") % name)
1373 map (process_include,
1374 filter (lambda x: is_derived_class (x.__class__,
1377 except Compile_error:
1378 os.chdir (original_dir)
1379 ly.progress (_ ("Removing `%s'") % output_filename)
1382 os.unlink (output_filename)
1386 global format, output_name
1387 global filter_cmd, process_cmd, verbose_p
1389 (sh, long) = ly.getopt_args (option_definitions)
1391 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1392 except getopt.error, s:
1393 sys.stderr.write ('\n')
1394 ly.error (_ ("getopt says: `%s'" % s))
1395 sys.stderr.write ('\n')
1405 elif o == '--filter' or o == '-F':
1408 elif o == '--format' or o == '-f':
1410 if a == 'texi-html' or a == 'texi':
1412 elif o == '--help' or o == '-h':
1415 elif o == '--include' or o == '-I':
1416 include_path.append (os.path.join (original_dir,
1418 elif o == '--output' or o == '-o':
1420 elif o == '--outdir':
1422 elif o == '--process' or o == '-P':
1425 elif o == '--version' or o == '-v':
1426 ly.identify (sys.stdout)
1428 elif o == '--verbose' or o == '-V':
1430 elif o == '--warranty' or o == '-w':
1437 files = do_options ()
1439 if process_cmd == '':
1440 process_cmd = lilypond_binary
1443 process_cmd += string.join ([(' -I %s' % p)
1444 for p in include_path])
1446 ly.identify (sys.stderr)
1447 ly.setup_environment ()
1451 except Compile_error:
1454 if __name__ == '__main__':