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')
122 sys.stdout.write ('''
129 ''' % ( _('Copyright (c) %s by') % '2001--2006',
131 _('Distributed under terms of the GNU General Public License.'),
132 _('It comes with NO WARRANTY.')))
135 def get_option_parser ():
136 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
137 version="@TOPLEVEL_VERSION@",
138 description=help_summary)
140 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
143 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
145 p.add_option ('-f', '--format', help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
147 p.add_option ("-I", '--include', help=_('add DIR to include path'),
149 action='append', dest='include_path',
150 default=[os.path.abspath (os.getcwd ())])
152 p.add_option ("-o", '--output', help=_('write output to DIR'),
154 action='store', dest='output_name', default=None)
155 p.add_option ('-P', '--process', metavar=_("COMMAND"),
156 help = _ ("process ly_files using COMMAND FILE..."),
158 dest='process_cmd', default='lilypond -b eps')
160 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
161 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
162 '''must use this with dvips -h INPUT.psfonts'''),
164 p.add_option ('-V', '--verbose', help=_("be verbose"),
169 p.add_option ('-w', '--warranty',
170 help=_("show warranty and copyright"),
174 p.add_option_group ('bugs',
175 description='''Report bugs via http://post.gmane.org/post.php'''
176 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
180 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
182 # Only use installed binary when we are installed too.
183 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
184 lilypond_binary = 'lilypond'
186 global_options = None
189 default_ly_options = { 'alt': "[image of music]" }
192 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
196 EXAMPLEINDENT = 'exampleindent'
198 FRAGMENT = 'fragment'
203 LINE_WIDTH = 'line-width'
204 NOFRAGMENT = 'nofragment'
205 NOINDENT = 'noindent'
210 OUTPUTIMAGE = 'outputimage'
213 PREAMBLE = 'preamble'
214 PRINTFILENAME = 'printfilename'
216 RAGGED_RIGHT = 'ragged-right'
217 RELATIVE = 'relative'
218 STAFFSIZE = 'staffsize'
221 VERBATIM = 'verbatim'
222 FONTLOAD = 'fontload'
223 FILENAME = 'filename'
227 # NOTIME has no opposite so it isn't part of this dictionary.
228 # NOQUOTE is used internally only.
230 NOFRAGMENT: FRAGMENT,
235 # Recognize special sequences in the input.
237 # (?P<name>regex) -- Assign result of REGEX to NAME.
238 # *? -- Match non-greedily.
239 # (?m) -- Multiline regex: Make ^ and $ match at each line.
240 # (?s) -- Make the dot match all characters including newline.
241 # (?x) -- Ignore whitespace in patterns.
253 (\s*(?P<options>.*?)\s*:)?\s*
261 \s*(?P<options>.*?)\s*
270 \s*(?P<options>.*?)\s*
272 \s*(?P<filename>.*?)\s*
279 (?P<code><!--\s.*?!-->)
282 'singleline_comment':
288 (?P<code><pre>.*?</pre>))''',
294 (?P<code><pre>\s.*?</pre>\s))''',
313 \s*(?P<options>.*?)\s*
324 \s*(?P<options>.*?)\s*
328 \\end\s*{lilypond})''',
336 \s*(?P<options>.*?)\s*
344 'singleline_comment':
367 \\end\s*{verbatim}))''',
376 (?P<filename>\S+))''',
380 ^[^\n]*?(?!@c\s+)[^\n]*?
384 \s*(?P<options>.*?)\s*
394 \s*(?P<options>.*?)\s*
397 ^@end\s+lilypond)\s''',
404 \s*(?P<options>.*?)\s*
415 @end\s+ignore))\s''',
417 'singleline_comment':
422 @c([ \t][^\n]*|)\n))''',
424 # Don't do this: It interferes with @code{@{}.
425 # 'verb': r'''(?P<code>@code{.*?})''',
433 @end\s+example\s))''',
442 'intertext': r',?\s*intertext=\".*?\"',
447 'intertext': r',?\s*intertext=\".*?\"',
448 'option_sep': '\s*,\s*',
452 'intertext': r',?\s*intertext=\".*?\"',
453 'option_sep': '\s*,\s*',
457 # Options without a pattern in ly_options.
474 RELATIVE: r'''\relative c%(relative_quotes)s''',
479 INDENT: r'''indent = %(indent)s''',
481 LINE_WIDTH: r'''line-width = %(line-width)s''',
483 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
485 RAGGED_RIGHT: r'''ragged-right = ##t''',
487 PACKED: r'''packed = ##t''',
499 \remove Time_signature_engraver
505 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
512 FILTER: r'''<lilypond %(options)s>
522 <a href="%(base)s.ly">''',
525 <img align="center" valign="center"
526 border="0" src="%(image)s" alt="%(alt)s">''',
528 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
530 QUOTE: r'''<blockquote>
544 \ifx\preLilyPondExample \undefined%%
547 \preLilyPondExample%%
549 \def\lilypondbook{}%%
550 \input %(base)s-systems.tex%%
551 \ifx\postLilyPondExample \undefined%%
554 \postLilyPondExample%%
558 PRINTFILENAME: '''\\texttt{%(filename)s}
561 QUOTE: r'''\begin{quotation}%(str)s
564 VERBATIM: r'''\noindent
565 \begin{verbatim}%(verb)s\end{verbatim}''',
567 FILTER: r'''\begin{lilypond}[%(options)s]
574 FILTER: r'''@lilypond[%(options)s]
580 @include %(base)s-systems.texi
584 OUTPUTIMAGE: r'''@noindent
586 @image{%(base)s,,,%(alt)s,%(ext)s}
590 <a href="%(base)s.ly">
591 <img align="center" valign="center"
592 border="0" src="%(image)s" alt="%(alt)s">
598 PRINTFILENAME: '''@file{%(filename)s}
601 QUOTE: r'''@quotation
602 %(str)s@end quotation
609 VERBATIM: r'''@exampleindent 0
617 # Maintain line numbers.
622 for f in [HTML, LATEX]:
623 for s in (QUOTE, VERBATIM):
624 output[f][s] = output[f][s].replace("\n"," ")
627 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
628 %%%% Options: [%(option_string)s]
630 #(set! toplevel-score-handler print-score-with-defaults)
631 #(set! toplevel-music-handler
633 (if (not (eq? (ly:music-property m \'void) #t))
634 (print-score-with-defaults
635 p (scorify-music m p)))))
637 #(ly:set-option (quote no-point-and-click))
638 #(define inside-lilypond-book #t)
639 #(define version-seen? #t)
647 %% ****************************************************************
648 %% Start cut-&-pastable-section
649 %% ****************************************************************
652 #(define dump-extents #t)
653 %(font_dump_setting)s
667 %% ****************************************************************
668 %% ly snippet contents follows:
669 %% ****************************************************************
673 %% ****************************************************************
675 %% ****************************************************************
682 %% ****************************************************************
684 %% ****************************************************************
688 %% ****************************************************************
690 %% ****************************************************************
693 texinfo_line_widths = {
694 '@afourpaper': '160\\mm',
695 '@afourwide': '6.5\\in',
696 '@afourlatex': '150\\mm',
697 '@smallbook': '5\\in',
698 '@letterpaper': '6\\in',
701 def classic_lilypond_book_compatibility (key, value):
702 if key == 'singleline' and value == None:
703 return (RAGGED_RIGHT, None)
705 m = re.search ('relative\s*([-0-9])', key)
707 return ('relative', m.group (1))
709 m = re.match ('([0-9]+)pt', key)
711 return ('staffsize', m.group (1))
713 if key == 'indent' or key == 'line-width':
714 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
716 f = float (m.group (1))
717 return (key, '%f\\%s' % (f, m.group (2)))
721 def find_file (name):
722 for i in global_options.include_path:
723 full = os.path.join (i, name)
724 if os.path.exists (full):
727 error (_ ("file not found: %s") % name + '\n')
731 def verbatim_html (s):
732 return re.sub ('>', '>',
734 re.sub ('&', '&', s)))
736 def verbatim_texinfo (s):
737 return re.sub ('{', '@{',
739 re.sub ('@', '@@', s)))
741 def split_options (option_string):
743 if global_options.format == HTML:
744 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
745 for i in range(len(options)):
746 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
749 return re.split (format_res[global_options.format]['option_sep'],
753 def set_default_options (source):
754 global default_ly_options
755 if not default_ly_options.has_key (LINE_WIDTH):
756 if global_options.format == LATEX:
757 textwidth = get_latex_textwidth (source)
758 default_ly_options[LINE_WIDTH] = \
759 '''%.0f\\pt''' % textwidth
760 elif global_options.format == TEXINFO:
761 for (k, v) in texinfo_line_widths.items ():
762 # FIXME: @layout is usually not in
765 # \input texinfo @c -*-texinfo-*-
767 # Bluntly search first K items of
769 # s = chunks[0].replacement_text ()
770 if re.search (k, source[:1024]):
771 default_ly_options[LINE_WIDTH] = v
775 def replacement_text (self):
778 def filter_text (self):
779 return self.replacement_text ()
781 def ly_is_outdated (self):
784 def png_is_outdated (self):
790 class Substring (Chunk):
791 def __init__ (self, source, start, end, line_number):
795 self.line_number = line_number
796 self.override_text = None
801 def replacement_text (self):
802 if self.override_text:
803 return self.override_text
805 return self.source[self.start:self.end]
807 class Snippet (Chunk):
808 def __init__ (self, type, match, format, line_number):
812 self.option_dict = {}
814 self.line_number = line_number
816 def replacement_text (self):
817 return self.match.group ('match')
819 def substring (self, s):
820 return self.match.group (s)
823 return `self.__class__` + ' type = ' + self.type
825 class Include_snippet (Snippet):
826 def processed_filename (self):
827 f = self.substring ('filename')
828 return os.path.splitext (f)[0] + format2ext[global_options.format]
830 def replacement_text (self):
831 s = self.match.group ('match')
832 f = self.substring ('filename')
834 return re.sub (f, self.processed_filename (), s)
836 class Lilypond_snippet (Snippet):
837 def __init__ (self, type, match, format, line_number):
838 Snippet.__init__ (self, type, match, format, line_number)
839 os = match.group ('options')
840 self.do_options (os, self.type)
843 return self.substring ('code')
848 return self.compose_ly (s)
851 def do_options (self, option_string, type):
852 self.option_dict = {}
854 options = split_options (option_string)
857 if string.find (i, '=') > 0:
858 (key, value) = re.split ('\s*=\s*', i)
859 self.option_dict[key] = value
861 if i in no_options.keys ():
862 if no_options[i] in self.option_dict.keys ():
863 del self.option_dict[no_options[i]]
865 self.option_dict[i] = None
867 has_line_width = self.option_dict.has_key (LINE_WIDTH)
868 no_line_width_value = 0
870 # If LINE_WIDTH is used without parameter, set it to default.
871 if has_line_width and self.option_dict[LINE_WIDTH] == None:
872 no_line_width_value = 1
873 del self.option_dict[LINE_WIDTH]
875 for i in default_ly_options.keys ():
876 if i not in self.option_dict.keys ():
877 self.option_dict[i] = default_ly_options[i]
879 if not has_line_width:
880 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
881 self.option_dict[RAGGED_RIGHT] = None
883 if type == 'lilypond':
884 if LINE_WIDTH in self.option_dict.keys ():
885 del self.option_dict[LINE_WIDTH]
887 if RAGGED_RIGHT in self.option_dict.keys ():
888 if LINE_WIDTH in self.option_dict.keys ():
889 del self.option_dict[LINE_WIDTH]
891 if QUOTE in self.option_dict.keys () or type == 'lilypond':
892 if LINE_WIDTH in self.option_dict.keys ():
893 del self.option_dict[LINE_WIDTH]
895 if not INDENT in self.option_dict.keys ():
896 self.option_dict[INDENT] = '0\\mm'
898 # The QUOTE pattern from ly_options only emits the `line-width'
900 if has_line_width and QUOTE in self.option_dict.keys ():
901 if no_line_width_value:
902 del self.option_dict[LINE_WIDTH]
904 del self.option_dict[QUOTE]
906 def compose_ly (self, code):
907 if FRAGMENT in self.option_dict.keys ():
915 # The original concept of the `exampleindent' option is broken.
916 # It is not possible to get a sane value for @exampleindent at all
917 # without processing the document itself. Saying
925 # causes ugly results with the DVI backend of texinfo since the
926 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
927 # value). Executing the above code changes the environment
928 # indentation to an unknown value because we don't know the amount
929 # of 1em in advance since it is font-dependent. Modifying
930 # @exampleindent in the middle of a document is simply not
931 # supported within texinfo.
933 # As a consequence, the only function of @exampleindent is now to
934 # specify the amount of indentation for the `quote' option.
936 # To set @exampleindent locally to zero, we use the @format
937 # environment for non-quoted snippets.
938 override[EXAMPLEINDENT] = r'0.4\in'
939 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
940 override.update (default_ly_options)
943 for (key, value) in self.option_dict.items ():
945 option_list.append (key)
947 option_list.append (key + '=' + value)
948 option_string = string.join (option_list, ',')
951 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
952 for a in compose_types:
955 for (key, value) in self.option_dict.items ():
957 classic_lilypond_book_compatibility (key, value)
961 (_ ("deprecated ly-option used: %s=%s" \
964 (_ ("compatibility mode translation: %s=%s" \
968 (_ ("deprecated ly-option used: %s" \
971 (_ ("compatibility mode translation: %s" \
974 (key, value) = (c_key, c_value)
977 override[key] = value
979 if not override.has_key (key):
983 for type in compose_types:
984 if ly_options[type].has_key (key):
985 compose_dict[type].append (ly_options[type][key])
989 if not found and key not in simple_options:
990 warning (_ ("ignoring unknown ly option: %s") % key)
993 if RELATIVE in override.keys () and override[RELATIVE]:
994 relative = int (override[RELATIVE])
1000 relative_quotes += ',' * (- relative)
1002 relative_quotes += "'" * relative
1004 paper_string = string.join (compose_dict[PAPER],
1006 layout_string = string.join (compose_dict[LAYOUT],
1008 notes_string = string.join (compose_dict[NOTES],
1010 preamble_string = string.join (compose_dict[PREAMBLE],
1013 font_dump_setting = ''
1014 if FONTLOAD in self.option_dict:
1015 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1017 d = globals().copy()
1019 return (PREAMBLE_LY + body) % d
1022 def get_hash (self):
1024 self.hash = abs (hash (self.full_ly ()))
1027 def basename (self):
1028 if FILENAME in self.option_dict:
1029 return self.option_dict[FILENAME]
1030 if global_options.use_hash:
1031 return 'lily-%d' % self.get_hash ()
1034 def write_ly (self):
1035 outf = open (self.basename () + '.ly', 'w')
1036 outf.write (self.full_ly ())
1038 open (self.basename () + '.txt', 'w').write ('image of music')
1040 def ly_is_outdated (self):
1041 base = self.basename ()
1043 tex_file = '%s.tex' % base
1044 eps_file = '%s.eps' % base
1045 system_file = '%s-systems.tex' % base
1046 ly_file = '%s.ly' % base
1047 ok = os.path.exists (ly_file) \
1048 and os.path.exists (system_file)\
1049 and os.stat (system_file)[stat.ST_SIZE] \
1050 and re.match ('% eof', open (system_file).readlines ()[-1])
1051 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1052 ok = (self.full_ly () == open (ly_file).read ())
1054 # TODO: Do something smart with target formats
1055 # (ps, png) and m/ctimes.
1059 def png_is_outdated (self):
1060 base = self.basename ()
1061 ok = self.ly_is_outdated ()
1062 if global_options.format in (HTML, TEXINFO):
1063 ok = ok and os.path.exists (base + '.eps')
1067 page_count = ly.ps_page_count (base + '.eps')
1070 ok = ok and os.path.exists (base + '.png')
1071 elif page_count > 1:
1072 for a in range (1, page_count + 1):
1073 ok = ok and os.path.exists (base + '-page%d.png' % a)
1077 def texstr_is_outdated (self):
1081 base = self.basename ()
1082 ok = self.ly_is_outdated ()
1083 ok = ok and (os.path.exists (base + '.texstr'))
1086 def filter_text (self):
1087 code = self.substring ('code')
1088 s = run_filter (code)
1091 'options': self.match.group ('options')
1094 return output[self.format][FILTER] % d
1096 def replacement_text (self):
1097 func = Lilypond_snippet.__dict__['output_' + self.format]
1100 def get_images (self):
1101 base = self.basename ()
1103 single = '%(base)s.png' % vars ()
1104 multiple = '%(base)s-page1.png' % vars ()
1106 if os.path.exists (multiple) \
1107 and (not os.path.exists (single) \
1108 or (os.stat (multiple)[stat.ST_MTIME] \
1109 > os.stat (single)[stat.ST_MTIME])):
1110 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1111 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1112 images = tuple (images)
1115 def output_html (self):
1117 base = self.basename ()
1118 if global_options.format == HTML:
1119 str += self.output_print_filename (HTML)
1120 if VERBATIM in self.option_dict:
1121 verb = verbatim_html (self.substring ('code'))
1122 str += output[HTML][VERBATIM] % vars ()
1123 if QUOTE in self.option_dict:
1124 str = output[HTML][QUOTE] % vars ()
1126 str += output[HTML][BEFORE] % vars ()
1127 for image in self.get_images ():
1128 (base, ext) = os.path.splitext (image)
1129 alt = self.option_dict[ALT]
1130 str += output[HTML][OUTPUT] % vars ()
1131 str += output[HTML][AFTER] % vars ()
1134 def output_info (self):
1136 for image in self.get_images ():
1137 (base, ext) = os.path.splitext (image)
1139 # URG, makeinfo implicitly prepends dot to extension.
1140 # Specifying no extension is most robust.
1142 alt = self.option_dict[ALT]
1143 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1145 base = self.basename ()
1146 str += output[global_options.format][OUTPUT] % vars ()
1149 def output_latex (self):
1151 base = self.basename ()
1152 if global_options.format == LATEX:
1153 str += self.output_print_filename (LATEX)
1154 if VERBATIM in self.option_dict:
1155 verb = self.substring ('code')
1156 str += (output[LATEX][VERBATIM] % vars ())
1158 str += (output[LATEX][OUTPUT] % vars ())
1160 ## todo: maintain breaks
1162 breaks = self.ly ().count ("\n")
1163 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1165 if QUOTE in self.option_dict:
1166 str = output[LATEX][QUOTE] % vars ()
1169 def output_print_filename (self, format):
1171 if PRINTFILENAME in self.option_dict:
1172 base = self.basename ()
1173 filename = self.substring ('filename')
1174 str = output[global_options.format][PRINTFILENAME] % vars ()
1178 def output_texinfo (self):
1180 if self.output_print_filename (TEXINFO):
1182 + self.output_print_filename (HTML)
1185 + self.output_print_filename (LATEX)
1187 base = self.basename ()
1188 if TEXIDOC in self.option_dict:
1189 texidoc = base + '.texidoc'
1190 if os.path.exists (texidoc):
1191 str += '@include %(texidoc)s\n\n' % vars ()
1193 if VERBATIM in self.option_dict:
1194 verb = verbatim_texinfo (self.substring ('code'))
1195 str += (output[TEXINFO][VERBATIM] % vars ())
1196 if not QUOTE in self.option_dict:
1197 str = output[TEXINFO][NOQUOTE] % vars ()
1199 str += self.output_info ()
1201 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1202 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1203 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1205 if QUOTE in self.option_dict:
1206 str = output[TEXINFO][QUOTE] % vars ()
1208 # need par after image
1213 class Lilypond_file_snippet (Lilypond_snippet):
1215 name = self.substring ('filename')
1216 return '\\sourcefilename \"%s\"\n%s' \
1217 % (name, open (find_file (name)).read ())
1219 snippet_type_to_class = {
1220 'lilypond_file': Lilypond_file_snippet,
1221 'lilypond_block': Lilypond_snippet,
1222 'lilypond': Lilypond_snippet,
1223 'include': Include_snippet,
1226 def find_linestarts (s):
1231 i = s.find ('\n', start)
1239 nls.append (len (s))
1242 def find_toplevel_snippets (s, types):
1245 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1249 ## found = dict (map (lambda x: (x, None),
1253 map (lambda x, f = found: f.setdefault (x, None),
1256 line_starts = find_linestarts (s)
1258 # We want to search for multiple regexes, without searching
1259 # the string multiple times for one regex.
1260 # Hence, we use earlier results to limit the string portion
1262 # Since every part of the string is traversed at most once for
1263 # every type of snippet, this is linear.
1269 if not found[type] or found[type][0] < index:
1272 m = res[type].search (s[index:endex])
1277 if snippet_type_to_class.has_key (type):
1278 cl = snippet_type_to_class[type]
1281 start = index + m.start ('match')
1282 line_number = line_start_idx
1283 while (line_starts[line_number] < start):
1287 snip = cl (type, m, global_options.format, line_number)
1289 found[type] = (start, snip)
1293 or found[type][0] < found[first][0]):
1298 # Limiting the search space is a cute
1299 # idea, but this *requires* to search
1300 # for possible containing blocks
1301 # first, at least as long as we do not
1302 # search for the start of blocks, but
1303 # always/directly for the entire
1304 # @block ... @end block.
1306 endex = found[first][0]
1309 snippets.append (Substring (s, index, len (s), line_start_idx))
1312 while (start > line_starts[line_start_idx+1]):
1315 (start, snip) = found[first]
1316 snippets.append (Substring (s, index, start, line_start_idx + 1))
1317 snippets.append (snip)
1319 index = start + len (snip.match.group ('match'))
1323 def filter_pipe (input, cmd):
1324 if global_options.verbose:
1325 progress (_ ("Opening filter `%s'") % cmd)
1327 (stdin, stdout, stderr) = os.popen3 (cmd)
1329 status = stdin.close ()
1333 output = stdout.read ()
1334 status = stdout.close ()
1335 error = stderr.read ()
1339 signal = 0x0f & status
1340 if status or (not output and error):
1341 exit_status = status >> 8
1342 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1343 error (_ ("The error log is as follows:"))
1344 sys.stderr.write (error)
1345 sys.stderr.write (stderr.read ())
1348 if global_options.verbose:
1354 return filter_pipe (s, global_options.filter_cmd)
1356 def is_derived_class (cl, baseclass):
1359 for b in cl.__bases__:
1360 if is_derived_class (b, baseclass):
1364 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1365 ly_names = filter (lambda x: x,
1366 map (Lilypond_snippet.basename, ly_snippets))
1367 texstr_names = filter (lambda x: x,
1368 map (Lilypond_snippet.basename, texstr_snippets))
1369 png_names = filter (lambda x: x,
1370 map (Lilypond_snippet.basename, png_snippets))
1373 def my_system (cmd):
1374 status = ly.system (cmd,
1375 ignore_error = 1, progress_p = 1)
1378 error ('Process %s exited unsuccessfully.' % cmd)
1382 # the --process=CMD switch is a bad idea
1383 # it is too generic for lilypond-book.
1385 my_system (string.join ([cmd, '--backend texstr',
1386 'snippet-map.ly'] + texstr_names))
1387 for l in texstr_names:
1388 my_system ('latex %s.texstr' % l)
1391 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1393 LATEX_INSPECTION_DOCUMENT = r'''
1397 \typeout{textwidth=\the\textwidth}
1398 \typeout{columnsep=\the\columnsep}
1399 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1403 # Do we need anything else besides `textwidth'?
1404 def get_latex_textwidth (source):
1405 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1406 preamble = source[:m.start (0)]
1407 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1409 (handle, tmpfile) = tempfile.mkstemp('.tex')
1410 logfile = os.path.splitext (tmpfile)[0] + '.log'
1411 open (tmpfile,'w').write (latex_document)
1412 ly.system ('latex %s' % tmpfile)
1413 parameter_string = open (logfile).read()
1419 m = re.search ('columns=([0-9.]*)', parameter_string)
1421 columns = int (m.group (1))
1424 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1426 columnsep = float (m.group (1))
1429 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1431 textwidth = float (m.group (1))
1433 textwidth = (textwidth - columnsep) / columns
1437 def modify_preamble (chunk):
1438 str = chunk.replacement_text ()
1439 if (re.search (r"\\begin *{document}", str)
1440 and not re.search ("{graphic[sx]", str)):
1441 str = re.sub (r"\\begin{document}",
1442 r"\\usepackage{graphics}" + '\n'
1443 + r"\\begin{document}",
1445 chunk.override_text = str
1457 '.texinfo': TEXINFO,
1463 # TEXINFO: '.texinfo',
1468 class Compile_error:
1471 def write_file_map (lys, name):
1472 snippet_map = open ('snippet-map.ly', 'w')
1473 snippet_map.write ("""
1474 #(define version-seen? #t)
1475 #(ly:add-file-name-alist '(
1478 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1484 snippet_map.write ('))\n')
1486 def do_process_cmd (chunks, input_name):
1487 all_lys = filter (lambda x: is_derived_class (x.__class__,
1491 write_file_map (all_lys, input_name)
1493 filter (lambda x: is_derived_class (x.__class__,
1495 and x.ly_is_outdated (),
1498 filter (lambda x: is_derived_class (x.__class__,
1500 and x.texstr_is_outdated (),
1503 filter (lambda x: is_derived_class (x.__class__,
1505 and x.png_is_outdated (),
1508 progress (_ ("Writing snippets..."))
1509 map (Lilypond_snippet.write_ly, ly_outdated)
1513 progress (_ ("Processing..."))
1515 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1517 progress (_ ("All snippets are up to date..."))
1520 def guess_format (input_filename):
1522 e = os.path.splitext (input_filename)[1]
1523 if e in ext2format.keys ():
1525 format = ext2format[e]
1527 error (_ ("can't determine format for: %s" \
1532 def write_if_updated (file_name, lines):
1534 f = open (file_name)
1536 new_str = string.join (lines, '')
1537 if oldstr == new_str:
1538 progress (_ ("%s is up to date.") % file_name)
1544 progress (_ ("Writing `%s'...") % file_name)
1545 open (file_name, 'w').writelines (lines)
1548 def note_input_file (name, inputs=[]):
1549 ## hack: inputs is mutable!
1550 inputs.append (name)
1553 def do_file (input_filename):
1555 if not input_filename or input_filename == '-':
1556 in_handle = sys.stdin
1557 input_fullname = '<stdin>'
1559 if os.path.exists (input_filename):
1560 input_fullname = input_filename
1561 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1562 input_fullname = os.read_pipe ('kpsewhich ' + input_filename).read()[:-1]
1564 input_fullname = find_file (input_filename)
1566 note_input_file (input_fullname)
1567 in_handle = open (input_fullname)
1569 if input_filename == '-':
1570 input_base = 'stdin'
1572 input_base = os.path.basename \
1573 (os.path.splitext (input_filename)[0])
1575 # Only default to stdout when filtering.
1576 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1577 output_filename = '-'
1578 output_file = sys.stdout
1580 # don't complain when global_options.output_name is existing
1581 output_filename = input_base + format2ext[global_options.format]
1582 if global_options.output_name:
1583 if not os.path.isdir (global_options.output_name):
1584 os.mkdir (global_options.output_name, 0777)
1585 os.chdir (global_options.output_name)
1587 if os.path.exists (input_filename) \
1588 and os.path.exists (output_filename) \
1589 and os.path.samefile (output_filename, input_fullname):
1591 _ ("Output would overwrite input file; use --output."))
1595 progress (_ ("Reading %s...") % input_fullname)
1596 source = in_handle.read ()
1599 set_default_options (source)
1602 # FIXME: Containing blocks must be first, see
1603 # find_toplevel_snippets.
1605 'multiline_comment',
1609 'singleline_comment',
1614 progress (_ ("Dissecting..."))
1615 chunks = find_toplevel_snippets (source, snippet_types)
1617 if global_options.format == LATEX:
1619 if (c.is_plain () and
1620 re.search (r"\\begin *{document}", c.replacement_text())):
1625 if global_options.filter_cmd:
1626 write_if_updated (output_filename,
1627 [c.filter_text () for c in chunks])
1628 elif global_options.process_cmd:
1629 do_process_cmd (chunks, input_fullname)
1630 progress (_ ("Compiling %s...") % output_filename)
1632 write_if_updated (output_filename,
1633 [s.replacement_text ()
1636 def process_include (snippet):
1637 os.chdir (original_dir)
1638 name = snippet.substring ('filename')
1639 progress (_ ("Processing include: %s") % name)
1641 return do_file (name)
1643 include_chunks = map (process_include,
1644 filter (lambda x: is_derived_class (x.__class__,
1649 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1651 except Compile_error:
1652 os.chdir (original_dir)
1653 progress (_ ("Removing `%s'") % output_filename)
1659 global global_options
1661 opt_parser = get_option_parser()
1662 (global_options, args) = opt_parser.parse_args ()
1664 if global_options.format in ('texi-html', 'texi'):
1665 global_options.format = TEXINFO
1666 global_options.use_hash = True
1668 global_options.include_path = map (os.path.abspath, global_options.include_path)
1670 if global_options.warranty:
1673 if not args or len (args) > 1:
1674 opt_parser.print_help ()
1680 files = do_options ()
1684 basename = os.path.splitext (file)[0]
1685 basename = os.path.split (basename)[1]
1687 if not global_options.format:
1688 global_options.format = guess_format (files[0])
1691 if global_options.format in (TEXINFO, HTML):
1693 if global_options.process_cmd == '':
1694 global_options.process_cmd = lilypond_binary \
1695 + ' --formats=%s --backend eps ' % formats
1697 if global_options.process_cmd:
1698 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1699 for p in global_options.include_path])
1704 chunks = do_file (file)
1705 if global_options.psfonts:
1706 fontextract.verbose = global_options.verbose
1707 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1711 psfonts_file = basename + '.psfonts'
1712 if not global_options.verbose:
1713 progress (_ ("Writing fonts to %s...") % psfonts_file)
1714 fontextract.extract_fonts (psfonts_file,
1715 [x.basename() + '.eps'
1716 for x in snippet_chunks])
1717 if not global_options.verbose:
1720 except Compile_error:
1723 if global_options.format in (TEXINFO, LATEX):
1724 if not global_options.psfonts:
1725 warning (_ ("option --psfonts not used"))
1726 warning (_ ("processing with dvips will have no fonts"))
1728 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1729 output = os.path.join (global_options.output_name, basename + '.dvi' )
1732 progress (_ ("DVIPS usage:"))
1734 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1737 inputs = note_input_file ('')
1740 base_file_name = os.path.splitext (os.path.basename (file))[0]
1741 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1742 final_output_file = os.path.join (global_options.output_name,
1744 + '.%s' % global_options.format)
1746 os.chdir (original_dir)
1747 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1749 if __name__ == '__main__':