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
37 # Users of python modules should include this snippet
38 # and customize variables below.
40 # We'll suffer this path initialization stuff as long as we don't install
41 # our python packages in <prefix>/lib/pythonX.Y
43 # If set, LILYPONDPREFIX must take prevalence.
44 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
45 import getopt, os, sys
46 datadir = '@local_lilypond_datadir@'
47 if not os.path.isdir (datadir):
48 datadir = '@lilypond_datadir@'
49 if os.environ.has_key ('LILYPONDPREFIX'):
50 datadir = os.environ['LILYPONDPREFIX']
51 while datadir[-1] == os.sep:
54 datadir = os.path.join (datadir, "share/lilypond/current/")
56 sys.path.insert (0, os.path.join (datadir, 'python'))
59 #if __name__ == '__main__':
67 program_version = '@TOPLEVEL_VERSION@'
68 program_name = os.path.basename (sys.argv[0])
71 original_dir = os.getcwd ()
75 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
78 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
79 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
80 lilypond-book --process='lilypond -I include' BOOK
83 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
84 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
86 option_definitions = [
87 (_ ("FMT"), 'f', 'format',
88 _ ('''use output format FMT (texi [default], texi-html,
90 (_ ("FILTER"), 'F', 'filter',
91 _ ("pipe snippets through FILTER [convert-ly -n -]")),
93 _ ("print this help")),
94 (_ ("DIR"), 'I', 'include',
95 _ ("add DIR to include path")),
96 (_ ("DIR"), 'o', 'output',
97 _ ("write output to DIR")),
98 (_ ("COMMAND"), 'P', 'process',
99 _ ("process ly_files using COMMAND FILE...")),
101 _ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
102 must use this with dvips -h INPUT.psfonts''')),
106 _ ("print version information")),
107 ('', 'w', 'warranty',
108 _ ("show warranty and copyright")),
111 include_path = [os.path.abspath (os.getcwd ())]
112 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
114 # Only use installed binary when we are installed too.
115 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
116 lilypond_binary = 'lilypond'
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 print-score-with-defaults)
556 #(set! toplevel-music-handler (lambda (p m)
557 (print-score-with-defaults
558 p (scorify-music m p))))
560 #(ly:set-option (quote no-point-and-click))
561 #(define inside-lilypond-book #t)
562 #(define version-seen? #t)
570 %% ****************************************************************
571 %% Start cut-&-pastable-section
572 %% ****************************************************************
575 #(define dump-extents #t)
576 %(font_dump_setting)s
590 %% ****************************************************************
591 %% ly snippet contents follows:
592 %% ****************************************************************
596 %% ****************************************************************
598 %% ****************************************************************
605 %% ****************************************************************
607 %% ****************************************************************
611 %% ****************************************************************
613 %% ****************************************************************
616 texinfo_linewidths = {
617 '@afourpaper': '160\\mm',
618 '@afourwide': '6.5\\in',
619 '@afourlatex': '150\\mm',
620 '@smallbook': '5\\in',
621 '@letterpaper': '6\\in',
624 def classic_lilypond_book_compatibility (key, value):
625 if key == 'singleline' and value == None:
626 return (RAGGEDRIGHT, None)
628 m = re.search ('relative\s*([-0-9])', key)
630 return ('relative', m.group (1))
632 m = re.match ('([0-9]+)pt', key)
634 return ('staffsize', m.group (1))
636 if key == 'indent' or key == 'linewidth':
637 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
639 f = float (m.group (1))
640 return (key, '%f\\%s' % (f, m.group (2)))
644 def find_file (name):
645 for i in include_path:
646 full = os.path.join (i, name)
647 if os.path.exists (full):
649 ly.error (_ ("file not found: %s") % name + '\n')
653 def verbatim_html (s):
654 return re.sub ('>', '>',
656 re.sub ('&', '&', s)))
658 def verbatim_texinfo (s):
659 return re.sub ('{', '@{',
661 re.sub ('@', '@@', s)))
663 def split_options (option_string):
666 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
667 for i in range(len(options)):
668 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
671 return re.split (format_res[format]['option_sep'],
675 def invokes_lilypond ():
676 return re.search ('^[\'\"0-9A-Za-z/]*lilypond', process_cmd)
678 def set_default_options (source):
679 global default_ly_options
680 if not default_ly_options.has_key (LINEWIDTH):
682 textwidth = get_latex_textwidth (source)
683 default_ly_options[LINEWIDTH] = \
684 '''%.0f\\pt''' % textwidth
685 elif format == TEXINFO:
686 for (k, v) in texinfo_linewidths.items ():
687 # FIXME: @layout is usually not in
690 # \input texinfo @c -*-texinfo-*-
692 # Bluntly search first K items of
694 # s = chunks[0].replacement_text ()
695 if re.search (k, source[:1024]):
696 default_ly_options[LINEWIDTH] = v
700 def replacement_text (self):
703 def filter_text (self):
704 return self.replacement_text ()
706 def ly_is_outdated (self):
709 def png_is_outdated (self):
712 class Substring (Chunk):
713 def __init__ (self, source, start, end, line_number):
717 self.line_number = line_number
718 self.override_text = None
720 def replacement_text (self):
721 if self.override_text:
722 return self.override_text
724 return self.source[self.start:self.end]
726 class Snippet (Chunk):
727 def __init__ (self, type, match, format, line_number):
731 self.option_dict = {}
733 self.line_number = line_number
735 def replacement_text (self):
736 return self.match.group ('match')
738 def substring (self, s):
739 return self.match.group (s)
742 return `self.__class__` + ' type = ' + self.type
744 class Include_snippet (Snippet):
745 def processed_filename (self):
746 f = self.substring ('filename')
747 return os.path.splitext (f)[0] + format2ext[format]
749 def replacement_text (self):
750 s = self.match.group ('match')
751 f = self.substring ('filename')
753 return re.sub (f, self.processed_filename (), s)
755 class Lilypond_snippet (Snippet):
756 def __init__ (self, type, match, format, line_number):
757 Snippet.__init__ (self, type, match, format, line_number)
758 os = match.group ('options')
759 self.do_options (os, self.type)
762 return self.substring ('code')
767 return self.compose_ly (s)
770 def do_options (self, option_string, type):
771 self.option_dict = {}
773 options = split_options (option_string)
776 if string.find (i, '=') > 0:
777 (key, value) = re.split ('\s*=\s*', i)
778 self.option_dict[key] = value
780 if i in no_options.keys ():
781 if no_options[i] in self.option_dict.keys ():
782 del self.option_dict[no_options[i]]
784 self.option_dict[i] = None
786 has_linewidth = self.option_dict.has_key (LINEWIDTH)
787 no_linewidth_value = 0
789 # If LINEWIDTH is used without parameter, set it to default.
790 if has_linewidth and self.option_dict[LINEWIDTH] == None:
791 no_linewidth_value = 1
792 del self.option_dict[LINEWIDTH]
794 for i in default_ly_options.keys ():
795 if i not in self.option_dict.keys ():
796 self.option_dict[i] = default_ly_options[i]
798 if not has_linewidth:
799 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
800 self.option_dict[RAGGEDRIGHT] = None
802 if type == 'lilypond':
803 if LINEWIDTH in self.option_dict.keys ():
804 del self.option_dict[LINEWIDTH]
806 if RAGGEDRIGHT in self.option_dict.keys ():
807 if LINEWIDTH in self.option_dict.keys ():
808 del self.option_dict[LINEWIDTH]
810 if QUOTE in self.option_dict.keys () or type == 'lilypond':
811 if LINEWIDTH in self.option_dict.keys ():
812 del self.option_dict[LINEWIDTH]
814 if not INDENT in self.option_dict.keys ():
815 self.option_dict[INDENT] = '0\\mm'
817 # The QUOTE pattern from ly_options only emits the `linewidth'
819 if has_linewidth and QUOTE in self.option_dict.keys ():
820 if no_linewidth_value:
821 del self.option_dict[LINEWIDTH]
823 del self.option_dict[QUOTE]
825 def compose_ly (self, code):
826 if FRAGMENT in self.option_dict.keys ():
834 # The original concept of the `exampleindent' option is broken.
835 # It is not possible to get a sane value for @exampleindent at all
836 # without processing the document itself. Saying
844 # causes ugly results with the DVI backend of texinfo since the
845 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
846 # value). Executing the above code changes the environment
847 # indentation to an unknown value because we don't know the amount
848 # of 1em in advance since it is font-dependent. Modifying
849 # @exampleindent in the middle of a document is simply not
850 # supported within texinfo.
852 # As a consequence, the only function of @exampleindent is now to
853 # specify the amount of indentation for the `quote' option.
855 # To set @exampleindent locally to zero, we use the @format
856 # environment for non-quoted snippets.
857 override[EXAMPLEINDENT] = r'0.4\in'
858 override[LINEWIDTH] = texinfo_linewidths['@smallbook']
859 override.update (default_ly_options)
862 for (key, value) in self.option_dict.items ():
864 option_list.append (key)
866 option_list.append (key + '=' + value)
867 option_string = string.join (option_list, ',')
870 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
871 for a in compose_types:
874 for (key, value) in self.option_dict.items ():
876 classic_lilypond_book_compatibility (key, value)
880 (_ ("deprecated ly-option used: %s=%s" \
883 (_ ("compatibility mode translation: %s=%s" \
887 (_ ("deprecated ly-option used: %s" \
890 (_ ("compatibility mode translation: %s" \
893 (key, value) = (c_key, c_value)
896 override[key] = value
898 if not override.has_key (key):
902 for type in compose_types:
903 if ly_options[type].has_key (key):
904 compose_dict[type].append (ly_options[type][key])
908 if not found and key not in simple_options:
909 ly.warning (_ ("ignoring unknown ly option: %s") % key)
912 if RELATIVE in override.keys () and override[RELATIVE]:
913 relative = string.atoi (override[RELATIVE])
919 relative_quotes += ',' * (- relative)
921 relative_quotes += "'" * relative
923 program_name = __main__.program_name
925 paper_string = string.join (compose_dict[PAPER],
927 layout_string = string.join (compose_dict[LAYOUT],
929 notes_string = string.join (compose_dict[NOTES],
931 preamble_string = string.join (compose_dict[PREAMBLE],
934 font_dump_setting = ''
935 if FONTLOAD in self.option_dict:
936 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
938 return (PREAMBLE_LY + body) % vars ()
943 self.hash = abs (hash (self.full_ly ()))
947 if FILENAME in self.option_dict:
948 return self.option_dict[FILENAME]
950 return 'lily-%d' % self.get_hash ()
954 outf = open (self.basename () + '.ly', 'w')
955 outf.write (self.full_ly ())
957 open (self.basename () + '.txt', 'w').write ('image of music')
959 def ly_is_outdated (self):
960 base = self.basename ()
962 tex_file = '%s.tex' % base
963 eps_file = '%s.eps' % base
964 system_file = '%s-systems.tex' % base
965 ly_file = '%s.ly' % base
966 ok = os.path.exists (ly_file) \
967 and os.path.exists (system_file)\
968 and os.stat (system_file)[stat.ST_SIZE] \
969 and re.match ('% eof', open (system_file).readlines ()[-1])
970 if ok and (not use_hash_p or FILENAME in self.option_dict):
971 ok = (self.full_ly () == open (ly_file).read ())
973 # TODO: Do something smart with target formats
974 # (ps, png) and m/ctimes.
978 def png_is_outdated (self):
979 base = self.basename ()
980 ok = self.ly_is_outdated ()
981 if format == HTML or format == TEXINFO:
982 ok = ok and os.path.exists (base + '.eps')
986 page_count = ly.ps_page_count (base + '.eps')
989 ok = ok and os.path.exists (base + '.png')
991 for a in range (1, page_count + 1):
992 ok = ok and os.path.exists (base + '-page%d.png' % a)
996 def texstr_is_outdated (self):
1000 base = self.basename ()
1001 ok = self.ly_is_outdated ()
1002 ok = ok and (os.path.exists (base + '.texstr'))
1005 def filter_text (self):
1006 code = self.substring ('code')
1007 s = run_filter (code)
1010 'options': self.match.group ('options')
1013 return output[self.format][FILTER] % d
1015 def replacement_text (self):
1016 func = Lilypond_snippet.__dict__['output_' + self.format]
1019 def get_images (self):
1020 base = self.basename ()
1022 single = '%(base)s.png' % vars ()
1023 multiple = '%(base)s-page1.png' % vars ()
1025 if os.path.exists (multiple) \
1026 and (not os.path.exists (single) \
1027 or (os.stat (multiple)[stat.ST_MTIME] \
1028 > os.stat (single)[stat.ST_MTIME])):
1029 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1030 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1031 images = tuple (images)
1034 def output_html (self):
1036 base = self.basename ()
1038 str += self.output_print_filename (HTML)
1039 if VERBATIM in self.option_dict:
1040 verb = verbatim_html (self.substring ('code'))
1041 str += write (output[HTML][VERBATIM] % vars ())
1042 if QUOTE in self.option_dict:
1043 str = output[HTML][QUOTE] % vars ()
1045 str += output[HTML][BEFORE] % vars ()
1046 for image in self.get_images ():
1047 (base, ext) = os.path.splitext (image)
1048 alt = self.option_dict[ALT]
1049 str += output[HTML][OUTPUT] % vars ()
1050 str += output[HTML][AFTER] % vars ()
1053 def output_info (self):
1055 for image in self.get_images ():
1056 (base, ext) = os.path.splitext (image)
1058 # URG, makeinfo implicitly prepends dot to extension.
1059 # Specifying no extension is most robust.
1061 alt = self.option_dict[ALT]
1062 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1064 base = self.basename ()
1065 str += output[format][OUTPUT] % vars ()
1068 def output_latex (self):
1070 base = self.basename ()
1072 str += self.output_print_filename (LATEX)
1073 if VERBATIM in self.option_dict:
1074 verb = self.substring ('code')
1075 str += (output[LATEX][VERBATIM] % vars ())
1077 str += (output[LATEX][OUTPUT] % vars ())
1078 if QUOTE in self.option_dict:
1079 str = output[LATEX][QUOTE] % vars ()
1082 def output_print_filename (self, format):
1084 if PRINTFILENAME in self.option_dict:
1085 base = self.basename ()
1086 filename = self.substring ('filename')
1087 str = output[format][PRINTFILENAME] % vars ()
1091 def output_texinfo (self):
1093 if self.output_print_filename (TEXINFO):
1095 + self.output_print_filename (HTML)
1098 + self.output_print_filename (LATEX)
1100 base = self.basename ()
1101 if TEXIDOC in self.option_dict:
1102 texidoc = base + '.texidoc'
1103 if os.path.exists (texidoc):
1104 str += '@include %(texidoc)s\n\n' % vars ()
1106 if VERBATIM in self.option_dict:
1107 verb = verbatim_texinfo (self.substring ('code'))
1108 str += (output[TEXINFO][VERBATIM] % vars ())
1109 if not QUOTE in self.option_dict:
1110 str = output[TEXINFO][NOQUOTE] % vars ()
1112 str += self.output_info ()
1114 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1115 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1116 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1118 if QUOTE in self.option_dict:
1119 str = output[TEXINFO][QUOTE] % vars ()
1121 # need par after image
1126 class Lilypond_file_snippet (Lilypond_snippet):
1128 name = self.substring ('filename')
1129 return '\\renameinput \"%s\"\n%s' \
1130 % (name, open (find_file (name)).read ())
1132 snippet_type_to_class = {
1133 'lilypond_file': Lilypond_file_snippet,
1134 'lilypond_block': Lilypond_snippet,
1135 'lilypond': Lilypond_snippet,
1136 'include': Include_snippet,
1139 def find_linestarts (s):
1144 i = s.find ('\n', start)
1152 nls.append (len (s))
1155 def find_toplevel_snippets (s, types):
1158 res[i] = ly.re.compile (snippet_res[format][i])
1162 ## found = dict (map (lambda x: (x, None),
1166 map (lambda x, f = found: f.setdefault (x, None),
1169 line_starts = find_linestarts (s)
1171 # We want to search for multiple regexes, without searching
1172 # the string multiple times for one regex.
1173 # Hence, we use earlier results to limit the string portion
1175 # Since every part of the string is traversed at most once for
1176 # every type of snippet, this is linear.
1182 if not found[type] or found[type][0] < index:
1184 m = res[type].search (s[index:endex])
1189 if snippet_type_to_class.has_key (type):
1190 cl = snippet_type_to_class[type]
1193 start = index + m.start ('match')
1194 line_number = line_start_idx
1195 while (line_starts[line_number] < start):
1199 snip = cl (type, m, format, line_number)
1200 found[type] = (start, snip)
1204 or found[type][0] < found[first][0]):
1209 # Limiting the search space is a cute
1210 # idea, but this *requires* to search
1211 # for possible containing blocks
1212 # first, at least as long as we do not
1213 # search for the start of blocks, but
1214 # always/directly for the entire
1215 # @block ... @end block.
1217 endex = found[first][0]
1220 snippets.append (Substring (s, index, len (s), line_start_idx))
1223 while (start > line_starts[line_start_idx+1]):
1226 (start, snip) = found[first]
1227 snippets.append (Substring (s, index, start, line_start_idx + 1))
1228 snippets.append (snip)
1230 index = start + len (snip.match.group ('match'))
1234 def filter_pipe (input, cmd):
1236 ly.progress (_ ("Opening filter `%s'") % cmd)
1238 (stdin, stdout, stderr) = os.popen3 (cmd)
1240 status = stdin.close ()
1244 output = stdout.read ()
1245 status = stdout.close ()
1246 error = stderr.read ()
1250 signal = 0x0f & status
1251 if status or (not output and error):
1252 exit_status = status >> 8
1253 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1254 ly.error (_ ("The error log is as follows:"))
1255 sys.stderr.write (error)
1256 sys.stderr.write (stderr.read ())
1265 return filter_pipe (s, filter_cmd)
1267 def is_derived_class (cl, baseclass):
1270 for b in cl.__bases__:
1271 if is_derived_class (b, baseclass):
1275 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1276 ly_names = filter (lambda x: x,
1277 map (Lilypond_snippet.basename, ly_snippets))
1278 texstr_names = filter (lambda x: x,
1279 map (Lilypond_snippet.basename, texstr_snippets))
1280 png_names = filter (lambda x: x,
1281 map (Lilypond_snippet.basename, png_snippets))
1284 def my_system (cmd):
1285 status = ly.system (cmd,
1286 ignore_error = 1, progress_p = 1)
1289 ly.error ('Process %s exited unsuccessfully.' % cmd)
1293 # the --process=CMD switch is a bad idea
1294 # it is too generic for lilypond-book.
1295 if texstr_names and invokes_lilypond:
1296 my_system (string.join ([cmd, '--backend texstr',
1297 'snippet-map.ly'] + texstr_names))
1298 for l in texstr_names:
1299 my_system ('latex %s.texstr' % l)
1302 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1304 LATEX_INSPECTION_DOCUMENT = r'''
1308 \typeout{textwidth=\the\textwidth}
1309 \typeout{columnsep=\the\columnsep}
1310 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1314 # Do we need anything else besides `textwidth'?
1315 def get_latex_textwidth (source):
1316 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1317 preamble = source[:m.start (0)]
1318 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1319 # Workaround problems with unusable $TMP on Cygwin:
1320 tempfile.tempdir = ''
1321 tmpfile = tempfile.mktemp('.tex')
1322 logfile = os.path.splitext (tmpfile)[0] + '.log'
1323 open (tmpfile,'w').write (latex_document)
1324 ly.system ('latex %s' % tmpfile)
1325 parameter_string = open (logfile).read()
1330 m = re.search ('columns=([0-9.]*)', parameter_string)
1332 columns = string.atoi (m.group (1))
1335 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1337 columnsep = string.atof (m.group (1))
1340 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1342 textwidth = string.atof (m.group (1))
1344 textwidth = (textwidth - columnsep) / columns
1348 def modify_preamble (chunk):
1349 str = chunk.replacement_text ()
1350 if (re.search (r"\\begin{document}", str)
1351 and not re.search ("{graphic[sx]", str)):
1352 str = re.sub (r"\\begin{document}",
1353 r"\\RequirePackage{graphics}" + '\n'
1354 + r"\\begin{document}",
1356 chunk.override_text = str
1368 '.texinfo': TEXINFO,
1374 # TEXINFO: '.texinfo',
1379 class Compile_error:
1382 def write_file_map (lys, name):
1383 snippet_map = open ('snippet-map.ly', 'w')
1384 snippet_map.write ("""
1385 #(define version-seen? #t)
1386 #(ly:add-file-name-alist '(
1389 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1395 snippet_map.write ('))\n')
1397 def do_process_cmd (chunks, input_name):
1398 all_lys = filter (lambda x: is_derived_class (x.__class__,
1402 write_file_map (all_lys, input_name)
1404 filter (lambda x: is_derived_class (x.__class__,
1406 and x.ly_is_outdated (),
1409 filter (lambda x: is_derived_class (x.__class__,
1411 and x.texstr_is_outdated (),
1414 filter (lambda x: is_derived_class (x.__class__,
1416 and x.png_is_outdated (),
1419 ly.progress (_ ("Writing snippets..."))
1420 map (Lilypond_snippet.write_ly, ly_outdated)
1424 ly.progress (_ ("Processing..."))
1426 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1428 ly.progress (_ ("All snippets are up to date..."))
1431 def guess_format (input_filename):
1433 e = os.path.splitext (input_filename)[1]
1434 if e in ext2format.keys ():
1436 format = ext2format[e]
1438 ly.error (_ ("can't determine format for: %s" \
1443 def write_if_updated (file_name, lines):
1445 f = open (file_name)
1447 new_str = string.join (lines, '')
1448 if oldstr == new_str:
1449 ly.progress (_ ("%s is up to date.") % file_name)
1455 ly.progress (_ ("Writing `%s'...") % file_name)
1456 open (file_name, 'w').writelines (lines)
1459 def do_file (input_filename):
1461 if not input_filename or input_filename == '-':
1462 in_handle = sys.stdin
1463 input_fullname = '<stdin>'
1465 if os.path.exists (input_filename):
1466 input_fullname = input_filename
1467 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1468 # urg python interface to libkpathsea?
1469 input_fullname = ly.read_pipe ('kpsewhich '
1470 + input_filename)[:-1]
1472 input_fullname = find_file (input_filename)
1473 in_handle = open (input_fullname)
1475 if input_filename == '-':
1476 input_base = 'stdin'
1478 input_base = os.path.basename \
1479 (os.path.splitext (input_filename)[0])
1481 # Only default to stdout when filtering.
1482 if output_name == '-' or (not output_name and filter_cmd):
1483 output_filename = '-'
1484 output_file = sys.stdout
1486 # don't complain when output_name is existing
1487 output_filename = input_base + format2ext[format]
1489 if not os.path.isdir (output_name):
1490 os.mkdir (output_name, 0777)
1491 os.chdir (output_name)
1493 if os.path.exists (input_filename) \
1494 and os.path.exists (output_filename) \
1495 and os.path.samefile (output_filename, input_fullname):
1497 _ ("Output would overwrite input file; use --output."))
1501 ly.progress (_ ("Reading %s...") % input_fullname)
1502 source = in_handle.read ()
1505 set_default_options (source)
1508 # FIXME: Containing blocks must be first, see
1509 # find_toplevel_snippets.
1511 'multiline_comment',
1515 'singleline_comment',
1520 ly.progress (_ ("Dissecting..."))
1521 chunks = find_toplevel_snippets (source, snippet_types)
1524 modify_preamble (chunks[0])
1530 write_if_updated (output_filename,
1531 [c.filter_text () for c in chunks])
1533 do_process_cmd (chunks, input_fullname)
1534 ly.progress (_ ("Compiling %s...") % output_filename)
1536 write_if_updated (output_filename,
1537 [s.replacement_text ()
1540 def process_include (snippet):
1541 os.chdir (original_dir)
1542 name = snippet.substring ('filename')
1543 ly.progress (_ ("Processing include: %s") % name)
1545 return do_file (name)
1547 include_chunks = map (process_include,
1548 filter (lambda x: is_derived_class (x.__class__,
1553 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1555 except Compile_error:
1556 os.chdir (original_dir)
1557 ly.progress (_ ("Removing `%s'") % output_filename)
1562 global format, output_name, psfonts_p
1563 global filter_cmd, process_cmd, verbose_p
1565 (sh, long) = ly.getopt_args (option_definitions)
1567 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1568 except getopt.error, s:
1569 sys.stderr.write ('\n')
1570 ly.error (_ ("getopt says: `%s'" % s))
1571 sys.stderr.write ('\n')
1581 elif o == '--filter' or o == '-F':
1584 elif o == '--format' or o == '-f':
1586 if a == 'texi-html' or a == 'texi':
1588 elif o == '--tex-backend ':
1590 elif o == '--help' or o == '-h':
1593 elif o == '--include' or o == '-I':
1594 include_path.append (os.path.join (original_dir,
1595 os.path.abspath (a)))
1596 elif o == '--output' or o == '-o':
1598 elif o == '--process' or o == '-P':
1601 elif o == '--version' or o == '-v':
1602 ly.identify (sys.stdout)
1604 elif o == '--verbose' or o == '-V':
1606 elif o == '--psfonts':
1608 elif o == '--warranty' or o == '-w':
1615 files = do_options ()
1616 if not files or len (files) > 1:
1622 basename = os.path.splitext (file)[0]
1623 basename = os.path.split (basename)[1]
1625 global process_cmd, format
1627 format = guess_format (files[0])
1630 if format == TEXINFO or format == HTML:
1632 if process_cmd == '':
1633 process_cmd = lilypond_binary \
1634 + ' --formats=%s --backend eps ' % formats
1637 process_cmd += string.join ([(' -I %s' % p)
1638 for p in include_path])
1640 ly.identify (sys.stderr)
1643 chunks = do_file (file)
1644 if psfonts_p and invokes_lilypond ():
1645 fontextract.verbose = verbose_p
1646 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1650 psfonts_file = basename + '.psfonts'
1652 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1653 fontextract.extract_fonts (psfonts_file,
1654 [x.basename() + '.eps'
1655 for x in snippet_chunks])
1659 except Compile_error:
1662 if format == TEXINFO or format == LATEX:
1664 ly.warning (_ ("option --psfonts not used"))
1665 ly.warning (_ ("processing with dvips will have no fonts"))
1667 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1668 output = os.path.join (output_name, basename + '.dvi' )
1671 ly.progress (_ ("DVIPS usage:"))
1673 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1676 if __name__ == '__main__':