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
50 program_version = '@TOPLEVEL_VERSION@'
51 program_name = os.path.basename (sys.argv[0])
53 original_dir = os.getcwd ()
57 '''Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.
61 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
62 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" BOOK
63 lilypond-book --process='lilypond -I include' BOOK
66 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
67 'Han-Wen Nienhuys <hanwen@cs.uu.nl>')
69 ################################################################
71 if global_options.verbose:
72 raise _ ('Exiting (%d)...') % i
77 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
83 sys.stderr.write (program_name + ": " + _ ("warning: %s") % s + '\n')
86 sys.stderr.write (program_name + ": " + _ ("error: %s") % s + '\n')
88 def ps_page_count (ps_name):
89 header = open (ps_name).read (1024)
90 m = re.search ('\n%%Pages: ([0-9]+)', header)
92 return string.atoi (m.group (1))
104 ''' % (_ ('Copyright (c) %s by') % '2001--2007',
106 _('Distributed under terms of the GNU General Public License.'),
107 _('It comes with NO WARRANTY.')))
110 def get_option_parser ():
111 p = ly.get_option_parser (usage='lilypond-book [OPTIONS] FILE',
112 version="@TOPLEVEL_VERSION@",
113 description=help_summary)
115 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
118 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
120 p.add_option ('-f', '--format',
121 help=_('''use output format FORMAT (texi [default], texi-html, latex, html, docbook)'''),
124 p.add_option ("-I", '--include', help=_('add DIR to include path'),
126 action='append', dest='include_path',
127 default=[os.path.abspath (os.getcwd ())])
129 p.add_option ('--left-padding',
132 help="Pad left side of music to align music inspite of uneven bar numbers. (in mm)",
136 p.add_option ("-o", '--output', help=_('write output to DIR'),
138 action='store', dest='output_name',
141 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
142 help = _ ("process ly_files using COMMAND FILE..."),
144 dest='process_cmd', default='lilypond -b eps')
146 p.add_option ('--pdf',
149 help="Create PDF files for use with PDFTeX",
152 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
153 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
154 must use this with dvips -h INPUT.psfonts'''),
156 p.add_option ('-V', '--verbose', help=_("be verbose"),
161 p.add_option ('-w', '--warranty',
162 help=_("show warranty and copyright"),
166 p.add_option_group ('bugs',
167 description='''Report bugs via http://post.gmane.org/post.php'''
168 '''?group=gmane.comp.gnu.lilypond.bugs\n''')
172 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
174 # Only use installed binary when we are installed too.
175 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
176 lilypond_binary = 'lilypond'
178 global_options = None
181 default_ly_options = { 'alt': "[image of music]" }
184 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
189 EXAMPLEINDENT = 'exampleindent'
191 FRAGMENT = 'fragment'
196 LINE_WIDTH = 'line-width'
197 NOFRAGMENT = 'nofragment'
198 NOINDENT = 'noindent'
203 OUTPUTIMAGE = 'outputimage'
206 PREAMBLE = 'preamble'
207 PRINTFILENAME = 'printfilename'
209 RAGGED_RIGHT = 'ragged-right'
210 RELATIVE = 'relative'
211 STAFFSIZE = 'staffsize'
214 VERBATIM = 'verbatim'
215 FONTLOAD = 'fontload'
216 FILENAME = 'filename'
220 # NOTIME has no opposite so it isn't part of this dictionary.
221 # NOQUOTE is used internally only.
223 NOFRAGMENT: FRAGMENT,
228 # Recognize special sequences in the input.
230 # (?P<name>regex) -- Assign result of REGEX to NAME.
231 # *? -- Match non-greedily.
232 # (?m) -- Multiline regex: Make ^ and $ match at each line.
233 # (?s) -- Make the dot match all characters including newline.
234 # (?x) -- Ignore whitespace in patterns.
245 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
250 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
255 <(?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>)''',
261 (?P<code><!--\s.*?!-->)
264 'singleline_comment':
283 (\s*(?P<options>.*?)\s*:)?\s*
291 \s*(?P<options>.*?)\s*
300 \s*(?P<options>.*?)\s*
302 \s*(?P<filename>.*?)\s*
309 (?P<code><!--\s.*?!-->)
312 'singleline_comment':
318 (?P<code><pre>.*?</pre>))''',
324 (?P<code><pre>\s.*?</pre>\s))''',
343 \s*(?P<options>.*?)\s*
354 \s*(?P<options>.*?)\s*
358 \\end\s*{lilypond})''',
366 \s*(?P<options>.*?)\s*
374 'singleline_comment':
397 \\end\s*{verbatim}))''',
406 (?P<filename>\S+))''',
410 ^[^\n]*?(?!@c\s+)[^\n]*?
414 \s*(?P<options>.*?)\s*
424 \s*(?P<options>.*?)\s*
427 ^@end\s+lilypond)\s''',
434 \s*(?P<options>.*?)\s*
445 @end\s+ignore))\s''',
447 'singleline_comment':
452 @c([ \t][^\n]*|)\n))''',
454 # Don't do this: It interferes with @code{@{}.
455 # 'verb': r'''(?P<code>@code{.*?})''',
463 @end\s+example\s))''',
472 'intertext': r',?\s*intertext=\".*?\"',
476 'intertext': r',?\s*intertext=\".*?\"',
481 'intertext': r',?\s*intertext=\".*?\"',
482 'option_sep': '\s*,\s*',
486 'intertext': r',?\s*intertext=\".*?\"',
487 'option_sep': '\s*,\s*',
491 # Options without a pattern in ly_options.
508 RELATIVE: r'''\relative c%(relative_quotes)s''',
513 INDENT: r'''indent = %(indent)s''',
515 LINE_WIDTH: r'''line-width = %(line-width)s''',
517 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
519 RAGGED_RIGHT: r'''ragged-right = ##t''',
521 PACKED: r'''packed = ##t''',
533 \remove Time_signature_engraver
539 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
546 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
549 <imageobject role="latex">
550 <imagedata fileref="%(base)s.pdf" format="PDF"/>
552 <imageobject role="html">
553 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
555 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
557 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
561 FILTER: r'''<lilypond %(options)s>
571 <a href="%(base)s.ly">''',
574 <img align="center" valign="center"
575 border="0" src="%(image)s" alt="%(alt)s">''',
577 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
579 QUOTE: r'''<blockquote>
592 \ifx\preLilyPondExample \undefined%%
595 \preLilyPondExample%%
597 \def\lilypondbook{}%%
598 \input %(base)s-systems.tex%%
599 \ifx\postLilyPondExample \undefined%%
602 \postLilyPondExample%%
606 PRINTFILENAME: '''\\texttt{%(filename)s}
609 QUOTE: r'''\begin{quotation}%(str)s
612 VERBATIM: r'''\noindent
613 \begin{verbatim}%(verb)s\end{verbatim}''',
615 FILTER: r'''\begin{lilypond}[%(options)s]
622 FILTER: r'''@lilypond[%(options)s]
628 @include %(base)s-systems.texi
632 OUTPUTIMAGE: r'''@noindent
634 @image{%(base)s,,,%(alt)s,%(ext)s}
638 <a href="%(base)s.ly">
639 <img align="center" valign="center"
640 border="0" src="%(image)s" alt="%(alt)s">
648 <a href="%(base)s.ly">
656 QUOTE: r'''@quotation
657 %(str)s@end quotation
664 VERBATIM: r'''@exampleindent 0
666 %(verb)s@end verbatim
672 # Maintain line numbers.
677 for f in [HTML, LATEX]:
678 for s in (QUOTE, VERBATIM):
679 output[f][s] = output[f][s].replace("\n"," ")
682 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
683 %%%% Options: [%(option_string)s]
684 \\include "lilypond-book-preamble.ly"
692 %% ****************************************************************
693 %% Start cut-&-pastable-section
694 %% ****************************************************************
697 #(define dump-extents #t)
698 %(font_dump_setting)s
700 force-assignment = #""
701 line-width = #(- line-width (* mm %(padding_mm)f))
714 %% ****************************************************************
715 %% ly snippet contents follows:
716 %% ****************************************************************
720 %% ****************************************************************
722 %% ****************************************************************
729 %% ****************************************************************
731 %% ****************************************************************
735 %% ****************************************************************
737 %% ****************************************************************
740 texinfo_line_widths = {
741 '@afourpaper': '160\\mm',
742 '@afourwide': '6.5\\in',
743 '@afourlatex': '150\\mm',
744 '@smallbook': '5\\in',
745 '@letterpaper': '6\\in',
748 def classic_lilypond_book_compatibility (key, value):
749 if key == 'singleline' and value == None:
750 return (RAGGED_RIGHT, None)
752 m = re.search ('relative\s*([-0-9])', key)
754 return ('relative', m.group (1))
756 m = re.match ('([0-9]+)pt', key)
758 return ('staffsize', m.group (1))
760 if key == 'indent' or key == 'line-width':
761 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
763 f = float (m.group (1))
764 return (key, '%f\\%s' % (f, m.group (2)))
768 def find_file (name):
769 for i in global_options.include_path:
770 full = os.path.join (i, name)
771 if os.path.exists (full):
774 error (_ ("file not found: %s") % name + '\n')
778 def verbatim_html (s):
779 return re.sub ('>', '>',
781 re.sub ('&', '&', s)))
783 def split_options (option_string):
785 if global_options.format == HTML:
786 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
787 for i in range(len(options)):
788 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
791 return re.split (format_res[global_options.format]['option_sep'],
795 def set_default_options (source):
796 global default_ly_options
797 if not default_ly_options.has_key (LINE_WIDTH):
798 if global_options.format == LATEX:
799 textwidth = get_latex_textwidth (source)
800 default_ly_options[LINE_WIDTH] = \
801 '''%.0f\\pt''' % textwidth
802 elif global_options.format == TEXINFO:
803 for (k, v) in texinfo_line_widths.items ():
804 # FIXME: @layout is usually not in
807 # \input texinfo @c -*-texinfo-*-
809 # Bluntly search first K items of
811 # s = chunks[0].replacement_text ()
812 if re.search (k, source[:1024]):
813 default_ly_options[LINE_WIDTH] = v
817 def replacement_text (self):
820 def filter_text (self):
821 return self.replacement_text ()
823 def ly_is_outdated (self):
826 def png_is_outdated (self):
832 class Substring (Chunk):
833 def __init__ (self, source, start, end, line_number):
837 self.line_number = line_number
838 self.override_text = None
843 def replacement_text (self):
844 if self.override_text:
845 return self.override_text
847 return self.source[self.start:self.end]
849 class Snippet (Chunk):
850 def __init__ (self, type, match, format, line_number):
854 self.option_dict = {}
856 self.line_number = line_number
858 def replacement_text (self):
859 return self.match.group ('match')
861 def substring (self, s):
862 return self.match.group (s)
865 return `self.__class__` + ' type = ' + self.type
867 class Include_snippet (Snippet):
868 def processed_filename (self):
869 f = self.substring ('filename')
870 return os.path.splitext (f)[0] + format2ext[global_options.format]
872 def replacement_text (self):
873 s = self.match.group ('match')
874 f = self.substring ('filename')
876 return re.sub (f, self.processed_filename (), s)
878 class Lilypond_snippet (Snippet):
879 def __init__ (self, type, match, format, line_number):
880 Snippet.__init__ (self, type, match, format, line_number)
881 os = match.group ('options')
882 self.do_options (os, self.type)
885 contents = self.substring ('code')
886 return ('\\sourcefileline %d\n%s'
887 % (self.line_number - 1, contents))
892 return self.compose_ly (s)
895 def do_options (self, option_string, type):
896 self.option_dict = {}
898 options = split_options (option_string)
902 (key, value) = re.split ('\s*=\s*', i)
903 self.option_dict[key] = value
905 if i in no_options.keys ():
906 if no_options[i] in self.option_dict.keys ():
907 del self.option_dict[no_options[i]]
909 self.option_dict[i] = None
911 has_line_width = self.option_dict.has_key (LINE_WIDTH)
912 no_line_width_value = 0
914 # If LINE_WIDTH is used without parameter, set it to default.
915 if has_line_width and self.option_dict[LINE_WIDTH] == None:
916 no_line_width_value = 1
917 del self.option_dict[LINE_WIDTH]
919 for i in default_ly_options.keys ():
920 if i not in self.option_dict.keys ():
921 self.option_dict[i] = default_ly_options[i]
923 if not has_line_width:
924 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
925 self.option_dict[RAGGED_RIGHT] = None
927 if type == 'lilypond':
928 if LINE_WIDTH in self.option_dict.keys ():
929 del self.option_dict[LINE_WIDTH]
931 if RAGGED_RIGHT in self.option_dict.keys ():
932 if LINE_WIDTH in self.option_dict.keys ():
933 del self.option_dict[LINE_WIDTH]
935 if QUOTE in self.option_dict.keys () or type == 'lilypond':
936 if LINE_WIDTH in self.option_dict.keys ():
937 del self.option_dict[LINE_WIDTH]
939 if not INDENT in self.option_dict.keys ():
940 self.option_dict[INDENT] = '0\\mm'
942 # The QUOTE pattern from ly_options only emits the `line-width'
944 if has_line_width and QUOTE in self.option_dict.keys ():
945 if no_line_width_value:
946 del self.option_dict[LINE_WIDTH]
948 del self.option_dict[QUOTE]
950 def compose_ly (self, code):
951 if FRAGMENT in self.option_dict.keys ():
959 # The original concept of the `exampleindent' option is broken.
960 # It is not possible to get a sane value for @exampleindent at all
961 # without processing the document itself. Saying
969 # causes ugly results with the DVI backend of texinfo since the
970 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
971 # value). Executing the above code changes the environment
972 # indentation to an unknown value because we don't know the amount
973 # of 1em in advance since it is font-dependent. Modifying
974 # @exampleindent in the middle of a document is simply not
975 # supported within texinfo.
977 # As a consequence, the only function of @exampleindent is now to
978 # specify the amount of indentation for the `quote' option.
980 # To set @exampleindent locally to zero, we use the @format
981 # environment for non-quoted snippets.
982 override[EXAMPLEINDENT] = r'0.4\in'
983 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
984 override.update (default_ly_options)
987 for (key, value) in self.option_dict.items ():
989 option_list.append (key)
991 option_list.append (key + '=' + value)
992 option_string = string.join (option_list, ',')
995 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
996 for a in compose_types:
999 for (key, value) in self.option_dict.items ():
1000 (c_key, c_value) = \
1001 classic_lilypond_book_compatibility (key, value)
1005 (_ ("deprecated ly-option used: %s=%s" \
1008 (_ ("compatibility mode translation: %s=%s" \
1009 % (c_key, c_value)))
1012 (_ ("deprecated ly-option used: %s" \
1015 (_ ("compatibility mode translation: %s" \
1018 (key, value) = (c_key, c_value)
1021 override[key] = value
1023 if not override.has_key (key):
1024 override[key] = None
1027 for type in compose_types:
1028 if ly_options[type].has_key (key):
1029 compose_dict[type].append (ly_options[type][key])
1033 if not found and key not in simple_options:
1034 warning (_ ("ignoring unknown ly option: %s") % key)
1037 if RELATIVE in override.keys () and override[RELATIVE]:
1038 relative = int (override[RELATIVE])
1040 relative_quotes = ''
1044 relative_quotes += ',' * (- relative)
1046 relative_quotes += "'" * relative
1048 paper_string = string.join (compose_dict[PAPER],
1050 layout_string = string.join (compose_dict[LAYOUT],
1052 notes_string = string.join (compose_dict[NOTES],
1054 preamble_string = string.join (compose_dict[PREAMBLE],
1056 padding_mm = global_options.padding_mm
1057 font_dump_setting = ''
1058 if FONTLOAD in self.option_dict:
1059 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1061 d = globals().copy()
1063 return (PREAMBLE_LY + body) % d
1065 def get_hash (self):
1067 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1069 ## let's not create too long names.
1070 self.hash = hash.hexdigest ()[:10]
1074 def basename (self):
1075 if FILENAME in self.option_dict:
1076 return self.option_dict[FILENAME]
1077 if global_options.use_hash:
1078 return 'lily-%s' % self.get_hash ()
1081 def write_ly (self):
1082 outf = open (self.basename () + '.ly', 'w')
1083 outf.write (self.full_ly ())
1084 open (self.basename () + '.txt', 'w').write ('image of music')
1086 def relevant_contents (self, ly):
1087 return re.sub (r'\\(version|sourcefileline)[^\n]*\n', '', ly)
1089 def ly_is_outdated (self):
1090 base = self.basename ()
1091 ly_file = base + '.ly'
1092 tex_file = base + '.tex'
1093 eps_file = base + '.eps'
1094 systems_file = base + '-systems.tex'
1096 if (os.path.exists (ly_file)
1097 and os.path.exists (systems_file)
1098 and os.stat (systems_file)[stat.ST_SIZE]
1099 and re.match ('% eof', open (systems_file).readlines ()[-1])
1100 and (global_options.use_hash or FILENAME in self.option_dict)
1101 and (self.relevant_contents (self.full_ly ())
1102 == self.relevant_contents (open (ly_file).read ()))):
1104 if global_options.verbose:
1105 print 'OUT OF DATE: ', ly_file
1108 def png_is_outdated (self):
1109 base = self.basename ()
1110 # FIXME: refactor stupid OK stuff
1111 ok = not self.ly_is_outdated ()
1112 if global_options.format in (HTML, TEXINFO):
1113 ok = ok and os.path.exists (base + '.eps')
1117 page_count = ps_page_count (base + '.eps')
1120 ok = ok and os.path.exists (base + '.png')
1122 elif page_count > 1:
1123 for a in range (1, page_count + 1):
1124 ok = ok and os.path.exists (base + '-page%d.png' % a)
1128 def texstr_is_outdated (self):
1132 # FIXME: refactor stupid OK stuff
1133 base = self.basename ()
1134 ok = self.ly_is_outdated ()
1135 ok = ok and (os.path.exists (base + '.texstr'))
1138 def filter_text (self):
1139 code = self.substring ('code')
1140 s = run_filter (code)
1143 'options': self.match.group ('options')
1146 return output[self.format][FILTER] % d
1148 def replacement_text (self):
1149 func = Lilypond_snippet.__dict__['output_' + self.format]
1152 def get_images (self):
1153 base = self.basename ()
1155 single = '%(base)s.png' % vars ()
1156 multiple = '%(base)s-page1.png' % vars ()
1158 if os.path.exists (multiple) \
1159 and (not os.path.exists (single) \
1160 or (os.stat (multiple)[stat.ST_MTIME] \
1161 > os.stat (single)[stat.ST_MTIME])):
1162 count = ps_page_count ('%(base)s.eps' % vars ())
1163 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1164 images = tuple (images)
1167 def output_docbook (self):
1169 base = self.basename ()
1170 for image in self.get_images ():
1171 (base, ext) = os.path.splitext (image)
1172 str += output[DOCBOOK][OUTPUT] % vars ()
1173 str += self.output_print_filename (DOCBOOK)
1174 if (self.substring('inline') == 'inline'):
1175 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1177 str = '<mediaobject>' + str + '</mediaobject>'
1178 if VERBATIM in self.option_dict:
1179 verb = verbatim_html (self.substring ('code'))
1180 str = output[DOCBOOK][VERBATIM] % vars () + str
1183 def output_html (self):
1185 base = self.basename ()
1186 if global_options.format == HTML:
1187 str += self.output_print_filename (HTML)
1188 if VERBATIM in self.option_dict:
1189 verb = verbatim_html (self.substring ('code'))
1190 str += output[HTML][VERBATIM] % vars ()
1191 if QUOTE in self.option_dict:
1192 str = output[HTML][QUOTE] % vars ()
1194 str += output[HTML][BEFORE] % vars ()
1195 for image in self.get_images ():
1196 (base, ext) = os.path.splitext (image)
1197 alt = self.option_dict[ALT]
1198 str += output[HTML][OUTPUT] % vars ()
1199 str += output[HTML][AFTER] % vars ()
1202 def output_info (self):
1204 for image in self.get_images ():
1205 (base, ext) = os.path.splitext (image)
1207 # URG, makeinfo implicitly prepends dot to extension.
1208 # Specifying no extension is most robust.
1210 alt = self.option_dict[ALT]
1211 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1213 base = self.basename ()
1214 str += output[global_options.format][OUTPUT] % vars ()
1217 def output_latex (self):
1219 base = self.basename ()
1220 if global_options.format == LATEX:
1221 str += self.output_print_filename (LATEX)
1222 if VERBATIM in self.option_dict:
1223 verb = self.substring ('code')
1224 str += (output[LATEX][VERBATIM] % vars ())
1226 str += (output[LATEX][OUTPUT] % vars ())
1228 ## todo: maintain breaks
1230 breaks = self.ly ().count ("\n")
1231 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1233 if QUOTE in self.option_dict:
1234 str = output[LATEX][QUOTE] % vars ()
1237 def output_print_filename (self, format):
1239 if PRINTFILENAME in self.option_dict:
1240 base = self.basename ()
1241 filename = self.substring ('filename')
1242 str = output[global_options.format][PRINTFILENAME] % vars ()
1246 def output_texinfo (self):
1248 if self.output_print_filename (TEXINFO):
1250 + self.output_print_filename (HTML)
1253 + self.output_print_filename (LATEX)
1255 base = self.basename ()
1256 if TEXIDOC in self.option_dict:
1257 texidoc = base + '.texidoc'
1258 if os.path.exists (texidoc):
1259 str += '@include %(texidoc)s\n\n' % vars ()
1261 if VERBATIM in self.option_dict:
1262 verb = self.substring ('code')
1263 str += (output[TEXINFO][VERBATIM] % vars ())
1264 if not QUOTE in self.option_dict:
1265 str = output[TEXINFO][NOQUOTE] % vars ()
1267 str += self.output_info ()
1269 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1270 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1271 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1273 if QUOTE in self.option_dict:
1274 str = output[TEXINFO][QUOTE] % vars ()
1276 # need par after image
1281 class Lilypond_file_snippet (Lilypond_snippet):
1283 name = self.substring ('filename')
1284 contents = open (find_file (name)).read ()
1285 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1288 snippet_type_to_class = {
1289 'lilypond_file': Lilypond_file_snippet,
1290 'lilypond_block': Lilypond_snippet,
1291 'lilypond': Lilypond_snippet,
1292 'include': Include_snippet,
1295 def find_linestarts (s):
1300 i = s.find ('\n', start)
1308 nls.append (len (s))
1311 def find_toplevel_snippets (s, types):
1314 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1318 found = dict ([(t, None) for t in types])
1320 line_starts = find_linestarts (s)
1322 # We want to search for multiple regexes, without searching
1323 # the string multiple times for one regex.
1324 # Hence, we use earlier results to limit the string portion
1326 # Since every part of the string is traversed at most once for
1327 # every type of snippet, this is linear.
1333 if not found[type] or found[type][0] < index:
1336 m = res[type].search (s[index:endex])
1341 if snippet_type_to_class.has_key (type):
1342 cl = snippet_type_to_class[type]
1345 start = index + m.start ('match')
1346 line_number = line_start_idx
1347 while (line_starts[line_number] < start):
1351 snip = cl (type, m, global_options.format, line_number)
1353 found[type] = (start, snip)
1357 or found[type][0] < found[first][0]):
1362 # Limiting the search space is a cute
1363 # idea, but this *requires* to search
1364 # for possible containing blocks
1365 # first, at least as long as we do not
1366 # search for the start of blocks, but
1367 # always/directly for the entire
1368 # @block ... @end block.
1370 endex = found[first][0]
1373 snippets.append (Substring (s, index, len (s), line_start_idx))
1376 while (start > line_starts[line_start_idx+1]):
1379 (start, snip) = found[first]
1380 snippets.append (Substring (s, index, start, line_start_idx + 1))
1381 snippets.append (snip)
1383 index = start + len (snip.match.group ('match'))
1387 def filter_pipe (input, cmd):
1388 if global_options.verbose:
1389 progress (_ ("Opening filter `%s'") % cmd)
1391 (stdin, stdout, stderr) = os.popen3 (cmd)
1393 status = stdin.close ()
1397 output = stdout.read ()
1398 status = stdout.close ()
1399 error = stderr.read ()
1403 signal = 0x0f & status
1404 if status or (not output and error):
1405 exit_status = status >> 8
1406 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1407 error (_ ("The error log is as follows:"))
1408 sys.stderr.write (error)
1409 sys.stderr.write (stderr.read ())
1412 if global_options.verbose:
1418 return filter_pipe (s, global_options.filter_cmd)
1420 def is_derived_class (cl, baseclass):
1423 for b in cl.__bases__:
1424 if is_derived_class (b, baseclass):
1428 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1429 ly_names = filter (lambda x: x,
1430 map (Lilypond_snippet.basename, ly_snippets))
1431 texstr_names = filter (lambda x: x,
1432 map (Lilypond_snippet.basename, texstr_snippets))
1434 png_names = filter (lambda x: x,
1435 map (Lilypond_snippet.basename, png_snippets))
1438 def my_system (cmd):
1439 status = ly.system (cmd,
1440 be_verbose=global_options.verbose,
1443 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1444 cmd += ' --formats=png '
1445 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1446 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 ()
1768 def psfonts_warning (options, basename):
1769 if options.format in (TEXINFO, LATEX):
1770 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1771 output = os.path.join (options.output_name, basename + '.dvi' )
1773 if not options.create_pdf:
1774 if not options.psfonts:
1775 warning (_ ("option --psfonts not used"))
1776 warning (_ ("processing with dvips will have no fonts"))
1779 progress (_ ("DVIPS usage:"))
1781 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1785 # FIXME: 85 lines of `main' macramee??
1786 files = do_options ()
1790 basename = os.path.splitext (file)[0]
1791 basename = os.path.split (basename)[1]
1793 if not global_options.format:
1794 global_options.format = guess_format (files[0])
1797 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1801 if global_options.process_cmd == '':
1802 global_options.process_cmd = (lilypond_binary
1803 + ' --formats=%s --backend eps ' % formats)
1805 if global_options.process_cmd:
1806 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1807 for p in global_options.include_path])
1809 if global_options.format in (TEXINFO, LATEX):
1810 ## prevent PDF from being switched on by default.
1811 global_options.process_cmd += ' --formats=eps '
1812 if global_options.create_pdf:
1813 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1815 if global_options.verbose:
1816 global_options.process_cmd += " --verbose "
1818 if global_options.padding_mm:
1819 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1821 global_options.process_cmd += " -dread-file-list "
1826 chunks = do_file (file)
1827 if global_options.psfonts:
1828 fontextract.verbose = global_options.verbose
1829 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1833 psfonts_file = basename + '.psfonts'
1834 if not global_options.verbose:
1835 progress (_ ("Writing fonts to %s...") % psfonts_file)
1836 fontextract.extract_fonts (psfonts_file,
1837 [x.basename() + '.eps'
1838 for x in snippet_chunks])
1839 if not global_options.verbose:
1842 except Compile_error:
1845 psfonts_warning (global_options, basename)
1847 inputs = note_input_file ('')
1850 base_file_name = os.path.splitext (os.path.basename (file))[0]
1851 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1852 final_output_file = os.path.join (global_options.output_name,
1854 + '.%s' % global_options.format)
1856 os.chdir (original_dir)
1857 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1859 if __name__ == '__main__':