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
611 %(verb)s@end verbatim
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 split_options (option_string):
738 if global_options.format == HTML:
739 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
740 for i in range(len(options)):
741 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
744 return re.split (format_res[global_options.format]['option_sep'],
748 def set_default_options (source):
749 global default_ly_options
750 if not default_ly_options.has_key (LINE_WIDTH):
751 if global_options.format == LATEX:
752 textwidth = get_latex_textwidth (source)
753 default_ly_options[LINE_WIDTH] = \
754 '''%.0f\\pt''' % textwidth
755 elif global_options.format == TEXINFO:
756 for (k, v) in texinfo_line_widths.items ():
757 # FIXME: @layout is usually not in
760 # \input texinfo @c -*-texinfo-*-
762 # Bluntly search first K items of
764 # s = chunks[0].replacement_text ()
765 if re.search (k, source[:1024]):
766 default_ly_options[LINE_WIDTH] = v
770 def replacement_text (self):
773 def filter_text (self):
774 return self.replacement_text ()
776 def ly_is_outdated (self):
779 def png_is_outdated (self):
785 class Substring (Chunk):
786 def __init__ (self, source, start, end, line_number):
790 self.line_number = line_number
791 self.override_text = None
796 def replacement_text (self):
797 if self.override_text:
798 return self.override_text
800 return self.source[self.start:self.end]
802 class Snippet (Chunk):
803 def __init__ (self, type, match, format, line_number):
807 self.option_dict = {}
809 self.line_number = line_number
811 def replacement_text (self):
812 return self.match.group ('match')
814 def substring (self, s):
815 return self.match.group (s)
818 return `self.__class__` + ' type = ' + self.type
820 class Include_snippet (Snippet):
821 def processed_filename (self):
822 f = self.substring ('filename')
823 return os.path.splitext (f)[0] + format2ext[global_options.format]
825 def replacement_text (self):
826 s = self.match.group ('match')
827 f = self.substring ('filename')
829 return re.sub (f, self.processed_filename (), s)
831 class Lilypond_snippet (Snippet):
832 def __init__ (self, type, match, format, line_number):
833 Snippet.__init__ (self, type, match, format, line_number)
834 os = match.group ('options')
835 self.do_options (os, self.type)
838 return self.substring ('code')
843 return self.compose_ly (s)
846 def do_options (self, option_string, type):
847 self.option_dict = {}
849 options = split_options (option_string)
852 if string.find (i, '=') > 0:
853 (key, value) = re.split ('\s*=\s*', i)
854 self.option_dict[key] = value
856 if i in no_options.keys ():
857 if no_options[i] in self.option_dict.keys ():
858 del self.option_dict[no_options[i]]
860 self.option_dict[i] = None
862 has_line_width = self.option_dict.has_key (LINE_WIDTH)
863 no_line_width_value = 0
865 # If LINE_WIDTH is used without parameter, set it to default.
866 if has_line_width and self.option_dict[LINE_WIDTH] == None:
867 no_line_width_value = 1
868 del self.option_dict[LINE_WIDTH]
870 for i in default_ly_options.keys ():
871 if i not in self.option_dict.keys ():
872 self.option_dict[i] = default_ly_options[i]
874 if not has_line_width:
875 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
876 self.option_dict[RAGGED_RIGHT] = None
878 if type == 'lilypond':
879 if LINE_WIDTH in self.option_dict.keys ():
880 del self.option_dict[LINE_WIDTH]
882 if RAGGED_RIGHT in self.option_dict.keys ():
883 if LINE_WIDTH in self.option_dict.keys ():
884 del self.option_dict[LINE_WIDTH]
886 if QUOTE in self.option_dict.keys () or type == 'lilypond':
887 if LINE_WIDTH in self.option_dict.keys ():
888 del self.option_dict[LINE_WIDTH]
890 if not INDENT in self.option_dict.keys ():
891 self.option_dict[INDENT] = '0\\mm'
893 # The QUOTE pattern from ly_options only emits the `line-width'
895 if has_line_width and QUOTE in self.option_dict.keys ():
896 if no_line_width_value:
897 del self.option_dict[LINE_WIDTH]
899 del self.option_dict[QUOTE]
901 def compose_ly (self, code):
902 if FRAGMENT in self.option_dict.keys ():
910 # The original concept of the `exampleindent' option is broken.
911 # It is not possible to get a sane value for @exampleindent at all
912 # without processing the document itself. Saying
920 # causes ugly results with the DVI backend of texinfo since the
921 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
922 # value). Executing the above code changes the environment
923 # indentation to an unknown value because we don't know the amount
924 # of 1em in advance since it is font-dependent. Modifying
925 # @exampleindent in the middle of a document is simply not
926 # supported within texinfo.
928 # As a consequence, the only function of @exampleindent is now to
929 # specify the amount of indentation for the `quote' option.
931 # To set @exampleindent locally to zero, we use the @format
932 # environment for non-quoted snippets.
933 override[EXAMPLEINDENT] = r'0.4\in'
934 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
935 override.update (default_ly_options)
938 for (key, value) in self.option_dict.items ():
940 option_list.append (key)
942 option_list.append (key + '=' + value)
943 option_string = string.join (option_list, ',')
946 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
947 for a in compose_types:
950 for (key, value) in self.option_dict.items ():
952 classic_lilypond_book_compatibility (key, value)
956 (_ ("deprecated ly-option used: %s=%s" \
959 (_ ("compatibility mode translation: %s=%s" \
963 (_ ("deprecated ly-option used: %s" \
966 (_ ("compatibility mode translation: %s" \
969 (key, value) = (c_key, c_value)
972 override[key] = value
974 if not override.has_key (key):
978 for type in compose_types:
979 if ly_options[type].has_key (key):
980 compose_dict[type].append (ly_options[type][key])
984 if not found and key not in simple_options:
985 warning (_ ("ignoring unknown ly option: %s") % key)
988 if RELATIVE in override.keys () and override[RELATIVE]:
989 relative = int (override[RELATIVE])
995 relative_quotes += ',' * (- relative)
997 relative_quotes += "'" * relative
999 paper_string = string.join (compose_dict[PAPER],
1001 layout_string = string.join (compose_dict[LAYOUT],
1003 notes_string = string.join (compose_dict[NOTES],
1005 preamble_string = string.join (compose_dict[PREAMBLE],
1008 font_dump_setting = ''
1009 if FONTLOAD in self.option_dict:
1010 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1012 d = globals().copy()
1014 return (PREAMBLE_LY + body) % d
1017 def get_hash (self):
1019 self.hash = abs (hash (self.full_ly ()))
1022 def basename (self):
1023 if FILENAME in self.option_dict:
1024 return self.option_dict[FILENAME]
1025 if global_options.use_hash:
1026 return 'lily-%d' % self.get_hash ()
1029 def write_ly (self):
1030 outf = open (self.basename () + '.ly', 'w')
1031 outf.write (self.full_ly ())
1033 open (self.basename () + '.txt', 'w').write ('image of music')
1035 def ly_is_outdated (self):
1036 base = self.basename ()
1038 tex_file = '%s.tex' % base
1039 eps_file = '%s.eps' % base
1040 system_file = '%s-systems.tex' % base
1041 ly_file = '%s.ly' % base
1042 ok = os.path.exists (ly_file) \
1043 and os.path.exists (system_file)\
1044 and os.stat (system_file)[stat.ST_SIZE] \
1045 and re.match ('% eof', open (system_file).readlines ()[-1])
1046 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1047 ok = (self.full_ly () == open (ly_file).read ())
1049 # TODO: Do something smart with target formats
1050 # (ps, png) and m/ctimes.
1054 def png_is_outdated (self):
1055 base = self.basename ()
1056 ok = self.ly_is_outdated ()
1057 if global_options.format in (HTML, TEXINFO):
1058 ok = ok and os.path.exists (base + '.eps')
1062 page_count = ly.ps_page_count (base + '.eps')
1065 ok = ok and os.path.exists (base + '.png')
1066 elif page_count > 1:
1067 for a in range (1, page_count + 1):
1068 ok = ok and os.path.exists (base + '-page%d.png' % a)
1072 def texstr_is_outdated (self):
1076 base = self.basename ()
1077 ok = self.ly_is_outdated ()
1078 ok = ok and (os.path.exists (base + '.texstr'))
1081 def filter_text (self):
1082 code = self.substring ('code')
1083 s = run_filter (code)
1086 'options': self.match.group ('options')
1089 return output[self.format][FILTER] % d
1091 def replacement_text (self):
1092 func = Lilypond_snippet.__dict__['output_' + self.format]
1095 def get_images (self):
1096 base = self.basename ()
1098 single = '%(base)s.png' % vars ()
1099 multiple = '%(base)s-page1.png' % vars ()
1101 if os.path.exists (multiple) \
1102 and (not os.path.exists (single) \
1103 or (os.stat (multiple)[stat.ST_MTIME] \
1104 > os.stat (single)[stat.ST_MTIME])):
1105 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1106 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1107 images = tuple (images)
1110 def output_html (self):
1112 base = self.basename ()
1113 if global_options.format == HTML:
1114 str += self.output_print_filename (HTML)
1115 if VERBATIM in self.option_dict:
1116 verb = verbatim_html (self.substring ('code'))
1117 str += output[HTML][VERBATIM] % vars ()
1118 if QUOTE in self.option_dict:
1119 str = output[HTML][QUOTE] % vars ()
1121 str += output[HTML][BEFORE] % vars ()
1122 for image in self.get_images ():
1123 (base, ext) = os.path.splitext (image)
1124 alt = self.option_dict[ALT]
1125 str += output[HTML][OUTPUT] % vars ()
1126 str += output[HTML][AFTER] % vars ()
1129 def output_info (self):
1131 for image in self.get_images ():
1132 (base, ext) = os.path.splitext (image)
1134 # URG, makeinfo implicitly prepends dot to extension.
1135 # Specifying no extension is most robust.
1137 alt = self.option_dict[ALT]
1138 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1140 base = self.basename ()
1141 str += output[global_options.format][OUTPUT] % vars ()
1144 def output_latex (self):
1146 base = self.basename ()
1147 if global_options.format == LATEX:
1148 str += self.output_print_filename (LATEX)
1149 if VERBATIM in self.option_dict:
1150 verb = self.substring ('code')
1151 str += (output[LATEX][VERBATIM] % vars ())
1153 str += (output[LATEX][OUTPUT] % vars ())
1155 ## todo: maintain breaks
1157 breaks = self.ly ().count ("\n")
1158 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1160 if QUOTE in self.option_dict:
1161 str = output[LATEX][QUOTE] % vars ()
1164 def output_print_filename (self, format):
1166 if PRINTFILENAME in self.option_dict:
1167 base = self.basename ()
1168 filename = self.substring ('filename')
1169 str = output[global_options.format][PRINTFILENAME] % vars ()
1173 def output_texinfo (self):
1175 if self.output_print_filename (TEXINFO):
1177 + self.output_print_filename (HTML)
1180 + self.output_print_filename (LATEX)
1182 base = self.basename ()
1183 if TEXIDOC in self.option_dict:
1184 texidoc = base + '.texidoc'
1185 if os.path.exists (texidoc):
1186 str += '@include %(texidoc)s\n\n' % vars ()
1188 if VERBATIM in self.option_dict:
1189 verb = self.substring ('code')
1190 str += (output[TEXINFO][VERBATIM] % vars ())
1191 if not QUOTE in self.option_dict:
1192 str = output[TEXINFO][NOQUOTE] % vars ()
1194 str += self.output_info ()
1196 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1197 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1198 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1200 if QUOTE in self.option_dict:
1201 str = output[TEXINFO][QUOTE] % vars ()
1203 # need par after image
1208 class Lilypond_file_snippet (Lilypond_snippet):
1210 name = self.substring ('filename')
1211 return '\\sourcefilename \"%s\"\n%s' \
1212 % (name, open (find_file (name)).read ())
1214 snippet_type_to_class = {
1215 'lilypond_file': Lilypond_file_snippet,
1216 'lilypond_block': Lilypond_snippet,
1217 'lilypond': Lilypond_snippet,
1218 'include': Include_snippet,
1221 def find_linestarts (s):
1226 i = s.find ('\n', start)
1234 nls.append (len (s))
1237 def find_toplevel_snippets (s, types):
1240 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1244 ## found = dict (map (lambda x: (x, None),
1248 map (lambda x, f = found: f.setdefault (x, None),
1251 line_starts = find_linestarts (s)
1253 # We want to search for multiple regexes, without searching
1254 # the string multiple times for one regex.
1255 # Hence, we use earlier results to limit the string portion
1257 # Since every part of the string is traversed at most once for
1258 # every type of snippet, this is linear.
1264 if not found[type] or found[type][0] < index:
1267 m = res[type].search (s[index:endex])
1272 if snippet_type_to_class.has_key (type):
1273 cl = snippet_type_to_class[type]
1276 start = index + m.start ('match')
1277 line_number = line_start_idx
1278 while (line_starts[line_number] < start):
1282 snip = cl (type, m, global_options.format, line_number)
1284 found[type] = (start, snip)
1288 or found[type][0] < found[first][0]):
1293 # Limiting the search space is a cute
1294 # idea, but this *requires* to search
1295 # for possible containing blocks
1296 # first, at least as long as we do not
1297 # search for the start of blocks, but
1298 # always/directly for the entire
1299 # @block ... @end block.
1301 endex = found[first][0]
1304 snippets.append (Substring (s, index, len (s), line_start_idx))
1307 while (start > line_starts[line_start_idx+1]):
1310 (start, snip) = found[first]
1311 snippets.append (Substring (s, index, start, line_start_idx + 1))
1312 snippets.append (snip)
1314 index = start + len (snip.match.group ('match'))
1318 def filter_pipe (input, cmd):
1319 if global_options.verbose:
1320 progress (_ ("Opening filter `%s'") % cmd)
1322 (stdin, stdout, stderr) = os.popen3 (cmd)
1324 status = stdin.close ()
1328 output = stdout.read ()
1329 status = stdout.close ()
1330 error = stderr.read ()
1334 signal = 0x0f & status
1335 if status or (not output and error):
1336 exit_status = status >> 8
1337 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1338 error (_ ("The error log is as follows:"))
1339 sys.stderr.write (error)
1340 sys.stderr.write (stderr.read ())
1343 if global_options.verbose:
1349 return filter_pipe (s, global_options.filter_cmd)
1351 def is_derived_class (cl, baseclass):
1354 for b in cl.__bases__:
1355 if is_derived_class (b, baseclass):
1359 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1360 ly_names = filter (lambda x: x,
1361 map (Lilypond_snippet.basename, ly_snippets))
1362 texstr_names = filter (lambda x: x,
1363 map (Lilypond_snippet.basename, texstr_snippets))
1364 png_names = filter (lambda x: x,
1365 map (Lilypond_snippet.basename, png_snippets))
1368 def my_system (cmd):
1369 status = ly.system (cmd,
1370 be_verbose=global_options.verbose,
1374 # the --process=CMD switch is a bad idea
1375 # it is too generic for lilypond-book.
1377 my_system (string.join ([cmd, '--backend texstr',
1378 'snippet-map.ly'] + texstr_names))
1379 for l in texstr_names:
1380 my_system ('latex %s.texstr' % l)
1383 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1385 LATEX_INSPECTION_DOCUMENT = r'''
1389 \typeout{textwidth=\the\textwidth}
1390 \typeout{columnsep=\the\columnsep}
1391 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1395 # Do we need anything else besides `textwidth'?
1396 def get_latex_textwidth (source):
1397 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1398 preamble = source[:m.start (0)]
1399 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1401 (handle, tmpfile) = tempfile.mkstemp('.tex')
1402 logfile = os.path.splitext (tmpfile)[0] + '.log'
1403 logfile = os.path.split (logfile)[1]
1405 tmp_handle = open (tmpfile,'w')
1406 tmp_handle.write (latex_document)
1409 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1410 parameter_string = open (logfile).read()
1416 m = re.search ('columns=([0-9.]*)', parameter_string)
1418 columns = int (m.group (1))
1421 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1423 columnsep = float (m.group (1))
1426 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1428 textwidth = float (m.group (1))
1430 textwidth = (textwidth - columnsep) / columns
1434 def modify_preamble (chunk):
1435 str = chunk.replacement_text ()
1436 if (re.search (r"\\begin *{document}", str)
1437 and not re.search ("{graphic[sx]", str)):
1438 str = re.sub (r"\\begin{document}",
1439 r"\\usepackage{graphics}" + '\n'
1440 + r"\\begin{document}",
1442 chunk.override_text = str
1454 '.texinfo': TEXINFO,
1460 # TEXINFO: '.texinfo',
1465 class Compile_error:
1468 def write_file_map (lys, name):
1469 snippet_map = open ('snippet-map.ly', 'w')
1470 snippet_map.write ("""
1471 #(define version-seen? #t)
1472 #(ly:add-file-name-alist '(
1475 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1481 snippet_map.write ('))\n')
1483 def do_process_cmd (chunks, input_name):
1484 all_lys = filter (lambda x: is_derived_class (x.__class__,
1488 write_file_map (all_lys, input_name)
1490 filter (lambda x: is_derived_class (x.__class__,
1492 and x.ly_is_outdated (),
1495 filter (lambda x: is_derived_class (x.__class__,
1497 and x.texstr_is_outdated (),
1500 filter (lambda x: is_derived_class (x.__class__,
1502 and x.png_is_outdated (),
1505 progress (_ ("Writing snippets..."))
1506 map (Lilypond_snippet.write_ly, ly_outdated)
1510 progress (_ ("Processing..."))
1512 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1514 progress (_ ("All snippets are up to date..."))
1517 def guess_format (input_filename):
1519 e = os.path.splitext (input_filename)[1]
1520 if e in ext2format.keys ():
1522 format = ext2format[e]
1524 error (_ ("can't determine format for: %s" \
1529 def write_if_updated (file_name, lines):
1531 f = open (file_name)
1533 new_str = string.join (lines, '')
1534 if oldstr == new_str:
1535 progress (_ ("%s is up to date.") % file_name)
1541 progress (_ ("Writing `%s'...") % file_name)
1542 open (file_name, 'w').writelines (lines)
1545 def note_input_file (name, inputs=[]):
1546 ## hack: inputs is mutable!
1547 inputs.append (name)
1550 def do_file (input_filename):
1552 if not input_filename or input_filename == '-':
1553 in_handle = sys.stdin
1554 input_fullname = '<stdin>'
1556 if os.path.exists (input_filename):
1557 input_fullname = input_filename
1558 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1559 input_fullname = os.read_pipe ('kpsewhich ' + input_filename).read()[:-1]
1561 input_fullname = find_file (input_filename)
1563 note_input_file (input_fullname)
1564 in_handle = open (input_fullname)
1566 if input_filename == '-':
1567 input_base = 'stdin'
1569 input_base = os.path.basename \
1570 (os.path.splitext (input_filename)[0])
1572 # Only default to stdout when filtering.
1573 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1574 output_filename = '-'
1575 output_file = sys.stdout
1577 # don't complain when global_options.output_name is existing
1578 output_filename = input_base + format2ext[global_options.format]
1579 if global_options.output_name:
1580 if not os.path.isdir (global_options.output_name):
1581 os.mkdir (global_options.output_name, 0777)
1582 os.chdir (global_options.output_name)
1584 if os.path.exists (input_filename) \
1585 and os.path.exists (output_filename) \
1586 and os.path.samefile (output_filename, input_fullname):
1588 _ ("Output would overwrite input file; use --output."))
1592 progress (_ ("Reading %s...") % input_fullname)
1593 source = in_handle.read ()
1596 set_default_options (source)
1599 # FIXME: Containing blocks must be first, see
1600 # find_toplevel_snippets.
1602 'multiline_comment',
1606 'singleline_comment',
1611 progress (_ ("Dissecting..."))
1612 chunks = find_toplevel_snippets (source, snippet_types)
1614 if global_options.format == LATEX:
1616 if (c.is_plain () and
1617 re.search (r"\\begin *{document}", c.replacement_text())):
1622 if global_options.filter_cmd:
1623 write_if_updated (output_filename,
1624 [c.filter_text () for c in chunks])
1625 elif global_options.process_cmd:
1626 do_process_cmd (chunks, input_fullname)
1627 progress (_ ("Compiling %s...") % output_filename)
1629 write_if_updated (output_filename,
1630 [s.replacement_text ()
1633 def process_include (snippet):
1634 os.chdir (original_dir)
1635 name = snippet.substring ('filename')
1636 progress (_ ("Processing include: %s") % name)
1638 return do_file (name)
1640 include_chunks = map (process_include,
1641 filter (lambda x: is_derived_class (x.__class__,
1646 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1648 except Compile_error:
1649 os.chdir (original_dir)
1650 progress (_ ("Removing `%s'") % output_filename)
1656 global global_options
1658 opt_parser = get_option_parser()
1659 (global_options, args) = opt_parser.parse_args ()
1661 if global_options.format in ('texi-html', 'texi'):
1662 global_options.format = TEXINFO
1663 global_options.use_hash = True
1665 global_options.include_path = map (os.path.abspath, global_options.include_path)
1667 if global_options.warranty:
1670 if not args or len (args) > 1:
1671 opt_parser.print_help ()
1677 files = do_options ()
1681 basename = os.path.splitext (file)[0]
1682 basename = os.path.split (basename)[1]
1684 if not global_options.format:
1685 global_options.format = guess_format (files[0])
1688 if global_options.format in (TEXINFO, HTML):
1690 if global_options.process_cmd == '':
1691 global_options.process_cmd = lilypond_binary \
1692 + ' --formats=%s --backend eps ' % formats
1694 if global_options.process_cmd:
1695 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1696 for p in global_options.include_path])
1701 chunks = do_file (file)
1702 if global_options.psfonts:
1703 fontextract.verbose = global_options.verbose
1704 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1708 psfonts_file = basename + '.psfonts'
1709 if not global_options.verbose:
1710 progress (_ ("Writing fonts to %s...") % psfonts_file)
1711 fontextract.extract_fonts (psfonts_file,
1712 [x.basename() + '.eps'
1713 for x in snippet_chunks])
1714 if not global_options.verbose:
1717 except Compile_error:
1720 if global_options.format in (TEXINFO, LATEX):
1721 if not global_options.psfonts:
1722 warning (_ ("option --psfonts not used"))
1723 warning (_ ("processing with dvips will have no fonts"))
1725 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1726 output = os.path.join (global_options.output_name, basename + '.dvi' )
1729 progress (_ ("DVIPS usage:"))
1731 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1734 inputs = note_input_file ('')
1737 base_file_name = os.path.splitext (os.path.basename (file))[0]
1738 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1739 final_output_file = os.path.join (global_options.output_name,
1741 + '.%s' % global_options.format)
1743 os.chdir (original_dir)
1744 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1746 if __name__ == '__main__':