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
44 for d in ['@lilypond_datadir@',
46 sys.path.insert (0, os.path.join (d, 'python'))
48 # dynamic relocation, for GUB binaries.
49 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
51 os.environ['PATH'] = bindir + os.pathsep + os.environ['PATH']
52 for p in ['share', 'lib']:
53 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
54 sys.path.insert (0, datadir)
63 program_version = '@TOPLEVEL_VERSION@'
64 program_name = os.path.basename (sys.argv[0])
66 original_dir = os.getcwd ()
70 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
74 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
75 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
76 lilypond-book --process='lilypond -I include' BOOK
79 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
80 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
83 ################################################################
85 if global_options.verbose:
86 raise _ ('Exiting (%d)...') % i
91 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
97 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
100 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
102 def ps_page_count (ps_name):
103 header = open (ps_name).read (1024)
104 m = re.search ('\n%%Pages: ([0-9]+)', header)
106 return string.atoi (m.group (1))
111 sys.stdout.write ('''
118 ''' % ( _('Copyright (c) %s by') % '2001--2006',
120 _('Distributed under terms of the GNU General Public License.'),
121 _('It comes with NO WARRANTY.')))
124 def get_option_parser ():
125 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
126 version="@TOPLEVEL_VERSION@",
127 description=help_summary)
129 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
132 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
134 p.add_option ('-f', '--format',
135 help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
138 p.add_option ("-I", '--include', help=_('add DIR to include path'),
140 action='append', dest='include_path',
141 default=[os.path.abspath (os.getcwd ())])
143 p.add_option ("-o", '--output', help=_('write output to DIR'),
145 action='store', dest='output_name',
147 p.add_option ('-P', '--process', metavar=_("COMMAND"),
148 help = _ ("process ly_files using COMMAND FILE..."),
150 dest='process_cmd', default='lilypond -b eps')
152 p.add_option ('--pdf',
155 help="Create PDF files for use with PDFTeX",
158 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
159 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
160 '''must use this with dvips -h INPUT.psfonts'''),
162 p.add_option ('-V', '--verbose', help=_("be verbose"),
167 p.add_option ('-w', '--warranty',
168 help=_("show warranty and copyright"),
172 p.add_option_group ('bugs',
173 description='''Report bugs via http://post.gmane.org/post.php'''
174 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
178 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
180 # Only use installed binary when we are installed too.
181 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
182 lilypond_binary = 'lilypond'
184 global_options = None
187 default_ly_options = { 'alt': "[image of music]" }
190 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
194 EXAMPLEINDENT = 'exampleindent'
196 FRAGMENT = 'fragment'
201 LINE_WIDTH = 'line-width'
202 NOFRAGMENT = 'nofragment'
203 NOINDENT = 'noindent'
208 OUTPUTIMAGE = 'outputimage'
211 PREAMBLE = 'preamble'
212 PRINTFILENAME = 'printfilename'
214 RAGGED_RIGHT = 'ragged-right'
215 RELATIVE = 'relative'
216 STAFFSIZE = 'staffsize'
219 VERBATIM = 'verbatim'
220 FONTLOAD = 'fontload'
221 FILENAME = 'filename'
225 # NOTIME has no opposite so it isn't part of this dictionary.
226 # NOQUOTE is used internally only.
228 NOFRAGMENT: FRAGMENT,
233 # Recognize special sequences in the input.
235 # (?P<name>regex) -- Assign result of REGEX to NAME.
236 # *? -- Match non-greedily.
237 # (?m) -- Multiline regex: Make ^ and $ match at each line.
238 # (?s) -- Make the dot match all characters including newline.
239 # (?x) -- Ignore whitespace in patterns.
251 (\s*(?P<options>.*?)\s*:)?\s*
259 \s*(?P<options>.*?)\s*
268 \s*(?P<options>.*?)\s*
270 \s*(?P<filename>.*?)\s*
277 (?P<code><!--\s.*?!-->)
280 'singleline_comment':
286 (?P<code><pre>.*?</pre>))''',
292 (?P<code><pre>\s.*?</pre>\s))''',
311 \s*(?P<options>.*?)\s*
322 \s*(?P<options>.*?)\s*
326 \\end\s*{lilypond})''',
334 \s*(?P<options>.*?)\s*
342 'singleline_comment':
365 \\end\s*{verbatim}))''',
374 (?P<filename>\S+))''',
378 ^[^\n]*?(?!@c\s+)[^\n]*?
382 \s*(?P<options>.*?)\s*
392 \s*(?P<options>.*?)\s*
395 ^@end\s+lilypond)\s''',
402 \s*(?P<options>.*?)\s*
413 @end\s+ignore))\s''',
415 'singleline_comment':
420 @c([ \t][^\n]*|)\n))''',
422 # Don't do this: It interferes with @code{@{}.
423 # 'verb': r'''(?P<code>@code{.*?})''',
431 @end\s+example\s))''',
440 'intertext': r',?\s*intertext=\".*?\"',
445 'intertext': r',?\s*intertext=\".*?\"',
446 'option_sep': '\s*,\s*',
450 'intertext': r',?\s*intertext=\".*?\"',
451 'option_sep': '\s*,\s*',
455 # Options without a pattern in ly_options.
472 RELATIVE: r'''\relative c%(relative_quotes)s''',
477 INDENT: r'''indent = %(indent)s''',
479 LINE_WIDTH: r'''line-width = %(line-width)s''',
481 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
483 RAGGED_RIGHT: r'''ragged-right = ##t''',
485 PACKED: r'''packed = ##t''',
497 \remove Time_signature_engraver
503 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
510 FILTER: r'''<lilypond %(options)s>
520 <a href="%(base)s.ly">''',
523 <img align="center" valign="center"
524 border="0" src="%(image)s" alt="%(alt)s">''',
526 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
528 QUOTE: r'''<blockquote>
541 \ifx\preLilyPondExample \undefined%%
544 \preLilyPondExample%%
546 \def\lilypondbook{}%%
547 \input %(base)s-systems.tex%%
548 \ifx\postLilyPondExample \undefined%%
551 \postLilyPondExample%%
555 PRINTFILENAME: '''\\texttt{%(filename)s}
558 QUOTE: r'''\begin{quotation}%(str)s
561 VERBATIM: r'''\noindent
562 \begin{verbatim}%(verb)s\end{verbatim}''',
564 FILTER: r'''\begin{lilypond}[%(options)s]
571 FILTER: r'''@lilypond[%(options)s]
577 @include %(base)s-systems.texi
581 OUTPUTIMAGE: r'''@noindent
583 @image{%(base)s,,,%(alt)s,%(ext)s}
587 <a href="%(base)s.ly">
588 <img align="center" valign="center"
589 border="0" src="%(image)s" alt="%(alt)s">
597 <a href="%(base)s.ly">
605 QUOTE: r'''@quotation
606 %(str)s@end quotation
613 VERBATIM: r'''@exampleindent 0
615 %(verb)s@end verbatim
621 # Maintain line numbers.
626 for f in [HTML, LATEX]:
627 for s in (QUOTE, VERBATIM):
628 output[f][s] = output[f][s].replace("\n"," ")
631 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
632 %%%% Options: [%(option_string)s]
633 \\include "lilypond-book-preamble.ly"
641 %% ****************************************************************
642 %% Start cut-&-pastable-section
643 %% ****************************************************************
646 #(define dump-extents #t)
647 %(font_dump_setting)s
661 %% ****************************************************************
662 %% ly snippet contents follows:
663 %% ****************************************************************
667 %% ****************************************************************
669 %% ****************************************************************
676 %% ****************************************************************
678 %% ****************************************************************
682 %% ****************************************************************
684 %% ****************************************************************
687 texinfo_line_widths = {
688 '@afourpaper': '160\\mm',
689 '@afourwide': '6.5\\in',
690 '@afourlatex': '150\\mm',
691 '@smallbook': '5\\in',
692 '@letterpaper': '6\\in',
695 def classic_lilypond_book_compatibility (key, value):
696 if key == 'singleline' and value == None:
697 return (RAGGED_RIGHT, None)
699 m = re.search ('relative\s*([-0-9])', key)
701 return ('relative', m.group (1))
703 m = re.match ('([0-9]+)pt', key)
705 return ('staffsize', m.group (1))
707 if key == 'indent' or key == 'line-width':
708 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
710 f = float (m.group (1))
711 return (key, '%f\\%s' % (f, m.group (2)))
715 def find_file (name):
716 for i in global_options.include_path:
717 full = os.path.join (i, name)
718 if os.path.exists (full):
721 error (_ ("file not found: %s") % name + '\n')
725 def verbatim_html (s):
726 return re.sub ('>', '>',
728 re.sub ('&', '&', s)))
730 def split_options (option_string):
732 if global_options.format == HTML:
733 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
734 for i in range(len(options)):
735 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
738 return re.split (format_res[global_options.format]['option_sep'],
742 def set_default_options (source):
743 global default_ly_options
744 if not default_ly_options.has_key (LINE_WIDTH):
745 if global_options.format == LATEX:
746 textwidth = get_latex_textwidth (source)
747 default_ly_options[LINE_WIDTH] = \
748 '''%.0f\\pt''' % textwidth
749 elif global_options.format == TEXINFO:
750 for (k, v) in texinfo_line_widths.items ():
751 # FIXME: @layout is usually not in
754 # \input texinfo @c -*-texinfo-*-
756 # Bluntly search first K items of
758 # s = chunks[0].replacement_text ()
759 if re.search (k, source[:1024]):
760 default_ly_options[LINE_WIDTH] = v
764 def replacement_text (self):
767 def filter_text (self):
768 return self.replacement_text ()
770 def ly_is_outdated (self):
773 def png_is_outdated (self):
779 class Substring (Chunk):
780 def __init__ (self, source, start, end, line_number):
784 self.line_number = line_number
785 self.override_text = None
790 def replacement_text (self):
791 if self.override_text:
792 return self.override_text
794 return self.source[self.start:self.end]
796 class Snippet (Chunk):
797 def __init__ (self, type, match, format, line_number):
801 self.option_dict = {}
803 self.line_number = line_number
805 def replacement_text (self):
806 return self.match.group ('match')
808 def substring (self, s):
809 return self.match.group (s)
812 return `self.__class__` + ' type = ' + self.type
814 class Include_snippet (Snippet):
815 def processed_filename (self):
816 f = self.substring ('filename')
817 return os.path.splitext (f)[0] + format2ext[global_options.format]
819 def replacement_text (self):
820 s = self.match.group ('match')
821 f = self.substring ('filename')
823 return re.sub (f, self.processed_filename (), s)
825 class Lilypond_snippet (Snippet):
826 def __init__ (self, type, match, format, line_number):
827 Snippet.__init__ (self, type, match, format, line_number)
828 os = match.group ('options')
829 self.do_options (os, self.type)
832 contents = self.substring ('code')
833 return ('\\sourcefileline %d\n%s'
834 % (self.line_number - 1, contents))
839 return self.compose_ly (s)
842 def do_options (self, option_string, type):
843 self.option_dict = {}
845 options = split_options (option_string)
849 (key, value) = re.split ('\s*=\s*', i)
850 self.option_dict[key] = value
852 if i in no_options.keys ():
853 if no_options[i] in self.option_dict.keys ():
854 del self.option_dict[no_options[i]]
856 self.option_dict[i] = None
858 has_line_width = self.option_dict.has_key (LINE_WIDTH)
859 no_line_width_value = 0
861 # If LINE_WIDTH is used without parameter, set it to default.
862 if has_line_width and self.option_dict[LINE_WIDTH] == None:
863 no_line_width_value = 1
864 del self.option_dict[LINE_WIDTH]
866 for i in default_ly_options.keys ():
867 if i not in self.option_dict.keys ():
868 self.option_dict[i] = default_ly_options[i]
870 if not has_line_width:
871 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
872 self.option_dict[RAGGED_RIGHT] = None
874 if type == 'lilypond':
875 if LINE_WIDTH in self.option_dict.keys ():
876 del self.option_dict[LINE_WIDTH]
878 if RAGGED_RIGHT in self.option_dict.keys ():
879 if LINE_WIDTH in self.option_dict.keys ():
880 del self.option_dict[LINE_WIDTH]
882 if QUOTE in self.option_dict.keys () or type == 'lilypond':
883 if LINE_WIDTH in self.option_dict.keys ():
884 del self.option_dict[LINE_WIDTH]
886 if not INDENT in self.option_dict.keys ():
887 self.option_dict[INDENT] = '0\\mm'
889 # The QUOTE pattern from ly_options only emits the `line-width'
891 if has_line_width and QUOTE in self.option_dict.keys ():
892 if no_line_width_value:
893 del self.option_dict[LINE_WIDTH]
895 del self.option_dict[QUOTE]
897 def compose_ly (self, code):
898 if FRAGMENT in self.option_dict.keys ():
906 # The original concept of the `exampleindent' option is broken.
907 # It is not possible to get a sane value for @exampleindent at all
908 # without processing the document itself. Saying
916 # causes ugly results with the DVI backend of texinfo since the
917 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
918 # value). Executing the above code changes the environment
919 # indentation to an unknown value because we don't know the amount
920 # of 1em in advance since it is font-dependent. Modifying
921 # @exampleindent in the middle of a document is simply not
922 # supported within texinfo.
924 # As a consequence, the only function of @exampleindent is now to
925 # specify the amount of indentation for the `quote' option.
927 # To set @exampleindent locally to zero, we use the @format
928 # environment for non-quoted snippets.
929 override[EXAMPLEINDENT] = r'0.4\in'
930 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
931 override.update (default_ly_options)
934 for (key, value) in self.option_dict.items ():
936 option_list.append (key)
938 option_list.append (key + '=' + value)
939 option_string = string.join (option_list, ',')
942 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
943 for a in compose_types:
946 for (key, value) in self.option_dict.items ():
948 classic_lilypond_book_compatibility (key, value)
952 (_ ("deprecated ly-option used: %s=%s" \
955 (_ ("compatibility mode translation: %s=%s" \
959 (_ ("deprecated ly-option used: %s" \
962 (_ ("compatibility mode translation: %s" \
965 (key, value) = (c_key, c_value)
968 override[key] = value
970 if not override.has_key (key):
974 for type in compose_types:
975 if ly_options[type].has_key (key):
976 compose_dict[type].append (ly_options[type][key])
980 if not found and key not in simple_options:
981 warning (_ ("ignoring unknown ly option: %s") % key)
984 if RELATIVE in override.keys () and override[RELATIVE]:
985 relative = int (override[RELATIVE])
991 relative_quotes += ',' * (- relative)
993 relative_quotes += "'" * relative
995 paper_string = string.join (compose_dict[PAPER],
997 layout_string = string.join (compose_dict[LAYOUT],
999 notes_string = string.join (compose_dict[NOTES],
1001 preamble_string = string.join (compose_dict[PREAMBLE],
1004 font_dump_setting = ''
1005 if FONTLOAD in self.option_dict:
1006 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1008 d = globals().copy()
1010 return (PREAMBLE_LY + body) % d
1013 def get_hash (self):
1015 self.hash = abs (hash (self.full_ly ()))
1018 def basename (self):
1019 if FILENAME in self.option_dict:
1020 return self.option_dict[FILENAME]
1021 if global_options.use_hash:
1022 return 'lily-%d' % self.get_hash ()
1025 def write_ly (self):
1026 outf = open (self.basename () + '.ly', 'w')
1027 outf.write (self.full_ly ())
1029 open (self.basename () + '.txt', 'w').write ('image of music')
1031 def ly_is_outdated (self):
1032 base = self.basename ()
1034 tex_file = '%s.tex' % base
1035 eps_file = '%s.eps' % base
1036 system_file = '%s-systems.tex' % base
1037 ly_file = '%s.ly' % base
1038 ok = os.path.exists (ly_file) \
1039 and os.path.exists (system_file)\
1040 and os.stat (system_file)[stat.ST_SIZE] \
1041 and re.match ('% eof', open (system_file).readlines ()[-1])
1042 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1043 ok = (self.full_ly () == open (ly_file).read ())
1045 # TODO: Do something smart with target formats
1046 # (ps, png) and m/ctimes.
1050 def png_is_outdated (self):
1051 base = self.basename ()
1052 ok = not self.ly_is_outdated ()
1053 if global_options.format in (HTML, TEXINFO):
1054 ok = ok and os.path.exists (base + '.eps')
1058 page_count = ps_page_count (base + '.eps')
1061 ok = ok and os.path.exists (base + '.png')
1063 elif page_count > 1:
1064 for a in range (1, page_count + 1):
1065 ok = ok and os.path.exists (base + '-page%d.png' % a)
1069 def texstr_is_outdated (self):
1073 base = self.basename ()
1074 ok = self.ly_is_outdated ()
1075 ok = ok and (os.path.exists (base + '.texstr'))
1078 def filter_text (self):
1079 code = self.substring ('code')
1080 s = run_filter (code)
1083 'options': self.match.group ('options')
1086 return output[self.format][FILTER] % d
1088 def replacement_text (self):
1089 func = Lilypond_snippet.__dict__['output_' + self.format]
1092 def get_images (self):
1093 base = self.basename ()
1095 single = '%(base)s.png' % vars ()
1096 multiple = '%(base)s-page1.png' % vars ()
1098 if os.path.exists (multiple) \
1099 and (not os.path.exists (single) \
1100 or (os.stat (multiple)[stat.ST_MTIME] \
1101 > os.stat (single)[stat.ST_MTIME])):
1102 count = ps_page_count ('%(base)s.eps' % vars ())
1103 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1104 images = tuple (images)
1107 def output_html (self):
1109 base = self.basename ()
1110 if global_options.format == HTML:
1111 str += self.output_print_filename (HTML)
1112 if VERBATIM in self.option_dict:
1113 verb = verbatim_html (self.substring ('code'))
1114 str += output[HTML][VERBATIM] % vars ()
1115 if QUOTE in self.option_dict:
1116 str = output[HTML][QUOTE] % vars ()
1118 str += output[HTML][BEFORE] % vars ()
1119 for image in self.get_images ():
1120 (base, ext) = os.path.splitext (image)
1121 alt = self.option_dict[ALT]
1122 str += output[HTML][OUTPUT] % vars ()
1123 str += output[HTML][AFTER] % vars ()
1126 def output_info (self):
1128 for image in self.get_images ():
1129 (base, ext) = os.path.splitext (image)
1131 # URG, makeinfo implicitly prepends dot to extension.
1132 # Specifying no extension is most robust.
1134 alt = self.option_dict[ALT]
1135 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1137 base = self.basename ()
1138 str += output[global_options.format][OUTPUT] % vars ()
1141 def output_latex (self):
1143 base = self.basename ()
1144 if global_options.format == LATEX:
1145 str += self.output_print_filename (LATEX)
1146 if VERBATIM in self.option_dict:
1147 verb = self.substring ('code')
1148 str += (output[LATEX][VERBATIM] % vars ())
1150 str += (output[LATEX][OUTPUT] % vars ())
1152 ## todo: maintain breaks
1154 breaks = self.ly ().count ("\n")
1155 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1157 if QUOTE in self.option_dict:
1158 str = output[LATEX][QUOTE] % vars ()
1161 def output_print_filename (self, format):
1163 if PRINTFILENAME in self.option_dict:
1164 base = self.basename ()
1165 filename = self.substring ('filename')
1166 str = output[global_options.format][PRINTFILENAME] % vars ()
1170 def output_texinfo (self):
1172 if self.output_print_filename (TEXINFO):
1174 + self.output_print_filename (HTML)
1177 + self.output_print_filename (LATEX)
1179 base = self.basename ()
1180 if TEXIDOC in self.option_dict:
1181 texidoc = base + '.texidoc'
1182 if os.path.exists (texidoc):
1183 str += '@include %(texidoc)s\n\n' % vars ()
1185 if VERBATIM in self.option_dict:
1186 verb = self.substring ('code')
1187 str += (output[TEXINFO][VERBATIM] % vars ())
1188 if not QUOTE in self.option_dict:
1189 str = output[TEXINFO][NOQUOTE] % vars ()
1191 str += self.output_info ()
1193 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1194 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1195 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1197 if QUOTE in self.option_dict:
1198 str = output[TEXINFO][QUOTE] % vars ()
1200 # need par after image
1205 class Lilypond_file_snippet (Lilypond_snippet):
1207 name = self.substring ('filename')
1208 contents = open (find_file (name)).read ()
1210 ## strip version string to make automated regtest comparisons
1211 ## across versions easier.
1212 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1214 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1217 snippet_type_to_class = {
1218 'lilypond_file': Lilypond_file_snippet,
1219 'lilypond_block': Lilypond_snippet,
1220 'lilypond': Lilypond_snippet,
1221 'include': Include_snippet,
1224 def find_linestarts (s):
1229 i = s.find ('\n', start)
1237 nls.append (len (s))
1240 def find_toplevel_snippets (s, types):
1243 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1247 found = dict ([(t, None) for t in types])
1249 line_starts = find_linestarts (s)
1251 # We want to search for multiple regexes, without searching
1252 # the string multiple times for one regex.
1253 # Hence, we use earlier results to limit the string portion
1255 # Since every part of the string is traversed at most once for
1256 # every type of snippet, this is linear.
1262 if not found[type] or found[type][0] < index:
1265 m = res[type].search (s[index:endex])
1270 if snippet_type_to_class.has_key (type):
1271 cl = snippet_type_to_class[type]
1274 start = index + m.start ('match')
1275 line_number = line_start_idx
1276 while (line_starts[line_number] < start):
1280 snip = cl (type, m, global_options.format, line_number)
1282 found[type] = (start, snip)
1286 or found[type][0] < found[first][0]):
1291 # Limiting the search space is a cute
1292 # idea, but this *requires* to search
1293 # for possible containing blocks
1294 # first, at least as long as we do not
1295 # search for the start of blocks, but
1296 # always/directly for the entire
1297 # @block ... @end block.
1299 endex = found[first][0]
1302 snippets.append (Substring (s, index, len (s), line_start_idx))
1305 while (start > line_starts[line_start_idx+1]):
1308 (start, snip) = found[first]
1309 snippets.append (Substring (s, index, start, line_start_idx + 1))
1310 snippets.append (snip)
1312 index = start + len (snip.match.group ('match'))
1316 def filter_pipe (input, cmd):
1317 if global_options.verbose:
1318 progress (_ ("Opening filter `%s'") % cmd)
1320 (stdin, stdout, stderr) = os.popen3 (cmd)
1322 status = stdin.close ()
1326 output = stdout.read ()
1327 status = stdout.close ()
1328 error = stderr.read ()
1332 signal = 0x0f & status
1333 if status or (not output and error):
1334 exit_status = status >> 8
1335 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1336 error (_ ("The error log is as follows:"))
1337 sys.stderr.write (error)
1338 sys.stderr.write (stderr.read ())
1341 if global_options.verbose:
1347 return filter_pipe (s, global_options.filter_cmd)
1349 def is_derived_class (cl, baseclass):
1352 for b in cl.__bases__:
1353 if is_derived_class (b, baseclass):
1357 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1358 ly_names = filter (lambda x: x,
1359 map (Lilypond_snippet.basename, ly_snippets))
1360 texstr_names = filter (lambda x: x,
1361 map (Lilypond_snippet.basename, texstr_snippets))
1363 png_names = filter (lambda x: x,
1364 map (Lilypond_snippet.basename, png_snippets))
1367 def my_system (cmd):
1368 status = ly.system (cmd,
1369 be_verbose=global_options.verbose,
1372 if global_options.format in (HTML, TEXINFO):
1373 cmd += ' --formats=png '
1376 # the --process=CMD switch is a bad idea
1377 # it is too generic for lilypond-book.
1379 my_system (string.join ([cmd, '--backend texstr',
1380 'snippet-map.ly'] + texstr_names))
1381 for l in texstr_names:
1382 my_system ('latex %s.texstr' % l)
1385 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1388 my_system (string.join ([cmd, 'snippet-names']))
1391 LATEX_INSPECTION_DOCUMENT = r'''
1395 \typeout{textwidth=\the\textwidth}
1396 \typeout{columnsep=\the\columnsep}
1397 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1401 # Do we need anything else besides `textwidth'?
1402 def get_latex_textwidth (source):
1403 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1405 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1407 ## what's a sensible default?
1410 preamble = source[:m.start (0)]
1411 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1413 (handle, tmpfile) = tempfile.mkstemp('.tex')
1414 logfile = os.path.splitext (tmpfile)[0] + '.log'
1415 logfile = os.path.split (logfile)[1]
1417 tmp_handle = os.fdopen (handle,'w')
1418 tmp_handle.write (latex_document)
1421 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1422 parameter_string = open (logfile).read()
1428 m = re.search ('columns=([0-9.]*)', parameter_string)
1430 columns = int (m.group (1))
1433 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1435 columnsep = float (m.group (1))
1438 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1440 textwidth = float (m.group (1))
1442 textwidth = (textwidth - columnsep) / columns
1446 def modify_preamble (chunk):
1447 str = chunk.replacement_text ()
1448 if (re.search (r"\\begin *{document}", str)
1449 and not re.search ("{graphic[sx]", str)):
1450 str = re.sub (r"\\begin{document}",
1451 r"\\usepackage{graphics}" + '\n'
1452 + r"\\begin{document}",
1454 chunk.override_text = str
1466 '.texinfo': TEXINFO,
1472 # TEXINFO: '.texinfo',
1477 class Compile_error:
1480 def write_file_map (lys, name):
1481 snippet_map = open ('snippet-map.ly', 'w')
1482 snippet_map.write ("""
1483 #(define version-seen #t)
1484 #(ly:add-file-name-alist '(
1487 snippet_map.write ('("%s.ly" . "%s")\n'
1491 snippet_map.write ('))\n')
1493 def do_process_cmd (chunks, input_name):
1494 all_lys = filter (lambda x: is_derived_class (x.__class__,
1498 write_file_map (all_lys, input_name)
1499 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1501 and x.ly_is_outdated (), chunks)
1502 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1504 and x.texstr_is_outdated (),
1506 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1508 and x.png_is_outdated (),
1511 outdated = png_outdated + texstr_outdated + ly_outdated
1513 progress (_ ("Writing snippets..."))
1514 map (Lilypond_snippet.write_ly, ly_outdated)
1518 progress (_ ("Processing..."))
1520 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1522 progress (_ ("All snippets are up to date..."))
1525 def guess_format (input_filename):
1527 e = os.path.splitext (input_filename)[1]
1528 if e in ext2format.keys ():
1530 format = ext2format[e]
1532 error (_ ("can't determine format for: %s" \
1537 def write_if_updated (file_name, lines):
1539 f = open (file_name)
1541 new_str = string.join (lines, '')
1542 if oldstr == new_str:
1543 progress (_ ("%s is up to date.") % file_name)
1549 progress (_ ("Writing `%s'...") % file_name)
1550 open (file_name, 'w').writelines (lines)
1553 def note_input_file (name, inputs=[]):
1554 ## hack: inputs is mutable!
1555 inputs.append (name)
1558 def samefile (f1, f2):
1560 return os.path.samefile (f1, f2)
1561 except AttributeError: # Windoze
1562 f1 = re.sub ("//*", "/", f1)
1563 f2 = re.sub ("//*", "/", f2)
1566 def do_file (input_filename):
1568 if not input_filename or input_filename == '-':
1569 in_handle = sys.stdin
1570 input_fullname = '<stdin>'
1572 if os.path.exists (input_filename):
1573 input_fullname = input_filename
1574 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1575 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1577 input_fullname = find_file (input_filename)
1579 note_input_file (input_fullname)
1580 in_handle = open (input_fullname)
1582 if input_filename == '-':
1583 input_base = 'stdin'
1585 input_base = os.path.basename \
1586 (os.path.splitext (input_filename)[0])
1588 # Only default to stdout when filtering.
1589 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1590 output_filename = '-'
1591 output_file = sys.stdout
1593 # don't complain when global_options.output_name is existing
1594 output_filename = input_base + format2ext[global_options.format]
1595 if global_options.output_name:
1596 if not os.path.isdir (global_options.output_name):
1597 os.mkdir (global_options.output_name, 0777)
1598 os.chdir (global_options.output_name)
1600 if (os.path.exists (input_filename)
1601 and os.path.exists (output_filename)
1602 and samefile (output_filename, input_fullname)):
1604 _ ("Output would overwrite input file; use --output."))
1608 progress (_ ("Reading %s...") % input_fullname)
1609 source = in_handle.read ()
1612 set_default_options (source)
1615 # FIXME: Containing blocks must be first, see
1616 # find_toplevel_snippets.
1618 'multiline_comment',
1622 'singleline_comment',
1627 progress (_ ("Dissecting..."))
1628 chunks = find_toplevel_snippets (source, snippet_types)
1630 if global_options.format == LATEX:
1632 if (c.is_plain () and
1633 re.search (r"\\begin *{document}", c.replacement_text())):
1638 if global_options.filter_cmd:
1639 write_if_updated (output_filename,
1640 [c.filter_text () for c in chunks])
1641 elif global_options.process_cmd:
1642 do_process_cmd (chunks, input_fullname)
1643 progress (_ ("Compiling %s...") % output_filename)
1645 write_if_updated (output_filename,
1646 [s.replacement_text ()
1649 def process_include (snippet):
1650 os.chdir (original_dir)
1651 name = snippet.substring ('filename')
1652 progress (_ ("Processing include: %s") % name)
1654 return do_file (name)
1656 include_chunks = map (process_include,
1657 filter (lambda x: is_derived_class (x.__class__,
1662 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1664 except Compile_error:
1665 os.chdir (original_dir)
1666 progress (_ ("Removing `%s'") % output_filename)
1672 global global_options
1674 opt_parser = get_option_parser()
1675 (global_options, args) = opt_parser.parse_args ()
1677 if global_options.format in ('texi-html', 'texi'):
1678 global_options.format = TEXINFO
1679 global_options.use_hash = True
1681 global_options.include_path = map (os.path.abspath, global_options.include_path)
1683 if global_options.warranty:
1686 if not args or len (args) > 1:
1687 opt_parser.print_help ()
1693 files = do_options ()
1697 basename = os.path.splitext (file)[0]
1698 basename = os.path.split (basename)[1]
1700 if not global_options.format:
1701 global_options.format = guess_format (files[0])
1704 if global_options.format in (TEXINFO, HTML):
1708 if global_options.process_cmd == '':
1709 global_options.process_cmd = (lilypond_binary
1710 + ' --formats=%s --backend eps ' % formats)
1712 if global_options.process_cmd:
1713 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1714 for p in global_options.include_path])
1716 if global_options.format in (TEXINFO, LATEX):
1717 ## prevent PDF from being switched on by default.
1718 global_options.process_cmd += ' --formats=eps '
1720 if (global_options.format in (TEXINFO, LATEX)
1721 and global_options.create_pdf):
1722 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1726 if global_options.verbose:
1727 global_options.process_cmd += " --verbose "
1729 global_options.process_cmd += " -dread-file-list -dpad-eps-boxes "
1734 chunks = do_file (file)
1735 if global_options.psfonts:
1736 fontextract.verbose = global_options.verbose
1737 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1741 psfonts_file = basename + '.psfonts'
1742 if not global_options.verbose:
1743 progress (_ ("Writing fonts to %s...") % psfonts_file)
1744 fontextract.extract_fonts (psfonts_file,
1745 [x.basename() + '.eps'
1746 for x in snippet_chunks])
1747 if not global_options.verbose:
1750 except Compile_error:
1753 if global_options.format in (TEXINFO, LATEX):
1754 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1755 output = os.path.join (global_options.output_name, basename + '.dvi' )
1757 if not global_options.psfonts and not global_options.create_pdf:
1758 warning (_ ("option --psfonts not used"))
1759 warning (_ ("processing with dvips will have no fonts"))
1762 progress (_ ("DVIPS usage:"))
1764 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1767 inputs = note_input_file ('')
1770 base_file_name = os.path.splitext (os.path.basename (file))[0]
1771 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1772 final_output_file = os.path.join (global_options.output_name,
1774 + '.%s' % global_options.format)
1776 os.chdir (original_dir)
1777 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1779 if __name__ == '__main__':