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.pathsep + 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, texinfo or DocBook 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, docbook)'''),
138 p.add_option ("-I", '--include', help=_('add DIR to include path'),
140 action='append', dest='include_path',
141 default=[os.path.abspath (os.getcwd ())])
143 p.add_option ("-o", '--output', help=_('write output to DIR'),
145 action='store', dest='output_name',
147 p.add_option ('-P', '--process', metavar=_("COMMAND"),
148 help = _ ("process ly_files using COMMAND FILE..."),
150 dest='process_cmd', default='lilypond -b eps')
152 p.add_option ('--pdf',
155 help="Create PDF files for use with PDFTeX",
158 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
159 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
160 must use this with dvips -h INPUT.psfonts'''),
162 p.add_option ('-V', '--verbose', help=_("be verbose"),
167 p.add_option ('-w', '--warranty',
168 help=_("show warranty and copyright"),
172 p.add_option_group ('bugs',
173 description='''Report bugs via http://post.gmane.org/post.php'''
174 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
178 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
180 # Only use installed binary when we are installed too.
181 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
182 lilypond_binary = 'lilypond'
184 global_options = None
187 default_ly_options = { 'alt': "[image of music]" }
190 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
195 EXAMPLEINDENT = 'exampleindent'
197 FRAGMENT = 'fragment'
202 LINE_WIDTH = 'line-width'
203 NOFRAGMENT = 'nofragment'
204 NOINDENT = 'noindent'
209 OUTPUTIMAGE = 'outputimage'
212 PREAMBLE = 'preamble'
213 PRINTFILENAME = 'printfilename'
215 RAGGED_RIGHT = 'ragged-right'
216 RELATIVE = 'relative'
217 STAFFSIZE = 'staffsize'
220 VERBATIM = 'verbatim'
221 FONTLOAD = 'fontload'
222 FILENAME = 'filename'
226 # NOTIME has no opposite so it isn't part of this dictionary.
227 # NOQUOTE is used internally only.
229 NOFRAGMENT: FRAGMENT,
234 # Recognize special sequences in the input.
236 # (?P<name>regex) -- Assign result of REGEX to NAME.
237 # *? -- Match non-greedily.
238 # (?m) -- Multiline regex: Make ^ and $ match at each line.
239 # (?s) -- Make the dot match all characters including newline.
240 # (?x) -- Ignore whitespace in patterns.
251 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
256 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
261 <(?P<inline>(inline)?)mediaobject>\s*<imageobject.*?>\s*<imagedata\s+fileref="(?P<filename>.*?\.ly)"\s*(role="(?P<options>.*?)")?\s*(/>|>\s*</imagedata>)\s*</imageobject>\s*</(inline)?mediaobject>)''',
267 (?P<code><!--\s.*?!-->)
270 'singleline_comment':
289 (\s*(?P<options>.*?)\s*:)?\s*
297 \s*(?P<options>.*?)\s*
306 \s*(?P<options>.*?)\s*
308 \s*(?P<filename>.*?)\s*
315 (?P<code><!--\s.*?!-->)
318 'singleline_comment':
324 (?P<code><pre>.*?</pre>))''',
330 (?P<code><pre>\s.*?</pre>\s))''',
349 \s*(?P<options>.*?)\s*
360 \s*(?P<options>.*?)\s*
364 \\end\s*{lilypond})''',
372 \s*(?P<options>.*?)\s*
380 'singleline_comment':
403 \\end\s*{verbatim}))''',
412 (?P<filename>\S+))''',
416 ^[^\n]*?(?!@c\s+)[^\n]*?
420 \s*(?P<options>.*?)\s*
430 \s*(?P<options>.*?)\s*
433 ^@end\s+lilypond)\s''',
440 \s*(?P<options>.*?)\s*
451 @end\s+ignore))\s''',
453 'singleline_comment':
458 @c([ \t][^\n]*|)\n))''',
460 # Don't do this: It interferes with @code{@{}.
461 # 'verb': r'''(?P<code>@code{.*?})''',
469 @end\s+example\s))''',
478 'intertext': r',?\s*intertext=\".*?\"',
482 'intertext': r',?\s*intertext=\".*?\"',
487 'intertext': r',?\s*intertext=\".*?\"',
488 'option_sep': '\s*,\s*',
492 'intertext': r',?\s*intertext=\".*?\"',
493 'option_sep': '\s*,\s*',
497 # Options without a pattern in ly_options.
514 RELATIVE: r'''\relative c%(relative_quotes)s''',
519 INDENT: r'''indent = %(indent)s''',
521 LINE_WIDTH: r'''line-width = %(line-width)s''',
523 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
525 RAGGED_RIGHT: r'''ragged-right = ##t''',
527 PACKED: r'''packed = ##t''',
539 \remove Time_signature_engraver
545 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
552 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
555 <imageobject role="latex">
556 <imagedata fileref="%(base)s.pdf" format="PDF"/>
558 <imageobject role="html">
559 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
561 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
563 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
567 FILTER: r'''<lilypond %(options)s>
577 <a href="%(base)s.ly">''',
580 <img align="center" valign="center"
581 border="0" src="%(image)s" alt="%(alt)s">''',
583 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
585 QUOTE: r'''<blockquote>
598 \ifx\preLilyPondExample \undefined%%
601 \preLilyPondExample%%
603 \def\lilypondbook{}%%
604 \input %(base)s-systems.tex%%
605 \ifx\postLilyPondExample \undefined%%
608 \postLilyPondExample%%
612 PRINTFILENAME: '''\\texttt{%(filename)s}
615 QUOTE: r'''\begin{quotation}%(str)s
618 VERBATIM: r'''\noindent
619 \begin{verbatim}%(verb)s\end{verbatim}''',
621 FILTER: r'''\begin{lilypond}[%(options)s]
628 FILTER: r'''@lilypond[%(options)s]
634 @include %(base)s-systems.texi
638 OUTPUTIMAGE: r'''@noindent
640 @image{%(base)s,,,%(alt)s,%(ext)s}
644 <a href="%(base)s.ly">
645 <img align="center" valign="center"
646 border="0" src="%(image)s" alt="%(alt)s">
654 <a href="%(base)s.ly">
662 QUOTE: r'''@quotation
663 %(str)s@end quotation
670 VERBATIM: r'''@exampleindent 0
672 %(verb)s@end verbatim
678 # Maintain line numbers.
683 for f in [HTML, LATEX]:
684 for s in (QUOTE, VERBATIM):
685 output[f][s] = output[f][s].replace("\n"," ")
688 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
689 %%%% Options: [%(option_string)s]
690 \\include "lilypond-book-preamble.ly"
698 %% ****************************************************************
699 %% Start cut-&-pastable-section
700 %% ****************************************************************
703 #(define dump-extents #t)
704 %(font_dump_setting)s
718 %% ****************************************************************
719 %% ly snippet contents follows:
720 %% ****************************************************************
724 %% ****************************************************************
726 %% ****************************************************************
733 %% ****************************************************************
735 %% ****************************************************************
739 %% ****************************************************************
741 %% ****************************************************************
744 texinfo_line_widths = {
745 '@afourpaper': '160\\mm',
746 '@afourwide': '6.5\\in',
747 '@afourlatex': '150\\mm',
748 '@smallbook': '5\\in',
749 '@letterpaper': '6\\in',
752 def classic_lilypond_book_compatibility (key, value):
753 if key == 'singleline' and value == None:
754 return (RAGGED_RIGHT, None)
756 m = re.search ('relative\s*([-0-9])', key)
758 return ('relative', m.group (1))
760 m = re.match ('([0-9]+)pt', key)
762 return ('staffsize', m.group (1))
764 if key == 'indent' or key == 'line-width':
765 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
767 f = float (m.group (1))
768 return (key, '%f\\%s' % (f, m.group (2)))
772 def find_file (name):
773 for i in global_options.include_path:
774 full = os.path.join (i, name)
775 if os.path.exists (full):
778 error (_ ("file not found: %s") % name + '\n')
782 def verbatim_html (s):
783 return re.sub ('>', '>',
785 re.sub ('&', '&', s)))
787 def split_options (option_string):
789 if global_options.format == HTML:
790 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
791 for i in range(len(options)):
792 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
795 return re.split (format_res[global_options.format]['option_sep'],
799 def set_default_options (source):
800 global default_ly_options
801 if not default_ly_options.has_key (LINE_WIDTH):
802 if global_options.format == LATEX:
803 textwidth = get_latex_textwidth (source)
804 default_ly_options[LINE_WIDTH] = \
805 '''%.0f\\pt''' % textwidth
806 elif global_options.format == TEXINFO:
807 for (k, v) in texinfo_line_widths.items ():
808 # FIXME: @layout is usually not in
811 # \input texinfo @c -*-texinfo-*-
813 # Bluntly search first K items of
815 # s = chunks[0].replacement_text ()
816 if re.search (k, source[:1024]):
817 default_ly_options[LINE_WIDTH] = v
821 def replacement_text (self):
824 def filter_text (self):
825 return self.replacement_text ()
827 def ly_is_outdated (self):
830 def png_is_outdated (self):
836 class Substring (Chunk):
837 def __init__ (self, source, start, end, line_number):
841 self.line_number = line_number
842 self.override_text = None
847 def replacement_text (self):
848 if self.override_text:
849 return self.override_text
851 return self.source[self.start:self.end]
853 class Snippet (Chunk):
854 def __init__ (self, type, match, format, line_number):
858 self.option_dict = {}
860 self.line_number = line_number
862 def replacement_text (self):
863 return self.match.group ('match')
865 def substring (self, s):
866 return self.match.group (s)
869 return `self.__class__` + ' type = ' + self.type
871 class Include_snippet (Snippet):
872 def processed_filename (self):
873 f = self.substring ('filename')
874 return os.path.splitext (f)[0] + format2ext[global_options.format]
876 def replacement_text (self):
877 s = self.match.group ('match')
878 f = self.substring ('filename')
880 return re.sub (f, self.processed_filename (), s)
882 class Lilypond_snippet (Snippet):
883 def __init__ (self, type, match, format, line_number):
884 Snippet.__init__ (self, type, match, format, line_number)
885 os = match.group ('options')
886 self.do_options (os, self.type)
889 contents = self.substring ('code')
890 return ('\\sourcefileline %d\n%s'
891 % (self.line_number - 1, contents))
896 return self.compose_ly (s)
899 def do_options (self, option_string, type):
900 self.option_dict = {}
902 options = split_options (option_string)
906 (key, value) = re.split ('\s*=\s*', i)
907 self.option_dict[key] = value
909 if i in no_options.keys ():
910 if no_options[i] in self.option_dict.keys ():
911 del self.option_dict[no_options[i]]
913 self.option_dict[i] = None
915 has_line_width = self.option_dict.has_key (LINE_WIDTH)
916 no_line_width_value = 0
918 # If LINE_WIDTH is used without parameter, set it to default.
919 if has_line_width and self.option_dict[LINE_WIDTH] == None:
920 no_line_width_value = 1
921 del self.option_dict[LINE_WIDTH]
923 for i in default_ly_options.keys ():
924 if i not in self.option_dict.keys ():
925 self.option_dict[i] = default_ly_options[i]
927 if not has_line_width:
928 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
929 self.option_dict[RAGGED_RIGHT] = None
931 if type == 'lilypond':
932 if LINE_WIDTH in self.option_dict.keys ():
933 del self.option_dict[LINE_WIDTH]
935 if RAGGED_RIGHT in self.option_dict.keys ():
936 if LINE_WIDTH in self.option_dict.keys ():
937 del self.option_dict[LINE_WIDTH]
939 if QUOTE in self.option_dict.keys () or type == 'lilypond':
940 if LINE_WIDTH in self.option_dict.keys ():
941 del self.option_dict[LINE_WIDTH]
943 if not INDENT in self.option_dict.keys ():
944 self.option_dict[INDENT] = '0\\mm'
946 # The QUOTE pattern from ly_options only emits the `line-width'
948 if has_line_width and QUOTE in self.option_dict.keys ():
949 if no_line_width_value:
950 del self.option_dict[LINE_WIDTH]
952 del self.option_dict[QUOTE]
954 def compose_ly (self, code):
955 if FRAGMENT in self.option_dict.keys ():
963 # The original concept of the `exampleindent' option is broken.
964 # It is not possible to get a sane value for @exampleindent at all
965 # without processing the document itself. Saying
973 # causes ugly results with the DVI backend of texinfo since the
974 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
975 # value). Executing the above code changes the environment
976 # indentation to an unknown value because we don't know the amount
977 # of 1em in advance since it is font-dependent. Modifying
978 # @exampleindent in the middle of a document is simply not
979 # supported within texinfo.
981 # As a consequence, the only function of @exampleindent is now to
982 # specify the amount of indentation for the `quote' option.
984 # To set @exampleindent locally to zero, we use the @format
985 # environment for non-quoted snippets.
986 override[EXAMPLEINDENT] = r'0.4\in'
987 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
988 override.update (default_ly_options)
991 for (key, value) in self.option_dict.items ():
993 option_list.append (key)
995 option_list.append (key + '=' + value)
996 option_string = string.join (option_list, ',')
999 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1000 for a in compose_types:
1001 compose_dict[a] = []
1003 for (key, value) in self.option_dict.items ():
1004 (c_key, c_value) = \
1005 classic_lilypond_book_compatibility (key, value)
1009 (_ ("deprecated ly-option used: %s=%s" \
1012 (_ ("compatibility mode translation: %s=%s" \
1013 % (c_key, c_value)))
1016 (_ ("deprecated ly-option used: %s" \
1019 (_ ("compatibility mode translation: %s" \
1022 (key, value) = (c_key, c_value)
1025 override[key] = value
1027 if not override.has_key (key):
1028 override[key] = None
1031 for type in compose_types:
1032 if ly_options[type].has_key (key):
1033 compose_dict[type].append (ly_options[type][key])
1037 if not found and key not in simple_options:
1038 warning (_ ("ignoring unknown ly option: %s") % key)
1041 if RELATIVE in override.keys () and override[RELATIVE]:
1042 relative = int (override[RELATIVE])
1044 relative_quotes = ''
1048 relative_quotes += ',' * (- relative)
1050 relative_quotes += "'" * relative
1052 paper_string = string.join (compose_dict[PAPER],
1054 layout_string = string.join (compose_dict[LAYOUT],
1056 notes_string = string.join (compose_dict[NOTES],
1058 preamble_string = string.join (compose_dict[PREAMBLE],
1061 font_dump_setting = ''
1062 if FONTLOAD in self.option_dict:
1063 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1065 d = globals().copy()
1067 return (PREAMBLE_LY + body) % d
1070 def get_hash (self):
1072 self.hash = abs (hash (self.full_ly ()))
1075 def basename (self):
1076 if FILENAME in self.option_dict:
1077 return self.option_dict[FILENAME]
1078 if global_options.use_hash:
1079 return 'lily-%d' % self.get_hash ()
1082 def write_ly (self):
1083 outf = open (self.basename () + '.ly', 'w')
1084 outf.write (self.full_ly ())
1086 open (self.basename () + '.txt', 'w').write ('image of music')
1088 def ly_is_outdated (self):
1089 base = self.basename ()
1091 tex_file = '%s.tex' % base
1092 eps_file = '%s.eps' % base
1093 system_file = '%s-systems.tex' % base
1094 ly_file = '%s.ly' % base
1095 ok = os.path.exists (ly_file) \
1096 and os.path.exists (system_file)\
1097 and os.stat (system_file)[stat.ST_SIZE] \
1098 and re.match ('% eof', open (system_file).readlines ()[-1])
1099 if ok and (not global_options.use_hash or FILENAME in self.option_dict):
1100 ok = (self.full_ly () == open (ly_file).read ())
1102 # TODO: Do something smart with target formats
1103 # (ps, png) and m/ctimes.
1107 def png_is_outdated (self):
1108 base = self.basename ()
1109 ok = not self.ly_is_outdated ()
1110 if global_options.format in (HTML, TEXINFO):
1111 ok = ok and os.path.exists (base + '.eps')
1115 page_count = ps_page_count (base + '.eps')
1118 ok = ok and os.path.exists (base + '.png')
1120 elif page_count > 1:
1121 for a in range (1, page_count + 1):
1122 ok = ok and os.path.exists (base + '-page%d.png' % a)
1126 def texstr_is_outdated (self):
1130 base = self.basename ()
1131 ok = self.ly_is_outdated ()
1132 ok = ok and (os.path.exists (base + '.texstr'))
1135 def filter_text (self):
1136 code = self.substring ('code')
1137 s = run_filter (code)
1140 'options': self.match.group ('options')
1143 return output[self.format][FILTER] % d
1145 def replacement_text (self):
1146 func = Lilypond_snippet.__dict__['output_' + self.format]
1149 def get_images (self):
1150 base = self.basename ()
1152 single = '%(base)s.png' % vars ()
1153 multiple = '%(base)s-page1.png' % vars ()
1155 if os.path.exists (multiple) \
1156 and (not os.path.exists (single) \
1157 or (os.stat (multiple)[stat.ST_MTIME] \
1158 > os.stat (single)[stat.ST_MTIME])):
1159 count = ps_page_count ('%(base)s.eps' % vars ())
1160 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1161 images = tuple (images)
1164 def output_docbook (self):
1166 base = self.basename ()
1167 for image in self.get_images ():
1168 (base, ext) = os.path.splitext (image)
1169 str += output[DOCBOOK][OUTPUT] % vars ()
1170 str += self.output_print_filename (DOCBOOK)
1171 if (self.substring('inline') == 'inline'):
1172 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1174 str = '<mediaobject>' + str + '</mediaobject>'
1175 if VERBATIM in self.option_dict:
1176 verb = verbatim_html (self.substring ('code'))
1177 str = output[DOCBOOK][VERBATIM] % vars () + str
1180 def output_html (self):
1182 base = self.basename ()
1183 if global_options.format == HTML:
1184 str += self.output_print_filename (HTML)
1185 if VERBATIM in self.option_dict:
1186 verb = verbatim_html (self.substring ('code'))
1187 str += output[HTML][VERBATIM] % vars ()
1188 if QUOTE in self.option_dict:
1189 str = output[HTML][QUOTE] % vars ()
1191 str += output[HTML][BEFORE] % vars ()
1192 for image in self.get_images ():
1193 (base, ext) = os.path.splitext (image)
1194 alt = self.option_dict[ALT]
1195 str += output[HTML][OUTPUT] % vars ()
1196 str += output[HTML][AFTER] % vars ()
1199 def output_info (self):
1201 for image in self.get_images ():
1202 (base, ext) = os.path.splitext (image)
1204 # URG, makeinfo implicitly prepends dot to extension.
1205 # Specifying no extension is most robust.
1207 alt = self.option_dict[ALT]
1208 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1210 base = self.basename ()
1211 str += output[global_options.format][OUTPUT] % vars ()
1214 def output_latex (self):
1216 base = self.basename ()
1217 if global_options.format == LATEX:
1218 str += self.output_print_filename (LATEX)
1219 if VERBATIM in self.option_dict:
1220 verb = self.substring ('code')
1221 str += (output[LATEX][VERBATIM] % vars ())
1223 str += (output[LATEX][OUTPUT] % vars ())
1225 ## todo: maintain breaks
1227 breaks = self.ly ().count ("\n")
1228 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1230 if QUOTE in self.option_dict:
1231 str = output[LATEX][QUOTE] % vars ()
1234 def output_print_filename (self, format):
1236 if PRINTFILENAME in self.option_dict:
1237 base = self.basename ()
1238 filename = self.substring ('filename')
1239 str = output[global_options.format][PRINTFILENAME] % vars ()
1243 def output_texinfo (self):
1245 if self.output_print_filename (TEXINFO):
1247 + self.output_print_filename (HTML)
1250 + self.output_print_filename (LATEX)
1252 base = self.basename ()
1253 if TEXIDOC in self.option_dict:
1254 texidoc = base + '.texidoc'
1255 if os.path.exists (texidoc):
1256 str += '@include %(texidoc)s\n\n' % vars ()
1258 if VERBATIM in self.option_dict:
1259 verb = self.substring ('code')
1260 str += (output[TEXINFO][VERBATIM] % vars ())
1261 if not QUOTE in self.option_dict:
1262 str = output[TEXINFO][NOQUOTE] % vars ()
1264 str += self.output_info ()
1266 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1267 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1268 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1270 if QUOTE in self.option_dict:
1271 str = output[TEXINFO][QUOTE] % vars ()
1273 # need par after image
1278 class Lilypond_file_snippet (Lilypond_snippet):
1280 name = self.substring ('filename')
1281 contents = open (find_file (name)).read ()
1283 ## strip version string to make automated regtest comparisons
1284 ## across versions easier.
1285 contents = re.sub (r'\\version *"[^"]*"', '', contents)
1287 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1290 snippet_type_to_class = {
1291 'lilypond_file': Lilypond_file_snippet,
1292 'lilypond_block': Lilypond_snippet,
1293 'lilypond': Lilypond_snippet,
1294 'include': Include_snippet,
1297 def find_linestarts (s):
1302 i = s.find ('\n', start)
1310 nls.append (len (s))
1313 def find_toplevel_snippets (s, types):
1316 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1320 found = dict ([(t, None) for t in types])
1322 line_starts = find_linestarts (s)
1324 # We want to search for multiple regexes, without searching
1325 # the string multiple times for one regex.
1326 # Hence, we use earlier results to limit the string portion
1328 # Since every part of the string is traversed at most once for
1329 # every type of snippet, this is linear.
1335 if not found[type] or found[type][0] < index:
1338 m = res[type].search (s[index:endex])
1343 if snippet_type_to_class.has_key (type):
1344 cl = snippet_type_to_class[type]
1347 start = index + m.start ('match')
1348 line_number = line_start_idx
1349 while (line_starts[line_number] < start):
1353 snip = cl (type, m, global_options.format, line_number)
1355 found[type] = (start, snip)
1359 or found[type][0] < found[first][0]):
1364 # Limiting the search space is a cute
1365 # idea, but this *requires* to search
1366 # for possible containing blocks
1367 # first, at least as long as we do not
1368 # search for the start of blocks, but
1369 # always/directly for the entire
1370 # @block ... @end block.
1372 endex = found[first][0]
1375 snippets.append (Substring (s, index, len (s), line_start_idx))
1378 while (start > line_starts[line_start_idx+1]):
1381 (start, snip) = found[first]
1382 snippets.append (Substring (s, index, start, line_start_idx + 1))
1383 snippets.append (snip)
1385 index = start + len (snip.match.group ('match'))
1389 def filter_pipe (input, cmd):
1390 if global_options.verbose:
1391 progress (_ ("Opening filter `%s'") % cmd)
1393 (stdin, stdout, stderr) = os.popen3 (cmd)
1395 status = stdin.close ()
1399 output = stdout.read ()
1400 status = stdout.close ()
1401 error = stderr.read ()
1405 signal = 0x0f & status
1406 if status or (not output and error):
1407 exit_status = status >> 8
1408 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1409 error (_ ("The error log is as follows:"))
1410 sys.stderr.write (error)
1411 sys.stderr.write (stderr.read ())
1414 if global_options.verbose:
1420 return filter_pipe (s, global_options.filter_cmd)
1422 def is_derived_class (cl, baseclass):
1425 for b in cl.__bases__:
1426 if is_derived_class (b, baseclass):
1430 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1431 ly_names = filter (lambda x: x,
1432 map (Lilypond_snippet.basename, ly_snippets))
1433 texstr_names = filter (lambda x: x,
1434 map (Lilypond_snippet.basename, texstr_snippets))
1436 png_names = filter (lambda x: x,
1437 map (Lilypond_snippet.basename, png_snippets))
1440 def my_system (cmd):
1441 status = ly.system (cmd,
1442 be_verbose=global_options.verbose,
1445 if global_options.format in (HTML, TEXINFO):
1446 cmd += ' --formats=png '
1447 if global_options.format in (DOCBOOK):
1448 cmd += ' --formats=png,pdf '
1450 # the --process=CMD switch is a bad idea
1451 # it is too generic for lilypond-book.
1453 my_system (string.join ([cmd, '--backend texstr',
1454 'snippet-map.ly'] + texstr_names))
1455 for l in texstr_names:
1456 my_system ('latex %s.texstr' % l)
1459 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1462 my_system (string.join ([cmd, 'snippet-names']))
1465 LATEX_INSPECTION_DOCUMENT = r'''
1469 \typeout{textwidth=\the\textwidth}
1470 \typeout{columnsep=\the\columnsep}
1471 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1475 # Do we need anything else besides `textwidth'?
1476 def get_latex_textwidth (source):
1477 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1479 warning (_ ("Can't find \\begin{document} in LaTeX document"))
1481 ## what's a sensible default?
1484 preamble = source[:m.start (0)]
1485 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1487 (handle, tmpfile) = tempfile.mkstemp('.tex')
1488 logfile = os.path.splitext (tmpfile)[0] + '.log'
1489 logfile = os.path.split (logfile)[1]
1491 tmp_handle = os.fdopen (handle,'w')
1492 tmp_handle.write (latex_document)
1495 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1496 parameter_string = open (logfile).read()
1502 m = re.search ('columns=([0-9.]*)', parameter_string)
1504 columns = int (m.group (1))
1507 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1509 columnsep = float (m.group (1))
1512 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1514 textwidth = float (m.group (1))
1516 textwidth = (textwidth - columnsep) / columns
1520 def modify_preamble (chunk):
1521 str = chunk.replacement_text ()
1522 if (re.search (r"\\begin *{document}", str)
1523 and not re.search ("{graphic[sx]", str)):
1524 str = re.sub (r"\\begin{document}",
1525 r"\\usepackage{graphics}" + '\n'
1526 + r"\\begin{document}",
1528 chunk.override_text = str
1540 '.texinfo': TEXINFO,
1547 # TEXINFO: '.texinfo',
1553 class Compile_error:
1556 def write_file_map (lys, name):
1557 snippet_map = open ('snippet-map.ly', 'w')
1558 snippet_map.write ("""
1559 #(define version-seen #t)
1560 #(ly:add-file-name-alist '(
1563 snippet_map.write ('("%s.ly" . "%s")\n'
1567 snippet_map.write ('))\n')
1569 def do_process_cmd (chunks, input_name):
1570 all_lys = filter (lambda x: is_derived_class (x.__class__,
1574 write_file_map (all_lys, input_name)
1575 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1577 and x.ly_is_outdated (), chunks)
1578 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1580 and x.texstr_is_outdated (),
1582 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1584 and x.png_is_outdated (),
1587 outdated = png_outdated + texstr_outdated + ly_outdated
1589 progress (_ ("Writing snippets..."))
1590 map (Lilypond_snippet.write_ly, ly_outdated)
1594 progress (_ ("Processing..."))
1596 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1598 progress (_ ("All snippets are up to date..."))
1601 def guess_format (input_filename):
1603 e = os.path.splitext (input_filename)[1]
1604 if e in ext2format.keys ():
1606 format = ext2format[e]
1608 error (_ ("can't determine format for: %s" \
1613 def write_if_updated (file_name, lines):
1615 f = open (file_name)
1617 new_str = string.join (lines, '')
1618 if oldstr == new_str:
1619 progress (_ ("%s is up to date.") % file_name)
1625 progress (_ ("Writing `%s'...") % file_name)
1626 open (file_name, 'w').writelines (lines)
1629 def note_input_file (name, inputs=[]):
1630 ## hack: inputs is mutable!
1631 inputs.append (name)
1634 def samefile (f1, f2):
1636 return os.path.samefile (f1, f2)
1637 except AttributeError: # Windoze
1638 f1 = re.sub ("//*", "/", f1)
1639 f2 = re.sub ("//*", "/", f2)
1642 def do_file (input_filename):
1644 if not input_filename or input_filename == '-':
1645 in_handle = sys.stdin
1646 input_fullname = '<stdin>'
1648 if os.path.exists (input_filename):
1649 input_fullname = input_filename
1650 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1651 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1653 input_fullname = find_file (input_filename)
1655 note_input_file (input_fullname)
1656 in_handle = open (input_fullname)
1658 if input_filename == '-':
1659 input_base = 'stdin'
1661 input_base = os.path.basename \
1662 (os.path.splitext (input_filename)[0])
1664 # Only default to stdout when filtering.
1665 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1666 output_filename = '-'
1667 output_file = sys.stdout
1669 # don't complain when global_options.output_name is existing
1670 output_filename = input_base + format2ext[global_options.format]
1671 if global_options.output_name:
1672 if not os.path.isdir (global_options.output_name):
1673 os.mkdir (global_options.output_name, 0777)
1674 os.chdir (global_options.output_name)
1676 if (os.path.exists (input_filename)
1677 and os.path.exists (output_filename)
1678 and samefile (output_filename, input_fullname)):
1680 _ ("Output would overwrite input file; use --output."))
1684 progress (_ ("Reading %s...") % input_fullname)
1685 source = in_handle.read ()
1688 set_default_options (source)
1691 # FIXME: Containing blocks must be first, see
1692 # find_toplevel_snippets.
1694 'multiline_comment',
1698 'singleline_comment',
1703 progress (_ ("Dissecting..."))
1704 chunks = find_toplevel_snippets (source, snippet_types)
1706 if global_options.format == LATEX:
1708 if (c.is_plain () and
1709 re.search (r"\\begin *{document}", c.replacement_text())):
1714 if global_options.filter_cmd:
1715 write_if_updated (output_filename,
1716 [c.filter_text () for c in chunks])
1717 elif global_options.process_cmd:
1718 do_process_cmd (chunks, input_fullname)
1719 progress (_ ("Compiling %s...") % output_filename)
1721 write_if_updated (output_filename,
1722 [s.replacement_text ()
1725 def process_include (snippet):
1726 os.chdir (original_dir)
1727 name = snippet.substring ('filename')
1728 progress (_ ("Processing include: %s") % name)
1730 return do_file (name)
1732 include_chunks = map (process_include,
1733 filter (lambda x: is_derived_class (x.__class__,
1738 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1740 except Compile_error:
1741 os.chdir (original_dir)
1742 progress (_ ("Removing `%s'") % output_filename)
1748 global global_options
1750 opt_parser = get_option_parser()
1751 (global_options, args) = opt_parser.parse_args ()
1753 if global_options.format in ('texi-html', 'texi'):
1754 global_options.format = TEXINFO
1755 global_options.use_hash = True
1757 global_options.include_path = map (os.path.abspath, global_options.include_path)
1759 if global_options.warranty:
1762 if not args or len (args) > 1:
1763 opt_parser.print_help ()
1769 files = do_options ()
1773 basename = os.path.splitext (file)[0]
1774 basename = os.path.split (basename)[1]
1776 if not global_options.format:
1777 global_options.format = guess_format (files[0])
1780 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1784 if global_options.process_cmd == '':
1785 global_options.process_cmd = (lilypond_binary
1786 + ' --formats=%s --backend eps ' % formats)
1788 if global_options.process_cmd:
1789 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1790 for p in global_options.include_path])
1792 if global_options.format in (TEXINFO, LATEX):
1793 ## prevent PDF from being switched on by default.
1794 global_options.process_cmd += ' --formats=eps '
1796 if (global_options.format in (TEXINFO, LATEX)
1797 and global_options.create_pdf):
1798 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1802 if global_options.verbose:
1803 global_options.process_cmd += " --verbose "
1805 global_options.process_cmd += " -dread-file-list -deps-box-padding=-3 "
1810 chunks = do_file (file)
1811 if global_options.psfonts:
1812 fontextract.verbose = global_options.verbose
1813 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1817 psfonts_file = basename + '.psfonts'
1818 if not global_options.verbose:
1819 progress (_ ("Writing fonts to %s...") % psfonts_file)
1820 fontextract.extract_fonts (psfonts_file,
1821 [x.basename() + '.eps'
1822 for x in snippet_chunks])
1823 if not global_options.verbose:
1826 except Compile_error:
1829 if global_options.format in (TEXINFO, LATEX):
1830 psfonts_file = os.path.join (global_options.output_name, basename + '.psfonts')
1831 output = os.path.join (global_options.output_name, basename + '.dvi' )
1833 if not global_options.psfonts and not global_options.create_pdf:
1834 warning (_ ("option --psfonts not used"))
1835 warning (_ ("processing with dvips will have no fonts"))
1838 progress (_ ("DVIPS usage:"))
1840 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1843 inputs = note_input_file ('')
1846 base_file_name = os.path.splitext (os.path.basename (file))[0]
1847 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1848 final_output_file = os.path.join (global_options.output_name,
1850 + '.%s' % global_options.format)
1852 os.chdir (original_dir)
1853 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1855 if __name__ == '__main__':