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 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.")))
109 def get_option_parser ():
110 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
111 version="@TOPLEVEL_VERSION@",
112 description=help_summary)
114 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
117 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 ("-I", '--include', help=_ ("add DIR to include path"),
125 action='append', dest='include_path',
126 default=[os.path.abspath (os.getcwd ())])
128 p.add_option ('--left-padding',
131 help="Pad left side of music to align music inspite of uneven bar numbers. (in mm)",
135 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
137 action='store', dest='output_name',
140 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
141 help = _ ("process ly_files using COMMAND FILE..."),
143 dest='process_cmd', default='lilypond -dbackend=eps')
144 p.add_option ('--pdf',
147 help=_ ("Create PDF files for use with PDFTeX"),
149 p.add_option ('', '--psfonts', action="store_true", dest="psfonts",
150 help=_ ('''extract all PostScript fonts into INPUT.psfonts for LaTeX
151 must use this with dvips -h INPUT.psfonts'''),
153 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
157 p.add_option ('-w', '--warranty',
158 help=_ ("show warranty and copyright"),
160 p.add_option_group ('bugs',
161 description=(_ ("Report bugs via")
162 + ''' http://post.gmane.org/post.php'''
163 '''?group=gmane.comp.gnu.lilypond.bugs\n'''))
166 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
168 # Only use installed binary when we are installed too.
169 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
170 lilypond_binary = 'lilypond'
172 global_options = None
175 default_ly_options = { 'alt': "[image of music]" }
178 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
183 EXAMPLEINDENT = 'exampleindent'
185 FRAGMENT = 'fragment'
190 LINE_WIDTH = 'line-width'
191 NOFRAGMENT = 'nofragment'
192 NOINDENT = 'noindent'
197 OUTPUTIMAGE = 'outputimage'
200 PREAMBLE = 'preamble'
201 PRINTFILENAME = 'printfilename'
203 RAGGED_RIGHT = 'ragged-right'
204 RELATIVE = 'relative'
205 STAFFSIZE = 'staffsize'
208 VERBATIM = 'verbatim'
209 FONTLOAD = 'fontload'
210 FILENAME = 'filename'
214 # NOTIME has no opposite so it isn't part of this dictionary.
215 # NOQUOTE is used internally only.
217 NOFRAGMENT: FRAGMENT,
222 # Recognize special sequences in the input.
224 # (?P<name>regex) -- Assign result of REGEX to NAME.
225 # *? -- Match non-greedily.
226 # (?m) -- Multiline regex: Make ^ and $ match at each line.
227 # (?s) -- Make the dot match all characters including newline.
228 # (?x) -- Ignore whitespace in patterns.
239 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
244 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
249 <(?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>)''',
258 (?P<code><!--\s.*?!-->)
261 'singleline_comment':
279 (\s*(?P<options>.*?)\s*:)?\s*
287 \s*(?P<options>.*?)\s*
296 \s*(?P<options>.*?)\s*
298 \s*(?P<filename>.*?)\s*
302 r'''(?mx)(?P<match><lilypond-version>)''',
308 (?P<code><!--\s.*?!-->)
311 'singleline_comment':
317 (?P<code><pre>.*?</pre>))''',
323 (?P<code><pre>\s.*?</pre>\s))''',
342 \s*(?P<options>.*?)\s*
353 \s*(?P<options>.*?)\s*
357 \\end\s*{lilypond})''',
365 \s*(?P<options>.*?)\s*
371 r'''(?P<match>\\lilypond_version)''',
376 'singleline_comment':
399 \\end\s*{verbatim}))''',
408 (?P<filename>\S+))''',
412 ^[^\n]*?(?!@c\s+)[^\n]*?
416 \s*(?P<options>.*?)\s*
426 \s*(?P<options>.*?)\s*
429 ^@end\s+lilypond)\s''',
436 \s*(?P<options>.*?)\s*
442 r'''(?mx)(?P<match>@lilypondversion)''',
450 @end\s+ignore))\s''',
452 'singleline_comment':
457 @c([ \t][^\n]*|)\n))''',
459 # Don't do this: It interferes with @code{@{}.
460 # 'verb': r'''(?P<code>@code{.*?})''',
468 @end\s+example\s))''',
477 'intertext': r',?\s*intertext=\".*?\"',
481 'intertext': r',?\s*intertext=\".*?\"',
486 'intertext': r',?\s*intertext=\".*?\"',
487 'option_sep': '\s*,\s*',
491 'intertext': r',?\s*intertext=\".*?\"',
492 'option_sep': '\s*,\s*',
496 # Options without a pattern in ly_options.
513 RELATIVE: r'''\relative c%(relative_quotes)s''',
518 INDENT: r'''indent = %(indent)s''',
520 LINE_WIDTH: r'''line-width = %(line-width)s''',
522 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
524 RAGGED_RIGHT: r'''ragged-right = ##t''',
526 PACKED: r'''packed = ##t''',
538 \remove Time_signature_engraver
544 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
551 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
554 <imageobject role="latex">
555 <imagedata fileref="%(base)s.pdf" format="PDF"/>
557 <imageobject role="html">
558 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
560 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
562 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
566 FILTER: r'''<lilypond %(options)s>
576 <a href="%(base)s.ly">''',
579 <img align="center" valign="center"
580 border="0" src="%(image)s" alt="%(alt)s">''',
582 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
584 QUOTE: r'''<blockquote>
597 \ifx\preLilyPondExample \undefined%%
600 \preLilyPondExample%%
602 \def\lilypondbook{}%%
603 \input %(base)s-systems.tex%%
604 \ifx\postLilyPondExample \undefined%%
607 \postLilyPondExample%%
611 PRINTFILENAME: '''\\texttt{%(filename)s}
614 QUOTE: r'''\begin{quotation}%(str)s
617 VERBATIM: r'''\noindent
618 \begin{verbatim}%(verb)s\end{verbatim}''',
620 FILTER: r'''\begin{lilypond}[%(options)s]
627 FILTER: r'''@lilypond[%(options)s]
633 @include %(base)s-systems.texi
637 OUTPUTIMAGE: r'''@noindent
639 @image{%(base)s,,,%(alt)s,%(ext)s}
643 <a href="%(base)s.ly">
644 <img align="center" valign="center"
645 border="0" src="%(image)s" alt="%(alt)s">
653 <a href="%(base)s.ly">
661 QUOTE: r'''@quotation
662 %(str)s@end quotation
669 VERBATIM: r'''@exampleindent 0
671 %(verb)s@end verbatim
677 # Maintain line numbers.
682 for f in [HTML, LATEX]:
683 for s in (QUOTE, VERBATIM):
684 output[f][s] = output[f][s].replace("\n"," ")
687 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
688 %%%% Options: [%(option_string)s]
689 \\include "lilypond-book-preamble.ly"
692 %% ****************************************************************
693 %% Start cut-&-pastable-section
694 %% ****************************************************************
699 #(define dump-extents #t)
700 %(font_dump_setting)s
702 force-assignment = #""
703 line-width = #(- line-width (* mm %(padding_mm)f))
716 %% ****************************************************************
717 %% ly snippet contents follows:
718 %% ****************************************************************
722 %% ****************************************************************
724 %% ****************************************************************
731 %% ****************************************************************
733 %% ****************************************************************
737 %% ****************************************************************
739 %% ****************************************************************
742 texinfo_line_widths = {
743 '@afourpaper': '160\\mm',
744 '@afourwide': '6.5\\in',
745 '@afourlatex': '150\\mm',
746 '@smallbook': '5\\in',
747 '@letterpaper': '6\\in',
750 def classic_lilypond_book_compatibility (key, value):
751 if key == 'singleline' and value == None:
752 return (RAGGED_RIGHT, None)
754 m = re.search ('relative\s*([-0-9])', key)
756 return ('relative', m.group (1))
758 m = re.match ('([0-9]+)pt', key)
760 return ('staffsize', m.group (1))
762 if key == 'indent' or key == 'line-width':
763 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
765 f = float (m.group (1))
766 return (key, '%f\\%s' % (f, m.group (2)))
770 def find_file (name):
771 for i in global_options.include_path:
772 full = os.path.join (i, name)
773 if os.path.exists (full):
776 error (_ ("file not found: %s") % name + '\n')
780 def verbatim_html (s):
781 return re.sub ('>', '>',
783 re.sub ('&', '&', s)))
785 def split_options (option_string):
787 if global_options.format == HTML:
788 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
789 for i in range(len(options)):
790 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
793 return re.split (format_res[global_options.format]['option_sep'],
797 def set_default_options (source):
798 global default_ly_options
799 if not default_ly_options.has_key (LINE_WIDTH):
800 if global_options.format == LATEX:
801 textwidth = get_latex_textwidth (source)
802 default_ly_options[LINE_WIDTH] = \
803 '''%.0f\\pt''' % textwidth
804 elif global_options.format == TEXINFO:
805 for (k, v) in texinfo_line_widths.items ():
806 # FIXME: @layout is usually not in
809 # \input texinfo @c -*-texinfo-*-
811 # Bluntly search first K items of
813 # s = chunks[0].replacement_text ()
814 if re.search (k, source[:1024]):
815 default_ly_options[LINE_WIDTH] = v
819 def replacement_text (self):
822 def filter_text (self):
823 return self.replacement_text ()
825 def ly_is_outdated (self):
828 def png_is_outdated (self):
834 class Substring (Chunk):
835 def __init__ (self, source, start, end, line_number):
839 self.line_number = line_number
840 self.override_text = None
845 def replacement_text (self):
846 if self.override_text:
847 return self.override_text
849 return self.source[self.start:self.end]
851 class Snippet (Chunk):
852 def __init__ (self, type, match, format, line_number):
856 self.option_dict = {}
858 self.line_number = line_number
860 def replacement_text (self):
861 return self.match.group ('match')
863 def substring (self, s):
864 return self.match.group (s)
867 return `self.__class__` + ' type = ' + self.type
869 class Include_snippet (Snippet):
870 def processed_filename (self):
871 f = self.substring ('filename')
872 return os.path.splitext (f)[0] + format2ext[global_options.format]
874 def replacement_text (self):
875 s = self.match.group ('match')
876 f = self.substring ('filename')
878 return re.sub (f, self.processed_filename (), s)
880 class Lilypond_snippet (Snippet):
881 def __init__ (self, type, match, format, line_number):
882 Snippet.__init__ (self, type, match, format, line_number)
883 os = match.group ('options')
884 self.do_options (os, self.type)
887 contents = self.substring ('code')
888 return ('\\sourcefileline %d\n%s'
889 % (self.line_number - 1, contents))
894 return self.compose_ly (s)
897 def do_options (self, option_string, type):
898 self.option_dict = {}
900 options = split_options (option_string)
904 (key, value) = re.split ('\s*=\s*', i)
905 self.option_dict[key] = value
907 if i in no_options.keys ():
908 if no_options[i] in self.option_dict.keys ():
909 del self.option_dict[no_options[i]]
911 self.option_dict[i] = None
913 has_line_width = self.option_dict.has_key (LINE_WIDTH)
914 no_line_width_value = 0
916 # If LINE_WIDTH is used without parameter, set it to default.
917 if has_line_width and self.option_dict[LINE_WIDTH] == None:
918 no_line_width_value = 1
919 del self.option_dict[LINE_WIDTH]
921 for i in default_ly_options.keys ():
922 if i not in self.option_dict.keys ():
923 self.option_dict[i] = default_ly_options[i]
925 if not has_line_width:
926 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
927 self.option_dict[RAGGED_RIGHT] = None
929 if type == 'lilypond':
930 if LINE_WIDTH in self.option_dict.keys ():
931 del self.option_dict[LINE_WIDTH]
933 if RAGGED_RIGHT in self.option_dict.keys ():
934 if LINE_WIDTH in self.option_dict.keys ():
935 del self.option_dict[LINE_WIDTH]
937 if QUOTE in self.option_dict.keys () or type == 'lilypond':
938 if LINE_WIDTH in self.option_dict.keys ():
939 del self.option_dict[LINE_WIDTH]
941 if not INDENT in self.option_dict.keys ():
942 self.option_dict[INDENT] = '0\\mm'
944 # The QUOTE pattern from ly_options only emits the `line-width'
946 if has_line_width and QUOTE in self.option_dict.keys ():
947 if no_line_width_value:
948 del self.option_dict[LINE_WIDTH]
950 del self.option_dict[QUOTE]
952 def compose_ly (self, code):
953 if FRAGMENT in self.option_dict.keys ():
961 # The original concept of the `exampleindent' option is broken.
962 # It is not possible to get a sane value for @exampleindent at all
963 # without processing the document itself. Saying
971 # causes ugly results with the DVI backend of texinfo since the
972 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
973 # value). Executing the above code changes the environment
974 # indentation to an unknown value because we don't know the amount
975 # of 1em in advance since it is font-dependent. Modifying
976 # @exampleindent in the middle of a document is simply not
977 # supported within texinfo.
979 # As a consequence, the only function of @exampleindent is now to
980 # specify the amount of indentation for the `quote' option.
982 # To set @exampleindent locally to zero, we use the @format
983 # environment for non-quoted snippets.
984 override[EXAMPLEINDENT] = r'0.4\in'
985 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
986 override.update (default_ly_options)
989 for (key, value) in self.option_dict.items ():
991 option_list.append (key)
993 option_list.append (key + '=' + value)
994 option_string = string.join (option_list, ',')
997 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
998 for a in compose_types:
1001 for (key, value) in self.option_dict.items ():
1002 (c_key, c_value) = \
1003 classic_lilypond_book_compatibility (key, value)
1007 (_ ("deprecated ly-option used: %s=%s" \
1010 (_ ("compatibility mode translation: %s=%s" \
1011 % (c_key, c_value)))
1014 (_ ("deprecated ly-option used: %s" \
1017 (_ ("compatibility mode translation: %s" \
1020 (key, value) = (c_key, c_value)
1023 override[key] = value
1025 if not override.has_key (key):
1026 override[key] = None
1029 for type in compose_types:
1030 if ly_options[type].has_key (key):
1031 compose_dict[type].append (ly_options[type][key])
1035 if not found and key not in simple_options:
1036 warning (_ ("ignoring unknown ly option: %s") % key)
1039 if RELATIVE in override.keys () and override[RELATIVE]:
1040 relative = int (override[RELATIVE])
1042 relative_quotes = ''
1046 relative_quotes += ',' * (- relative)
1048 relative_quotes += "'" * relative
1050 paper_string = string.join (compose_dict[PAPER],
1052 layout_string = string.join (compose_dict[LAYOUT],
1054 notes_string = string.join (compose_dict[NOTES],
1056 preamble_string = string.join (compose_dict[PREAMBLE],
1058 padding_mm = global_options.padding_mm
1059 font_dump_setting = ''
1060 if FONTLOAD in self.option_dict:
1061 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1063 d = globals().copy()
1065 return (PREAMBLE_LY + body) % d
1067 def get_hash (self):
1069 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1071 ## let's not create too long names.
1072 self.hash = hash.hexdigest ()[:10]
1076 def basename (self):
1077 if FILENAME in self.option_dict:
1078 return self.option_dict[FILENAME]
1079 if global_options.use_hash:
1080 return 'lily-%s' % self.get_hash ()
1083 def write_ly (self):
1084 outf = open (self.basename () + '.ly', 'w')
1085 outf.write (self.full_ly ())
1086 open (self.basename () + '.txt', 'w').write ('image of music')
1088 def relevant_contents (self, ly):
1089 return re.sub (r'\\(version|sourcefileline)[^\n]*\n', '', ly)
1091 def ly_is_outdated (self):
1092 base = self.basename ()
1093 ly_file = base + '.ly'
1094 tex_file = base + '.tex'
1095 eps_file = base + '.eps'
1096 systems_file = base + '-systems.tex'
1098 if (os.path.exists (ly_file)
1099 and os.path.exists (systems_file)
1100 and os.stat (systems_file)[stat.ST_SIZE]
1101 and re.match ('% eof', open (systems_file).readlines ()[-1])
1102 and (global_options.use_hash or FILENAME in self.option_dict)
1103 and (self.relevant_contents (self.full_ly ())
1104 == self.relevant_contents (open (ly_file).read ()))):
1109 def png_is_outdated (self):
1110 base = self.basename ()
1111 # FIXME: refactor stupid OK stuff
1112 ok = not self.ly_is_outdated ()
1113 if global_options.format in (HTML, TEXINFO):
1114 ok = ok and os.path.exists (base + '.eps')
1118 page_count = ps_page_count (base + '.eps')
1121 ok = ok and os.path.exists (base + '.png')
1123 elif page_count > 1:
1124 for a in range (1, page_count + 1):
1125 ok = ok and os.path.exists (base + '-page%d.png' % a)
1129 def texstr_is_outdated (self):
1133 # FIXME: refactor stupid OK stuff
1134 base = self.basename ()
1135 ok = self.ly_is_outdated ()
1136 ok = ok and (os.path.exists (base + '.texstr'))
1139 def filter_text (self):
1140 code = self.substring ('code')
1141 s = run_filter (code)
1144 'options': self.match.group ('options')
1147 return output[self.format][FILTER] % d
1149 def replacement_text (self):
1150 func = Lilypond_snippet.__dict__['output_' + self.format]
1153 def get_images (self):
1154 base = self.basename ()
1156 single = '%(base)s.png' % vars ()
1157 multiple = '%(base)s-page1.png' % vars ()
1159 if os.path.exists (multiple) \
1160 and (not os.path.exists (single) \
1161 or (os.stat (multiple)[stat.ST_MTIME] \
1162 > os.stat (single)[stat.ST_MTIME])):
1163 count = ps_page_count ('%(base)s.eps' % vars ())
1164 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1165 images = tuple (images)
1168 def output_docbook (self):
1170 base = self.basename ()
1171 for image in self.get_images ():
1172 (base, ext) = os.path.splitext (image)
1173 str += output[DOCBOOK][OUTPUT] % vars ()
1174 str += self.output_print_filename (DOCBOOK)
1175 if (self.substring('inline') == 'inline'):
1176 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1178 str = '<mediaobject>' + str + '</mediaobject>'
1179 if VERBATIM in self.option_dict:
1180 verb = verbatim_html (self.substring ('code'))
1181 str = output[DOCBOOK][VERBATIM] % vars () + str
1184 def output_html (self):
1186 base = self.basename ()
1187 if global_options.format == HTML:
1188 str += self.output_print_filename (HTML)
1189 if VERBATIM in self.option_dict:
1190 verb = verbatim_html (self.substring ('code'))
1191 str += output[HTML][VERBATIM] % vars ()
1192 if QUOTE in self.option_dict:
1193 str = output[HTML][QUOTE] % vars ()
1195 str += output[HTML][BEFORE] % vars ()
1196 for image in self.get_images ():
1197 (base, ext) = os.path.splitext (image)
1198 alt = self.option_dict[ALT]
1199 str += output[HTML][OUTPUT] % vars ()
1200 str += output[HTML][AFTER] % vars ()
1203 def output_info (self):
1205 for image in self.get_images ():
1206 (base, ext) = os.path.splitext (image)
1208 # URG, makeinfo implicitly prepends dot to extension.
1209 # Specifying no extension is most robust.
1211 alt = self.option_dict[ALT]
1212 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1214 base = self.basename ()
1215 str += output[global_options.format][OUTPUT] % vars ()
1218 def output_latex (self):
1220 base = self.basename ()
1221 if global_options.format == LATEX:
1222 str += self.output_print_filename (LATEX)
1223 if VERBATIM in self.option_dict:
1224 verb = self.substring ('code')
1225 str += (output[LATEX][VERBATIM] % vars ())
1227 str += (output[LATEX][OUTPUT] % vars ())
1229 ## todo: maintain breaks
1231 breaks = self.ly ().count ("\n")
1232 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1234 if QUOTE in self.option_dict:
1235 str = output[LATEX][QUOTE] % vars ()
1238 def output_print_filename (self, format):
1240 if PRINTFILENAME in self.option_dict:
1241 base = self.basename ()
1242 filename = self.substring ('filename')
1243 str = output[global_options.format][PRINTFILENAME] % vars ()
1247 def output_texinfo (self):
1249 if self.output_print_filename (TEXINFO):
1251 + self.output_print_filename (HTML)
1254 + self.output_print_filename (LATEX)
1256 base = self.basename ()
1257 if TEXIDOC in self.option_dict:
1258 texidoc = base + '.texidoc'
1259 if os.path.exists (texidoc):
1260 str += '@include %(texidoc)s\n\n' % vars ()
1262 if VERBATIM in self.option_dict:
1263 verb = self.substring ('code')
1264 str += (output[TEXINFO][VERBATIM] % vars ())
1265 if not QUOTE in self.option_dict:
1266 str = output[TEXINFO][NOQUOTE] % vars ()
1268 str += self.output_info ()
1270 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1271 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1272 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1274 if QUOTE in self.option_dict:
1275 str = output[TEXINFO][QUOTE] % vars ()
1277 # need par after image
1282 class Lilypond_file_snippet (Lilypond_snippet):
1284 name = self.substring ('filename')
1285 contents = open (find_file (name)).read ()
1286 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1289 class Version_snippet (Snippet):
1290 def replacement_text (self):
1291 return (program_version)
1293 snippet_type_to_class = {
1294 'lilypond_file': Lilypond_file_snippet,
1295 'lilypond_block': Lilypond_snippet,
1296 'lilypond_version': Version_snippet,
1297 'lilypond': Lilypond_snippet,
1298 'include': Include_snippet,
1301 def find_linestarts (s):
1306 i = s.find ('\n', start)
1314 nls.append (len (s))
1317 def find_toplevel_snippets (s, types):
1320 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1324 found = dict ([(t, None) for t in types])
1326 line_starts = find_linestarts (s)
1328 # We want to search for multiple regexes, without searching
1329 # the string multiple times for one regex.
1330 # Hence, we use earlier results to limit the string portion
1332 # Since every part of the string is traversed at most once for
1333 # every type of snippet, this is linear.
1339 if not found[type] or found[type][0] < index:
1342 m = res[type].search (s[index:endex])
1347 if snippet_type_to_class.has_key (type):
1348 cl = snippet_type_to_class[type]
1351 start = index + m.start ('match')
1352 line_number = line_start_idx
1353 while (line_starts[line_number] < start):
1357 snip = cl (type, m, global_options.format, line_number)
1359 found[type] = (start, snip)
1363 or found[type][0] < found[first][0]):
1368 # Limiting the search space is a cute
1369 # idea, but this *requires* to search
1370 # for possible containing blocks
1371 # first, at least as long as we do not
1372 # search for the start of blocks, but
1373 # always/directly for the entire
1374 # @block ... @end block.
1376 endex = found[first][0]
1379 snippets.append (Substring (s, index, len (s), line_start_idx))
1382 while (start > line_starts[line_start_idx+1]):
1385 (start, snip) = found[first]
1386 snippets.append (Substring (s, index, start, line_start_idx + 1))
1387 snippets.append (snip)
1389 index = start + len (snip.match.group ('match'))
1393 def filter_pipe (input, cmd):
1394 if global_options.verbose:
1395 progress (_ ("Opening filter `%s'") % cmd)
1397 (stdin, stdout, stderr) = os.popen3 (cmd)
1399 status = stdin.close ()
1403 output = stdout.read ()
1404 status = stdout.close ()
1405 error = stderr.read ()
1409 signal = 0x0f & status
1410 if status or (not output and error):
1411 exit_status = status >> 8
1412 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1413 error (_ ("The error log is as follows:"))
1414 sys.stderr.write (error)
1415 sys.stderr.write (stderr.read ())
1418 if global_options.verbose:
1424 return filter_pipe (s, global_options.filter_cmd)
1426 def is_derived_class (cl, baseclass):
1429 for b in cl.__bases__:
1430 if is_derived_class (b, baseclass):
1434 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1435 ly_names = filter (lambda x: x,
1436 map (Lilypond_snippet.basename, ly_snippets))
1437 texstr_names = filter (lambda x: x,
1438 map (Lilypond_snippet.basename, texstr_snippets))
1440 png_names = filter (lambda x: x,
1441 map (Lilypond_snippet.basename, png_snippets))
1444 def my_system (cmd):
1445 status = ly.system (cmd,
1446 be_verbose=global_options.verbose,
1449 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1450 cmd += ' --formats=png '
1451 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1452 cmd += ' --formats=png,pdf '
1456 # the --process=CMD switch is a bad idea
1457 # it is too generic for lilypond-book.
1459 my_system (string.join ([cmd, '--backend texstr',
1460 'snippet-map.ly'] + texstr_names))
1461 for l in texstr_names:
1462 my_system ('latex %s.texstr' % l)
1465 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1468 my_system (string.join ([cmd, 'snippet-names']))
1471 LATEX_INSPECTION_DOCUMENT = r'''
1475 \typeout{textwidth=\the\textwidth}
1476 \typeout{columnsep=\the\columnsep}
1477 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1481 # Do we need anything else besides `textwidth'?
1482 def get_latex_textwidth (source):
1483 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1485 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1487 ## what's a sensible default?
1490 preamble = source[:m.start (0)]
1491 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1493 (handle, tmpfile) = tempfile.mkstemp('.tex')
1494 logfile = os.path.splitext (tmpfile)[0] + '.log'
1495 logfile = os.path.split (logfile)[1]
1497 tmp_handle = os.fdopen (handle,'w')
1498 tmp_handle.write (latex_document)
1501 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1502 parameter_string = open (logfile).read()
1508 m = re.search ('columns=([0-9.]*)', parameter_string)
1510 columns = int (m.group (1))
1513 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1515 columnsep = float (m.group (1))
1518 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1520 textwidth = float (m.group (1))
1522 textwidth = (textwidth - columnsep) / columns
1526 def modify_preamble (chunk):
1527 str = chunk.replacement_text ()
1528 if (re.search (r"\\begin *{document}", str)
1529 and not re.search ("{graphic[sx]", str)):
1530 str = re.sub (r"\\begin{document}",
1531 r"\\usepackage{graphics}" + '\n'
1532 + r"\\begin{document}",
1534 chunk.override_text = str
1546 '.texinfo': TEXINFO,
1553 # TEXINFO: '.texinfo',
1559 class Compile_error:
1562 def write_file_map (lys, name):
1563 snippet_map = open ('snippet-map.ly', 'w')
1564 snippet_map.write ("""
1565 #(define version-seen #t)
1566 #(define output-empty-score-list #f)
1567 #(ly:add-file-name-alist '(
1570 snippet_map.write ('("%s.ly" . "%s")\n'
1574 snippet_map.write ('))\n')
1576 def do_process_cmd (chunks, input_name):
1577 all_lys = filter (lambda x: is_derived_class (x.__class__,
1581 write_file_map (all_lys, input_name)
1582 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1584 and x.ly_is_outdated (), chunks)
1585 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1587 and x.texstr_is_outdated (),
1589 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1591 and x.png_is_outdated (),
1594 outdated = png_outdated + texstr_outdated + ly_outdated
1596 progress (_ ("Writing snippets..."))
1597 map (Lilypond_snippet.write_ly, ly_outdated)
1601 progress (_ ("Processing..."))
1603 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1605 progress (_ ("All snippets are up to date..."))
1608 def guess_format (input_filename):
1610 e = os.path.splitext (input_filename)[1]
1611 if e in ext2format.keys ():
1613 format = ext2format[e]
1615 error (_ ("cannot determine format for: %s" \
1620 def write_if_updated (file_name, lines):
1622 f = open (file_name)
1624 new_str = string.join (lines, '')
1625 if oldstr == new_str:
1626 progress (_ ("%s is up to date.") % file_name)
1632 progress (_ ("Writing `%s'...") % file_name)
1633 open (file_name, 'w').writelines (lines)
1636 def note_input_file (name, inputs=[]):
1637 ## hack: inputs is mutable!
1638 inputs.append (name)
1641 def samefile (f1, f2):
1643 return os.path.samefile (f1, f2)
1644 except AttributeError: # Windoze
1645 f1 = re.sub ("//*", "/", f1)
1646 f2 = re.sub ("//*", "/", f2)
1649 def do_file (input_filename):
1651 if not input_filename or input_filename == '-':
1652 in_handle = sys.stdin
1653 input_fullname = '<stdin>'
1655 if os.path.exists (input_filename):
1656 input_fullname = input_filename
1657 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1658 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1660 input_fullname = find_file (input_filename)
1662 note_input_file (input_fullname)
1663 in_handle = open (input_fullname)
1665 if input_filename == '-':
1666 input_base = 'stdin'
1668 input_base = os.path.basename \
1669 (os.path.splitext (input_filename)[0])
1671 # Only default to stdout when filtering.
1672 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1673 output_filename = '-'
1674 output_file = sys.stdout
1676 # don't complain when global_options.output_name is existing
1677 output_filename = input_base + format2ext[global_options.format]
1678 if global_options.output_name:
1679 if not os.path.isdir (global_options.output_name):
1680 os.mkdir (global_options.output_name, 0777)
1681 os.chdir (global_options.output_name)
1683 if (os.path.exists (input_filename)
1684 and os.path.exists (output_filename)
1685 and samefile (output_filename, input_fullname)):
1687 _ ("Output would overwrite input file; use --output."))
1691 progress (_ ("Reading %s...") % input_fullname)
1692 source = in_handle.read ()
1695 set_default_options (source)
1698 # FIXME: Containing blocks must be first, see
1699 # find_toplevel_snippets.
1701 'multiline_comment',
1705 'singleline_comment',
1711 progress (_ ("Dissecting..."))
1712 chunks = find_toplevel_snippets (source, snippet_types)
1714 if global_options.format == LATEX:
1716 if (c.is_plain () and
1717 re.search (r"\\begin *{document}", c.replacement_text())):
1722 if global_options.filter_cmd:
1723 write_if_updated (output_filename,
1724 [c.filter_text () for c in chunks])
1725 elif global_options.process_cmd:
1726 do_process_cmd (chunks, input_fullname)
1727 progress (_ ("Compiling %s...") % output_filename)
1729 write_if_updated (output_filename,
1730 [s.replacement_text ()
1733 def process_include (snippet):
1734 os.chdir (original_dir)
1735 name = snippet.substring ('filename')
1736 progress (_ ("Processing include: %s") % name)
1738 return do_file (name)
1740 include_chunks = map (process_include,
1741 filter (lambda x: is_derived_class (x.__class__,
1746 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1748 except Compile_error:
1749 os.chdir (original_dir)
1750 progress (_ ("Removing `%s'") % output_filename)
1756 global global_options
1758 opt_parser = get_option_parser()
1759 (global_options, args) = opt_parser.parse_args ()
1761 if global_options.format in ('texi-html', 'texi'):
1762 global_options.format = TEXINFO
1763 global_options.use_hash = True
1765 global_options.include_path = map (os.path.abspath, global_options.include_path)
1767 if global_options.warranty:
1770 if not args or len (args) > 1:
1771 opt_parser.print_help ()
1776 def psfonts_warning (options, basename):
1777 if options.format in (TEXINFO, LATEX):
1778 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1779 output = os.path.join (options.output_name, basename + '.dvi' )
1781 if not options.create_pdf:
1782 if not options.psfonts:
1783 warning (_ ("option --psfonts not used"))
1784 warning (_ ("processing with dvips will have no fonts"))
1787 progress (_ ("DVIPS usage:"))
1789 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1793 # FIXME: 85 lines of `main' macramee??
1794 files = do_options ()
1798 basename = os.path.splitext (file)[0]
1799 basename = os.path.split (basename)[1]
1801 if not global_options.format:
1802 global_options.format = guess_format (files[0])
1805 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1809 if global_options.process_cmd == '':
1810 global_options.process_cmd = (lilypond_binary
1811 + ' --formats=%s --backend eps ' % formats)
1813 if global_options.process_cmd:
1814 global_options.process_cmd += string.join ([(' -I %s' % ly.mkarg (p))
1815 for p in global_options.include_path])
1817 if global_options.format in (TEXINFO, LATEX):
1818 ## prevent PDF from being switched on by default.
1819 global_options.process_cmd += ' --formats=eps '
1820 if global_options.create_pdf:
1821 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1823 if global_options.verbose:
1824 global_options.process_cmd += " --verbose "
1826 if global_options.padding_mm:
1827 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1829 global_options.process_cmd += " -dread-file-list "
1834 chunks = do_file (file)
1835 if global_options.psfonts:
1836 fontextract.verbose = global_options.verbose
1837 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1841 psfonts_file = basename + '.psfonts'
1842 if not global_options.verbose:
1843 progress (_ ("Writing fonts to %s...") % psfonts_file)
1844 fontextract.extract_fonts (psfonts_file,
1845 [x.basename() + '.eps'
1846 for x in snippet_chunks])
1847 if not global_options.verbose:
1850 except Compile_error:
1853 psfonts_warning (global_options, basename)
1855 inputs = note_input_file ('')
1858 base_file_name = os.path.splitext (os.path.basename (file))[0]
1859 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1860 final_output_file = os.path.join (global_options.output_name,
1862 + '.%s' % global_options.format)
1864 os.chdir (original_dir)
1865 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1867 if __name__ == '__main__':