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
42 # Users of python modules should include this snippet
43 # and customize variables below.
45 # We'll suffer this path initialization stuff as long as we don't install
46 # our python packages in <prefix>/lib/pythonX.Y
48 # If set, LILYPONDPREFIX must take prevalence.
49 # if datadir is not set, we're doing a build and LILYPONDPREFIX.
55 datadir = '@local_lilypond_datadir@'
56 if not os.path.isdir (datadir):
57 datadir = '@lilypond_datadir@'
59 sys.path.insert (0, os.path.join (datadir, 'python'))
61 if os.environ.has_key ('LILYPONDPREFIX'):
62 datadir = os.environ['LILYPONDPREFIX']
63 while datadir[-1] == os.sep:
66 datadir = os.path.join (datadir, "share/lilypond/current/")
67 sys.path.insert (0, os.path.join (datadir, 'python'))
69 # dynamic relocation, for GUB binaries.
70 bindir = os.path.split (sys.argv[0])[0]
71 for p in ['share', 'lib']:
72 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
73 sys.path.insert (0, os.path.join (datadir))
82 program_version = '@TOPLEVEL_VERSION@'
83 program_name = os.path.basename (sys.argv[0])
85 original_dir = os.getcwd ()
89 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
93 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
94 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
95 lilypond-book --process='lilypond -I include' BOOK
98 copyright = ('Jan Nieuwenhuizen <janneke@gnu.org>',
99 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
101 def get_option_parser ():
102 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
103 version="@TOPLEVEL_VERSION@",
104 description=help_summary)
106 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
109 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
111 p.add_option ('-f', '--format', help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
113 p.add_option ("-I", '--include', help=_('add DIR to include path'),
115 action='append', dest='include_path',
116 default=[os.path.abspath (os.getcwd ())])
118 p.add_option ("-o", '--output', help=_('write output to DIR'),
120 action='store', dest='output_name', default=None)
121 p.add_option ('-P', '--process', metavar=_("COMMAND"),
122 help = _ ("process ly_files using COMMAND FILE..."),
124 dest='process_cmd', default='lilypond -b eps')
126 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
127 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
128 '''must use this with dvips -h INPUT.psfonts'''),
130 p.add_option ('-V', '--verbose', help=_("be verbose"), action="store_true",
133 p.add_option ('-w', '--warranty', help=_("show warranty and copyright"),
134 action='store_true'),
137 p.add_option_group ('bugs',
138 description='''Report bugs via http://post.gmane.org/post.php'''
139 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
143 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
145 # Only use installed binary when we are installed too.
146 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
147 lilypond_binary = 'lilypond'
149 global_options = None
152 default_ly_options = { 'alt': "[image of music]" }
155 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
159 EXAMPLEINDENT = 'exampleindent'
161 FRAGMENT = 'fragment'
166 LINE_WIDTH = 'line-width'
167 NOFRAGMENT = 'nofragment'
168 NOINDENT = 'noindent'
173 OUTPUTIMAGE = 'outputimage'
176 PREAMBLE = 'preamble'
177 PRINTFILENAME = 'printfilename'
179 RAGGED_RIGHT = 'ragged-right'
180 RELATIVE = 'relative'
181 STAFFSIZE = 'staffsize'
184 VERBATIM = 'verbatim'
185 FONTLOAD = 'fontload'
186 FILENAME = 'filename'
190 # NOTIME has no opposite so it isn't part of this dictionary.
191 # NOQUOTE is used internally only.
193 NOFRAGMENT: FRAGMENT,
198 # Recognize special sequences in the input.
200 # (?P<name>regex) -- Assign result of REGEX to NAME.
201 # *? -- Match non-greedily.
202 # (?m) -- Multiline regex: Make ^ and $ match at each line.
203 # (?s) -- Make the dot match all characters including newline.
204 # (?x) -- Ignore whitespace in patterns.
216 (\s*(?P<options>.*?)\s*:)?\s*
224 \s*(?P<options>.*?)\s*
233 \s*(?P<options>.*?)\s*
235 \s*(?P<filename>.*?)\s*
242 (?P<code><!--\s.*?!-->)
245 'singleline_comment':
251 (?P<code><pre>.*?</pre>))''',
257 (?P<code><pre>\s.*?</pre>\s))''',
276 \s*(?P<options>.*?)\s*
287 \s*(?P<options>.*?)\s*
291 \\end\s*{lilypond})''',
299 \s*(?P<options>.*?)\s*
307 'singleline_comment':
330 \\end\s*{verbatim}))''',
339 (?P<filename>\S+))''',
343 ^[^\n]*?(?!@c\s+)[^\n]*?
347 \s*(?P<options>.*?)\s*
357 \s*(?P<options>.*?)\s*
360 ^@end\s+lilypond)\s''',
367 \s*(?P<options>.*?)\s*
378 @end\s+ignore))\s''',
380 'singleline_comment':
385 @c([ \t][^\n]*|)\n))''',
387 # Don't do this: It interferes with @code{@{}.
388 # 'verb': r'''(?P<code>@code{.*?})''',
396 @end\s+example\s))''',
405 'intertext': r',?\s*intertext=\".*?\"',
410 'intertext': r',?\s*intertext=\".*?\"',
411 'option_sep': '\s*,\s*',
415 'intertext': r',?\s*intertext=\".*?\"',
416 'option_sep': '\s*,\s*',
420 # Options without a pattern in ly_options.
437 RELATIVE: r'''\relative c%(relative_quotes)s''',
442 INDENT: r'''indent = %(indent)s''',
444 LINE_WIDTH: r'''line-width = %(line-width)s''',
446 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
448 RAGGED_RIGHT: r'''ragged-right = ##t''',
450 PACKED: r'''packed = ##t''',
462 \remove Time_signature_engraver
468 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
475 FILTER: r'''<lilypond %(options)s>
485 <a href="%(base)s.ly">''',
488 <img align="center" valign="center"
489 border="0" src="%(image)s" alt="%(alt)s">''',
491 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
493 QUOTE: r'''<blockquote>
507 \ifx\preLilyPondExample \undefined%%
510 \preLilyPondExample%%
512 \def\lilypondbook{}%%
513 \input %(base)s-systems.tex%%
514 \ifx\postLilyPondExample \undefined%%
517 \postLilyPondExample%%
521 PRINTFILENAME: '''\\texttt{%(filename)s}
524 QUOTE: r'''\begin{quotation}%(str)s
527 VERBATIM: r'''\noindent
528 \begin{verbatim}%(verb)s\end{verbatim}''',
530 FILTER: r'''\begin{lilypond}[%(options)s]
537 FILTER: r'''@lilypond[%(options)s]
543 @include %(base)s-systems.texi
547 OUTPUTIMAGE: r'''@noindent
549 @image{%(base)s,,,%(alt)s,%(ext)s}
553 <a href="%(base)s.ly">
554 <img align="center" valign="center"
555 border="0" src="%(image)s" alt="%(alt)s">
561 PRINTFILENAME: '''@file{%(filename)s}
564 QUOTE: r'''@quotation
565 %(str)s@end quotation
572 VERBATIM: r'''@exampleindent 0
580 # Maintain line numbers.
585 for f in [HTML, LATEX]:
586 for s in (QUOTE, VERBATIM):
587 output[f][s] = output[f][s].replace("\n"," ")
590 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
591 %%%% Options: [%(option_string)s]
593 #(set! toplevel-score-handler print-score-with-defaults)
594 #(set! toplevel-music-handler
596 (if (not (eq? (ly:music-property m \'void) #t))
597 (print-score-with-defaults
598 p (scorify-music m p)))))
600 #(ly:set-option (quote no-point-and-click))
601 #(define inside-lilypond-book #t)
602 #(define version-seen? #t)
610 %% ****************************************************************
611 %% Start cut-&-pastable-section
612 %% ****************************************************************
615 #(define dump-extents #t)
616 %(font_dump_setting)s
630 %% ****************************************************************
631 %% ly snippet contents follows:
632 %% ****************************************************************
636 %% ****************************************************************
638 %% ****************************************************************
645 %% ****************************************************************
647 %% ****************************************************************
651 %% ****************************************************************
653 %% ****************************************************************
656 texinfo_line_widths = {
657 '@afourpaper': '160\\mm',
658 '@afourwide': '6.5\\in',
659 '@afourlatex': '150\\mm',
660 '@smallbook': '5\\in',
661 '@letterpaper': '6\\in',
664 def classic_lilypond_book_compatibility (key, value):
665 if key == 'singleline' and value == None:
666 return (RAGGED_RIGHT, None)
668 m = re.search ('relative\s*([-0-9])', key)
670 return ('relative', m.group (1))
672 m = re.match ('([0-9]+)pt', key)
674 return ('staffsize', m.group (1))
676 if key == 'indent' or key == 'line-width':
677 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
679 f = float (m.group (1))
680 return (key, '%f\\%s' % (f, m.group (2)))
684 def find_file (name):
685 for i in global_options.include_path:
686 full = os.path.join (i, name)
687 if os.path.exists (full):
690 ly.error (_ ("file not found: %s") % name + '\n')
694 def verbatim_html (s):
695 return re.sub ('>', '>',
697 re.sub ('&', '&', s)))
699 def verbatim_texinfo (s):
700 return re.sub ('{', '@{',
702 re.sub ('@', '@@', s)))
704 def split_options (option_string):
706 if global_options.format == HTML:
707 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
708 for i in range(len(options)):
709 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
712 return re.split (format_res[global_options.format]['option_sep'],
716 def set_default_options (source):
717 global default_ly_options
718 if not default_ly_options.has_key (LINE_WIDTH):
719 if global_options.format == LATEX:
720 textwidth = get_latex_textwidth (source)
721 default_ly_options[LINE_WIDTH] = \
722 '''%.0f\\pt''' % textwidth
723 elif global_options.format == TEXINFO:
724 for (k, v) in texinfo_line_widths.items ():
725 # FIXME: @layout is usually not in
728 # \input texinfo @c -*-texinfo-*-
730 # Bluntly search first K items of
732 # s = chunks[0].replacement_text ()
733 if re.search (k, source[:1024]):
734 default_ly_options[LINE_WIDTH] = v
738 def replacement_text (self):
741 def filter_text (self):
742 return self.replacement_text ()
744 def ly_is_outdated (self):
747 def png_is_outdated (self):
753 class Substring (Chunk):
754 def __init__ (self, source, start, end, line_number):
758 self.line_number = line_number
759 self.override_text = None
764 def replacement_text (self):
765 if self.override_text:
766 return self.override_text
768 return self.source[self.start:self.end]
770 class Snippet (Chunk):
771 def __init__ (self, type, match, format, line_number):
775 self.option_dict = {}
777 self.line_number = line_number
779 def replacement_text (self):
780 return self.match.group ('match')
782 def substring (self, s):
783 return self.match.group (s)
786 return `self.__class__` + ' type = ' + self.type
788 class Include_snippet (Snippet):
789 def processed_filename (self):
790 f = self.substring ('filename')
791 return os.path.splitext (f)[0] + format2ext[global_options.format]
793 def replacement_text (self):
794 s = self.match.group ('match')
795 f = self.substring ('filename')
797 return re.sub (f, self.processed_filename (), s)
799 class Lilypond_snippet (Snippet):
800 def __init__ (self, type, match, format, line_number):
801 Snippet.__init__ (self, type, match, format, line_number)
802 os = match.group ('options')
803 self.do_options (os, self.type)
806 return self.substring ('code')
811 return self.compose_ly (s)
814 def do_options (self, option_string, type):
815 self.option_dict = {}
817 options = split_options (option_string)
820 if string.find (i, '=') > 0:
821 (key, value) = re.split ('\s*=\s*', i)
822 self.option_dict[key] = value
824 if i in no_options.keys ():
825 if no_options[i] in self.option_dict.keys ():
826 del self.option_dict[no_options[i]]
828 self.option_dict[i] = None
830 has_line_width = self.option_dict.has_key (LINE_WIDTH)
831 no_line_width_value = 0
833 # If LINE_WIDTH is used without parameter, set it to default.
834 if has_line_width and self.option_dict[LINE_WIDTH] == None:
835 no_line_width_value = 1
836 del self.option_dict[LINE_WIDTH]
838 for i in default_ly_options.keys ():
839 if i not in self.option_dict.keys ():
840 self.option_dict[i] = default_ly_options[i]
842 if not has_line_width:
843 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
844 self.option_dict[RAGGED_RIGHT] = None
846 if type == 'lilypond':
847 if LINE_WIDTH in self.option_dict.keys ():
848 del self.option_dict[LINE_WIDTH]
850 if RAGGED_RIGHT in self.option_dict.keys ():
851 if LINE_WIDTH in self.option_dict.keys ():
852 del self.option_dict[LINE_WIDTH]
854 if QUOTE in self.option_dict.keys () or type == 'lilypond':
855 if LINE_WIDTH in self.option_dict.keys ():
856 del self.option_dict[LINE_WIDTH]
858 if not INDENT in self.option_dict.keys ():
859 self.option_dict[INDENT] = '0\\mm'
861 # The QUOTE pattern from ly_options only emits the `line-width'
863 if has_line_width and QUOTE in self.option_dict.keys ():
864 if no_line_width_value:
865 del self.option_dict[LINE_WIDTH]
867 del self.option_dict[QUOTE]
869 def compose_ly (self, code):
870 if FRAGMENT in self.option_dict.keys ():
878 # The original concept of the `exampleindent' option is broken.
879 # It is not possible to get a sane value for @exampleindent at all
880 # without processing the document itself. Saying
888 # causes ugly results with the DVI backend of texinfo since the
889 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
890 # value). Executing the above code changes the environment
891 # indentation to an unknown value because we don't know the amount
892 # of 1em in advance since it is font-dependent. Modifying
893 # @exampleindent in the middle of a document is simply not
894 # supported within texinfo.
896 # As a consequence, the only function of @exampleindent is now to
897 # specify the amount of indentation for the `quote' option.
899 # To set @exampleindent locally to zero, we use the @format
900 # environment for non-quoted snippets.
901 override[EXAMPLEINDENT] = r'0.4\in'
902 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
903 override.update (default_ly_options)
906 for (key, value) in self.option_dict.items ():
908 option_list.append (key)
910 option_list.append (key + '=' + value)
911 option_string = string.join (option_list, ',')
914 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
915 for a in compose_types:
918 for (key, value) in self.option_dict.items ():
920 classic_lilypond_book_compatibility (key, value)
924 (_ ("deprecated ly-option used: %s=%s" \
927 (_ ("compatibility mode translation: %s=%s" \
931 (_ ("deprecated ly-option used: %s" \
934 (_ ("compatibility mode translation: %s" \
937 (key, value) = (c_key, c_value)
940 override[key] = value
942 if not override.has_key (key):
946 for type in compose_types:
947 if ly_options[type].has_key (key):
948 compose_dict[type].append (ly_options[type][key])
952 if not found and key not in simple_options:
953 ly.warning (_ ("ignoring unknown ly option: %s") % key)
956 if RELATIVE in override.keys () and override[RELATIVE]:
957 relative = string.atoi (override[RELATIVE])
963 relative_quotes += ',' * (- relative)
965 relative_quotes += "'" * relative
967 program_name = __main__.program_name
969 paper_string = string.join (compose_dict[PAPER],
971 layout_string = string.join (compose_dict[LAYOUT],
973 notes_string = string.join (compose_dict[NOTES],
975 preamble_string = string.join (compose_dict[PREAMBLE],
978 font_dump_setting = ''
979 if FONTLOAD in self.option_dict:
980 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
982 return (PREAMBLE_LY + body) % vars ()
987 self.hash = abs (hash (self.full_ly ()))
991 if FILENAME in self.option_dict:
992 return self.option_dict[FILENAME]
993 if global_options.use_hash:
994 return 'lily-%d' % self.get_hash ()
998 outf = open (self.basename () + '.ly', 'w')
999 outf.write (self.full_ly ())
1001 open (self.basename () + '.txt', 'w').write ('image of music')
1003 def ly_is_outdated (self):
1004 base = self.basename ()
1006 tex_file = '%s.tex' % base
1007 eps_file = '%s.eps' % base
1008 system_file = '%s-systems.tex' % base
1009 ly_file = '%s.ly' % base
1010 ok = os.path.exists (ly_file) \
1011 and os.path.exists (system_file)\
1012 and os.stat (system_file)[stat.ST_SIZE] \
1013 and re.match ('% eof', open (system_file).readlines ()[-1])
1014 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1015 ok = (self.full_ly () == open (ly_file).read ())
1017 # TODO: Do something smart with target formats
1018 # (ps, png) and m/ctimes.
1022 def png_is_outdated (self):
1023 base = self.basename ()
1024 ok = self.ly_is_outdated ()
1025 if global_options.format in (HTML, TEXINFO):
1026 ok = ok and os.path.exists (base + '.eps')
1030 page_count = ly.ps_page_count (base + '.eps')
1033 ok = ok and os.path.exists (base + '.png')
1034 elif page_count > 1:
1035 for a in range (1, page_count + 1):
1036 ok = ok and os.path.exists (base + '-page%d.png' % a)
1040 def texstr_is_outdated (self):
1044 base = self.basename ()
1045 ok = self.ly_is_outdated ()
1046 ok = ok and (os.path.exists (base + '.texstr'))
1049 def filter_text (self):
1050 code = self.substring ('code')
1051 s = run_filter (code)
1054 'options': self.match.group ('options')
1057 return output[self.format][FILTER] % d
1059 def replacement_text (self):
1060 func = Lilypond_snippet.__dict__['output_' + self.format]
1063 def get_images (self):
1064 base = self.basename ()
1066 single = '%(base)s.png' % vars ()
1067 multiple = '%(base)s-page1.png' % vars ()
1069 if os.path.exists (multiple) \
1070 and (not os.path.exists (single) \
1071 or (os.stat (multiple)[stat.ST_MTIME] \
1072 > os.stat (single)[stat.ST_MTIME])):
1073 count = ly.ps_page_count ('%(base)s.eps' % vars ())
1074 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1075 images = tuple (images)
1078 def output_html (self):
1080 base = self.basename ()
1081 if global_options.format == HTML:
1082 str += self.output_print_filename (HTML)
1083 if VERBATIM in self.option_dict:
1084 verb = verbatim_html (self.substring ('code'))
1085 str += write (output[HTML][VERBATIM] % vars ())
1086 if QUOTE in self.option_dict:
1087 str = output[HTML][QUOTE] % vars ()
1089 str += output[HTML][BEFORE] % vars ()
1090 for image in self.get_images ():
1091 (base, ext) = os.path.splitext (image)
1092 alt = self.option_dict[ALT]
1093 str += output[HTML][OUTPUT] % vars ()
1094 str += output[HTML][AFTER] % vars ()
1097 def output_info (self):
1099 for image in self.get_images ():
1100 (base, ext) = os.path.splitext (image)
1102 # URG, makeinfo implicitly prepends dot to extension.
1103 # Specifying no extension is most robust.
1105 alt = self.option_dict[ALT]
1106 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1108 base = self.basename ()
1109 str += output[global_options.format][OUTPUT] % vars ()
1112 def output_latex (self):
1114 base = self.basename ()
1115 if global_options.format == LATEX:
1116 str += self.output_print_filename (LATEX)
1117 if VERBATIM in self.option_dict:
1118 verb = self.substring ('code')
1119 str += (output[LATEX][VERBATIM] % vars ())
1121 str += (output[LATEX][OUTPUT] % vars ())
1123 ## todo: maintain breaks
1125 breaks = self.ly ().count ("\n")
1126 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1128 if QUOTE in self.option_dict:
1129 str = output[LATEX][QUOTE] % vars ()
1132 def output_print_filename (self, format):
1134 if PRINTFILENAME in self.option_dict:
1135 base = self.basename ()
1136 filename = self.substring ('filename')
1137 str = output[global_options.format][PRINTFILENAME] % vars ()
1141 def output_texinfo (self):
1143 if self.output_print_filename (TEXINFO):
1145 + self.output_print_filename (HTML)
1148 + self.output_print_filename (LATEX)
1150 base = self.basename ()
1151 if TEXIDOC in self.option_dict:
1152 texidoc = base + '.texidoc'
1153 if os.path.exists (texidoc):
1154 str += '@include %(texidoc)s\n\n' % vars ()
1156 if VERBATIM in self.option_dict:
1157 verb = verbatim_texinfo (self.substring ('code'))
1158 str += (output[TEXINFO][VERBATIM] % vars ())
1159 if not QUOTE in self.option_dict:
1160 str = output[TEXINFO][NOQUOTE] % vars ()
1162 str += self.output_info ()
1164 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1165 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1166 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1168 if QUOTE in self.option_dict:
1169 str = output[TEXINFO][QUOTE] % vars ()
1171 # need par after image
1176 class Lilypond_file_snippet (Lilypond_snippet):
1178 name = self.substring ('filename')
1179 return '\\sourcefilename \"%s\"\n%s' \
1180 % (name, open (find_file (name)).read ())
1182 snippet_type_to_class = {
1183 'lilypond_file': Lilypond_file_snippet,
1184 'lilypond_block': Lilypond_snippet,
1185 'lilypond': Lilypond_snippet,
1186 'include': Include_snippet,
1189 def find_linestarts (s):
1194 i = s.find ('\n', start)
1202 nls.append (len (s))
1205 def find_toplevel_snippets (s, types):
1208 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1212 ## found = dict (map (lambda x: (x, None),
1216 map (lambda x, f = found: f.setdefault (x, None),
1219 line_starts = find_linestarts (s)
1221 # We want to search for multiple regexes, without searching
1222 # the string multiple times for one regex.
1223 # Hence, we use earlier results to limit the string portion
1225 # Since every part of the string is traversed at most once for
1226 # every type of snippet, this is linear.
1232 if not found[type] or found[type][0] < index:
1235 m = res[type].search (s[index:endex])
1240 if snippet_type_to_class.has_key (type):
1241 cl = snippet_type_to_class[type]
1244 start = index + m.start ('match')
1245 line_number = line_start_idx
1246 while (line_starts[line_number] < start):
1250 snip = cl (type, m, global_options.format, line_number)
1252 found[type] = (start, snip)
1256 or found[type][0] < found[first][0]):
1261 # Limiting the search space is a cute
1262 # idea, but this *requires* to search
1263 # for possible containing blocks
1264 # first, at least as long as we do not
1265 # search for the start of blocks, but
1266 # always/directly for the entire
1267 # @block ... @end block.
1269 endex = found[first][0]
1272 snippets.append (Substring (s, index, len (s), line_start_idx))
1275 while (start > line_starts[line_start_idx+1]):
1278 (start, snip) = found[first]
1279 snippets.append (Substring (s, index, start, line_start_idx + 1))
1280 snippets.append (snip)
1282 index = start + len (snip.match.group ('match'))
1286 def filter_pipe (input, cmd):
1287 if global_options.verbose:
1288 ly.progress (_ ("Opening filter `%s'") % cmd)
1290 (stdin, stdout, stderr) = os.popen3 (cmd)
1292 status = stdin.close ()
1296 output = stdout.read ()
1297 status = stdout.close ()
1298 error = stderr.read ()
1302 signal = 0x0f & status
1303 if status or (not output and error):
1304 exit_status = status >> 8
1305 ly.error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1306 ly.error (_ ("The error log is as follows:"))
1307 sys.stderr.write (error)
1308 sys.stderr.write (stderr.read ())
1311 if global_options.verbose:
1317 return filter_pipe (s, global_options.filter_cmd)
1319 def is_derived_class (cl, baseclass):
1322 for b in cl.__bases__:
1323 if is_derived_class (b, baseclass):
1327 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1328 ly_names = filter (lambda x: x,
1329 map (Lilypond_snippet.basename, ly_snippets))
1330 texstr_names = filter (lambda x: x,
1331 map (Lilypond_snippet.basename, texstr_snippets))
1332 png_names = filter (lambda x: x,
1333 map (Lilypond_snippet.basename, png_snippets))
1336 def my_system (cmd):
1337 status = ly.system (cmd,
1338 ignore_error = 1, progress_p = 1)
1341 ly.error ('Process %s exited unsuccessfully.' % cmd)
1345 # the --process=CMD switch is a bad idea
1346 # it is too generic for lilypond-book.
1348 my_system (string.join ([cmd, '--backend texstr',
1349 'snippet-map.ly'] + texstr_names))
1350 for l in texstr_names:
1351 my_system ('latex %s.texstr' % l)
1354 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1356 LATEX_INSPECTION_DOCUMENT = r'''
1360 \typeout{textwidth=\the\textwidth}
1361 \typeout{columnsep=\the\columnsep}
1362 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1366 # Do we need anything else besides `textwidth'?
1367 def get_latex_textwidth (source):
1368 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1369 preamble = source[:m.start (0)]
1370 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1371 # Workaround problems with unusable $TMP on Cygwin:
1372 tempfile.tempdir = ''
1373 tmpfile = tempfile.mktemp('.tex')
1374 logfile = os.path.splitext (tmpfile)[0] + '.log'
1375 open (tmpfile,'w').write (latex_document)
1376 ly.system ('latex %s' % tmpfile)
1377 parameter_string = open (logfile).read()
1382 m = re.search ('columns=([0-9.]*)', parameter_string)
1384 columns = string.atoi (m.group (1))
1387 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1389 columnsep = string.atof (m.group (1))
1392 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1394 textwidth = string.atof (m.group (1))
1396 textwidth = (textwidth - columnsep) / columns
1400 def modify_preamble (chunk):
1401 str = chunk.replacement_text ()
1402 if (re.search (r"\\begin *{document}", str)
1403 and not re.search ("{graphic[sx]", str)):
1404 str = re.sub (r"\\begin{document}",
1405 r"\\usepackage{graphics}" + '\n'
1406 + r"\\begin{document}",
1408 chunk.override_text = str
1420 '.texinfo': TEXINFO,
1426 # TEXINFO: '.texinfo',
1431 class Compile_error:
1434 def write_file_map (lys, name):
1435 snippet_map = open ('snippet-map.ly', 'w')
1436 snippet_map.write ("""
1437 #(define version-seen? #t)
1438 #(ly:add-file-name-alist '(
1441 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1447 snippet_map.write ('))\n')
1449 def do_process_cmd (chunks, input_name):
1450 all_lys = filter (lambda x: is_derived_class (x.__class__,
1454 write_file_map (all_lys, input_name)
1456 filter (lambda x: is_derived_class (x.__class__,
1458 and x.ly_is_outdated (),
1461 filter (lambda x: is_derived_class (x.__class__,
1463 and x.texstr_is_outdated (),
1466 filter (lambda x: is_derived_class (x.__class__,
1468 and x.png_is_outdated (),
1471 ly.progress (_ ("Writing snippets..."))
1472 map (Lilypond_snippet.write_ly, ly_outdated)
1476 ly.progress (_ ("Processing..."))
1478 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1480 ly.progress (_ ("All snippets are up to date..."))
1483 def guess_format (input_filename):
1485 e = os.path.splitext (input_filename)[1]
1486 if e in ext2format.keys ():
1488 format = ext2format[e]
1490 ly.error (_ ("can't determine format for: %s" \
1495 def write_if_updated (file_name, lines):
1497 f = open (file_name)
1499 new_str = string.join (lines, '')
1500 if oldstr == new_str:
1501 ly.progress (_ ("%s is up to date.") % file_name)
1507 ly.progress (_ ("Writing `%s'...") % file_name)
1508 open (file_name, 'w').writelines (lines)
1511 def note_input_file (name, inputs=[]):
1512 inputs.append (name)
1515 def do_file (input_filename):
1517 if not input_filename or input_filename == '-':
1518 in_handle = sys.stdin
1519 input_fullname = '<stdin>'
1521 if os.path.exists (input_filename):
1522 input_fullname = input_filename
1523 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1524 # urg python interface to libkpathsea?
1525 input_fullname = ly.read_pipe ('kpsewhich '
1526 + input_filename)[:-1]
1528 input_fullname = find_file (input_filename)
1530 note_input_file (input_fullname)
1531 in_handle = open (input_fullname)
1533 if input_filename == '-':
1534 input_base = 'stdin'
1536 input_base = os.path.basename \
1537 (os.path.splitext (input_filename)[0])
1539 # Only default to stdout when filtering.
1540 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1541 output_filename = '-'
1542 output_file = sys.stdout
1544 # don't complain when global_options.output_name is existing
1545 output_filename = input_base + format2ext[global_options.format]
1546 if global_options.output_name:
1547 if not os.path.isdir (global_options.output_name):
1548 os.mkdir (global_options.output_name, 0777)
1549 os.chdir (global_options.output_name)
1551 if os.path.exists (input_filename) \
1552 and os.path.exists (output_filename) \
1553 and os.path.samefile (output_filename, input_fullname):
1555 _ ("Output would overwrite input file; use --output."))
1559 ly.progress (_ ("Reading %s...") % input_fullname)
1560 source = in_handle.read ()
1563 set_default_options (source)
1566 # FIXME: Containing blocks must be first, see
1567 # find_toplevel_snippets.
1569 'multiline_comment',
1573 'singleline_comment',
1578 ly.progress (_ ("Dissecting..."))
1579 chunks = find_toplevel_snippets (source, snippet_types)
1581 if global_options.format == LATEX:
1583 if (c.is_plain () and
1584 re.search (r"\\begin *{document}", c.replacement_text())):
1589 if global_options.filter_cmd:
1590 write_if_updated (output_filename,
1591 [c.filter_text () for c in chunks])
1592 elif global_options.process_cmd:
1593 do_process_cmd (chunks, input_fullname)
1594 ly.progress (_ ("Compiling %s...") % output_filename)
1596 write_if_updated (output_filename,
1597 [s.replacement_text ()
1600 def process_include (snippet):
1601 os.chdir (original_dir)
1602 name = snippet.substring ('filename')
1603 ly.progress (_ ("Processing include: %s") % name)
1605 return do_file (name)
1607 include_chunks = map (process_include,
1608 filter (lambda x: is_derived_class (x.__class__,
1613 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1615 except Compile_error:
1616 os.chdir (original_dir)
1617 ly.progress (_ ("Removing `%s'") % output_filename)
1622 opt_parser = get_option_parser()
1623 (options, args) = opt_parser.parse_args ()
1625 if options.format in ('texi-html', 'texi'):
1626 options.format = TEXINFO
1627 options.use_hash = True
1628 options.pseudo_filter = False
1630 options.include_path = map (os.path.abspath, options.include_path)
1632 global global_options
1633 global_options = options
1637 files = do_options ()
1638 if not files or len (files) > 1:
1644 basename = os.path.splitext (file)[0]
1645 basename = os.path.split (basename)[1]
1647 if not global_options.format:
1648 global_options.format = guess_format (files[0])
1651 if global_options.format in (TEXINFO, HTML):
1653 if global_options.process_cmd == '':
1654 global_options.process_cmd = lilypond_binary \
1655 + ' --formats=%s --backend eps ' % formats
1657 if global_options.process_cmd:
1658 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1659 for p in global_options.include_path])
1661 ly.identify (sys.stderr)
1664 chunks = do_file (file)
1665 if global_options.psfonts:
1666 fontextract.verbose = global_options.verbose
1667 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1671 psfonts_file = basename + '.psfonts'
1672 if not global_options.verbose:
1673 ly.progress (_ ("Writing fonts to %s...") % psfonts_file)
1674 fontextract.extract_fonts (psfonts_file,
1675 [x.basename() + '.eps'
1676 for x in snippet_chunks])
1677 if not global_options.verbose:
1680 except Compile_error:
1683 if global_options.format in (TEXINFO, LATEX):
1684 if not global_options.psfonts:
1685 ly.warning (_ ("option --psfonts not used"))
1686 ly.warning (_ ("processing with dvips will have no fonts"))
1688 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1689 output = os.path.join (global_options.output_name, basename + '.dvi' )
1692 ly.progress (_ ("DVIPS usage:"))
1694 ly.progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1697 inputs = note_input_file ('')
1700 base_file_name = os.path.splitext (os.path.basename (file))[0]
1701 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1702 final_output_file = os.path.join (global_options.output_name,
1704 + '.%s' % global_options.format)
1706 os.chdir (original_dir)
1707 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1709 if __name__ == '__main__':