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
39 # Users of python modules should include this snippet
40 # and customize variables below.
42 # We'll suffer this path initialization stuff as long as we don't install
43 # our python packages in <prefix>/lib/pythonX.Y
45 # If set, LILYPONDPREFIX must take prevalence.
46 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
52 datadir = '@local_lilypond_datadir@'
53 if not os.path.isdir (datadir):
54 datadir = '@lilypond_datadir@'
56 sys.path.insert (0, os.path.join (datadir, 'python'))
58 if os.environ.has_key ('LILYPONDPREFIX'):
59 datadir = os.environ['LILYPONDPREFIX']
60 while datadir[-1] == os.sep:
63 datadir = os.path.join (datadir, "share/lilypond/current/")
64 sys.path.insert (0, os.path.join (datadir, 'python'))
66 # dynamic relocation, for GUB binaries.
67 bindir = os.path.split (sys.argv[0])[0]
70 for prefix_component in ['share', 'lib']:
71 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
72 sys.path.insert (0, datadir)
81 program_version = '@TOPLEVEL_VERSION@'
82 program_name = os.path.basename (sys.argv[0])
84 original_dir = os.getcwd ()
88 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
92 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
93 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
94 lilypond-book --process='lilypond -I include' BOOK
97 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
98 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
101 ################################################################
103 if global_options.verbose:
104 raise _ ('Exiting (%d)...') % i
109 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
115 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
118 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
120 def ps_page_count (ps_name):
121 header = open (ps_name).read (1024)
122 m = re.search ('\n%%Pages: ([0-9]+)', header)
124 return string.atoi (m.group (1))
129 sys.stdout.write ('''
136 ''' % ( _('Copyright (c) %s by') % '2001--2006',
138 _('Distributed under terms of the GNU General Public License.'),
139 _('It comes with NO WARRANTY.')))
142 def get_option_parser ():
143 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
144 version="@TOPLEVEL_VERSION@",
145 description=help_summary)
147 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
150 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
152 p.add_option ('-f', '--format',
153 help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
155 p.add_option ("-I", '--include', help=_('add DIR to include path'),
157 action='append', dest='include_path',
158 default=[os.path.abspath (os.getcwd ())])
160 p.add_option ("-o", '--output', help=_('write output to DIR'),
162 action='store', dest='output_name',
164 p.add_option ('-P', '--process', metavar=_("COMMAND"),
165 help = _ ("process ly_files using COMMAND FILE..."),
167 dest='process_cmd', default='lilypond -b eps')
169 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
170 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
171 '''must use this with dvips -h INPUT.psfonts'''),
173 p.add_option ('-V', '--verbose', help=_("be verbose"),
178 p.add_option ('-w', '--warranty',
179 help=_("show warranty and copyright"),
183 p.add_option_group ('bugs',
184 description='''Report bugs via http://post.gmane.org/post.php'''
185 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
189 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
191 # Only use installed binary when we are installed too.
192 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
193 lilypond_binary = 'lilypond'
195 global_options = None
198 default_ly_options = { 'alt': "[image of music]" }
201 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
205 EXAMPLEINDENT = 'exampleindent'
207 FRAGMENT = 'fragment'
212 LINE_WIDTH = 'line-width'
213 NOFRAGMENT = 'nofragment'
214 NOINDENT = 'noindent'
219 OUTPUTIMAGE = 'outputimage'
222 PREAMBLE = 'preamble'
223 PRINTFILENAME = 'printfilename'
225 RAGGED_RIGHT = 'ragged-right'
226 RELATIVE = 'relative'
227 STAFFSIZE = 'staffsize'
230 VERBATIM = 'verbatim'
231 FONTLOAD = 'fontload'
232 FILENAME = 'filename'
236 # NOTIME has no opposite so it isn't part of this dictionary.
237 # NOQUOTE is used internally only.
239 NOFRAGMENT: FRAGMENT,
244 # Recognize special sequences in the input.
246 # (?P<name>regex) -- Assign result of REGEX to NAME.
247 # *? -- Match non-greedily.
248 # (?m) -- Multiline regex: Make ^ and $ match at each line.
249 # (?s) -- Make the dot match all characters including newline.
250 # (?x) -- Ignore whitespace in patterns.
262 (\s*(?P<options>.*?)\s*:)?\s*
270 \s*(?P<options>.*?)\s*
279 \s*(?P<options>.*?)\s*
281 \s*(?P<filename>.*?)\s*
288 (?P<code><!--\s.*?!-->)
291 'singleline_comment':
297 (?P<code><pre>.*?</pre>))''',
303 (?P<code><pre>\s.*?</pre>\s))''',
322 \s*(?P<options>.*?)\s*
333 \s*(?P<options>.*?)\s*
337 \\end\s*{lilypond})''',
345 \s*(?P<options>.*?)\s*
353 'singleline_comment':
376 \\end\s*{verbatim}))''',
385 (?P<filename>\S+))''',
389 ^[^\n]*?(?!@c\s+)[^\n]*?
393 \s*(?P<options>.*?)\s*
403 \s*(?P<options>.*?)\s*
406 ^@end\s+lilypond)\s''',
413 \s*(?P<options>.*?)\s*
424 @end\s+ignore))\s''',
426 'singleline_comment':
431 @c([ \t][^\n]*|)\n))''',
433 # Don't do this: It interferes with @code{@{}.
434 # 'verb': r'''(?P<code>@code{.*?})''',
442 @end\s+example\s))''',
451 'intertext': r',?\s*intertext=\".*?\"',
456 'intertext': r',?\s*intertext=\".*?\"',
457 'option_sep': '\s*,\s*',
461 'intertext': r',?\s*intertext=\".*?\"',
462 'option_sep': '\s*,\s*',
466 # Options without a pattern in ly_options.
483 RELATIVE: r'''\relative c%(relative_quotes)s''',
488 INDENT: r'''indent = %(indent)s''',
490 LINE_WIDTH: r'''line-width = %(line-width)s''',
492 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
494 RAGGED_RIGHT: r'''ragged-right = ##t''',
496 PACKED: r'''packed = ##t''',
508 \remove Time_signature_engraver
514 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
521 FILTER: r'''<lilypond %(options)s>
531 <a href="%(base)s.ly">''',
534 <img align="center" valign="center"
535 border="0" src="%(image)s" alt="%(alt)s">''',
537 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
539 QUOTE: r'''<blockquote>
553 \ifx\preLilyPondExample \undefined%%
556 \preLilyPondExample%%
558 \def\lilypondbook{}%%
559 \input %(base)s-systems.tex%%
560 \ifx\postLilyPondExample \undefined%%
563 \postLilyPondExample%%
567 PRINTFILENAME: '''\\texttt{%(filename)s}
570 QUOTE: r'''\begin{quotation}%(str)s
573 VERBATIM: r'''\noindent
574 \begin{verbatim}%(verb)s\end{verbatim}''',
576 FILTER: r'''\begin{lilypond}[%(options)s]
583 FILTER: r'''@lilypond[%(options)s]
589 @include %(base)s-systems.texi
593 OUTPUTIMAGE: r'''@noindent
595 @image{%(base)s,,,%(alt)s,%(ext)s}
599 <a href="%(base)s.ly">
600 <img align="center" valign="center"
601 border="0" src="%(image)s" alt="%(alt)s">
609 <a href="%(base)s.ly">
617 QUOTE: r'''@quotation
618 %(str)s@end quotation
625 VERBATIM: r'''@exampleindent 0
627 %(verb)s@end verbatim
633 # Maintain line numbers.
638 for f in [HTML, LATEX]:
639 for s in (QUOTE, VERBATIM):
640 output[f][s] = output[f][s].replace("\n"," ")
643 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
644 %%%% Options: [%(option_string)s]
646 #(set! toplevel-score-handler print-score-with-defaults)
647 #(set! toplevel-music-handler
649 (if (not (eq? (ly:music-property m \'void) #t))
650 (print-score-with-defaults
651 p (scorify-music m p)))))
653 #(ly:set-option (quote no-point-and-click))
654 #(define inside-lilypond-book #t)
655 #(define version-seen? #t)
663 %% ****************************************************************
664 %% Start cut-&-pastable-section
665 %% ****************************************************************
668 #(define dump-extents #t)
669 %(font_dump_setting)s
683 %% ****************************************************************
684 %% ly snippet contents follows:
685 %% ****************************************************************
689 %% ****************************************************************
691 %% ****************************************************************
698 %% ****************************************************************
700 %% ****************************************************************
704 %% ****************************************************************
706 %% ****************************************************************
709 texinfo_line_widths = {
710 '@afourpaper': '160\\mm',
711 '@afourwide': '6.5\\in',
712 '@afourlatex': '150\\mm',
713 '@smallbook': '5\\in',
714 '@letterpaper': '6\\in',
717 def classic_lilypond_book_compatibility (key, value):
718 if key == 'singleline' and value == None:
719 return (RAGGED_RIGHT, None)
721 m = re.search ('relative\s*([-0-9])', key)
723 return ('relative', m.group (1))
725 m = re.match ('([0-9]+)pt', key)
727 return ('staffsize', m.group (1))
729 if key == 'indent' or key == 'line-width':
730 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
732 f = float (m.group (1))
733 return (key, '%f\\%s' % (f, m.group (2)))
737 def find_file (name):
738 for i in global_options.include_path:
739 full = os.path.join (i, name)
740 if os.path.exists (full):
743 error (_ ("file not found: %s") % name + '\n')
747 def verbatim_html (s):
748 return re.sub ('>', '>',
750 re.sub ('&', '&', s)))
752 def split_options (option_string):
754 if global_options.format == HTML:
755 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
756 for i in range(len(options)):
757 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
760 return re.split (format_res[global_options.format]['option_sep'],
764 def set_default_options (source):
765 global default_ly_options
766 if not default_ly_options.has_key (LINE_WIDTH):
767 if global_options.format == LATEX:
768 textwidth = get_latex_textwidth (source)
769 default_ly_options[LINE_WIDTH] = \
770 '''%.0f\\pt''' % textwidth
771 elif global_options.format == TEXINFO:
772 for (k, v) in texinfo_line_widths.items ():
773 # FIXME: @layout is usually not in
776 # \input texinfo @c -*-texinfo-*-
778 # Bluntly search first K items of
780 # s = chunks[0].replacement_text ()
781 if re.search (k, source[:1024]):
782 default_ly_options[LINE_WIDTH] = v
786 def replacement_text (self):
789 def filter_text (self):
790 return self.replacement_text ()
792 def ly_is_outdated (self):
795 def png_is_outdated (self):
801 class Substring (Chunk):
802 def __init__ (self, source, start, end, line_number):
806 self.line_number = line_number
807 self.override_text = None
812 def replacement_text (self):
813 if self.override_text:
814 return self.override_text
816 return self.source[self.start:self.end]
818 class Snippet (Chunk):
819 def __init__ (self, type, match, format, line_number):
823 self.option_dict = {}
825 self.line_number = line_number
827 def replacement_text (self):
828 return self.match.group ('match')
830 def substring (self, s):
831 return self.match.group (s)
834 return `self.__class__` + ' type = ' + self.type
836 class Include_snippet (Snippet):
837 def processed_filename (self):
838 f = self.substring ('filename')
839 return os.path.splitext (f)[0] + format2ext[global_options.format]
841 def replacement_text (self):
842 s = self.match.group ('match')
843 f = self.substring ('filename')
845 return re.sub (f, self.processed_filename (), s)
847 class Lilypond_snippet (Snippet):
848 def __init__ (self, type, match, format, line_number):
849 Snippet.__init__ (self, type, match, format, line_number)
850 os = match.group ('options')
851 self.do_options (os, self.type)
854 return self.substring ('code')
859 return self.compose_ly (s)
862 def do_options (self, option_string, type):
863 self.option_dict = {}
865 options = split_options (option_string)
868 if string.find (i, '=') > 0:
869 (key, value) = re.split ('\s*=\s*', i)
870 self.option_dict[key] = value
872 if i in no_options.keys ():
873 if no_options[i] in self.option_dict.keys ():
874 del self.option_dict[no_options[i]]
876 self.option_dict[i] = None
878 has_line_width = self.option_dict.has_key (LINE_WIDTH)
879 no_line_width_value = 0
881 # If LINE_WIDTH is used without parameter, set it to default.
882 if has_line_width and self.option_dict[LINE_WIDTH] == None:
883 no_line_width_value = 1
884 del self.option_dict[LINE_WIDTH]
886 for i in default_ly_options.keys ():
887 if i not in self.option_dict.keys ():
888 self.option_dict[i] = default_ly_options[i]
890 if not has_line_width:
891 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
892 self.option_dict[RAGGED_RIGHT] = None
894 if type == 'lilypond':
895 if LINE_WIDTH in self.option_dict.keys ():
896 del self.option_dict[LINE_WIDTH]
898 if RAGGED_RIGHT in self.option_dict.keys ():
899 if LINE_WIDTH in self.option_dict.keys ():
900 del self.option_dict[LINE_WIDTH]
902 if QUOTE in self.option_dict.keys () or type == 'lilypond':
903 if LINE_WIDTH in self.option_dict.keys ():
904 del self.option_dict[LINE_WIDTH]
906 if not INDENT in self.option_dict.keys ():
907 self.option_dict[INDENT] = '0\\mm'
909 # The QUOTE pattern from ly_options only emits the `line-width'
911 if has_line_width and QUOTE in self.option_dict.keys ():
912 if no_line_width_value:
913 del self.option_dict[LINE_WIDTH]
915 del self.option_dict[QUOTE]
917 def compose_ly (self, code):
918 if FRAGMENT in self.option_dict.keys ():
926 # The original concept of the `exampleindent' option is broken.
927 # It is not possible to get a sane value for @exampleindent at all
928 # without processing the document itself. Saying
936 # causes ugly results with the DVI backend of texinfo since the
937 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
938 # value). Executing the above code changes the environment
939 # indentation to an unknown value because we don't know the amount
940 # of 1em in advance since it is font-dependent. Modifying
941 # @exampleindent in the middle of a document is simply not
942 # supported within texinfo.
944 # As a consequence, the only function of @exampleindent is now to
945 # specify the amount of indentation for the `quote' option.
947 # To set @exampleindent locally to zero, we use the @format
948 # environment for non-quoted snippets.
949 override[EXAMPLEINDENT] = r'0.4\in'
950 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
951 override.update (default_ly_options)
954 for (key, value) in self.option_dict.items ():
956 option_list.append (key)
958 option_list.append (key + '=' + value)
959 option_string = string.join (option_list, ',')
962 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
963 for a in compose_types:
966 for (key, value) in self.option_dict.items ():
968 classic_lilypond_book_compatibility (key, value)
972 (_ ("deprecated ly-option used: %s=%s" \
975 (_ ("compatibility mode translation: %s=%s" \
979 (_ ("deprecated ly-option used: %s" \
982 (_ ("compatibility mode translation: %s" \
985 (key, value) = (c_key, c_value)
988 override[key] = value
990 if not override.has_key (key):
994 for type in compose_types:
995 if ly_options[type].has_key (key):
996 compose_dict[type].append (ly_options[type][key])
1000 if not found and key not in simple_options:
1001 warning (_ ("ignoring unknown ly option: %s") % key)
1004 if RELATIVE in override.keys () and override[RELATIVE]:
1005 relative = int (override[RELATIVE])
1007 relative_quotes = ''
1011 relative_quotes += ',' * (- relative)
1013 relative_quotes += "'" * relative
1015 paper_string = string.join (compose_dict[PAPER],
1017 layout_string = string.join (compose_dict[LAYOUT],
1019 notes_string = string.join (compose_dict[NOTES],
1021 preamble_string = string.join (compose_dict[PREAMBLE],
1024 font_dump_setting = ''
1025 if FONTLOAD in self.option_dict:
1026 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1028 d = globals().copy()
1030 return (PREAMBLE_LY + body) % d
1033 def get_hash (self):
1035 self.hash = abs (hash (self.full_ly ()))
1038 def basename (self):
1039 if FILENAME in self.option_dict:
1040 return self.option_dict[FILENAME]
1041 if global_options.use_hash:
1042 return 'lily-%d' % self.get_hash ()
1045 def write_ly (self):
1046 outf = open (self.basename () + '.ly', 'w')
1047 outf.write (self.full_ly ())
1049 open (self.basename () + '.txt', 'w').write ('image of music')
1051 def ly_is_outdated (self):
1052 base = self.basename ()
1054 tex_file = '%s.tex' % base
1055 eps_file = '%s.eps' % base
1056 system_file = '%s-systems.tex' % base
1057 ly_file = '%s.ly' % base
1058 ok = os.path.exists (ly_file) \
1059 and os.path.exists (system_file)\
1060 and os.stat (system_file)[stat.ST_SIZE] \
1061 and re.match ('% eof', open (system_file).readlines ()[-1])
1062 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1063 ok = (self.full_ly () == open (ly_file).read ())
1065 # TODO: Do something smart with target formats
1066 # (ps, png) and m/ctimes.
1070 def png_is_outdated (self):
1071 base = self.basename ()
1072 ok = not self.ly_is_outdated ()
1073 if global_options.format in (HTML, TEXINFO):
1074 ok = ok and os.path.exists (base + '.eps')
1078 page_count = ps_page_count (base + '.eps')
1081 ok = ok and os.path.exists (base + '.png')
1083 elif page_count > 1:
1084 for a in range (1, page_count + 1):
1085 ok = ok and os.path.exists (base + '-page%d.png' % a)
1089 def texstr_is_outdated (self):
1093 base = self.basename ()
1094 ok = self.ly_is_outdated ()
1095 ok = ok and (os.path.exists (base + '.texstr'))
1098 def filter_text (self):
1099 code = self.substring ('code')
1100 s = run_filter (code)
1103 'options': self.match.group ('options')
1106 return output[self.format][FILTER] % d
1108 def replacement_text (self):
1109 func = Lilypond_snippet.__dict__['output_' + self.format]
1112 def get_images (self):
1113 base = self.basename ()
1115 single = '%(base)s.png' % vars ()
1116 multiple = '%(base)s-page1.png' % vars ()
1118 if os.path.exists (multiple) \
1119 and (not os.path.exists (single) \
1120 or (os.stat (multiple)[stat.ST_MTIME] \
1121 > os.stat (single)[stat.ST_MTIME])):
1122 count = ps_page_count ('%(base)s.eps' % vars ())
1123 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1124 images = tuple (images)
1127 def output_html (self):
1129 base = self.basename ()
1130 if global_options.format == HTML:
1131 str += self.output_print_filename (HTML)
1132 if VERBATIM in self.option_dict:
1133 verb = verbatim_html (self.substring ('code'))
1134 str += output[HTML][VERBATIM] % vars ()
1135 if QUOTE in self.option_dict:
1136 str = output[HTML][QUOTE] % vars ()
1138 str += output[HTML][BEFORE] % vars ()
1139 for image in self.get_images ():
1140 (base, ext) = os.path.splitext (image)
1141 alt = self.option_dict[ALT]
1142 str += output[HTML][OUTPUT] % vars ()
1143 str += output[HTML][AFTER] % vars ()
1146 def output_info (self):
1148 for image in self.get_images ():
1149 (base, ext) = os.path.splitext (image)
1151 # URG, makeinfo implicitly prepends dot to extension.
1152 # Specifying no extension is most robust.
1154 alt = self.option_dict[ALT]
1155 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1157 base = self.basename ()
1158 str += output[global_options.format][OUTPUT] % vars ()
1161 def output_latex (self):
1163 base = self.basename ()
1164 if global_options.format == LATEX:
1165 str += self.output_print_filename (LATEX)
1166 if VERBATIM in self.option_dict:
1167 verb = self.substring ('code')
1168 str += (output[LATEX][VERBATIM] % vars ())
1170 str += (output[LATEX][OUTPUT] % vars ())
1172 ## todo: maintain breaks
1174 breaks = self.ly ().count ("\n")
1175 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1177 if QUOTE in self.option_dict:
1178 str = output[LATEX][QUOTE] % vars ()
1181 def output_print_filename (self, format):
1183 if PRINTFILENAME in self.option_dict:
1184 base = self.basename ()
1185 filename = self.substring ('filename')
1186 str = output[global_options.format][PRINTFILENAME] % vars ()
1190 def output_texinfo (self):
1192 if self.output_print_filename (TEXINFO):
1194 + self.output_print_filename (HTML)
1197 + self.output_print_filename (LATEX)
1199 base = self.basename ()
1200 if TEXIDOC in self.option_dict:
1201 texidoc = base + '.texidoc'
1202 if os.path.exists (texidoc):
1203 str += '@include %(texidoc)s\n\n' % vars ()
1205 if VERBATIM in self.option_dict:
1206 verb = self.substring ('code')
1207 str += (output[TEXINFO][VERBATIM] % vars ())
1208 if not QUOTE in self.option_dict:
1209 str = output[TEXINFO][NOQUOTE] % vars ()
1211 str += self.output_info ()
1213 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1214 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1215 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1217 if QUOTE in self.option_dict:
1218 str = output[TEXINFO][QUOTE] % vars ()
1220 # need par after image
1225 class Lilypond_file_snippet (Lilypond_snippet):
1227 name = self.substring ('filename')
1228 contents = open (find_file (name)).read ()
1230 ## strip version string to make automated regtest comparisons
1231 ## across versions easier.
1232 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1234 return ('\\sourcefilename \"%s\"\n%s'
1237 snippet_type_to_class = {
1238 'lilypond_file': Lilypond_file_snippet,
1239 'lilypond_block': Lilypond_snippet,
1240 'lilypond': Lilypond_snippet,
1241 'include': Include_snippet,
1244 def find_linestarts (s):
1249 i = s.find ('\n', start)
1257 nls.append (len (s))
1260 def find_toplevel_snippets (s, types):
1263 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1267 found = dict ((t, None) for t in types)
1269 line_starts = find_linestarts (s)
1271 # We want to search for multiple regexes, without searching
1272 # the string multiple times for one regex.
1273 # Hence, we use earlier results to limit the string portion
1275 # Since every part of the string is traversed at most once for
1276 # every type of snippet, this is linear.
1282 if not found[type] or found[type][0] < index:
1285 m = res[type].search (s[index:endex])
1290 if snippet_type_to_class.has_key (type):
1291 cl = snippet_type_to_class[type]
1294 start = index + m.start ('match')
1295 line_number = line_start_idx
1296 while (line_starts[line_number] < start):
1300 snip = cl (type, m, global_options.format, line_number)
1302 found[type] = (start, snip)
1306 or found[type][0] < found[first][0]):
1311 # Limiting the search space is a cute
1312 # idea, but this *requires* to search
1313 # for possible containing blocks
1314 # first, at least as long as we do not
1315 # search for the start of blocks, but
1316 # always/directly for the entire
1317 # @block ... @end block.
1319 endex = found[first][0]
1322 snippets.append (Substring (s, index, len (s), line_start_idx))
1325 while (start > line_starts[line_start_idx+1]):
1328 (start, snip) = found[first]
1329 snippets.append (Substring (s, index, start, line_start_idx + 1))
1330 snippets.append (snip)
1332 index = start + len (snip.match.group ('match'))
1336 def filter_pipe (input, cmd):
1337 if global_options.verbose:
1338 progress (_ ("Opening filter `%s'") % cmd)
1340 (stdin, stdout, stderr) = os.popen3 (cmd)
1342 status = stdin.close ()
1346 output = stdout.read ()
1347 status = stdout.close ()
1348 error = stderr.read ()
1352 signal = 0x0f & status
1353 if status or (not output and error):
1354 exit_status = status >> 8
1355 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1356 error (_ ("The error log is as follows:"))
1357 sys.stderr.write (error)
1358 sys.stderr.write (stderr.read ())
1361 if global_options.verbose:
1367 return filter_pipe (s, global_options.filter_cmd)
1369 def is_derived_class (cl, baseclass):
1372 for b in cl.__bases__:
1373 if is_derived_class (b, baseclass):
1377 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1378 ly_names = filter (lambda x: x,
1379 map (Lilypond_snippet.basename, ly_snippets))
1380 texstr_names = filter (lambda x: x,
1381 map (Lilypond_snippet.basename, texstr_snippets))
1383 png_names = filter (lambda x: x,
1384 map (Lilypond_snippet.basename, png_snippets))
1387 def my_system (cmd):
1388 status = ly.system (cmd,
1389 be_verbose=global_options.verbose,
1392 if global_options.format in (HTML, TEXINFO):
1393 cmd += ' --format png '
1396 # the --process=CMD switch is a bad idea
1397 # it is too generic for lilypond-book.
1399 my_system (string.join ([cmd, '--backend texstr',
1400 'snippet-map.ly'] + texstr_names))
1401 for l in texstr_names:
1402 my_system ('latex %s.texstr' % l)
1405 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1407 LATEX_INSPECTION_DOCUMENT = r'''
1411 \typeout{textwidth=\the\textwidth}
1412 \typeout{columnsep=\the\columnsep}
1413 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1417 # Do we need anything else besides `textwidth'?
1418 def get_latex_textwidth (source):
1419 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1421 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1423 ## what's a sensible default?
1426 preamble = source[:m.start (0)]
1427 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1429 (handle, tmpfile) = tempfile.mkstemp('.tex')
1430 logfile = os.path.splitext (tmpfile)[0] + '.log'
1431 logfile = os.path.split (logfile)[1]
1433 tmp_handle = os.fdopen (handle,'w')
1434 tmp_handle.write (latex_document)
1437 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1438 parameter_string = open (logfile).read()
1444 m = re.search ('columns=([0-9.]*)', parameter_string)
1446 columns = int (m.group (1))
1449 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1451 columnsep = float (m.group (1))
1454 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1456 textwidth = float (m.group (1))
1458 textwidth = (textwidth - columnsep) / columns
1462 def modify_preamble (chunk):
1463 str = chunk.replacement_text ()
1464 if (re.search (r"\\begin *{document}", str)
1465 and not re.search ("{graphic[sx]", str)):
1466 str = re.sub (r"\\begin{document}",
1467 r"\\usepackage{graphics}" + '\n'
1468 + r"\\begin{document}",
1470 chunk.override_text = str
1482 '.texinfo': TEXINFO,
1488 # TEXINFO: '.texinfo',
1493 class Compile_error:
1496 def write_file_map (lys, name):
1497 snippet_map = open ('snippet-map.ly', 'w')
1498 snippet_map.write ("""
1499 #(define version-seen? #t)
1500 #(ly:add-file-name-alist '(
1503 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1509 snippet_map.write ('))\n')
1511 def do_process_cmd (chunks, input_name):
1512 all_lys = filter (lambda x: is_derived_class (x.__class__,
1516 write_file_map (all_lys, input_name)
1517 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1519 and x.ly_is_outdated (), chunks)
1520 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1522 and x.texstr_is_outdated (),
1524 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1526 and x.png_is_outdated (),
1529 outdated = png_outdated + texstr_outdated + ly_outdated
1531 progress (_ ("Writing snippets..."))
1532 map (Lilypond_snippet.write_ly, ly_outdated)
1536 progress (_ ("Processing..."))
1538 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1540 progress (_ ("All snippets are up to date..."))
1543 def guess_format (input_filename):
1545 e = os.path.splitext (input_filename)[1]
1546 if e in ext2format.keys ():
1548 format = ext2format[e]
1550 error (_ ("can't determine format for: %s" \
1555 def write_if_updated (file_name, lines):
1557 f = open (file_name)
1559 new_str = string.join (lines, '')
1560 if oldstr == new_str:
1561 progress (_ ("%s is up to date.") % file_name)
1567 progress (_ ("Writing `%s'...") % file_name)
1568 open (file_name, 'w').writelines (lines)
1571 def note_input_file (name, inputs=[]):
1572 ## hack: inputs is mutable!
1573 inputs.append (name)
1576 def samefile (f1, f2):
1578 return os.path.samefile (f1, f2)
1579 except AttributeError: # Windoze
1580 f1 = re.sub ("//*", "/", f1)
1581 f2 = re.sub ("//*", "/", f2)
1584 def do_file (input_filename):
1586 if not input_filename or input_filename == '-':
1587 in_handle = sys.stdin
1588 input_fullname = '<stdin>'
1590 if os.path.exists (input_filename):
1591 input_fullname = input_filename
1592 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1593 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1595 input_fullname = find_file (input_filename)
1597 note_input_file (input_fullname)
1598 in_handle = open (input_fullname)
1600 if input_filename == '-':
1601 input_base = 'stdin'
1603 input_base = os.path.basename \
1604 (os.path.splitext (input_filename)[0])
1606 # Only default to stdout when filtering.
1607 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1608 output_filename = '-'
1609 output_file = sys.stdout
1611 # don't complain when global_options.output_name is existing
1612 output_filename = input_base + format2ext[global_options.format]
1613 if global_options.output_name:
1614 if not os.path.isdir (global_options.output_name):
1615 os.mkdir (global_options.output_name, 0777)
1616 os.chdir (global_options.output_name)
1618 if (os.path.exists (input_filename)
1619 and os.path.exists (output_filename)
1620 and samefile (output_filename, input_fullname)):
1622 _ ("Output would overwrite input file; use --output."))
1626 progress (_ ("Reading %s...") % input_fullname)
1627 source = in_handle.read ()
1630 set_default_options (source)
1633 # FIXME: Containing blocks must be first, see
1634 # find_toplevel_snippets.
1636 'multiline_comment',
1640 'singleline_comment',
1645 progress (_ ("Dissecting..."))
1646 chunks = find_toplevel_snippets (source, snippet_types)
1648 if global_options.format == LATEX:
1650 if (c.is_plain () and
1651 re.search (r"\\begin *{document}", c.replacement_text())):
1656 if global_options.filter_cmd:
1657 write_if_updated (output_filename,
1658 [c.filter_text () for c in chunks])
1659 elif global_options.process_cmd:
1660 do_process_cmd (chunks, input_fullname)
1661 progress (_ ("Compiling %s...") % output_filename)
1663 write_if_updated (output_filename,
1664 [s.replacement_text ()
1667 def process_include (snippet):
1668 os.chdir (original_dir)
1669 name = snippet.substring ('filename')
1670 progress (_ ("Processing include: %s") % name)
1672 return do_file (name)
1674 include_chunks = map (process_include,
1675 filter (lambda x: is_derived_class (x.__class__,
1680 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1682 except Compile_error:
1683 os.chdir (original_dir)
1684 progress (_ ("Removing `%s'") % output_filename)
1690 global global_options
1692 opt_parser = get_option_parser()
1693 (global_options, args) = opt_parser.parse_args ()
1695 if global_options.format in ('texi-html', 'texi'):
1696 global_options.format = TEXINFO
1697 global_options.use_hash = True
1699 global_options.include_path = map (os.path.abspath, global_options.include_path)
1701 if global_options.warranty:
1704 if not args or len (args) > 1:
1705 opt_parser.print_help ()
1711 files = do_options ()
1715 basename = os.path.splitext (file)[0]
1716 basename = os.path.split (basename)[1]
1718 if not global_options.format:
1719 global_options.format = guess_format (files[0])
1722 if global_options.format in (TEXINFO, HTML):
1724 if global_options.process_cmd == '':
1725 global_options.process_cmd = lilypond_binary \
1726 + ' --formats=%s --backend eps ' % formats
1728 if global_options.process_cmd:
1729 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1730 for p in global_options.include_path])
1735 chunks = do_file (file)
1736 if global_options.psfonts:
1737 fontextract.verbose = global_options.verbose
1738 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1742 psfonts_file = basename + '.psfonts'
1743 if not global_options.verbose:
1744 progress (_ ("Writing fonts to %s...") % psfonts_file)
1745 fontextract.extract_fonts (psfonts_file,
1746 [x.basename() + '.eps'
1747 for x in snippet_chunks])
1748 if not global_options.verbose:
1751 except Compile_error:
1754 if global_options.format in (TEXINFO, LATEX):
1755 if not global_options.psfonts:
1756 warning (_ ("option --psfonts not used"))
1757 warning (_ ("processing with dvips will have no fonts"))
1759 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1760 output = os.path.join (global_options.output_name, basename + '.dvi' )
1763 progress (_ ("DVIPS usage:"))
1765 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1768 inputs = note_input_file ('')
1771 base_file_name = os.path.splitext (os.path.basename (file))[0]
1772 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1773 final_output_file = os.path.join (global_options.output_name,
1775 + '.%s' % global_options.format)
1777 os.chdir (original_dir)
1778 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1780 if __name__ == '__main__':