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
38 # Users of python modules should include this snippet
39 # and customize variables below.
41 # We'll suffer this path initialization stuff as long as we don't install
42 # our python packages in <prefix>/lib/pythonX.Y
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 datadir = os.path.join (datadir, "share/lilypond/current/")
57 sys.path.insert (0, os.path.join (datadir, 'python'))
60 #if __name__ == '__main__':
68 program_version = '@TOPLEVEL_VERSION@'
69 program_name = os.path.basename (sys.argv[0])
72 original_dir = os.getcwd ()
76 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
79 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
80 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
81 lilypond-book --process='lilypond -I include' BOOK
84 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
85 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
87 option_definitions = [
88 (_ ("FMT"), 'f', 'format',
89 _ ('''use output format FMT (texi [default], texi-html,
91 (_ ("FILTER"), 'F', 'filter',
92 _ ("pipe snippets through FILTER [convert-ly -n -]")),
94 _ ("print this help")),
95 (_ ("DIR"), 'I', 'include',
96 _ ("add DIR to include path")),
97 (_ ("DIR"), 'o', 'output',
98 _ ("write output to DIR")),
99 (_ ("COMMAND"), 'P', 'process',
100 _ ("process ly_files using COMMAND FILE...")),
102 _ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
103 must use this with dvips -h INPUT.psfonts''')),
107 _ ("print version information")),
108 ('', 'w', 'warranty',
109 _ ("show warranty and copyright")),
112 include_path = [os.path.abspath (os.getcwd ())]
113 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
115 # Only use installed binary when we are installed too.
116 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
117 lilypond_binary = 'lilypond'
125 default_ly_options = { 'alt': "[image of music]" }
128 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
132 EXAMPLEINDENT = 'exampleindent'
134 FRAGMENT = 'fragment'
139 LINEWIDTH = 'linewidth'
140 NOFRAGMENT = 'nofragment'
141 NOINDENT = 'noindent'
146 OUTPUTIMAGE = 'outputimage'
149 PREAMBLE = 'preamble'
150 PRINTFILENAME = 'printfilename'
152 RAGGEDRIGHT = 'raggedright'
153 RELATIVE = 'relative'
154 STAFFSIZE = 'staffsize'
157 VERBATIM = 'verbatim'
158 FONTLOAD = 'fontload'
159 FILENAME = 'filename'
163 # NOTIME has no opposite so it isn't part of this dictionary.
164 # NOQUOTE is used internally only.
166 NOFRAGMENT: FRAGMENT,
171 # Recognize special sequences in the input.
173 # (?P<name>regex) -- Assign result of REGEX to NAME.
174 # *? -- Match non-greedily.
175 # (?m) -- Multiline regex: Make ^ and $ match at each line.
176 # (?s) -- Make the dot match all characters including newline.
177 # (?x) -- Ignore whitespace in patterns.
189 (\s*(?P<options>.*?)\s*:)?\s*
197 \s*(?P<options>.*?)\s*
206 \s*(?P<options>.*?)\s*
208 \s*(?P<filename>.*?)\s*
215 (?P<code><!--\s.*?!-->)
218 'singleline_comment':
224 (?P<code><pre>.*?</pre>))''',
230 (?P<code><pre>\s.*?</pre>\s))''',
249 \s*(?P<options>.*?)\s*
260 \s*(?P<options>.*?)\s*
264 \\end\s*{lilypond})''',
272 \s*(?P<options>.*?)\s*
280 'singleline_comment':
303 \\end\s*{verbatim}))''',
312 (?P<filename>\S+))''',
316 ^[^\n]*?(?!@c\s+)[^\n]*?
320 \s*(?P<options>.*?)\s*
330 \s*(?P<options>.*?)\s*
333 ^@end\s+lilypond)\s''',
340 \s*(?P<options>.*?)\s*
351 @end\s+ignore))\s''',
353 'singleline_comment':
358 @c([ \t][^\n]*|)\n))''',
360 # Don't do this: It interferes with @code{@{}.
361 # 'verb': r'''(?P<code>@code{.*?})''',
369 @end\s+example\s))''',
375 'intertext': r',?\s*intertext=\".*?\"',
380 'intertext': r',?\s*intertext=\".*?\"',
381 'option_sep': '\s*,\s*',
385 'intertext': r',?\s*intertext=\".*?\"',
386 'option_sep': '\s*,\s*',
390 # Options without a pattern in ly_options.
407 RELATIVE: r'''\relative c%(relative_quotes)s''',
412 INDENT: r'''indent = %(indent)s''',
414 LINEWIDTH: r'''linewidth = %(linewidth)s''',
416 QUOTE: r'''linewidth = %(linewidth)s - 2.0 * %(exampleindent)s''',
418 RAGGEDRIGHT: r'''raggedright = ##t''',
420 PACKED: r'''packed = ##t''',
432 \remove Time_signature_engraver
438 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
445 FILTER: r'''<lilypond %(options)s>
455 <a href="%(base)s.ly">''',
458 <img align="center" valign="center"
459 border="0" src="%(image)s" alt="%(alt)s">''',
461 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
463 QUOTE: r'''<blockquote>
477 \ifx\preLilyPondExample \undefined
482 \def\lilypondbook{}%%
483 \input %(base)s-systems.tex
484 \ifx\postLilyPondExample \undefined
491 PRINTFILENAME: '''\\texttt{%(filename)s}
494 QUOTE: r'''\begin{quotation}
499 VERBATIM: r'''\noindent
501 %(verb)s\end{verbatim}
504 FILTER: r'''\begin{lilypond}[%(options)s]
511 FILTER: r'''@lilypond[%(options)s]
517 @include %(base)s-systems.texi
521 OUTPUTIMAGE: r'''@noindent
523 @image{%(base)s,,,%(alt)s,%(ext)s}
527 <a href="%(base)s.ly">
528 <img align="center" valign="center"
529 border="0" src="%(image)s" alt="%(alt)s">
535 PRINTFILENAME: '''@file{%(filename)s}
538 QUOTE: r'''@quotation
539 %(str)s@end quotation
546 VERBATIM: r'''@exampleindent 0
553 PREAMBLE_LY = r'''%%%% Generated by %(program_name)s
554 %%%% Options: [%(option_string)s]
556 #(set! toplevel-score-handler print-score-with-defaults)
557 #(set! toplevel-music-handler (lambda (p m)
558 (print-score-with-defaults
559 p (scorify-music m p))))
561 #(ly:set-option (quote no-point-and-click))
562 #(define inside-lilypond-book #t)
563 #(define version-seen? #t)
571 %% ****************************************************************
572 %% Start cut-&-pastable-section
573 %% ****************************************************************
576 #(define dump-extents #t)
577 %(font_dump_setting)s
591 %% ****************************************************************
592 %% ly snippet contents follows:
593 %% ****************************************************************
597 %% ****************************************************************
599 %% ****************************************************************
606 %% ****************************************************************
608 %% ****************************************************************
612 %% ****************************************************************
614 %% ****************************************************************
617 texinfo_linewidths = {
618 '@afourpaper': '160\\mm',
619 '@afourwide': '6.5\\in',
620 '@afourlatex': '150\\mm',
621 '@smallbook': '5\\in',
622 '@letterpaper': '6\\in',
625 def classic_lilypond_book_compatibility (key, value):
626 if key == 'singleline' and value == None:
627 return (RAGGEDRIGHT, None)
629 m = re.search ('relative\s*([-0-9])', key)
631 return ('relative', m.group (1))
633 m = re.match ('([0-9]+)pt', key)
635 return ('staffsize', m.group (1))
637 if key == 'indent' or key == 'linewidth':
638 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
640 f = float (m.group (1))
641 return (key, '%f\\%s' % (f, m.group (2)))
645 def find_file (name):
646 for i in include_path:
647 full = os.path.join (i, name)
648 if os.path.exists (full):
650 ly.error (_ ("file not found: %s") % name + '\n')
654 def verbatim_html (s):
655 return re.sub ('>', '>',
657 re.sub ('&', '&', s)))
659 def verbatim_texinfo (s):
660 return re.sub ('{', '@{',
662 re.sub ('@', '@@', s)))
664 def split_options (option_string):
667 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
668 for i in range(len(options)):
669 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
672 return re.split (format_res[format]['option_sep'],
676 def invokes_lilypond ():
677 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
679 def set_default_options (source):
680 global default_ly_options
681 if not default_ly_options.has_key (LINEWIDTH):
683 textwidth = get_latex_textwidth (source)
684 default_ly_options[LINEWIDTH] = \
685 '''%.0f\\pt''' % textwidth
686 elif format == TEXINFO:
687 for (k, v) in texinfo_linewidths.items ():
688 # FIXME: @layout is usually not in
691 # \input texinfo @c -*-texinfo-*-
693 # Bluntly search first K items of
695 # s = chunks[0].replacement_text ()
696 if re.search (k, source[:1024]):
697 default_ly_options[LINEWIDTH] = v
701 def replacement_text (self):
704 def filter_text (self):
705 return self.replacement_text ()
707 def ly_is_outdated (self):
710 def png_is_outdated (self):
716 class Substring (Chunk):
717 def __init__ (self, source, start, end, line_number):
721 self.line_number = line_number
722 self.override_text = None
727 def replacement_text (self):
728 if self.override_text:
729 return self.override_text
731 return self.source[self.start:self.end]
733 class Snippet (Chunk):
734 def __init__ (self, type, match, format, line_number):
738 self.option_dict = {}
740 self.line_number = line_number
742 def replacement_text (self):
743 return self.match.group ('match')
745 def substring (self, s):
746 return self.match.group (s)
749 return `self.__class__` + ' type = ' + self.type
751 class Include_snippet (Snippet):
752 def processed_filename (self):
753 f = self.substring ('filename')
754 return os.path.splitext (f)[0] + format2ext[format]
756 def replacement_text (self):
757 s = self.match.group ('match')
758 f = self.substring ('filename')
760 return re.sub (f, self.processed_filename (), s)
762 class Lilypond_snippet (Snippet):
763 def __init__ (self, type, match, format, line_number):
764 Snippet.__init__ (self, type, match, format, line_number)
765 os = match.group ('options')
766 self.do_options (os, self.type)
769 return self.substring ('code')
774 return self.compose_ly (s)
777 def do_options (self, option_string, type):
778 self.option_dict = {}
780 options = split_options (option_string)
783 if string.find (i, '=') > 0:
784 (key, value) = re.split ('\s*=\s*', i)
785 self.option_dict[key] = value
787 if i in no_options.keys ():
788 if no_options[i] in self.option_dict.keys ():
789 del self.option_dict[no_options[i]]
791 self.option_dict[i] = None
793 has_linewidth = self.option_dict.has_key (LINEWIDTH)
794 no_linewidth_value = 0
796 # If LINEWIDTH is used without parameter, set it to default.
797 if has_linewidth and self.option_dict[LINEWIDTH] == None:
798 no_linewidth_value = 1
799 del self.option_dict[LINEWIDTH]
801 for i in default_ly_options.keys ():
802 if i not in self.option_dict.keys ():
803 self.option_dict[i] = default_ly_options[i]
805 if not has_linewidth:
806 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
807 self.option_dict[RAGGEDRIGHT] = None
809 if type == 'lilypond':
810 if LINEWIDTH in self.option_dict.keys ():
811 del self.option_dict[LINEWIDTH]
813 if RAGGEDRIGHT in self.option_dict.keys ():
814 if LINEWIDTH in self.option_dict.keys ():
815 del self.option_dict[LINEWIDTH]
817 if QUOTE in self.option_dict.keys () or type == 'lilypond':
818 if LINEWIDTH in self.option_dict.keys ():
819 del self.option_dict[LINEWIDTH]
821 if not INDENT in self.option_dict.keys ():
822 self.option_dict[INDENT] = '0\\mm'
824 # The QUOTE pattern from ly_options only emits the `linewidth'
826 if has_linewidth and QUOTE in self.option_dict.keys ():
827 if no_linewidth_value:
828 del self.option_dict[LINEWIDTH]
830 del self.option_dict[QUOTE]
832 def compose_ly (self, code):
833 if FRAGMENT in self.option_dict.keys ():
841 # The original concept of the `exampleindent' option is broken.
842 # It is not possible to get a sane value for @exampleindent at all
843 # without processing the document itself. Saying
851 # causes ugly results with the DVI backend of texinfo since the
852 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
853 # value). Executing the above code changes the environment
854 # indentation to an unknown value because we don't know the amount
855 # of 1em in advance since it is font-dependent. Modifying
856 # @exampleindent in the middle of a document is simply not
857 # supported within texinfo.
859 # As a consequence, the only function of @exampleindent is now to
860 # specify the amount of indentation for the `quote' option.
862 # To set @exampleindent locally to zero, we use the @format
863 # environment for non-quoted snippets.
864 override[EXAMPLEINDENT] = r'0.4\in'
865 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
866 override.update (default_ly_options)
869 for (key, value) in self.option_dict.items ():
871 option_list.append (key)
873 option_list.append (key + '=' + value)
874 option_string = string.join (option_list, ',')
877 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
878 for a in compose_types:
881 for (key, value) in self.option_dict.items ():
883 classic_lilypond_book_compatibility (key, value)
887 (_ ("deprecated ly-option used: %s=%s" \
890 (_ ("compatibility mode translation: %s=%s" \
894 (_ ("deprecated ly-option used: %s" \
897 (_ ("compatibility mode translation: %s" \
900 (key, value) = (c_key, c_value)
903 override[key] = value
905 if not override.has_key (key):
909 for type in compose_types:
910 if ly_options[type].has_key (key):
911 compose_dict[type].append (ly_options[type][key])
915 if not found and key not in simple_options:
916 ly.warning (_ ("ignoring unknown ly option: %s") % key)
919 if RELATIVE in override.keys () and override[RELATIVE]:
920 relative = string.atoi (override[RELATIVE])
926 relative_quotes += ',' * (- relative)
928 relative_quotes += "'" * relative
930 program_name = __main__.program_name
932 paper_string = string.join (compose_dict[PAPER],
934 layout_string = string.join (compose_dict[LAYOUT],
936 notes_string = string.join (compose_dict[NOTES],
938 preamble_string = string.join (compose_dict[PREAMBLE],
941 font_dump_setting = ''
942 if FONTLOAD in self.option_dict:
943 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
945 return (PREAMBLE_LY + body) % vars ()
950 self.hash = abs (hash (self.full_ly ()))
954 if FILENAME in self.option_dict:
955 return self.option_dict[FILENAME]
957 return 'lily-%d' % self.get_hash ()
961 outf = open (self.basename () + '.ly', 'w')
962 outf.write (self.full_ly ())
964 open (self.basename () + '.txt', 'w').write ('image of music')
966 def ly_is_outdated (self):
967 base = self.basename ()
969 tex_file = '%s.tex' % base
970 eps_file = '%s.eps' % base
971 system_file = '%s-systems.tex' % base
972 ly_file = '%s.ly' % base
973 ok = os.path.exists (ly_file) \
974 and os.path.exists (system_file)\
975 and os.stat (system_file)[stat.ST_SIZE] \
976 and re.match ('% eof', open (system_file).readlines ()[-1])
977 if ok and (not use_hash_p or FILENAME in self.option_dict):
978 ok = (self.full_ly () == open (ly_file).read ())
980 # TODO: Do something smart with target formats
981 # (ps, png) and m/ctimes.
985 def png_is_outdated (self):
986 base = self.basename ()
987 ok = self.ly_is_outdated ()
988 if format == HTML or format == TEXINFO:
989 ok = ok and os.path.exists (base + '.eps')
993 page_count = ly.ps_page_count (base + '.eps')
996 ok = ok and os.path.exists (base + '.png')
998 for a in range (1, page_count + 1):
999 ok = ok and os.path.exists (base + '-page%d.png' % a)
1003 def texstr_is_outdated (self):
1007 base = self.basename ()
1008 ok = self.ly_is_outdated ()
1009 ok = ok and (os.path.exists (base + '.texstr'))
1012 def filter_text (self):
1013 code = self.substring ('code')
1014 s = run_filter (code)
1017 'options': self.match.group ('options')
1020 return output[self.format][FILTER] % d
1022 def replacement_text (self):
1023 func = Lilypond_snippet.__dict__['output_' + self.format]
1026 def get_images (self):
1027 base = self.basename ()
1029 single = '%(base)s.png' % vars ()
1030 multiple = '%(base)s-page1.png' % vars ()
1032 if os.path.exists (multiple) \
1033 and (not os.path.exists (single) \
1034 or (os.stat (multiple)[stat.ST_MTIME] \
1035 > os.stat (single)[stat.ST_MTIME])):
1036 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1037 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1038 images = tuple (images)
1041 def output_html (self):
1043 base = self.basename ()
1045 str += self.output_print_filename (HTML)
1046 if VERBATIM in self.option_dict:
1047 verb = verbatim_html (self.substring ('code'))
1048 str += write (output[HTML][VERBATIM] % vars ())
1049 if QUOTE in self.option_dict:
1050 str = output[HTML][QUOTE] % vars ()
1052 str += output[HTML][BEFORE] % vars ()
1053 for image in self.get_images ():
1054 (base, ext) = os.path.splitext (image)
1055 alt = self.option_dict[ALT]
1056 str += output[HTML][OUTPUT] % vars ()
1057 str += output[HTML][AFTER] % vars ()
1060 def output_info (self):
1062 for image in self.get_images ():
1063 (base, ext) = os.path.splitext (image)
1065 # URG, makeinfo implicitly prepends dot to extension.
1066 # Specifying no extension is most robust.
1068 alt = self.option_dict[ALT]
1069 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1071 base = self.basename ()
1072 str += output[format][OUTPUT] % vars ()
1075 def output_latex (self):
1077 base = self.basename ()
1079 str += self.output_print_filename (LATEX)
1080 if VERBATIM in self.option_dict:
1081 verb = self.substring ('code')
1082 str += (output[LATEX][VERBATIM] % vars ())
1084 str += (output[LATEX][OUTPUT] % vars ())
1085 if QUOTE in self.option_dict:
1086 str = output[LATEX][QUOTE] % vars ()
1089 def output_print_filename (self, format):
1091 if PRINTFILENAME in self.option_dict:
1092 base = self.basename ()
1093 filename = self.substring ('filename')
1094 str = output[format][PRINTFILENAME] % vars ()
1098 def output_texinfo (self):
1100 if self.output_print_filename (TEXINFO):
1102 + self.output_print_filename (HTML)
1105 + self.output_print_filename (LATEX)
1107 base = self.basename ()
1108 if TEXIDOC in self.option_dict:
1109 texidoc = base + '.texidoc'
1110 if os.path.exists (texidoc):
1111 str += '@include %(texidoc)s\n\n' % vars ()
1113 if VERBATIM in self.option_dict:
1114 verb = verbatim_texinfo (self.substring ('code'))
1115 str += (output[TEXINFO][VERBATIM] % vars ())
1116 if not QUOTE in self.option_dict:
1117 str = output[TEXINFO][NOQUOTE] % vars ()
1119 str += self.output_info ()
1121 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1122 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1123 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1125 if QUOTE in self.option_dict:
1126 str = output[TEXINFO][QUOTE] % vars ()
1128 # need par after image
1133 class Lilypond_file_snippet (Lilypond_snippet):
1135 name = self.substring ('filename')
1136 return '\\renameinput \"%s\"\n%s' \
1137 % (name, open (find_file (name)).read ())
1139 snippet_type_to_class = {
1140 'lilypond_file': Lilypond_file_snippet,
1141 'lilypond_block': Lilypond_snippet,
1142 'lilypond': Lilypond_snippet,
1143 'include': Include_snippet,
1146 def find_linestarts (s):
1151 i = s.find ('\n', start)
1159 nls.append (len (s))
1162 def find_toplevel_snippets (s, types):
1165 res[i] = ly.re.compile (snippet_res[format][i])
1169 ## found = dict (map (lambda x: (x, None),
1173 map (lambda x, f = found: f.setdefault (x, None),
1176 line_starts = find_linestarts (s)
1178 # We want to search for multiple regexes, without searching
1179 # the string multiple times for one regex.
1180 # Hence, we use earlier results to limit the string portion
1182 # Since every part of the string is traversed at most once for
1183 # every type of snippet, this is linear.
1189 if not found[type] or found[type][0] < index:
1191 m = res[type].search (s[index:endex])
1196 if snippet_type_to_class.has_key (type):
1197 cl = snippet_type_to_class[type]
1200 start = index + m.start ('match')
1201 line_number = line_start_idx
1202 while (line_starts[line_number] < start):
1206 snip = cl (type, m, format, line_number)
1207 found[type] = (start, snip)
1211 or found[type][0] < found[first][0]):
1216 # Limiting the search space is a cute
1217 # idea, but this *requires* to search
1218 # for possible containing blocks
1219 # first, at least as long as we do not
1220 # search for the start of blocks, but
1221 # always/directly for the entire
1222 # @block ... @end block.
1224 endex = found[first][0]
1227 snippets.append (Substring (s, index, len (s), line_start_idx))
1230 while (start > line_starts[line_start_idx+1]):
1233 (start, snip) = found[first]
1234 snippets.append (Substring (s, index, start, line_start_idx + 1))
1235 snippets.append (snip)
1237 index = start + len (snip.match.group ('match'))
1241 def filter_pipe (input, cmd):
1243 ly.progress (_ ("Opening filter `%s'") % cmd)
1245 (stdin, stdout, stderr) = os.popen3 (cmd)
1247 status = stdin.close ()
1251 output = stdout.read ()
1252 status = stdout.close ()
1253 error = stderr.read ()
1257 signal = 0x0f & status
1258 if status or (not output and error):
1259 exit_status = status >> 8
1260 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1261 ly.error (_ ("The error log is as follows:"))
1262 sys.stderr.write (error)
1263 sys.stderr.write (stderr.read ())
1272 return filter_pipe (s, filter_cmd)
1274 def is_derived_class (cl, baseclass):
1277 for b in cl.__bases__:
1278 if is_derived_class (b, baseclass):
1282 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1283 ly_names = filter (lambda x: x,
1284 map (Lilypond_snippet.basename, ly_snippets))
1285 texstr_names = filter (lambda x: x,
1286 map (Lilypond_snippet.basename, texstr_snippets))
1287 png_names = filter (lambda x: x,
1288 map (Lilypond_snippet.basename, png_snippets))
1291 def my_system (cmd):
1292 status = ly.system (cmd,
1293 ignore_error = 1, progress_p = 1)
1296 ly.error ('Process %s exited unsuccessfully.' % cmd)
1300 # the --process=CMD switch is a bad idea
1301 # it is too generic for lilypond-book.
1302 if texstr_names and invokes_lilypond:
1303 my_system (string.join ([cmd, '--backend texstr',
1304 'snippet-map.ly'] + texstr_names))
1305 for l in texstr_names:
1306 my_system ('latex %s.texstr' % l)
1309 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1311 LATEX_INSPECTION_DOCUMENT = r'''
1315 \typeout{textwidth=\the\textwidth}
1316 \typeout{columnsep=\the\columnsep}
1317 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1321 # Do we need anything else besides `textwidth'?
1322 def get_latex_textwidth (source):
1323 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1324 preamble = source[:m.start (0)]
1325 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1326 # Workaround problems with unusable $TMP on Cygwin:
1327 tempfile.tempdir = ''
1328 tmpfile = tempfile.mktemp('.tex')
1329 logfile = os.path.splitext (tmpfile)[0] + '.log'
1330 open (tmpfile,'w').write (latex_document)
1331 ly.system ('latex %s' % tmpfile)
1332 parameter_string = open (logfile).read()
1337 m = re.search ('columns=([0-9.]*)', parameter_string)
1339 columns = string.atoi (m.group (1))
1342 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1344 columnsep = string.atof (m.group (1))
1347 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1349 textwidth = string.atof (m.group (1))
1351 textwidth = (textwidth - columnsep) / columns
1355 def modify_preamble (chunk):
1356 str = chunk.replacement_text ()
1357 if (re.search (r"\\begin{document}", str)
1358 and not re.search ("{graphic[sx]", str)):
1359 str = re.sub (r"\\begin{document}",
1360 r"\\RequirePackage{graphics}" + '\n'
1361 + r"\\begin{document}",
1363 chunk.override_text = str
1375 '.texinfo': TEXINFO,
1381 # TEXINFO: '.texinfo',
1386 class Compile_error:
1389 def write_file_map (lys, name):
1390 snippet_map = open ('snippet-map.ly', 'w')
1391 snippet_map.write ("""
1392 #(define version-seen? #t)
1393 #(ly:add-file-name-alist '(
1396 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1402 snippet_map.write ('))\n')
1404 def do_process_cmd (chunks, input_name):
1405 all_lys = filter (lambda x: is_derived_class (x.__class__,
1409 write_file_map (all_lys, input_name)
1411 filter (lambda x: is_derived_class (x.__class__,
1413 and x.ly_is_outdated (),
1416 filter (lambda x: is_derived_class (x.__class__,
1418 and x.texstr_is_outdated (),
1421 filter (lambda x: is_derived_class (x.__class__,
1423 and x.png_is_outdated (),
1426 ly.progress (_ ("Writing snippets..."))
1427 map (Lilypond_snippet.write_ly, ly_outdated)
1431 ly.progress (_ ("Processing..."))
1433 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1435 ly.progress (_ ("All snippets are up to date..."))
1438 def guess_format (input_filename):
1440 e = os.path.splitext (input_filename)[1]
1441 if e in ext2format.keys ():
1443 format = ext2format[e]
1445 ly.error (_ ("can't determine format for: %s" \
1450 def write_if_updated (file_name, lines):
1452 f = open (file_name)
1454 new_str = string.join (lines, '')
1455 if oldstr == new_str:
1456 ly.progress (_ ("%s is up to date.") % file_name)
1462 ly.progress (_ ("Writing `%s'...") % file_name)
1463 open (file_name, 'w').writelines (lines)
1466 def do_file (input_filename):
1468 if not input_filename or input_filename == '-':
1469 in_handle = sys.stdin
1470 input_fullname = '<stdin>'
1472 if os.path.exists (input_filename):
1473 input_fullname = input_filename
1474 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1475 # urg python interface to libkpathsea?
1476 input_fullname = ly.read_pipe ('kpsewhich '
1477 + input_filename)[:-1]
1479 input_fullname = find_file (input_filename)
1480 in_handle = open (input_fullname)
1482 if input_filename == '-':
1483 input_base = 'stdin'
1485 input_base = os.path.basename \
1486 (os.path.splitext (input_filename)[0])
1488 # Only default to stdout when filtering.
1489 if output_name == '-' or (not output_name and filter_cmd):
1490 output_filename = '-'
1491 output_file = sys.stdout
1493 # don't complain when output_name is existing
1494 output_filename = input_base + format2ext[format]
1496 if not os.path.isdir (output_name):
1497 os.mkdir (output_name, 0777)
1498 os.chdir (output_name)
1500 if os.path.exists (input_filename) \
1501 and os.path.exists (output_filename) \
1502 and os.path.samefile (output_filename, input_fullname):
1504 _ ("Output would overwrite input file; use --output."))
1508 ly.progress (_ ("Reading %s...") % input_fullname)
1509 source = in_handle.read ()
1512 set_default_options (source)
1515 # FIXME: Containing blocks must be first, see
1516 # find_toplevel_snippets.
1518 'multiline_comment',
1522 'singleline_comment',
1527 ly.progress (_ ("Dissecting..."))
1528 chunks = find_toplevel_snippets (source, snippet_types)
1532 if (c.is_plain () and
1533 re.search (r"\\begin{document}", c.replacement_text())):
1534 modify_preamble (chunks[0])
1539 write_if_updated (output_filename,
1540 [c.filter_text () for c in chunks])
1542 do_process_cmd (chunks, input_fullname)
1543 ly.progress (_ ("Compiling %s...") % output_filename)
1545 write_if_updated (output_filename,
1546 [s.replacement_text ()
1549 def process_include (snippet):
1550 os.chdir (original_dir)
1551 name = snippet.substring ('filename')
1552 ly.progress (_ ("Processing include: %s") % name)
1554 return do_file (name)
1556 include_chunks = map (process_include,
1557 filter (lambda x: is_derived_class (x.__class__,
1562 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1564 except Compile_error:
1565 os.chdir (original_dir)
1566 ly.progress (_ ("Removing `%s'") % output_filename)
1571 global format, output_name, psfonts_p
1572 global filter_cmd, process_cmd, verbose_p
1574 (sh, long) = ly.getopt_args (option_definitions)
1576 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1577 except getopt.error, s:
1578 sys.stderr.write ('\n')
1579 ly.error (_ ("getopt says: `%s'" % s))
1580 sys.stderr.write ('\n')
1590 elif o == '--filter' or o == '-F':
1593 elif o == '--format' or o == '-f':
1595 if a == 'texi-html' or a == 'texi':
1597 elif o == '--tex-backend ':
1599 elif o == '--help' or o == '-h':
1602 elif o == '--include' or o == '-I':
1603 include_path.append (os.path.join (original_dir,
1604 os.path.abspath (a)))
1605 elif o == '--output' or o == '-o':
1607 elif o == '--process' or o == '-P':
1610 elif o == '--version' or o == '-v':
1611 ly.identify (sys.stdout)
1613 elif o == '--verbose' or o == '-V':
1615 elif o == '--psfonts':
1617 elif o == '--warranty' or o == '-w':
1624 files = do_options ()
1625 if not files or len (files) > 1:
1631 basename = os.path.splitext (file)[0]
1632 basename = os.path.split (basename)[1]
1634 global process_cmd, format
1636 format = guess_format (files[0])
1639 if format == TEXINFO or format == HTML:
1641 if process_cmd == '':
1642 process_cmd = lilypond_binary \
1643 + ' --formats=%s --backend eps ' % formats
1646 process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1647 for p in include_path])
1649 ly.identify (sys.stderr)
1652 chunks = do_file (file)
1653 if psfonts_p and invokes_lilypond ():
1654 fontextract.verbose = verbose_p
1655 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1659 psfonts_file = basename + '.psfonts'
1661 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1662 fontextract.extract_fonts (psfonts_file,
1663 [x.basename() + '.eps'
1664 for x in snippet_chunks])
1668 except Compile_error:
1671 if format == TEXINFO or format == LATEX:
1673 ly.warning (_ ("option --psfonts not used"))
1674 ly.warning (_ ("processing with dvips will have no fonts"))
1676 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1677 output = os.path.join (output_name, basename + '.dvi' )
1680 ly.progress (_ ("DVIPS usage:"))
1682 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1685 if __name__ == '__main__':