7 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
10 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
12 classic lilypond-book:
13 lilypond-book --process="lilypond" BOOK.tely
16 * ly-options: intertext?
18 * eps in latex / eps by lilypond -b ps?
19 * check latex parameters, twocolumn, multicolumn?
20 * use --png --ps --pdf for making images?
22 * Converting from lilypond-book source, substitute:
23 @mbinclude foo.itely -> @include foo.itely
33 # Users of python modules should include this snippet
34 # and customize variables below.
36 # We'll suffer this path initialization stuff as long as we don't install
37 # our python packages in <prefix>/lib/pythonX.Y (and don't kludge around
38 # it as we do with teTeX on Red Hat Linux: set some environment variables
39 # (PYTHONPATH) in `etc/profile').
41 # If set, LILYPONDPREFIX must take prevalence.
42 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
43 import getopt, os, sys
44 datadir = '@local_lilypond_datadir@'
45 if not os.path.isdir (datadir):
46 datadir = '@lilypond_datadir@'
47 if os.environ.has_key ('LILYPONDPREFIX'):
48 datadir = os.environ['LILYPONDPREFIX']
49 while datadir[-1] == os.sep:
52 sys.path.insert (0, os.path.join (datadir, 'python'))
55 #if __name__ == '__main__':
62 program_version = '@TOPLEVEL_VERSION@'
63 program_name = sys.argv[0]
66 original_dir = os.getcwd ()
70 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
73 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
74 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
75 lilypond-book --process='lilypond -I include' BOOK
78 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
79 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
81 option_definitions = [
82 (_ ("EXT"), 'f', 'format',
83 _ ('''use output format EXT (texi [default], texi-html,
85 (_ ("FILTER"), 'F', 'filter',
86 _ ("pipe snippets through FILTER [convert-ly -n -]")),
88 _ ("print this help")),
89 (_ ("DIR"), 'I', 'include',
90 _ ("add DIR to include path")),
91 (_ ("DIR"), 'o', 'output',
92 _ ("write output to DIR")),
93 (_ ("COMMAND"), 'P', 'process',
94 _ ("process ly_files using COMMAND FILE...")),
98 _ ("print version information")),
100 _ ("show warranty and copyright")),
103 include_path = [ly.abspath (os.getcwd ())]
104 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
106 # Only use installed binary when we are installed too.
107 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
108 lilypond_binary = 'lilypond'
113 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
116 default_ly_options = {}
119 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
123 EXAMPLEINDENT = 'exampleindent'
125 FRAGMENT = 'fragment'
130 LINEWIDTH = 'linewidth'
131 NOFRAGMENT = 'nofragment'
132 NOINDENT = 'noindent'
137 OUTPUTIMAGE = 'outputimage'
140 PREAMBLE = 'preamble'
141 PRINTFILENAME = 'printfilename'
143 RAGGEDRIGHT = 'raggedright'
144 RELATIVE = 'relative'
145 STAFFSIZE = 'staffsize'
148 VERBATIM = 'verbatim'
149 FONTLOAD = 'fontload'
152 # NOTIME has no opposite so it isn't part of this dictionary.
153 # NOQUOTE is used internally only.
155 NOFRAGMENT: FRAGMENT,
159 # Recognize special sequences in the input.
161 # (?P<name>regex) -- Assign result of REGEX to NAME.
162 # *? -- Match non-greedily.
163 # (?m) -- Multiline regex: Make ^ and $ match at each line.
164 # (?s) -- Make the dot match all characters including newline.
165 # (?x) -- Ignore whitespace in patterns.
177 (\s*(?P<options>.*?)\s*:)?\s*
185 \s*(?P<options>.*?)\s*
194 \s*(?P<options>.*?)\s*
196 \s*(?P<filename>.*?)\s*
203 (?P<code><!--\s.*?!-->)
206 'singleline_comment':
212 (?P<code><pre>.*?</pre>))''',
218 (?P<code><pre>\s.*?</pre>\s))''',
237 \s*(?P<options>.*?)\s*
248 \s*(?P<options>.*?)\s*
252 \\end\s*{lilypond})''',
260 \s*(?P<options>.*?)\s*
268 'singleline_comment':
291 \\end\s*{verbatim}))''',
300 (?P<filename>\S+))''',
304 ^[^\n]*?(?!@c\s+)[^\n]*?
308 \s*(?P<options>.*?)\s*
318 \s*(?P<options>.*?)\s*
321 ^@end\s+lilypond)\s''',
328 \s*(?P<options>.*?)\s*
339 @end\s+ignore))\s''',
341 'singleline_comment':
346 @c([ \t][^\n]*|)\n))''',
348 # Don't do this: It interferes with @code{@{}.
349 # 'verb': r'''(?P<code>@code{.*?})''',
357 @end\s+example\s))''',
363 'intertext': r',?\s*intertext=\".*?\"',
368 'intertext': r',?\s*intertext=\".*?\"',
369 'option_sep': '\s*,\s*',
373 'intertext': r',?\s*intertext=\".*?\"',
374 'option_sep': '\s*,\s*',
378 # Options without a pattern in ly_options.
393 RELATIVE: r'''\relative c%(relative_quotes)s''',
398 INDENT: r'''indent = %(indent)s''',
400 LINEWIDTH: r'''linewidth = %(linewidth)s''',
402 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
404 RAGGEDRIGHT: r'''raggedright = ##t''',
406 PACKED: r'''packed = ##t''',
411 NOTIME: r'''\context {
413 \remove Time_signature_engraver
419 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
426 FILTER: r'''<lilypond %(options)s>
436 <a href="%(base)s.ly">''',
439 <img align="center" valign="center"
440 border="0" src="%(image)s" alt="[image of music]">''',
442 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
444 QUOTE: r'''<blockquote>
458 \ifx\preLilyPondExample \undefined
463 \def\lilypondbook{}%%
464 \input %(base)s-systems.tex
465 \ifx\postLilyPondExample \undefined
472 PRINTFILENAME: '''\\texttt{%(filename)s}
475 QUOTE: r'''\begin{quotation}
480 VERBATIM: r'''\noindent
482 %(verb)s\end{verbatim}
485 FILTER: r'''\begin{lilypond}[%(options)s]
492 FILTER: r'''@lilypond[%(options)s]
498 @include %(base)s-systems.texi
502 OUTPUTIMAGE: r'''@noindent
504 @image{%(base)s,,,[image of music],%(ext)s}
508 <a href="%(base)s.ly">
509 <img align="center" valign="center"
510 border="0" src="%(image)s" alt="[image of music]">
516 PRINTFILENAME: '''@file{%(filename)s}
519 QUOTE: r'''@quotation
520 %(str)s@end quotation
527 VERBATIM: r'''@exampleindent 0
534 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
535 %%%% Options: [%(option_string)s]
537 #(set! toplevel-score-handler ly:parser-print-score)
538 #(set! toplevel-music-handler (lambda (p m)
539 (ly:parser-print-score
540 p (ly:music-scorify m p))))
542 #(define version-seen? #t)
546 #(define dump-extents #t)
547 %(font_dump_setting)s
559 %% ly snippet contents follows:
571 texinfo_linewidths = {
572 '@afourpaper': '160\\mm',
573 '@afourwide': '6.5\\in',
574 '@afourlatex': '150\\mm',
575 '@smallbook': '5\\in',
576 '@letterpaper': '6\\in',
579 def classic_lilypond_book_compatibility (key, value):
580 if key == 'singleline' and value == None:
581 return (RAGGEDRIGHT, None)
583 m = re.search ('relative\s*([-0-9])', key)
585 return ('relative', m.group (1))
587 m = re.match ('([0-9]+)pt', key)
589 return ('staffsize', m.group (1))
591 if key == 'indent' or key == 'linewidth':
592 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
594 f = float (m.group (1))
595 return (key, '%f\\%s' % (f, m.group (2)))
599 def compose_ly (code, options, type):
603 if string.find (i, '=') > 0:
604 (key, value) = re.split ('\s*=\s*', i)
605 option_dict[key] = value
607 if i in no_options.keys ():
608 if no_options[i] in option_dict.keys ():
609 del option_dict[no_options[i]]
611 option_dict[i] = None
613 has_linewidth = option_dict.has_key (LINEWIDTH)
614 no_linewidth_value = 0
616 # If LINEWIDTH is used without parameter, set it to default.
617 if has_linewidth and option_dict[LINEWIDTH] == None:
618 no_linewidth_value = 1
619 del option_dict[LINEWIDTH]
621 for i in default_ly_options.keys ():
622 if i not in option_dict.keys ():
623 option_dict[i] = default_ly_options[i]
625 if not has_linewidth:
626 if type == 'lilypond' or FRAGMENT in option_dict.keys ():
627 option_dict[RAGGEDRIGHT] = None
629 if type == 'lilypond':
630 if LINEWIDTH in option_dict.keys ():
631 del option_dict[LINEWIDTH]
633 if RAGGEDRIGHT in option_dict.keys ():
634 if LINEWIDTH in option_dict.keys ():
635 del option_dict[LINEWIDTH]
637 if QUOTE in option_dict.keys () or type == 'lilypond':
638 if LINEWIDTH in option_dict.keys ():
639 del option_dict[LINEWIDTH]
641 if not INDENT in option_dict.keys ():
642 option_dict[INDENT] = '0\\mm'
644 # The QUOTE pattern from ly_options only emits the `linewidth'
646 if has_linewidth and QUOTE in option_dict.keys ():
647 if no_linewidth_value:
648 del option_dict[LINEWIDTH]
650 del option_dict[QUOTE]
652 if FRAGMENT in option_dict.keys ():
660 # The original concept of the `exampleindent' option is broken.
661 # It is not possible to get a sane value for @exampleindent at all
662 # without processing the document itself. Saying
670 # causes ugly results with the DVI backend of texinfo since the
671 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
672 # value). Executing the above code changes the environment
673 # indentation to an unknown value because we don't know the amount
674 # of 1em in advance since it is font-dependent. Modifying
675 # @exampleindent in the middle of a document is simply not
676 # supported within texinfo.
678 # As a consequence, the only function of @exampleindent is now to
679 # specify the amount of indentation for the `quote' option.
681 # To set @exampleindent locally to zero, we use the @format
682 # environment for non-quoted snippets.
683 override[EXAMPLEINDENT] = r'0.4\in'
684 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
685 override.update (default_ly_options)
688 for (key, value) in option_dict.items ():
690 option_list.append (key)
692 option_list.append (key + '=' + value)
693 option_string = string.join (option_list, ',')
696 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
697 for a in compose_types:
700 for (key, value) in option_dict.items():
702 classic_lilypond_book_compatibility (key, value)
706 (_ ("deprecated ly-option used: %s=%s" \
709 (_ ("compatibility mode translation: %s=%s" \
713 (_ ("deprecated ly-option used: %s" \
716 (_ ("compatibility mode translation: %s" \
719 (key, value) = (c_key, c_value)
722 override[key] = value
724 if not override.has_key (key):
728 for type in compose_types:
729 if ly_options[type].has_key (key):
730 compose_dict[type].append (ly_options[type][key])
734 if not found and key not in simple_options:
735 ly.warning (_ ("ignoring unknown ly option: %s") % i)
738 if RELATIVE in override.keys () and override[RELATIVE]:
739 relative = string.atoi (override[RELATIVE])
745 relative_quotes += ',' * (- relative)
747 relative_quotes += "'" * relative
749 program_name = __main__.program_name
752 string.join (compose_dict[PAPER], '\n ') % override
754 string.join (compose_dict[LAYOUT], '\n ') % override
756 string.join (compose_dict[NOTES], '\n ') % vars ()
758 string.join (compose_dict[PREAMBLE], '\n ') % override
760 font_dump_setting = ''
761 if FONTLOAD in options:
762 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
764 return (PREAMBLE_LY + body) % vars ()
767 def find_file (name):
768 for i in include_path:
769 full = os.path.join (i, name)
770 if os.path.exists (full):
772 ly.error (_ ("file not found: %s") % name + '\n')
776 def verbatim_html (s):
777 return re.sub ('>', '>',
779 re.sub ('&', '&', s)))
781 def verbatim_texinfo (s):
782 return re.sub ('{', '@{',
784 re.sub ('@', '@@', s)))
786 def split_options (option_string):
787 return re.split (format_res[format]['option_sep'], option_string)
790 def replacement_text (self):
793 def filter_text (self):
794 return self.replacement_text ()
796 def ly_is_outdated (self):
799 def png_is_outdated (self):
802 class Substring (Chunk):
803 def __init__ (self, source, start, end, line_number):
807 self.line_number = line_number
809 def replacement_text (self):
810 return self.source[self.start:self.end]
812 class Snippet (Chunk):
813 def __init__ (self, type, match, format, line_number):
819 self.line_number = line_number
821 def replacement_text (self):
822 return self.match.group ('match')
824 def substring (self, s):
825 return self.match.group (s)
828 return `self.__class__` + ' type = ' + self.type
830 class Include_snippet (Snippet):
831 def processed_filename (self):
832 f = self.substring ('filename')
833 return os.path.splitext (f)[0] + format2ext[format]
835 def replacement_text (self):
836 s = self.match.group ('match')
837 f = self.substring ('filename')
839 return re.sub (f, self.processed_filename (), s)
841 class Lilypond_snippet (Snippet):
842 def __init__ (self, type, match, format, line_number):
843 Snippet.__init__ (self, type, match, format, line_number)
844 os = match.group ('options')
846 self.options = split_options (os)
849 return self.substring ('code')
854 return compose_ly (s, self.options, self.type)
860 self.hash = abs (hash (self.full_ly ()))
865 return 'lily-%d' % self.get_hash ()
869 outf = open (self.basename () + '.ly', 'w')
870 outf.write (self.full_ly ())
872 open (self.basename () + '.txt', 'w').write ('image of music')
874 def ly_is_outdated (self):
875 base = self.basename ()
877 tex_file = '%s.tex' % base
878 eps_file = '%s.eps' % base
879 system_file = '%s-systems.tex' % base
880 ly_file = '%s.ly' % base
881 ok = os.path.exists (ly_file) \
882 and os.path.exists (system_file)\
883 and os.stat (system_file)[stat.ST_SIZE] \
884 and re.match ('% eof', open (system_file).readlines ()[-1])
885 if ok and (use_hash_p \
886 or self.ly () == open (ly_file).read ()):
887 # TODO: Do something smart with target formats
888 # (ps, png) and m/ctimes.
892 def png_is_outdated (self):
893 base = self.basename ()
894 ok = self.ly_is_outdated ()
895 if format == HTML or format == TEXINFO:
896 ok = ok and (os.path.exists (base + '.png')
897 or glob.glob (base + '-page*.png'))
899 def texstr_is_outdated (self):
903 base = self.basename ()
904 ok = self.ly_is_outdated ()
905 ok = ok and (os.path.exists (base + '.texstr'))
908 def filter_text (self):
909 code = self.substring ('code')
910 s = run_filter (code)
913 'options': self.match.group ('options')
916 return output[self.format][FILTER] % d
918 def replacement_text (self):
919 func = Lilypond_snippet.__dict__['output_' + self.format]
922 def get_images (self):
923 base = self.basename ()
925 single = '%(base)s.png' % vars ()
926 multiple = '%(base)s-page1.png' % vars ()
928 if os.path.exists (multiple) \
929 and (not os.path.exists (single) \
930 or (os.stat (multiple)[stat.ST_MTIME] \
931 > os.stat (single)[stat.ST_MTIME])):
932 images = glob.glob ('%(base)s-page*.png' % vars ())
935 def output_html (self):
937 base = self.basename ()
939 str += self.output_print_filename (HTML)
940 if VERBATIM in self.options:
941 verb = verbatim_html (self.substring ('code'))
942 str += write (output[HTML][VERBATIM] % vars ())
943 if QUOTE in self.options:
944 str = output[HTML][QUOTE] % vars ()
946 str += output[HTML][BEFORE] % vars ()
947 for image in self.get_images ():
948 (base, ext) = os.path.splitext (image)
949 str += output[HTML][OUTPUT] % vars ()
950 str += output[HTML][AFTER] % vars ()
953 def output_info (self):
955 for image in self.get_images ():
956 (base, ext) = os.path.splitext (image)
958 # URG, makeinfo implicitly prepends dot to extension.
959 # Specifying no extension is most robust.
961 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
963 base = self.basename ()
964 str += output[format][OUTPUT] % vars ()
967 def output_latex (self):
969 base = self.basename ()
971 str += self.output_print_filename (LATEX)
972 if VERBATIM in self.options:
973 verb = self.substring ('code')
974 str += (output[LATEX][VERBATIM] % vars ())
975 if QUOTE in self.options:
976 str = output[LATEX][QUOTE] % vars ()
978 str += (output[LATEX][OUTPUT] % vars ())
981 def output_print_filename (self, format):
983 if PRINTFILENAME in self.options:
984 base = self.basename ()
985 filename = self.substring ('filename')
986 str = output[format][PRINTFILENAME] % vars ()
990 def output_texinfo (self):
992 if self.output_print_filename (TEXINFO):
994 + self.output_print_filename (HTML)
997 + self.output_print_filename (LATEX)
999 base = self.basename ()
1000 if TEXIDOC in self.options:
1001 texidoc = base + '.texidoc'
1002 if os.path.exists (texidoc):
1003 str += '@include %(texidoc)s\n\n' % vars ()
1005 if VERBATIM in self.options:
1006 verb = verbatim_texinfo (self.substring ('code'))
1007 str += (output[TEXINFO][VERBATIM] % vars ())
1008 if not QUOTE in self.options:
1009 str = output[TEXINFO][NOQUOTE] % vars ()
1011 str += self.output_info ()
1013 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1014 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1015 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1017 if QUOTE in self.options:
1018 str = output[TEXINFO][QUOTE] % vars ()
1020 # need par after image
1025 class Lilypond_file_snippet (Lilypond_snippet):
1027 name = self.substring ('filename')
1028 return '\\renameinput \"%s\"\n%s' \
1029 % (name, open (find_file (name)).read ())
1031 snippet_type_to_class = {
1032 'lilypond_file': Lilypond_file_snippet,
1033 'lilypond_block': Lilypond_snippet,
1034 'lilypond': Lilypond_snippet,
1035 'include': Include_snippet,
1038 def find_linestarts (s):
1043 i = s.find ('\n', start)
1051 nls.append (len (s))
1054 def find_toplevel_snippets (s, types):
1057 res[i] = ly.re.compile (snippet_res[format][i])
1061 ## found = dict (map (lambda x: (x, None),
1065 map (lambda x, f = found: f.setdefault (x, None),
1068 line_starts = find_linestarts (s)
1070 # We want to search for multiple regexes, without searching
1071 # the string multiple times for one regex.
1072 # Hence, we use earlier results to limit the string portion
1074 # Since every part of the string is traversed at most once for
1075 # every type of snippet, this is linear.
1081 if not found[type] or found[type][0] < index:
1083 m = res[type].search (s[index:endex])
1088 if snippet_type_to_class.has_key (type):
1089 cl = snippet_type_to_class[type]
1091 line_number = line_start_idx
1092 while (line_starts[line_number] < index):
1096 snip = cl (type, m, format, line_number)
1097 start = index + m.start ('match')
1098 found[type] = (start, snip)
1102 or found[type][0] < found[first][0]):
1107 # Limiting the search space is a cute
1108 # idea, but this *requires* to search
1109 # for possible containing blocks
1110 # first, at least as long as we do not
1111 # search for the start of blocks, but
1112 # always/directly for the entire
1113 # @block ... @end block.
1115 endex = found[first][0]
1118 snippets.append (Substring (s, index, len (s), line_start_idx))
1121 while (start > line_starts[line_start_idx+1]):
1124 (start, snip) = found[first]
1125 snippets.append (Substring (s, index, start, line_start_idx + 1))
1126 snippets.append (snip)
1128 index = start + len (snip.match.group ('match'))
1132 def filter_pipe (input, cmd):
1134 ly.progress (_ ("Opening filter `%s'") % cmd)
1136 (stdin, stdout, stderr) = os.popen3 (cmd)
1138 status = stdin.close ()
1142 output = stdout.read ()
1143 status = stdout.close ()
1144 error = stderr.read ()
1148 signal = 0x0f & status
1149 if status or (not output and error):
1150 exit_status = status >> 8
1151 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1152 ly.error (_ ("The error log is as follows:"))
1153 sys.stderr.write (error)
1154 sys.stderr.write (stderr.read ())
1163 return filter_pipe (s, filter_cmd)
1165 def is_derived_class (cl, baseclass):
1168 for b in cl.__bases__:
1169 if is_derived_class (b, baseclass):
1173 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1174 ly_names = filter (lambda x: x,
1175 map (Lilypond_snippet.basename, ly_snippets))
1176 texstr_names = filter (lambda x: x,
1177 map (Lilypond_snippet.basename, texstr_snippets))
1178 png_names = filter (lambda x: x,
1179 map (Lilypond_snippet.basename, png_snippets))
1182 def my_system (cmd):
1183 status = ly.system (cmd,
1184 ignore_error = 1, progress_p = 1)
1187 ly.error ('Process %s exited unsuccessfully.' % cmd)
1191 # the --process=CMD switch is a bad idea
1192 # it is too generic for lilypond-book.
1193 if texstr_names and re.search ('^[0-9A-Za-z/]*lilypond', cmd):
1195 my_system (string.join ([cmd,'--backend texstr', 'snippet-map.ly'] + texstr_names))
1196 for l in texstr_names:
1197 my_system ('latex %s.texstr' % l)
1200 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1202 LATEX_DOCUMENT = r'''
1205 \typeout{textwidth=\the\textwidth}
1206 \typeout{columnsep=\the\columnsep}
1207 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1211 # Do we need anything else besides `textwidth'?
1212 def get_latex_textwidth (source):
1213 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1214 preamble = source[:m.start (0)]
1215 latex_document = LATEX_DOCUMENT % vars ()
1216 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1219 m = re.search ('columns=([0-9.]*)', parameter_string)
1221 columns = string.atoi (m.group (1))
1224 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1226 columnsep = string.atof (m.group (1))
1229 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1231 textwidth = string.atof (m.group (1))
1233 textwidth = (textwidth - columnsep) / columns
1245 '.texinfo': TEXINFO,
1251 # TEXINFO: '.texinfo',
1256 class Compile_error:
1259 def write_file_map (lys, name):
1260 snippet_map = open ('snippet-map.ly', 'w')
1261 snippet_map.write ("\n#(ly:add-file-name-alist '(")
1263 snippet_map.write ('("%s" . "%s:%d (%s.ly)")\n' % (ly.basename(),
1268 snippet_map.write ('))\n')
1270 def do_process_cmd (chunks, input_name):
1271 all_lys = filter(lambda x: is_derived_class (x.__class__, Lilypond_snippet),
1274 write_file_map (all_lys, input_name)
1276 filter (lambda x: is_derived_class (x.__class__,
1278 and x.ly_is_outdated (),
1281 filter (lambda x: is_derived_class (x.__class__,
1283 and x.texstr_is_outdated (),
1286 filter (lambda x: is_derived_class (x.__class__,
1288 and x.png_is_outdated (),
1291 ly.progress (_ ("Writing snippets..."))
1292 map (Lilypond_snippet.write_ly, ly_outdated)
1296 ly.progress (_ ("Processing..."))
1298 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1300 ly.progress (_ ("All snippets are up to date..."))
1303 def guess_format (input_filename):
1305 e = os.path.splitext (input_filename)[1]
1306 if e in ext2format.keys ():
1308 format = ext2format[e]
1310 ly.error (_ ("cannot determine format for: %s" \
1315 def do_file (input_filename):
1317 if not input_filename or input_filename == '-':
1318 in_handle = sys.stdin
1319 input_fullname = '<stdin>'
1321 if os.path.exists (input_filename):
1322 input_fullname = input_filename
1323 elif format == LATEX:
1324 # urg python interface to libkpathsea?
1325 input_fullname = ly.read_pipe ('kpsewhich '
1326 + input_filename)[:-1]
1328 input_fullname = find_file (input_filename)
1329 in_handle = open (input_fullname)
1331 if input_filename == '-':
1332 input_base = 'stdin'
1334 input_base = os.path.basename \
1335 (os.path.splitext (input_filename)[0])
1337 # Only default to stdout when filtering.
1338 if output_name == '-' or (not output_name and filter_cmd):
1339 output_filename = '-'
1340 output_file = sys.stdout
1343 output_filename = input_base + format2ext[format]
1345 if not os.path.isdir (output_name):
1346 os.mkdir (output_name, 0777)
1347 output_filename = (output_name
1349 + format2ext[format])
1351 if os.path.exists (input_filename) \
1352 and os.path.exists (output_filename) \
1353 and os.path.samefile (output_filename, input_fullname):
1355 _ ("Output would overwrite input file; use --output."))
1358 output_file = open (output_filename, 'w')
1360 os.chdir (output_name)
1362 ly.progress (_ ("Reading %s...") % input_fullname)
1363 source = in_handle.read ()
1366 # FIXME: Containing blocks must be first, see
1367 # find_toplevel_snippets.
1369 'multiline_comment',
1373 'singleline_comment',
1378 ly.progress (_ ("Dissecting..."))
1379 chunks = find_toplevel_snippets (source, snippet_types)
1382 global default_ly_options
1384 if not default_ly_options.has_key (LINEWIDTH):
1386 textwidth = get_latex_textwidth (source)
1387 default_ly_options[LINEWIDTH] = \
1388 '''%.0f\\pt''' % textwidth
1389 elif format == TEXINFO:
1390 for (k, v) in texinfo_linewidths.items ():
1391 # FIXME: @layout is usually not in
1394 # \input texinfo @c -*-texinfo-*-
1396 # Bluntly search first K items of
1398 # s = chunks[0].replacement_text ()
1399 if re.search (k, source[:1024]):
1400 default_ly_options[LINEWIDTH] = v
1404 output_file.writelines ([c.filter_text () \
1408 do_process_cmd (chunks, input_fullname)
1409 ly.progress (_ ("Compiling %s...") % output_filename)
1410 output_file.writelines ([s.replacement_text () \
1414 def process_include (snippet):
1415 os.chdir (original_dir)
1416 name = snippet.substring ('filename')
1417 ly.progress (_ ("Processing include: %s") % name)
1421 map (process_include,
1422 filter (lambda x: is_derived_class (x.__class__,
1425 except Compile_error:
1426 os.chdir (original_dir)
1427 ly.progress (_ ("Removing `%s'") % output_filename)
1430 os.unlink (output_filename)
1434 global format, output_name
1435 global filter_cmd, process_cmd, verbose_p
1437 (sh, long) = ly.getopt_args (option_definitions)
1439 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1440 except getopt.error, s:
1441 sys.stderr.write ('\n')
1442 ly.error (_ ("getopt says: `%s'" % s))
1443 sys.stderr.write ('\n')
1453 elif o == '--filter' or o == '-F':
1456 elif o == '--format' or o == '-f':
1458 if a == 'texi-html' or a == 'texi':
1460 elif o == '--tex-backend ':
1462 elif o == '--help' or o == '-h':
1465 elif o == '--include' or o == '-I':
1466 include_path.append (os.path.join (original_dir,
1468 elif o == '--output' or o == '-o':
1470 elif o == '--outdir':
1472 elif o == '--process' or o == '-P':
1475 elif o == '--version' or o == '-v':
1476 ly.identify (sys.stdout)
1478 elif o == '--verbose' or o == '-V':
1480 elif o == '--warranty' or o == '-w':
1487 files = do_options ()
1489 ly.warning ("Need to have command line option")
1493 global process_cmd, format
1495 format = guess_format (files[0])
1498 if format == TEXINFO or format == HTML:
1500 if process_cmd == '':
1501 process_cmd = lilypond_binary + ' --formats=%s --backend eps ' % formats
1504 process_cmd += string.join ([(' -I %s' % p)
1505 for p in include_path])
1507 ly.identify (sys.stderr)
1508 ly.setup_environment ()
1512 except Compile_error:
1516 if __name__ == '__main__':