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>')
102 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
106 sys.stdout.write ('''
113 ''' ( _('Copyright (c) %s by') % '2001--2006',
115 _('Distributed under terms of the GNU General Public License.'),
116 _('It comes with NO WARRANTY.')))
119 def get_option_parser ():
120 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
121 version="@TOPLEVEL_VERSION@",
122 description=help_summary)
124 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
127 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
129 p.add_option ('-f', '--format', help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
131 p.add_option ("-I", '--include', help=_('add DIR to include path'),
133 action='append', dest='include_path',
134 default=[os.path.abspath (os.getcwd ())])
136 p.add_option ("-o", '--output', help=_('write output to DIR'),
138 action='store', dest='output_name', default=None)
139 p.add_option ('-P', '--process', metavar=_("COMMAND"),
140 help = _ ("process ly_files using COMMAND FILE..."),
142 dest='process_cmd', default='lilypond -b eps')
144 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
145 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
146 '''must use this with dvips -h INPUT.psfonts'''),
148 p.add_option ('-V', '--verbose', help=_("be verbose"), action="store_true",
151 p.add_option ('-w', '--warranty',
152 help=_("show warranty and copyright"),
156 p.add_option_group ('bugs',
157 description='''Report bugs via http://post.gmane.org/post.php'''
158 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
162 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
164 # Only use installed binary when we are installed too.
165 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
166 lilypond_binary = 'lilypond'
168 global_options = None
171 default_ly_options = { 'alt': "[image of music]" }
174 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
178 EXAMPLEINDENT = 'exampleindent'
180 FRAGMENT = 'fragment'
185 LINE_WIDTH = 'line-width'
186 NOFRAGMENT = 'nofragment'
187 NOINDENT = 'noindent'
192 OUTPUTIMAGE = 'outputimage'
195 PREAMBLE = 'preamble'
196 PRINTFILENAME = 'printfilename'
198 RAGGED_RIGHT = 'ragged-right'
199 RELATIVE = 'relative'
200 STAFFSIZE = 'staffsize'
203 VERBATIM = 'verbatim'
204 FONTLOAD = 'fontload'
205 FILENAME = 'filename'
209 # NOTIME has no opposite so it isn't part of this dictionary.
210 # NOQUOTE is used internally only.
212 NOFRAGMENT: FRAGMENT,
217 # Recognize special sequences in the input.
219 # (?P<name>regex) -- Assign result of REGEX to NAME.
220 # *? -- Match non-greedily.
221 # (?m) -- Multiline regex: Make ^ and $ match at each line.
222 # (?s) -- Make the dot match all characters including newline.
223 # (?x) -- Ignore whitespace in patterns.
235 (\s*(?P<options>.*?)\s*:)?\s*
243 \s*(?P<options>.*?)\s*
252 \s*(?P<options>.*?)\s*
254 \s*(?P<filename>.*?)\s*
261 (?P<code><!--\s.*?!-->)
264 'singleline_comment':
270 (?P<code><pre>.*?</pre>))''',
276 (?P<code><pre>\s.*?</pre>\s))''',
295 \s*(?P<options>.*?)\s*
306 \s*(?P<options>.*?)\s*
310 \\end\s*{lilypond})''',
318 \s*(?P<options>.*?)\s*
326 'singleline_comment':
349 \\end\s*{verbatim}))''',
358 (?P<filename>\S+))''',
362 ^[^\n]*?(?!@c\s+)[^\n]*?
366 \s*(?P<options>.*?)\s*
376 \s*(?P<options>.*?)\s*
379 ^@end\s+lilypond)\s''',
386 \s*(?P<options>.*?)\s*
397 @end\s+ignore))\s''',
399 'singleline_comment':
404 @c([ \t][^\n]*|)\n))''',
406 # Don't do this: It interferes with @code{@{}.
407 # 'verb': r'''(?P<code>@code{.*?})''',
415 @end\s+example\s))''',
424 'intertext': r',?\s*intertext=\".*?\"',
429 'intertext': r',?\s*intertext=\".*?\"',
430 'option_sep': '\s*,\s*',
434 'intertext': r',?\s*intertext=\".*?\"',
435 'option_sep': '\s*,\s*',
439 # Options without a pattern in ly_options.
456 RELATIVE: r'''\relative c%(relative_quotes)s''',
461 INDENT: r'''indent = %(indent)s''',
463 LINE_WIDTH: r'''line-width = %(line-width)s''',
465 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
467 RAGGED_RIGHT: r'''ragged-right = ##t''',
469 PACKED: r'''packed = ##t''',
481 \remove Time_signature_engraver
487 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
494 FILTER: r'''<lilypond %(options)s>
504 <a href="%(base)s.ly">''',
507 <img align="center" valign="center"
508 border="0" src="%(image)s" alt="%(alt)s">''',
510 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
512 QUOTE: r'''<blockquote>
526 \ifx\preLilyPondExample \undefined%%
529 \preLilyPondExample%%
531 \def\lilypondbook{}%%
532 \input %(base)s-systems.tex%%
533 \ifx\postLilyPondExample \undefined%%
536 \postLilyPondExample%%
540 PRINTFILENAME: '''\\texttt{%(filename)s}
543 QUOTE: r'''\begin{quotation}%(str)s
546 VERBATIM: r'''\noindent
547 \begin{verbatim}%(verb)s\end{verbatim}''',
549 FILTER: r'''\begin{lilypond}[%(options)s]
556 FILTER: r'''@lilypond[%(options)s]
562 @include %(base)s-systems.texi
566 OUTPUTIMAGE: r'''@noindent
568 @image{%(base)s,,,%(alt)s,%(ext)s}
572 <a href="%(base)s.ly">
573 <img align="center" valign="center"
574 border="0" src="%(image)s" alt="%(alt)s">
580 PRINTFILENAME: '''@file{%(filename)s}
583 QUOTE: r'''@quotation
584 %(str)s@end quotation
591 VERBATIM: r'''@exampleindent 0
599 # Maintain line numbers.
604 for f in [HTML, LATEX]:
605 for s in (QUOTE, VERBATIM):
606 output[f][s] = output[f][s].replace("\n"," ")
609 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
610 %%%% Options: [%(option_string)s]
612 #(set! toplevel-score-handler print-score-with-defaults)
613 #(set! toplevel-music-handler
615 (if (not (eq? (ly:music-property m \'void) #t))
616 (print-score-with-defaults
617 p (scorify-music m p)))))
619 #(ly:set-option (quote no-point-and-click))
620 #(define inside-lilypond-book #t)
621 #(define version-seen? #t)
629 %% ****************************************************************
630 %% Start cut-&-pastable-section
631 %% ****************************************************************
634 #(define dump-extents #t)
635 %(font_dump_setting)s
649 %% ****************************************************************
650 %% ly snippet contents follows:
651 %% ****************************************************************
655 %% ****************************************************************
657 %% ****************************************************************
664 %% ****************************************************************
666 %% ****************************************************************
670 %% ****************************************************************
672 %% ****************************************************************
675 texinfo_line_widths = {
676 '@afourpaper': '160\\mm',
677 '@afourwide': '6.5\\in',
678 '@afourlatex': '150\\mm',
679 '@smallbook': '5\\in',
680 '@letterpaper': '6\\in',
683 def classic_lilypond_book_compatibility (key, value):
684 if key == 'singleline' and value == None:
685 return (RAGGED_RIGHT, None)
687 m = re.search ('relative\s*([-0-9])', key)
689 return ('relative', m.group (1))
691 m = re.match ('([0-9]+)pt', key)
693 return ('staffsize', m.group (1))
695 if key == 'indent' or key == 'line-width':
696 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
698 f = float (m.group (1))
699 return (key, '%f\\%s' % (f, m.group (2)))
703 def find_file (name):
704 for i in global_options.include_path:
705 full = os.path.join (i, name)
706 if os.path.exists (full):
709 ly.error (_ ("file not found: %s") % name + '\n')
713 def verbatim_html (s):
714 return re.sub ('>', '>',
716 re.sub ('&', '&', s)))
718 def verbatim_texinfo (s):
719 return re.sub ('{', '@{',
721 re.sub ('@', '@@', s)))
723 def split_options (option_string):
725 if global_options.format == HTML:
726 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
727 for i in range(len(options)):
728 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
731 return re.split (format_res[global_options.format]['option_sep'],
735 def set_default_options (source):
736 global default_ly_options
737 if not default_ly_options.has_key (LINE_WIDTH):
738 if global_options.format == LATEX:
739 textwidth = get_latex_textwidth (source)
740 default_ly_options[LINE_WIDTH] = \
741 '''%.0f\\pt''' % textwidth
742 elif global_options.format == TEXINFO:
743 for (k, v) in texinfo_line_widths.items ():
744 # FIXME: @layout is usually not in
747 # \input texinfo @c -*-texinfo-*-
749 # Bluntly search first K items of
751 # s = chunks[0].replacement_text ()
752 if re.search (k, source[:1024]):
753 default_ly_options[LINE_WIDTH] = v
757 def replacement_text (self):
760 def filter_text (self):
761 return self.replacement_text ()
763 def ly_is_outdated (self):
766 def png_is_outdated (self):
772 class Substring (Chunk):
773 def __init__ (self, source, start, end, line_number):
777 self.line_number = line_number
778 self.override_text = None
783 def replacement_text (self):
784 if self.override_text:
785 return self.override_text
787 return self.source[self.start:self.end]
789 class Snippet (Chunk):
790 def __init__ (self, type, match, format, line_number):
794 self.option_dict = {}
796 self.line_number = line_number
798 def replacement_text (self):
799 return self.match.group ('match')
801 def substring (self, s):
802 return self.match.group (s)
805 return `self.__class__` + ' type = ' + self.type
807 class Include_snippet (Snippet):
808 def processed_filename (self):
809 f = self.substring ('filename')
810 return os.path.splitext (f)[0] + format2ext[global_options.format]
812 def replacement_text (self):
813 s = self.match.group ('match')
814 f = self.substring ('filename')
816 return re.sub (f, self.processed_filename (), s)
818 class Lilypond_snippet (Snippet):
819 def __init__ (self, type, match, format, line_number):
820 Snippet.__init__ (self, type, match, format, line_number)
821 os = match.group ('options')
822 self.do_options (os, self.type)
825 return self.substring ('code')
830 return self.compose_ly (s)
833 def do_options (self, option_string, type):
834 self.option_dict = {}
836 options = split_options (option_string)
839 if string.find (i, '=') > 0:
840 (key, value) = re.split ('\s*=\s*', i)
841 self.option_dict[key] = value
843 if i in no_options.keys ():
844 if no_options[i] in self.option_dict.keys ():
845 del self.option_dict[no_options[i]]
847 self.option_dict[i] = None
849 has_line_width = self.option_dict.has_key (LINE_WIDTH)
850 no_line_width_value = 0
852 # If LINE_WIDTH is used without parameter, set it to default.
853 if has_line_width and self.option_dict[LINE_WIDTH] == None:
854 no_line_width_value = 1
855 del self.option_dict[LINE_WIDTH]
857 for i in default_ly_options.keys ():
858 if i not in self.option_dict.keys ():
859 self.option_dict[i] = default_ly_options[i]
861 if not has_line_width:
862 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
863 self.option_dict[RAGGED_RIGHT] = None
865 if type == 'lilypond':
866 if LINE_WIDTH in self.option_dict.keys ():
867 del self.option_dict[LINE_WIDTH]
869 if RAGGED_RIGHT in self.option_dict.keys ():
870 if LINE_WIDTH in self.option_dict.keys ():
871 del self.option_dict[LINE_WIDTH]
873 if QUOTE in self.option_dict.keys () or type == 'lilypond':
874 if LINE_WIDTH in self.option_dict.keys ():
875 del self.option_dict[LINE_WIDTH]
877 if not INDENT in self.option_dict.keys ():
878 self.option_dict[INDENT] = '0\\mm'
880 # The QUOTE pattern from ly_options only emits the `line-width'
882 if has_line_width and QUOTE in self.option_dict.keys ():
883 if no_line_width_value:
884 del self.option_dict[LINE_WIDTH]
886 del self.option_dict[QUOTE]
888 def compose_ly (self, code):
889 if FRAGMENT in self.option_dict.keys ():
897 # The original concept of the `exampleindent' option is broken.
898 # It is not possible to get a sane value for @exampleindent at all
899 # without processing the document itself. Saying
907 # causes ugly results with the DVI backend of texinfo since the
908 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
909 # value). Executing the above code changes the environment
910 # indentation to an unknown value because we don't know the amount
911 # of 1em in advance since it is font-dependent. Modifying
912 # @exampleindent in the middle of a document is simply not
913 # supported within texinfo.
915 # As a consequence, the only function of @exampleindent is now to
916 # specify the amount of indentation for the `quote' option.
918 # To set @exampleindent locally to zero, we use the @format
919 # environment for non-quoted snippets.
920 override[EXAMPLEINDENT] = r'0.4\in'
921 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
922 override.update (default_ly_options)
925 for (key, value) in self.option_dict.items ():
927 option_list.append (key)
929 option_list.append (key + '=' + value)
930 option_string = string.join (option_list, ',')
933 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
934 for a in compose_types:
937 for (key, value) in self.option_dict.items ():
939 classic_lilypond_book_compatibility (key, value)
943 (_ ("deprecated ly-option used: %s=%s" \
946 (_ ("compatibility mode translation: %s=%s" \
950 (_ ("deprecated ly-option used: %s" \
953 (_ ("compatibility mode translation: %s" \
956 (key, value) = (c_key, c_value)
959 override[key] = value
961 if not override.has_key (key):
965 for type in compose_types:
966 if ly_options[type].has_key (key):
967 compose_dict[type].append (ly_options[type][key])
971 if not found and key not in simple_options:
972 ly.warning (_ ("ignoring unknown ly option: %s") % key)
975 if RELATIVE in override.keys () and override[RELATIVE]:
976 relative = int (override[RELATIVE])
982 relative_quotes += ',' * (- relative)
984 relative_quotes += "'" * relative
986 paper_string = string.join (compose_dict[PAPER],
988 layout_string = string.join (compose_dict[LAYOUT],
990 notes_string = string.join (compose_dict[NOTES],
992 preamble_string = string.join (compose_dict[PREAMBLE],
995 font_dump_setting = ''
996 if FONTLOAD in self.option_dict:
997 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1001 return (PREAMBLE_LY + body) % d
1004 def get_hash (self):
1006 self.hash = abs (hash (self.full_ly ()))
1009 def basename (self):
1010 if FILENAME in self.option_dict:
1011 return self.option_dict[FILENAME]
1012 if global_options.use_hash:
1013 return 'lily-%d' % self.get_hash ()
1016 def write_ly (self):
1017 outf = open (self.basename () + '.ly', 'w')
1018 outf.write (self.full_ly ())
1020 open (self.basename () + '.txt', 'w').write ('image of music')
1022 def ly_is_outdated (self):
1023 base = self.basename ()
1025 tex_file = '%s.tex' % base
1026 eps_file = '%s.eps' % base
1027 system_file = '%s-systems.tex' % base
1028 ly_file = '%s.ly' % base
1029 ok = os.path.exists (ly_file) \
1030 and os.path.exists (system_file)\
1031 and os.stat (system_file)[stat.ST_SIZE] \
1032 and re.match ('% eof', open (system_file).readlines ()[-1])
1033 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1034 ok = (self.full_ly () == open (ly_file).read ())
1036 # TODO: Do something smart with target formats
1037 # (ps, png) and m/ctimes.
1041 def png_is_outdated (self):
1042 base = self.basename ()
1043 ok = self.ly_is_outdated ()
1044 if global_options.format in (HTML, TEXINFO):
1045 ok = ok and os.path.exists (base + '.eps')
1049 page_count = ly.ps_page_count (base + '.eps')
1052 ok = ok and os.path.exists (base + '.png')
1053 elif page_count > 1:
1054 for a in range (1, page_count + 1):
1055 ok = ok and os.path.exists (base + '-page%d.png' % a)
1059 def texstr_is_outdated (self):
1063 base = self.basename ()
1064 ok = self.ly_is_outdated ()
1065 ok = ok and (os.path.exists (base + '.texstr'))
1068 def filter_text (self):
1069 code = self.substring ('code')
1070 s = run_filter (code)
1073 'options': self.match.group ('options')
1076 return output[self.format][FILTER] % d
1078 def replacement_text (self):
1079 func = Lilypond_snippet.__dict__['output_' + self.format]
1082 def get_images (self):
1083 base = self.basename ()
1085 single = '%(base)s.png' % vars ()
1086 multiple = '%(base)s-page1.png' % vars ()
1088 if os.path.exists (multiple) \
1089 and (not os.path.exists (single) \
1090 or (os.stat (multiple)[stat.ST_MTIME] \
1091 > os.stat (single)[stat.ST_MTIME])):
1092 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1093 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1094 images = tuple (images)
1097 def output_html (self):
1099 base = self.basename ()
1100 if global_options.format == HTML:
1101 str += self.output_print_filename (HTML)
1102 if VERBATIM in self.option_dict:
1103 verb = verbatim_html (self.substring ('code'))
1104 str += output[HTML][VERBATIM] % vars ()
1105 if QUOTE in self.option_dict:
1106 str = output[HTML][QUOTE] % vars ()
1108 str += output[HTML][BEFORE] % vars ()
1109 for image in self.get_images ():
1110 (base, ext) = os.path.splitext (image)
1111 alt = self.option_dict[ALT]
1112 str += output[HTML][OUTPUT] % vars ()
1113 str += output[HTML][AFTER] % vars ()
1116 def output_info (self):
1118 for image in self.get_images ():
1119 (base, ext) = os.path.splitext (image)
1121 # URG, makeinfo implicitly prepends dot to extension.
1122 # Specifying no extension is most robust.
1124 alt = self.option_dict[ALT]
1125 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1127 base = self.basename ()
1128 str += output[global_options.format][OUTPUT] % vars ()
1131 def output_latex (self):
1133 base = self.basename ()
1134 if global_options.format == LATEX:
1135 str += self.output_print_filename (LATEX)
1136 if VERBATIM in self.option_dict:
1137 verb = self.substring ('code')
1138 str += (output[LATEX][VERBATIM] % vars ())
1140 str += (output[LATEX][OUTPUT] % vars ())
1142 ## todo: maintain breaks
1144 breaks = self.ly ().count ("\n")
1145 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1147 if QUOTE in self.option_dict:
1148 str = output[LATEX][QUOTE] % vars ()
1151 def output_print_filename (self, format):
1153 if PRINTFILENAME in self.option_dict:
1154 base = self.basename ()
1155 filename = self.substring ('filename')
1156 str = output[global_options.format][PRINTFILENAME] % vars ()
1160 def output_texinfo (self):
1162 if self.output_print_filename (TEXINFO):
1164 + self.output_print_filename (HTML)
1167 + self.output_print_filename (LATEX)
1169 base = self.basename ()
1170 if TEXIDOC in self.option_dict:
1171 texidoc = base + '.texidoc'
1172 if os.path.exists (texidoc):
1173 str += '@include %(texidoc)s\n\n' % vars ()
1175 if VERBATIM in self.option_dict:
1176 verb = verbatim_texinfo (self.substring ('code'))
1177 str += (output[TEXINFO][VERBATIM] % vars ())
1178 if not QUOTE in self.option_dict:
1179 str = output[TEXINFO][NOQUOTE] % vars ()
1181 str += self.output_info ()
1183 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1184 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1185 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1187 if QUOTE in self.option_dict:
1188 str = output[TEXINFO][QUOTE] % vars ()
1190 # need par after image
1195 class Lilypond_file_snippet (Lilypond_snippet):
1197 name = self.substring ('filename')
1198 return '\\sourcefilename \"%s\"\n%s' \
1199 % (name, open (find_file (name)).read ())
1201 snippet_type_to_class = {
1202 'lilypond_file': Lilypond_file_snippet,
1203 'lilypond_block': Lilypond_snippet,
1204 'lilypond': Lilypond_snippet,
1205 'include': Include_snippet,
1208 def find_linestarts (s):
1213 i = s.find ('\n', start)
1221 nls.append (len (s))
1224 def find_toplevel_snippets (s, types):
1227 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1231 ## found = dict (map (lambda x: (x, None),
1235 map (lambda x, f = found: f.setdefault (x, None),
1238 line_starts = find_linestarts (s)
1240 # We want to search for multiple regexes, without searching
1241 # the string multiple times for one regex.
1242 # Hence, we use earlier results to limit the string portion
1244 # Since every part of the string is traversed at most once for
1245 # every type of snippet, this is linear.
1251 if not found[type] or found[type][0] < index:
1254 m = res[type].search (s[index:endex])
1259 if snippet_type_to_class.has_key (type):
1260 cl = snippet_type_to_class[type]
1263 start = index + m.start ('match')
1264 line_number = line_start_idx
1265 while (line_starts[line_number] < start):
1269 snip = cl (type, m, global_options.format, line_number)
1271 found[type] = (start, snip)
1275 or found[type][0] < found[first][0]):
1280 # Limiting the search space is a cute
1281 # idea, but this *requires* to search
1282 # for possible containing blocks
1283 # first, at least as long as we do not
1284 # search for the start of blocks, but
1285 # always/directly for the entire
1286 # @block ... @end block.
1288 endex = found[first][0]
1291 snippets.append (Substring (s, index, len (s), line_start_idx))
1294 while (start > line_starts[line_start_idx+1]):
1297 (start, snip) = found[first]
1298 snippets.append (Substring (s, index, start, line_start_idx + 1))
1299 snippets.append (snip)
1301 index = start + len (snip.match.group ('match'))
1305 def filter_pipe (input, cmd):
1306 if global_options.verbose:
1307 ly.progress (_ ("Opening filter `%s'") % cmd)
1309 (stdin, stdout, stderr) = os.popen3 (cmd)
1311 status = stdin.close ()
1315 output = stdout.read ()
1316 status = stdout.close ()
1317 error = stderr.read ()
1321 signal = 0x0f & status
1322 if status or (not output and error):
1323 exit_status = status >> 8
1324 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1325 ly.error (_ ("The error log is as follows:"))
1326 sys.stderr.write (error)
1327 sys.stderr.write (stderr.read ())
1330 if global_options.verbose:
1336 return filter_pipe (s, global_options.filter_cmd)
1338 def is_derived_class (cl, baseclass):
1341 for b in cl.__bases__:
1342 if is_derived_class (b, baseclass):
1346 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1347 ly_names = filter (lambda x: x,
1348 map (Lilypond_snippet.basename, ly_snippets))
1349 texstr_names = filter (lambda x: x,
1350 map (Lilypond_snippet.basename, texstr_snippets))
1351 png_names = filter (lambda x: x,
1352 map (Lilypond_snippet.basename, png_snippets))
1355 def my_system (cmd):
1356 status = ly.system (cmd,
1357 ignore_error = 1, progress_p = 1)
1360 ly.error ('Process %s exited unsuccessfully.' % cmd)
1364 # the --process=CMD switch is a bad idea
1365 # it is too generic for lilypond-book.
1367 my_system (string.join ([cmd, '--backend texstr',
1368 'snippet-map.ly'] + texstr_names))
1369 for l in texstr_names:
1370 my_system ('latex %s.texstr' % l)
1373 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1375 LATEX_INSPECTION_DOCUMENT = r'''
1379 \typeout{textwidth=\the\textwidth}
1380 \typeout{columnsep=\the\columnsep}
1381 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1385 # Do we need anything else besides `textwidth'?
1386 def get_latex_textwidth (source):
1387 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1388 preamble = source[:m.start (0)]
1389 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1391 (handle, tmpfile) = tempfile.mkstemp('.tex')
1392 logfile = os.path.splitext (tmpfile)[0] + '.log'
1393 open (tmpfile,'w').write (latex_document)
1394 ly.system ('latex %s' % tmpfile)
1395 parameter_string = open (logfile).read()
1401 m = re.search ('columns=([0-9.]*)', parameter_string)
1403 columns = int (m.group (1))
1406 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1408 columnsep = float (m.group (1))
1411 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1413 textwidth = float (m.group (1))
1415 textwidth = (textwidth - columnsep) / columns
1419 def modify_preamble (chunk):
1420 str = chunk.replacement_text ()
1421 if (re.search (r"\\begin *{document}", str)
1422 and not re.search ("{graphic[sx]", str)):
1423 str = re.sub (r"\\begin{document}",
1424 r"\\usepackage{graphics}" + '\n'
1425 + r"\\begin{document}",
1427 chunk.override_text = str
1439 '.texinfo': TEXINFO,
1445 # TEXINFO: '.texinfo',
1450 class Compile_error:
1453 def write_file_map (lys, name):
1454 snippet_map = open ('snippet-map.ly', 'w')
1455 snippet_map.write ("""
1456 #(define version-seen? #t)
1457 #(ly:add-file-name-alist '(
1460 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1466 snippet_map.write ('))\n')
1468 def do_process_cmd (chunks, input_name):
1469 all_lys = filter (lambda x: is_derived_class (x.__class__,
1473 write_file_map (all_lys, input_name)
1475 filter (lambda x: is_derived_class (x.__class__,
1477 and x.ly_is_outdated (),
1480 filter (lambda x: is_derived_class (x.__class__,
1482 and x.texstr_is_outdated (),
1485 filter (lambda x: is_derived_class (x.__class__,
1487 and x.png_is_outdated (),
1490 ly.progress (_ ("Writing snippets..."))
1491 map (Lilypond_snippet.write_ly, ly_outdated)
1495 ly.progress (_ ("Processing..."))
1497 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1499 ly.progress (_ ("All snippets are up to date..."))
1502 def guess_format (input_filename):
1504 e = os.path.splitext (input_filename)[1]
1505 if e in ext2format.keys ():
1507 format = ext2format[e]
1509 ly.error (_ ("can't determine format for: %s" \
1514 def write_if_updated (file_name, lines):
1516 f = open (file_name)
1518 new_str = string.join (lines, '')
1519 if oldstr == new_str:
1520 ly.progress (_ ("%s is up to date.") % file_name)
1526 ly.progress (_ ("Writing `%s'...") % file_name)
1527 open (file_name, 'w').writelines (lines)
1530 def note_input_file (name, inputs=[]):
1531 ## hack: inputs is mutable!
1532 inputs.append (name)
1535 def do_file (input_filename):
1537 if not input_filename or input_filename == '-':
1538 in_handle = sys.stdin
1539 input_fullname = '<stdin>'
1541 if os.path.exists (input_filename):
1542 input_fullname = input_filename
1543 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1544 # urg python interface to libkpathsea?
1545 input_fullname = ly.read_pipe ('kpsewhich '
1546 + input_filename)[:-1]
1548 input_fullname = find_file (input_filename)
1550 note_input_file (input_fullname)
1551 in_handle = open (input_fullname)
1553 if input_filename == '-':
1554 input_base = 'stdin'
1556 input_base = os.path.basename \
1557 (os.path.splitext (input_filename)[0])
1559 # Only default to stdout when filtering.
1560 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1561 output_filename = '-'
1562 output_file = sys.stdout
1564 # don't complain when global_options.output_name is existing
1565 output_filename = input_base + format2ext[global_options.format]
1566 if global_options.output_name:
1567 if not os.path.isdir (global_options.output_name):
1568 os.mkdir (global_options.output_name, 0777)
1569 os.chdir (global_options.output_name)
1571 if os.path.exists (input_filename) \
1572 and os.path.exists (output_filename) \
1573 and os.path.samefile (output_filename, input_fullname):
1575 _ ("Output would overwrite input file; use --output."))
1579 ly.progress (_ ("Reading %s...") % input_fullname)
1580 source = in_handle.read ()
1583 set_default_options (source)
1586 # FIXME: Containing blocks must be first, see
1587 # find_toplevel_snippets.
1589 'multiline_comment',
1593 'singleline_comment',
1598 ly.progress (_ ("Dissecting..."))
1599 chunks = find_toplevel_snippets (source, snippet_types)
1601 if global_options.format == LATEX:
1603 if (c.is_plain () and
1604 re.search (r"\\begin *{document}", c.replacement_text())):
1609 if global_options.filter_cmd:
1610 write_if_updated (output_filename,
1611 [c.filter_text () for c in chunks])
1612 elif global_options.process_cmd:
1613 do_process_cmd (chunks, input_fullname)
1614 ly.progress (_ ("Compiling %s...") % output_filename)
1616 write_if_updated (output_filename,
1617 [s.replacement_text ()
1620 def process_include (snippet):
1621 os.chdir (original_dir)
1622 name = snippet.substring ('filename')
1623 ly.progress (_ ("Processing include: %s") % name)
1625 return do_file (name)
1627 include_chunks = map (process_include,
1628 filter (lambda x: is_derived_class (x.__class__,
1633 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1635 except Compile_error:
1636 os.chdir (original_dir)
1637 ly.progress (_ ("Removing `%s'") % output_filename)
1642 opt_parser = get_option_parser()
1643 (options, args) = opt_parser.parse_args ()
1645 if options.format in ('texi-html', 'texi'):
1646 options.format = TEXINFO
1647 options.use_hash = True
1648 options.pseudo_filter = False
1650 options.include_path = map (os.path.abspath, options.include_path)
1652 global global_options
1653 global_options = options
1657 files = do_options ()
1658 if not files or len (files) > 1:
1664 basename = os.path.splitext (file)[0]
1665 basename = os.path.split (basename)[1]
1667 if not global_options.format:
1668 global_options.format = guess_format (files[0])
1671 if global_options.format in (TEXINFO, HTML):
1673 if global_options.process_cmd == '':
1674 global_options.process_cmd = lilypond_binary \
1675 + ' --formats=%s --backend eps ' % formats
1677 if global_options.process_cmd:
1678 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1679 for p in global_options.include_path])
1681 ly.identify (sys.stderr)
1684 chunks = do_file (file)
1685 if global_options.psfonts:
1686 fontextract.verbose = global_options.verbose
1687 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1691 psfonts_file = basename + '.psfonts'
1692 if not global_options.verbose:
1693 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1694 fontextract.extract_fonts (psfonts_file,
1695 [x.basename() + '.eps'
1696 for x in snippet_chunks])
1697 if not global_options.verbose:
1700 except Compile_error:
1703 if global_options.format in (TEXINFO, LATEX):
1704 if not global_options.psfonts:
1705 ly.warning (_ ("option --psfonts not used"))
1706 ly.warning (_ ("processing with dvips will have no fonts"))
1708 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1709 output = os.path.join (global_options.output_name, basename + '.dvi' )
1712 ly.progress (_ ("DVIPS usage:"))
1714 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1717 inputs = note_input_file ('')
1720 base_file_name = os.path.splitext (os.path.basename (file))[0]
1721 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1722 final_output_file = os.path.join (global_options.output_name,
1724 + '.%s' % global_options.format)
1726 os.chdir (original_dir)
1727 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1729 if __name__ == '__main__':