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
48 ly.require_python_version ()
51 program_version = '@TOPLEVEL_VERSION@'
52 program_name = os.path.basename (sys.argv[0])
54 # Check if program_version contains @ characters. This will be the case if
55 # the .py file is called directly while building the lilypond documentation.
56 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
57 # makefiles and use its value.
58 at_re = re.compile (r'@')
59 if at_re.match (program_version):
60 if os.environ.has_key('LILYPOND_VERSION'):
61 program_version = os.environ['LILYPOND_VERSION']
63 program_version = "unknown"
65 original_dir = os.getcwd ()
69 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
73 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
74 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
75 $ lilypond-book --process='lilypond -I include' %(BOOK)s
76 ''' % {'BOOK': _ ("BOOK")})
78 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
79 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
81 ################################################################
83 if global_options.verbose:
84 raise Exception (_ ('Exiting (%d)...') % i)
89 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
91 progress = ly.progress
94 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
97 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
99 def ps_page_count (ps_name):
100 header = file (ps_name).read (1024)
101 m = re.search ('\n%%Pages: ([0-9]+)', header)
103 return int (m.group (1))
108 ly.encoded_write (sys.stdout, '''
115 ''' % ( _ ('Copyright (c) %s by') % '2001--2008',
117 _ ("Distributed under terms of the GNU General Public License."),
118 _ ("It comes with NO WARRANTY.")))
120 def get_option_parser ():
121 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
122 description=help_summary,
123 add_help_option=False)
125 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
128 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
131 p.add_option ('-f', '--format',
132 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
133 metavar=_ ("FORMAT"),
136 p.add_option("-h", "--help",
138 help=_ ("show this help and exit"))
140 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
142 action='append', dest='include_path',
143 default=[os.path.abspath (os.getcwd ())])
145 p.add_option ('--info-images-dir',
146 help=_ ("format Texinfo output so that Info will "
147 "look for images of music in DIR"),
149 action='store', dest='info_images_dir',
152 p.add_option ('--latex-program',
153 help=_ ("run executable PROG instead of latex"),
155 action='store', dest='latex_program',
158 p.add_option ('--left-padding',
161 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
165 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
167 action='store', dest='output_dir',
170 p.add_option ('--skip-lily-check',
171 help=_ ("do not fail if no lilypond output is found"),
173 action='store_true', dest='skip_lilypond_run',
176 p.add_option ('--skip-png-check',
177 help=_ ("do not fail if no PNG images are found for EPS files"),
179 action='store_true', dest='skip_png_check',
182 p.add_option ('--lily-output-dir',
183 help=_ ("write lily-XXX files to DIR, link into --output dir"),
185 action='store', dest='lily_output_dir',
188 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
189 help = _ ("process ly_files using COMMAND FILE..."),
191 dest='process_cmd', default='')
193 p.add_option ('--pdf',
196 help=_ ("create PDF files for use with PDFTeX"),
199 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
204 p.version = "@TOPLEVEL_VERSION@"
205 p.add_option("--version",
207 help=_ ("show version number and exit"))
209 p.add_option ('-w', '--warranty',
210 help=_ ("show warranty and copyright"),
212 p.add_option_group ('',
214 _ ("Report bugs via")
215 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
218 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
220 # If we are called with full path, try to use lilypond binary
221 # installed in the same path; this is needed in GUB binaries, where
222 # @bindir is always different from the installed binary path.
223 if 'bindir' in globals () and bindir:
224 lilypond_binary = os.path.join (bindir, 'lilypond')
226 # Only use installed binary when we are installed too.
227 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
228 lilypond_binary = 'lilypond'
230 global_options = None
233 default_ly_options = { 'alt': "[image of music]" }
235 document_language = ''
238 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
240 ADDVERSION = 'addversion'
244 EXAMPLEINDENT = 'exampleindent'
246 FRAGMENT = 'fragment'
252 LINE_WIDTH = 'line-width'
253 LILYQUOTE = 'lilyquote'
254 NOFRAGMENT = 'nofragment'
255 NOINDENT = 'noindent'
257 NORAGGED_RIGHT = 'noragged-right'
261 OUTPUTIMAGE = 'outputimage'
264 PREAMBLE = 'preamble'
265 PRINTFILENAME = 'printfilename'
267 RAGGED_RIGHT = 'ragged-right'
268 RELATIVE = 'relative'
269 STAFFSIZE = 'staffsize'
270 DOCTITLE = 'doctitle'
273 VERBATIM = 'verbatim'
274 VERSION = 'lilypondversion'
275 FONTLOAD = 'fontload'
276 FILENAME = 'filename'
280 # NOTIME has no opposite so it isn't part of this dictionary.
281 # NOQUOTE is used internally only.
283 NOFRAGMENT: FRAGMENT,
288 # Recognize special sequences in the input.
290 # (?P<name>regex) -- Assign result of REGEX to NAME.
291 # *? -- Match non-greedily.
292 # (?m) -- Multiline regex: Make ^ and $ match at each line.
293 # (?s) -- Make the dot match all characters including newline.
294 # (?x) -- Ignore whitespace in patterns.
305 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
310 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
315 <(?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>)''',
321 (?P<code><!--\s.*?!-->)
324 'singleline_comment':
345 (\s*(?P<options>.*?)\s*:)?\s*
353 \s*(?P<options>.*?)\s*
362 \s*(?P<options>.*?)\s*
364 \s*(?P<filename>.*?)\s*
371 (?P<code><!--\s.*?!-->)
374 'singleline_comment':
380 (?P<code><pre>.*?</pre>))''',
386 (?P<code><pre>\s.*?</pre>\s))''',
391 <lilypondversion\s*/>)''',
410 \s*(?P<options>.*?)\s*
421 \s*(?P<options>.*?)\s*
425 \\end\s*{lilypond})''',
433 \s*(?P<options>.*?)\s*
441 'singleline_comment':
464 \\end\s*{verbatim}))''',
469 \\lilypondversion)[^a-zA-Z]''',
479 (?P<filename>\S+))''',
483 ^[^\n]*?(?!@c\s+)[^\n]*?
487 \s*(?P<options>.*?)\s*
497 \s*(?P<options>.*?)\s*
500 ^@end\s+lilypond)\s''',
507 \s*(?P<options>.*?)\s*
518 @end\s+ignore))\s''',
520 'singleline_comment':
525 @c([ \t][^\n]*|)\n))''',
527 # Don't do this: It interferes with @code{@{}.
528 # 'verb': r'''(?P<code>@code{.*?})''',
536 @end\s+example\s))''',
541 @lilypondversion)[^a-zA-Z]''',
551 'intertext': r',?\s*intertext=\".*?\"',
555 'intertext': r',?\s*intertext=\".*?\"',
560 'intertext': r',?\s*intertext=\".*?\"',
561 'option_sep': '\s*,\s*',
565 'intertext': r',?\s*intertext=\".*?\"',
566 'option_sep': '\s*,\s*',
570 # Options without a pattern in ly_options.
590 RELATIVE: r'''\relative c%(relative_quotes)s''',
595 INDENT: r'''indent = %(indent)s''',
597 LINE_WIDTH: r'''line-width = %(line-width)s''',
599 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
601 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
603 RAGGED_RIGHT: r'''ragged-right = ##t''',
605 NORAGGED_RIGHT: r'''ragged-right = ##f''',
607 PACKED: r'''packed = ##t''',
619 \remove "Time_signature_engraver"
625 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
632 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
635 <imageobject role="latex">
636 <imagedata fileref="%(base)s.pdf" format="PDF"/>
638 <imageobject role="html">
639 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
641 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
643 VERSION: program_version,
645 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
649 FILTER: r'''<lilypond %(options)s>
659 <a href="%(base)s.ly">''',
663 border="0" src="%(image)s" alt="%(alt)s">''',
665 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
667 QUOTE: r'''<blockquote>
675 VERSION: program_version,
682 \ifx\preLilyPondExample \undefined%%
685 \preLilyPondExample%%
687 \def\lilypondbook{}%%
688 \input %(base)s-systems.tex%%
689 \ifx\postLilyPondExample \undefined%%
692 \postLilyPondExample%%
696 PRINTFILENAME: '''\\texttt{%(filename)s}
699 QUOTE: r'''\begin{quotation}%(str)s
702 VERBATIM: r'''\noindent
703 \begin{verbatim}%(verb)s\end{verbatim}''',
705 VERSION: program_version,
707 FILTER: r'''\begin{lilypond}[%(options)s]
714 FILTER: r'''@lilypond[%(options)s]
720 @include %(base)s-systems.texi
724 OUTPUTIMAGE: r'''@noindent
726 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
730 <a href="%(base)s.ly">
732 border="0" src="%(image)s" alt="%(alt)s">
740 <a href="%(base)s.ly">
748 QUOTE: r'''@quotation
749 %(str)s@end quotation
756 VERBATIM: r'''@exampleindent 0
758 %(verb)s@end verbatim
761 VERSION: program_version,
763 ADDVERSION: r'''@example
764 \version @w{"@version{}"}
771 # Maintain line numbers.
776 for f in [HTML, LATEX]:
777 for s in (QUOTE, VERBATIM):
778 output[f][s] = output[f][s].replace("\n"," ")
781 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
782 %%%% Options: [%(option_string)s]
783 \\include "lilypond-book-preamble.ly"
786 %% ****************************************************************
787 %% Start cut-&-pastable-section
788 %% ****************************************************************
793 #(define dump-extents #t)
794 %(font_dump_setting)s
796 force-assignment = #""
797 line-width = #(- line-width (* mm %(padding_mm)f))
810 %% ****************************************************************
811 %% ly snippet contents follows:
812 %% ****************************************************************
816 %% ****************************************************************
818 %% ****************************************************************
825 %% ****************************************************************
827 %% ****************************************************************
831 %% ****************************************************************
833 %% ****************************************************************
836 texinfo_line_widths = {
837 '@afourpaper': '160\\mm',
838 '@afourwide': '6.5\\in',
839 '@afourlatex': '150\\mm',
840 '@smallbook': '5\\in',
841 '@letterpaper': '6\\in',
844 def classic_lilypond_book_compatibility (key, value):
845 if key == 'singleline' and value == None:
846 return (RAGGED_RIGHT, None)
848 m = re.search ('relative\s*([-0-9])', key)
850 return ('relative', m.group (1))
852 m = re.match ('([0-9]+)pt', key)
854 return ('staffsize', m.group (1))
856 if key == 'indent' or key == 'line-width':
857 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
859 f = float (m.group (1))
860 return (key, '%f\\%s' % (f, m.group (2)))
864 def find_file (name, raise_error=True):
865 for i in global_options.include_path:
866 full = os.path.join (i, name)
867 if os.path.exists (full):
871 error (_ ("file not found: %s") % name + '\n')
875 def verbatim_html (s):
876 return re.sub ('>', '>',
878 re.sub ('&', '&', s)))
880 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
881 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
882 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
883 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
885 def ly_comment_gettext (t, m):
886 return m.group (1) + t (m.group (2))
888 def verb_ly_gettext (s):
889 if not document_language:
892 t = langdefs.translation[document_language]
896 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
898 for v in ly_var_def_re.findall (s):
899 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
900 "\\1" + t (v) + "\\2",
902 for id in ly_context_id_re.findall (s):
903 s = re.sub (r'(\s+|")%s(\s+|")' % id,
904 "\\1" + t (id) + "\\2",
908 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
909 def set_default_options (source, default_ly_options, format):
910 global document_language
911 if LINE_WIDTH not in default_ly_options:
913 textwidth = get_latex_textwidth (source)
914 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
915 elif format == TEXINFO:
916 m = texinfo_lang_re.search (source)
917 if m and not m.group (1).startswith ('en'):
918 document_language = m.group (1)
920 document_language = ''
921 for regex in texinfo_line_widths:
922 # FIXME: @layout is usually not in
925 # \input texinfo @c -*-texinfo-*-
927 # Bluntly search first K items of
929 # s = chunks[0].replacement_text ()
930 if re.search (regex, source[:1024]):
931 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
935 def replacement_text (self):
938 def filter_text (self):
939 return self.replacement_text ()
944 class Substring (Chunk):
945 """A string that does not require extra memory."""
946 def __init__ (self, source, start, end, line_number):
950 self.line_number = line_number
951 self.override_text = None
956 def replacement_text (self):
957 if self.override_text:
958 return self.override_text
960 return self.source[self.start:self.end]
962 class Snippet (Chunk):
963 def __init__ (self, type, match, format, line_number):
967 self.option_dict = {}
969 self.line_number = line_number
971 def replacement_text (self):
972 return self.match.group ('match')
974 def substring (self, s):
975 return self.match.group (s)
978 return `self.__class__` + ' type = ' + self.type
980 class IncludeSnippet (Snippet):
981 def processed_filename (self):
982 f = self.substring ('filename')
983 return os.path.splitext (f)[0] + format2ext[self.format]
985 def replacement_text (self):
986 s = self.match.group ('match')
987 f = self.substring ('filename')
989 return re.sub (f, self.processed_filename (), s)
991 class LilypondSnippet (Snippet):
992 def __init__ (self, type, match, format, line_number):
993 Snippet.__init__ (self, type, match, format, line_number)
994 os = match.group ('options')
995 self.do_options (os, self.type)
998 return verb_ly_gettext (self.substring ('code'))
1001 contents = self.substring ('code')
1002 return ('\\sourcefileline %d\n%s'
1003 % (self.line_number - 1, contents))
1008 return self.compose_ly (s)
1011 def split_options (self, option_string):
1013 if self.format == HTML:
1014 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1016 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1020 return re.split (format_res[self.format]['option_sep'],
1024 def do_options (self, option_string, type):
1025 self.option_dict = {}
1027 options = self.split_options (option_string)
1029 for option in options:
1031 (key, value) = re.split ('\s*=\s*', option)
1032 self.option_dict[key] = value
1034 if option in no_options:
1035 if no_options[option] in self.option_dict:
1036 del self.option_dict[no_options[option]]
1038 self.option_dict[option] = None
1040 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1041 no_line_width_value = 0
1043 # If LINE_WIDTH is used without parameter, set it to default.
1044 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1045 no_line_width_value = 1
1046 del self.option_dict[LINE_WIDTH]
1048 for k in default_ly_options:
1049 if k not in self.option_dict:
1050 self.option_dict[k] = default_ly_options[k]
1052 # RELATIVE does not work without FRAGMENT;
1053 # make RELATIVE imply FRAGMENT
1054 has_relative = self.option_dict.has_key (RELATIVE)
1055 if has_relative and not self.option_dict.has_key (FRAGMENT):
1056 self.option_dict[FRAGMENT] = None
1058 if not has_line_width:
1059 if type == 'lilypond' or FRAGMENT in self.option_dict:
1060 self.option_dict[RAGGED_RIGHT] = None
1062 if type == 'lilypond':
1063 if LINE_WIDTH in self.option_dict:
1064 del self.option_dict[LINE_WIDTH]
1066 if RAGGED_RIGHT in self.option_dict:
1067 if LINE_WIDTH in self.option_dict:
1068 del self.option_dict[LINE_WIDTH]
1070 if QUOTE in self.option_dict or type == 'lilypond':
1071 if LINE_WIDTH in self.option_dict:
1072 del self.option_dict[LINE_WIDTH]
1074 if not INDENT in self.option_dict:
1075 self.option_dict[INDENT] = '0\\mm'
1077 # The QUOTE pattern from ly_options only emits the `line-width'
1079 if has_line_width and QUOTE in self.option_dict:
1080 if no_line_width_value:
1081 del self.option_dict[LINE_WIDTH]
1083 del self.option_dict[QUOTE]
1085 def compose_ly (self, code):
1086 if FRAGMENT in self.option_dict:
1094 # The original concept of the `exampleindent' option is broken.
1095 # It is not possible to get a sane value for @exampleindent at all
1096 # without processing the document itself. Saying
1104 # causes ugly results with the DVI backend of texinfo since the
1105 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1106 # value). Executing the above code changes the environment
1107 # indentation to an unknown value because we don't know the amount
1108 # of 1em in advance since it is font-dependent. Modifying
1109 # @exampleindent in the middle of a document is simply not
1110 # supported within texinfo.
1112 # As a consequence, the only function of @exampleindent is now to
1113 # specify the amount of indentation for the `quote' option.
1115 # To set @exampleindent locally to zero, we use the @format
1116 # environment for non-quoted snippets.
1117 override[EXAMPLEINDENT] = r'0.4\in'
1118 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1119 override.update (default_ly_options)
1122 for (key, value) in self.option_dict.items ():
1124 option_list.append (key)
1126 option_list.append (key + '=' + value)
1127 option_string = ','.join (option_list)
1130 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1131 for a in compose_types:
1132 compose_dict[a] = []
1134 for (key, value) in self.option_dict.items ():
1135 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1139 _ ("deprecated ly-option used: %s=%s") % (key, value))
1141 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1144 _ ("deprecated ly-option used: %s") % key)
1146 _ ("compatibility mode translation: %s") % c_key)
1148 (key, value) = (c_key, c_value)
1151 override[key] = value
1153 if not override.has_key (key):
1154 override[key] = None
1157 for type in compose_types:
1158 if ly_options[type].has_key (key):
1159 compose_dict[type].append (ly_options[type][key])
1163 if not found and key not in simple_options:
1164 warning (_ ("ignoring unknown ly option: %s") % key)
1167 if RELATIVE in override and override[RELATIVE]:
1168 relative = int (override[RELATIVE])
1170 relative_quotes = ''
1174 relative_quotes += ',' * (- relative)
1176 relative_quotes += "'" * relative
1178 paper_string = '\n '.join (compose_dict[PAPER]) % override
1179 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1180 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1181 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1182 padding_mm = global_options.padding_mm
1183 font_dump_setting = ''
1184 if FONTLOAD in self.option_dict:
1185 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1187 d = globals().copy()
1189 return (PREAMBLE_LY + body) % d
1191 def get_checksum (self):
1192 if not self.checksum:
1193 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1195 ## let's not create too long names.
1196 self.checksum = hash.hexdigest ()[:10]
1198 return self.checksum
1200 def basename (self):
1201 cs = self.get_checksum ()
1202 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1205 def write_ly (self):
1206 base = self.basename ()
1207 path = os.path.join (global_options.lily_output_dir, base)
1208 directory = os.path.split(path)[0]
1209 if not os.path.isdir (directory):
1210 os.makedirs (directory)
1211 out = file (path + '.ly', 'w')
1212 out.write (self.full_ly ())
1213 file (path + '.txt', 'w').write ('image of music')
1215 def relevant_contents (self, ly):
1216 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1218 def link_all_output_files (self, output_dir, output_dir_files, destination):
1219 existing, missing = self.all_output_files (output_dir, output_dir_files)
1221 print '\nMissing', missing
1222 raise CompileError(self.basename())
1223 for name in existing:
1225 os.unlink (os.path.join (destination, name))
1229 src = os.path.join (output_dir, name)
1230 dst = os.path.join (destination, name)
1231 dst_path = os.path.split(dst)[0]
1232 if not os.path.isdir (dst_path):
1233 os.makedirs (dst_path)
1237 def all_output_files (self, output_dir, output_dir_files):
1238 """Return all files generated in lily_output_dir, a set.
1240 output_dir_files is the list of files in the output directory.
1244 base = self.basename()
1245 full = os.path.join (output_dir, base)
1246 def consider_file (name):
1247 if name in output_dir_files:
1250 def require_file (name):
1251 if name in output_dir_files:
1256 # UGH - junk global_options
1257 skip_lily = global_options.skip_lilypond_run
1258 for required in [base + '.ly',
1260 require_file (required)
1262 require_file (base + '-systems.count')
1264 if 'ddump-profile' in global_options.process_cmd:
1265 require_file (base + '.profile')
1266 if 'dseparate-log-file' in global_options.process_cmd:
1267 require_file (base + '.log')
1269 map (consider_file, [base + '.tex',
1273 base + '-systems.texi',
1274 base + '-systems.tex',
1275 base + '-systems.pdftexi'])
1276 if document_language:
1278 [base + '.texidoc' + document_language,
1279 base + '.doctitle' + document_language])
1281 # UGH - junk global_options
1282 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1283 and not global_options.skip_png_check):
1284 page_count = ps_page_count (full + '.eps')
1286 require_file (base + '.png')
1288 for page in range (1, page_count + 1):
1289 require_file (base + '-page%d.png' % page)
1292 if not skip_lily and not missing:
1293 system_count = int(file (full + '-systems.count').read())
1295 for number in range(1, system_count + 1):
1296 systemfile = '%s-%d' % (base, number)
1297 require_file (systemfile + '.eps')
1298 consider_file (systemfile + '.pdf')
1300 # We can't require signatures, since books and toplevel
1301 # markups do not output a signature.
1302 if 'ddump-signature' in global_options.process_cmd:
1303 consider_file (systemfile + '.signature')
1306 return (result, missing)
1308 def is_outdated (self, output_dir, current_files):
1309 found, missing = self.all_output_files (output_dir, current_files)
1312 def filter_text (self):
1313 """Run snippet bodies through a command (say: convert-ly).
1315 This functionality is rarely used, and this code must have bitrot.
1317 code = self.substring ('code')
1318 s = filter_pipe (code, global_options.filter_cmd)
1321 'options': self.match.group ('options')
1324 return output[self.format][FILTER] % d
1326 def replacement_text (self):
1327 func = LilypondSnippet.__dict__['output_' + self.format]
1330 def get_images (self):
1331 base = self.basename ()
1333 single = '%(base)s.png' % vars ()
1334 multiple = '%(base)s-page1.png' % vars ()
1336 if (os.path.exists (multiple)
1337 and (not os.path.exists (single)
1338 or (os.stat (multiple)[stat.ST_MTIME]
1339 > os.stat (single)[stat.ST_MTIME]))):
1340 count = ps_page_count ('%(base)s.eps' % vars ())
1341 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1342 images = tuple (images)
1346 def output_docbook (self):
1348 base = self.basename ()
1349 for image in self.get_images ():
1350 (base, ext) = os.path.splitext (image)
1351 str += output[DOCBOOK][OUTPUT] % vars ()
1352 str += self.output_print_filename (DOCBOOK)
1353 if (self.substring('inline') == 'inline'):
1354 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1356 str = '<mediaobject>' + str + '</mediaobject>'
1357 if VERBATIM in self.option_dict:
1358 verb = verbatim_html (self.verb_ly ())
1359 str = output[DOCBOOK][VERBATIM] % vars () + str
1362 def output_html (self):
1364 base = self.basename ()
1365 if self.format == HTML:
1366 str += self.output_print_filename (HTML)
1367 if VERBATIM in self.option_dict:
1368 verb = verbatim_html (self.verb_ly ())
1369 str += output[HTML][VERBATIM] % vars ()
1370 if QUOTE in self.option_dict:
1371 str = output[HTML][QUOTE] % vars ()
1373 str += output[HTML][BEFORE] % vars ()
1374 for image in self.get_images ():
1375 (base, ext) = os.path.splitext (image)
1376 alt = self.option_dict[ALT]
1377 str += output[HTML][OUTPUT] % vars ()
1378 str += output[HTML][AFTER] % vars ()
1381 def output_info (self):
1383 for image in self.get_images ():
1384 (base, ext) = os.path.splitext (image)
1386 # URG, makeinfo implicitly prepends dot to extension.
1387 # Specifying no extension is most robust.
1389 alt = self.option_dict[ALT]
1390 info_image_path = os.path.join (global_options.info_images_dir, base)
1391 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1393 base = self.basename ()
1394 str += output[self.format][OUTPUT] % vars ()
1397 def output_latex (self):
1399 base = self.basename ()
1400 if self.format == LATEX:
1401 str += self.output_print_filename (LATEX)
1402 if VERBATIM in self.option_dict:
1403 verb = self.verb_ly ()
1404 str += (output[LATEX][VERBATIM] % vars ())
1406 str += (output[LATEX][OUTPUT] % vars ())
1408 ## todo: maintain breaks
1410 breaks = self.ly ().count ("\n")
1411 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1413 if QUOTE in self.option_dict:
1414 str = output[LATEX][QUOTE] % vars ()
1417 def output_print_filename (self, format):
1419 if PRINTFILENAME in self.option_dict:
1420 base = self.basename ()
1421 filename = os.path.basename (self.substring ('filename'))
1422 str = output[format][PRINTFILENAME] % vars ()
1426 def output_texinfo (self):
1427 str = self.output_print_filename (TEXINFO)
1428 base = self.basename ()
1429 if DOCTITLE in self.option_dict:
1430 doctitle = base + '.doctitle'
1431 translated_doctitle = doctitle + document_language
1432 if os.path.exists (translated_doctitle):
1433 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1434 elif os.path.exists (doctitle):
1435 str += '@lydoctitle %s\n' % open (doctitle).read ()
1436 if TEXIDOC in self.option_dict:
1437 texidoc = base + '.texidoc'
1438 translated_texidoc = texidoc + document_language
1439 if os.path.exists (translated_texidoc):
1440 str += '@include %(translated_texidoc)s\n\n' % vars ()
1441 elif os.path.exists (texidoc):
1442 str += '@include %(texidoc)s\n\n' % vars ()
1445 if VERBATIM in self.option_dict:
1447 if ADDVERSION in self.option_dict:
1448 version = output[TEXINFO][ADDVERSION]
1449 verb = self.verb_ly ()
1450 substr = output[TEXINFO][VERBATIM] % vars ()
1451 substr += self.output_info ()
1452 if LILYQUOTE in self.option_dict:
1453 substr = output[TEXINFO][QUOTE] % {'str':substr}
1456 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1457 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1458 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1460 if QUOTE in self.option_dict:
1461 str = output[TEXINFO][QUOTE] % vars ()
1463 # need par after image
1468 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1469 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1471 class LilypondFileSnippet (LilypondSnippet):
1472 def __init__ (self, type, match, format, line_number):
1473 LilypondSnippet.__init__ (self, type, match, format, line_number)
1474 self.contents = file (find_file (self.substring ('filename'))).read ()
1478 s = re_begin_verbatim.split (s)[-1]
1479 s = re_end_verbatim.split (s)[0]
1480 return verb_ly_gettext (s)
1483 name = self.substring ('filename')
1484 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1485 % (name, self.contents))
1488 class LilyPondVersionString (Snippet):
1489 """A string that does not require extra memory."""
1490 def __init__ (self, type, match, format, line_number):
1491 Snippet.__init__ (self, type, match, format, line_number)
1493 def replacement_text (self):
1494 return output[self.format][self.type]
1497 snippet_type_to_class = {
1498 'lilypond_file': LilypondFileSnippet,
1499 'lilypond_block': LilypondSnippet,
1500 'lilypond': LilypondSnippet,
1501 'include': IncludeSnippet,
1502 'lilypondversion': LilyPondVersionString,
1505 def find_linestarts (s):
1510 i = s.find ('\n', start)
1518 nls.append (len (s))
1521 def find_toplevel_snippets (input_string, format, types):
1524 res[t] = re.compile (snippet_res[format][t])
1528 found = dict ([(t, None) for t in types])
1530 line_starts = find_linestarts (input_string)
1532 # We want to search for multiple regexes, without searching
1533 # the string multiple times for one regex.
1534 # Hence, we use earlier results to limit the string portion
1536 # Since every part of the string is traversed at most once for
1537 # every type of snippet, this is linear.
1543 if not found[type] or found[type][0] < index:
1546 m = res[type].search (input_string[index:endex])
1551 if type in snippet_type_to_class:
1552 klass = snippet_type_to_class[type]
1554 start = index + m.start ('match')
1555 line_number = line_start_idx
1556 while (line_starts[line_number] < start):
1560 snip = klass (type, m, format, line_number)
1562 found[type] = (start, snip)
1566 or found[type][0] < found[first][0])):
1571 # Limiting the search space is a cute
1572 # idea, but this *requires* to search
1573 # for possible containing blocks
1574 # first, at least as long as we do not
1575 # search for the start of blocks, but
1576 # always/directly for the entire
1577 # @block ... @end block.
1579 endex = found[first][0]
1582 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1585 while (start > line_starts[line_start_idx+1]):
1588 (start, snip) = found[first]
1589 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1590 snippets.append (snip)
1592 index = start + len (snip.match.group ('match'))
1596 def filter_pipe (input, cmd):
1597 """Pass input through cmd, and return the result."""
1599 if global_options.verbose:
1600 progress (_ ("Opening filter `%s'") % cmd)
1602 (stdin, stdout, stderr) = os.popen3 (cmd)
1604 status = stdin.close ()
1608 output = stdout.read ()
1609 status = stdout.close ()
1610 error = stderr.read ()
1614 signal = 0x0f & status
1615 if status or (not output and error):
1616 exit_status = status >> 8
1617 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1618 error (_ ("The error log is as follows:"))
1619 ly.stderr_write (error)
1620 ly.stderr_write (stderr.read ())
1623 if global_options.verbose:
1628 def system_in_directory (cmd, directory):
1629 """Execute a command in a different directory.
1631 Because of win32 compatibility, we can't simply use subprocess.
1634 current = os.getcwd()
1635 os.chdir (directory)
1636 ly.system(cmd, be_verbose=global_options.verbose,
1641 def process_snippets (cmd, snippets,
1642 format, lily_output_dir):
1643 """Run cmd on all of the .ly files from snippets."""
1648 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1649 cmd += ' --formats=png '
1650 elif format in (DOCBOOK) and '--formats' not in cmd:
1651 cmd += ' --formats=png,pdf '
1653 checksum = snippet_list_checksum (snippets)
1654 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1655 + [snip.basename() + '.ly' for snip in snippets])
1656 name = os.path.join (lily_output_dir,
1657 'snippet-names-%d.ly' % checksum)
1658 file (name, 'wb').write (contents)
1660 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1665 # Retrieve dimensions from LaTeX
1666 LATEX_INSPECTION_DOCUMENT = r'''
1670 \typeout{textwidth=\the\textwidth}
1671 \typeout{columnsep=\the\columnsep}
1672 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1676 # Do we need anything else besides `textwidth'?
1677 def get_latex_textwidth (source):
1678 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1680 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1682 ## what's a sensible default?
1685 preamble = source[:m.start (0)]
1686 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1688 (handle, tmpfile) = tempfile.mkstemp('.tex')
1689 logfile = os.path.splitext (tmpfile)[0] + '.log'
1690 logfile = os.path.split (logfile)[1]
1692 tmp_handle = os.fdopen (handle,'w')
1693 tmp_handle.write (latex_document)
1696 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1697 be_verbose=global_options.verbose)
1698 parameter_string = file (logfile).read()
1704 m = re.search ('columns=([0-9.]*)', parameter_string)
1706 columns = int (m.group (1))
1709 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1711 columnsep = float (m.group (1))
1714 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1716 textwidth = float (m.group (1))
1718 textwidth = (textwidth - columnsep) / columns
1722 def modify_preamble (chunk):
1723 str = chunk.replacement_text ()
1724 if (re.search (r"\\begin *{document}", str)
1725 and not re.search ("{graphic[sx]", str)):
1726 str = re.sub (r"\\begin{document}",
1727 r"\\usepackage{graphics}" + '\n'
1728 + r"\\begin{document}",
1730 chunk.override_text = str
1735 # TEXINFO: '.texinfo',
1741 class CompileError(Exception):
1744 def snippet_list_checksum (snippets):
1745 return hash (' '.join([l.basename() for l in snippets]))
1747 def write_file_map (lys, name):
1748 snippet_map = file (os.path.join (
1749 global_options.lily_output_dir,
1750 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1752 snippet_map.write ("""
1753 #(define version-seen #t)
1754 #(define output-empty-score-list #f)
1755 #(ly:add-file-name-alist '(%s
1757 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1760 def split_output_files(directory):
1761 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1763 Return value is a set of strings.
1766 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1767 base_subdir = os.path.split (subdir)[1]
1768 sub_files = [os.path.join (base_subdir, name)
1769 for name in os.listdir (subdir)]
1773 def do_process_cmd (chunks, input_name, options):
1774 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1776 output_files = split_output_files (options.lily_output_dir)
1777 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1779 write_file_map (outdated, input_name)
1780 progress (_ ("Writing snippets..."))
1781 for snippet in outdated:
1786 progress (_ ("Processing..."))
1788 process_snippets (options.process_cmd, outdated,
1789 options.format, options.lily_output_dir)
1792 progress (_ ("All snippets are up to date..."))
1794 if options.lily_output_dir != options.output_dir:
1795 output_files = split_output_files (options.lily_output_dir)
1796 for snippet in snippets:
1797 snippet.link_all_output_files (options.lily_output_dir,
1805 # Format guessing data
1814 '.texinfo': TEXINFO,
1819 def guess_format (input_filename):
1821 e = os.path.splitext (input_filename)[1]
1824 format = ext2format[e]
1826 error (_ ("cannot determine format for: %s"
1831 def write_if_updated (file_name, lines):
1833 f = file (file_name)
1835 new_str = ''.join (lines)
1836 if oldstr == new_str:
1837 progress (_ ("%s is up to date.") % file_name)
1840 # this prevents make from always rerunning lilypond-book:
1841 # output file must be touched in order to be up to date
1842 os.utime (file_name, None)
1847 output_dir = os.path.dirname (file_name)
1848 if not os.path.exists (output_dir):
1849 os.makedirs (output_dir)
1851 progress (_ ("Writing `%s'...") % file_name)
1852 file (file_name, 'w').writelines (lines)
1856 def note_input_file (name, inputs=[]):
1857 ## hack: inputs is mutable!
1858 inputs.append (name)
1861 def samefile (f1, f2):
1863 return os.path.samefile (f1, f2)
1864 except AttributeError: # Windoze
1865 f1 = re.sub ("//*", "/", f1)
1866 f2 = re.sub ("//*", "/", f2)
1869 def do_file (input_filename, included=False):
1871 if not input_filename or input_filename == '-':
1872 in_handle = sys.stdin
1873 input_fullname = '<stdin>'
1875 if os.path.exists (input_filename):
1876 input_fullname = input_filename
1877 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1878 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1880 input_fullname = find_file (input_filename)
1882 note_input_file (input_fullname)
1883 in_handle = file (input_fullname)
1885 if input_filename == '-':
1886 input_base = 'stdin'
1888 input_base = os.path.splitext (input_filename)[0]
1890 input_base = os.path.basename (
1891 os.path.splitext (input_filename)[0])
1893 # don't complain when global_options.output_dir is existing
1894 if not global_options.output_dir:
1895 global_options.output_dir = os.getcwd()
1897 global_options.output_dir = os.path.abspath(global_options.output_dir)
1899 if not os.path.isdir (global_options.output_dir):
1900 os.mkdir (global_options.output_dir, 0777)
1901 os.chdir (global_options.output_dir)
1903 output_filename = os.path.join(global_options.output_dir,
1904 input_base + format2ext[global_options.format])
1905 if (os.path.exists (input_filename)
1906 and os.path.exists (output_filename)
1907 and samefile (output_filename, input_fullname)):
1909 _ ("Output would overwrite input file; use --output."))
1913 progress (_ ("Reading %s...") % input_fullname)
1914 source = in_handle.read ()
1917 set_default_options (source, default_ly_options, global_options.format)
1920 # FIXME: Containing blocks must be first, see
1921 # find_toplevel_snippets.
1923 'multiline_comment',
1927 'singleline_comment',
1933 progress (_ ("Dissecting..."))
1934 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1936 if global_options.format == LATEX:
1938 if (c.is_plain () and
1939 re.search (r"\\begin *{document}", c.replacement_text())):
1944 if global_options.filter_cmd:
1945 write_if_updated (output_filename,
1946 [c.filter_text () for c in chunks])
1947 elif global_options.process_cmd:
1948 do_process_cmd (chunks, input_fullname, global_options)
1949 progress (_ ("Compiling %s...") % output_filename)
1951 write_if_updated (output_filename,
1952 [s.replacement_text ()
1955 def process_include (snippet):
1956 os.chdir (original_dir)
1957 name = snippet.substring ('filename')
1958 progress (_ ("Processing include: %s") % name)
1960 return do_file (name, included=True)
1962 include_chunks = map (process_include,
1963 filter (lambda x: isinstance (x, IncludeSnippet),
1966 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1968 except CompileError:
1969 os.chdir (original_dir)
1970 progress (_ ("Removing `%s'") % output_filename)
1975 global global_options
1977 opt_parser = get_option_parser()
1978 (global_options, args) = opt_parser.parse_args ()
1979 if global_options.format in ('texi-html', 'texi'):
1980 global_options.format = TEXINFO
1982 global_options.include_path = map (os.path.abspath, global_options.include_path)
1984 if global_options.warranty:
1987 if not args or len (args) > 1:
1988 opt_parser.print_help ()
1994 # FIXME: 85 lines of `main' macramee??
1995 files = do_options ()
1997 basename = os.path.splitext (files[0])[0]
1998 basename = os.path.split (basename)[1]
2000 if not global_options.format:
2001 global_options.format = guess_format (files[0])
2004 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2007 if global_options.process_cmd == '':
2008 global_options.process_cmd = (lilypond_binary
2009 + ' --formats=%s -dbackend=eps ' % formats)
2011 if global_options.process_cmd:
2012 includes = global_options.include_path
2013 if global_options.lily_output_dir:
2014 # This must be first, so lilypond prefers to read .ly
2015 # files in the other lybookdb dir.
2016 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2017 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2020 if global_options.format in (TEXINFO, LATEX):
2021 ## prevent PDF from being switched on by default.
2022 global_options.process_cmd += ' --formats=eps '
2023 if global_options.create_pdf:
2024 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2026 if global_options.verbose:
2027 global_options.process_cmd += " --verbose "
2029 if global_options.padding_mm:
2030 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2032 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2034 if global_options.lily_output_dir:
2035 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2036 if not os.path.isdir (global_options.lily_output_dir):
2037 os.makedirs (global_options.lily_output_dir)
2039 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2044 chunks = do_file (files[0])
2045 except CompileError:
2048 inputs = note_input_file ('')
2051 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2052 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2053 final_output_file = os.path.join (global_options.output_dir,
2055 + '.%s' % global_options.format)
2057 os.chdir (original_dir)
2058 file (dep_file, 'w').write ('%s: %s'
2059 % (final_output_file, ' '.join (inputs)))
2061 if __name__ == '__main__':