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 _ ('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 string.atoi (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
203 EXAMPLEINDENT = 'exampleindent'
205 FRAGMENT = 'fragment'
210 LINE_WIDTH = 'line-width'
211 LILYQUOTE = 'lilyquote'
212 NOFRAGMENT = 'nofragment'
213 NOINDENT = 'noindent'
218 OUTPUTIMAGE = 'outputimage'
221 PREAMBLE = 'preamble'
222 PRINTFILENAME = 'printfilename'
224 RAGGED_RIGHT = 'ragged-right'
225 RELATIVE = 'relative'
226 STAFFSIZE = 'staffsize'
229 VERBATIM = 'verbatim'
230 FONTLOAD = 'fontload'
231 FILENAME = 'filename'
235 # NOTIME has no opposite so it isn't part of this dictionary.
236 # NOQUOTE is used internally only.
238 NOFRAGMENT: FRAGMENT,
243 # Recognize special sequences in the input.
245 # (?P<name>regex) -- Assign result of REGEX to NAME.
246 # *? -- Match non-greedily.
247 # (?m) -- Multiline regex: Make ^ and $ match at each line.
248 # (?s) -- Make the dot match all characters including newline.
249 # (?x) -- Ignore whitespace in patterns.
260 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
265 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
270 <(?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>)''',
276 (?P<code><!--\s.*?!-->)
279 'singleline_comment':
298 (\s*(?P<options>.*?)\s*:)?\s*
306 \s*(?P<options>.*?)\s*
315 \s*(?P<options>.*?)\s*
317 \s*(?P<filename>.*?)\s*
324 (?P<code><!--\s.*?!-->)
327 'singleline_comment':
333 (?P<code><pre>.*?</pre>))''',
339 (?P<code><pre>\s.*?</pre>\s))''',
358 \s*(?P<options>.*?)\s*
369 \s*(?P<options>.*?)\s*
373 \\end\s*{lilypond})''',
381 \s*(?P<options>.*?)\s*
389 'singleline_comment':
412 \\end\s*{verbatim}))''',
421 (?P<filename>\S+))''',
425 ^[^\n]*?(?!@c\s+)[^\n]*?
429 \s*(?P<options>.*?)\s*
439 \s*(?P<options>.*?)\s*
442 ^@end\s+lilypond)\s''',
449 \s*(?P<options>.*?)\s*
460 @end\s+ignore))\s''',
462 'singleline_comment':
467 @c([ \t][^\n]*|)\n))''',
469 # Don't do this: It interferes with @code{@{}.
470 # 'verb': r'''(?P<code>@code{.*?})''',
478 @end\s+example\s))''',
487 'intertext': r',?\s*intertext=\".*?\"',
491 'intertext': r',?\s*intertext=\".*?\"',
496 'intertext': r',?\s*intertext=\".*?\"',
497 'option_sep': '\s*,\s*',
501 'intertext': r',?\s*intertext=\".*?\"',
502 'option_sep': '\s*,\s*',
506 # Options without a pattern in ly_options.
523 RELATIVE: r'''\relative c%(relative_quotes)s''',
528 INDENT: r'''indent = %(indent)s''',
530 LINE_WIDTH: r'''line-width = %(line-width)s''',
532 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
534 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
536 RAGGED_RIGHT: r'''ragged-right = ##t''',
538 PACKED: r'''packed = ##t''',
550 \remove Time_signature_engraver
556 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
563 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
566 <imageobject role="latex">
567 <imagedata fileref="%(base)s.pdf" format="PDF"/>
569 <imageobject role="html">
570 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
572 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
574 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
578 FILTER: r'''<lilypond %(options)s>
588 <a href="%(base)s.ly">''',
591 <img align="center" valign="center"
592 border="0" src="%(image)s" alt="%(alt)s">''',
594 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
596 QUOTE: r'''<blockquote>
609 \ifx\preLilyPondExample \undefined%%
612 \preLilyPondExample%%
614 \def\lilypondbook{}%%
615 \input %(base)s-systems.tex%%
616 \ifx\postLilyPondExample \undefined%%
619 \postLilyPondExample%%
623 PRINTFILENAME: '''\\texttt{%(filename)s}
626 QUOTE: r'''\begin{quotation}%(str)s
629 VERBATIM: r'''\noindent
630 \begin{verbatim}%(verb)s\end{verbatim}''',
632 FILTER: r'''\begin{lilypond}[%(options)s]
639 FILTER: r'''@lilypond[%(options)s]
645 @include %(base)s-systems.texi
649 OUTPUTIMAGE: r'''@noindent
651 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
655 <a href="%(base)s.ly">
656 <img align="center" valign="center"
657 border="0" src="%(image)s" alt="%(alt)s">
665 <a href="%(base)s.ly">
673 QUOTE: r'''@quotation
674 %(str)s@end quotation
681 VERBATIM: r'''@exampleindent 0
683 %(verb)s@end verbatim
689 # Maintain line numbers.
694 for f in [HTML, LATEX]:
695 for s in (QUOTE, VERBATIM):
696 output[f][s] = output[f][s].replace("\n"," ")
699 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
700 %%%% Options: [%(option_string)s]
701 \\include "lilypond-book-preamble.ly"
704 %% ****************************************************************
705 %% Start cut-&-pastable-section
706 %% ****************************************************************
711 #(define dump-extents #t)
712 %(font_dump_setting)s
714 force-assignment = #""
715 line-width = #(- line-width (* mm %(padding_mm)f))
728 %% ****************************************************************
729 %% ly snippet contents follows:
730 %% ****************************************************************
734 %% ****************************************************************
736 %% ****************************************************************
743 %% ****************************************************************
745 %% ****************************************************************
749 %% ****************************************************************
751 %% ****************************************************************
754 texinfo_line_widths = {
755 '@afourpaper': '160\\mm',
756 '@afourwide': '6.5\\in',
757 '@afourlatex': '150\\mm',
758 '@smallbook': '5\\in',
759 '@letterpaper': '6\\in',
762 def classic_lilypond_book_compatibility (key, value):
763 if key == 'singleline' and value == None:
764 return (RAGGED_RIGHT, None)
766 m = re.search ('relative\s*([-0-9])', key)
768 return ('relative', m.group (1))
770 m = re.match ('([0-9]+)pt', key)
772 return ('staffsize', m.group (1))
774 if key == 'indent' or key == 'line-width':
775 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
777 f = float (m.group (1))
778 return (key, '%f\\%s' % (f, m.group (2)))
782 def find_file (name):
783 for i in global_options.include_path:
784 full = os.path.join (i, name)
785 if os.path.exists (full):
788 error (_ ("file not found: %s") % name + '\n')
792 def verbatim_html (s):
793 return re.sub ('>', '>',
795 re.sub ('&', '&', s)))
797 def split_options (option_string):
799 if global_options.format == HTML:
800 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
801 for i in range(len(options)):
802 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
805 return re.split (format_res[global_options.format]['option_sep'],
809 def set_default_options (source):
810 global default_ly_options
811 if not default_ly_options.has_key (LINE_WIDTH):
812 if global_options.format == LATEX:
813 textwidth = get_latex_textwidth (source)
814 default_ly_options[LINE_WIDTH] = \
815 '''%.0f\\pt''' % textwidth
816 elif global_options.format == TEXINFO:
817 for (k, v) in texinfo_line_widths.items ():
818 # FIXME: @layout is usually not in
821 # \input texinfo @c -*-texinfo-*-
823 # Bluntly search first K items of
825 # s = chunks[0].replacement_text ()
826 if re.search (k, source[:1024]):
827 default_ly_options[LINE_WIDTH] = v
831 def replacement_text (self):
834 def filter_text (self):
835 return self.replacement_text ()
837 def ly_is_outdated (self):
840 def png_is_outdated (self):
846 class Substring (Chunk):
847 def __init__ (self, source, start, end, line_number):
851 self.line_number = line_number
852 self.override_text = None
857 def replacement_text (self):
858 if self.override_text:
859 return self.override_text
861 return self.source[self.start:self.end]
863 class Snippet (Chunk):
864 def __init__ (self, type, match, format, line_number):
868 self.option_dict = {}
870 self.line_number = line_number
872 def replacement_text (self):
873 return self.match.group ('match')
875 def substring (self, s):
876 return self.match.group (s)
879 return `self.__class__` + ' type = ' + self.type
881 class Include_snippet (Snippet):
882 def processed_filename (self):
883 f = self.substring ('filename')
884 return os.path.splitext (f)[0] + format2ext[global_options.format]
886 def replacement_text (self):
887 s = self.match.group ('match')
888 f = self.substring ('filename')
890 return re.sub (f, self.processed_filename (), s)
892 class Lilypond_snippet (Snippet):
893 def __init__ (self, type, match, format, line_number):
894 Snippet.__init__ (self, type, match, format, line_number)
895 os = match.group ('options')
896 self.do_options (os, self.type)
899 return self.substring ('code')
902 contents = self.substring ('code')
903 return ('\\sourcefileline %d\n%s'
904 % (self.line_number - 1, contents))
909 return self.compose_ly (s)
912 def do_options (self, option_string, type):
913 self.option_dict = {}
915 options = split_options (option_string)
919 (key, value) = re.split ('\s*=\s*', i)
920 self.option_dict[key] = value
922 if i in no_options.keys ():
923 if no_options[i] in self.option_dict.keys ():
924 del self.option_dict[no_options[i]]
926 self.option_dict[i] = None
928 has_line_width = self.option_dict.has_key (LINE_WIDTH)
929 no_line_width_value = 0
931 # If LINE_WIDTH is used without parameter, set it to default.
932 if has_line_width and self.option_dict[LINE_WIDTH] == None:
933 no_line_width_value = 1
934 del self.option_dict[LINE_WIDTH]
936 for i in default_ly_options.keys ():
937 if i not in self.option_dict.keys ():
938 self.option_dict[i] = default_ly_options[i]
940 if not has_line_width:
941 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
942 self.option_dict[RAGGED_RIGHT] = None
944 if type == 'lilypond':
945 if LINE_WIDTH in self.option_dict.keys ():
946 del self.option_dict[LINE_WIDTH]
948 if RAGGED_RIGHT in self.option_dict.keys ():
949 if LINE_WIDTH in self.option_dict.keys ():
950 del self.option_dict[LINE_WIDTH]
952 if QUOTE in self.option_dict.keys () or type == 'lilypond':
953 if LINE_WIDTH in self.option_dict.keys ():
954 del self.option_dict[LINE_WIDTH]
956 if not INDENT in self.option_dict.keys ():
957 self.option_dict[INDENT] = '0\\mm'
959 # The QUOTE pattern from ly_options only emits the `line-width'
961 if has_line_width and QUOTE in self.option_dict.keys ():
962 if no_line_width_value:
963 del self.option_dict[LINE_WIDTH]
965 del self.option_dict[QUOTE]
967 def compose_ly (self, code):
968 if FRAGMENT in self.option_dict.keys ():
976 # The original concept of the `exampleindent' option is broken.
977 # It is not possible to get a sane value for @exampleindent at all
978 # without processing the document itself. Saying
986 # causes ugly results with the DVI backend of texinfo since the
987 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
988 # value). Executing the above code changes the environment
989 # indentation to an unknown value because we don't know the amount
990 # of 1em in advance since it is font-dependent. Modifying
991 # @exampleindent in the middle of a document is simply not
992 # supported within texinfo.
994 # As a consequence, the only function of @exampleindent is now to
995 # specify the amount of indentation for the `quote' option.
997 # To set @exampleindent locally to zero, we use the @format
998 # environment for non-quoted snippets.
999 override[EXAMPLEINDENT] = r'0.4\in'
1000 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1001 override.update (default_ly_options)
1004 for (key, value) in self.option_dict.items ():
1006 option_list.append (key)
1008 option_list.append (key + '=' + value)
1009 option_string = string.join (option_list, ',')
1012 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1013 for a in compose_types:
1014 compose_dict[a] = []
1016 for (key, value) in self.option_dict.items ():
1017 (c_key, c_value) = \
1018 classic_lilypond_book_compatibility (key, value)
1022 (_ ("deprecated ly-option used: %s=%s" \
1025 (_ ("compatibility mode translation: %s=%s" \
1026 % (c_key, c_value)))
1029 (_ ("deprecated ly-option used: %s" \
1032 (_ ("compatibility mode translation: %s" \
1035 (key, value) = (c_key, c_value)
1038 override[key] = value
1040 if not override.has_key (key):
1041 override[key] = None
1044 for type in compose_types:
1045 if ly_options[type].has_key (key):
1046 compose_dict[type].append (ly_options[type][key])
1050 if not found and key not in simple_options:
1051 warning (_ ("ignoring unknown ly option: %s") % key)
1054 if RELATIVE in override.keys () and override[RELATIVE]:
1055 relative = int (override[RELATIVE])
1057 relative_quotes = ''
1061 relative_quotes += ',' * (- relative)
1063 relative_quotes += "'" * relative
1065 paper_string = string.join (compose_dict[PAPER],
1067 layout_string = string.join (compose_dict[LAYOUT],
1069 notes_string = string.join (compose_dict[NOTES],
1071 preamble_string = string.join (compose_dict[PREAMBLE],
1073 padding_mm = global_options.padding_mm
1074 font_dump_setting = ''
1075 if FONTLOAD in self.option_dict:
1076 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1078 d = globals().copy()
1080 return (PREAMBLE_LY + body) % d
1082 def get_hash (self):
1084 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1086 ## let's not create too long names.
1087 self.hash = hash.hexdigest ()[:10]
1091 def basename (self):
1092 if FILENAME in self.option_dict:
1093 return self.option_dict[FILENAME]
1094 if global_options.use_hash:
1095 return 'lily-%s' % self.get_hash ()
1098 def write_ly (self):
1099 outf = open (self.basename () + '.ly', 'w')
1100 outf.write (self.full_ly ())
1101 open (self.basename () + '.txt', 'w').write ('image of music')
1103 def relevant_contents (self, ly):
1104 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1106 def ly_is_outdated (self):
1107 base = self.basename ()
1108 ly_file = base + '.ly'
1109 tex_file = base + '.tex'
1110 eps_file = base + '.eps'
1111 systems_file = base + '-systems.tex'
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 # FIXME: refactor stupid OK stuff
1127 ok = not self.ly_is_outdated ()
1128 if global_options.format in (HTML, TEXINFO):
1129 ok = ok and os.path.exists (base + '.eps')
1133 page_count = ps_page_count (base + '.eps')
1136 ok = ok and os.path.exists (base + '.png')
1138 elif page_count > 1:
1139 for a in range (1, page_count + 1):
1140 ok = ok and os.path.exists (base + '-page%d.png' % a)
1144 def texstr_is_outdated (self):
1148 # FIXME: refactor stupid OK stuff
1149 base = self.basename ()
1150 ok = self.ly_is_outdated ()
1151 ok = ok and (os.path.exists (base + '.texstr'))
1154 def filter_text (self):
1155 code = self.substring ('code')
1156 s = run_filter (code)
1159 'options': self.match.group ('options')
1162 return output[self.format][FILTER] % d
1164 def replacement_text (self):
1165 func = Lilypond_snippet.__dict__['output_' + self.format]
1168 def get_images (self):
1169 base = self.basename ()
1171 single = '%(base)s.png' % vars ()
1172 multiple = '%(base)s-page1.png' % vars ()
1174 if os.path.exists (multiple) \
1175 and (not os.path.exists (single) \
1176 or (os.stat (multiple)[stat.ST_MTIME] \
1177 > os.stat (single)[stat.ST_MTIME])):
1178 count = ps_page_count ('%(base)s.eps' % vars ())
1179 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1180 images = tuple (images)
1183 def output_docbook (self):
1185 base = self.basename ()
1186 for image in self.get_images ():
1187 (base, ext) = os.path.splitext (image)
1188 str += output[DOCBOOK][OUTPUT] % vars ()
1189 str += self.output_print_filename (DOCBOOK)
1190 if (self.substring('inline') == 'inline'):
1191 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1193 str = '<mediaobject>' + str + '</mediaobject>'
1194 if VERBATIM in self.option_dict:
1195 verb = verbatim_html (self.verb_ly ())
1196 str = output[DOCBOOK][VERBATIM] % vars () + str
1199 def output_html (self):
1201 base = self.basename ()
1202 if global_options.format == HTML:
1203 str += self.output_print_filename (HTML)
1204 if VERBATIM in self.option_dict:
1205 verb = verbatim_html (self.verb_ly ())
1206 str += output[HTML][VERBATIM] % vars ()
1207 if QUOTE in self.option_dict:
1208 str = output[HTML][QUOTE] % vars ()
1210 str += output[HTML][BEFORE] % vars ()
1211 for image in self.get_images ():
1212 (base, ext) = os.path.splitext (image)
1213 alt = self.option_dict[ALT]
1214 str += output[HTML][OUTPUT] % vars ()
1215 str += output[HTML][AFTER] % vars ()
1218 def output_info (self):
1220 for image in self.get_images ():
1221 (base, ext) = os.path.splitext (image)
1223 # URG, makeinfo implicitly prepends dot to extension.
1224 # Specifying no extension is most robust.
1226 alt = self.option_dict[ALT]
1227 info_image_path = os.path.join (global_options.info_images_dir, base)
1228 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1230 base = self.basename ()
1231 str += output[global_options.format][OUTPUT] % vars ()
1234 def output_latex (self):
1236 base = self.basename ()
1237 if global_options.format == LATEX:
1238 str += self.output_print_filename (LATEX)
1239 if VERBATIM in self.option_dict:
1240 verb = self.verb_ly ()
1241 str += (output[LATEX][VERBATIM] % vars ())
1243 str += (output[LATEX][OUTPUT] % vars ())
1245 ## todo: maintain breaks
1247 breaks = self.ly ().count ("\n")
1248 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1250 if QUOTE in self.option_dict:
1251 str = output[LATEX][QUOTE] % vars ()
1254 def output_print_filename (self, format):
1256 if PRINTFILENAME in self.option_dict:
1257 base = self.basename ()
1258 filename = self.substring ('filename')
1259 str = output[global_options.format][PRINTFILENAME] % vars ()
1263 def output_texinfo (self):
1265 if self.output_print_filename (TEXINFO):
1267 + self.output_print_filename (HTML)
1270 + self.output_print_filename (LATEX)
1272 base = self.basename ()
1273 if TEXIDOC in self.option_dict:
1274 texidoc = base + '.texidoc'
1275 if os.path.exists (texidoc):
1276 str += '@include %(texidoc)s\n\n' % vars ()
1279 if VERBATIM in self.option_dict:
1280 verb = self.verb_ly ()
1281 substr += output[TEXINFO][VERBATIM] % vars ()
1282 if not QUOTE in self.option_dict:
1283 substr = output[TEXINFO][NOQUOTE] % {'str':substr}
1284 substr += self.output_info ()
1285 if LILYQUOTE in self.option_dict:
1286 substr = output[TEXINFO][QUOTE] % {'str':substr}
1289 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1290 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1291 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1293 if QUOTE in self.option_dict:
1294 str = output[TEXINFO][QUOTE] % vars ()
1296 # need par after image
1301 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1302 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1304 class Lilypond_file_snippet (Lilypond_snippet):
1305 def __init__ (self, type, match, format, line_number):
1306 Lilypond_snippet.__init__ (self, type, match, format, line_number)
1307 self.contents = open (find_file (self.substring ('filename'))).read ()
1311 s = re_begin_verbatim.split (s)[-1]
1312 s = re_end_verbatim.split (s)[0]
1316 name = self.substring ('filename')
1317 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1318 % (name, self.contents))
1321 snippet_type_to_class = {
1322 'lilypond_file': Lilypond_file_snippet,
1323 'lilypond_block': Lilypond_snippet,
1324 'lilypond': Lilypond_snippet,
1325 'include': Include_snippet,
1328 def find_linestarts (s):
1333 i = s.find ('\n', start)
1341 nls.append (len (s))
1344 def find_toplevel_snippets (s, types):
1347 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1351 found = dict ([(t, None) for t in types])
1353 line_starts = find_linestarts (s)
1355 # We want to search for multiple regexes, without searching
1356 # the string multiple times for one regex.
1357 # Hence, we use earlier results to limit the string portion
1359 # Since every part of the string is traversed at most once for
1360 # every type of snippet, this is linear.
1366 if not found[type] or found[type][0] < index:
1369 m = res[type].search (s[index:endex])
1374 if snippet_type_to_class.has_key (type):
1375 cl = snippet_type_to_class[type]
1378 start = index + m.start ('match')
1379 line_number = line_start_idx
1380 while (line_starts[line_number] < start):
1384 snip = cl (type, m, global_options.format, line_number)
1386 found[type] = (start, snip)
1390 or found[type][0] < found[first][0]):
1395 # Limiting the search space is a cute
1396 # idea, but this *requires* to search
1397 # for possible containing blocks
1398 # first, at least as long as we do not
1399 # search for the start of blocks, but
1400 # always/directly for the entire
1401 # @block ... @end block.
1403 endex = found[first][0]
1406 snippets.append (Substring (s, index, len (s), line_start_idx))
1409 while (start > line_starts[line_start_idx+1]):
1412 (start, snip) = found[first]
1413 snippets.append (Substring (s, index, start, line_start_idx + 1))
1414 snippets.append (snip)
1416 index = start + len (snip.match.group ('match'))
1420 def filter_pipe (input, cmd):
1421 if global_options.verbose:
1422 progress (_ ("Opening filter `%s'") % cmd)
1424 (stdin, stdout, stderr) = os.popen3 (cmd)
1426 status = stdin.close ()
1430 output = stdout.read ()
1431 status = stdout.close ()
1432 error = stderr.read ()
1436 signal = 0x0f & status
1437 if status or (not output and error):
1438 exit_status = status >> 8
1439 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1440 error (_ ("The error log is as follows:"))
1441 ly.stderr_write (error)
1442 ly.stderr_write (stderr.read ())
1445 if global_options.verbose:
1451 return filter_pipe (s, global_options.filter_cmd)
1453 def is_derived_class (cl, baseclass):
1456 for b in cl.__bases__:
1457 if is_derived_class (b, baseclass):
1461 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1462 ly_names = filter (lambda x: x,
1463 map (Lilypond_snippet.basename, ly_snippets))
1464 texstr_names = filter (lambda x: x,
1465 map (Lilypond_snippet.basename, texstr_snippets))
1467 png_names = filter (lambda x: x,
1468 map (Lilypond_snippet.basename, png_snippets))
1471 def my_system (cmd):
1472 status = ly.system (cmd,
1473 be_verbose=global_options.verbose,
1476 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1477 cmd += ' --formats=png '
1478 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1479 cmd += ' --formats=png,pdf '
1483 # the --process=CMD switch is a bad idea
1484 # it is too generic for lilypond-book.
1486 my_system (string.join ([cmd, '--backend texstr',
1487 'snippet-map.ly'] + texstr_names))
1488 for l in texstr_names:
1489 my_system ('latex %s.texstr' % l)
1492 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1495 my_system (string.join ([cmd, 'snippet-names']))
1498 LATEX_INSPECTION_DOCUMENT = r'''
1502 \typeout{textwidth=\the\textwidth}
1503 \typeout{columnsep=\the\columnsep}
1504 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1508 # Do we need anything else besides `textwidth'?
1509 def get_latex_textwidth (source):
1510 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1512 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1514 ## what's a sensible default?
1517 preamble = source[:m.start (0)]
1518 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1520 (handle, tmpfile) = tempfile.mkstemp('.tex')
1521 logfile = os.path.splitext (tmpfile)[0] + '.log'
1522 logfile = os.path.split (logfile)[1]
1524 tmp_handle = os.fdopen (handle,'w')
1525 tmp_handle.write (latex_document)
1528 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1529 parameter_string = open (logfile).read()
1535 m = re.search ('columns=([0-9.]*)', parameter_string)
1537 columns = int (m.group (1))
1540 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1542 columnsep = float (m.group (1))
1545 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1547 textwidth = float (m.group (1))
1549 textwidth = (textwidth - columnsep) / columns
1553 def modify_preamble (chunk):
1554 str = chunk.replacement_text ()
1555 if (re.search (r"\\begin *{document}", str)
1556 and not re.search ("{graphic[sx]", str)):
1557 str = re.sub (r"\\begin{document}",
1558 r"\\usepackage{graphics}" + '\n'
1559 + r"\\begin{document}",
1561 chunk.override_text = str
1573 '.texinfo': TEXINFO,
1580 # TEXINFO: '.texinfo',
1586 class Compile_error:
1589 def write_file_map (lys, name):
1590 snippet_map = open ('snippet-map.ly', 'w')
1591 snippet_map.write ("""
1592 #(define version-seen #t)
1593 #(define output-empty-score-list #f)
1594 #(ly:add-file-name-alist '(
1597 snippet_map.write ('("%s.ly" . "%s")\n'
1601 snippet_map.write ('))\n')
1603 def do_process_cmd (chunks, input_name):
1604 all_lys = filter (lambda x: is_derived_class (x.__class__,
1608 write_file_map (all_lys, input_name)
1609 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1611 and x.ly_is_outdated (), chunks)
1612 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1614 and x.texstr_is_outdated (),
1616 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1618 and x.png_is_outdated (),
1621 outdated = png_outdated + texstr_outdated + ly_outdated
1623 progress (_ ("Writing snippets..."))
1624 map (Lilypond_snippet.write_ly, ly_outdated)
1628 progress (_ ("Processing..."))
1630 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1632 progress (_ ("All snippets are up to date..."))
1635 def guess_format (input_filename):
1637 e = os.path.splitext (input_filename)[1]
1638 if e in ext2format.keys ():
1640 format = ext2format[e]
1642 error (_ ("cannot determine format for: %s" \
1647 def write_if_updated (file_name, lines):
1649 f = open (file_name)
1651 new_str = string.join (lines, '')
1652 if oldstr == new_str:
1653 progress (_ ("%s is up to date.") % file_name)
1659 progress (_ ("Writing `%s'...") % file_name)
1660 open (file_name, 'w').writelines (lines)
1663 def note_input_file (name, inputs=[]):
1664 ## hack: inputs is mutable!
1665 inputs.append (name)
1668 def samefile (f1, f2):
1670 return os.path.samefile (f1, f2)
1671 except AttributeError: # Windoze
1672 f1 = re.sub ("//*", "/", f1)
1673 f2 = re.sub ("//*", "/", f2)
1676 def do_file (input_filename):
1678 if not input_filename or input_filename == '-':
1679 in_handle = sys.stdin
1680 input_fullname = '<stdin>'
1682 if os.path.exists (input_filename):
1683 input_fullname = input_filename
1684 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1685 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1687 input_fullname = find_file (input_filename)
1689 note_input_file (input_fullname)
1690 in_handle = open (input_fullname)
1692 if input_filename == '-':
1693 input_base = 'stdin'
1695 input_base = os.path.basename \
1696 (os.path.splitext (input_filename)[0])
1698 # Only default to stdout when filtering.
1699 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1700 output_filename = '-'
1701 output_file = sys.stdout
1703 # don't complain when global_options.output_name is existing
1704 output_filename = input_base + format2ext[global_options.format]
1705 if global_options.output_name:
1706 if not os.path.isdir (global_options.output_name):
1707 os.mkdir (global_options.output_name, 0777)
1708 os.chdir (global_options.output_name)
1710 if (os.path.exists (input_filename)
1711 and os.path.exists (output_filename)
1712 and samefile (output_filename, input_fullname)):
1714 _ ("Output would overwrite input file; use --output."))
1718 progress (_ ("Reading %s...") % input_fullname)
1719 source = in_handle.read ()
1722 set_default_options (source)
1725 # FIXME: Containing blocks must be first, see
1726 # find_toplevel_snippets.
1728 'multiline_comment',
1732 'singleline_comment',
1737 progress (_ ("Dissecting..."))
1738 chunks = find_toplevel_snippets (source, snippet_types)
1740 if global_options.format == LATEX:
1742 if (c.is_plain () and
1743 re.search (r"\\begin *{document}", c.replacement_text())):
1748 if global_options.filter_cmd:
1749 write_if_updated (output_filename,
1750 [c.filter_text () for c in chunks])
1751 elif global_options.process_cmd:
1752 do_process_cmd (chunks, input_fullname)
1753 progress (_ ("Compiling %s...") % output_filename)
1755 write_if_updated (output_filename,
1756 [s.replacement_text ()
1759 def process_include (snippet):
1760 os.chdir (original_dir)
1761 name = snippet.substring ('filename')
1762 progress (_ ("Processing include: %s") % name)
1764 return do_file (name)
1766 include_chunks = map (process_include,
1767 filter (lambda x: is_derived_class (x.__class__,
1772 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1774 except Compile_error:
1775 os.chdir (original_dir)
1776 progress (_ ("Removing `%s'") % output_filename)
1782 global global_options
1784 opt_parser = get_option_parser()
1785 (global_options, args) = opt_parser.parse_args ()
1787 if global_options.format in ('texi-html', 'texi'):
1788 global_options.format = TEXINFO
1789 global_options.use_hash = True
1791 global_options.include_path = map (os.path.abspath, global_options.include_path)
1793 if global_options.warranty:
1796 if not args or len (args) > 1:
1797 opt_parser.print_help ()
1802 def psfonts_warning (options, basename):
1803 if options.format in (TEXINFO, LATEX):
1804 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1805 output = os.path.join (options.output_name, basename + '.dvi' )
1807 if not options.create_pdf:
1808 if not options.psfonts:
1809 warning (_ ("option --psfonts not used"))
1810 warning (_ ("processing with dvips will have no fonts"))
1813 progress (_ ("DVIPS usage:"))
1815 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1819 # FIXME: 85 lines of `main' macramee??
1820 files = do_options ()
1824 basename = os.path.splitext (file)[0]
1825 basename = os.path.split (basename)[1]
1827 if not global_options.format:
1828 global_options.format = guess_format (files[0])
1831 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1835 if global_options.process_cmd == '':
1836 global_options.process_cmd = (lilypond_binary
1837 + ' --formats=%s --backend eps ' % formats)
1839 if global_options.process_cmd:
1840 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1841 for p in global_options.include_path])
1843 if global_options.format in (TEXINFO, LATEX):
1844 ## prevent PDF from being switched on by default.
1845 global_options.process_cmd += ' --formats=eps '
1846 if global_options.create_pdf:
1847 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1849 if global_options.verbose:
1850 global_options.process_cmd += " --verbose "
1852 if global_options.padding_mm:
1853 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1855 global_options.process_cmd += " -dread-file-list "
1860 chunks = do_file (file)
1861 if global_options.psfonts:
1862 fontextract.verbose = global_options.verbose
1863 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1867 psfonts_file = basename + '.psfonts'
1868 if not global_options.verbose:
1869 progress (_ ("Writing fonts to %s...") % psfonts_file)
1870 fontextract.extract_fonts (psfonts_file,
1871 [x.basename() + '.eps'
1872 for x in snippet_chunks])
1873 if not global_options.verbose:
1876 except Compile_error:
1879 psfonts_warning (global_options, basename)
1881 inputs = note_input_file ('')
1884 base_file_name = os.path.splitext (os.path.basename (file))[0]
1885 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1886 final_output_file = os.path.join (global_options.output_name,
1888 + '.%s' % global_options.format)
1890 os.chdir (original_dir)
1891 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1893 if __name__ == '__main__':