3 # This file is part of LilyPond, the GNU music typesetter.
5 # LilyPond is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # LilyPond is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
22 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
25 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
27 classic lilypond-book:
28 lilypond-book --process="lilypond" BOOK.tely
32 * this script is too complex. Modularize.
34 * ly-options: intertext?
36 * eps in latex / eps by lilypond -b ps?
37 * check latex parameters, twocolumn, multicolumn?
38 * use --png --ps --pdf for making images?
40 * Converting from lilypond-book source, substitute:
41 @mbinclude foo.itely -> @include foo.itely
62 ly.require_python_version ()
65 program_version = '@TOPLEVEL_VERSION@'
66 program_name = os.path.basename (sys.argv[0])
68 # Check if program_version contains @ characters. This will be the case if
69 # the .py file is called directly while building the lilypond documentation.
70 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
71 # makefiles and use its value.
72 at_re = re.compile (r'@')
73 if at_re.match (program_version):
74 if os.environ.has_key('LILYPOND_VERSION'):
75 program_version = os.environ['LILYPOND_VERSION']
77 program_version = "unknown"
79 original_dir = os.getcwd ()
83 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
87 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
88 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
89 $ lilypond-book --process='lilypond -I include' %(BOOK)s
90 ''' % {'BOOK': _ ("BOOK")})
92 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
93 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
95 ################################################################
97 if global_options.verbose:
98 raise Exception (_ ('Exiting (%d)...') % i)
103 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
105 progress = ly.progress
108 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
111 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
113 def ps_page_count (ps_name):
114 header = file (ps_name).read (1024)
115 m = re.search ('\n%%Pages: ([0-9]+)', header)
117 return int (m.group (1))
122 ly.encoded_write (sys.stdout, '''
129 ''' % ( _ ('Copyright (c) %s by') % '2001--2009',
130 '\n '.join (authors),
131 _ ("Distributed under terms of the GNU General Public License."),
132 _ ("It comes with NO WARRANTY.")))
134 def get_option_parser ():
135 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
136 description=help_summary,
137 add_help_option=False)
139 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
142 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
145 p.add_option ('-f', '--format',
146 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
147 metavar=_ ("FORMAT"),
150 p.add_option("-h", "--help",
152 help=_ ("show this help and exit"))
154 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
156 action='append', dest='include_path',
157 default=[os.path.abspath (os.getcwd ())])
159 p.add_option ('--info-images-dir',
160 help=_ ("format Texinfo output so that Info will "
161 "look for images of music in DIR"),
163 action='store', dest='info_images_dir',
166 p.add_option ('--latex-program',
167 help=_ ("run executable PROG instead of latex"),
169 action='store', dest='latex_program',
172 p.add_option ('--left-padding',
175 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
179 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
181 action='store', dest='output_dir',
184 p.add_option ('--skip-lily-check',
185 help=_ ("do not fail if no lilypond output is found"),
187 action='store_true', dest='skip_lilypond_run',
190 p.add_option ('--skip-png-check',
191 help=_ ("do not fail if no PNG images are found for EPS files"),
193 action='store_true', dest='skip_png_check',
196 p.add_option ('--lily-output-dir',
197 help=_ ("write lily-XXX files to DIR, link into --output dir"),
199 action='store', dest='lily_output_dir',
202 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
203 help = _ ("process ly_files using COMMAND FILE..."),
205 dest='process_cmd', default='')
207 p.add_option ('--pdf',
210 help=_ ("create PDF files for use with PDFTeX"),
213 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
218 p.version = "@TOPLEVEL_VERSION@"
219 p.add_option("--version",
221 help=_ ("show version number and exit"))
223 p.add_option ('-w', '--warranty',
224 help=_ ("show warranty and copyright"),
226 p.add_option_group ('',
228 _ ("Report bugs via %s")
229 % ' http://post.gmane.org/post.php'
230 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
233 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
235 # If we are called with full path, try to use lilypond binary
236 # installed in the same path; this is needed in GUB binaries, where
237 # @bindir is always different from the installed binary path.
238 if 'bindir' in globals () and bindir:
239 lilypond_binary = os.path.join (bindir, 'lilypond')
241 # Only use installed binary when we are installed too.
242 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
243 lilypond_binary = 'lilypond'
245 global_options = None
248 default_ly_options = { 'alt': "[image of music]" }
250 document_language = ''
253 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
255 ADDVERSION = 'addversion'
259 EXAMPLEINDENT = 'exampleindent'
261 FRAGMENT = 'fragment'
267 LINE_WIDTH = 'line-width'
268 LILYQUOTE = 'lilyquote'
269 NOFRAGMENT = 'nofragment'
270 NOGETTEXT = 'nogettext'
271 NOINDENT = 'noindent'
273 NORAGGED_RIGHT = 'noragged-right'
277 OUTPUTIMAGE = 'outputimage'
279 PREAMBLE = 'preamble'
280 PRINTFILENAME = 'printfilename'
282 RAGGED_RIGHT = 'ragged-right'
283 RELATIVE = 'relative'
284 STAFFSIZE = 'staffsize'
285 DOCTITLE = 'doctitle'
288 VERBATIM = 'verbatim'
289 VERSION = 'lilypondversion'
290 FILENAME = 'filename'
294 # NOTIME has no opposite so it isn't part of this dictionary.
295 # NOQUOTE is used internally only.
297 NOFRAGMENT: FRAGMENT,
302 # Recognize special sequences in the input.
304 # (?P<name>regex) -- Assign result of REGEX to NAME.
305 # *? -- Match non-greedily.
306 # (?!...) -- Match if `...' doesn't match next (without consuming
309 # (?m) -- Multiline regex: Make ^ and $ match at each line.
310 # (?s) -- Make the dot match all characters including newline.
311 # (?x) -- Ignore whitespace in patterns.
322 <(?P<inline>(inline)?)mediaobject>\s*
324 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
326 </programlisting\s*>\s*
328 </(inline)?mediaobject>)''',
333 <(?P<inline>(inline)?)mediaobject>\s*
335 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
337 </programlisting\s*>\s*
339 </(inline)?mediaobject>)''',
344 <(?P<inline>(inline)?)mediaobject>\s*
347 fileref="(?P<filename>.*?\.ly)"\s*
348 (role="(?P<options>.*?)")?\s*
349 (/>|>\s*</imagedata>)\s*
351 </(inline)?mediaobject>)''',
357 (?P<code><!--\s.*?!-->)
360 'singleline_comment':
381 (\s*(?P<options>.*?)\s*:)?\s*
389 \s*(?P<options>.*?)\s*
398 \s*(?P<options>.*?)\s*
400 \s*(?P<filename>.*?)\s*
407 (?P<code><!--\s.*?!-->)
410 'singleline_comment':
416 (?P<code><pre>.*?</pre>))''',
422 (?P<code><pre>\s.*?</pre>\s))''',
427 <lilypondversion\s*/>)''',
446 \s*(?P<options>.*?)\s*
457 \s*(?P<options>.*?)\s*
461 \\end\s*{lilypond})''',
469 \s*(?P<options>.*?)\s*
477 'singleline_comment':
500 \\end\s*{verbatim}))''',
505 \\lilypondversion)[^a-zA-Z]''',
515 (?P<filename>\S+))''',
519 ^[^\n]*?(?!@c\s+)[^\n]*?
523 \s*(?P<options>.*?)\s*
533 \s*(?P<options>.*?)\s*
536 ^@end\s+lilypond)\s''',
543 \s*(?P<options>.*?)\s*
554 @end\s+ignore))\s''',
556 'singleline_comment':
561 @c([ \t][^\n]*|)\n))''',
563 # Don't do this: It interferes with @code{@{}.
564 # 'verb': r'''(?P<code>@code{.*?})''',
572 @end\s+example\s))''',
577 @lilypondversion)[^a-zA-Z]''',
585 'intertext': r',?\s*intertext=\".*?\"',
589 'intertext': r',?\s*intertext=\".*?\"',
594 'intertext': r',?\s*intertext=\".*?\"',
595 'option_sep': '\s*,\s*',
599 'intertext': r',?\s*intertext=\".*?\"',
600 'option_sep': '\s*,\s*',
605 # Options without a pattern in ly_options.
625 RELATIVE: r'''\relative c%(relative_quotes)s''',
630 INDENT: r'''indent = %(indent)s''',
632 LINE_WIDTH: r'''line-width = %(line-width)s''',
634 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
636 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
638 RAGGED_RIGHT: r'''ragged-right = ##t''',
640 NORAGGED_RIGHT: r'''ragged-right = ##f''',
652 \remove "Time_signature_engraver"
658 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
665 FILTER: r'''<mediaobject>
667 <programlisting language="lilypond"
674 OUTPUT: r'''<imageobject role="latex">
675 <imagedata fileref="%(base)s.pdf" format="PDF"/>
677 <imageobject role="html">
678 <imagedata fileref="%(base)s.png" format="PNG"/>
681 VERBATIM: r'''<programlisting>
682 %(verb)s</programlisting>''',
684 VERSION: program_version,
686 PRINTFILENAME: r'''<textobject>
688 <ulink url="%(base)s.ly">
698 FILTER: r'''<lilypond %(options)s>
708 <a href="%(base)s.ly">''',
716 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
718 QUOTE: r'''<blockquote>
726 VERSION: program_version,
733 \ifx\preLilyPondExample \undefined
735 \expandafter\preLilyPondExample
737 \def\lilypondbook{}%%
738 \input %(base)s-systems.tex
739 \ifx\postLilyPondExample \undefined
741 \expandafter\postLilyPondExample
745 PRINTFILENAME: '''\\texttt{%(filename)s}
748 QUOTE: r'''\begin{quotation}
752 VERBATIM: r'''\noindent
753 \begin{verbatim}%(verb)s\end{verbatim}
756 VERSION: program_version,
758 FILTER: r'''\begin{lilypond}[%(options)s]
765 FILTER: r'''@lilypond[%(options)s]
771 @include %(base)s-systems.texi
775 OUTPUTIMAGE: r'''@noindent
777 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
781 <a href="%(base)s.ly">
793 <a href="%(base)s.ly">
801 QUOTE: r'''@quotation
802 %(str)s@end quotation
809 VERBATIM: r'''@exampleindent 0
811 %(verb)s@end verbatim
814 VERSION: program_version,
816 ADDVERSION: r'''@example
817 \version @w{"@version{}"}
824 # Maintain line numbers.
829 for f in [HTML, LATEX]:
830 for s in (QUOTE, VERBATIM):
831 output[f][s] = output[f][s].replace("\n"," ")
834 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
835 %%%% Options: [%(option_string)s]
836 \\include "lilypond-book-preamble.ly"
839 %% ****************************************************************
840 %% Start cut-&-pastable-section
841 %% ****************************************************************
847 force-assignment = #""
848 line-width = #(- line-width (* mm %(padding_mm)f))
861 %% ****************************************************************
862 %% ly snippet contents follows:
863 %% ****************************************************************
867 %% ****************************************************************
869 %% ****************************************************************
876 %% ****************************************************************
878 %% ****************************************************************
882 %% ****************************************************************
884 %% ****************************************************************
887 texinfo_line_widths = {
888 '@afourpaper': '160\\mm',
889 '@afourwide': '6.5\\in',
890 '@afourlatex': '150\\mm',
891 '@smallbook': '5\\in',
892 '@letterpaper': '6\\in',
895 def classic_lilypond_book_compatibility (key, value):
896 if key == 'singleline' and value == None:
897 return (RAGGED_RIGHT, None)
899 m = re.search ('relative\s*([-0-9])', key)
901 return ('relative', m.group (1))
903 m = re.match ('([0-9]+)pt', key)
905 return ('staffsize', m.group (1))
907 if key == 'indent' or key == 'line-width':
908 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
910 f = float (m.group (1))
911 return (key, '%f\\%s' % (f, m.group (2)))
915 def find_file (name, raise_error=True):
916 for i in global_options.include_path:
917 full = os.path.join (i, name)
918 if os.path.exists (full):
922 error (_ ("file not found: %s") % name + '\n')
926 def verbatim_html (s):
927 return re.sub ('>', '>',
929 re.sub ('&', '&', s)))
931 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
932 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
933 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
934 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
936 def ly_comment_gettext (t, m):
937 return m.group (1) + t (m.group (2))
939 def verb_ly_gettext (s):
940 if not document_language:
943 t = langdefs.translation[document_language]
947 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
949 if langdefs.LANGDICT[document_language].enable_ly_identifier_l10n:
950 for v in ly_var_def_re.findall (s):
951 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
952 "\\1" + t (v) + "\\2",
954 for id in ly_context_id_re.findall (s):
955 s = re.sub (r'(\s+|")%s(\s+|")' % id,
956 "\\1" + t (id) + "\\2",
960 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
961 def set_default_options (source, default_ly_options, format):
962 global document_language
963 if LINE_WIDTH not in default_ly_options:
965 textwidth = get_latex_textwidth (source)
966 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
967 elif format == TEXINFO:
968 m = texinfo_lang_re.search (source)
969 if m and not m.group (1).startswith ('en'):
970 document_language = m.group (1)
972 document_language = ''
973 for regex in texinfo_line_widths:
974 # FIXME: @layout is usually not in
977 # \input texinfo @c -*-texinfo-*-
979 # Bluntly search first K items of
981 # s = chunks[0].replacement_text ()
982 if re.search (regex, source[:1024]):
983 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
987 def replacement_text (self):
990 def filter_text (self):
991 return self.replacement_text ()
996 class Substring (Chunk):
997 """A string that does not require extra memory."""
998 def __init__ (self, source, start, end, line_number):
1002 self.line_number = line_number
1003 self.override_text = None
1005 def is_plain (self):
1008 def replacement_text (self):
1009 if self.override_text:
1010 return self.override_text
1012 return self.source[self.start:self.end]
1014 class Snippet (Chunk):
1015 def __init__ (self, type, match, format, line_number):
1019 self.option_dict = {}
1020 self.format = format
1021 self.line_number = line_number
1023 def replacement_text (self):
1024 return self.match.group ('match')
1026 def substring (self, s):
1027 return self.match.group (s)
1029 def __repr__ (self):
1030 return `self.__class__` + ' type = ' + self.type
1032 class IncludeSnippet (Snippet):
1033 def processed_filename (self):
1034 f = self.substring ('filename')
1035 return os.path.splitext (f)[0] + format2ext[self.format]
1037 def replacement_text (self):
1038 s = self.match.group ('match')
1039 f = self.substring ('filename')
1041 return re.sub (f, self.processed_filename (), s)
1043 class LilypondSnippet (Snippet):
1044 def __init__ (self, type, match, format, line_number):
1045 Snippet.__init__ (self, type, match, format, line_number)
1046 os = match.group ('options')
1047 self.do_options (os, self.type)
1050 verb_text = self.substring ('code')
1051 if not NOGETTEXT in self.option_dict:
1052 verb_text = verb_ly_gettext (verb_text)
1053 if not verb_text.endswith ('\n'):
1058 contents = self.substring ('code')
1059 return ('\\sourcefileline %d\n%s'
1060 % (self.line_number - 1, contents))
1065 return self.compose_ly (s)
1068 def split_options (self, option_string):
1070 if self.format == HTML:
1071 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1073 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1077 return re.split (format_res[self.format]['option_sep'],
1081 def do_options (self, option_string, type):
1082 self.option_dict = {}
1084 options = self.split_options (option_string)
1086 for option in options:
1088 (key, value) = re.split ('\s*=\s*', option)
1089 self.option_dict[key] = value
1091 if option in no_options:
1092 if no_options[option] in self.option_dict:
1093 del self.option_dict[no_options[option]]
1095 self.option_dict[option] = None
1097 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1098 no_line_width_value = 0
1100 # If LINE_WIDTH is used without parameter, set it to default.
1101 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1102 no_line_width_value = 1
1103 del self.option_dict[LINE_WIDTH]
1105 for k in default_ly_options:
1106 if k not in self.option_dict:
1107 self.option_dict[k] = default_ly_options[k]
1109 # RELATIVE does not work without FRAGMENT;
1110 # make RELATIVE imply FRAGMENT
1111 has_relative = self.option_dict.has_key (RELATIVE)
1112 if has_relative and not self.option_dict.has_key (FRAGMENT):
1113 self.option_dict[FRAGMENT] = None
1115 if not has_line_width:
1116 if type == 'lilypond' or FRAGMENT in self.option_dict:
1117 self.option_dict[RAGGED_RIGHT] = None
1119 if type == 'lilypond':
1120 if LINE_WIDTH in self.option_dict:
1121 del self.option_dict[LINE_WIDTH]
1123 if RAGGED_RIGHT in self.option_dict:
1124 if LINE_WIDTH in self.option_dict:
1125 del self.option_dict[LINE_WIDTH]
1127 if QUOTE in self.option_dict or type == 'lilypond':
1128 if LINE_WIDTH in self.option_dict:
1129 del self.option_dict[LINE_WIDTH]
1131 if not INDENT in self.option_dict:
1132 self.option_dict[INDENT] = '0\\mm'
1134 # Set a default line-width if there is none. We need this, because
1135 # lilypond-book has set left-padding by default and therefore does
1136 # #(define line-width (- line-width (* 3 mm)))
1137 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
1138 # all settings before writing them in the \paper block.
1139 if not LINE_WIDTH in self.option_dict:
1140 if not QUOTE in self.option_dict:
1141 if not LILYQUOTE in self.option_dict:
1142 self.option_dict[LINE_WIDTH] = "#(- paper-width \
1143 left-margin-default right-margin-default)"
1145 def compose_ly (self, code):
1146 if FRAGMENT in self.option_dict:
1154 # The original concept of the `exampleindent' option is broken.
1155 # It is not possible to get a sane value for @exampleindent at all
1156 # without processing the document itself. Saying
1164 # causes ugly results with the DVI backend of texinfo since the
1165 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1166 # value). Executing the above code changes the environment
1167 # indentation to an unknown value because we don't know the amount
1168 # of 1em in advance since it is font-dependent. Modifying
1169 # @exampleindent in the middle of a document is simply not
1170 # supported within texinfo.
1172 # As a consequence, the only function of @exampleindent is now to
1173 # specify the amount of indentation for the `quote' option.
1175 # To set @exampleindent locally to zero, we use the @format
1176 # environment for non-quoted snippets.
1177 override[EXAMPLEINDENT] = r'0.4\in'
1178 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1179 override.update (default_ly_options)
1182 for (key, value) in self.option_dict.items ():
1184 option_list.append (key)
1186 option_list.append (key + '=' + value)
1187 option_string = ','.join (option_list)
1190 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1191 for a in compose_types:
1192 compose_dict[a] = []
1194 for (key, value) in self.option_dict.items ():
1195 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1199 _ ("deprecated ly-option used: %s=%s") % (key, value))
1201 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1204 _ ("deprecated ly-option used: %s") % key)
1206 _ ("compatibility mode translation: %s") % c_key)
1208 (key, value) = (c_key, c_value)
1211 override[key] = value
1213 if not override.has_key (key):
1214 override[key] = None
1217 for type in compose_types:
1218 if ly_options[type].has_key (key):
1219 compose_dict[type].append (ly_options[type][key])
1223 if not found and key not in simple_options:
1224 warning (_ ("ignoring unknown ly option: %s") % key)
1227 if RELATIVE in override and override[RELATIVE]:
1228 relative = int (override[RELATIVE])
1230 relative_quotes = ''
1234 relative_quotes += ',' * (- relative)
1236 relative_quotes += "'" * relative
1238 paper_string = '\n '.join (compose_dict[PAPER]) % override
1239 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1240 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1241 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1242 padding_mm = global_options.padding_mm
1244 d = globals().copy()
1246 return (PREAMBLE_LY + body) % d
1248 def get_checksum (self):
1249 if not self.checksum:
1250 # Work-around for md5 module deprecation warning in python 2.5+:
1252 from hashlib import md5
1256 # We only want to calculate the hash based
1257 # on the snippet code, not the snippet + preamble
1258 hash = md5 (self.relevant_contents (self.ly ()))
1260 ## let's not create too long names.
1261 self.checksum = hash.hexdigest ()[:10]
1263 return self.checksum
1265 def basename (self):
1266 cs = self.get_checksum ()
1267 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1270 def write_ly (self):
1271 base = self.basename ()
1272 path = os.path.join (global_options.lily_output_dir, base)
1273 directory = os.path.split(path)[0]
1274 if not os.path.isdir (directory):
1275 os.makedirs (directory)
1276 out = file (path + '.ly', 'w')
1277 out.write (self.full_ly ())
1278 file (path + '.txt', 'w').write ('image of music')
1280 def relevant_contents (self, ly):
1281 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n|' +
1282 NOGETTEXT + '[,\]]', '', ly)
1284 def link_all_output_files (self, output_dir, output_dir_files, destination):
1285 existing, missing = self.all_output_files (output_dir, output_dir_files)
1287 print '\nMissing', missing
1288 raise CompileError(self.basename())
1289 for name in existing:
1291 os.unlink (os.path.join (destination, name))
1295 src = os.path.join (output_dir, name)
1296 dst = os.path.join (destination, name)
1297 dst_path = os.path.split(dst)[0]
1298 if not os.path.isdir (dst_path):
1299 os.makedirs (dst_path)
1303 def all_output_files (self, output_dir, output_dir_files):
1304 """Return all files generated in lily_output_dir, a set.
1306 output_dir_files is the list of files in the output directory.
1310 base = self.basename()
1311 full = os.path.join (output_dir, base)
1312 def consider_file (name):
1313 if name in output_dir_files:
1316 def require_file (name):
1317 if name in output_dir_files:
1322 # UGH - junk global_options
1323 skip_lily = global_options.skip_lilypond_run
1324 for required in [base + '.ly',
1326 require_file (required)
1328 require_file (base + '-systems.count')
1330 if 'ddump-profile' in global_options.process_cmd:
1331 require_file (base + '.profile')
1332 if 'dseparate-log-file' in global_options.process_cmd:
1333 require_file (base + '.log')
1335 map (consider_file, [base + '.tex',
1339 base + '-systems.texi',
1340 base + '-systems.tex',
1341 base + '-systems.pdftexi'])
1342 if document_language:
1344 [base + '.texidoc' + document_language,
1345 base + '.doctitle' + document_language])
1347 # UGH - junk global_options
1348 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1349 and not global_options.skip_png_check):
1350 page_count = ps_page_count (full + '.eps')
1352 require_file (base + '.png')
1354 for page in range (1, page_count + 1):
1355 require_file (base + '-page%d.png' % page)
1358 if not skip_lily and not missing:
1359 system_count = int(file (full + '-systems.count').read())
1361 for number in range(1, system_count + 1):
1362 systemfile = '%s-%d' % (base, number)
1363 require_file (systemfile + '.eps')
1364 consider_file (systemfile + '.pdf')
1366 # We can't require signatures, since books and toplevel
1367 # markups do not output a signature.
1368 if 'ddump-signature' in global_options.process_cmd:
1369 consider_file (systemfile + '.signature')
1372 return (result, missing)
1374 def is_outdated (self, output_dir, current_files):
1375 found, missing = self.all_output_files (output_dir, current_files)
1378 def filter_text (self):
1379 """Run snippet bodies through a command (say: convert-ly).
1381 This functionality is rarely used, and this code must have bitrot.
1383 code = self.substring ('code')
1384 s = filter_pipe (code, global_options.filter_cmd)
1387 'options': self.match.group ('options')
1390 return output[self.format][FILTER] % d
1392 def replacement_text (self):
1393 func = LilypondSnippet.__dict__['output_' + self.format]
1396 def get_images (self):
1397 base = self.basename ()
1399 single = '%(base)s.png' % vars ()
1400 multiple = '%(base)s-page1.png' % vars ()
1402 if (os.path.exists (multiple)
1403 and (not os.path.exists (single)
1404 or (os.stat (multiple)[stat.ST_MTIME]
1405 > os.stat (single)[stat.ST_MTIME]))):
1406 count = ps_page_count ('%(base)s.eps' % vars ())
1407 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1408 images = tuple (images)
1412 def output_docbook (self):
1414 base = self.basename ()
1415 for image in self.get_images ():
1416 (base, ext) = os.path.splitext (image)
1417 str += output[DOCBOOK][OUTPUT] % vars ()
1418 str += self.output_print_filename (DOCBOOK)
1419 if (self.substring('inline') == 'inline'):
1420 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1422 str = '<mediaobject>' + str + '</mediaobject>'
1423 if VERBATIM in self.option_dict:
1424 verb = verbatim_html (self.verb_ly ())
1425 str = output[DOCBOOK][VERBATIM] % vars () + str
1428 def output_html (self):
1430 base = self.basename ()
1431 if self.format == HTML:
1432 str += self.output_print_filename (HTML)
1433 if VERBATIM in self.option_dict:
1434 verb = verbatim_html (self.verb_ly ())
1435 str += output[HTML][VERBATIM] % vars ()
1436 if QUOTE in self.option_dict:
1437 str = output[HTML][QUOTE] % vars ()
1439 str += output[HTML][BEFORE] % vars ()
1440 for image in self.get_images ():
1441 (base, ext) = os.path.splitext (image)
1442 alt = self.option_dict[ALT]
1443 str += output[HTML][OUTPUT] % vars ()
1444 str += output[HTML][AFTER] % vars ()
1447 def output_info (self):
1449 for image in self.get_images ():
1450 (base, ext) = os.path.splitext (image)
1452 # URG, makeinfo implicitly prepends dot to extension.
1453 # Specifying no extension is most robust.
1455 alt = self.option_dict[ALT]
1456 info_image_path = os.path.join (global_options.info_images_dir, base)
1457 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1459 base = self.basename ()
1460 str += output[self.format][OUTPUT] % vars ()
1463 def output_latex (self):
1465 base = self.basename ()
1466 if self.format == LATEX:
1467 str += self.output_print_filename (LATEX)
1468 if VERBATIM in self.option_dict:
1469 verb = self.verb_ly ()
1470 str += (output[LATEX][VERBATIM] % vars ())
1472 str += (output[LATEX][OUTPUT] % vars ())
1474 ## todo: maintain breaks
1476 breaks = self.ly ().count ("\n")
1477 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1479 if QUOTE in self.option_dict:
1480 str = output[LATEX][QUOTE] % vars ()
1483 def output_print_filename (self, format):
1485 if PRINTFILENAME in self.option_dict:
1486 base = self.basename ()
1487 filename = os.path.basename (self.substring ('filename'))
1488 str = output[format][PRINTFILENAME] % vars ()
1492 def output_texinfo (self):
1493 str = self.output_print_filename (TEXINFO)
1494 base = self.basename ()
1495 if DOCTITLE in self.option_dict:
1496 doctitle = base + '.doctitle'
1497 translated_doctitle = doctitle + document_language
1498 if os.path.exists (translated_doctitle):
1499 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
1500 elif os.path.exists (doctitle):
1501 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
1502 if TEXIDOC in self.option_dict:
1503 texidoc = base + '.texidoc'
1504 translated_texidoc = texidoc + document_language
1505 if os.path.exists (translated_texidoc):
1506 str += '@include %(translated_texidoc)s\n\n' % vars ()
1507 elif os.path.exists (texidoc):
1508 str += '@include %(texidoc)s\n\n' % vars ()
1511 if VERBATIM in self.option_dict:
1513 if ADDVERSION in self.option_dict:
1514 version = output[TEXINFO][ADDVERSION]
1515 verb = self.verb_ly ()
1516 substr = output[TEXINFO][VERBATIM] % vars ()
1517 substr += self.output_info ()
1518 if LILYQUOTE in self.option_dict:
1519 substr = output[TEXINFO][QUOTE] % {'str':substr}
1522 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1523 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1524 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1526 if QUOTE in self.option_dict:
1527 str = output[TEXINFO][QUOTE] % vars ()
1529 # need par after image
1534 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1535 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1537 class LilypondFileSnippet (LilypondSnippet):
1538 def __init__ (self, type, match, format, line_number):
1539 LilypondSnippet.__init__ (self, type, match, format, line_number)
1540 self.contents = file (find_file (self.substring ('filename'))).read ()
1544 s = re_begin_verbatim.split (s)[-1]
1545 s = re_end_verbatim.split (s)[0]
1546 if not NOGETTEXT in self.option_dict:
1547 s = verb_ly_gettext (s)
1548 if not s.endswith ('\n'):
1553 name = self.substring ('filename')
1554 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1555 % (name, self.contents))
1558 class LilyPondVersionString (Snippet):
1559 """A string that does not require extra memory."""
1560 def __init__ (self, type, match, format, line_number):
1561 Snippet.__init__ (self, type, match, format, line_number)
1563 def replacement_text (self):
1564 return output[self.format][self.type]
1567 snippet_type_to_class = {
1568 'lilypond_file': LilypondFileSnippet,
1569 'lilypond_block': LilypondSnippet,
1570 'lilypond': LilypondSnippet,
1571 'include': IncludeSnippet,
1572 'lilypondversion': LilyPondVersionString,
1575 def find_linestarts (s):
1580 i = s.find ('\n', start)
1588 nls.append (len (s))
1591 def find_toplevel_snippets (input_string, format, types):
1594 res[t] = re.compile (snippet_res[format][t])
1598 found = dict ([(t, None) for t in types])
1600 line_starts = find_linestarts (input_string)
1602 # We want to search for multiple regexes, without searching
1603 # the string multiple times for one regex.
1604 # Hence, we use earlier results to limit the string portion
1606 # Since every part of the string is traversed at most once for
1607 # every type of snippet, this is linear.
1613 if not found[type] or found[type][0] < index:
1616 m = res[type].search (input_string[index:endex])
1621 if type in snippet_type_to_class:
1622 klass = snippet_type_to_class[type]
1624 start = index + m.start ('match')
1625 line_number = line_start_idx
1626 while (line_starts[line_number] < start):
1630 snip = klass (type, m, format, line_number)
1632 found[type] = (start, snip)
1636 or found[type][0] < found[first][0])):
1641 # Limiting the search space is a cute
1642 # idea, but this *requires* to search
1643 # for possible containing blocks
1644 # first, at least as long as we do not
1645 # search for the start of blocks, but
1646 # always/directly for the entire
1647 # @block ... @end block.
1649 endex = found[first][0]
1652 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1655 while (start > line_starts[line_start_idx+1]):
1658 (start, snip) = found[first]
1659 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1660 snippets.append (snip)
1662 index = start + len (snip.match.group ('match'))
1666 def filter_pipe (input, cmd):
1667 """Pass input through cmd, and return the result."""
1669 if global_options.verbose:
1670 progress (_ ("Opening filter `%s'") % cmd)
1672 (stdin, stdout, stderr) = os.popen3 (cmd)
1674 status = stdin.close ()
1678 output = stdout.read ()
1679 status = stdout.close ()
1680 error = stderr.read ()
1684 signal = 0x0f & status
1685 if status or (not output and error):
1686 exit_status = status >> 8
1687 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1688 error (_ ("The error log is as follows:"))
1689 ly.stderr_write (error)
1690 ly.stderr_write (stderr.read ())
1693 if global_options.verbose:
1698 def system_in_directory (cmd, directory):
1699 """Execute a command in a different directory.
1701 Because of win32 compatibility, we can't simply use subprocess.
1704 current = os.getcwd()
1705 os.chdir (directory)
1706 ly.system(cmd, be_verbose=global_options.verbose,
1711 def process_snippets (cmd, snippets,
1712 format, lily_output_dir):
1713 """Run cmd on all of the .ly files from snippets."""
1718 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1719 cmd += ' --formats=png '
1720 elif format in (DOCBOOK) and '--formats' not in cmd:
1721 cmd += ' --formats=png,pdf '
1723 checksum = snippet_list_checksum (snippets)
1724 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1725 + [snip.basename() + '.ly' for snip in snippets])
1726 name = os.path.join (lily_output_dir,
1727 'snippet-names-%d.ly' % checksum)
1728 file (name, 'wb').write (contents)
1730 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1735 # Retrieve dimensions from LaTeX
1736 LATEX_INSPECTION_DOCUMENT = r'''
1740 \typeout{textwidth=\the\textwidth}
1741 \typeout{columnsep=\the\columnsep}
1742 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1746 # Do we need anything else besides `textwidth'?
1747 def get_latex_textwidth (source):
1748 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1750 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1752 ## what's a sensible default?
1755 preamble = source[:m.start (0)]
1756 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1758 (handle, tmpfile) = tempfile.mkstemp('.tex')
1759 logfile = os.path.splitext (tmpfile)[0] + '.log'
1760 logfile = os.path.split (logfile)[1]
1762 tmp_handle = os.fdopen (handle,'w')
1763 tmp_handle.write (latex_document)
1766 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1767 be_verbose=global_options.verbose)
1768 parameter_string = file (logfile).read()
1774 m = re.search ('columns=([0-9.]+)', parameter_string)
1776 columns = int (m.group (1))
1779 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
1781 columnsep = float (m.group (1))
1784 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
1786 textwidth = float (m.group (1))
1788 textwidth = (textwidth - columnsep) / columns
1792 def modify_preamble (chunk):
1793 str = chunk.replacement_text ()
1794 if (re.search (r"\\begin *{document}", str)
1795 and not re.search ("{graphic[sx]", str)):
1796 str = re.sub (r"\\begin{document}",
1797 r"\\usepackage{graphics}" + '\n'
1798 + r"\\begin{document}",
1800 chunk.override_text = str
1805 # TEXINFO: '.texinfo',
1811 class CompileError(Exception):
1814 def snippet_list_checksum (snippets):
1815 return hash (' '.join([l.basename() for l in snippets]))
1817 def write_file_map (lys, name):
1818 snippet_map = file (os.path.join (
1819 global_options.lily_output_dir,
1820 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1822 snippet_map.write ("""
1823 #(define version-seen #t)
1824 #(define output-empty-score-list #f)
1825 #(ly:add-file-name-alist '(%s
1827 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1830 def split_output_files(directory):
1831 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1833 Return value is a set of strings.
1836 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1837 base_subdir = os.path.split (subdir)[1]
1838 sub_files = [os.path.join (base_subdir, name)
1839 for name in os.listdir (subdir)]
1843 def do_process_cmd (chunks, input_name, options):
1844 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1846 output_files = split_output_files (options.lily_output_dir)
1847 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1849 write_file_map (outdated, input_name)
1850 progress (_ ("Writing snippets..."))
1851 for snippet in outdated:
1856 progress (_ ("Processing..."))
1858 process_snippets (options.process_cmd, outdated,
1859 options.format, options.lily_output_dir)
1862 progress (_ ("All snippets are up to date..."))
1864 if options.lily_output_dir != options.output_dir:
1865 output_files = split_output_files (options.lily_output_dir)
1866 for snippet in snippets:
1867 snippet.link_all_output_files (options.lily_output_dir,
1875 # Format guessing data
1884 '.texinfo': TEXINFO,
1889 def guess_format (input_filename):
1891 e = os.path.splitext (input_filename)[1]
1894 format = ext2format[e]
1896 error (_ ("cannot determine format for: %s"
1901 def write_if_updated (file_name, lines):
1903 f = file (file_name)
1905 new_str = ''.join (lines)
1906 if oldstr == new_str:
1907 progress (_ ("%s is up to date.") % file_name)
1910 # this prevents make from always rerunning lilypond-book:
1911 # output file must be touched in order to be up to date
1912 os.utime (file_name, None)
1917 output_dir = os.path.dirname (file_name)
1918 if not os.path.exists (output_dir):
1919 os.makedirs (output_dir)
1921 progress (_ ("Writing `%s'...") % file_name)
1922 file (file_name, 'w').writelines (lines)
1926 def note_input_file (name, inputs=[]):
1927 ## hack: inputs is mutable!
1928 inputs.append (name)
1931 def samefile (f1, f2):
1933 return os.path.samefile (f1, f2)
1934 except AttributeError: # Windoze
1935 f1 = re.sub ("//*", "/", f1)
1936 f2 = re.sub ("//*", "/", f2)
1939 def do_file (input_filename, included=False):
1941 if not input_filename or input_filename == '-':
1942 in_handle = sys.stdin
1943 input_fullname = '<stdin>'
1945 if os.path.exists (input_filename):
1946 input_fullname = input_filename
1947 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1948 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1950 input_fullname = find_file (input_filename)
1952 note_input_file (input_fullname)
1953 in_handle = file (input_fullname)
1955 if input_filename == '-':
1956 input_base = 'stdin'
1958 input_base = os.path.splitext (input_filename)[0]
1960 input_base = os.path.basename (
1961 os.path.splitext (input_filename)[0])
1963 # don't complain when global_options.output_dir is existing
1964 if not global_options.output_dir:
1965 global_options.output_dir = os.getcwd()
1967 global_options.output_dir = os.path.abspath(global_options.output_dir)
1969 if not os.path.isdir (global_options.output_dir):
1970 os.mkdir (global_options.output_dir, 0777)
1971 os.chdir (global_options.output_dir)
1973 output_filename = os.path.join(global_options.output_dir,
1974 input_base + format2ext[global_options.format])
1975 if (os.path.exists (input_filename)
1976 and os.path.exists (output_filename)
1977 and samefile (output_filename, input_fullname)):
1979 _ ("Output would overwrite input file; use --output."))
1983 progress (_ ("Reading %s...") % input_fullname)
1984 source = in_handle.read ()
1987 set_default_options (source, default_ly_options, global_options.format)
1990 # FIXME: Containing blocks must be first, see
1991 # find_toplevel_snippets.
1993 'multiline_comment',
1997 'singleline_comment',
2003 progress (_ ("Dissecting..."))
2004 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
2006 if global_options.format == LATEX:
2008 if (c.is_plain () and
2009 re.search (r"\\begin *{document}", c.replacement_text())):
2014 if global_options.filter_cmd:
2015 write_if_updated (output_filename,
2016 [c.filter_text () for c in chunks])
2017 elif global_options.process_cmd:
2018 do_process_cmd (chunks, input_fullname, global_options)
2019 progress (_ ("Compiling %s...") % output_filename)
2021 write_if_updated (output_filename,
2022 [s.replacement_text ()
2025 def process_include (snippet):
2026 os.chdir (original_dir)
2027 name = snippet.substring ('filename')
2028 progress (_ ("Processing include: %s") % name)
2030 return do_file (name, included=True)
2032 include_chunks = map (process_include,
2033 filter (lambda x: isinstance (x, IncludeSnippet),
2036 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2038 except CompileError:
2039 os.chdir (original_dir)
2040 progress (_ ("Removing `%s'") % output_filename)
2045 global global_options
2047 opt_parser = get_option_parser()
2048 (global_options, args) = opt_parser.parse_args ()
2049 if global_options.format in ('texi-html', 'texi'):
2050 global_options.format = TEXINFO
2052 global_options.include_path = map (os.path.abspath, global_options.include_path)
2054 if global_options.warranty:
2057 if not args or len (args) > 1:
2058 opt_parser.print_help ()
2064 # FIXME: 85 lines of `main' macramee??
2065 files = do_options ()
2067 basename = os.path.splitext (files[0])[0]
2068 basename = os.path.split (basename)[1]
2070 if not global_options.format:
2071 global_options.format = guess_format (files[0])
2074 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2077 if global_options.process_cmd == '':
2078 global_options.process_cmd = (lilypond_binary
2079 + ' --formats=%s -dbackend=eps ' % formats)
2081 if global_options.process_cmd:
2082 includes = global_options.include_path
2083 if global_options.lily_output_dir:
2084 # This must be first, so lilypond prefers to read .ly
2085 # files in the other lybookdb dir.
2086 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2087 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2090 if global_options.format in (TEXINFO, LATEX):
2091 ## prevent PDF from being switched on by default.
2092 global_options.process_cmd += ' --formats=eps '
2093 if global_options.create_pdf:
2094 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2096 if global_options.verbose:
2097 global_options.process_cmd += " --verbose "
2099 if global_options.padding_mm:
2100 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2102 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2104 if global_options.lily_output_dir:
2105 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2106 if not os.path.isdir (global_options.lily_output_dir):
2107 os.makedirs (global_options.lily_output_dir)
2109 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2114 chunks = do_file (files[0])
2115 except CompileError:
2118 inputs = note_input_file ('')
2121 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2122 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2123 final_output_file = os.path.join (global_options.output_dir,
2125 + '.%s' % global_options.format)
2127 os.chdir (original_dir)
2128 file (dep_file, 'w').write ('%s: %s'
2129 % (final_output_file, ' '.join (inputs)))
2131 if __name__ == '__main__':