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
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, raise_error=True):
783 for i in global_options.include_path:
784 full = os.path.join (i, name)
785 if os.path.exists (full):
789 error (_ ("file not found: %s") % name + '\n')
793 def verbatim_html (s):
794 return re.sub ('>', '>',
796 re.sub ('&', '&', s)))
798 def split_options (option_string):
800 if global_options.format == HTML:
801 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',option_string)
802 for i in range(len(options)):
803 options[i] = re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)','\g<1>\g<3>',options[i])
806 return re.split (format_res[global_options.format]['option_sep'],
810 def set_default_options (source):
811 global default_ly_options
812 if not default_ly_options.has_key (LINE_WIDTH):
813 if global_options.format == LATEX:
814 textwidth = get_latex_textwidth (source)
815 default_ly_options[LINE_WIDTH] = \
816 '''%.0f\\pt''' % textwidth
817 elif global_options.format == TEXINFO:
818 for (k, v) in texinfo_line_widths.items ():
819 # FIXME: @layout is usually not in
822 # \input texinfo @c -*-texinfo-*-
824 # Bluntly search first K items of
826 # s = chunks[0].replacement_text ()
827 if re.search (k, source[:1024]):
828 default_ly_options[LINE_WIDTH] = v
832 def replacement_text (self):
835 def filter_text (self):
836 return self.replacement_text ()
838 def ly_is_outdated (self):
841 def png_is_outdated (self):
847 class Substring (Chunk):
848 def __init__ (self, source, start, end, line_number):
852 self.line_number = line_number
853 self.override_text = None
858 def replacement_text (self):
859 if self.override_text:
860 return self.override_text
862 return self.source[self.start:self.end]
864 class Snippet (Chunk):
865 def __init__ (self, type, match, format, line_number):
869 self.option_dict = {}
871 self.line_number = line_number
873 def replacement_text (self):
874 return self.match.group ('match')
876 def substring (self, s):
877 return self.match.group (s)
880 return `self.__class__` + ' type = ' + self.type
882 class Include_snippet (Snippet):
883 def processed_filename (self):
884 f = self.substring ('filename')
885 return os.path.splitext (f)[0] + format2ext[global_options.format]
887 def replacement_text (self):
888 s = self.match.group ('match')
889 f = self.substring ('filename')
891 return re.sub (f, self.processed_filename (), s)
893 class Lilypond_snippet (Snippet):
894 def __init__ (self, type, match, format, line_number):
895 Snippet.__init__ (self, type, match, format, line_number)
896 os = match.group ('options')
897 self.do_options (os, self.type)
900 return self.substring ('code')
903 contents = self.substring ('code')
904 return ('\\sourcefileline %d\n%s'
905 % (self.line_number - 1, contents))
910 return self.compose_ly (s)
913 def do_options (self, option_string, type):
914 self.option_dict = {}
916 options = split_options (option_string)
920 (key, value) = re.split ('\s*=\s*', i)
921 self.option_dict[key] = value
923 if i in no_options.keys ():
924 if no_options[i] in self.option_dict.keys ():
925 del self.option_dict[no_options[i]]
927 self.option_dict[i] = None
929 has_line_width = self.option_dict.has_key (LINE_WIDTH)
930 no_line_width_value = 0
932 # If LINE_WIDTH is used without parameter, set it to default.
933 if has_line_width and self.option_dict[LINE_WIDTH] == None:
934 no_line_width_value = 1
935 del self.option_dict[LINE_WIDTH]
937 for i in default_ly_options.keys ():
938 if i not in self.option_dict.keys ():
939 self.option_dict[i] = default_ly_options[i]
941 if not has_line_width:
942 if type == 'lilypond' or FRAGMENT in self.option_dict.keys ():
943 self.option_dict[RAGGED_RIGHT] = None
945 if type == 'lilypond':
946 if LINE_WIDTH in self.option_dict.keys ():
947 del self.option_dict[LINE_WIDTH]
949 if RAGGED_RIGHT in self.option_dict.keys ():
950 if LINE_WIDTH in self.option_dict.keys ():
951 del self.option_dict[LINE_WIDTH]
953 if QUOTE in self.option_dict.keys () or type == 'lilypond':
954 if LINE_WIDTH in self.option_dict.keys ():
955 del self.option_dict[LINE_WIDTH]
957 if not INDENT in self.option_dict.keys ():
958 self.option_dict[INDENT] = '0\\mm'
960 # The QUOTE pattern from ly_options only emits the `line-width'
962 if has_line_width and QUOTE in self.option_dict.keys ():
963 if no_line_width_value:
964 del self.option_dict[LINE_WIDTH]
966 del self.option_dict[QUOTE]
968 def compose_ly (self, code):
969 if FRAGMENT in self.option_dict.keys ():
977 # The original concept of the `exampleindent' option is broken.
978 # It is not possible to get a sane value for @exampleindent at all
979 # without processing the document itself. Saying
987 # causes ugly results with the DVI backend of texinfo since the
988 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
989 # value). Executing the above code changes the environment
990 # indentation to an unknown value because we don't know the amount
991 # of 1em in advance since it is font-dependent. Modifying
992 # @exampleindent in the middle of a document is simply not
993 # supported within texinfo.
995 # As a consequence, the only function of @exampleindent is now to
996 # specify the amount of indentation for the `quote' option.
998 # To set @exampleindent locally to zero, we use the @format
999 # environment for non-quoted snippets.
1000 override[EXAMPLEINDENT] = r'0.4\in'
1001 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1002 override.update (default_ly_options)
1005 for (key, value) in self.option_dict.items ():
1007 option_list.append (key)
1009 option_list.append (key + '=' + value)
1010 option_string = ','.join (option_list)
1013 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1014 for a in compose_types:
1015 compose_dict[a] = []
1017 for (key, value) in self.option_dict.items ():
1018 (c_key, c_value) = \
1019 classic_lilypond_book_compatibility (key, value)
1023 (_ ("deprecated ly-option used: %s=%s" \
1026 (_ ("compatibility mode translation: %s=%s" \
1027 % (c_key, c_value)))
1030 (_ ("deprecated ly-option used: %s" \
1033 (_ ("compatibility mode translation: %s" \
1036 (key, value) = (c_key, c_value)
1039 override[key] = value
1041 if not override.has_key (key):
1042 override[key] = None
1045 for type in compose_types:
1046 if ly_options[type].has_key (key):
1047 compose_dict[type].append (ly_options[type][key])
1051 if not found and key not in simple_options:
1052 warning (_ ("ignoring unknown ly option: %s") % key)
1055 if RELATIVE in override.keys () and override[RELATIVE]:
1056 relative = int (override[RELATIVE])
1058 relative_quotes = ''
1062 relative_quotes += ',' * (- relative)
1064 relative_quotes += "'" * relative
1066 paper_string = '\n '.join (compose_dict[PAPER]) % override
1067 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1068 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1069 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1070 padding_mm = global_options.padding_mm
1071 font_dump_setting = ''
1072 if FONTLOAD in self.option_dict:
1073 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1075 d = globals().copy()
1077 return (PREAMBLE_LY + body) % d
1079 def get_hash (self):
1081 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1083 ## let's not create too long names.
1084 self.hash = hash.hexdigest ()[:10]
1088 def basename (self):
1089 if FILENAME in self.option_dict:
1090 return self.option_dict[FILENAME]
1091 if global_options.use_hash:
1092 return 'lily-%s' % self.get_hash ()
1095 def write_ly (self):
1096 outf = open (self.basename () + '.ly', 'w')
1097 outf.write (self.full_ly ())
1098 open (self.basename () + '.txt', 'w').write ('image of music')
1100 def relevant_contents (self, ly):
1101 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1103 def ly_is_outdated (self):
1104 base = self.basename ()
1105 ly_file = find_file (base + '.ly', raise_error=False)
1106 tex_file = find_file (base + '.tex', raise_error=False)
1107 systems_file = find_file (base + '-systems.tex', raise_error=False)
1109 if (os.path.exists (ly_file)
1110 and os.path.exists (systems_file)
1111 and os.stat (systems_file)[stat.ST_SIZE]
1112 and re.match ('% eof', open (systems_file).readlines ()[-1])
1113 and (global_options.use_hash or FILENAME in self.option_dict)
1114 and (self.relevant_contents (self.full_ly ())
1115 == self.relevant_contents (open (ly_file).read ()))):
1120 def png_is_outdated (self):
1121 base = self.basename ()
1122 eps_file = find_file (base + '.eps', raise_error=False)
1123 png_file = find_file (base + '.png', raise_error=False)
1124 if not self.ly_is_outdated () and global_options.format in (HTML, TEXINFO):
1125 if os.path.exists (eps_file):
1126 page_count = ps_page_count (eps_file)
1128 return not os.path.exists (png_file)
1130 return not reduce (operator.or_,
1131 [find_file (base + '-page%d.png' % a, raise_error=False)
1132 for a in range (1, page_count + 1)])
1135 def texstr_is_outdated (self):
1139 base = self.basename ()
1140 return not (self.ly_is_outdated ()
1141 and find_file (base + '.texstr', raise_error=False))
1143 def filter_text (self):
1144 code = self.substring ('code')
1145 s = run_filter (code)
1148 'options': self.match.group ('options')
1151 return output[self.format][FILTER] % d
1153 def replacement_text (self):
1154 func = Lilypond_snippet.__dict__['output_' + self.format]
1157 def get_images (self):
1158 base = self.basename ()
1160 single = '%(base)s.png' % vars ()
1161 multiple = '%(base)s-page1.png' % vars ()
1163 if os.path.exists (multiple) \
1164 and (not os.path.exists (single) \
1165 or (os.stat (multiple)[stat.ST_MTIME] \
1166 > os.stat (single)[stat.ST_MTIME])):
1167 count = ps_page_count ('%(base)s.eps' % vars ())
1168 images = ['%s-page%d.png' % (base, a) for a in range (1, count+1)]
1169 images = tuple (images)
1172 def output_docbook (self):
1174 base = self.basename ()
1175 for image in self.get_images ():
1176 (base, ext) = os.path.splitext (image)
1177 str += output[DOCBOOK][OUTPUT] % vars ()
1178 str += self.output_print_filename (DOCBOOK)
1179 if (self.substring('inline') == 'inline'):
1180 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1182 str = '<mediaobject>' + str + '</mediaobject>'
1183 if VERBATIM in self.option_dict:
1184 verb = verbatim_html (self.verb_ly ())
1185 str = output[DOCBOOK][VERBATIM] % vars () + str
1188 def output_html (self):
1190 base = self.basename ()
1191 if global_options.format == HTML:
1192 str += self.output_print_filename (HTML)
1193 if VERBATIM in self.option_dict:
1194 verb = verbatim_html (self.verb_ly ())
1195 str += output[HTML][VERBATIM] % vars ()
1196 if QUOTE in self.option_dict:
1197 str = output[HTML][QUOTE] % vars ()
1199 str += output[HTML][BEFORE] % vars ()
1200 for image in self.get_images ():
1201 (base, ext) = os.path.splitext (image)
1202 alt = self.option_dict[ALT]
1203 str += output[HTML][OUTPUT] % vars ()
1204 str += output[HTML][AFTER] % vars ()
1207 def output_info (self):
1209 for image in self.get_images ():
1210 (base, ext) = os.path.splitext (image)
1212 # URG, makeinfo implicitly prepends dot to extension.
1213 # Specifying no extension is most robust.
1215 alt = self.option_dict[ALT]
1216 info_image_path = os.path.join (global_options.info_images_dir, base)
1217 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1219 base = self.basename ()
1220 str += output[global_options.format][OUTPUT] % vars ()
1223 def output_latex (self):
1225 base = self.basename ()
1226 if global_options.format == LATEX:
1227 str += self.output_print_filename (LATEX)
1228 if VERBATIM in self.option_dict:
1229 verb = self.verb_ly ()
1230 str += (output[LATEX][VERBATIM] % vars ())
1232 str += (output[LATEX][OUTPUT] % vars ())
1234 ## todo: maintain breaks
1236 breaks = self.ly ().count ("\n")
1237 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1239 if QUOTE in self.option_dict:
1240 str = output[LATEX][QUOTE] % vars ()
1243 def output_print_filename (self, format):
1245 if PRINTFILENAME in self.option_dict:
1246 base = self.basename ()
1247 filename = os.path.basename (self.substring ('filename'))
1248 str = output[format][PRINTFILENAME] % vars ()
1252 def output_texinfo (self):
1253 str = self.output_print_filename (TEXINFO)
1254 base = self.basename ()
1255 if TEXIDOC in self.option_dict:
1256 texidoc = base + '.texidoc'
1257 if os.path.exists (texidoc):
1258 str += '@include %(texidoc)s\n\n' % vars ()
1261 if VERBATIM in self.option_dict:
1262 verb = self.verb_ly ()
1263 substr += output[TEXINFO][VERBATIM] % vars ()
1264 if not QUOTE in self.option_dict:
1265 substr = output[TEXINFO][NOQUOTE] % {'str':substr}
1266 substr += self.output_info ()
1267 if LILYQUOTE in self.option_dict:
1268 substr = output[TEXINFO][QUOTE] % {'str':substr}
1271 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1272 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1273 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1275 if QUOTE in self.option_dict:
1276 str = output[TEXINFO][QUOTE] % vars ()
1278 # need par after image
1283 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1284 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1286 class Lilypond_file_snippet (Lilypond_snippet):
1287 def __init__ (self, type, match, format, line_number):
1288 Lilypond_snippet.__init__ (self, type, match, format, line_number)
1289 self.contents = open (find_file (self.substring ('filename'))).read ()
1293 s = re_begin_verbatim.split (s)[-1]
1294 s = re_end_verbatim.split (s)[0]
1298 name = self.substring ('filename')
1299 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1300 % (name, self.contents))
1303 snippet_type_to_class = {
1304 'lilypond_file': Lilypond_file_snippet,
1305 'lilypond_block': Lilypond_snippet,
1306 'lilypond': Lilypond_snippet,
1307 'include': Include_snippet,
1310 def find_linestarts (s):
1315 i = s.find ('\n', start)
1323 nls.append (len (s))
1326 def find_toplevel_snippets (s, types):
1329 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1333 found = dict ([(t, None) for t in types])
1335 line_starts = find_linestarts (s)
1337 # We want to search for multiple regexes, without searching
1338 # the string multiple times for one regex.
1339 # Hence, we use earlier results to limit the string portion
1341 # Since every part of the string is traversed at most once for
1342 # every type of snippet, this is linear.
1348 if not found[type] or found[type][0] < index:
1351 m = res[type].search (s[index:endex])
1356 if snippet_type_to_class.has_key (type):
1357 cl = snippet_type_to_class[type]
1360 start = index + m.start ('match')
1361 line_number = line_start_idx
1362 while (line_starts[line_number] < start):
1366 snip = cl (type, m, global_options.format, line_number)
1368 found[type] = (start, snip)
1372 or found[type][0] < found[first][0]):
1377 # Limiting the search space is a cute
1378 # idea, but this *requires* to search
1379 # for possible containing blocks
1380 # first, at least as long as we do not
1381 # search for the start of blocks, but
1382 # always/directly for the entire
1383 # @block ... @end block.
1385 endex = found[first][0]
1388 snippets.append (Substring (s, index, len (s), line_start_idx))
1391 while (start > line_starts[line_start_idx+1]):
1394 (start, snip) = found[first]
1395 snippets.append (Substring (s, index, start, line_start_idx + 1))
1396 snippets.append (snip)
1398 index = start + len (snip.match.group ('match'))
1402 def filter_pipe (input, cmd):
1403 if global_options.verbose:
1404 progress (_ ("Opening filter `%s'") % cmd)
1406 (stdin, stdout, stderr) = os.popen3 (cmd)
1408 status = stdin.close ()
1412 output = stdout.read ()
1413 status = stdout.close ()
1414 error = stderr.read ()
1418 signal = 0x0f & status
1419 if status or (not output and error):
1420 exit_status = status >> 8
1421 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1422 error (_ ("The error log is as follows:"))
1423 ly.stderr_write (error)
1424 ly.stderr_write (stderr.read ())
1427 if global_options.verbose:
1433 return filter_pipe (s, global_options.filter_cmd)
1435 def is_derived_class (cl, baseclass):
1438 for b in cl.__bases__:
1439 if is_derived_class (b, baseclass):
1443 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1444 ly_names = filter (lambda x: x,
1445 map (Lilypond_snippet.basename, ly_snippets))
1446 texstr_names = filter (lambda x: x,
1447 map (Lilypond_snippet.basename, texstr_snippets))
1449 png_names = filter (lambda x: x,
1450 map (Lilypond_snippet.basename, png_snippets))
1453 def my_system (cmd):
1454 status = ly.system (cmd,
1455 be_verbose=global_options.verbose,
1458 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1459 cmd += ' --formats=png '
1460 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1461 cmd += ' --formats=png,pdf '
1465 # the --process=CMD switch is a bad idea
1466 # it is too generic for lilypond-book.
1468 my_system (' '.join ([cmd, '--backend texstr',
1469 'snippet-map.ly'] + texstr_names))
1470 for l in texstr_names:
1471 my_system ('latex %s.texstr' % l)
1474 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1477 my_system (' '.join ([cmd, 'snippet-names']))
1480 LATEX_INSPECTION_DOCUMENT = r'''
1484 \typeout{textwidth=\the\textwidth}
1485 \typeout{columnsep=\the\columnsep}
1486 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1490 # Do we need anything else besides `textwidth'?
1491 def get_latex_textwidth (source):
1492 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1494 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1496 ## what's a sensible default?
1499 preamble = source[:m.start (0)]
1500 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1502 (handle, tmpfile) = tempfile.mkstemp('.tex')
1503 logfile = os.path.splitext (tmpfile)[0] + '.log'
1504 logfile = os.path.split (logfile)[1]
1506 tmp_handle = os.fdopen (handle,'w')
1507 tmp_handle.write (latex_document)
1510 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1511 parameter_string = open (logfile).read()
1517 m = re.search ('columns=([0-9.]*)', parameter_string)
1519 columns = int (m.group (1))
1522 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1524 columnsep = float (m.group (1))
1527 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1529 textwidth = float (m.group (1))
1531 textwidth = (textwidth - columnsep) / columns
1535 def modify_preamble (chunk):
1536 str = chunk.replacement_text ()
1537 if (re.search (r"\\begin *{document}", str)
1538 and not re.search ("{graphic[sx]", str)):
1539 str = re.sub (r"\\begin{document}",
1540 r"\\usepackage{graphics}" + '\n'
1541 + r"\\begin{document}",
1543 chunk.override_text = str
1555 '.texinfo': TEXINFO,
1562 # TEXINFO: '.texinfo',
1568 class Compile_error:
1571 def write_file_map (lys, name):
1572 snippet_map = open ('snippet-map.ly', 'w')
1573 snippet_map.write ("""
1574 #(define version-seen #t)
1575 #(define output-empty-score-list #f)
1576 #(ly:add-file-name-alist '(
1579 snippet_map.write ('("%s.ly" . "%s")\n'
1583 snippet_map.write ('))\n')
1585 def do_process_cmd (chunks, input_name):
1586 all_lys = filter (lambda x: is_derived_class (x.__class__,
1590 write_file_map (all_lys, input_name)
1591 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1593 and x.ly_is_outdated (), chunks)
1594 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1596 and x.texstr_is_outdated (),
1598 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1600 and x.png_is_outdated (),
1603 outdated = png_outdated + texstr_outdated + ly_outdated
1605 progress (_ ("Writing snippets..."))
1606 map (Lilypond_snippet.write_ly, ly_outdated)
1610 progress (_ ("Processing..."))
1612 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1614 progress (_ ("All snippets are up to date..."))
1617 def guess_format (input_filename):
1619 e = os.path.splitext (input_filename)[1]
1620 if e in ext2format.keys ():
1622 format = ext2format[e]
1624 error (_ ("cannot determine format for: %s" \
1629 def write_if_updated (file_name, lines):
1631 f = open (file_name)
1633 new_str = ''.join (lines)
1634 if oldstr == new_str:
1635 progress (_ ("%s is up to date.") % file_name)
1638 # this prevents make from always rerunning lilypond-book:
1639 # .texi target must be touched in order to be up to date
1640 if global_options.format == 'texinfo':
1641 os.utime (file_name, None)
1646 progress (_ ("Writing `%s'...") % file_name)
1647 open (file_name, 'w').writelines (lines)
1650 def note_input_file (name, inputs=[]):
1651 ## hack: inputs is mutable!
1652 inputs.append (name)
1655 def samefile (f1, f2):
1657 return os.path.samefile (f1, f2)
1658 except AttributeError: # Windoze
1659 f1 = re.sub ("//*", "/", f1)
1660 f2 = re.sub ("//*", "/", f2)
1663 def do_file (input_filename):
1665 if not input_filename or input_filename == '-':
1666 in_handle = sys.stdin
1667 input_fullname = '<stdin>'
1669 if os.path.exists (input_filename):
1670 input_fullname = input_filename
1671 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1672 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1674 input_fullname = find_file (input_filename)
1676 note_input_file (input_fullname)
1677 in_handle = open (input_fullname)
1679 if input_filename == '-':
1680 input_base = 'stdin'
1682 input_base = os.path.basename \
1683 (os.path.splitext (input_filename)[0])
1685 # Only default to stdout when filtering.
1686 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1687 output_filename = '-'
1688 output_file = sys.stdout
1690 # don't complain when global_options.output_name is existing
1691 output_filename = input_base + format2ext[global_options.format]
1692 if global_options.output_name:
1693 if not os.path.isdir (global_options.output_name):
1694 os.mkdir (global_options.output_name, 0777)
1695 os.chdir (global_options.output_name)
1697 if (os.path.exists (input_filename)
1698 and os.path.exists (output_filename)
1699 and samefile (output_filename, input_fullname)):
1701 _ ("Output would overwrite input file; use --output."))
1705 progress (_ ("Reading %s...") % input_fullname)
1706 source = in_handle.read ()
1709 set_default_options (source)
1712 # FIXME: Containing blocks must be first, see
1713 # find_toplevel_snippets.
1715 'multiline_comment',
1719 'singleline_comment',
1724 progress (_ ("Dissecting..."))
1725 chunks = find_toplevel_snippets (source, snippet_types)
1727 if global_options.format == LATEX:
1729 if (c.is_plain () and
1730 re.search (r"\\begin *{document}", c.replacement_text())):
1735 if global_options.filter_cmd:
1736 write_if_updated (output_filename,
1737 [c.filter_text () for c in chunks])
1738 elif global_options.process_cmd:
1739 do_process_cmd (chunks, input_fullname)
1740 progress (_ ("Compiling %s...") % output_filename)
1742 write_if_updated (output_filename,
1743 [s.replacement_text ()
1746 def process_include (snippet):
1747 os.chdir (original_dir)
1748 name = snippet.substring ('filename')
1749 progress (_ ("Processing include: %s") % name)
1751 return do_file (name)
1753 include_chunks = map (process_include,
1754 filter (lambda x: is_derived_class (x.__class__,
1759 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1761 except Compile_error:
1762 os.chdir (original_dir)
1763 progress (_ ("Removing `%s'") % output_filename)
1769 global global_options
1771 opt_parser = get_option_parser()
1772 (global_options, args) = opt_parser.parse_args ()
1774 if global_options.format in ('texi-html', 'texi'):
1775 global_options.format = TEXINFO
1776 global_options.use_hash = True
1778 global_options.include_path = map (os.path.abspath, global_options.include_path)
1780 if global_options.warranty:
1783 if not args or len (args) > 1:
1784 opt_parser.print_help ()
1789 def psfonts_warning (options, basename):
1790 if options.format in (TEXINFO, LATEX):
1791 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1792 output = os.path.join (options.output_name, basename + '.dvi' )
1794 if not options.create_pdf:
1795 if not options.psfonts:
1796 warning (_ ("option --psfonts not used"))
1797 warning (_ ("processing with dvips will have no fonts"))
1800 progress (_ ("DVIPS usage:"))
1802 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1806 # FIXME: 85 lines of `main' macramee??
1807 files = do_options ()
1811 basename = os.path.splitext (file)[0]
1812 basename = os.path.split (basename)[1]
1814 if not global_options.format:
1815 global_options.format = guess_format (files[0])
1818 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1822 if global_options.process_cmd == '':
1823 global_options.process_cmd = (lilypond_binary
1824 + ' --formats=%s --backend eps ' % formats)
1826 if global_options.process_cmd:
1827 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1828 for p in global_options.include_path])
1830 if global_options.format in (TEXINFO, LATEX):
1831 ## prevent PDF from being switched on by default.
1832 global_options.process_cmd += ' --formats=eps '
1833 if global_options.create_pdf:
1834 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1836 if global_options.verbose:
1837 global_options.process_cmd += " --verbose "
1839 if global_options.padding_mm:
1840 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1842 global_options.process_cmd += " -dread-file-list "
1847 chunks = do_file (file)
1848 if global_options.psfonts:
1849 fontextract.verbose = global_options.verbose
1850 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1854 psfonts_file = basename + '.psfonts'
1855 if not global_options.verbose:
1856 progress (_ ("Writing fonts to %s...") % psfonts_file)
1857 fontextract.extract_fonts (psfonts_file,
1858 [x.basename() + '.eps'
1859 for x in snippet_chunks])
1860 if not global_options.verbose:
1863 except Compile_error:
1866 psfonts_warning (global_options, basename)
1868 inputs = note_input_file ('')
1871 base_file_name = os.path.splitext (os.path.basename (file))[0]
1872 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1873 final_output_file = os.path.join (global_options.output_name,
1875 + '.%s' % global_options.format)
1877 os.chdir (original_dir)
1878 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1880 if __name__ == '__main__':