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', help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
154 p.add_option ("-I", '--include', help=_('add DIR to include path'),
156 action='append', dest='include_path',
157 default=[os.path.abspath (os.getcwd ())])
159 p.add_option ("-o", '--output', help=_('write output to DIR'),
161 action='store', dest='output_name',
163 p.add_option ('-P', '--process', metavar=_("COMMAND"),
164 help = _ ("process ly_files using COMMAND FILE..."),
166 dest='process_cmd', default='lilypond -b eps')
168 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
169 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
170 '''must use this with dvips -h INPUT.psfonts'''),
172 p.add_option ('-V', '--verbose', help=_("be verbose"),
177 p.add_option ('-w', '--warranty',
178 help=_("show warranty and copyright"),
182 p.add_option_group ('bugs',
183 description='''Report bugs via http://post.gmane.org/post.php'''
184 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
188 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
190 # Only use installed binary when we are installed too.
191 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
192 lilypond_binary = 'lilypond'
194 global_options = None
197 default_ly_options = { 'alt': "[image of music]" }
200 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
204 EXAMPLEINDENT = 'exampleindent'
206 FRAGMENT = 'fragment'
211 LINE_WIDTH = 'line-width'
212 NOFRAGMENT = 'nofragment'
213 NOINDENT = 'noindent'
218 OUTPUTIMAGE = 'outputimage'
221 PREAMBLE = 'preamble'
222 PRINTFILENAME = 'printfilename'
224 RAGGED_RIGHT = 'ragged-right'
225 RELATIVE = 'relative'
226 STAFFSIZE = 'staffsize'
229 VERBATIM = 'verbatim'
230 FONTLOAD = 'fontload'
231 FILENAME = 'filename'
235 # NOTIME has no opposite so it isn't part of this dictionary.
236 # NOQUOTE is used internally only.
238 NOFRAGMENT: FRAGMENT,
243 # Recognize special sequences in the input.
245 # (?P<name>regex) -- Assign result of REGEX to NAME.
246 # *? -- Match non-greedily.
247 # (?m) -- Multiline regex: Make ^ and $ match at each line.
248 # (?s) -- Make the dot match all characters including newline.
249 # (?x) -- Ignore whitespace in patterns.
261 (\s*(?P<options>.*?)\s*:)?\s*
269 \s*(?P<options>.*?)\s*
278 \s*(?P<options>.*?)\s*
280 \s*(?P<filename>.*?)\s*
287 (?P<code><!--\s.*?!-->)
290 'singleline_comment':
296 (?P<code><pre>.*?</pre>))''',
302 (?P<code><pre>\s.*?</pre>\s))''',
321 \s*(?P<options>.*?)\s*
332 \s*(?P<options>.*?)\s*
336 \\end\s*{lilypond})''',
344 \s*(?P<options>.*?)\s*
352 'singleline_comment':
375 \\end\s*{verbatim}))''',
384 (?P<filename>\S+))''',
388 ^[^\n]*?(?!@c\s+)[^\n]*?
392 \s*(?P<options>.*?)\s*
402 \s*(?P<options>.*?)\s*
405 ^@end\s+lilypond)\s''',
412 \s*(?P<options>.*?)\s*
423 @end\s+ignore))\s''',
425 'singleline_comment':
430 @c([ \t][^\n]*|)\n))''',
432 # Don't do this: It interferes with @code{@{}.
433 # 'verb': r'''(?P<code>@code{.*?})''',
441 @end\s+example\s))''',
450 'intertext': r',?\s*intertext=\".*?\"',
455 'intertext': r',?\s*intertext=\".*?\"',
456 'option_sep': '\s*,\s*',
460 'intertext': r',?\s*intertext=\".*?\"',
461 'option_sep': '\s*,\s*',
465 # Options without a pattern in ly_options.
482 RELATIVE: r'''\relative c%(relative_quotes)s''',
487 INDENT: r'''indent = %(indent)s''',
489 LINE_WIDTH: r'''line-width = %(line-width)s''',
491 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
493 RAGGED_RIGHT: r'''ragged-right = ##t''',
495 PACKED: r'''packed = ##t''',
507 \remove Time_signature_engraver
513 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
520 FILTER: r'''<lilypond %(options)s>
530 <a href="%(base)s.ly">''',
533 <img align="center" valign="center"
534 border="0" src="%(image)s" alt="%(alt)s">''',
536 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
538 QUOTE: r'''<blockquote>
552 \ifx\preLilyPondExample \undefined%%
555 \preLilyPondExample%%
557 \def\lilypondbook{}%%
558 \input %(base)s-systems.tex%%
559 \ifx\postLilyPondExample \undefined%%
562 \postLilyPondExample%%
566 PRINTFILENAME: '''\\texttt{%(filename)s}
569 QUOTE: r'''\begin{quotation}%(str)s
572 VERBATIM: r'''\noindent
573 \begin{verbatim}%(verb)s\end{verbatim}''',
575 FILTER: r'''\begin{lilypond}[%(options)s]
582 FILTER: r'''@lilypond[%(options)s]
588 @include %(base)s-systems.texi
592 OUTPUTIMAGE: r'''@noindent
594 @image{%(base)s,,,%(alt)s,%(ext)s}
598 <a href="%(base)s.ly">
599 <img align="center" valign="center"
600 border="0" src="%(image)s" alt="%(alt)s">
608 <a href="%(base)s.ly">
616 QUOTE: r'''@quotation
617 %(str)s@end quotation
624 VERBATIM: r'''@exampleindent 0
626 %(verb)s@end verbatim
632 # Maintain line numbers.
637 for f in [HTML, LATEX]:
638 for s in (QUOTE, VERBATIM):
639 output[f][s] = output[f][s].replace("\n"," ")
642 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
643 %%%% Options: [%(option_string)s]
645 #(set! toplevel-score-handler print-score-with-defaults)
646 #(set! toplevel-music-handler
648 (if (not (eq? (ly:music-property m \'void) #t))
649 (print-score-with-defaults
650 p (scorify-music m p)))))
652 #(ly:set-option (quote no-point-and-click))
653 #(define inside-lilypond-book #t)
654 #(define version-seen? #t)
662 %% ****************************************************************
663 %% Start cut-&-pastable-section
664 %% ****************************************************************
667 #(define dump-extents #t)
668 %(font_dump_setting)s
682 %% ****************************************************************
683 %% ly snippet contents follows:
684 %% ****************************************************************
688 %% ****************************************************************
690 %% ****************************************************************
697 %% ****************************************************************
699 %% ****************************************************************
703 %% ****************************************************************
705 %% ****************************************************************
708 texinfo_line_widths = {
709 '@afourpaper': '160\\mm',
710 '@afourwide': '6.5\\in',
711 '@afourlatex': '150\\mm',
712 '@smallbook': '5\\in',
713 '@letterpaper': '6\\in',
716 def classic_lilypond_book_compatibility (key, value):
717 if key == 'singleline' and value == None:
718 return (RAGGED_RIGHT, None)
720 m = re.search ('relative\s*([-0-9])', key)
722 return ('relative', m.group (1))
724 m = re.match ('([0-9]+)pt', key)
726 return ('staffsize', m.group (1))
728 if key == 'indent' or key == 'line-width':
729 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
731 f = float (m.group (1))
732 return (key, '%f\\%s' % (f, m.group (2)))
736 def find_file (name):
737 for i in global_options.include_path:
738 full = os.path.join (i, name)
739 if os.path.exists (full):
742 error (_ ("file not found: %s") % name + '\n')
746 def verbatim_html (s):
747 return re.sub ('>', '>',
749 re.sub ('&', '&', s)))
751 def split_options (option_string):
753 if global_options.format == HTML:
754 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
755 for i in range(len(options)):
756 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
759 return re.split (format_res[global_options.format]['option_sep'],
763 def set_default_options (source):
764 global default_ly_options
765 if not default_ly_options.has_key (LINE_WIDTH):
766 if global_options.format == LATEX:
767 textwidth = get_latex_textwidth (source)
768 default_ly_options[LINE_WIDTH] = \
769 '''%.0f\\pt''' % textwidth
770 elif global_options.format == TEXINFO:
771 for (k, v) in texinfo_line_widths.items ():
772 # FIXME: @layout is usually not in
775 # \input texinfo @c -*-texinfo-*-
777 # Bluntly search first K items of
779 # s = chunks[0].replacement_text ()
780 if re.search (k, source[:1024]):
781 default_ly_options[LINE_WIDTH] = v
785 def replacement_text (self):
788 def filter_text (self):
789 return self.replacement_text ()
791 def ly_is_outdated (self):
794 def png_is_outdated (self):
800 class Substring (Chunk):
801 def __init__ (self, source, start, end, line_number):
805 self.line_number = line_number
806 self.override_text = None
811 def replacement_text (self):
812 if self.override_text:
813 return self.override_text
815 return self.source[self.start:self.end]
817 class Snippet (Chunk):
818 def __init__ (self, type, match, format, line_number):
822 self.option_dict = {}
824 self.line_number = line_number
826 def replacement_text (self):
827 return self.match.group ('match')
829 def substring (self, s):
830 return self.match.group (s)
833 return `self.__class__` + ' type = ' + self.type
835 class Include_snippet (Snippet):
836 def processed_filename (self):
837 f = self.substring ('filename')
838 return os.path.splitext (f)[0] + format2ext[global_options.format]
840 def replacement_text (self):
841 s = self.match.group ('match')
842 f = self.substring ('filename')
844 return re.sub (f, self.processed_filename (), s)
846 class Lilypond_snippet (Snippet):
847 def __init__ (self, type, match, format, line_number):
848 Snippet.__init__ (self, type, match, format, line_number)
849 os = match.group ('options')
850 self.do_options (os, self.type)
853 return self.substring ('code')
858 return self.compose_ly (s)
861 def do_options (self, option_string, type):
862 self.option_dict = {}
864 options = split_options (option_string)
867 if string.find (i, '=') > 0:
868 (key, value) = re.split ('\s*=\s*', i)
869 self.option_dict[key] = value
871 if i in no_options.keys ():
872 if no_options[i] in self.option_dict.keys ():
873 del self.option_dict[no_options[i]]
875 self.option_dict[i] = None
877 has_line_width = self.option_dict.has_key (LINE_WIDTH)
878 no_line_width_value = 0
880 # If LINE_WIDTH is used without parameter, set it to default.
881 if has_line_width and self.option_dict[LINE_WIDTH] == None:
882 no_line_width_value = 1
883 del self.option_dict[LINE_WIDTH]
885 for i in default_ly_options.keys ():
886 if i not in self.option_dict.keys ():
887 self.option_dict[i] = default_ly_options[i]
889 if not has_line_width:
890 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
891 self.option_dict[RAGGED_RIGHT] = None
893 if type == 'lilypond':
894 if LINE_WIDTH in self.option_dict.keys ():
895 del self.option_dict[LINE_WIDTH]
897 if RAGGED_RIGHT in self.option_dict.keys ():
898 if LINE_WIDTH in self.option_dict.keys ():
899 del self.option_dict[LINE_WIDTH]
901 if QUOTE in self.option_dict.keys () or type == 'lilypond':
902 if LINE_WIDTH in self.option_dict.keys ():
903 del self.option_dict[LINE_WIDTH]
905 if not INDENT in self.option_dict.keys ():
906 self.option_dict[INDENT] = '0\\mm'
908 # The QUOTE pattern from ly_options only emits the `line-width'
910 if has_line_width and QUOTE in self.option_dict.keys ():
911 if no_line_width_value:
912 del self.option_dict[LINE_WIDTH]
914 del self.option_dict[QUOTE]
916 def compose_ly (self, code):
917 if FRAGMENT in self.option_dict.keys ():
925 # The original concept of the `exampleindent' option is broken.
926 # It is not possible to get a sane value for @exampleindent at all
927 # without processing the document itself. Saying
935 # causes ugly results with the DVI backend of texinfo since the
936 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
937 # value). Executing the above code changes the environment
938 # indentation to an unknown value because we don't know the amount
939 # of 1em in advance since it is font-dependent. Modifying
940 # @exampleindent in the middle of a document is simply not
941 # supported within texinfo.
943 # As a consequence, the only function of @exampleindent is now to
944 # specify the amount of indentation for the `quote' option.
946 # To set @exampleindent locally to zero, we use the @format
947 # environment for non-quoted snippets.
948 override[EXAMPLEINDENT] = r'0.4\in'
949 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
950 override.update (default_ly_options)
953 for (key, value) in self.option_dict.items ():
955 option_list.append (key)
957 option_list.append (key + '=' + value)
958 option_string = string.join (option_list, ',')
961 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
962 for a in compose_types:
965 for (key, value) in self.option_dict.items ():
967 classic_lilypond_book_compatibility (key, value)
971 (_ ("deprecated ly-option used: %s=%s" \
974 (_ ("compatibility mode translation: %s=%s" \
978 (_ ("deprecated ly-option used: %s" \
981 (_ ("compatibility mode translation: %s" \
984 (key, value) = (c_key, c_value)
987 override[key] = value
989 if not override.has_key (key):
993 for type in compose_types:
994 if ly_options[type].has_key (key):
995 compose_dict[type].append (ly_options[type][key])
999 if not found and key not in simple_options:
1000 warning (_ ("ignoring unknown ly option: %s") % key)
1003 if RELATIVE in override.keys () and override[RELATIVE]:
1004 relative = int (override[RELATIVE])
1006 relative_quotes = ''
1010 relative_quotes += ',' * (- relative)
1012 relative_quotes += "'" * relative
1014 paper_string = string.join (compose_dict[PAPER],
1016 layout_string = string.join (compose_dict[LAYOUT],
1018 notes_string = string.join (compose_dict[NOTES],
1020 preamble_string = string.join (compose_dict[PREAMBLE],
1023 font_dump_setting = ''
1024 if FONTLOAD in self.option_dict:
1025 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1027 d = globals().copy()
1029 return (PREAMBLE_LY + body) % d
1032 def get_hash (self):
1034 self.hash = abs (hash (self.full_ly ()))
1037 def basename (self):
1038 if FILENAME in self.option_dict:
1039 return self.option_dict[FILENAME]
1040 if global_options.use_hash:
1041 return 'lily-%d' % self.get_hash ()
1044 def write_ly (self):
1045 outf = open (self.basename () + '.ly', 'w')
1046 outf.write (self.full_ly ())
1048 open (self.basename () + '.txt', 'w').write ('image of music')
1050 def ly_is_outdated (self):
1051 base = self.basename ()
1053 tex_file = '%s.tex' % base
1054 eps_file = '%s.eps' % base
1055 system_file = '%s-systems.tex' % base
1056 ly_file = '%s.ly' % base
1057 ok = os.path.exists (ly_file) \
1058 and os.path.exists (system_file)\
1059 and os.stat (system_file)[stat.ST_SIZE] \
1060 and re.match ('% eof', open (system_file).readlines ()[-1])
1061 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1062 ok = (self.full_ly () == open (ly_file).read ())
1064 # TODO: Do something smart with target formats
1065 # (ps, png) and m/ctimes.
1069 def png_is_outdated (self):
1070 base = self.basename ()
1071 ok = self.ly_is_outdated ()
1072 if global_options.format in (HTML, TEXINFO):
1073 ok = ok and os.path.exists (base + '.eps')
1077 page_count = ps_page_count (base + '.eps')
1080 ok = ok and os.path.exists (base + '.png')
1081 elif page_count > 1:
1082 for a in range (1, page_count + 1):
1083 ok = ok and os.path.exists (base + '-page%d.png' % a)
1087 def texstr_is_outdated (self):
1091 base = self.basename ()
1092 ok = self.ly_is_outdated ()
1093 ok = ok and (os.path.exists (base + '.texstr'))
1096 def filter_text (self):
1097 code = self.substring ('code')
1098 s = run_filter (code)
1101 'options': self.match.group ('options')
1104 return output[self.format][FILTER] % d
1106 def replacement_text (self):
1107 func = Lilypond_snippet.__dict__['output_' + self.format]
1110 def get_images (self):
1111 base = self.basename ()
1113 single = '%(base)s.png' % vars ()
1114 multiple = '%(base)s-page1.png' % vars ()
1116 if os.path.exists (multiple) \
1117 and (not os.path.exists (single) \
1118 or (os.stat (multiple)[stat.ST_MTIME] \
1119 > os.stat (single)[stat.ST_MTIME])):
1120 count = ps_page_count ('%(base)s.eps' % vars ())
1121 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1122 images = tuple (images)
1125 def output_html (self):
1127 base = self.basename ()
1128 if global_options.format == HTML:
1129 str += self.output_print_filename (HTML)
1130 if VERBATIM in self.option_dict:
1131 verb = verbatim_html (self.substring ('code'))
1132 str += output[HTML][VERBATIM] % vars ()
1133 if QUOTE in self.option_dict:
1134 str = output[HTML][QUOTE] % vars ()
1136 str += output[HTML][BEFORE] % vars ()
1137 for image in self.get_images ():
1138 (base, ext) = os.path.splitext (image)
1139 alt = self.option_dict[ALT]
1140 str += output[HTML][OUTPUT] % vars ()
1141 str += output[HTML][AFTER] % vars ()
1144 def output_info (self):
1146 for image in self.get_images ():
1147 (base, ext) = os.path.splitext (image)
1149 # URG, makeinfo implicitly prepends dot to extension.
1150 # Specifying no extension is most robust.
1152 alt = self.option_dict[ALT]
1153 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1155 base = self.basename ()
1156 str += output[global_options.format][OUTPUT] % vars ()
1159 def output_latex (self):
1161 base = self.basename ()
1162 if global_options.format == LATEX:
1163 str += self.output_print_filename (LATEX)
1164 if VERBATIM in self.option_dict:
1165 verb = self.substring ('code')
1166 str += (output[LATEX][VERBATIM] % vars ())
1168 str += (output[LATEX][OUTPUT] % vars ())
1170 ## todo: maintain breaks
1172 breaks = self.ly ().count ("\n")
1173 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1175 if QUOTE in self.option_dict:
1176 str = output[LATEX][QUOTE] % vars ()
1179 def output_print_filename (self, format):
1181 if PRINTFILENAME in self.option_dict:
1182 base = self.basename ()
1183 filename = self.substring ('filename')
1184 str = output[global_options.format][PRINTFILENAME] % vars ()
1188 def output_texinfo (self):
1190 if self.output_print_filename (TEXINFO):
1192 + self.output_print_filename (HTML)
1195 + self.output_print_filename (LATEX)
1197 base = self.basename ()
1198 if TEXIDOC in self.option_dict:
1199 texidoc = base + '.texidoc'
1200 if os.path.exists (texidoc):
1201 str += '@include %(texidoc)s\n\n' % vars ()
1203 if VERBATIM in self.option_dict:
1204 verb = self.substring ('code')
1205 str += (output[TEXINFO][VERBATIM] % vars ())
1206 if not QUOTE in self.option_dict:
1207 str = output[TEXINFO][NOQUOTE] % vars ()
1209 str += self.output_info ()
1211 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1212 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1213 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1215 if QUOTE in self.option_dict:
1216 str = output[TEXINFO][QUOTE] % vars ()
1218 # need par after image
1223 class Lilypond_file_snippet (Lilypond_snippet):
1225 name = self.substring ('filename')
1226 return '\\sourcefilename \"%s\"\n%s' \
1227 % (name, open (find_file (name)).read ())
1229 snippet_type_to_class = {
1230 'lilypond_file': Lilypond_file_snippet,
1231 'lilypond_block': Lilypond_snippet,
1232 'lilypond': Lilypond_snippet,
1233 'include': Include_snippet,
1236 def find_linestarts (s):
1241 i = s.find ('\n', start)
1249 nls.append (len (s))
1252 def find_toplevel_snippets (s, types):
1255 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1259 ## found = dict (map (lambda x: (x, None),
1263 map (lambda x, f = found: f.setdefault (x, None),
1266 line_starts = find_linestarts (s)
1268 # We want to search for multiple regexes, without searching
1269 # the string multiple times for one regex.
1270 # Hence, we use earlier results to limit the string portion
1272 # Since every part of the string is traversed at most once for
1273 # every type of snippet, this is linear.
1279 if not found[type] or found[type][0] < index:
1282 m = res[type].search (s[index:endex])
1287 if snippet_type_to_class.has_key (type):
1288 cl = snippet_type_to_class[type]
1291 start = index + m.start ('match')
1292 line_number = line_start_idx
1293 while (line_starts[line_number] < start):
1297 snip = cl (type, m, global_options.format, line_number)
1299 found[type] = (start, snip)
1303 or found[type][0] < found[first][0]):
1308 # Limiting the search space is a cute
1309 # idea, but this *requires* to search
1310 # for possible containing blocks
1311 # first, at least as long as we do not
1312 # search for the start of blocks, but
1313 # always/directly for the entire
1314 # @block ... @end block.
1316 endex = found[first][0]
1319 snippets.append (Substring (s, index, len (s), line_start_idx))
1322 while (start > line_starts[line_start_idx+1]):
1325 (start, snip) = found[first]
1326 snippets.append (Substring (s, index, start, line_start_idx + 1))
1327 snippets.append (snip)
1329 index = start + len (snip.match.group ('match'))
1333 def filter_pipe (input, cmd):
1334 if global_options.verbose:
1335 progress (_ ("Opening filter `%s'") % cmd)
1337 (stdin, stdout, stderr) = os.popen3 (cmd)
1339 status = stdin.close ()
1343 output = stdout.read ()
1344 status = stdout.close ()
1345 error = stderr.read ()
1349 signal = 0x0f & status
1350 if status or (not output and error):
1351 exit_status = status >> 8
1352 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1353 error (_ ("The error log is as follows:"))
1354 sys.stderr.write (error)
1355 sys.stderr.write (stderr.read ())
1358 if global_options.verbose:
1364 return filter_pipe (s, global_options.filter_cmd)
1366 def is_derived_class (cl, baseclass):
1369 for b in cl.__bases__:
1370 if is_derived_class (b, baseclass):
1374 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1375 ly_names = filter (lambda x: x,
1376 map (Lilypond_snippet.basename, ly_snippets))
1377 texstr_names = filter (lambda x: x,
1378 map (Lilypond_snippet.basename, texstr_snippets))
1379 png_names = filter (lambda x: x,
1380 map (Lilypond_snippet.basename, png_snippets))
1383 def my_system (cmd):
1384 status = ly.system (cmd,
1385 be_verbose=global_options.verbose,
1389 # the --process=CMD switch is a bad idea
1390 # it is too generic for lilypond-book.
1392 my_system (string.join ([cmd, '--backend texstr',
1393 'snippet-map.ly'] + texstr_names))
1394 for l in texstr_names:
1395 my_system ('latex %s.texstr' % l)
1398 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1400 LATEX_INSPECTION_DOCUMENT = r'''
1404 \typeout{textwidth=\the\textwidth}
1405 \typeout{columnsep=\the\columnsep}
1406 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1410 # Do we need anything else besides `textwidth'?
1411 def get_latex_textwidth (source):
1412 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1414 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1416 ## what's a sensible default?
1419 preamble = source[:m.start (0)]
1420 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1422 (handle, tmpfile) = tempfile.mkstemp('.tex')
1423 logfile = os.path.splitext (tmpfile)[0] + '.log'
1424 logfile = os.path.split (logfile)[1]
1426 tmp_handle = os.fdopen (handle,'w')
1427 tmp_handle.write (latex_document)
1430 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1431 parameter_string = open (logfile).read()
1437 m = re.search ('columns=([0-9.]*)', parameter_string)
1439 columns = int (m.group (1))
1442 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1444 columnsep = float (m.group (1))
1447 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1449 textwidth = float (m.group (1))
1451 textwidth = (textwidth - columnsep) / columns
1455 def modify_preamble (chunk):
1456 str = chunk.replacement_text ()
1457 if (re.search (r"\\begin *{document}", str)
1458 and not re.search ("{graphic[sx]", str)):
1459 str = re.sub (r"\\begin{document}",
1460 r"\\usepackage{graphics}" + '\n'
1461 + r"\\begin{document}",
1463 chunk.override_text = str
1475 '.texinfo': TEXINFO,
1481 # TEXINFO: '.texinfo',
1486 class Compile_error:
1489 def write_file_map (lys, name):
1490 snippet_map = open ('snippet-map.ly', 'w')
1491 snippet_map.write ("""
1492 #(define version-seen? #t)
1493 #(ly:add-file-name-alist '(
1496 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1502 snippet_map.write ('))\n')
1504 def do_process_cmd (chunks, input_name):
1505 all_lys = filter (lambda x: is_derived_class (x.__class__,
1509 write_file_map (all_lys, input_name)
1511 filter (lambda x: is_derived_class (x.__class__,
1513 and x.ly_is_outdated (),
1516 filter (lambda x: is_derived_class (x.__class__,
1518 and x.texstr_is_outdated (),
1521 filter (lambda x: is_derived_class (x.__class__,
1523 and x.png_is_outdated (),
1526 progress (_ ("Writing snippets..."))
1527 map (Lilypond_snippet.write_ly, ly_outdated)
1531 progress (_ ("Processing..."))
1533 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1535 progress (_ ("All snippets are up to date..."))
1538 def guess_format (input_filename):
1540 e = os.path.splitext (input_filename)[1]
1541 if e in ext2format.keys ():
1543 format = ext2format[e]
1545 error (_ ("can't determine format for: %s" \
1550 def write_if_updated (file_name, lines):
1552 f = open (file_name)
1554 new_str = string.join (lines, '')
1555 if oldstr == new_str:
1556 progress (_ ("%s is up to date.") % file_name)
1562 progress (_ ("Writing `%s'...") % file_name)
1563 open (file_name, 'w').writelines (lines)
1566 def note_input_file (name, inputs=[]):
1567 ## hack: inputs is mutable!
1568 inputs.append (name)
1571 def samefile (f1, f2):
1573 return os.path.samefile (f1, f2)
1574 except AttributeError: # Windoze
1575 f1 = re.sub ("//*", "/", f1)
1576 f2 = re.sub ("//*", "/", f2)
1579 def do_file (input_filename):
1581 if not input_filename or input_filename == '-':
1582 in_handle = sys.stdin
1583 input_fullname = '<stdin>'
1585 if os.path.exists (input_filename):
1586 input_fullname = input_filename
1587 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1588 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1590 input_fullname = find_file (input_filename)
1592 note_input_file (input_fullname)
1593 in_handle = open (input_fullname)
1595 if input_filename == '-':
1596 input_base = 'stdin'
1598 input_base = os.path.basename \
1599 (os.path.splitext (input_filename)[0])
1601 # Only default to stdout when filtering.
1602 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1603 output_filename = '-'
1604 output_file = sys.stdout
1606 # don't complain when global_options.output_name is existing
1607 output_filename = input_base + format2ext[global_options.format]
1608 if global_options.output_name:
1609 if not os.path.isdir (global_options.output_name):
1610 os.mkdir (global_options.output_name, 0777)
1611 os.chdir (global_options.output_name)
1613 if os.path.exists (input_filename) \
1614 and os.path.exists (output_filename) \
1615 and samefile (output_filename, input_fullname):
1617 _ ("Output would overwrite input file; use --output."))
1621 progress (_ ("Reading %s...") % input_fullname)
1622 source = in_handle.read ()
1625 set_default_options (source)
1628 # FIXME: Containing blocks must be first, see
1629 # find_toplevel_snippets.
1631 'multiline_comment',
1635 'singleline_comment',
1640 progress (_ ("Dissecting..."))
1641 chunks = find_toplevel_snippets (source, snippet_types)
1643 if global_options.format == LATEX:
1645 if (c.is_plain () and
1646 re.search (r"\\begin *{document}", c.replacement_text())):
1651 if global_options.filter_cmd:
1652 write_if_updated (output_filename,
1653 [c.filter_text () for c in chunks])
1654 elif global_options.process_cmd:
1655 do_process_cmd (chunks, input_fullname)
1656 progress (_ ("Compiling %s...") % output_filename)
1658 write_if_updated (output_filename,
1659 [s.replacement_text ()
1662 def process_include (snippet):
1663 os.chdir (original_dir)
1664 name = snippet.substring ('filename')
1665 progress (_ ("Processing include: %s") % name)
1667 return do_file (name)
1669 include_chunks = map (process_include,
1670 filter (lambda x: is_derived_class (x.__class__,
1675 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1677 except Compile_error:
1678 os.chdir (original_dir)
1679 progress (_ ("Removing `%s'") % output_filename)
1685 global global_options
1687 opt_parser = get_option_parser()
1688 (global_options, args) = opt_parser.parse_args ()
1690 if global_options.format in ('texi-html', 'texi'):
1691 global_options.format = TEXINFO
1692 global_options.use_hash = True
1694 global_options.include_path = map (os.path.abspath, global_options.include_path)
1696 if global_options.warranty:
1699 if not args or len (args) > 1:
1700 opt_parser.print_help ()
1706 files = do_options ()
1710 basename = os.path.splitext (file)[0]
1711 basename = os.path.split (basename)[1]
1713 if not global_options.format:
1714 global_options.format = guess_format (files[0])
1717 if global_options.format in (TEXINFO, HTML):
1719 if global_options.process_cmd == '':
1720 global_options.process_cmd = lilypond_binary \
1721 + ' --formats=%s --backend eps ' % formats
1723 if global_options.process_cmd:
1724 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1725 for p in global_options.include_path])
1730 chunks = do_file (file)
1731 if global_options.psfonts:
1732 fontextract.verbose = global_options.verbose
1733 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1737 psfonts_file = basename + '.psfonts'
1738 if not global_options.verbose:
1739 progress (_ ("Writing fonts to %s...") % psfonts_file)
1740 fontextract.extract_fonts (psfonts_file,
1741 [x.basename() + '.eps'
1742 for x in snippet_chunks])
1743 if not global_options.verbose:
1746 except Compile_error:
1749 if global_options.format in (TEXINFO, LATEX):
1750 if not global_options.psfonts:
1751 warning (_ ("option --psfonts not used"))
1752 warning (_ ("processing with dvips will have no fonts"))
1754 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1755 output = os.path.join (global_options.output_name, basename + '.dvi' )
1758 progress (_ ("DVIPS usage:"))
1760 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1763 inputs = note_input_file ('')
1766 base_file_name = os.path.splitext (os.path.basename (file))[0]
1767 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1768 final_output_file = os.path.join (global_options.output_name,
1770 + '.%s' % global_options.format)
1772 os.chdir (original_dir)
1773 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1775 if __name__ == '__main__':