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
44 for d in ['@lilypond_datadir@',
46 sys.path.insert (0, os.path.join (d, 'python'))
48 # dynamic relocation, for GUB binaries.
49 bindir = os.path.abspath (os.path.split (sys.argv[0])[0])
51 os.environ['PATH'] = bindir + ':' + os.environ['PATH']
52 for p in ['share', 'lib']:
53 datadir = os.path.abspath (bindir + '/../%s/lilypond/current/python/' % p)
54 sys.path.insert (0, datadir)
63 program_version = '@TOPLEVEL_VERSION@'
64 program_name = os.path.basename (sys.argv[0])
66 original_dir = os.getcwd ()
70 '''Process LilyPond snippets in hybrid HTML, LaTeX, or texinfo document.
74 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
75 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
76 lilypond-book --process='lilypond -I include' BOOK
79 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
80 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
83 ################################################################
85 if global_options.verbose:
86 raise _ ('Exiting (%d)...') % i
91 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
97 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
100 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
102 def ps_page_count (ps_name):
103 header = open (ps_name).read (1024)
104 m = re.search ('\n%%Pages: ([0-9]+)', header)
106 return string.atoi (m.group (1))
111 sys.stdout.write ('''
118 ''' % ( _('Copyright (c) %s by') % '2001--2006',
120 _('Distributed under terms of the GNU General Public License.'),
121 _('It comes with NO WARRANTY.')))
124 def get_option_parser ():
125 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
126 version="@TOPLEVEL_VERSION@",
127 description=help_summary)
129 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
132 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
134 p.add_option ('-f', '--format',
135 help=_('''use output format FORMAT (texi [default], texi-html, latex, html)'''),
137 p.add_option ("-I", '--include', help=_('add DIR to include path'),
139 action='append', dest='include_path',
140 default=[os.path.abspath (os.getcwd ())])
142 p.add_option ("-o", '--output', help=_('write output to DIR'),
144 action='store', dest='output_name',
146 p.add_option ('-P', '--process', metavar=_("COMMAND"),
147 help = _ ("process ly_files using COMMAND FILE..."),
149 dest='process_cmd', default='lilypond -b eps')
151 p.add_option ('--pdf',
154 help="Create PDF files for use with PDFTeX",
157 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
158 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX'''
159 '''must use this with dvips -h INPUT.psfonts'''),
161 p.add_option ('-V', '--verbose', help=_("be verbose"),
166 p.add_option ('-w', '--warranty',
167 help=_("show warranty and copyright"),
171 p.add_option_group ('bugs',
172 description='''Report bugs via http://post.gmane.org/post.php'''
173 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
177 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
179 # Only use installed binary when we are installed too.
180 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
181 lilypond_binary = 'lilypond'
183 global_options = None
186 default_ly_options = { 'alt': "[image of music]" }
189 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
193 EXAMPLEINDENT = 'exampleindent'
195 FRAGMENT = 'fragment'
200 LINE_WIDTH = 'line-width'
201 NOFRAGMENT = 'nofragment'
202 NOINDENT = 'noindent'
207 OUTPUTIMAGE = 'outputimage'
210 PREAMBLE = 'preamble'
211 PRINTFILENAME = 'printfilename'
213 RAGGED_RIGHT = 'ragged-right'
214 RELATIVE = 'relative'
215 STAFFSIZE = 'staffsize'
218 VERBATIM = 'verbatim'
219 FONTLOAD = 'fontload'
220 FILENAME = 'filename'
224 # NOTIME has no opposite so it isn't part of this dictionary.
225 # NOQUOTE is used internally only.
227 NOFRAGMENT: FRAGMENT,
232 # Recognize special sequences in the input.
234 # (?P<name>regex) -- Assign result of REGEX to NAME.
235 # *? -- Match non-greedily.
236 # (?m) -- Multiline regex: Make ^ and $ match at each line.
237 # (?s) -- Make the dot match all characters including newline.
238 # (?x) -- Ignore whitespace in patterns.
250 (\s*(?P<options>.*?)\s*:)?\s*
258 \s*(?P<options>.*?)\s*
267 \s*(?P<options>.*?)\s*
269 \s*(?P<filename>.*?)\s*
276 (?P<code><!--\s.*?!-->)
279 'singleline_comment':
285 (?P<code><pre>.*?</pre>))''',
291 (?P<code><pre>\s.*?</pre>\s))''',
310 \s*(?P<options>.*?)\s*
321 \s*(?P<options>.*?)\s*
325 \\end\s*{lilypond})''',
333 \s*(?P<options>.*?)\s*
341 'singleline_comment':
364 \\end\s*{verbatim}))''',
373 (?P<filename>\S+))''',
377 ^[^\n]*?(?!@c\s+)[^\n]*?
381 \s*(?P<options>.*?)\s*
391 \s*(?P<options>.*?)\s*
394 ^@end\s+lilypond)\s''',
401 \s*(?P<options>.*?)\s*
412 @end\s+ignore))\s''',
414 'singleline_comment':
419 @c([ \t][^\n]*|)\n))''',
421 # Don't do this: It interferes with @code{@{}.
422 # 'verb': r'''(?P<code>@code{.*?})''',
430 @end\s+example\s))''',
439 'intertext': r',?\s*intertext=\".*?\"',
444 'intertext': r',?\s*intertext=\".*?\"',
445 'option_sep': '\s*,\s*',
449 'intertext': r',?\s*intertext=\".*?\"',
450 'option_sep': '\s*,\s*',
454 # Options without a pattern in ly_options.
471 RELATIVE: r'''\relative c%(relative_quotes)s''',
476 INDENT: r'''indent = %(indent)s''',
478 LINE_WIDTH: r'''line-width = %(line-width)s''',
480 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
482 RAGGED_RIGHT: r'''ragged-right = ##t''',
484 PACKED: r'''packed = ##t''',
496 \remove Time_signature_engraver
502 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
509 FILTER: r'''<lilypond %(options)s>
519 <a href="%(base)s.ly">''',
522 <img align="center" valign="center"
523 border="0" src="%(image)s" alt="%(alt)s">''',
525 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
527 QUOTE: r'''<blockquote>
540 \ifx\preLilyPondExample \undefined%%
543 \preLilyPondExample%%
545 \def\lilypondbook{}%%
546 \input %(base)s-systems.tex%%
547 \ifx\postLilyPondExample \undefined%%
550 \postLilyPondExample%%
554 PRINTFILENAME: '''\\texttt{%(filename)s}
557 QUOTE: r'''\begin{quotation}%(str)s
560 VERBATIM: r'''\noindent
561 \begin{verbatim}%(verb)s\end{verbatim}''',
563 FILTER: r'''\begin{lilypond}[%(options)s]
570 FILTER: r'''@lilypond[%(options)s]
576 @include %(base)s-systems.texi
580 OUTPUTIMAGE: r'''@noindent
582 @image{%(base)s,,,%(alt)s,%(ext)s}
586 <a href="%(base)s.ly">
587 <img align="center" valign="center"
588 border="0" src="%(image)s" alt="%(alt)s">
596 <a href="%(base)s.ly">
604 QUOTE: r'''@quotation
605 %(str)s@end quotation
612 VERBATIM: r'''@exampleindent 0
614 %(verb)s@end verbatim
620 # Maintain line numbers.
625 for f in [HTML, LATEX]:
626 for s in (QUOTE, VERBATIM):
627 output[f][s] = output[f][s].replace("\n"," ")
630 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
631 %%%% Options: [%(option_string)s]
632 \\include "lilypond-book-preamble.ly"
640 %% ****************************************************************
641 %% Start cut-&-pastable-section
642 %% ****************************************************************
645 #(define dump-extents #t)
646 %(font_dump_setting)s
660 %% ****************************************************************
661 %% ly snippet contents follows:
662 %% ****************************************************************
666 %% ****************************************************************
668 %% ****************************************************************
675 %% ****************************************************************
677 %% ****************************************************************
681 %% ****************************************************************
683 %% ****************************************************************
686 texinfo_line_widths = {
687 '@afourpaper': '160\\mm',
688 '@afourwide': '6.5\\in',
689 '@afourlatex': '150\\mm',
690 '@smallbook': '5\\in',
691 '@letterpaper': '6\\in',
694 def classic_lilypond_book_compatibility (key, value):
695 if key == 'singleline' and value == None:
696 return (RAGGED_RIGHT, None)
698 m = re.search ('relative\s*([-0-9])', key)
700 return ('relative', m.group (1))
702 m = re.match ('([0-9]+)pt', key)
704 return ('staffsize', m.group (1))
706 if key == 'indent' or key == 'line-width':
707 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
709 f = float (m.group (1))
710 return (key, '%f\\%s' % (f, m.group (2)))
714 def find_file (name):
715 for i in global_options.include_path:
716 full = os.path.join (i, name)
717 if os.path.exists (full):
720 error (_ ("file not found: %s") % name + '\n')
724 def verbatim_html (s):
725 return re.sub ('>', '>',
727 re.sub ('&', '&', s)))
729 def split_options (option_string):
731 if global_options.format == HTML:
732 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
733 for i in range(len(options)):
734 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
737 return re.split (format_res[global_options.format]['option_sep'],
741 def set_default_options (source):
742 global default_ly_options
743 if not default_ly_options.has_key (LINE_WIDTH):
744 if global_options.format == LATEX:
745 textwidth = get_latex_textwidth (source)
746 default_ly_options[LINE_WIDTH] = \
747 '''%.0f\\pt''' % textwidth
748 elif global_options.format == TEXINFO:
749 for (k, v) in texinfo_line_widths.items ():
750 # FIXME: @layout is usually not in
753 # \input texinfo @c -*-texinfo-*-
755 # Bluntly search first K items of
757 # s = chunks[0].replacement_text ()
758 if re.search (k, source[:1024]):
759 default_ly_options[LINE_WIDTH] = v
763 def replacement_text (self):
766 def filter_text (self):
767 return self.replacement_text ()
769 def ly_is_outdated (self):
772 def png_is_outdated (self):
778 class Substring (Chunk):
779 def __init__ (self, source, start, end, line_number):
783 self.line_number = line_number
784 self.override_text = None
789 def replacement_text (self):
790 if self.override_text:
791 return self.override_text
793 return self.source[self.start:self.end]
795 class Snippet (Chunk):
796 def __init__ (self, type, match, format, line_number):
800 self.option_dict = {}
802 self.line_number = line_number
804 def replacement_text (self):
805 return self.match.group ('match')
807 def substring (self, s):
808 return self.match.group (s)
811 return `self.__class__` + ' type = ' + self.type
813 class Include_snippet (Snippet):
814 def processed_filename (self):
815 f = self.substring ('filename')
816 return os.path.splitext (f)[0] + format2ext[global_options.format]
818 def replacement_text (self):
819 s = self.match.group ('match')
820 f = self.substring ('filename')
822 return re.sub (f, self.processed_filename (), s)
824 class Lilypond_snippet (Snippet):
825 def __init__ (self, type, match, format, line_number):
826 Snippet.__init__ (self, type, match, format, line_number)
827 os = match.group ('options')
828 self.do_options (os, self.type)
831 contents = self.substring ('code')
832 return ('\\sourcefileline %d\n%s'
833 % (self.line_number - 1, contents))
838 return self.compose_ly (s)
841 def do_options (self, option_string, type):
842 self.option_dict = {}
844 options = split_options (option_string)
847 if string.find (i, '=') > 0:
848 (key, value) = re.split ('\s*=\s*', i)
849 self.option_dict[key] = value
851 if i in no_options.keys ():
852 if no_options[i] in self.option_dict.keys ():
853 del self.option_dict[no_options[i]]
855 self.option_dict[i] = None
857 has_line_width = self.option_dict.has_key (LINE_WIDTH)
858 no_line_width_value = 0
860 # If LINE_WIDTH is used without parameter, set it to default.
861 if has_line_width and self.option_dict[LINE_WIDTH] == None:
862 no_line_width_value = 1
863 del self.option_dict[LINE_WIDTH]
865 for i in default_ly_options.keys ():
866 if i not in self.option_dict.keys ():
867 self.option_dict[i] = default_ly_options[i]
869 if not has_line_width:
870 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
871 self.option_dict[RAGGED_RIGHT] = None
873 if type == 'lilypond':
874 if LINE_WIDTH in self.option_dict.keys ():
875 del self.option_dict[LINE_WIDTH]
877 if RAGGED_RIGHT in self.option_dict.keys ():
878 if LINE_WIDTH in self.option_dict.keys ():
879 del self.option_dict[LINE_WIDTH]
881 if QUOTE in self.option_dict.keys () or type == 'lilypond':
882 if LINE_WIDTH in self.option_dict.keys ():
883 del self.option_dict[LINE_WIDTH]
885 if not INDENT in self.option_dict.keys ():
886 self.option_dict[INDENT] = '0\\mm'
888 # The QUOTE pattern from ly_options only emits the `line-width'
890 if has_line_width and QUOTE in self.option_dict.keys ():
891 if no_line_width_value:
892 del self.option_dict[LINE_WIDTH]
894 del self.option_dict[QUOTE]
896 def compose_ly (self, code):
897 if FRAGMENT in self.option_dict.keys ():
905 # The original concept of the `exampleindent' option is broken.
906 # It is not possible to get a sane value for @exampleindent at all
907 # without processing the document itself. Saying
915 # causes ugly results with the DVI backend of texinfo since the
916 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
917 # value). Executing the above code changes the environment
918 # indentation to an unknown value because we don't know the amount
919 # of 1em in advance since it is font-dependent. Modifying
920 # @exampleindent in the middle of a document is simply not
921 # supported within texinfo.
923 # As a consequence, the only function of @exampleindent is now to
924 # specify the amount of indentation for the `quote' option.
926 # To set @exampleindent locally to zero, we use the @format
927 # environment for non-quoted snippets.
928 override[EXAMPLEINDENT] = r'0.4\in'
929 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
930 override.update (default_ly_options)
933 for (key, value) in self.option_dict.items ():
935 option_list.append (key)
937 option_list.append (key + '=' + value)
938 option_string = string.join (option_list, ',')
941 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
942 for a in compose_types:
945 for (key, value) in self.option_dict.items ():
947 classic_lilypond_book_compatibility (key, value)
951 (_ ("deprecated ly-option used: %s=%s" \
954 (_ ("compatibility mode translation: %s=%s" \
958 (_ ("deprecated ly-option used: %s" \
961 (_ ("compatibility mode translation: %s" \
964 (key, value) = (c_key, c_value)
967 override[key] = value
969 if not override.has_key (key):
973 for type in compose_types:
974 if ly_options[type].has_key (key):
975 compose_dict[type].append (ly_options[type][key])
979 if not found and key not in simple_options:
980 warning (_ ("ignoring unknown ly option: %s") % key)
983 if RELATIVE in override.keys () and override[RELATIVE]:
984 relative = int (override[RELATIVE])
990 relative_quotes += ',' * (- relative)
992 relative_quotes += "'" * relative
994 paper_string = string.join (compose_dict[PAPER],
996 layout_string = string.join (compose_dict[LAYOUT],
998 notes_string = string.join (compose_dict[NOTES],
1000 preamble_string = string.join (compose_dict[PREAMBLE],
1003 font_dump_setting = ''
1004 if FONTLOAD in self.option_dict:
1005 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1007 d = globals().copy()
1009 return (PREAMBLE_LY + body) % d
1012 def get_hash (self):
1014 self.hash = abs (hash (self.full_ly ()))
1017 def basename (self):
1018 if FILENAME in self.option_dict:
1019 return self.option_dict[FILENAME]
1020 if global_options.use_hash:
1021 return 'lily-%d' % self.get_hash ()
1024 def write_ly (self):
1025 outf = open (self.basename () + '.ly', 'w')
1026 outf.write (self.full_ly ())
1028 open (self.basename () + '.txt', 'w').write ('image of music')
1030 def ly_is_outdated (self):
1031 base = self.basename ()
1033 tex_file = '%s.tex' % base
1034 eps_file = '%s.eps' % base
1035 system_file = '%s-systems.tex' % base
1036 ly_file = '%s.ly' % base
1037 ok = os.path.exists (ly_file) \
1038 and os.path.exists (system_file)\
1039 and os.stat (system_file)[stat.ST_SIZE] \
1040 and re.match ('% eof', open (system_file).readlines ()[-1])
1041 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1042 ok = (self.full_ly () == open (ly_file).read ())
1044 # TODO: Do something smart with target formats
1045 # (ps, png) and m/ctimes.
1049 def png_is_outdated (self):
1050 base = self.basename ()
1051 ok = not self.ly_is_outdated ()
1052 if global_options.format in (HTML, TEXINFO):
1053 ok = ok and os.path.exists (base + '.eps')
1057 page_count = ps_page_count (base + '.eps')
1060 ok = ok and os.path.exists (base + '.png')
1062 elif page_count > 1:
1063 for a in range (1, page_count + 1):
1064 ok = ok and os.path.exists (base + '-page%d.png' % a)
1068 def texstr_is_outdated (self):
1072 base = self.basename ()
1073 ok = self.ly_is_outdated ()
1074 ok = ok and (os.path.exists (base + '.texstr'))
1077 def filter_text (self):
1078 code = self.substring ('code')
1079 s = run_filter (code)
1082 'options': self.match.group ('options')
1085 return output[self.format][FILTER] % d
1087 def replacement_text (self):
1088 func = Lilypond_snippet.__dict__['output_' + self.format]
1091 def get_images (self):
1092 base = self.basename ()
1094 single = '%(base)s.png' % vars ()
1095 multiple = '%(base)s-page1.png' % vars ()
1097 if os.path.exists (multiple) \
1098 and (not os.path.exists (single) \
1099 or (os.stat (multiple)[stat.ST_MTIME] \
1100 > os.stat (single)[stat.ST_MTIME])):
1101 count = ps_page_count ('%(base)s.eps' % vars ())
1102 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1103 images = tuple (images)
1106 def output_html (self):
1108 base = self.basename ()
1109 if global_options.format == HTML:
1110 str += self.output_print_filename (HTML)
1111 if VERBATIM in self.option_dict:
1112 verb = verbatim_html (self.substring ('code'))
1113 str += output[HTML][VERBATIM] % vars ()
1114 if QUOTE in self.option_dict:
1115 str = output[HTML][QUOTE] % vars ()
1117 str += output[HTML][BEFORE] % vars ()
1118 for image in self.get_images ():
1119 (base, ext) = os.path.splitext (image)
1120 alt = self.option_dict[ALT]
1121 str += output[HTML][OUTPUT] % vars ()
1122 str += output[HTML][AFTER] % vars ()
1125 def output_info (self):
1127 for image in self.get_images ():
1128 (base, ext) = os.path.splitext (image)
1130 # URG, makeinfo implicitly prepends dot to extension.
1131 # Specifying no extension is most robust.
1133 alt = self.option_dict[ALT]
1134 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1136 base = self.basename ()
1137 str += output[global_options.format][OUTPUT] % vars ()
1140 def output_latex (self):
1142 base = self.basename ()
1143 if global_options.format == LATEX:
1144 str += self.output_print_filename (LATEX)
1145 if VERBATIM in self.option_dict:
1146 verb = self.substring ('code')
1147 str += (output[LATEX][VERBATIM] % vars ())
1149 str += (output[LATEX][OUTPUT] % vars ())
1151 ## todo: maintain breaks
1153 breaks = self.ly ().count ("\n")
1154 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1156 if QUOTE in self.option_dict:
1157 str = output[LATEX][QUOTE] % vars ()
1160 def output_print_filename (self, format):
1162 if PRINTFILENAME in self.option_dict:
1163 base = self.basename ()
1164 filename = self.substring ('filename')
1165 str = output[global_options.format][PRINTFILENAME] % vars ()
1169 def output_texinfo (self):
1171 if self.output_print_filename (TEXINFO):
1173 + self.output_print_filename (HTML)
1176 + self.output_print_filename (LATEX)
1178 base = self.basename ()
1179 if TEXIDOC in self.option_dict:
1180 texidoc = base + '.texidoc'
1181 if os.path.exists (texidoc):
1182 str += '@include %(texidoc)s\n\n' % vars ()
1184 if VERBATIM in self.option_dict:
1185 verb = self.substring ('code')
1186 str += (output[TEXINFO][VERBATIM] % vars ())
1187 if not QUOTE in self.option_dict:
1188 str = output[TEXINFO][NOQUOTE] % vars ()
1190 str += self.output_info ()
1192 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1193 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1194 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1196 if QUOTE in self.option_dict:
1197 str = output[TEXINFO][QUOTE] % vars ()
1199 # need par after image
1204 class Lilypond_file_snippet (Lilypond_snippet):
1206 name = self.substring ('filename')
1207 contents = open (find_file (name)).read ()
1209 ## strip version string to make automated regtest comparisons
1210 ## across versions easier.
1211 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1213 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1216 snippet_type_to_class = {
1217 'lilypond_file': Lilypond_file_snippet,
1218 'lilypond_block': Lilypond_snippet,
1219 'lilypond': Lilypond_snippet,
1220 'include': Include_snippet,
1223 def find_linestarts (s):
1228 i = s.find ('\n', start)
1236 nls.append (len (s))
1239 def find_toplevel_snippets (s, types):
1242 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1246 found = dict ([(t, None) for t in types])
1248 line_starts = find_linestarts (s)
1250 # We want to search for multiple regexes, without searching
1251 # the string multiple times for one regex.
1252 # Hence, we use earlier results to limit the string portion
1254 # Since every part of the string is traversed at most once for
1255 # every type of snippet, this is linear.
1261 if not found[type] or found[type][0] < index:
1264 m = res[type].search (s[index:endex])
1269 if snippet_type_to_class.has_key (type):
1270 cl = snippet_type_to_class[type]
1273 start = index + m.start ('match')
1274 line_number = line_start_idx
1275 while (line_starts[line_number] < start):
1279 snip = cl (type, m, global_options.format, line_number)
1281 found[type] = (start, snip)
1285 or found[type][0] < found[first][0]):
1290 # Limiting the search space is a cute
1291 # idea, but this *requires* to search
1292 # for possible containing blocks
1293 # first, at least as long as we do not
1294 # search for the start of blocks, but
1295 # always/directly for the entire
1296 # @block ... @end block.
1298 endex = found[first][0]
1301 snippets.append (Substring (s, index, len (s), line_start_idx))
1304 while (start > line_starts[line_start_idx+1]):
1307 (start, snip) = found[first]
1308 snippets.append (Substring (s, index, start, line_start_idx + 1))
1309 snippets.append (snip)
1311 index = start + len (snip.match.group ('match'))
1315 def filter_pipe (input, cmd):
1316 if global_options.verbose:
1317 progress (_ ("Opening filter `%s'") % cmd)
1319 (stdin, stdout, stderr) = os.popen3 (cmd)
1321 status = stdin.close ()
1325 output = stdout.read ()
1326 status = stdout.close ()
1327 error = stderr.read ()
1331 signal = 0x0f & status
1332 if status or (not output and error):
1333 exit_status = status >> 8
1334 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1335 error (_ ("The error log is as follows:"))
1336 sys.stderr.write (error)
1337 sys.stderr.write (stderr.read ())
1340 if global_options.verbose:
1346 return filter_pipe (s, global_options.filter_cmd)
1348 def is_derived_class (cl, baseclass):
1351 for b in cl.__bases__:
1352 if is_derived_class (b, baseclass):
1356 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1357 ly_names = filter (lambda x: x,
1358 map (Lilypond_snippet.basename, ly_snippets))
1359 texstr_names = filter (lambda x: x,
1360 map (Lilypond_snippet.basename, texstr_snippets))
1362 png_names = filter (lambda x: x,
1363 map (Lilypond_snippet.basename, png_snippets))
1366 def my_system (cmd):
1367 status = ly.system (cmd,
1368 be_verbose=global_options.verbose,
1371 if global_options.format in (HTML, TEXINFO):
1372 cmd += ' --formats=png '
1375 # the --process=CMD switch is a bad idea
1376 # it is too generic for lilypond-book.
1378 my_system (string.join ([cmd, '--backend texstr',
1379 'snippet-map.ly'] + texstr_names))
1380 for l in texstr_names:
1381 my_system ('latex %s.texstr' % l)
1384 my_system (string.join ([cmd, 'snippet-map.ly'] + ly_names))
1386 LATEX_INSPECTION_DOCUMENT = r'''
1390 \typeout{textwidth=\the\textwidth}
1391 \typeout{columnsep=\the\columnsep}
1392 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1396 # Do we need anything else besides `textwidth'?
1397 def get_latex_textwidth (source):
1398 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1400 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1402 ## what's a sensible default?
1405 preamble = source[:m.start (0)]
1406 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1408 (handle, tmpfile) = tempfile.mkstemp('.tex')
1409 logfile = os.path.splitext (tmpfile)[0] + '.log'
1410 logfile = os.path.split (logfile)[1]
1412 tmp_handle = os.fdopen (handle,'w')
1413 tmp_handle.write (latex_document)
1416 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1417 parameter_string = open (logfile).read()
1423 m = re.search ('columns=([0-9.]*)', parameter_string)
1425 columns = int (m.group (1))
1428 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1430 columnsep = float (m.group (1))
1433 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1435 textwidth = float (m.group (1))
1437 textwidth = (textwidth - columnsep) / columns
1441 def modify_preamble (chunk):
1442 str = chunk.replacement_text ()
1443 if (re.search (r"\\begin *{document}", str)
1444 and not re.search ("{graphic[sx]", str)):
1445 str = re.sub (r"\\begin{document}",
1446 r"\\usepackage{graphics}" + '\n'
1447 + r"\\begin{document}",
1449 chunk.override_text = str
1461 '.texinfo': TEXINFO,
1467 # TEXINFO: '.texinfo',
1472 class Compile_error:
1475 def write_file_map (lys, name):
1476 snippet_map = open ('snippet-map.ly', 'w')
1477 snippet_map.write ("""
1478 #(define version-seen #t)
1479 #(ly:add-file-name-alist '(
1482 snippet_map.write ('("%s.ly" . "%s")\n'
1486 snippet_map.write ('))\n')
1488 def do_process_cmd (chunks, input_name):
1489 all_lys = filter (lambda x: is_derived_class (x.__class__,
1493 write_file_map (all_lys, input_name)
1494 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1496 and x.ly_is_outdated (), chunks)
1497 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1499 and x.texstr_is_outdated (),
1501 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1503 and x.png_is_outdated (),
1506 outdated = png_outdated + texstr_outdated + ly_outdated
1508 progress (_ ("Writing snippets..."))
1509 map (Lilypond_snippet.write_ly, ly_outdated)
1513 progress (_ ("Processing..."))
1515 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1517 progress (_ ("All snippets are up to date..."))
1520 def guess_format (input_filename):
1522 e = os.path.splitext (input_filename)[1]
1523 if e in ext2format.keys ():
1525 format = ext2format[e]
1527 error (_ ("can't determine format for: %s" \
1532 def write_if_updated (file_name, lines):
1534 f = open (file_name)
1536 new_str = string.join (lines, '')
1537 if oldstr == new_str:
1538 progress (_ ("%s is up to date.") % file_name)
1544 progress (_ ("Writing `%s'...") % file_name)
1545 open (file_name, 'w').writelines (lines)
1548 def note_input_file (name, inputs=[]):
1549 ## hack: inputs is mutable!
1550 inputs.append (name)
1553 def samefile (f1, f2):
1555 return os.path.samefile (f1, f2)
1556 except AttributeError: # Windoze
1557 f1 = re.sub ("//*", "/", f1)
1558 f2 = re.sub ("//*", "/", f2)
1561 def do_file (input_filename):
1563 if not input_filename or input_filename == '-':
1564 in_handle = sys.stdin
1565 input_fullname = '<stdin>'
1567 if os.path.exists (input_filename):
1568 input_fullname = input_filename
1569 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1570 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1572 input_fullname = find_file (input_filename)
1574 note_input_file (input_fullname)
1575 in_handle = open (input_fullname)
1577 if input_filename == '-':
1578 input_base = 'stdin'
1580 input_base = os.path.basename \
1581 (os.path.splitext (input_filename)[0])
1583 # Only default to stdout when filtering.
1584 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1585 output_filename = '-'
1586 output_file = sys.stdout
1588 # don't complain when global_options.output_name is existing
1589 output_filename = input_base + format2ext[global_options.format]
1590 if global_options.output_name:
1591 if not os.path.isdir (global_options.output_name):
1592 os.mkdir (global_options.output_name, 0777)
1593 os.chdir (global_options.output_name)
1595 if (os.path.exists (input_filename)
1596 and os.path.exists (output_filename)
1597 and samefile (output_filename, input_fullname)):
1599 _ ("Output would overwrite input file; use --output."))
1603 progress (_ ("Reading %s...") % input_fullname)
1604 source = in_handle.read ()
1607 set_default_options (source)
1610 # FIXME: Containing blocks must be first, see
1611 # find_toplevel_snippets.
1613 'multiline_comment',
1617 'singleline_comment',
1622 progress (_ ("Dissecting..."))
1623 chunks = find_toplevel_snippets (source, snippet_types)
1625 if global_options.format == LATEX:
1627 if (c.is_plain () and
1628 re.search (r"\\begin *{document}", c.replacement_text())):
1633 if global_options.filter_cmd:
1634 write_if_updated (output_filename,
1635 [c.filter_text () for c in chunks])
1636 elif global_options.process_cmd:
1637 do_process_cmd (chunks, input_fullname)
1638 progress (_ ("Compiling %s...") % output_filename)
1640 write_if_updated (output_filename,
1641 [s.replacement_text ()
1644 def process_include (snippet):
1645 os.chdir (original_dir)
1646 name = snippet.substring ('filename')
1647 progress (_ ("Processing include: %s") % name)
1649 return do_file (name)
1651 include_chunks = map (process_include,
1652 filter (lambda x: is_derived_class (x.__class__,
1657 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1659 except Compile_error:
1660 os.chdir (original_dir)
1661 progress (_ ("Removing `%s'") % output_filename)
1667 global global_options
1669 opt_parser = get_option_parser()
1670 (global_options, args) = opt_parser.parse_args ()
1672 if global_options.format in ('texi-html', 'texi'):
1673 global_options.format = TEXINFO
1674 global_options.use_hash = True
1676 global_options.include_path = map (os.path.abspath, global_options.include_path)
1678 if global_options.warranty:
1681 if not args or len (args) > 1:
1682 opt_parser.print_help ()
1688 files = do_options ()
1692 basename = os.path.splitext (file)[0]
1693 basename = os.path.split (basename)[1]
1695 if not global_options.format:
1696 global_options.format = guess_format (files[0])
1699 if global_options.format in (TEXINFO, HTML):
1703 if global_options.process_cmd == '':
1704 global_options.process_cmd = (lilypond_binary
1705 + ' --formats=%s --backend eps ' % formats)
1707 if global_options.process_cmd:
1708 global_options.process_cmd += string.join ([(' -I %s' % commands.mkarg (p))
1709 for p in global_options.include_path])
1711 if (global_options.format in (TEXINFO, LATEX)
1712 and global_options.create_pdf):
1713 global_options.process_cmd += "--pdf -deps-font-include -dgs-font-load "
1715 if global_options.verbose:
1716 global_options.process_cmd += " --verbose "
1720 chunks = do_file (file)
1721 if global_options.psfonts:
1722 fontextract.verbose = global_options.verbose
1723 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1727 psfonts_file = basename + '.psfonts'
1728 if not global_options.verbose:
1729 progress (_ ("Writing fonts to %s...") % psfonts_file)
1730 fontextract.extract_fonts (psfonts_file,
1731 [x.basename() + '.eps'
1732 for x in snippet_chunks])
1733 if not global_options.verbose:
1736 except Compile_error:
1739 if global_options.format in (TEXINFO, LATEX):
1740 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1741 output = os.path.join (global_options.output_name, basename + '.dvi' )
1743 if not global_options.psfonts and not global_options.create_pdf:
1744 warning (_ ("option --psfonts not used"))
1745 warning (_ ("processing with dvips will have no fonts"))
1748 progress (_ ("DVIPS usage:"))
1750 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1753 inputs = note_input_file ('')
1756 base_file_name = os.path.splitext (os.path.basename (file))[0]
1757 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1758 final_output_file = os.path.join (global_options.output_name,
1760 + '.%s' % global_options.format)
1762 os.chdir (original_dir)
1763 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1765 if __name__ == '__main__':