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)s
62 lilypond-book --filter="convert-ly --no-version --from=2.0.0 -" %(BOOK)s
63 lilypond-book --process='lilypond -I include' %(BOOK)s
64 ''' % {'BOOK': _ ("BOOK")})
66 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
67 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
69 ################################################################
71 if global_options.verbose:
72 raise Exception (_ ('Exiting (%d)...') % i)
77 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
79 progress = ly.progress
82 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
85 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
87 def ps_page_count (ps_name):
88 header = open (ps_name).read (1024)
89 m = re.search ('\n%%Pages: ([0-9]+)', header)
91 return int (m.group (1))
96 ly.encoded_write (sys.stdout, '''
103 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
105 _ ("Distributed under terms of the GNU General Public License."),
106 _ ("It comes with NO WARRANTY.")))
108 def get_option_parser ():
109 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
110 description=help_summary,
111 add_help_option=False)
113 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
116 help=_ ("pipe snippets through FILTER [convert-ly -n -]"),
119 p.add_option ('-f', '--format',
120 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
123 p.add_option("-h", "--help",
125 help=_ ("show this help and exit"))
127 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
129 action='append', dest='include_path',
130 default=[os.path.abspath (os.getcwd ())])
132 p.add_option ('--info-images-dir',
133 help=_ ("format Texinfo output so that Info will "
134 "look for images of music in DIR"),
136 action='store', dest='info_images_dir',
139 p.add_option ('--left-padding',
142 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
146 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
148 action='store', dest='output_name',
151 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
152 help = _ ("process ly_files using COMMAND FILE..."),
154 dest='process_cmd', default='lilypond -dbackend=eps')
156 p.add_option ('--pdf',
159 help=_ ("create PDF files for use with PDFTeX"),
162 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
163 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
164 must use this with dvips -h INPUT.psfonts'''),
167 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
172 p.version = "@TOPLEVEL_VERSION@"
173 p.add_option("--version",
175 help=_ ("show version number and exit"))
177 p.add_option ('-w', '--warranty',
178 help=_ ("show warranty and copyright"),
180 p.add_option_group (ly.display_encode (_ ('Bugs')),
181 description=(_ ("Report bugs via")
182 + ''' http://post.gmane.org/post.php'''
183 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
186 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
188 # Only use installed binary when we are installed too.
189 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
190 lilypond_binary = 'lilypond'
192 global_options = None
195 default_ly_options = { 'alt': "[image of music]" }
198 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
200 ADDVERSION = 'addversion'
204 EXAMPLEINDENT = 'exampleindent'
206 FRAGMENT = 'fragment'
211 LINE_WIDTH = 'line-width'
212 LILYQUOTE = 'lilyquote'
213 NOFRAGMENT = 'nofragment'
214 NOINDENT = 'noindent'
219 OUTPUTIMAGE = 'outputimage'
222 PREAMBLE = 'preamble'
223 PRINTFILENAME = 'printfilename'
225 RAGGED_RIGHT = 'ragged-right'
226 RELATIVE = 'relative'
227 STAFFSIZE = 'staffsize'
230 VERBATIM = 'verbatim'
231 FONTLOAD = 'fontload'
232 FILENAME = 'filename'
236 # NOTIME has no opposite so it isn't part of this dictionary.
237 # NOQUOTE is used internally only.
239 NOFRAGMENT: FRAGMENT,
244 # Recognize special sequences in the input.
246 # (?P<name>regex) -- Assign result of REGEX to NAME.
247 # *? -- Match non-greedily.
248 # (?m) -- Multiline regex: Make ^ and $ match at each line.
249 # (?s) -- Make the dot match all characters including newline.
250 # (?x) -- Ignore whitespace in patterns.
261 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
266 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
271 <(?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>)''',
277 (?P<code><!--\s.*?!-->)
280 'singleline_comment':
299 (\s*(?P<options>.*?)\s*:)?\s*
307 \s*(?P<options>.*?)\s*
316 \s*(?P<options>.*?)\s*
318 \s*(?P<filename>.*?)\s*
325 (?P<code><!--\s.*?!-->)
328 'singleline_comment':
334 (?P<code><pre>.*?</pre>))''',
340 (?P<code><pre>\s.*?</pre>\s))''',
359 \s*(?P<options>.*?)\s*
370 \s*(?P<options>.*?)\s*
374 \\end\s*{lilypond})''',
382 \s*(?P<options>.*?)\s*
390 'singleline_comment':
413 \\end\s*{verbatim}))''',
422 (?P<filename>\S+))''',
426 ^[^\n]*?(?!@c\s+)[^\n]*?
430 \s*(?P<options>.*?)\s*
440 \s*(?P<options>.*?)\s*
443 ^@end\s+lilypond)\s''',
450 \s*(?P<options>.*?)\s*
461 @end\s+ignore))\s''',
463 'singleline_comment':
468 @c([ \t][^\n]*|)\n))''',
470 # Don't do this: It interferes with @code{@{}.
471 # 'verb': r'''(?P<code>@code{.*?})''',
479 @end\s+example\s))''',
488 'intertext': r',?\s*intertext=\".*?\"',
492 'intertext': r',?\s*intertext=\".*?\"',
497 'intertext': r',?\s*intertext=\".*?\"',
498 'option_sep': '\s*,\s*',
502 'intertext': r',?\s*intertext=\".*?\"',
503 'option_sep': '\s*,\s*',
507 # Options without a pattern in ly_options.
524 RELATIVE: r'''\relative c%(relative_quotes)s''',
529 INDENT: r'''indent = %(indent)s''',
531 LINE_WIDTH: r'''line-width = %(line-width)s''',
533 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
535 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
537 RAGGED_RIGHT: r'''ragged-right = ##t''',
539 PACKED: r'''packed = ##t''',
551 \remove Time_signature_engraver
557 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
564 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
567 <imageobject role="latex">
568 <imagedata fileref="%(base)s.pdf" format="PDF"/>
570 <imageobject role="html">
571 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
573 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
575 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
579 FILTER: r'''<lilypond %(options)s>
589 <a href="%(base)s.ly">''',
592 <img align="center" valign="center"
593 border="0" src="%(image)s" alt="%(alt)s">''',
595 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
597 QUOTE: r'''<blockquote>
610 \ifx\preLilyPondExample \undefined%%
613 \preLilyPondExample%%
615 \def\lilypondbook{}%%
616 \input %(base)s-systems.tex%%
617 \ifx\postLilyPondExample \undefined%%
620 \postLilyPondExample%%
624 PRINTFILENAME: '''\\texttt{%(filename)s}
627 QUOTE: r'''\begin{quotation}%(str)s
630 VERBATIM: r'''\noindent
631 \begin{verbatim}%(verb)s\end{verbatim}''',
633 FILTER: r'''\begin{lilypond}[%(options)s]
640 FILTER: r'''@lilypond[%(options)s]
646 @include %(base)s-systems.texi
650 OUTPUTIMAGE: r'''@noindent
652 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
656 <a href="%(base)s.ly">
657 <img align="center" valign="center"
658 border="0" src="%(image)s" alt="%(alt)s">
666 <a href="%(base)s.ly">
674 QUOTE: r'''@quotation
675 %(str)s@end quotation
682 VERBATIM: r'''@exampleindent 0
684 %(verb)s@end verbatim
687 ADDVERSION: r'''\version @w{"@version{}"}
693 # Maintain line numbers.
698 for f in [HTML, LATEX]:
699 for s in (QUOTE, VERBATIM):
700 output[f][s] = output[f][s].replace("\n"," ")
703 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
704 %%%% Options: [%(option_string)s]
705 \\include "lilypond-book-preamble.ly"
708 %% ****************************************************************
709 %% Start cut-&-pastable-section
710 %% ****************************************************************
715 #(define dump-extents #t)
716 %(font_dump_setting)s
718 force-assignment = #""
719 line-width = #(- line-width (* mm %(padding_mm)f))
732 %% ****************************************************************
733 %% ly snippet contents follows:
734 %% ****************************************************************
738 %% ****************************************************************
740 %% ****************************************************************
747 %% ****************************************************************
749 %% ****************************************************************
753 %% ****************************************************************
755 %% ****************************************************************
758 texinfo_line_widths = {
759 '@afourpaper': '160\\mm',
760 '@afourwide': '6.5\\in',
761 '@afourlatex': '150\\mm',
762 '@smallbook': '5\\in',
763 '@letterpaper': '6\\in',
766 def classic_lilypond_book_compatibility (key, value):
767 if key == 'singleline' and value == None:
768 return (RAGGED_RIGHT, None)
770 m = re.search ('relative\s*([-0-9])', key)
772 return ('relative', m.group (1))
774 m = re.match ('([0-9]+)pt', key)
776 return ('staffsize', m.group (1))
778 if key == 'indent' or key == 'line-width':
779 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
781 f = float (m.group (1))
782 return (key, '%f\\%s' % (f, m.group (2)))
786 def find_file (name, raise_error=True):
787 for i in global_options.include_path:
788 full = os.path.join (i, name)
789 if os.path.exists (full):
793 error (_ ("file not found: %s") % name + '\n')
797 def verbatim_html (s):
798 return re.sub ('>', '>',
800 re.sub ('&', '&', s)))
802 def split_options (option_string):
804 if global_options.format == HTML:
805 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
806 for i in range(len(options)):
807 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
810 return re.split (format_res[global_options.format]['option_sep'],
814 def set_default_options (source):
815 global default_ly_options
816 if not default_ly_options.has_key (LINE_WIDTH):
817 if global_options.format == LATEX:
818 textwidth = get_latex_textwidth (source)
819 default_ly_options[LINE_WIDTH] = \
820 '''%.0f\\pt''' % textwidth
821 elif global_options.format == TEXINFO:
822 for (k, v) in texinfo_line_widths.items ():
823 # FIXME: @layout is usually not in
826 # \input texinfo @c -*-texinfo-*-
828 # Bluntly search first K items of
830 # s = chunks[0].replacement_text ()
831 if re.search (k, source[:1024]):
832 default_ly_options[LINE_WIDTH] = v
836 def replacement_text (self):
839 def filter_text (self):
840 return self.replacement_text ()
842 def ly_is_outdated (self):
845 def png_is_outdated (self):
851 class Substring (Chunk):
852 def __init__ (self, source, start, end, line_number):
856 self.line_number = line_number
857 self.override_text = None
862 def replacement_text (self):
863 if self.override_text:
864 return self.override_text
866 return self.source[self.start:self.end]
868 class Snippet (Chunk):
869 def __init__ (self, type, match, format, line_number):
873 self.option_dict = {}
875 self.line_number = line_number
877 def replacement_text (self):
878 return self.match.group ('match')
880 def substring (self, s):
881 return self.match.group (s)
884 return `self.__class__` + ' type = ' + self.type
886 class Include_snippet (Snippet):
887 def processed_filename (self):
888 f = self.substring ('filename')
889 return os.path.splitext (f)[0] + format2ext[global_options.format]
891 def replacement_text (self):
892 s = self.match.group ('match')
893 f = self.substring ('filename')
895 return re.sub (f, self.processed_filename (), s)
897 class Lilypond_snippet (Snippet):
898 def __init__ (self, type, match, format, line_number):
899 Snippet.__init__ (self, type, match, format, line_number)
900 os = match.group ('options')
901 self.do_options (os, self.type)
904 return self.substring ('code')
907 contents = self.substring ('code')
908 return ('\\sourcefileline %d\n%s'
909 % (self.line_number - 1, contents))
914 return self.compose_ly (s)
917 def do_options (self, option_string, type):
918 self.option_dict = {}
920 options = split_options (option_string)
924 (key, value) = re.split ('\s*=\s*', i)
925 self.option_dict[key] = value
927 if i in no_options.keys ():
928 if no_options[i] in self.option_dict.keys ():
929 del self.option_dict[no_options[i]]
931 self.option_dict[i] = None
933 has_line_width = self.option_dict.has_key (LINE_WIDTH)
934 no_line_width_value = 0
936 # If LINE_WIDTH is used without parameter, set it to default.
937 if has_line_width and self.option_dict[LINE_WIDTH] == None:
938 no_line_width_value = 1
939 del self.option_dict[LINE_WIDTH]
941 for i in default_ly_options.keys ():
942 if i not in self.option_dict.keys ():
943 self.option_dict[i] = default_ly_options[i]
945 if not has_line_width:
946 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
947 self.option_dict[RAGGED_RIGHT] = None
949 if type == 'lilypond':
950 if LINE_WIDTH in self.option_dict.keys ():
951 del self.option_dict[LINE_WIDTH]
953 if RAGGED_RIGHT in self.option_dict.keys ():
954 if LINE_WIDTH in self.option_dict.keys ():
955 del self.option_dict[LINE_WIDTH]
957 if QUOTE in self.option_dict.keys () or type == 'lilypond':
958 if LINE_WIDTH in self.option_dict.keys ():
959 del self.option_dict[LINE_WIDTH]
961 if not INDENT in self.option_dict.keys ():
962 self.option_dict[INDENT] = '0\\mm'
964 # The QUOTE pattern from ly_options only emits the `line-width'
966 if has_line_width and QUOTE in self.option_dict.keys ():
967 if no_line_width_value:
968 del self.option_dict[LINE_WIDTH]
970 del self.option_dict[QUOTE]
972 def compose_ly (self, code):
973 if FRAGMENT in self.option_dict.keys ():
981 # The original concept of the `exampleindent' option is broken.
982 # It is not possible to get a sane value for @exampleindent at all
983 # without processing the document itself. Saying
991 # causes ugly results with the DVI backend of texinfo since the
992 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
993 # value). Executing the above code changes the environment
994 # indentation to an unknown value because we don't know the amount
995 # of 1em in advance since it is font-dependent. Modifying
996 # @exampleindent in the middle of a document is simply not
997 # supported within texinfo.
999 # As a consequence, the only function of @exampleindent is now to
1000 # specify the amount of indentation for the `quote' option.
1002 # To set @exampleindent locally to zero, we use the @format
1003 # environment for non-quoted snippets.
1004 override[EXAMPLEINDENT] = r'0.4\in'
1005 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1006 override.update (default_ly_options)
1009 for (key, value) in self.option_dict.items ():
1011 option_list.append (key)
1013 option_list.append (key + '=' + value)
1014 option_string = ','.join (option_list)
1017 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1018 for a in compose_types:
1019 compose_dict[a] = []
1021 for (key, value) in self.option_dict.items ():
1022 (c_key, c_value) = \
1023 classic_lilypond_book_compatibility (key, value)
1027 (_ ("deprecated ly-option used: %s=%s" \
1030 (_ ("compatibility mode translation: %s=%s" \
1031 % (c_key, c_value)))
1034 (_ ("deprecated ly-option used: %s" \
1037 (_ ("compatibility mode translation: %s" \
1040 (key, value) = (c_key, c_value)
1043 override[key] = value
1045 if not override.has_key (key):
1046 override[key] = None
1049 for type in compose_types:
1050 if ly_options[type].has_key (key):
1051 compose_dict[type].append (ly_options[type][key])
1055 if not found and key not in simple_options:
1056 warning (_ ("ignoring unknown ly option: %s") % key)
1059 if RELATIVE in override.keys () and override[RELATIVE]:
1060 relative = int (override[RELATIVE])
1062 relative_quotes = ''
1066 relative_quotes += ',' * (- relative)
1068 relative_quotes += "'" * relative
1070 paper_string = '\n '.join (compose_dict[PAPER]) % override
1071 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1072 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1073 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1074 padding_mm = global_options.padding_mm
1075 font_dump_setting = ''
1076 if FONTLOAD in self.option_dict:
1077 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1079 d = globals().copy()
1081 return (PREAMBLE_LY + body) % d
1083 def get_hash (self):
1085 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1087 ## let's not create too long names.
1088 self.hash = hash.hexdigest ()[:10]
1092 def basename (self):
1093 if FILENAME in self.option_dict:
1094 return self.option_dict[FILENAME]
1095 if global_options.use_hash:
1096 return 'lily-%s' % self.get_hash ()
1099 def write_ly (self):
1100 outf = open (self.basename () + '.ly', 'w')
1101 outf.write (self.full_ly ())
1102 open (self.basename () + '.txt', 'w').write ('image of music')
1104 def relevant_contents (self, ly):
1105 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1107 def ly_is_outdated (self):
1108 base = self.basename ()
1109 ly_file = find_file (base + '.ly', raise_error=False)
1110 tex_file = find_file (base + '.tex', raise_error=False)
1111 systems_file = find_file (base + '-systems.tex', raise_error=False)
1113 if (os.path.exists (ly_file)
1114 and os.path.exists (systems_file)
1115 and os.stat (systems_file)[stat.ST_SIZE]
1116 and re.match ('% eof', open (systems_file).readlines ()[-1])
1117 and (global_options.use_hash or FILENAME in self.option_dict)
1118 and (self.relevant_contents (self.full_ly ())
1119 == self.relevant_contents (open (ly_file).read ()))):
1124 def png_is_outdated (self):
1125 base = self.basename ()
1126 eps_file = find_file (base + '.eps', raise_error=False)
1127 png_file = find_file (base + '.png', raise_error=False)
1128 if not self.ly_is_outdated () and global_options.format in (HTML, TEXINFO):
1129 if os.path.exists (eps_file):
1130 page_count = ps_page_count (eps_file)
1132 return not os.path.exists (png_file)
1134 return not reduce (operator.or_,
1135 [find_file (base + '-page%d.png' % a, raise_error=False)
1136 for a in range (1, page_count + 1)])
1139 def texstr_is_outdated (self):
1143 base = self.basename ()
1144 return not (self.ly_is_outdated ()
1145 and find_file (base + '.texstr', raise_error=False))
1147 def filter_text (self):
1148 code = self.substring ('code')
1149 s = run_filter (code)
1152 'options': self.match.group ('options')
1155 return output[self.format][FILTER] % d
1157 def replacement_text (self):
1158 func = Lilypond_snippet.__dict__['output_' + self.format]
1161 def get_images (self):
1162 base = self.basename ()
1164 single = '%(base)s.png' % vars ()
1165 multiple = '%(base)s-page1.png' % vars ()
1167 if os.path.exists (multiple) \
1168 and (not os.path.exists (single) \
1169 or (os.stat (multiple)[stat.ST_MTIME] \
1170 > os.stat (single)[stat.ST_MTIME])):
1171 count = ps_page_count ('%(base)s.eps' % vars ())
1172 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1173 images = tuple (images)
1176 def output_docbook (self):
1178 base = self.basename ()
1179 for image in self.get_images ():
1180 (base, ext) = os.path.splitext (image)
1181 str += output[DOCBOOK][OUTPUT] % vars ()
1182 str += self.output_print_filename (DOCBOOK)
1183 if (self.substring('inline') == 'inline'):
1184 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1186 str = '<mediaobject>' + str + '</mediaobject>'
1187 if VERBATIM in self.option_dict:
1188 verb = verbatim_html (self.verb_ly ())
1189 str = output[DOCBOOK][VERBATIM] % vars () + str
1192 def output_html (self):
1194 base = self.basename ()
1195 if global_options.format == HTML:
1196 str += self.output_print_filename (HTML)
1197 if VERBATIM in self.option_dict:
1198 verb = verbatim_html (self.verb_ly ())
1199 str += output[HTML][VERBATIM] % vars ()
1200 if QUOTE in self.option_dict:
1201 str = output[HTML][QUOTE] % vars ()
1203 str += output[HTML][BEFORE] % vars ()
1204 for image in self.get_images ():
1205 (base, ext) = os.path.splitext (image)
1206 alt = self.option_dict[ALT]
1207 str += output[HTML][OUTPUT] % vars ()
1208 str += output[HTML][AFTER] % vars ()
1211 def output_info (self):
1213 for image in self.get_images ():
1214 (base, ext) = os.path.splitext (image)
1216 # URG, makeinfo implicitly prepends dot to extension.
1217 # Specifying no extension is most robust.
1219 alt = self.option_dict[ALT]
1220 info_image_path = os.path.join (global_options.info_images_dir, base)
1221 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1223 base = self.basename ()
1224 str += output[global_options.format][OUTPUT] % vars ()
1227 def output_latex (self):
1229 base = self.basename ()
1230 if global_options.format == LATEX:
1231 str += self.output_print_filename (LATEX)
1232 if VERBATIM in self.option_dict:
1233 verb = self.verb_ly ()
1234 str += (output[LATEX][VERBATIM] % vars ())
1236 str += (output[LATEX][OUTPUT] % vars ())
1238 ## todo: maintain breaks
1240 breaks = self.ly ().count ("\n")
1241 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1243 if QUOTE in self.option_dict:
1244 str = output[LATEX][QUOTE] % vars ()
1247 def output_print_filename (self, format):
1249 if PRINTFILENAME in self.option_dict:
1250 base = self.basename ()
1251 filename = os.path.basename (self.substring ('filename'))
1252 str = output[format][PRINTFILENAME] % vars ()
1256 def output_texinfo (self):
1257 str = self.output_print_filename (TEXINFO)
1258 base = self.basename ()
1259 if TEXIDOC in self.option_dict:
1260 texidoc = base + '.texidoc'
1261 if os.path.exists (texidoc):
1262 str += '@include %(texidoc)s\n\n' % vars ()
1265 if VERBATIM in self.option_dict:
1266 verb = self.verb_ly ()
1267 if ADDVERSION in self.option_dict:
1268 verb = output[TEXINFO][ADDVERSION] % vars ()
1269 substr += output[TEXINFO][VERBATIM] % vars ()
1270 if not QUOTE in self.option_dict:
1271 substr = output[TEXINFO][NOQUOTE] % {'str':substr}
1272 substr += self.output_info ()
1273 if LILYQUOTE in self.option_dict:
1274 substr = output[TEXINFO][QUOTE] % {'str':substr}
1277 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1278 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1279 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1281 if QUOTE in self.option_dict:
1282 str = output[TEXINFO][QUOTE] % vars ()
1284 # need par after image
1289 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1290 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1292 class Lilypond_file_snippet (Lilypond_snippet):
1293 def __init__ (self, type, match, format, line_number):
1294 Lilypond_snippet.__init__ (self, type, match, format, line_number)
1295 self.contents = open (find_file (self.substring ('filename'))).read ()
1299 s = re_begin_verbatim.split (s)[-1]
1300 s = re_end_verbatim.split (s)[0]
1304 name = self.substring ('filename')
1305 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1306 % (name, self.contents))
1309 snippet_type_to_class = {
1310 'lilypond_file': Lilypond_file_snippet,
1311 'lilypond_block': Lilypond_snippet,
1312 'lilypond': Lilypond_snippet,
1313 'include': Include_snippet,
1316 def find_linestarts (s):
1321 i = s.find ('\n', start)
1329 nls.append (len (s))
1332 def find_toplevel_snippets (s, types):
1335 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1339 found = dict ([(t, None) for t in types])
1341 line_starts = find_linestarts (s)
1343 # We want to search for multiple regexes, without searching
1344 # the string multiple times for one regex.
1345 # Hence, we use earlier results to limit the string portion
1347 # Since every part of the string is traversed at most once for
1348 # every type of snippet, this is linear.
1354 if not found[type] or found[type][0] < index:
1357 m = res[type].search (s[index:endex])
1362 if snippet_type_to_class.has_key (type):
1363 cl = snippet_type_to_class[type]
1366 start = index + m.start ('match')
1367 line_number = line_start_idx
1368 while (line_starts[line_number] < start):
1372 snip = cl (type, m, global_options.format, line_number)
1374 found[type] = (start, snip)
1378 or found[type][0] < found[first][0]):
1383 # Limiting the search space is a cute
1384 # idea, but this *requires* to search
1385 # for possible containing blocks
1386 # first, at least as long as we do not
1387 # search for the start of blocks, but
1388 # always/directly for the entire
1389 # @block ... @end block.
1391 endex = found[first][0]
1394 snippets.append (Substring (s, index, len (s), line_start_idx))
1397 while (start > line_starts[line_start_idx+1]):
1400 (start, snip) = found[first]
1401 snippets.append (Substring (s, index, start, line_start_idx + 1))
1402 snippets.append (snip)
1404 index = start + len (snip.match.group ('match'))
1408 def filter_pipe (input, cmd):
1409 if global_options.verbose:
1410 progress (_ ("Opening filter `%s'") % cmd)
1412 (stdin, stdout, stderr) = os.popen3 (cmd)
1414 status = stdin.close ()
1418 output = stdout.read ()
1419 status = stdout.close ()
1420 error = stderr.read ()
1424 signal = 0x0f & status
1425 if status or (not output and error):
1426 exit_status = status >> 8
1427 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1428 error (_ ("The error log is as follows:"))
1429 ly.stderr_write (error)
1430 ly.stderr_write (stderr.read ())
1433 if global_options.verbose:
1439 return filter_pipe (s, global_options.filter_cmd)
1441 def is_derived_class (cl, baseclass):
1444 for b in cl.__bases__:
1445 if is_derived_class (b, baseclass):
1449 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1450 ly_names = filter (lambda x: x,
1451 map (Lilypond_snippet.basename, ly_snippets))
1452 texstr_names = filter (lambda x: x,
1453 map (Lilypond_snippet.basename, texstr_snippets))
1455 png_names = filter (lambda x: x,
1456 map (Lilypond_snippet.basename, png_snippets))
1459 def my_system (cmd):
1460 status = ly.system (cmd,
1461 be_verbose=global_options.verbose,
1464 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1465 cmd += ' --formats=png '
1466 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1467 cmd += ' --formats=png,pdf '
1471 # the --process=CMD switch is a bad idea
1472 # it is too generic for lilypond-book.
1474 my_system (' '.join ([cmd, '--backend texstr',
1475 'snippet-map.ly'] + texstr_names))
1476 for l in texstr_names:
1477 my_system ('latex %s.texstr' % l)
1480 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1483 my_system (' '.join ([cmd, 'snippet-names']))
1486 LATEX_INSPECTION_DOCUMENT = r'''
1490 \typeout{textwidth=\the\textwidth}
1491 \typeout{columnsep=\the\columnsep}
1492 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1496 # Do we need anything else besides `textwidth'?
1497 def get_latex_textwidth (source):
1498 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1500 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1502 ## what's a sensible default?
1505 preamble = source[:m.start (0)]
1506 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1508 (handle, tmpfile) = tempfile.mkstemp('.tex')
1509 logfile = os.path.splitext (tmpfile)[0] + '.log'
1510 logfile = os.path.split (logfile)[1]
1512 tmp_handle = os.fdopen (handle,'w')
1513 tmp_handle.write (latex_document)
1516 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1517 parameter_string = open (logfile).read()
1523 m = re.search ('columns=([0-9.]*)', parameter_string)
1525 columns = int (m.group (1))
1528 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1530 columnsep = float (m.group (1))
1533 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1535 textwidth = float (m.group (1))
1537 textwidth = (textwidth - columnsep) / columns
1541 def modify_preamble (chunk):
1542 str = chunk.replacement_text ()
1543 if (re.search (r"\\begin *{document}", str)
1544 and not re.search ("{graphic[sx]", str)):
1545 str = re.sub (r"\\begin{document}",
1546 r"\\usepackage{graphics}" + '\n'
1547 + r"\\begin{document}",
1549 chunk.override_text = str
1561 '.texinfo': TEXINFO,
1568 # TEXINFO: '.texinfo',
1574 class Compile_error:
1577 def write_file_map (lys, name):
1578 snippet_map = open ('snippet-map.ly', 'w')
1579 snippet_map.write ("""
1580 #(define version-seen #t)
1581 #(define output-empty-score-list #f)
1582 #(ly:add-file-name-alist '(
1585 snippet_map.write ('("%s.ly" . "%s")\n'
1589 snippet_map.write ('))\n')
1591 def do_process_cmd (chunks, input_name):
1592 all_lys = filter (lambda x: is_derived_class (x.__class__,
1596 write_file_map (all_lys, input_name)
1597 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1599 and x.ly_is_outdated (), chunks)
1600 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1602 and x.texstr_is_outdated (),
1604 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1606 and x.png_is_outdated (),
1609 outdated = png_outdated + texstr_outdated + ly_outdated
1611 progress (_ ("Writing snippets..."))
1612 map (Lilypond_snippet.write_ly, ly_outdated)
1616 progress (_ ("Processing..."))
1618 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1620 progress (_ ("All snippets are up to date..."))
1623 def guess_format (input_filename):
1625 e = os.path.splitext (input_filename)[1]
1626 if e in ext2format.keys ():
1628 format = ext2format[e]
1630 error (_ ("cannot determine format for: %s" \
1635 def write_if_updated (file_name, lines):
1637 f = open (file_name)
1639 new_str = ''.join (lines)
1640 if oldstr == new_str:
1641 progress (_ ("%s is up to date.") % file_name)
1644 # this prevents make from always rerunning lilypond-book:
1645 # .texi target must be touched in order to be up to date
1646 if global_options.format == 'texinfo':
1647 os.utime (file_name, None)
1652 progress (_ ("Writing `%s'...") % file_name)
1653 open (file_name, 'w').writelines (lines)
1656 def note_input_file (name, inputs=[]):
1657 ## hack: inputs is mutable!
1658 inputs.append (name)
1661 def samefile (f1, f2):
1663 return os.path.samefile (f1, f2)
1664 except AttributeError: # Windoze
1665 f1 = re.sub ("//*", "/", f1)
1666 f2 = re.sub ("//*", "/", f2)
1669 def do_file (input_filename):
1671 if not input_filename or input_filename == '-':
1672 in_handle = sys.stdin
1673 input_fullname = '<stdin>'
1675 if os.path.exists (input_filename):
1676 input_fullname = input_filename
1677 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1678 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1680 input_fullname = find_file (input_filename)
1682 note_input_file (input_fullname)
1683 in_handle = open (input_fullname)
1685 if input_filename == '-':
1686 input_base = 'stdin'
1688 input_base = os.path.basename \
1689 (os.path.splitext (input_filename)[0])
1691 # Only default to stdout when filtering.
1692 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1693 output_filename = '-'
1694 output_file = sys.stdout
1696 # don't complain when global_options.output_name is existing
1697 output_filename = input_base + format2ext[global_options.format]
1698 if global_options.output_name:
1699 if not os.path.isdir (global_options.output_name):
1700 os.mkdir (global_options.output_name, 0777)
1701 os.chdir (global_options.output_name)
1703 if (os.path.exists (input_filename)
1704 and os.path.exists (output_filename)
1705 and samefile (output_filename, input_fullname)):
1707 _ ("Output would overwrite input file; use --output."))
1711 progress (_ ("Reading %s...") % input_fullname)
1712 source = in_handle.read ()
1715 set_default_options (source)
1718 # FIXME: Containing blocks must be first, see
1719 # find_toplevel_snippets.
1721 'multiline_comment',
1725 'singleline_comment',
1730 progress (_ ("Dissecting..."))
1731 chunks = find_toplevel_snippets (source, snippet_types)
1733 if global_options.format == LATEX:
1735 if (c.is_plain () and
1736 re.search (r"\\begin *{document}", c.replacement_text())):
1741 if global_options.filter_cmd:
1742 write_if_updated (output_filename,
1743 [c.filter_text () for c in chunks])
1744 elif global_options.process_cmd:
1745 do_process_cmd (chunks, input_fullname)
1746 progress (_ ("Compiling %s...") % output_filename)
1748 write_if_updated (output_filename,
1749 [s.replacement_text ()
1752 def process_include (snippet):
1753 os.chdir (original_dir)
1754 name = snippet.substring ('filename')
1755 progress (_ ("Processing include: %s") % name)
1757 return do_file (name)
1759 include_chunks = map (process_include,
1760 filter (lambda x: is_derived_class (x.__class__,
1765 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1767 except Compile_error:
1768 os.chdir (original_dir)
1769 progress (_ ("Removing `%s'") % output_filename)
1775 global global_options
1777 opt_parser = get_option_parser()
1778 (global_options, args) = opt_parser.parse_args ()
1780 if global_options.format in ('texi-html', 'texi'):
1781 global_options.format = TEXINFO
1782 global_options.use_hash = True
1784 global_options.include_path = map (os.path.abspath, global_options.include_path)
1786 if global_options.warranty:
1789 if not args or len (args) > 1:
1790 opt_parser.print_help ()
1795 def psfonts_warning (options, basename):
1796 if options.format in (TEXINFO, LATEX):
1797 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1798 output = os.path.join (options.output_name, basename + '.dvi' )
1800 if not options.create_pdf:
1801 if not options.psfonts:
1802 warning (_ ("option --psfonts not used"))
1803 warning (_ ("processing with dvips will have no fonts"))
1806 progress (_ ("DVIPS usage:"))
1808 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1812 # FIXME: 85 lines of `main' macramee??
1813 files = do_options ()
1817 basename = os.path.splitext (file)[0]
1818 basename = os.path.split (basename)[1]
1820 if not global_options.format:
1821 global_options.format = guess_format (files[0])
1824 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1828 if global_options.process_cmd == '':
1829 global_options.process_cmd = (lilypond_binary
1830 + ' --formats=%s --backend eps ' % formats)
1832 if global_options.process_cmd:
1833 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1834 for p in global_options.include_path])
1836 if global_options.format in (TEXINFO, LATEX):
1837 ## prevent PDF from being switched on by default.
1838 global_options.process_cmd += ' --formats=eps '
1839 if global_options.create_pdf:
1840 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1842 if global_options.verbose:
1843 global_options.process_cmd += " --verbose "
1845 if global_options.padding_mm:
1846 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1848 global_options.process_cmd += " -dread-file-list "
1853 chunks = do_file (file)
1854 if global_options.psfonts:
1855 fontextract.verbose = global_options.verbose
1856 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1860 psfonts_file = basename + '.psfonts'
1861 if not global_options.verbose:
1862 progress (_ ("Writing fonts to %s...") % psfonts_file)
1863 fontextract.extract_fonts (psfonts_file,
1864 [x.basename() + '.eps'
1865 for x in snippet_chunks])
1866 if not global_options.verbose:
1869 except Compile_error:
1872 psfonts_warning (global_options, basename)
1874 inputs = note_input_file ('')
1877 base_file_name = os.path.splitext (os.path.basename (file))[0]
1878 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1879 final_output_file = os.path.join (global_options.output_name,
1881 + '.%s' % global_options.format)
1883 os.chdir (original_dir)
1884 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1886 if __name__ == '__main__':