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
17 * this script is too complex. Modularize.
19 * ly-options: intertext?
21 * eps in latex / eps by lilypond -b ps?
22 * check latex parameters, twocolumn, multicolumn?
23 * use --png --ps --pdf for making images?
25 * Converting from lilypond-book source, substitute:
26 @mbinclude foo.itely -> @include foo.itely
36 # Users of python modules should include this snippet
37 # and customize variables below.
39 # We'll suffer this path initialization stuff as long as we don't install
40 # our python packages in <prefix>/lib/pythonX.Y (and don't kludge around
41 # it as we do with teTeX on Red Hat Linux: set some environment variables
42 # (PYTHONPATH) in `etc/profile').
44 # If set, LILYPONDPREFIX must take prevalence.
45 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
46 import getopt, os, sys
47 datadir = '@local_lilypond_datadir@'
48 if not os.path.isdir (datadir):
49 datadir = '@lilypond_datadir@'
50 if os.environ.has_key ('LILYPONDPREFIX'):
51 datadir = os.environ['LILYPONDPREFIX']
52 while datadir[-1] == os.sep:
55 sys.path.insert (0, os.path.join (datadir, 'python'))
58 #if __name__ == '__main__':
66 program_version = '@TOPLEVEL_VERSION@'
67 program_name = os.path.basename (sys.argv[0])
70 original_dir = os.getcwd ()
74 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
77 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
78 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
79 lilypond-book --process='lilypond -I include' BOOK
82 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
83 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
85 option_definitions = [
86 (_ ("FMT"), 'f', 'format',
87 _ ('''use output format FMT (texi [default], texi-html,
89 (_ ("FILTER"), 'F', 'filter',
90 _ ("pipe snippets through FILTER [convert-ly -n -]")),
92 _ ("print this help")),
93 (_ ("DIR"), 'I', 'include',
94 _ ("add DIR to include path")),
95 (_ ("DIR"), 'o', 'output',
96 _ ("write output to DIR")),
97 (_ ("COMMAND"), 'P', 'process',
98 _ ("process ly_files using COMMAND FILE...")),
99 (_(''), '', 'psfonts',
100 _ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
101 must use this with dvips -h INPUT.psfonts''')),
105 _ ("print version information")),
106 ('', 'w', 'warranty',
107 _ ("show warranty and copyright")),
110 include_path = [ly.abspath (os.getcwd ())]
111 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
113 # Only use installed binary when we are installed too.
114 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
115 lilypond_binary = 'lilypond'
121 latex_filter_cmd = 'latex "\\nonstopmode \input /dev/stdin"'
124 default_ly_options = { 'alt': "[image of music]" }
127 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
131 EXAMPLEINDENT = 'exampleindent'
133 FRAGMENT = 'fragment'
138 LINEWIDTH = 'linewidth'
139 NOFRAGMENT = 'nofragment'
140 NOINDENT = 'noindent'
145 OUTPUTIMAGE = 'outputimage'
148 PREAMBLE = 'preamble'
149 PRINTFILENAME = 'printfilename'
151 RAGGEDRIGHT = 'raggedright'
152 RELATIVE = 'relative'
153 STAFFSIZE = 'staffsize'
156 VERBATIM = 'verbatim'
157 FONTLOAD = 'fontload'
158 FILENAME = 'filename'
162 # NOTIME has no opposite so it isn't part of this dictionary.
163 # NOQUOTE is used internally only.
165 NOFRAGMENT: FRAGMENT,
170 # Recognize special sequences in the input.
172 # (?P<name>regex) -- Assign result of REGEX to NAME.
173 # *? -- Match non-greedily.
174 # (?m) -- Multiline regex: Make ^ and $ match at each line.
175 # (?s) -- Make the dot match all characters including newline.
176 # (?x) -- Ignore whitespace in patterns.
188 (\s*(?P<options>.*?)\s*:)?\s*
196 \s*(?P<options>.*?)\s*
205 \s*(?P<options>.*?)\s*
207 \s*(?P<filename>.*?)\s*
214 (?P<code><!--\s.*?!-->)
217 'singleline_comment':
223 (?P<code><pre>.*?</pre>))''',
229 (?P<code><pre>\s.*?</pre>\s))''',
248 \s*(?P<options>.*?)\s*
259 \s*(?P<options>.*?)\s*
263 \\end\s*{lilypond})''',
271 \s*(?P<options>.*?)\s*
279 'singleline_comment':
302 \\end\s*{verbatim}))''',
311 (?P<filename>\S+))''',
315 ^[^\n]*?(?!@c\s+)[^\n]*?
319 \s*(?P<options>.*?)\s*
329 \s*(?P<options>.*?)\s*
332 ^@end\s+lilypond)\s''',
339 \s*(?P<options>.*?)\s*
350 @end\s+ignore))\s''',
352 'singleline_comment':
357 @c([ \t][^\n]*|)\n))''',
359 # Don't do this: It interferes with @code{@{}.
360 # 'verb': r'''(?P<code>@code{.*?})''',
368 @end\s+example\s))''',
374 'intertext': r',?\s*intertext=\".*?\"',
379 'intertext': r',?\s*intertext=\".*?\"',
380 'option_sep': '\s*,\s*',
384 'intertext': r',?\s*intertext=\".*?\"',
385 'option_sep': '\s*,\s*',
389 # Options without a pattern in ly_options.
406 RELATIVE: r'''\relative c%(relative_quotes)s''',
411 INDENT: r'''indent = %(indent)s''',
413 LINEWIDTH: r'''linewidth = %(linewidth)s''',
415 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
417 RAGGEDRIGHT: r'''raggedright = ##t''',
419 PACKED: r'''packed = ##t''',
431 \remove Time_signature_engraver
437 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
444 FILTER: r'''<lilypond %(options)s>
454 <a href="%(base)s.ly">''',
457 <img align="center" valign="center"
458 border="0" src="%(image)s" alt="%(alt)s">''',
460 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
462 QUOTE: r'''<blockquote>
476 \ifx\preLilyPondExample \undefined
481 \def\lilypondbook{}%%
482 \input %(base)s-systems.tex
483 \ifx\postLilyPondExample \undefined
490 PRINTFILENAME: '''\\texttt{%(filename)s}
493 QUOTE: r'''\begin{quotation}
498 VERBATIM: r'''\noindent
500 %(verb)s\end{verbatim}
503 FILTER: r'''\begin{lilypond}[%(options)s]
510 FILTER: r'''@lilypond[%(options)s]
516 @include %(base)s-systems.texi
520 OUTPUTIMAGE: r'''@noindent
522 @image{%(base)s,,,%(alt)s,%(ext)s}
526 <a href="%(base)s.ly">
527 <img align="center" valign="center"
528 border="0" src="%(image)s" alt="%(alt)s">
534 PRINTFILENAME: '''@file{%(filename)s}
537 QUOTE: r'''@quotation
538 %(str)s@end quotation
545 VERBATIM: r'''@exampleindent 0
552 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
553 %%%% Options: [%(option_string)s]
555 #(set! toplevel-score-handler ly:parser-print-score)
556 #(set! toplevel-music-handler (lambda (p m)
557 (ly:parser-print-score
558 p (ly:music-scorify m p))))
560 #(ly:set-option (quote no-point-and-click))
562 #(define version-seen? #t)
566 %% ********************************
567 %% Start cut-&-pastable-section
568 %% ********************************
571 #(define dump-extents #t)
572 %(font_dump_setting)s
584 %% ly snippet contents follows:
596 texinfo_linewidths = {
597 '@afourpaper': '160\\mm',
598 '@afourwide': '6.5\\in',
599 '@afourlatex': '150\\mm',
600 '@smallbook': '5\\in',
601 '@letterpaper': '6\\in',
604 def classic_lilypond_book_compatibility (key, value):
605 if key == 'singleline' and value == None:
606 return (RAGGEDRIGHT, None)
608 m = re.search ('relative\s*([-0-9])', key)
610 return ('relative', m.group (1))
612 m = re.match ('([0-9]+)pt', key)
614 return ('staffsize', m.group (1))
616 if key == 'indent' or key == 'linewidth':
617 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
619 f = float (m.group (1))
620 return (key, '%f\\%s' % (f, m.group (2)))
624 def find_file (name):
625 for i in include_path:
626 full = os.path.join (i, name)
627 if os.path.exists (full):
629 ly.error (_ ("file not found: %s") % name + '\n')
633 def verbatim_html (s):
634 return re.sub ('>', '>',
636 re.sub ('&', '&', s)))
638 def verbatim_texinfo (s):
639 return re.sub ('{', '@{',
641 re.sub ('@', '@@', s)))
643 def split_options (option_string):
646 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
647 for i in range(len(options)):
648 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
651 return re.split (format_res[format]['option_sep'],
655 def invokes_lilypond ():
656 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
658 def set_default_options (source):
659 global default_ly_options
660 if not default_ly_options.has_key (LINEWIDTH):
662 textwidth = get_latex_textwidth (source)
663 default_ly_options[LINEWIDTH] = \
664 '''%.0f\\pt''' % textwidth
665 elif format == TEXINFO:
666 for (k, v) in texinfo_linewidths.items ():
667 # FIXME: @layout is usually not in
670 # \input texinfo @c -*-texinfo-*-
672 # Bluntly search first K items of
674 # s = chunks[0].replacement_text ()
675 if re.search (k, source[:1024]):
676 default_ly_options[LINEWIDTH] = v
680 def replacement_text (self):
683 def filter_text (self):
684 return self.replacement_text ()
686 def ly_is_outdated (self):
689 def png_is_outdated (self):
692 class Substring (Chunk):
693 def __init__ (self, source, start, end, line_number):
697 self.line_number = line_number
699 def replacement_text (self):
700 return self.source[self.start:self.end]
702 class Snippet (Chunk):
703 def __init__ (self, type, match, format, line_number):
707 self.option_dict = {}
709 self.line_number = line_number
711 def replacement_text (self):
712 return self.match.group ('match')
714 def substring (self, s):
715 return self.match.group (s)
718 return `self.__class__` + ' type = ' + self.type
720 class Include_snippet (Snippet):
721 def processed_filename (self):
722 f = self.substring ('filename')
723 return os.path.splitext (f)[0] + format2ext[format]
725 def replacement_text (self):
726 s = self.match.group ('match')
727 f = self.substring ('filename')
729 return re.sub (f, self.processed_filename (), s)
731 class Lilypond_snippet (Snippet):
732 def __init__ (self, type, match, format, line_number):
733 Snippet.__init__ (self, type, match, format, line_number)
734 os = match.group ('options')
735 self.do_options (os, self.type)
738 return self.substring ('code')
743 return self.compose_ly (s)
746 def do_options (self, option_string, type):
747 self.option_dict = {}
749 options = split_options (option_string)
752 if string.find (i, '=') > 0:
753 (key, value) = re.split ('\s*=\s*', i)
754 self.option_dict[key] = value
756 if i in no_options.keys ():
757 if no_options[i] in self.option_dict.keys ():
758 del self.option_dict[no_options[i]]
760 self.option_dict[i] = None
762 has_linewidth = self.option_dict.has_key (LINEWIDTH)
763 no_linewidth_value = 0
765 # If LINEWIDTH is used without parameter, set it to default.
766 if has_linewidth and self.option_dict[LINEWIDTH] == None:
767 no_linewidth_value = 1
768 del self.option_dict[LINEWIDTH]
770 for i in default_ly_options.keys ():
771 if i not in self.option_dict.keys ():
772 self.option_dict[i] = default_ly_options[i]
774 if not has_linewidth:
775 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
776 self.option_dict[RAGGEDRIGHT] = None
778 if type == 'lilypond':
779 if LINEWIDTH in self.option_dict.keys ():
780 del self.option_dict[LINEWIDTH]
782 if RAGGEDRIGHT in self.option_dict.keys ():
783 if LINEWIDTH in self.option_dict.keys ():
784 del self.option_dict[LINEWIDTH]
786 if QUOTE in self.option_dict.keys () or type == 'lilypond':
787 if LINEWIDTH in self.option_dict.keys ():
788 del self.option_dict[LINEWIDTH]
790 if not INDENT in self.option_dict.keys ():
791 self.option_dict[INDENT] = '0\\mm'
793 # The QUOTE pattern from ly_options only emits the `linewidth'
795 if has_linewidth and QUOTE in self.option_dict.keys ():
796 if no_linewidth_value:
797 del self.option_dict[LINEWIDTH]
799 del self.option_dict[QUOTE]
801 def compose_ly (self, code):
802 if FRAGMENT in self.option_dict.keys ():
810 # The original concept of the `exampleindent' option is broken.
811 # It is not possible to get a sane value for @exampleindent at all
812 # without processing the document itself. Saying
820 # causes ugly results with the DVI backend of texinfo since the
821 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
822 # value). Executing the above code changes the environment
823 # indentation to an unknown value because we don't know the amount
824 # of 1em in advance since it is font-dependent. Modifying
825 # @exampleindent in the middle of a document is simply not
826 # supported within texinfo.
828 # As a consequence, the only function of @exampleindent is now to
829 # specify the amount of indentation for the `quote' option.
831 # To set @exampleindent locally to zero, we use the @format
832 # environment for non-quoted snippets.
833 override[EXAMPLEINDENT] = r'0.4\in'
834 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
835 override.update (default_ly_options)
838 for (key, value) in self.option_dict.items ():
840 option_list.append (key)
842 option_list.append (key + '=' + value)
843 option_string = string.join (option_list, ',')
846 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
847 for a in compose_types:
850 for (key, value) in self.option_dict.items ():
852 classic_lilypond_book_compatibility (key, value)
856 (_ ("deprecated ly-option used: %s=%s" \
859 (_ ("compatibility mode translation: %s=%s" \
863 (_ ("deprecated ly-option used: %s" \
866 (_ ("compatibility mode translation: %s" \
869 (key, value) = (c_key, c_value)
872 override[key] = value
874 if not override.has_key (key):
878 for type in compose_types:
879 if ly_options[type].has_key (key):
880 compose_dict[type].append (ly_options[type][key])
884 if not found and key not in simple_options:
885 ly.warning (_ ("ignoring unknown ly option: %s") % key)
888 if RELATIVE in override.keys () and override[RELATIVE]:
889 relative = string.atoi (override[RELATIVE])
895 relative_quotes += ',' * (- relative)
897 relative_quotes += "'" * relative
899 program_name = __main__.program_name
901 paper_string = string.join (compose_dict[PAPER],
903 layout_string = string.join (compose_dict[LAYOUT],
905 notes_string = string.join (compose_dict[NOTES],
907 preamble_string = string.join (compose_dict[PREAMBLE],
910 font_dump_setting = ''
911 if FONTLOAD in self.option_dict:
912 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
914 return (PREAMBLE_LY + body) % vars ()
919 self.hash = abs (hash (self.full_ly ()))
923 if FILENAME in self.option_dict:
924 return self.option_dict[FILENAME]
926 return 'lily-%d' % self.get_hash ()
930 outf = open (self.basename () + '.ly', 'w')
931 outf.write (self.full_ly ())
933 open (self.basename () + '.txt', 'w').write ('image of music')
935 def ly_is_outdated (self):
936 base = self.basename ()
938 tex_file = '%s.tex' % base
939 eps_file = '%s.eps' % base
940 system_file = '%s-systems.tex' % base
941 ly_file = '%s.ly' % base
942 ok = os.path.exists (ly_file) \
943 and os.path.exists (system_file)\
944 and os.stat (system_file)[stat.ST_SIZE] \
945 and re.match ('% eof', open (system_file).readlines ()[-1])
946 if ok and (not use_hash_p or FILENAME in self.option_dict):
947 ok = (self.full_ly () == open (ly_file).read ())
949 # TODO: Do something smart with target formats
950 # (ps, png) and m/ctimes.
954 def png_is_outdated (self):
955 base = self.basename ()
956 ok = self.ly_is_outdated ()
957 if format == HTML or format == TEXINFO:
958 ok = ok and (os.path.exists (base + '.png')
959 or glob.glob (base + '-page*.png'))
961 def texstr_is_outdated (self):
965 base = self.basename ()
966 ok = self.ly_is_outdated ()
967 ok = ok and (os.path.exists (base + '.texstr'))
970 def filter_text (self):
971 code = self.substring ('code')
972 s = run_filter (code)
975 'options': self.match.group ('options')
978 return output[self.format][FILTER] % d
980 def replacement_text (self):
981 func = Lilypond_snippet.__dict__['output_' + self.format]
984 def get_images (self):
985 base = self.basename ()
987 single = '%(base)s.png' % vars ()
988 multiple = '%(base)s-page1.png' % vars ()
990 if os.path.exists (multiple) \
991 and (not os.path.exists (single) \
992 or (os.stat (multiple)[stat.ST_MTIME] \
993 > os.stat (single)[stat.ST_MTIME])):
994 images = glob.glob ('%(base)s-page*.png' % vars ())
997 def output_html (self):
999 base = self.basename ()
1001 str += self.output_print_filename (HTML)
1002 if VERBATIM in self.option_dict:
1003 verb = verbatim_html (self.substring ('code'))
1004 str += write (output[HTML][VERBATIM] % vars ())
1005 if QUOTE in self.option_dict:
1006 str = output[HTML][QUOTE] % vars ()
1008 str += output[HTML][BEFORE] % vars ()
1009 for image in self.get_images ():
1010 (base, ext) = os.path.splitext (image)
1011 alt = self.option_dict[ALT]
1012 str += output[HTML][OUTPUT] % vars ()
1013 str += output[HTML][AFTER] % vars ()
1016 def output_info (self):
1018 for image in self.get_images ():
1019 (base, ext) = os.path.splitext (image)
1021 # URG, makeinfo implicitly prepends dot to extension.
1022 # Specifying no extension is most robust.
1024 alt = self.option_dict[ALT]
1025 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1027 base = self.basename ()
1028 str += output[format][OUTPUT] % vars ()
1031 def output_latex (self):
1033 base = self.basename ()
1035 str += self.output_print_filename (LATEX)
1036 if VERBATIM in self.option_dict:
1037 verb = self.substring ('code')
1038 str += (output[LATEX][VERBATIM] % vars ())
1039 if QUOTE in self.option_dict:
1040 str = output[LATEX][QUOTE] % vars ()
1042 str += (output[LATEX][OUTPUT] % vars ())
1045 def output_print_filename (self, format):
1047 if PRINTFILENAME in self.option_dict:
1048 base = self.basename ()
1049 filename = self.substring ('filename')
1050 str = output[format][PRINTFILENAME] % vars ()
1054 def output_texinfo (self):
1056 if self.output_print_filename (TEXINFO):
1058 + self.output_print_filename (HTML)
1061 + self.output_print_filename (LATEX)
1063 base = self.basename ()
1064 if TEXIDOC in self.option_dict:
1065 texidoc = base + '.texidoc'
1066 if os.path.exists (texidoc):
1067 str += '@include %(texidoc)s\n\n' % vars ()
1069 if VERBATIM in self.option_dict:
1070 verb = verbatim_texinfo (self.substring ('code'))
1071 str += (output[TEXINFO][VERBATIM] % vars ())
1072 if not QUOTE in self.option_dict:
1073 str = output[TEXINFO][NOQUOTE] % vars ()
1075 str += self.output_info ()
1077 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1078 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1079 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1081 if QUOTE in self.option_dict:
1082 str = output[TEXINFO][QUOTE] % vars ()
1084 # need par after image
1089 class Lilypond_file_snippet (Lilypond_snippet):
1091 name = self.substring ('filename')
1092 return '\\renameinput \"%s\"\n%s' \
1093 % (name, open (find_file (name)).read ())
1095 snippet_type_to_class = {
1096 'lilypond_file': Lilypond_file_snippet,
1097 'lilypond_block': Lilypond_snippet,
1098 'lilypond': Lilypond_snippet,
1099 'include': Include_snippet,
1102 def find_linestarts (s):
1107 i = s.find ('\n', start)
1115 nls.append (len (s))
1118 def find_toplevel_snippets (s, types):
1121 res[i] = ly.re.compile (snippet_res[format][i])
1125 ## found = dict (map (lambda x: (x, None),
1129 map (lambda x, f = found: f.setdefault (x, None),
1132 line_starts = find_linestarts (s)
1134 # We want to search for multiple regexes, without searching
1135 # the string multiple times for one regex.
1136 # Hence, we use earlier results to limit the string portion
1138 # Since every part of the string is traversed at most once for
1139 # every type of snippet, this is linear.
1145 if not found[type] or found[type][0] < index:
1147 m = res[type].search (s[index:endex])
1152 if snippet_type_to_class.has_key (type):
1153 cl = snippet_type_to_class[type]
1156 start = index + m.start ('match')
1157 line_number = line_start_idx
1158 while (line_starts[line_number] < start):
1162 snip = cl (type, m, format, line_number)
1163 found[type] = (start, snip)
1167 or found[type][0] < found[first][0]):
1172 # Limiting the search space is a cute
1173 # idea, but this *requires* to search
1174 # for possible containing blocks
1175 # first, at least as long as we do not
1176 # search for the start of blocks, but
1177 # always/directly for the entire
1178 # @block ... @end block.
1180 endex = found[first][0]
1183 snippets.append (Substring (s, index, len (s), line_start_idx))
1186 while (start > line_starts[line_start_idx+1]):
1189 (start, snip) = found[first]
1190 snippets.append (Substring (s, index, start, line_start_idx + 1))
1191 snippets.append (snip)
1193 index = start + len (snip.match.group ('match'))
1197 def filter_pipe (input, cmd):
1199 ly.progress (_ ("Opening filter `%s'") % cmd)
1201 (stdin, stdout, stderr) = os.popen3 (cmd)
1203 status = stdin.close ()
1207 output = stdout.read ()
1208 status = stdout.close ()
1209 error = stderr.read ()
1213 signal = 0x0f & status
1214 if status or (not output and error):
1215 exit_status = status >> 8
1216 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1217 ly.error (_ ("The error log is as follows:"))
1218 sys.stderr.write (error)
1219 sys.stderr.write (stderr.read ())
1228 return filter_pipe (s, filter_cmd)
1230 def is_derived_class (cl, baseclass):
1233 for b in cl.__bases__:
1234 if is_derived_class (b, baseclass):
1238 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1239 ly_names = filter (lambda x: x,
1240 map (Lilypond_snippet.basename, ly_snippets))
1241 texstr_names = filter (lambda x: x,
1242 map (Lilypond_snippet.basename, texstr_snippets))
1243 png_names = filter (lambda x: x,
1244 map (Lilypond_snippet.basename, png_snippets))
1247 def my_system (cmd):
1248 status = ly.system (cmd,
1249 ignore_error = 1, progress_p = 1)
1252 ly.error ('Process %s exited unsuccessfully.' % cmd)
1256 # the --process=CMD switch is a bad idea
1257 # it is too generic for lilypond-book.
1258 if texstr_names and invokes_lilypond:
1259 my_system (string.join ([cmd, '--backend texstr',
1260 'snippet-map.ly'] + texstr_names))
1261 for l in texstr_names:
1262 my_system ('latex %s.texstr' % l)
1265 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1267 LATEX_DOCUMENT = r'''
1270 \typeout{textwidth=\the\textwidth}
1271 \typeout{columnsep=\the\columnsep}
1272 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1276 # Do we need anything else besides `textwidth'?
1277 def get_latex_textwidth (source):
1278 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1279 preamble = source[:m.start (0)]
1280 latex_document = LATEX_DOCUMENT % vars ()
1281 parameter_string = filter_pipe (latex_document, latex_filter_cmd)
1284 m = re.search ('columns=([0-9.]*)', parameter_string)
1286 columns = string.atoi (m.group (1))
1289 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1291 columnsep = string.atof (m.group (1))
1294 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1296 textwidth = string.atof (m.group (1))
1298 textwidth = (textwidth - columnsep) / columns
1310 '.texinfo': TEXINFO,
1316 # TEXINFO: '.texinfo',
1321 class Compile_error:
1324 def write_file_map (lys, name):
1325 snippet_map = open ('snippet-map.ly', 'w')
1326 snippet_map.write ("""
1327 #(define version-seen? #t)
1328 #(ly:add-file-name-alist '(
1331 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1337 snippet_map.write ('))\n')
1339 def do_process_cmd (chunks, input_name):
1340 all_lys = filter (lambda x: is_derived_class (x.__class__,
1344 write_file_map (all_lys, input_name)
1346 filter (lambda x: is_derived_class (x.__class__,
1348 and x.ly_is_outdated (),
1351 filter (lambda x: is_derived_class (x.__class__,
1353 and x.texstr_is_outdated (),
1356 filter (lambda x: is_derived_class (x.__class__,
1358 and x.png_is_outdated (),
1361 ly.progress (_ ("Writing snippets..."))
1362 map (Lilypond_snippet.write_ly, ly_outdated)
1366 ly.progress (_ ("Processing..."))
1368 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1370 ly.progress (_ ("All snippets are up to date..."))
1373 def guess_format (input_filename):
1375 e = os.path.splitext (input_filename)[1]
1376 if e in ext2format.keys ():
1378 format = ext2format[e]
1380 ly.error (_ ("can't determine format for: %s" \
1385 def write_if_updated (file_name, lines):
1387 f = open (file_name)
1389 new_str = string.join (lines, '')
1390 if oldstr == new_str:
1391 ly.progress (_ ("%s is up to date.") % file_name)
1397 ly.progress (_ ("Writing `%s'...") % file_name)
1398 open (file_name, 'w').writelines (lines)
1401 def do_file (input_filename):
1403 if not input_filename or input_filename == '-':
1404 in_handle = sys.stdin
1405 input_fullname = '<stdin>'
1407 if os.path.exists (input_filename):
1408 input_fullname = input_filename
1409 elif format == LATEX:
1410 # urg python interface to libkpathsea?
1411 input_fullname = ly.read_pipe ('kpsewhich '
1412 + input_filename)[:-1]
1414 input_fullname = find_file (input_filename)
1415 in_handle = open (input_fullname)
1417 if input_filename == '-':
1418 input_base = 'stdin'
1420 input_base = os.path.basename \
1421 (os.path.splitext (input_filename)[0])
1423 # Only default to stdout when filtering.
1424 if output_name == '-' or (not output_name and filter_cmd):
1425 output_filename = '-'
1426 output_file = sys.stdout
1429 if not os.path.isdir (output_name):
1430 os.mkdir (output_name, 0777)
1431 os.chdir (output_name)
1433 output_filename = input_base + format2ext[format]
1434 if os.path.exists (input_filename) \
1435 and os.path.exists (output_filename) \
1436 and os.path.samefile (output_filename, input_fullname):
1438 _ ("Output would overwrite input file; use --output."))
1442 ly.progress (_ ("Reading %s...") % input_fullname)
1443 source = in_handle.read ()
1446 set_default_options (source)
1449 # FIXME: Containing blocks must be first, see
1450 # find_toplevel_snippets.
1452 'multiline_comment',
1456 'singleline_comment',
1461 ly.progress (_ ("Dissecting..."))
1462 chunks = find_toplevel_snippets (source, snippet_types)
1466 write_if_updated (output_filename,
1467 [c.filter_text () for c in chunks])
1469 do_process_cmd (chunks, input_fullname)
1470 ly.progress (_ ("Compiling %s...") % output_filename)
1472 write_if_updated (output_filename,
1473 [s.replacement_text ()
1476 def process_include (snippet):
1477 os.chdir (original_dir)
1478 name = snippet.substring ('filename')
1479 ly.progress (_ ("Processing include: %s") % name)
1481 return do_file (name)
1483 include_chunks = map (process_include,
1484 filter (lambda x: is_derived_class (x.__class__,
1489 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1491 except Compile_error:
1492 os.chdir (original_dir)
1493 ly.progress (_ ("Removing `%s'") % output_filename)
1498 global format, output_name, psfonts_p
1499 global filter_cmd, process_cmd, verbose_p
1501 (sh, long) = ly.getopt_args (option_definitions)
1503 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1504 except getopt.error, s:
1505 sys.stderr.write ('\n')
1506 ly.error (_ ("getopt says: `%s'" % s))
1507 sys.stderr.write ('\n')
1517 elif o == '--filter' or o == '-F':
1520 elif o == '--format' or o == '-f':
1522 if a == 'texi-html' or a == 'texi':
1524 elif o == '--tex-backend ':
1526 elif o == '--help' or o == '-h':
1529 elif o == '--include' or o == '-I':
1530 include_path.append (os.path.join (original_dir,
1532 elif o == '--output' or o == '-o':
1534 elif o == '--process' or o == '-P':
1537 elif o == '--version' or o == '-v':
1538 ly.identify (sys.stdout)
1540 elif o == '--verbose' or o == '-V':
1542 elif o == '--psfonts':
1544 elif o == '--warranty' or o == '-w':
1551 files = do_options ()
1552 if not files or len (files) > 1:
1558 basename = os.path.splitext (file)[0]
1559 basename = os.path.split (basename)[1]
1561 global process_cmd, format
1563 format = guess_format (files[0])
1566 if format == TEXINFO or format == HTML:
1568 if process_cmd == '':
1569 process_cmd = lilypond_binary \
1570 + ' --formats=%s --backend eps ' % formats
1573 process_cmd += string.join ([(' -I %s' % p)
1574 for p in include_path])
1576 ly.identify (sys.stderr)
1577 ly.setup_environment ()
1580 chunks = do_file (file)
1581 if psfonts_p and invokes_lilypond ():
1582 fontextract.verbose = verbose_p
1583 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1587 psfonts_file = basename + '.psfonts'
1589 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1590 fontextract.extract_fonts (psfonts_file,
1591 [x.basename() + '.eps'
1592 for x in snippet_chunks])
1596 except Compile_error:
1599 if format == TEXINFO or format == LATEX:
1601 ly.warning (_ ("option --psfonts not used"))
1602 ly.warning (_ ("processing with dvips will have no fonts"))
1604 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1605 output = os.path.join (output_name, basename + '.dvi' )
1608 ly.progress (_ ("DVIPS usage:"))
1610 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1613 if __name__ == '__main__':