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''')),
104 ('', '', 'keep-line-breaks',
105 _ ('''do not alter the number of newline characters in output
106 .tex files. Useful when the LaTeX package srcltx is used''')),
110 _ ("print version information")),
111 ('', 'w', 'warranty',
112 _ ("show warranty and copyright")),
115 include_path = [os.path.abspath (os.getcwd ())]
116 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
118 # Only use installed binary when we are installed too.
119 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
120 lilypond_binary = 'lilypond'
129 default_ly_options = { 'alt': "[image of music]" }
132 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
136 EXAMPLEINDENT = 'exampleindent'
138 FRAGMENT = 'fragment'
143 LINE_WIDTH = 'line-width'
144 NOFRAGMENT = 'nofragment'
145 NOINDENT = 'noindent'
150 OUTPUTIMAGE = 'outputimage'
153 PREAMBLE = 'preamble'
154 PRINTFILENAME = 'printfilename'
156 RAGGED_RIGHT = 'ragged-right'
157 RELATIVE = 'relative'
158 STAFFSIZE = 'staffsize'
161 VERBATIM = 'verbatim'
162 FONTLOAD = 'fontload'
163 FILENAME = 'filename'
167 # NOTIME has no opposite so it isn't part of this dictionary.
168 # NOQUOTE is used internally only.
170 NOFRAGMENT: FRAGMENT,
175 # Recognize special sequences in the input.
177 # (?P<name>regex) -- Assign result of REGEX to NAME.
178 # *? -- Match non-greedily.
179 # (?m) -- Multiline regex: Make ^ and $ match at each line.
180 # (?s) -- Make the dot match all characters including newline.
181 # (?x) -- Ignore whitespace in patterns.
193 (\s*(?P<options>.*?)\s*:)?\s*
201 \s*(?P<options>.*?)\s*
210 \s*(?P<options>.*?)\s*
212 \s*(?P<filename>.*?)\s*
219 (?P<code><!--\s.*?!-->)
222 'singleline_comment':
228 (?P<code><pre>.*?</pre>))''',
234 (?P<code><pre>\s.*?</pre>\s))''',
253 \s*(?P<options>.*?)\s*
264 \s*(?P<options>.*?)\s*
268 \\end\s*{lilypond})''',
276 \s*(?P<options>.*?)\s*
284 'singleline_comment':
307 \\end\s*{verbatim}))''',
316 (?P<filename>\S+))''',
320 ^[^\n]*?(?!@c\s+)[^\n]*?
324 \s*(?P<options>.*?)\s*
334 \s*(?P<options>.*?)\s*
337 ^@end\s+lilypond)\s''',
344 \s*(?P<options>.*?)\s*
355 @end\s+ignore))\s''',
357 'singleline_comment':
362 @c([ \t][^\n]*|)\n))''',
364 # Don't do this: It interferes with @code{@{}.
365 # 'verb': r'''(?P<code>@code{.*?})''',
373 @end\s+example\s))''',
379 'intertext': r',?\s*intertext=\".*?\"',
384 'intertext': r',?\s*intertext=\".*?\"',
385 'option_sep': '\s*,\s*',
389 'intertext': r',?\s*intertext=\".*?\"',
390 'option_sep': '\s*,\s*',
394 # Options without a pattern in ly_options.
411 RELATIVE: r'''\relative c%(relative_quotes)s''',
416 INDENT: r'''indent = %(indent)s''',
418 LINE_WIDTH: r'''line-width = %(line-width)s''',
420 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
422 RAGGED_RIGHT: r'''ragged-right = ##t''',
424 PACKED: r'''packed = ##t''',
436 \remove Time_signature_engraver
442 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
449 FILTER: r'''<lilypond %(options)s>
459 <a href="%(base)s.ly">''',
462 <img align="center" valign="center"
463 border="0" src="%(image)s" alt="%(alt)s">''',
465 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
467 QUOTE: r'''<blockquote>
481 \ifx\preLilyPondExample \undefined
487 \input %(base)s-systems.tex
488 \ifx\postLilyPondExample \undefined
495 PRINTFILENAME: '''\\texttt{%(filename)s}
498 QUOTE: r'''\begin{quotation}%(str)s
501 VERBATIM: r'''\noindent
502 \begin{verbatim}%(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 = '''%%%% Generated by %(program_name)s
554 %%%% Options: [%(option_string)s]
556 #(set! toplevel-score-handler print-score-with-defaults)
557 #(set! toplevel-music-handler
559 (if (not (eq? (ly:music-property m \'void) #t))
560 (print-score-with-defaults
561 p (scorify-music m p)))))
563 #(ly:set-option (quote no-point-and-click))
564 #(define inside-lilypond-book #t)
565 #(define version-seen? #t)
573 %% ****************************************************************
574 %% Start cut-&-pastable-section
575 %% ****************************************************************
578 #(define dump-extents #t)
579 %(font_dump_setting)s
593 %% ****************************************************************
594 %% ly snippet contents follows:
595 %% ****************************************************************
599 %% ****************************************************************
601 %% ****************************************************************
608 %% ****************************************************************
610 %% ****************************************************************
614 %% ****************************************************************
616 %% ****************************************************************
619 texinfo_line_widths = {
620 '@afourpaper': '160\\mm',
621 '@afourwide': '6.5\\in',
622 '@afourlatex': '150\\mm',
623 '@smallbook': '5\\in',
624 '@letterpaper': '6\\in',
627 def classic_lilypond_book_compatibility (key, value):
628 if key == 'singleline' and value == None:
629 return (RAGGED_RIGHT, None)
631 m = re.search ('relative\s*([-0-9])', key)
633 return ('relative', m.group (1))
635 m = re.match ('([0-9]+)pt', key)
637 return ('staffsize', m.group (1))
639 if key == 'indent' or key == 'line-width':
640 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
642 f = float (m.group (1))
643 return (key, '%f\\%s' % (f, m.group (2)))
647 def find_file (name):
648 for i in include_path:
649 full = os.path.join (i, name)
650 if os.path.exists (full):
652 ly.error (_ ("file not found: %s") % name + '\n')
656 def verbatim_html (s):
657 return re.sub ('>', '>',
659 re.sub ('&', '&', s)))
661 def verbatim_texinfo (s):
662 return re.sub ('{', '@{',
664 re.sub ('@', '@@', s)))
666 def split_options (option_string):
669 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
670 for i in range(len(options)):
671 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
674 return re.split (format_res[format]['option_sep'],
678 def invokes_lilypond ():
679 return re.search ('^[\'\"0-9A-Za-z/.]*lilypond', process_cmd)
681 def set_default_options (source):
682 global default_ly_options
683 if not default_ly_options.has_key (LINE_WIDTH):
685 textwidth = get_latex_textwidth (source)
686 default_ly_options[LINE_WIDTH] = \
687 '''%.0f\\pt''' % textwidth
688 elif format == TEXINFO:
689 for (k, v) in texinfo_line_widths.items ():
690 # FIXME: @layout is usually not in
693 # \input texinfo @c -*-texinfo-*-
695 # Bluntly search first K items of
697 # s = chunks[0].replacement_text ()
698 if re.search (k, source[:1024]):
699 default_ly_options[LINE_WIDTH] = v
703 def replacement_text (self):
706 def filter_text (self):
707 return self.replacement_text ()
709 def ly_is_outdated (self):
712 def png_is_outdated (self):
718 class Substring (Chunk):
719 def __init__ (self, source, start, end, line_number):
723 self.line_number = line_number
724 self.override_text = None
729 def replacement_text (self):
730 if self.override_text:
731 return self.override_text
733 return self.source[self.start:self.end]
735 class Snippet (Chunk):
736 def __init__ (self, type, match, format, line_number):
740 self.option_dict = {}
742 self.line_number = line_number
744 def replacement_text (self):
745 return self.match.group ('match')
747 def substring (self, s):
748 return self.match.group (s)
751 return `self.__class__` + ' type = ' + self.type
753 class Include_snippet (Snippet):
754 def processed_filename (self):
755 f = self.substring ('filename')
756 return os.path.splitext (f)[0] + format2ext[format]
758 def replacement_text (self):
759 s = self.match.group ('match')
760 f = self.substring ('filename')
762 return re.sub (f, self.processed_filename (), s)
764 class Lilypond_snippet (Snippet):
765 def __init__ (self, type, match, format, line_number):
766 Snippet.__init__ (self, type, match, format, line_number)
767 os = match.group ('options')
768 self.do_options (os, self.type)
771 return self.substring ('code')
776 return self.compose_ly (s)
779 def do_options (self, option_string, type):
780 self.option_dict = {}
782 options = split_options (option_string)
785 if string.find (i, '=') > 0:
786 (key, value) = re.split ('\s*=\s*', i)
787 self.option_dict[key] = value
789 if i in no_options.keys ():
790 if no_options[i] in self.option_dict.keys ():
791 del self.option_dict[no_options[i]]
793 self.option_dict[i] = None
795 has_line_width = self.option_dict.has_key (LINE_WIDTH)
796 no_line_width_value = 0
798 # If LINE_WIDTH is used without parameter, set it to default.
799 if has_line_width and self.option_dict[LINE_WIDTH] == None:
800 no_line_width_value = 1
801 del self.option_dict[LINE_WIDTH]
803 for i in default_ly_options.keys ():
804 if i not in self.option_dict.keys ():
805 self.option_dict[i] = default_ly_options[i]
807 if not has_line_width:
808 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
809 self.option_dict[RAGGED_RIGHT] = None
811 if type == 'lilypond':
812 if LINE_WIDTH in self.option_dict.keys ():
813 del self.option_dict[LINE_WIDTH]
815 if RAGGED_RIGHT in self.option_dict.keys ():
816 if LINE_WIDTH in self.option_dict.keys ():
817 del self.option_dict[LINE_WIDTH]
819 if QUOTE in self.option_dict.keys () or type == 'lilypond':
820 if LINE_WIDTH in self.option_dict.keys ():
821 del self.option_dict[LINE_WIDTH]
823 if not INDENT in self.option_dict.keys ():
824 self.option_dict[INDENT] = '0\\mm'
826 # The QUOTE pattern from ly_options only emits the `line-width'
828 if has_line_width and QUOTE in self.option_dict.keys ():
829 if no_line_width_value:
830 del self.option_dict[LINE_WIDTH]
832 del self.option_dict[QUOTE]
834 def compose_ly (self, code):
835 if FRAGMENT in self.option_dict.keys ():
843 # The original concept of the `exampleindent' option is broken.
844 # It is not possible to get a sane value for @exampleindent at all
845 # without processing the document itself. Saying
853 # causes ugly results with the DVI backend of texinfo since the
854 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
855 # value). Executing the above code changes the environment
856 # indentation to an unknown value because we don't know the amount
857 # of 1em in advance since it is font-dependent. Modifying
858 # @exampleindent in the middle of a document is simply not
859 # supported within texinfo.
861 # As a consequence, the only function of @exampleindent is now to
862 # specify the amount of indentation for the `quote' option.
864 # To set @exampleindent locally to zero, we use the @format
865 # environment for non-quoted snippets.
866 override[EXAMPLEINDENT] = r'0.4\in'
867 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
868 override.update (default_ly_options)
871 for (key, value) in self.option_dict.items ():
873 option_list.append (key)
875 option_list.append (key + '=' + value)
876 option_string = string.join (option_list, ',')
879 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
880 for a in compose_types:
883 for (key, value) in self.option_dict.items ():
885 classic_lilypond_book_compatibility (key, value)
889 (_ ("deprecated ly-option used: %s=%s" \
892 (_ ("compatibility mode translation: %s=%s" \
896 (_ ("deprecated ly-option used: %s" \
899 (_ ("compatibility mode translation: %s" \
902 (key, value) = (c_key, c_value)
905 override[key] = value
907 if not override.has_key (key):
911 for type in compose_types:
912 if ly_options[type].has_key (key):
913 compose_dict[type].append (ly_options[type][key])
917 if not found and key not in simple_options:
918 ly.warning (_ ("ignoring unknown ly option: %s") % key)
921 if RELATIVE in override.keys () and override[RELATIVE]:
922 relative = string.atoi (override[RELATIVE])
928 relative_quotes += ',' * (- relative)
930 relative_quotes += "'" * relative
932 program_name = __main__.program_name
934 paper_string = string.join (compose_dict[PAPER],
936 layout_string = string.join (compose_dict[LAYOUT],
938 notes_string = string.join (compose_dict[NOTES],
940 preamble_string = string.join (compose_dict[PREAMBLE],
943 font_dump_setting = ''
944 if FONTLOAD in self.option_dict:
945 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
947 return (PREAMBLE_LY + body) % vars ()
952 self.hash = abs (hash (self.full_ly ()))
956 if FILENAME in self.option_dict:
957 return self.option_dict[FILENAME]
959 return 'lily-%d' % self.get_hash ()
963 outf = open (self.basename () + '.ly', 'w')
964 outf.write (self.full_ly ())
966 open (self.basename () + '.txt', 'w').write ('image of music')
968 def ly_is_outdated (self):
969 base = self.basename ()
971 tex_file = '%s.tex' % base
972 eps_file = '%s.eps' % base
973 system_file = '%s-systems.tex' % base
974 ly_file = '%s.ly' % base
975 ok = os.path.exists (ly_file) \
976 and os.path.exists (system_file)\
977 and os.stat (system_file)[stat.ST_SIZE] \
978 and re.match ('% eof', open (system_file).readlines ()[-1])
979 if ok and (not use_hash_p or FILENAME in self.option_dict):
980 ok = (self.full_ly () == open (ly_file).read ())
982 # TODO: Do something smart with target formats
983 # (ps, png) and m/ctimes.
987 def png_is_outdated (self):
988 base = self.basename ()
989 ok = self.ly_is_outdated ()
990 if format == HTML or format == TEXINFO:
991 ok = ok and os.path.exists (base + '.eps')
995 page_count = ly.ps_page_count (base + '.eps')
998 ok = ok and os.path.exists (base + '.png')
1000 for a in range (1, page_count + 1):
1001 ok = ok and os.path.exists (base + '-page%d.png' % a)
1005 def texstr_is_outdated (self):
1009 base = self.basename ()
1010 ok = self.ly_is_outdated ()
1011 ok = ok and (os.path.exists (base + '.texstr'))
1014 def filter_text (self):
1015 code = self.substring ('code')
1016 s = run_filter (code)
1019 'options': self.match.group ('options')
1022 return output[self.format][FILTER] % d
1024 def replacement_text (self):
1025 func = Lilypond_snippet.__dict__['output_' + self.format]
1028 def get_images (self):
1029 base = self.basename ()
1031 single = '%(base)s.png' % vars ()
1032 multiple = '%(base)s-page1.png' % vars ()
1034 if os.path.exists (multiple) \
1035 and (not os.path.exists (single) \
1036 or (os.stat (multiple)[stat.ST_MTIME] \
1037 > os.stat (single)[stat.ST_MTIME])):
1038 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1039 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1040 images = tuple (images)
1043 def output_html (self):
1045 base = self.basename ()
1047 str += self.output_print_filename (HTML)
1048 if VERBATIM in self.option_dict:
1049 verb = verbatim_html (self.substring ('code'))
1050 str += write (output[HTML][VERBATIM] % vars ())
1051 if QUOTE in self.option_dict:
1052 str = output[HTML][QUOTE] % vars ()
1054 str += output[HTML][BEFORE] % vars ()
1055 for image in self.get_images ():
1056 (base, ext) = os.path.splitext (image)
1057 alt = self.option_dict[ALT]
1058 str += output[HTML][OUTPUT] % vars ()
1059 str += output[HTML][AFTER] % vars ()
1062 def output_info (self):
1064 for image in self.get_images ():
1065 (base, ext) = os.path.splitext (image)
1067 # URG, makeinfo implicitly prepends dot to extension.
1068 # Specifying no extension is most robust.
1070 alt = self.option_dict[ALT]
1071 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1073 base = self.basename ()
1074 str += output[format][OUTPUT] % vars ()
1077 def output_latex (self):
1079 base = self.basename ()
1081 str += self.output_print_filename (LATEX)
1082 if VERBATIM in self.option_dict:
1083 verb = self.substring ('code')
1084 str += (output[LATEX][VERBATIM] % vars ())
1086 breaks = self.ly ().count ("\n")
1087 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1088 str += (output[LATEX][OUTPUT] % vars ())
1089 if QUOTE in self.option_dict:
1090 str = output[LATEX][QUOTE] % vars ()
1093 def output_print_filename (self, format):
1095 if PRINTFILENAME in self.option_dict:
1096 base = self.basename ()
1097 filename = self.substring ('filename')
1098 str = output[format][PRINTFILENAME] % vars ()
1102 def output_texinfo (self):
1104 if self.output_print_filename (TEXINFO):
1106 + self.output_print_filename (HTML)
1109 + self.output_print_filename (LATEX)
1111 base = self.basename ()
1112 if TEXIDOC in self.option_dict:
1113 texidoc = base + '.texidoc'
1114 if os.path.exists (texidoc):
1115 str += '@include %(texidoc)s\n\n' % vars ()
1117 if VERBATIM in self.option_dict:
1118 verb = verbatim_texinfo (self.substring ('code'))
1119 str += (output[TEXINFO][VERBATIM] % vars ())
1120 if not QUOTE in self.option_dict:
1121 str = output[TEXINFO][NOQUOTE] % vars ()
1123 str += self.output_info ()
1125 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1126 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1127 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1129 if QUOTE in self.option_dict:
1130 str = output[TEXINFO][QUOTE] % vars ()
1132 # need par after image
1137 class Lilypond_file_snippet (Lilypond_snippet):
1139 name = self.substring ('filename')
1140 return '\\sourcefilename \"%s\"\n%s' \
1141 % (name, open (find_file (name)).read ())
1143 snippet_type_to_class = {
1144 'lilypond_file': Lilypond_file_snippet,
1145 'lilypond_block': Lilypond_snippet,
1146 'lilypond': Lilypond_snippet,
1147 'include': Include_snippet,
1150 def find_linestarts (s):
1155 i = s.find ('\n', start)
1163 nls.append (len (s))
1166 def find_toplevel_snippets (s, types):
1169 res[i] = ly.re.compile (snippet_res[format][i])
1173 ## found = dict (map (lambda x: (x, None),
1177 map (lambda x, f = found: f.setdefault (x, None),
1180 line_starts = find_linestarts (s)
1182 # We want to search for multiple regexes, without searching
1183 # the string multiple times for one regex.
1184 # Hence, we use earlier results to limit the string portion
1186 # Since every part of the string is traversed at most once for
1187 # every type of snippet, this is linear.
1193 if not found[type] or found[type][0] < index:
1195 m = res[type].search (s[index:endex])
1200 if snippet_type_to_class.has_key (type):
1201 cl = snippet_type_to_class[type]
1204 start = index + m.start ('match')
1205 line_number = line_start_idx
1206 while (line_starts[line_number] < start):
1210 snip = cl (type, m, format, line_number)
1211 found[type] = (start, snip)
1215 or found[type][0] < found[first][0]):
1220 # Limiting the search space is a cute
1221 # idea, but this *requires* to search
1222 # for possible containing blocks
1223 # first, at least as long as we do not
1224 # search for the start of blocks, but
1225 # always/directly for the entire
1226 # @block ... @end block.
1228 endex = found[first][0]
1231 snippets.append (Substring (s, index, len (s), line_start_idx))
1234 while (start > line_starts[line_start_idx+1]):
1237 (start, snip) = found[first]
1238 snippets.append (Substring (s, index, start, line_start_idx + 1))
1239 snippets.append (snip)
1241 index = start + len (snip.match.group ('match'))
1245 def filter_pipe (input, cmd):
1247 ly.progress (_ ("Opening filter `%s'") % cmd)
1249 (stdin, stdout, stderr) = os.popen3 (cmd)
1251 status = stdin.close ()
1255 output = stdout.read ()
1256 status = stdout.close ()
1257 error = stderr.read ()
1261 signal = 0x0f & status
1262 if status or (not output and error):
1263 exit_status = status >> 8
1264 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1265 ly.error (_ ("The error log is as follows:"))
1266 sys.stderr.write (error)
1267 sys.stderr.write (stderr.read ())
1276 return filter_pipe (s, filter_cmd)
1278 def is_derived_class (cl, baseclass):
1281 for b in cl.__bases__:
1282 if is_derived_class (b, baseclass):
1286 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1287 ly_names = filter (lambda x: x,
1288 map (Lilypond_snippet.basename, ly_snippets))
1289 texstr_names = filter (lambda x: x,
1290 map (Lilypond_snippet.basename, texstr_snippets))
1291 png_names = filter (lambda x: x,
1292 map (Lilypond_snippet.basename, png_snippets))
1295 def my_system (cmd):
1296 status = ly.system (cmd,
1297 ignore_error = 1, progress_p = 1)
1300 ly.error ('Process %s exited unsuccessfully.' % cmd)
1304 # the --process=CMD switch is a bad idea
1305 # it is too generic for lilypond-book.
1306 if texstr_names and invokes_lilypond ():
1307 my_system (string.join ([cmd, '--backend texstr',
1308 'snippet-map.ly'] + texstr_names))
1309 for l in texstr_names:
1310 my_system ('latex %s.texstr' % l)
1313 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1315 LATEX_INSPECTION_DOCUMENT = r'''
1319 \typeout{textwidth=\the\textwidth}
1320 \typeout{columnsep=\the\columnsep}
1321 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1325 # Do we need anything else besides `textwidth'?
1326 def get_latex_textwidth (source):
1327 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1328 preamble = source[:m.start (0)]
1329 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1330 # Workaround problems with unusable $TMP on Cygwin:
1331 tempfile.tempdir = ''
1332 tmpfile = tempfile.mktemp('.tex')
1333 logfile = os.path.splitext (tmpfile)[0] + '.log'
1334 open (tmpfile,'w').write (latex_document)
1335 ly.system ('latex %s' % tmpfile)
1336 parameter_string = open (logfile).read()
1341 m = re.search ('columns=([0-9.]*)', parameter_string)
1343 columns = string.atoi (m.group (1))
1346 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1348 columnsep = string.atof (m.group (1))
1351 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1353 textwidth = string.atof (m.group (1))
1355 textwidth = (textwidth - columnsep) / columns
1359 def modify_preamble (chunk):
1360 str = chunk.replacement_text ()
1361 if (re.search (r"\\begin *{document}", str)
1362 and not re.search ("{graphic[sx]", str)):
1363 str = re.sub (r"\\begin{document}",
1364 r"\\usepackage{graphics}" + '\n'
1365 + r"\\begin{document}",
1367 chunk.override_text = str
1379 '.texinfo': TEXINFO,
1385 # TEXINFO: '.texinfo',
1390 class Compile_error:
1393 def write_file_map (lys, name):
1394 snippet_map = open ('snippet-map.ly', 'w')
1395 snippet_map.write ("""
1396 #(define version-seen? #t)
1397 #(ly:add-file-name-alist '(
1400 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1406 snippet_map.write ('))\n')
1408 def do_process_cmd (chunks, input_name):
1409 all_lys = filter (lambda x: is_derived_class (x.__class__,
1413 write_file_map (all_lys, input_name)
1415 filter (lambda x: is_derived_class (x.__class__,
1417 and x.ly_is_outdated (),
1420 filter (lambda x: is_derived_class (x.__class__,
1422 and x.texstr_is_outdated (),
1425 filter (lambda x: is_derived_class (x.__class__,
1427 and x.png_is_outdated (),
1430 ly.progress (_ ("Writing snippets..."))
1431 map (Lilypond_snippet.write_ly, ly_outdated)
1435 ly.progress (_ ("Processing..."))
1437 process_snippets (process_cmd, ly_outdated, texstr_outdated, png_outdated)
1439 ly.progress (_ ("All snippets are up to date..."))
1442 def guess_format (input_filename):
1444 e = os.path.splitext (input_filename)[1]
1445 if e in ext2format.keys ():
1447 format = ext2format[e]
1449 ly.error (_ ("can't determine format for: %s" \
1454 def write_if_updated (file_name, lines):
1456 f = open (file_name)
1458 new_str = string.join (lines, '')
1459 if oldstr == new_str:
1460 ly.progress (_ ("%s is up to date.") % file_name)
1466 ly.progress (_ ("Writing `%s'...") % file_name)
1467 open (file_name, 'w').writelines (lines)
1470 def do_file (input_filename):
1472 if not input_filename or input_filename == '-':
1473 in_handle = sys.stdin
1474 input_fullname = '<stdin>'
1476 if os.path.exists (input_filename):
1477 input_fullname = input_filename
1478 elif format == LATEX and ly.search_exe_path ('kpsewhich'):
1479 # urg python interface to libkpathsea?
1480 input_fullname = ly.read_pipe ('kpsewhich '
1481 + input_filename)[:-1]
1483 input_fullname = find_file (input_filename)
1484 in_handle = open (input_fullname)
1486 if input_filename == '-':
1487 input_base = 'stdin'
1489 input_base = os.path.basename \
1490 (os.path.splitext (input_filename)[0])
1492 # Only default to stdout when filtering.
1493 if output_name == '-' or (not output_name and filter_cmd):
1494 output_filename = '-'
1495 output_file = sys.stdout
1497 # don't complain when output_name is existing
1498 output_filename = input_base + format2ext[format]
1500 if not os.path.isdir (output_name):
1501 os.mkdir (output_name, 0777)
1502 os.chdir (output_name)
1504 if os.path.exists (input_filename) \
1505 and os.path.exists (output_filename) \
1506 and os.path.samefile (output_filename, input_fullname):
1508 _ ("Output would overwrite input file; use --output."))
1512 ly.progress (_ ("Reading %s...") % input_fullname)
1513 source = in_handle.read ()
1516 set_default_options (source)
1519 # FIXME: Containing blocks must be first, see
1520 # find_toplevel_snippets.
1522 'multiline_comment',
1526 'singleline_comment',
1531 ly.progress (_ ("Dissecting..."))
1532 chunks = find_toplevel_snippets (source, snippet_types)
1536 if (c.is_plain () and
1537 re.search (r"\\begin *{document}", c.replacement_text())):
1543 write_if_updated (output_filename,
1544 [c.filter_text () for c in chunks])
1546 do_process_cmd (chunks, input_fullname)
1547 ly.progress (_ ("Compiling %s...") % output_filename)
1549 write_if_updated (output_filename,
1550 [s.replacement_text ()
1553 def process_include (snippet):
1554 os.chdir (original_dir)
1555 name = snippet.substring ('filename')
1556 ly.progress (_ ("Processing include: %s") % name)
1558 return do_file (name)
1560 include_chunks = map (process_include,
1561 filter (lambda x: is_derived_class (x.__class__,
1566 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1568 except Compile_error:
1569 os.chdir (original_dir)
1570 ly.progress (_ ("Removing `%s'") % output_filename)
1575 global format, output_name, psfonts_p, srcltx_p
1576 global filter_cmd, process_cmd, verbose_p
1578 (sh, long) = ly.getopt_args (option_definitions)
1580 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
1581 except getopt.error, s:
1582 sys.stderr.write ('\n')
1583 ly.error (_ ("getopt says: `%s'" % s))
1584 sys.stderr.write ('\n')
1594 elif o == '--filter' or o == '-F':
1597 elif o == '--format' or o == '-f':
1599 if a == 'texi-html' or a == 'texi':
1601 elif o == '--tex-backend ':
1603 elif o == '--help' or o == '-h':
1606 elif o == '--include' or o == '-I':
1607 include_path.append (os.path.join (original_dir,
1608 os.path.abspath (a)))
1609 elif o == '--output' or o == '-o':
1611 elif o == '--process' or o == '-P':
1614 elif o == '--version' or o == '-v':
1615 ly.identify (sys.stdout)
1617 elif o == '--verbose' or o == '-V':
1619 elif o == '--psfonts':
1621 elif o == '--keep-line-breaks':
1623 for s in (OUTPUT, QUOTE, VERBATIM):
1624 output[LATEX][s] = output[LATEX][s].replace("\n"," ")
1625 elif o == '--warranty' or o == '-w':
1632 files = do_options ()
1633 if not files or len (files) > 1:
1639 basename = os.path.splitext (file)[0]
1640 basename = os.path.split (basename)[1]
1642 global process_cmd, format
1644 format = guess_format (files[0])
1647 if format == TEXINFO or format == HTML:
1649 if process_cmd == '':
1650 process_cmd = lilypond_binary \
1651 + ' --formats=%s --backend eps ' % formats
1654 process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1655 for p in include_path])
1657 ly.identify (sys.stderr)
1660 chunks = do_file (file)
1661 if psfonts_p and invokes_lilypond ():
1662 fontextract.verbose = verbose_p
1663 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1667 psfonts_file = basename + '.psfonts'
1669 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1670 fontextract.extract_fonts (psfonts_file,
1671 [x.basename() + '.eps'
1672 for x in snippet_chunks])
1676 except Compile_error:
1679 if format == TEXINFO or format == LATEX:
1681 ly.warning (_ ("option --psfonts not used"))
1682 ly.warning (_ ("processing with dvips will have no fonts"))
1684 psfonts_file = os.path.join (output_name, basename + '.psfonts')
1685 output = os.path.join (output_name, basename + '.dvi' )
1688 ly.progress (_ ("DVIPS usage:"))
1690 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1693 if __name__ == '__main__':