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 = self.substring ('filename')
1248 str = output[global_options.format][PRINTFILENAME] % vars ()
1252 def output_texinfo (self):
1254 if self.output_print_filename (TEXINFO):
1256 + self.output_print_filename (HTML)
1259 + self.output_print_filename (LATEX)
1261 base = self.basename ()
1262 if TEXIDOC in self.option_dict:
1263 texidoc = base + '.texidoc'
1264 if os.path.exists (texidoc):
1265 str += '@include %(texidoc)s\n\n' % vars ()
1268 if VERBATIM in self.option_dict:
1269 verb = self.verb_ly ()
1270 substr += output[TEXINFO][VERBATIM] % vars ()
1271 if not QUOTE in self.option_dict:
1272 substr = output[TEXINFO][NOQUOTE] % {'str':substr}
1273 substr += self.output_info ()
1274 if LILYQUOTE in self.option_dict:
1275 substr = output[TEXINFO][QUOTE] % {'str':substr}
1278 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1279 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1280 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1282 if QUOTE in self.option_dict:
1283 str = output[TEXINFO][QUOTE] % vars ()
1285 # need par after image
1290 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1291 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1293 class Lilypond_file_snippet (Lilypond_snippet):
1294 def __init__ (self, type, match, format, line_number):
1295 Lilypond_snippet.__init__ (self, type, match, format, line_number)
1296 self.contents = open (find_file (self.substring ('filename'))).read ()
1300 s = re_begin_verbatim.split (s)[-1]
1301 s = re_end_verbatim.split (s)[0]
1305 name = self.substring ('filename')
1306 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1307 % (name, self.contents))
1310 snippet_type_to_class = {
1311 'lilypond_file': Lilypond_file_snippet,
1312 'lilypond_block': Lilypond_snippet,
1313 'lilypond': Lilypond_snippet,
1314 'include': Include_snippet,
1317 def find_linestarts (s):
1322 i = s.find ('\n', start)
1330 nls.append (len (s))
1333 def find_toplevel_snippets (s, types):
1336 res[i] = ly.re.compile (snippet_res[global_options.format][i])
1340 found = dict ([(t, None) for t in types])
1342 line_starts = find_linestarts (s)
1344 # We want to search for multiple regexes, without searching
1345 # the string multiple times for one regex.
1346 # Hence, we use earlier results to limit the string portion
1348 # Since every part of the string is traversed at most once for
1349 # every type of snippet, this is linear.
1355 if not found[type] or found[type][0] < index:
1358 m = res[type].search (s[index:endex])
1363 if snippet_type_to_class.has_key (type):
1364 cl = snippet_type_to_class[type]
1367 start = index + m.start ('match')
1368 line_number = line_start_idx
1369 while (line_starts[line_number] < start):
1373 snip = cl (type, m, global_options.format, line_number)
1375 found[type] = (start, snip)
1379 or found[type][0] < found[first][0]):
1384 # Limiting the search space is a cute
1385 # idea, but this *requires* to search
1386 # for possible containing blocks
1387 # first, at least as long as we do not
1388 # search for the start of blocks, but
1389 # always/directly for the entire
1390 # @block ... @end block.
1392 endex = found[first][0]
1395 snippets.append (Substring (s, index, len (s), line_start_idx))
1398 while (start > line_starts[line_start_idx+1]):
1401 (start, snip) = found[first]
1402 snippets.append (Substring (s, index, start, line_start_idx + 1))
1403 snippets.append (snip)
1405 index = start + len (snip.match.group ('match'))
1409 def filter_pipe (input, cmd):
1410 if global_options.verbose:
1411 progress (_ ("Opening filter `%s'") % cmd)
1413 (stdin, stdout, stderr) = os.popen3 (cmd)
1415 status = stdin.close ()
1419 output = stdout.read ()
1420 status = stdout.close ()
1421 error = stderr.read ()
1425 signal = 0x0f & status
1426 if status or (not output and error):
1427 exit_status = status >> 8
1428 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1429 error (_ ("The error log is as follows:"))
1430 ly.stderr_write (error)
1431 ly.stderr_write (stderr.read ())
1434 if global_options.verbose:
1440 return filter_pipe (s, global_options.filter_cmd)
1442 def is_derived_class (cl, baseclass):
1445 for b in cl.__bases__:
1446 if is_derived_class (b, baseclass):
1450 def process_snippets (cmd, ly_snippets, texstr_snippets, png_snippets):
1451 ly_names = filter (lambda x: x,
1452 map (Lilypond_snippet.basename, ly_snippets))
1453 texstr_names = filter (lambda x: x,
1454 map (Lilypond_snippet.basename, texstr_snippets))
1456 png_names = filter (lambda x: x,
1457 map (Lilypond_snippet.basename, png_snippets))
1460 def my_system (cmd):
1461 status = ly.system (cmd,
1462 be_verbose=global_options.verbose,
1465 if global_options.format in (HTML, TEXINFO) and '--formats' not in cmd:
1466 cmd += ' --formats=png '
1467 elif global_options.format in (DOCBOOK) and '--formats' not in cmd:
1468 cmd += ' --formats=png,pdf '
1472 # the --process=CMD switch is a bad idea
1473 # it is too generic for lilypond-book.
1475 my_system (' '.join ([cmd, '--backend texstr',
1476 'snippet-map.ly'] + texstr_names))
1477 for l in texstr_names:
1478 my_system ('latex %s.texstr' % l)
1481 open ('snippet-names', 'wb').write ('\n'.join (['snippet-map.ly']
1484 my_system (' '.join ([cmd, 'snippet-names']))
1487 LATEX_INSPECTION_DOCUMENT = r'''
1491 \typeout{textwidth=\the\textwidth}
1492 \typeout{columnsep=\the\columnsep}
1493 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1497 # Do we need anything else besides `textwidth'?
1498 def get_latex_textwidth (source):
1499 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1501 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1503 ## what's a sensible default?
1506 preamble = source[:m.start (0)]
1507 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1509 (handle, tmpfile) = tempfile.mkstemp('.tex')
1510 logfile = os.path.splitext (tmpfile)[0] + '.log'
1511 logfile = os.path.split (logfile)[1]
1513 tmp_handle = os.fdopen (handle,'w')
1514 tmp_handle.write (latex_document)
1517 ly.system ('latex %s' % tmpfile, be_verbose=global_options.verbose)
1518 parameter_string = open (logfile).read()
1524 m = re.search ('columns=([0-9.]*)', parameter_string)
1526 columns = int (m.group (1))
1529 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1531 columnsep = float (m.group (1))
1534 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1536 textwidth = float (m.group (1))
1538 textwidth = (textwidth - columnsep) / columns
1542 def modify_preamble (chunk):
1543 str = chunk.replacement_text ()
1544 if (re.search (r"\\begin *{document}", str)
1545 and not re.search ("{graphic[sx]", str)):
1546 str = re.sub (r"\\begin{document}",
1547 r"\\usepackage{graphics}" + '\n'
1548 + r"\\begin{document}",
1550 chunk.override_text = str
1562 '.texinfo': TEXINFO,
1569 # TEXINFO: '.texinfo',
1575 class Compile_error:
1578 def write_file_map (lys, name):
1579 snippet_map = open ('snippet-map.ly', 'w')
1580 snippet_map.write ("""
1581 #(define version-seen #t)
1582 #(define output-empty-score-list #f)
1583 #(ly:add-file-name-alist '(
1586 snippet_map.write ('("%s.ly" . "%s")\n'
1590 snippet_map.write ('))\n')
1592 def do_process_cmd (chunks, input_name):
1593 all_lys = filter (lambda x: is_derived_class (x.__class__,
1597 write_file_map (all_lys, input_name)
1598 ly_outdated = filter (lambda x: is_derived_class (x.__class__,
1600 and x.ly_is_outdated (), chunks)
1601 texstr_outdated = filter (lambda x: is_derived_class (x.__class__,
1603 and x.texstr_is_outdated (),
1605 png_outdated = filter (lambda x: is_derived_class (x.__class__,
1607 and x.png_is_outdated (),
1610 outdated = png_outdated + texstr_outdated + ly_outdated
1612 progress (_ ("Writing snippets..."))
1613 map (Lilypond_snippet.write_ly, ly_outdated)
1617 progress (_ ("Processing..."))
1619 process_snippets (global_options.process_cmd, ly_outdated, texstr_outdated, png_outdated)
1621 progress (_ ("All snippets are up to date..."))
1624 def guess_format (input_filename):
1626 e = os.path.splitext (input_filename)[1]
1627 if e in ext2format.keys ():
1629 format = ext2format[e]
1631 error (_ ("cannot determine format for: %s" \
1636 def write_if_updated (file_name, lines):
1638 f = open (file_name)
1640 new_str = ''.join (lines)
1641 if oldstr == new_str:
1642 progress (_ ("%s is up to date.") % file_name)
1645 # this prevents make from always rerunning lilypond-book:
1646 # .texi target must be touched in order to be up to date
1647 if global_options.format == 'texinfo':
1648 os.utime (file_name, None)
1653 progress (_ ("Writing `%s'...") % file_name)
1654 open (file_name, 'w').writelines (lines)
1657 def note_input_file (name, inputs=[]):
1658 ## hack: inputs is mutable!
1659 inputs.append (name)
1662 def samefile (f1, f2):
1664 return os.path.samefile (f1, f2)
1665 except AttributeError: # Windoze
1666 f1 = re.sub ("//*", "/", f1)
1667 f2 = re.sub ("//*", "/", f2)
1670 def do_file (input_filename):
1672 if not input_filename or input_filename == '-':
1673 in_handle = sys.stdin
1674 input_fullname = '<stdin>'
1676 if os.path.exists (input_filename):
1677 input_fullname = input_filename
1678 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1679 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1681 input_fullname = find_file (input_filename)
1683 note_input_file (input_fullname)
1684 in_handle = open (input_fullname)
1686 if input_filename == '-':
1687 input_base = 'stdin'
1689 input_base = os.path.basename \
1690 (os.path.splitext (input_filename)[0])
1692 # Only default to stdout when filtering.
1693 if global_options.output_name == '-' or (not global_options.output_name and global_options.filter_cmd):
1694 output_filename = '-'
1695 output_file = sys.stdout
1697 # don't complain when global_options.output_name is existing
1698 output_filename = input_base + format2ext[global_options.format]
1699 if global_options.output_name:
1700 if not os.path.isdir (global_options.output_name):
1701 os.mkdir (global_options.output_name, 0777)
1702 os.chdir (global_options.output_name)
1704 if (os.path.exists (input_filename)
1705 and os.path.exists (output_filename)
1706 and samefile (output_filename, input_fullname)):
1708 _ ("Output would overwrite input file; use --output."))
1712 progress (_ ("Reading %s...") % input_fullname)
1713 source = in_handle.read ()
1716 set_default_options (source)
1719 # FIXME: Containing blocks must be first, see
1720 # find_toplevel_snippets.
1722 'multiline_comment',
1726 'singleline_comment',
1731 progress (_ ("Dissecting..."))
1732 chunks = find_toplevel_snippets (source, snippet_types)
1734 if global_options.format == LATEX:
1736 if (c.is_plain () and
1737 re.search (r"\\begin *{document}", c.replacement_text())):
1742 if global_options.filter_cmd:
1743 write_if_updated (output_filename,
1744 [c.filter_text () for c in chunks])
1745 elif global_options.process_cmd:
1746 do_process_cmd (chunks, input_fullname)
1747 progress (_ ("Compiling %s...") % output_filename)
1749 write_if_updated (output_filename,
1750 [s.replacement_text ()
1753 def process_include (snippet):
1754 os.chdir (original_dir)
1755 name = snippet.substring ('filename')
1756 progress (_ ("Processing include: %s") % name)
1758 return do_file (name)
1760 include_chunks = map (process_include,
1761 filter (lambda x: is_derived_class (x.__class__,
1766 return chunks + reduce (lambda x,y: x + y, include_chunks, [])
1768 except Compile_error:
1769 os.chdir (original_dir)
1770 progress (_ ("Removing `%s'") % output_filename)
1776 global global_options
1778 opt_parser = get_option_parser()
1779 (global_options, args) = opt_parser.parse_args ()
1781 if global_options.format in ('texi-html', 'texi'):
1782 global_options.format = TEXINFO
1783 global_options.use_hash = True
1785 global_options.include_path = map (os.path.abspath, global_options.include_path)
1787 if global_options.warranty:
1790 if not args or len (args) > 1:
1791 opt_parser.print_help ()
1796 def psfonts_warning (options, basename):
1797 if options.format in (TEXINFO, LATEX):
1798 psfonts_file = os.path.join (options.output_name, basename + '.psfonts')
1799 output = os.path.join (options.output_name, basename + '.dvi' )
1801 if not options.create_pdf:
1802 if not options.psfonts:
1803 warning (_ ("option --psfonts not used"))
1804 warning (_ ("processing with dvips will have no fonts"))
1807 progress (_ ("DVIPS usage:"))
1809 progress (" dvips -h %(psfonts_file)s %(output)s" % vars ())
1813 # FIXME: 85 lines of `main' macramee??
1814 files = do_options ()
1818 basename = os.path.splitext (file)[0]
1819 basename = os.path.split (basename)[1]
1821 if not global_options.format:
1822 global_options.format = guess_format (files[0])
1825 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1829 if global_options.process_cmd == '':
1830 global_options.process_cmd = (lilypond_binary
1831 + ' --formats=%s --backend eps ' % formats)
1833 if global_options.process_cmd:
1834 global_options.process_cmd += ' '.join ([(' -I %s' % ly.mkarg (p))
1835 for p in global_options.include_path])
1837 if global_options.format in (TEXINFO, LATEX):
1838 ## prevent PDF from being switched on by default.
1839 global_options.process_cmd += ' --formats=eps '
1840 if global_options.create_pdf:
1841 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1843 if global_options.verbose:
1844 global_options.process_cmd += " --verbose "
1846 if global_options.padding_mm:
1847 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1849 global_options.process_cmd += " -dread-file-list "
1854 chunks = do_file (file)
1855 if global_options.psfonts:
1856 fontextract.verbose = global_options.verbose
1857 snippet_chunks = filter (lambda x: is_derived_class (x.__class__,
1861 psfonts_file = basename + '.psfonts'
1862 if not global_options.verbose:
1863 progress (_ ("Writing fonts to %s...") % psfonts_file)
1864 fontextract.extract_fonts (psfonts_file,
1865 [x.basename() + '.eps'
1866 for x in snippet_chunks])
1867 if not global_options.verbose:
1870 except Compile_error:
1873 psfonts_warning (global_options, basename)
1875 inputs = note_input_file ('')
1878 base_file_name = os.path.splitext (os.path.basename (file))[0]
1879 dep_file = os.path.join (global_options.output_name, base_file_name + '.dep')
1880 final_output_file = os.path.join (global_options.output_name,
1882 + '.%s' % global_options.format)
1884 os.chdir (original_dir)
1885 open (dep_file, 'w').write ('%s: %s' % (final_output_file, ' '.join (inputs)))
1887 if __name__ == '__main__':