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:
61 datadir = datadir[:-1]
63 if not os.path.exists (os.path.join (datadir, 'python/lilylib.py')):
64 datadir = os.path.join (datadir, 'share/lilypond/current/')
65 sys.path.insert (0, os.path.join (datadir, 'python'))
67 # dynamic relocation, for GUB binaries.
68 bindir = os.path.split (sys.argv[0])[0]
71 for prefix_component in ['share', 'lib']:
72 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % prefix_component)
73 sys.path.insert (0, 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 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
99 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
102 ################################################################
104 if global_options.verbose:
105 raise _ ('Exiting (%d)...') % i
110 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
116 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
119 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
121 def ps_page_count (ps_name):
122 header = open (ps_name).read (1024)
123 m = re.search ('\n%%Pages: ([0-9]+)', header)
125 return string.atoi (m.group (1))
130 sys.stdout.write ('''
137 ''' % ( _('Copyright (c) %s by') % '2001--2006',
139 _('Distributed under terms of the GNU General Public License.'),
140 _('It comes with NO WARRANTY.')))
143 def get_option_parser ():
144 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
145 version="@TOPLEVEL_VERSION@",
146 description=help_summary)
148 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
151 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
153 p.add_option ('-f', '--format',
154 help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
156 p.add_option ("-I", '--include', help=_('add DIR to include path'),
158 action='append', dest='include_path',
159 default=[os.path.abspath (os.getcwd ())])
161 p.add_option ("-o", '--output', help=_('write output to DIR'),
163 action='store', dest='output_name',
165 p.add_option ('-P', '--process', metavar=_("COMMAND"),
166 help = _ ("process ly_files using COMMAND FILE..."),
168 dest='process_cmd', default='lilypond -b eps')
170 p.add_option ('--pdf',
173 help="Create PDF files for use with PDFTeX",
176 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
177 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
178 '''must use this with dvips -h INPUT.psfonts'''),
180 p.add_option ('-V', '--verbose', help=_("be verbose"),
185 p.add_option ('-w', '--warranty',
186 help=_("show warranty and copyright"),
190 p.add_option_group ('bugs',
191 description='''Report bugs via http://post.gmane.org/post.php'''
192 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
196 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
198 # Only use installed binary when we are installed too.
199 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
200 lilypond_binary = 'lilypond'
202 global_options = None
205 default_ly_options = { 'alt': "[image of music]" }
208 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
212 EXAMPLEINDENT = 'exampleindent'
214 FRAGMENT = 'fragment'
219 LINE_WIDTH = 'line-width'
220 NOFRAGMENT = 'nofragment'
221 NOINDENT = 'noindent'
226 OUTPUTIMAGE = 'outputimage'
229 PREAMBLE = 'preamble'
230 PRINTFILENAME = 'printfilename'
232 RAGGED_RIGHT = 'ragged-right'
233 RELATIVE = 'relative'
234 STAFFSIZE = 'staffsize'
237 VERBATIM = 'verbatim'
238 FONTLOAD = 'fontload'
239 FILENAME = 'filename'
243 # NOTIME has no opposite so it isn't part of this dictionary.
244 # NOQUOTE is used internally only.
246 NOFRAGMENT: FRAGMENT,
251 # Recognize special sequences in the input.
253 # (?P<name>regex) -- Assign result of REGEX to NAME.
254 # *? -- Match non-greedily.
255 # (?m) -- Multiline regex: Make ^ and $ match at each line.
256 # (?s) -- Make the dot match all characters including newline.
257 # (?x) -- Ignore whitespace in patterns.
269 (\s*(?P<options>.*?)\s*:)?\s*
277 \s*(?P<options>.*?)\s*
286 \s*(?P<options>.*?)\s*
288 \s*(?P<filename>.*?)\s*
295 (?P<code><!--\s.*?!-->)
298 'singleline_comment':
304 (?P<code><pre>.*?</pre>))''',
310 (?P<code><pre>\s.*?</pre>\s))''',
329 \s*(?P<options>.*?)\s*
340 \s*(?P<options>.*?)\s*
344 \\end\s*{lilypond})''',
352 \s*(?P<options>.*?)\s*
360 'singleline_comment':
383 \\end\s*{verbatim}))''',
392 (?P<filename>\S+))''',
396 ^[^\n]*?(?!@c\s+)[^\n]*?
400 \s*(?P<options>.*?)\s*
410 \s*(?P<options>.*?)\s*
413 ^@end\s+lilypond)\s''',
420 \s*(?P<options>.*?)\s*
431 @end\s+ignore))\s''',
433 'singleline_comment':
438 @c([ \t][^\n]*|)\n))''',
440 # Don't do this: It interferes with @code{@{}.
441 # 'verb': r'''(?P<code>@code{.*?})''',
449 @end\s+example\s))''',
458 'intertext': r',?\s*intertext=\".*?\"',
463 'intertext': r',?\s*intertext=\".*?\"',
464 'option_sep': '\s*,\s*',
468 'intertext': r',?\s*intertext=\".*?\"',
469 'option_sep': '\s*,\s*',
473 # Options without a pattern in ly_options.
490 RELATIVE: r'''\relative c%(relative_quotes)s''',
495 INDENT: r'''indent = %(indent)s''',
497 LINE_WIDTH: r'''line-width = %(line-width)s''',
499 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
501 RAGGED_RIGHT: r'''ragged-right = ##t''',
503 PACKED: r'''packed = ##t''',
515 \remove Time_signature_engraver
521 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
528 FILTER: r'''<lilypond %(options)s>
538 <a href="%(base)s.ly">''',
541 <img align="center" valign="center"
542 border="0" src="%(image)s" alt="%(alt)s">''',
544 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
546 QUOTE: r'''<blockquote>
560 \ifx\preLilyPondExample \undefined%%
563 \preLilyPondExample%%
565 \def\lilypondbook{}%%
566 \input %(base)s-systems.tex%%
567 \ifx\postLilyPondExample \undefined%%
570 \postLilyPondExample%%
574 PRINTFILENAME: '''\\texttt{%(filename)s}
577 QUOTE: r'''\begin{quotation}%(str)s
580 VERBATIM: r'''\noindent
581 \begin{verbatim}%(verb)s\end{verbatim}''',
583 FILTER: r'''\begin{lilypond}[%(options)s]
590 FILTER: r'''@lilypond[%(options)s]
596 @include %(base)s-systems.texi
600 OUTPUTIMAGE: r'''@noindent
602 @image{%(base)s,,,%(alt)s,%(ext)s}
606 <a href="%(base)s.ly">
607 <img align="center" valign="center"
608 border="0" src="%(image)s" alt="%(alt)s">
616 <a href="%(base)s.ly">
624 QUOTE: r'''@quotation
625 %(str)s@end quotation
632 VERBATIM: r'''@exampleindent 0
634 %(verb)s@end verbatim
640 # Maintain line numbers.
645 for f in [HTML, LATEX]:
646 for s in (QUOTE, VERBATIM):
647 output[f][s] = output[f][s].replace("\n"," ")
650 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
651 %%%% Options: [%(option_string)s]
652 \\include "lilypond-book-preamble.ly"
660 %% ****************************************************************
661 %% Start cut-&-pastable-section
662 %% ****************************************************************
665 #(define dump-extents #t)
666 %(font_dump_setting)s
680 %% ****************************************************************
681 %% ly snippet contents follows:
682 %% ****************************************************************
686 %% ****************************************************************
688 %% ****************************************************************
695 %% ****************************************************************
697 %% ****************************************************************
701 %% ****************************************************************
703 %% ****************************************************************
706 texinfo_line_widths = {
707 '@afourpaper': '160\\mm',
708 '@afourwide': '6.5\\in',
709 '@afourlatex': '150\\mm',
710 '@smallbook': '5\\in',
711 '@letterpaper': '6\\in',
714 def classic_lilypond_book_compatibility (key, value):
715 if key == 'singleline' and value == None:
716 return (RAGGED_RIGHT, None)
718 m = re.search ('relative\s*([-0-9])', key)
720 return ('relative', m.group (1))
722 m = re.match ('([0-9]+)pt', key)
724 return ('staffsize', m.group (1))
726 if key == 'indent' or key == 'line-width':
727 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
729 f = float (m.group (1))
730 return (key, '%f\\%s' % (f, m.group (2)))
734 def find_file (name):
735 for i in global_options.include_path:
736 full = os.path.join (i, name)
737 if os.path.exists (full):
740 error (_ ("file not found: %s") % name + '\n')
744 def verbatim_html (s):
745 return re.sub ('>', '>',
747 re.sub ('&', '&', s)))
749 def split_options (option_string):
751 if global_options.format == HTML:
752 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
753 for i in range(len(options)):
754 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
757 return re.split (format_res[global_options.format]['option_sep'],
761 def set_default_options (source):
762 global default_ly_options
763 if not default_ly_options.has_key (LINE_WIDTH):
764 if global_options.format == LATEX:
765 textwidth = get_latex_textwidth (source)
766 default_ly_options[LINE_WIDTH] = \
767 '''%.0f\\pt''' % textwidth
768 elif global_options.format == TEXINFO:
769 for (k, v) in texinfo_line_widths.items ():
770 # FIXME: @layout is usually not in
773 # \input texinfo @c -*-texinfo-*-
775 # Bluntly search first K items of
777 # s = chunks[0].replacement_text ()
778 if re.search (k, source[:1024]):
779 default_ly_options[LINE_WIDTH] = v
783 def replacement_text (self):
786 def filter_text (self):
787 return self.replacement_text ()
789 def ly_is_outdated (self):
792 def png_is_outdated (self):
798 class Substring (Chunk):
799 def __init__ (self, source, start, end, line_number):
803 self.line_number = line_number
804 self.override_text = None
809 def replacement_text (self):
810 if self.override_text:
811 return self.override_text
813 return self.source[self.start:self.end]
815 class Snippet (Chunk):
816 def __init__ (self, type, match, format, line_number):
820 self.option_dict = {}
822 self.line_number = line_number
824 def replacement_text (self):
825 return self.match.group ('match')
827 def substring (self, s):
828 return self.match.group (s)
831 return `self.__class__` + ' type = ' + self.type
833 class Include_snippet (Snippet):
834 def processed_filename (self):
835 f = self.substring ('filename')
836 return os.path.splitext (f)[0] + format2ext[global_options.format]
838 def replacement_text (self):
839 s = self.match.group ('match')
840 f = self.substring ('filename')
842 return re.sub (f, self.processed_filename (), s)
844 class Lilypond_snippet (Snippet):
845 def __init__ (self, type, match, format, line_number):
846 Snippet.__init__ (self, type, match, format, line_number)
847 os = match.group ('options')
848 self.do_options (os, self.type)
851 return self.substring ('code')
856 return self.compose_ly (s)
859 def do_options (self, option_string, type):
860 self.option_dict = {}
862 options = split_options (option_string)
865 if string.find (i, '=') > 0:
866 (key, value) = re.split ('\s*=\s*', i)
867 self.option_dict[key] = value
869 if i in no_options.keys ():
870 if no_options[i] in self.option_dict.keys ():
871 del self.option_dict[no_options[i]]
873 self.option_dict[i] = None
875 has_line_width = self.option_dict.has_key (LINE_WIDTH)
876 no_line_width_value = 0
878 # If LINE_WIDTH is used without parameter, set it to default.
879 if has_line_width and self.option_dict[LINE_WIDTH] == None:
880 no_line_width_value = 1
881 del self.option_dict[LINE_WIDTH]
883 for i in default_ly_options.keys ():
884 if i not in self.option_dict.keys ():
885 self.option_dict[i] = default_ly_options[i]
887 if not has_line_width:
888 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
889 self.option_dict[RAGGED_RIGHT] = None
891 if type == 'lilypond':
892 if LINE_WIDTH in self.option_dict.keys ():
893 del self.option_dict[LINE_WIDTH]
895 if RAGGED_RIGHT in self.option_dict.keys ():
896 if LINE_WIDTH in self.option_dict.keys ():
897 del self.option_dict[LINE_WIDTH]
899 if QUOTE in self.option_dict.keys () or type == 'lilypond':
900 if LINE_WIDTH in self.option_dict.keys ():
901 del self.option_dict[LINE_WIDTH]
903 if not INDENT in self.option_dict.keys ():
904 self.option_dict[INDENT] = '0\\mm'
906 # The QUOTE pattern from ly_options only emits the `line-width'
908 if has_line_width and QUOTE in self.option_dict.keys ():
909 if no_line_width_value:
910 del self.option_dict[LINE_WIDTH]
912 del self.option_dict[QUOTE]
914 def compose_ly (self, code):
915 if FRAGMENT in self.option_dict.keys ():
923 # The original concept of the `exampleindent' option is broken.
924 # It is not possible to get a sane value for @exampleindent at all
925 # without processing the document itself. Saying
933 # causes ugly results with the DVI backend of texinfo since the
934 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
935 # value). Executing the above code changes the environment
936 # indentation to an unknown value because we don't know the amount
937 # of 1em in advance since it is font-dependent. Modifying
938 # @exampleindent in the middle of a document is simply not
939 # supported within texinfo.
941 # As a consequence, the only function of @exampleindent is now to
942 # specify the amount of indentation for the `quote' option.
944 # To set @exampleindent locally to zero, we use the @format
945 # environment for non-quoted snippets.
946 override[EXAMPLEINDENT] = r'0.4\in'
947 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
948 override.update (default_ly_options)
951 for (key, value) in self.option_dict.items ():
953 option_list.append (key)
955 option_list.append (key + '=' + value)
956 option_string = string.join (option_list, ',')
959 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
960 for a in compose_types:
963 for (key, value) in self.option_dict.items ():
965 classic_lilypond_book_compatibility (key, value)
969 (_ ("deprecated ly-option used: %s=%s" \
972 (_ ("compatibility mode translation: %s=%s" \
976 (_ ("deprecated ly-option used: %s" \
979 (_ ("compatibility mode translation: %s" \
982 (key, value) = (c_key, c_value)
985 override[key] = value
987 if not override.has_key (key):
991 for type in compose_types:
992 if ly_options[type].has_key (key):
993 compose_dict[type].append (ly_options[type][key])
997 if not found and key not in simple_options:
998 warning (_ ("ignoring unknown ly option: %s") % key)
1001 if RELATIVE in override.keys () and override[RELATIVE]:
1002 relative = int (override[RELATIVE])
1004 relative_quotes = ''
1008 relative_quotes += ',' * (- relative)
1010 relative_quotes += "'" * relative
1012 paper_string = string.join (compose_dict[PAPER],
1014 layout_string = string.join (compose_dict[LAYOUT],
1016 notes_string = string.join (compose_dict[NOTES],
1018 preamble_string = string.join (compose_dict[PREAMBLE],
1021 font_dump_setting = ''
1022 if FONTLOAD in self.option_dict:
1023 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1025 d = globals().copy()
1027 return (PREAMBLE_LY + body) % d
1030 def get_hash (self):
1032 self.hash = abs (hash (self.full_ly ()))
1035 def basename (self):
1036 if FILENAME in self.option_dict:
1037 return self.option_dict[FILENAME]
1038 if global_options.use_hash:
1039 return 'lily-%d' % self.get_hash ()
1042 def write_ly (self):
1043 outf = open (self.basename () + '.ly', 'w')
1044 outf.write (self.full_ly ())
1046 open (self.basename () + '.txt', 'w').write ('image of music')
1048 def ly_is_outdated (self):
1049 base = self.basename ()
1051 tex_file = '%s.tex' % base
1052 eps_file = '%s.eps' % base
1053 system_file = '%s-systems.tex' % base
1054 ly_file = '%s.ly' % base
1055 ok = os.path.exists (ly_file) \
1056 and os.path.exists (system_file)\
1057 and os.stat (system_file)[stat.ST_SIZE] \
1058 and re.match ('% eof', open (system_file).readlines ()[-1])
1059 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1060 ok = (self.full_ly () == open (ly_file).read ())
1062 # TODO: Do something smart with target formats
1063 # (ps, png) and m/ctimes.
1067 def png_is_outdated (self):
1068 base = self.basename ()
1069 ok = not self.ly_is_outdated ()
1070 if global_options.format in (HTML, TEXINFO):
1071 ok = ok and os.path.exists (base + '.eps')
1075 page_count = ps_page_count (base + '.eps')
1078 ok = ok and os.path.exists (base + '.png')
1080 elif page_count > 1:
1081 for a in range (1, page_count + 1):
1082 ok = ok and os.path.exists (base + '-page%d.png' % a)
1086 def texstr_is_outdated (self):
1090 base = self.basename ()
1091 ok = self.ly_is_outdated ()
1092 ok = ok and (os.path.exists (base + '.texstr'))
1095 def filter_text (self):
1096 code = self.substring ('code')
1097 s = run_filter (code)
1100 'options': self.match.group ('options')
1103 return output[self.format][FILTER] % d
1105 def replacement_text (self):
1106 func = Lilypond_snippet.__dict__['output_' + self.format]
1109 def get_images (self):
1110 base = self.basename ()
1112 single = '%(base)s.png' % vars ()
1113 multiple = '%(base)s-page1.png' % vars ()
1115 if os.path.exists (multiple) \
1116 and (not os.path.exists (single) \
1117 or (os.stat (multiple)[stat.ST_MTIME] \
1118 > os.stat (single)[stat.ST_MTIME])):
1119 count = ps_page_count ('%(base)s.eps' % vars ())
1120 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1121 images = tuple (images)
1124 def output_html (self):
1126 base = self.basename ()
1127 if global_options.format == HTML:
1128 str += self.output_print_filename (HTML)
1129 if VERBATIM in self.option_dict:
1130 verb = verbatim_html (self.substring ('code'))
1131 str += output[HTML][VERBATIM] % vars ()
1132 if QUOTE in self.option_dict:
1133 str = output[HTML][QUOTE] % vars ()
1135 str += output[HTML][BEFORE] % vars ()
1136 for image in self.get_images ():
1137 (base, ext) = os.path.splitext (image)
1138 alt = self.option_dict[ALT]
1139 str += output[HTML][OUTPUT] % vars ()
1140 str += output[HTML][AFTER] % vars ()
1143 def output_info (self):
1145 for image in self.get_images ():
1146 (base, ext) = os.path.splitext (image)
1148 # URG, makeinfo implicitly prepends dot to extension.
1149 # Specifying no extension is most robust.
1151 alt = self.option_dict[ALT]
1152 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1154 base = self.basename ()
1155 str += output[global_options.format][OUTPUT] % vars ()
1158 def output_latex (self):
1160 base = self.basename ()
1161 if global_options.format == LATEX:
1162 str += self.output_print_filename (LATEX)
1163 if VERBATIM in self.option_dict:
1164 verb = self.substring ('code')
1165 str += (output[LATEX][VERBATIM] % vars ())
1167 str += (output[LATEX][OUTPUT] % vars ())
1169 ## todo: maintain breaks
1171 breaks = self.ly ().count ("\n")
1172 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1174 if QUOTE in self.option_dict:
1175 str = output[LATEX][QUOTE] % vars ()
1178 def output_print_filename (self, format):
1180 if PRINTFILENAME in self.option_dict:
1181 base = self.basename ()
1182 filename = self.substring ('filename')
1183 str = output[global_options.format][PRINTFILENAME] % vars ()
1187 def output_texinfo (self):
1189 if self.output_print_filename (TEXINFO):
1191 + self.output_print_filename (HTML)
1194 + self.output_print_filename (LATEX)
1196 base = self.basename ()
1197 if TEXIDOC in self.option_dict:
1198 texidoc = base + '.texidoc'
1199 if os.path.exists (texidoc):
1200 str += '@include %(texidoc)s\n\n' % vars ()
1202 if VERBATIM in self.option_dict:
1203 verb = self.substring ('code')
1204 str += (output[TEXINFO][VERBATIM] % vars ())
1205 if not QUOTE in self.option_dict:
1206 str = output[TEXINFO][NOQUOTE] % vars ()
1208 str += self.output_info ()
1210 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1211 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1212 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1214 if QUOTE in self.option_dict:
1215 str = output[TEXINFO][QUOTE] % vars ()
1217 # need par after image
1222 class Lilypond_file_snippet (Lilypond_snippet):
1224 name = self.substring ('filename')
1225 contents = open (find_file (name)).read ()
1227 ## strip version string to make automated regtest comparisons
1228 ## across versions easier.
1229 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1231 return ('\\sourcefilename \"%s\"\n%s'
1234 snippet_type_to_class = {
1235 'lilypond_file': Lilypond_file_snippet,
1236 'lilypond_block': Lilypond_snippet,
1237 'lilypond': Lilypond_snippet,
1238 'include': Include_snippet,
1241 def find_linestarts (s):
1246 i = s.find ('\n', start)
1254 nls.append (len (s))
1257 def find_toplevel_snippets (s, types):
1260 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1264 found = dict ([(t, None) for t in types])
1266 line_starts = find_linestarts (s)
1268 # We want to search for multiple regexes, without searching
1269 # the string multiple times for one regex.
1270 # Hence, we use earlier results to limit the string portion
1272 # Since every part of the string is traversed at most once for
1273 # every type of snippet, this is linear.
1279 if not found[type] or found[type][0] < index:
1282 m = res[type].search (s[index:endex])
1287 if snippet_type_to_class.has_key (type):
1288 cl = snippet_type_to_class[type]
1291 start = index + m.start ('match')
1292 line_number = line_start_idx
1293 while (line_starts[line_number] < start):
1297 snip = cl (type, m, global_options.format, line_number)
1299 found[type] = (start, snip)
1303 or found[type][0] < found[first][0]):
1308 # Limiting the search space is a cute
1309 # idea, but this *requires* to search
1310 # for possible containing blocks
1311 # first, at least as long as we do not
1312 # search for the start of blocks, but
1313 # always/directly for the entire
1314 # @block ... @end block.
1316 endex = found[first][0]
1319 snippets.append (Substring (s, index, len (s), line_start_idx))
1322 while (start > line_starts[line_start_idx+1]):
1325 (start, snip) = found[first]
1326 snippets.append (Substring (s, index, start, line_start_idx + 1))
1327 snippets.append (snip)
1329 index = start + len (snip.match.group ('match'))
1333 def filter_pipe (input, cmd):
1334 if global_options.verbose:
1335 progress (_ ("Opening filter `%s'") % cmd)
1337 (stdin, stdout, stderr) = os.popen3 (cmd)
1339 status = stdin.close ()
1343 output = stdout.read ()
1344 status = stdout.close ()
1345 error = stderr.read ()
1349 signal = 0x0f & status
1350 if status or (not output and error):
1351 exit_status = status >> 8
1352 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1353 error (_ ("The error log is as follows:"))
1354 sys.stderr.write (error)
1355 sys.stderr.write (stderr.read ())
1358 if global_options.verbose:
1364 return filter_pipe (s, global_options.filter_cmd)
1366 def is_derived_class (cl, baseclass):
1369 for b in cl.__bases__:
1370 if is_derived_class (b, baseclass):
1374 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1375 ly_names = filter (lambda x: x,
1376 map (Lilypond_snippet.basename, ly_snippets))
1377 texstr_names = filter (lambda x: x,
1378 map (Lilypond_snippet.basename, texstr_snippets))
1380 png_names = filter (lambda x: x,
1381 map (Lilypond_snippet.basename, png_snippets))
1384 def my_system (cmd):
1385 status = ly.system (cmd,
1386 be_verbose=global_options.verbose,
1389 if global_options.format in (HTML, TEXINFO):
1390 cmd += ' --formats=png '
1393 # the --process=CMD switch is a bad idea
1394 # it is too generic for lilypond-book.
1396 my_system (string.join ([cmd, '--backend texstr',
1397 'snippet-map.ly'] + texstr_names))
1398 for l in texstr_names:
1399 my_system ('latex %s.texstr' % l)
1402 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1404 LATEX_INSPECTION_DOCUMENT = r'''
1408 \typeout{textwidth=\the\textwidth}
1409 \typeout{columnsep=\the\columnsep}
1410 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1414 # Do we need anything else besides `textwidth'?
1415 def get_latex_textwidth (source):
1416 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1418 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1420 ## what's a sensible default?
1423 preamble = source[:m.start (0)]
1424 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1426 (handle, tmpfile) = tempfile.mkstemp('.tex')
1427 logfile = os.path.splitext (tmpfile)[0] + '.log'
1428 logfile = os.path.split (logfile)[1]
1430 tmp_handle = os.fdopen (handle,'w')
1431 tmp_handle.write (latex_document)
1434 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1435 parameter_string = open (logfile).read()
1441 m = re.search ('columns=([0-9.]*)', parameter_string)
1443 columns = int (m.group (1))
1446 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1448 columnsep = float (m.group (1))
1451 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1453 textwidth = float (m.group (1))
1455 textwidth = (textwidth - columnsep) / columns
1459 def modify_preamble (chunk):
1460 str = chunk.replacement_text ()
1461 if (re.search (r"\\begin *{document}", str)
1462 and not re.search ("{graphic[sx]", str)):
1463 str = re.sub (r"\\begin{document}",
1464 r"\\usepackage{graphics}" + '\n'
1465 + r"\\begin{document}",
1467 chunk.override_text = str
1479 '.texinfo': TEXINFO,
1485 # TEXINFO: '.texinfo',
1490 class Compile_error:
1493 def write_file_map (lys, name):
1494 snippet_map = open ('snippet-map.ly', 'w')
1495 snippet_map.write ("""
1496 #(define version-seen #t)
1497 #(ly:add-file-name-alist '(
1500 snippet_map.write ('("%s.ly" . "%s:%d (%s.ly)")\n'
1506 snippet_map.write ('))\n')
1508 def do_process_cmd (chunks, input_name):
1509 all_lys = filter (lambda x: is_derived_class (x.__class__,
1513 write_file_map (all_lys, input_name)
1514 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1516 and x.ly_is_outdated (), chunks)
1517 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1519 and x.texstr_is_outdated (),
1521 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1523 and x.png_is_outdated (),
1526 outdated = png_outdated + texstr_outdated + ly_outdated
1528 progress (_ ("Writing snippets..."))
1529 map (Lilypond_snippet.write_ly, ly_outdated)
1533 progress (_ ("Processing..."))
1535 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1537 progress (_ ("All snippets are up to date..."))
1540 def guess_format (input_filename):
1542 e = os.path.splitext (input_filename)[1]
1543 if e in ext2format.keys ():
1545 format = ext2format[e]
1547 error (_ ("can't determine format for: %s" \
1552 def write_if_updated (file_name, lines):
1554 f = open (file_name)
1556 new_str = string.join (lines, '')
1557 if oldstr == new_str:
1558 progress (_ ("%s is up to date.") % file_name)
1564 progress (_ ("Writing `%s'...") % file_name)
1565 open (file_name, 'w').writelines (lines)
1568 def note_input_file (name, inputs=[]):
1569 ## hack: inputs is mutable!
1570 inputs.append (name)
1573 def samefile (f1, f2):
1575 return os.path.samefile (f1, f2)
1576 except AttributeError: # Windoze
1577 f1 = re.sub ("//*", "/", f1)
1578 f2 = re.sub ("//*", "/", f2)
1581 def do_file (input_filename):
1583 if not input_filename or input_filename == '-':
1584 in_handle = sys.stdin
1585 input_fullname = '<stdin>'
1587 if os.path.exists (input_filename):
1588 input_fullname = input_filename
1589 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1590 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1592 input_fullname = find_file (input_filename)
1594 note_input_file (input_fullname)
1595 in_handle = open (input_fullname)
1597 if input_filename == '-':
1598 input_base = 'stdin'
1600 input_base = os.path.basename \
1601 (os.path.splitext (input_filename)[0])
1603 # Only default to stdout when filtering.
1604 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1605 output_filename = '-'
1606 output_file = sys.stdout
1608 # don't complain when global_options.output_name is existing
1609 output_filename = input_base + format2ext[global_options.format]
1610 if global_options.output_name:
1611 if not os.path.isdir (global_options.output_name):
1612 os.mkdir (global_options.output_name, 0777)
1613 os.chdir (global_options.output_name)
1615 if (os.path.exists (input_filename)
1616 and os.path.exists (output_filename)
1617 and samefile (output_filename, input_fullname)):
1619 _ ("Output would overwrite input file; use --output."))
1623 progress (_ ("Reading %s...") % input_fullname)
1624 source = in_handle.read ()
1627 set_default_options (source)
1630 # FIXME: Containing blocks must be first, see
1631 # find_toplevel_snippets.
1633 'multiline_comment',
1637 'singleline_comment',
1642 progress (_ ("Dissecting..."))
1643 chunks = find_toplevel_snippets (source, snippet_types)
1645 if global_options.format == LATEX:
1647 if (c.is_plain () and
1648 re.search (r"\\begin *{document}", c.replacement_text())):
1653 if global_options.filter_cmd:
1654 write_if_updated (output_filename,
1655 [c.filter_text () for c in chunks])
1656 elif global_options.process_cmd:
1657 do_process_cmd (chunks, input_fullname)
1658 progress (_ ("Compiling %s...") % output_filename)
1660 write_if_updated (output_filename,
1661 [s.replacement_text ()
1664 def process_include (snippet):
1665 os.chdir (original_dir)
1666 name = snippet.substring ('filename')
1667 progress (_ ("Processing include: %s") % name)
1669 return do_file (name)
1671 include_chunks = map (process_include,
1672 filter (lambda x: is_derived_class (x.__class__,
1677 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1679 except Compile_error:
1680 os.chdir (original_dir)
1681 progress (_ ("Removing `%s'") % output_filename)
1687 global global_options
1689 opt_parser = get_option_parser()
1690 (global_options, args) = opt_parser.parse_args ()
1692 if global_options.format in ('texi-html', 'texi'):
1693 global_options.format = TEXINFO
1694 global_options.use_hash = True
1696 global_options.include_path = map (os.path.abspath, global_options.include_path)
1698 if global_options.warranty:
1701 if not args or len (args) > 1:
1702 opt_parser.print_help ()
1708 files = do_options ()
1712 basename = os.path.splitext (file)[0]
1713 basename = os.path.split (basename)[1]
1715 if not global_options.format:
1716 global_options.format = guess_format (files[0])
1719 if global_options.format in (TEXINFO, HTML):
1723 if global_options.process_cmd == '':
1724 global_options.process_cmd = (lilypond_binary
1725 + ' --formats=%s --backend eps ' % formats)
1727 if global_options.process_cmd:
1728 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1729 for p in global_options.include_path])
1731 if (global_options.format in (TEXINFO, LATEX)
1732 and global_options.create_pdf):
1733 global_options.process_cmd += "--pdf -deps-font-include -dgs-font-load "
1735 if global_options.verbose:
1736 global_options.process_cmd += " --verbose "
1740 chunks = do_file (file)
1741 if global_options.psfonts:
1742 fontextract.verbose = global_options.verbose
1743 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1747 psfonts_file = basename + '.psfonts'
1748 if not global_options.verbose:
1749 progress (_ ("Writing fonts to %s...") % psfonts_file)
1750 fontextract.extract_fonts (psfonts_file,
1751 [x.basename() + '.eps'
1752 for x in snippet_chunks])
1753 if not global_options.verbose:
1756 except Compile_error:
1759 if global_options.format in (TEXINFO, LATEX):
1760 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1761 output = os.path.join (global_options.output_name, basename + '.dvi' )
1763 if not global_options.psfonts and not global_options.create_pdf:
1764 warning (_ ("option --psfonts not used"))
1765 warning (_ ("processing with dvips will have no fonts"))
1768 progress (_ ("DVIPS usage:"))
1770 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1773 inputs = note_input_file ('')
1776 base_file_name = os.path.splitext (os.path.basename (file))[0]
1777 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1778 final_output_file = os.path.join (global_options.output_name,
1780 + '.%s' % global_options.format)
1782 os.chdir (original_dir)
1783 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1785 if __name__ == '__main__':