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"), action="store_true",
167 p.add_option ('-w', '--warranty',
168 help=_("show warranty and copyright"),
172 p.add_option_group ('bugs',
173 description='''Report bugs via http://post.gmane.org/post.php'''
174 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
178 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
180 # Only use installed binary when we are installed too.
181 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
182 lilypond_binary = 'lilypond'
184 global_options = None
187 default_ly_options = { 'alt': "[image of music]" }
190 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
194 EXAMPLEINDENT = 'exampleindent'
196 FRAGMENT = 'fragment'
201 LINE_WIDTH = 'line-width'
202 NOFRAGMENT = 'nofragment'
203 NOINDENT = 'noindent'
208 OUTPUTIMAGE = 'outputimage'
211 PREAMBLE = 'preamble'
212 PRINTFILENAME = 'printfilename'
214 RAGGED_RIGHT = 'ragged-right'
215 RELATIVE = 'relative'
216 STAFFSIZE = 'staffsize'
219 VERBATIM = 'verbatim'
220 FONTLOAD = 'fontload'
221 FILENAME = 'filename'
225 # NOTIME has no opposite so it isn't part of this dictionary.
226 # NOQUOTE is used internally only.
228 NOFRAGMENT: FRAGMENT,
233 # Recognize special sequences in the input.
235 # (?P<name>regex) -- Assign result of REGEX to NAME.
236 # *? -- Match non-greedily.
237 # (?m) -- Multiline regex: Make ^ and $ match at each line.
238 # (?s) -- Make the dot match all characters including newline.
239 # (?x) -- Ignore whitespace in patterns.
251 (\s*(?P<options>.*?)\s*:)?\s*
259 \s*(?P<options>.*?)\s*
268 \s*(?P<options>.*?)\s*
270 \s*(?P<filename>.*?)\s*
277 (?P<code><!--\s.*?!-->)
280 'singleline_comment':
286 (?P<code><pre>.*?</pre>))''',
292 (?P<code><pre>\s.*?</pre>\s))''',
311 \s*(?P<options>.*?)\s*
322 \s*(?P<options>.*?)\s*
326 \\end\s*{lilypond})''',
334 \s*(?P<options>.*?)\s*
342 'singleline_comment':
365 \\end\s*{verbatim}))''',
374 (?P<filename>\S+))''',
378 ^[^\n]*?(?!@c\s+)[^\n]*?
382 \s*(?P<options>.*?)\s*
392 \s*(?P<options>.*?)\s*
395 ^@end\s+lilypond)\s''',
402 \s*(?P<options>.*?)\s*
413 @end\s+ignore))\s''',
415 'singleline_comment':
420 @c([ \t][^\n]*|)\n))''',
422 # Don't do this: It interferes with @code{@{}.
423 # 'verb': r'''(?P<code>@code{.*?})''',
431 @end\s+example\s))''',
440 'intertext': r',?\s*intertext=\".*?\"',
445 'intertext': r',?\s*intertext=\".*?\"',
446 'option_sep': '\s*,\s*',
450 'intertext': r',?\s*intertext=\".*?\"',
451 'option_sep': '\s*,\s*',
455 # Options without a pattern in ly_options.
472 RELATIVE: r'''\relative c%(relative_quotes)s''',
477 INDENT: r'''indent = %(indent)s''',
479 LINE_WIDTH: r'''line-width = %(line-width)s''',
481 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
483 RAGGED_RIGHT: r'''ragged-right = ##t''',
485 PACKED: r'''packed = ##t''',
497 \remove Time_signature_engraver
503 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
510 FILTER: r'''<lilypond %(options)s>
520 <a href="%(base)s.ly">''',
523 <img align="center" valign="center"
524 border="0" src="%(image)s" alt="%(alt)s">''',
526 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
528 QUOTE: r'''<blockquote>
542 \ifx\preLilyPondExample \undefined%%
545 \preLilyPondExample%%
547 \def\lilypondbook{}%%
548 \input %(base)s-systems.tex%%
549 \ifx\postLilyPondExample \undefined%%
552 \postLilyPondExample%%
556 PRINTFILENAME: '''\\texttt{%(filename)s}
559 QUOTE: r'''\begin{quotation}%(str)s
562 VERBATIM: r'''\noindent
563 \begin{verbatim}%(verb)s\end{verbatim}''',
565 FILTER: r'''\begin{lilypond}[%(options)s]
572 FILTER: r'''@lilypond[%(options)s]
578 @include %(base)s-systems.texi
582 OUTPUTIMAGE: r'''@noindent
584 @image{%(base)s,,,%(alt)s,%(ext)s}
588 <a href="%(base)s.ly">
589 <img align="center" valign="center"
590 border="0" src="%(image)s" alt="%(alt)s">
596 PRINTFILENAME: '''@file{%(filename)s}
599 QUOTE: r'''@quotation
600 %(str)s@end quotation
607 VERBATIM: r'''@exampleindent 0
615 # Maintain line numbers.
620 for f in [HTML, LATEX]:
621 for s in (QUOTE, VERBATIM):
622 output[f][s] = output[f][s].replace("\n"," ")
625 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
626 %%%% Options: [%(option_string)s]
628 #(set! toplevel-score-handler print-score-with-defaults)
629 #(set! toplevel-music-handler
631 (if (not (eq? (ly:music-property m \'void) #t))
632 (print-score-with-defaults
633 p (scorify-music m p)))))
635 #(ly:set-option (quote no-point-and-click))
636 #(define inside-lilypond-book #t)
637 #(define version-seen? #t)
645 %% ****************************************************************
646 %% Start cut-&-pastable-section
647 %% ****************************************************************
650 #(define dump-extents #t)
651 %(font_dump_setting)s
665 %% ****************************************************************
666 %% ly snippet contents follows:
667 %% ****************************************************************
671 %% ****************************************************************
673 %% ****************************************************************
680 %% ****************************************************************
682 %% ****************************************************************
686 %% ****************************************************************
688 %% ****************************************************************
691 texinfo_line_widths = {
692 '@afourpaper': '160\\mm',
693 '@afourwide': '6.5\\in',
694 '@afourlatex': '150\\mm',
695 '@smallbook': '5\\in',
696 '@letterpaper': '6\\in',
699 def classic_lilypond_book_compatibility (key, value):
700 if key == 'singleline' and value == None:
701 return (RAGGED_RIGHT, None)
703 m = re.search ('relative\s*([-0-9])', key)
705 return ('relative', m.group (1))
707 m = re.match ('([0-9]+)pt', key)
709 return ('staffsize', m.group (1))
711 if key == 'indent' or key == 'line-width':
712 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
714 f = float (m.group (1))
715 return (key, '%f\\%s' % (f, m.group (2)))
719 def find_file (name):
720 for i in global_options.include_path:
721 full = os.path.join (i, name)
722 if os.path.exists (full):
725 error (_ ("file not found: %s") % name + '\n')
729 def verbatim_html (s):
730 return re.sub ('>', '>',
732 re.sub ('&', '&', s)))
734 def verbatim_texinfo (s):
735 return re.sub ('{', '@{',
737 re.sub ('@', '@@', s)))
739 def split_options (option_string):
741 if global_options.format == HTML:
742 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
743 for i in range(len(options)):
744 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
747 return re.split (format_res[global_options.format]['option_sep'],
751 def set_default_options (source):
752 global default_ly_options
753 if not default_ly_options.has_key (LINE_WIDTH):
754 if global_options.format == LATEX:
755 textwidth = get_latex_textwidth (source)
756 default_ly_options[LINE_WIDTH] = \
757 '''%.0f\\pt''' % textwidth
758 elif global_options.format == TEXINFO:
759 for (k, v) in texinfo_line_widths.items ():
760 # FIXME: @layout is usually not in
763 # \input texinfo @c -*-texinfo-*-
765 # Bluntly search first K items of
767 # s = chunks[0].replacement_text ()
768 if re.search (k, source[:1024]):
769 default_ly_options[LINE_WIDTH] = v
773 def replacement_text (self):
776 def filter_text (self):
777 return self.replacement_text ()
779 def ly_is_outdated (self):
782 def png_is_outdated (self):
788 class Substring (Chunk):
789 def __init__ (self, source, start, end, line_number):
793 self.line_number = line_number
794 self.override_text = None
799 def replacement_text (self):
800 if self.override_text:
801 return self.override_text
803 return self.source[self.start:self.end]
805 class Snippet (Chunk):
806 def __init__ (self, type, match, format, line_number):
810 self.option_dict = {}
812 self.line_number = line_number
814 def replacement_text (self):
815 return self.match.group ('match')
817 def substring (self, s):
818 return self.match.group (s)
821 return `self.__class__` + ' type = ' + self.type
823 class Include_snippet (Snippet):
824 def processed_filename (self):
825 f = self.substring ('filename')
826 return os.path.splitext (f)[0] + format2ext[global_options.format]
828 def replacement_text (self):
829 s = self.match.group ('match')
830 f = self.substring ('filename')
832 return re.sub (f, self.processed_filename (), s)
834 class Lilypond_snippet (Snippet):
835 def __init__ (self, type, match, format, line_number):
836 Snippet.__init__ (self, type, match, format, line_number)
837 os = match.group ('options')
838 self.do_options (os, self.type)
841 return self.substring ('code')
846 return self.compose_ly (s)
849 def do_options (self, option_string, type):
850 self.option_dict = {}
852 options = split_options (option_string)
855 if string.find (i, '=') > 0:
856 (key, value) = re.split ('\s*=\s*', i)
857 self.option_dict[key] = value
859 if i in no_options.keys ():
860 if no_options[i] in self.option_dict.keys ():
861 del self.option_dict[no_options[i]]
863 self.option_dict[i] = None
865 has_line_width = self.option_dict.has_key (LINE_WIDTH)
866 no_line_width_value = 0
868 # If LINE_WIDTH is used without parameter, set it to default.
869 if has_line_width and self.option_dict[LINE_WIDTH] == None:
870 no_line_width_value = 1
871 del self.option_dict[LINE_WIDTH]
873 for i in default_ly_options.keys ():
874 if i not in self.option_dict.keys ():
875 self.option_dict[i] = default_ly_options[i]
877 if not has_line_width:
878 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
879 self.option_dict[RAGGED_RIGHT] = None
881 if type == 'lilypond':
882 if LINE_WIDTH in self.option_dict.keys ():
883 del self.option_dict[LINE_WIDTH]
885 if RAGGED_RIGHT in self.option_dict.keys ():
886 if LINE_WIDTH in self.option_dict.keys ():
887 del self.option_dict[LINE_WIDTH]
889 if QUOTE in self.option_dict.keys () or type == 'lilypond':
890 if LINE_WIDTH in self.option_dict.keys ():
891 del self.option_dict[LINE_WIDTH]
893 if not INDENT in self.option_dict.keys ():
894 self.option_dict[INDENT] = '0\\mm'
896 # The QUOTE pattern from ly_options only emits the `line-width'
898 if has_line_width and QUOTE in self.option_dict.keys ():
899 if no_line_width_value:
900 del self.option_dict[LINE_WIDTH]
902 del self.option_dict[QUOTE]
904 def compose_ly (self, code):
905 if FRAGMENT in self.option_dict.keys ():
913 # The original concept of the `exampleindent' option is broken.
914 # It is not possible to get a sane value for @exampleindent at all
915 # without processing the document itself. Saying
923 # causes ugly results with the DVI backend of texinfo since the
924 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
925 # value). Executing the above code changes the environment
926 # indentation to an unknown value because we don't know the amount
927 # of 1em in advance since it is font-dependent. Modifying
928 # @exampleindent in the middle of a document is simply not
929 # supported within texinfo.
931 # As a consequence, the only function of @exampleindent is now to
932 # specify the amount of indentation for the `quote' option.
934 # To set @exampleindent locally to zero, we use the @format
935 # environment for non-quoted snippets.
936 override[EXAMPLEINDENT] = r'0.4\in'
937 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
938 override.update (default_ly_options)
941 for (key, value) in self.option_dict.items ():
943 option_list.append (key)
945 option_list.append (key + '=' + value)
946 option_string = string.join (option_list, ',')
949 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
950 for a in compose_types:
953 for (key, value) in self.option_dict.items ():
955 classic_lilypond_book_compatibility (key, value)
959 (_ ("deprecated ly-option used: %s=%s" \
962 (_ ("compatibility mode translation: %s=%s" \
966 (_ ("deprecated ly-option used: %s" \
969 (_ ("compatibility mode translation: %s" \
972 (key, value) = (c_key, c_value)
975 override[key] = value
977 if not override.has_key (key):
981 for type in compose_types:
982 if ly_options[type].has_key (key):
983 compose_dict[type].append (ly_options[type][key])
987 if not found and key not in simple_options:
988 warning (_ ("ignoring unknown ly option: %s") % key)
991 if RELATIVE in override.keys () and override[RELATIVE]:
992 relative = int (override[RELATIVE])
998 relative_quotes += ',' * (- relative)
1000 relative_quotes += "'" * relative
1002 paper_string = string.join (compose_dict[PAPER],
1004 layout_string = string.join (compose_dict[LAYOUT],
1006 notes_string = string.join (compose_dict[NOTES],
1008 preamble_string = string.join (compose_dict[PREAMBLE],
1011 font_dump_setting = ''
1012 if FONTLOAD in self.option_dict:
1013 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1015 d = globals().copy()
1017 return (PREAMBLE_LY + body) % d
1020 def get_hash (self):
1022 self.hash = abs (hash (self.full_ly ()))
1025 def basename (self):
1026 if FILENAME in self.option_dict:
1027 return self.option_dict[FILENAME]
1028 if global_options.use_hash:
1029 return 'lily-%d' % self.get_hash ()
1032 def write_ly (self):
1033 outf = open (self.basename () + '.ly', 'w')
1034 outf.write (self.full_ly ())
1036 open (self.basename () + '.txt', 'w').write ('image of music')
1038 def ly_is_outdated (self):
1039 base = self.basename ()
1041 tex_file = '%s.tex' % base
1042 eps_file = '%s.eps' % base
1043 system_file = '%s-systems.tex' % base
1044 ly_file = '%s.ly' % base
1045 ok = os.path.exists (ly_file) \
1046 and os.path.exists (system_file)\
1047 and os.stat (system_file)[stat.ST_SIZE] \
1048 and re.match ('% eof', open (system_file).readlines ()[-1])
1049 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1050 ok = (self.full_ly () == open (ly_file).read ())
1052 # TODO: Do something smart with target formats
1053 # (ps, png) and m/ctimes.
1057 def png_is_outdated (self):
1058 base = self.basename ()
1059 ok = self.ly_is_outdated ()
1060 if global_options.format in (HTML, TEXINFO):
1061 ok = ok and os.path.exists (base + '.eps')
1065 page_count = ly.ps_page_count (base + '.eps')
1068 ok = ok and os.path.exists (base + '.png')
1069 elif page_count > 1:
1070 for a in range (1, page_count + 1):
1071 ok = ok and os.path.exists (base + '-page%d.png' % a)
1075 def texstr_is_outdated (self):
1079 base = self.basename ()
1080 ok = self.ly_is_outdated ()
1081 ok = ok and (os.path.exists (base + '.texstr'))
1084 def filter_text (self):
1085 code = self.substring ('code')
1086 s = run_filter (code)
1089 'options': self.match.group ('options')
1092 return output[self.format][FILTER] % d
1094 def replacement_text (self):
1095 func = Lilypond_snippet.__dict__['output_' + self.format]
1098 def get_images (self):
1099 base = self.basename ()
1101 single = '%(base)s.png' % vars ()
1102 multiple = '%(base)s-page1.png' % vars ()
1104 if os.path.exists (multiple) \
1105 and (not os.path.exists (single) \
1106 or (os.stat (multiple)[stat.ST_MTIME] \
1107 > os.stat (single)[stat.ST_MTIME])):
1108 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1109 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1110 images = tuple (images)
1113 def output_html (self):
1115 base = self.basename ()
1116 if global_options.format == HTML:
1117 str += self.output_print_filename (HTML)
1118 if VERBATIM in self.option_dict:
1119 verb = verbatim_html (self.substring ('code'))
1120 str += output[HTML][VERBATIM] % vars ()
1121 if QUOTE in self.option_dict:
1122 str = output[HTML][QUOTE] % vars ()
1124 str += output[HTML][BEFORE] % vars ()
1125 for image in self.get_images ():
1126 (base, ext) = os.path.splitext (image)
1127 alt = self.option_dict[ALT]
1128 str += output[HTML][OUTPUT] % vars ()
1129 str += output[HTML][AFTER] % vars ()
1132 def output_info (self):
1134 for image in self.get_images ():
1135 (base, ext) = os.path.splitext (image)
1137 # URG, makeinfo implicitly prepends dot to extension.
1138 # Specifying no extension is most robust.
1140 alt = self.option_dict[ALT]
1141 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1143 base = self.basename ()
1144 str += output[global_options.format][OUTPUT] % vars ()
1147 def output_latex (self):
1149 base = self.basename ()
1150 if global_options.format == LATEX:
1151 str += self.output_print_filename (LATEX)
1152 if VERBATIM in self.option_dict:
1153 verb = self.substring ('code')
1154 str += (output[LATEX][VERBATIM] % vars ())
1156 str += (output[LATEX][OUTPUT] % vars ())
1158 ## todo: maintain breaks
1160 breaks = self.ly ().count ("\n")
1161 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1163 if QUOTE in self.option_dict:
1164 str = output[LATEX][QUOTE] % vars ()
1167 def output_print_filename (self, format):
1169 if PRINTFILENAME in self.option_dict:
1170 base = self.basename ()
1171 filename = self.substring ('filename')
1172 str = output[global_options.format][PRINTFILENAME] % vars ()
1176 def output_texinfo (self):
1178 if self.output_print_filename (TEXINFO):
1180 + self.output_print_filename (HTML)
1183 + self.output_print_filename (LATEX)
1185 base = self.basename ()
1186 if TEXIDOC in self.option_dict:
1187 texidoc = base + '.texidoc'
1188 if os.path.exists (texidoc):
1189 str += '@include %(texidoc)s\n\n' % vars ()
1191 if VERBATIM in self.option_dict:
1192 verb = verbatim_texinfo (self.substring ('code'))
1193 str += (output[TEXINFO][VERBATIM] % vars ())
1194 if not QUOTE in self.option_dict:
1195 str = output[TEXINFO][NOQUOTE] % vars ()
1197 str += self.output_info ()
1199 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1200 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1201 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1203 if QUOTE in self.option_dict:
1204 str = output[TEXINFO][QUOTE] % vars ()
1206 # need par after image
1211 class Lilypond_file_snippet (Lilypond_snippet):
1213 name = self.substring ('filename')
1214 return '\\sourcefilename \"%s\"\n%s' \
1215 % (name, open (find_file (name)).read ())
1217 snippet_type_to_class = {
1218 'lilypond_file': Lilypond_file_snippet,
1219 'lilypond_block': Lilypond_snippet,
1220 'lilypond': Lilypond_snippet,
1221 'include': Include_snippet,
1224 def find_linestarts (s):
1229 i = s.find ('\n', start)
1237 nls.append (len (s))
1240 def find_toplevel_snippets (s, types):
1243 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1247 ## found = dict (map (lambda x: (x, None),
1251 map (lambda x, f = found: f.setdefault (x, None),
1254 line_starts = find_linestarts (s)
1256 # We want to search for multiple regexes, without searching
1257 # the string multiple times for one regex.
1258 # Hence, we use earlier results to limit the string portion
1260 # Since every part of the string is traversed at most once for
1261 # every type of snippet, this is linear.
1267 if not found[type] or found[type][0] < index:
1270 m = res[type].search (s[index:endex])
1275 if snippet_type_to_class.has_key (type):
1276 cl = snippet_type_to_class[type]
1279 start = index + m.start ('match')
1280 line_number = line_start_idx
1281 while (line_starts[line_number] < start):
1285 snip = cl (type, m, global_options.format, line_number)
1287 found[type] = (start, snip)
1291 or found[type][0] < found[first][0]):
1296 # Limiting the search space is a cute
1297 # idea, but this *requires* to search
1298 # for possible containing blocks
1299 # first, at least as long as we do not
1300 # search for the start of blocks, but
1301 # always/directly for the entire
1302 # @block ... @end block.
1304 endex = found[first][0]
1307 snippets.append (Substring (s, index, len (s), line_start_idx))
1310 while (start > line_starts[line_start_idx+1]):
1313 (start, snip) = found[first]
1314 snippets.append (Substring (s, index, start, line_start_idx + 1))
1315 snippets.append (snip)
1317 index = start + len (snip.match.group ('match'))
1321 def filter_pipe (input, cmd):
1322 if global_options.verbose:
1323 progress (_ ("Opening filter `%s'") % cmd)
1325 (stdin, stdout, stderr) = os.popen3 (cmd)
1327 status = stdin.close ()
1331 output = stdout.read ()
1332 status = stdout.close ()
1333 error = stderr.read ()
1337 signal = 0x0f & status
1338 if status or (not output and error):
1339 exit_status = status >> 8
1340 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1341 error (_ ("The error log is as follows:"))
1342 sys.stderr.write (error)
1343 sys.stderr.write (stderr.read ())
1346 if global_options.verbose:
1352 return filter_pipe (s, global_options.filter_cmd)
1354 def is_derived_class (cl, baseclass):
1357 for b in cl.__bases__:
1358 if is_derived_class (b, baseclass):
1362 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1363 ly_names = filter (lambda x: x,
1364 map (Lilypond_snippet.basename, ly_snippets))
1365 texstr_names = filter (lambda x: x,
1366 map (Lilypond_snippet.basename, texstr_snippets))
1367 png_names = filter (lambda x: x,
1368 map (Lilypond_snippet.basename, png_snippets))
1371 def my_system (cmd):
1372 status = ly.system (cmd,
1373 ignore_error = 1, progress_p = 1)
1376 error ('Process %s exited unsuccessfully.' % cmd)
1380 # the --process=CMD switch is a bad idea
1381 # it is too generic for lilypond-book.
1383 my_system (string.join ([cmd, '--backend texstr',
1384 'snippet-map.ly'] + texstr_names))
1385 for l in texstr_names:
1386 my_system ('latex %s.texstr' % l)
1389 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1391 LATEX_INSPECTION_DOCUMENT = r'''
1395 \typeout{textwidth=\the\textwidth}
1396 \typeout{columnsep=\the\columnsep}
1397 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1401 # Do we need anything else besides `textwidth'?
1402 def get_latex_textwidth (source):
1403 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1404 preamble = source[:m.start (0)]
1405 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1407 (handle, tmpfile) = tempfile.mkstemp('.tex')
1408 logfile = os.path.splitext (tmpfile)[0] + '.log'
1409 open (tmpfile,'w').write (latex_document)
1410 ly.system ('latex %s' % tmpfile)
1411 parameter_string = open (logfile).read()
1417 m = re.search ('columns=([0-9.]*)', parameter_string)
1419 columns = int (m.group (1))
1422 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1424 columnsep = float (m.group (1))
1427 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1429 textwidth = float (m.group (1))
1431 textwidth = (textwidth - columnsep) / columns
1435 def modify_preamble (chunk):
1436 str = chunk.replacement_text ()
1437 if (re.search (r"\\begin *{document}", str)
1438 and not re.search ("{graphic[sx]", str)):
1439 str = re.sub (r"\\begin{document}",
1440 r"\\usepackage{graphics}" + '\n'
1441 + r"\\begin{document}",
1443 chunk.override_text = str
1455 '.texinfo': TEXINFO,
1461 # TEXINFO: '.texinfo',
1466 class Compile_error:
1469 def write_file_map (lys, name):
1470 snippet_map = open ('snippet-map.ly', 'w')
1471 snippet_map.write ("""
1472 #(define version-seen? #t)
1473 #(ly:add-file-name-alist '(
1476 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1482 snippet_map.write ('))\n')
1484 def do_process_cmd (chunks, input_name):
1485 all_lys = filter (lambda x: is_derived_class (x.__class__,
1489 write_file_map (all_lys, input_name)
1491 filter (lambda x: is_derived_class (x.__class__,
1493 and x.ly_is_outdated (),
1496 filter (lambda x: is_derived_class (x.__class__,
1498 and x.texstr_is_outdated (),
1501 filter (lambda x: is_derived_class (x.__class__,
1503 and x.png_is_outdated (),
1506 progress (_ ("Writing snippets..."))
1507 map (Lilypond_snippet.write_ly, ly_outdated)
1511 progress (_ ("Processing..."))
1513 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1515 progress (_ ("All snippets are up to date..."))
1518 def guess_format (input_filename):
1520 e = os.path.splitext (input_filename)[1]
1521 if e in ext2format.keys ():
1523 format = ext2format[e]
1525 error (_ ("can't determine format for: %s" \
1530 def write_if_updated (file_name, lines):
1532 f = open (file_name)
1534 new_str = string.join (lines, '')
1535 if oldstr == new_str:
1536 progress (_ ("%s is up to date.") % file_name)
1542 progress (_ ("Writing `%s'...") % file_name)
1543 open (file_name, 'w').writelines (lines)
1546 def note_input_file (name, inputs=[]):
1547 ## hack: inputs is mutable!
1548 inputs.append (name)
1551 def do_file (input_filename):
1553 if not input_filename or input_filename == '-':
1554 in_handle = sys.stdin
1555 input_fullname = '<stdin>'
1557 if os.path.exists (input_filename):
1558 input_fullname = input_filename
1559 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1560 input_fullname = os.read_pipe ('kpsewhich ' + input_filename).read()[:-1]
1562 input_fullname = find_file (input_filename)
1564 note_input_file (input_fullname)
1565 in_handle = open (input_fullname)
1567 if input_filename == '-':
1568 input_base = 'stdin'
1570 input_base = os.path.basename \
1571 (os.path.splitext (input_filename)[0])
1573 # Only default to stdout when filtering.
1574 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1575 output_filename = '-'
1576 output_file = sys.stdout
1578 # don't complain when global_options.output_name is existing
1579 output_filename = input_base + format2ext[global_options.format]
1580 if global_options.output_name:
1581 if not os.path.isdir (global_options.output_name):
1582 os.mkdir (global_options.output_name, 0777)
1583 os.chdir (global_options.output_name)
1585 if os.path.exists (input_filename) \
1586 and os.path.exists (output_filename) \
1587 and os.path.samefile (output_filename, input_fullname):
1589 _ ("Output would overwrite input file; use --output."))
1593 progress (_ ("Reading %s...") % input_fullname)
1594 source = in_handle.read ()
1597 set_default_options (source)
1600 # FIXME: Containing blocks must be first, see
1601 # find_toplevel_snippets.
1603 'multiline_comment',
1607 'singleline_comment',
1612 progress (_ ("Dissecting..."))
1613 chunks = find_toplevel_snippets (source, snippet_types)
1615 if global_options.format == LATEX:
1617 if (c.is_plain () and
1618 re.search (r"\\begin *{document}", c.replacement_text())):
1623 if global_options.filter_cmd:
1624 write_if_updated (output_filename,
1625 [c.filter_text () for c in chunks])
1626 elif global_options.process_cmd:
1627 do_process_cmd (chunks, input_fullname)
1628 progress (_ ("Compiling %s...") % output_filename)
1630 write_if_updated (output_filename,
1631 [s.replacement_text ()
1634 def process_include (snippet):
1635 os.chdir (original_dir)
1636 name = snippet.substring ('filename')
1637 progress (_ ("Processing include: %s") % name)
1639 return do_file (name)
1641 include_chunks = map (process_include,
1642 filter (lambda x: is_derived_class (x.__class__,
1647 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1649 except Compile_error:
1650 os.chdir (original_dir)
1651 progress (_ ("Removing `%s'") % output_filename)
1656 opt_parser = get_option_parser()
1657 (options, args) = opt_parser.parse_args ()
1659 if options.format in ('texi-html', 'texi'):
1660 options.format = TEXINFO
1661 options.use_hash = True
1663 options.include_path = map (os.path.abspath, options.include_path)
1665 global global_options
1666 global_options = options
1670 files = do_options ()
1671 if not files or len (files) > 1:
1677 basename = os.path.splitext (file)[0]
1678 basename = os.path.split (basename)[1]
1680 if not global_options.format:
1681 global_options.format = guess_format (files[0])
1684 if global_options.format in (TEXINFO, HTML):
1686 if global_options.process_cmd == '':
1687 global_options.process_cmd = lilypond_binary \
1688 + ' --formats=%s --backend eps ' % formats
1690 if global_options.process_cmd:
1691 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1692 for p in global_options.include_path])
1697 chunks = do_file (file)
1698 if global_options.psfonts:
1699 fontextract.verbose = global_options.verbose
1700 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1704 psfonts_file = basename + '.psfonts'
1705 if not global_options.verbose:
1706 progress (_ ("Writing fonts to %s...") % psfonts_file)
1707 fontextract.extract_fonts (psfonts_file,
1708 [x.basename() + '.eps'
1709 for x in snippet_chunks])
1710 if not global_options.verbose:
1713 except Compile_error:
1716 if global_options.format in (TEXINFO, LATEX):
1717 if not global_options.psfonts:
1718 warning (_ ("option --psfonts not used"))
1719 warning (_ ("processing with dvips will have no fonts"))
1721 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1722 output = os.path.join (global_options.output_name, basename + '.dvi' )
1725 progress (_ ("DVIPS usage:"))
1727 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1730 inputs = note_input_file ('')
1733 base_file_name = os.path.splitext (os.path.basename (file))[0]
1734 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1735 final_output_file = os.path.join (global_options.output_name,
1737 + '.%s' % global_options.format)
1739 os.chdir (original_dir)
1740 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1742 if __name__ == '__main__':