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 %s")
215 % ' http://post.gmane.org/post.php'
216 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
219 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
221 # If we are called with full path, try to use lilypond binary
222 # installed in the same path; this is needed in GUB binaries, where
223 # @bindir is always different from the installed binary path.
224 if 'bindir' in globals () and bindir:
225 lilypond_binary = os.path.join (bindir, 'lilypond')
227 # Only use installed binary when we are installed too.
228 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
229 lilypond_binary = 'lilypond'
231 global_options = None
234 default_ly_options = { 'alt': "[image of music]" }
236 document_language = ''
239 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
241 ADDVERSION = 'addversion'
245 EXAMPLEINDENT = 'exampleindent'
247 FRAGMENT = 'fragment'
253 LINE_WIDTH = 'line-width'
254 LILYQUOTE = 'lilyquote'
255 NOFRAGMENT = 'nofragment'
256 NOINDENT = 'noindent'
258 NORAGGED_RIGHT = 'noragged-right'
262 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''',
617 \remove "Time_signature_engraver"
623 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
630 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
633 <imageobject role="latex">
634 <imagedata fileref="%(base)s.pdf" format="PDF"/>
636 <imageobject role="html">
637 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
639 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
641 VERSION: program_version,
643 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
647 FILTER: r'''<lilypond %(options)s>
657 <a href="%(base)s.ly">''',
661 border="0" src="%(image)s" alt="%(alt)s">''',
663 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
665 QUOTE: r'''<blockquote>
673 VERSION: program_version,
680 \ifx\preLilyPondExample \undefined%%
683 \preLilyPondExample%%
685 \def\lilypondbook{}%%
686 \input %(base)s-systems.tex%%
687 \ifx\postLilyPondExample \undefined%%
690 \postLilyPondExample%%
694 PRINTFILENAME: '''\\texttt{%(filename)s}
697 QUOTE: r'''\begin{quotation}%(str)s
700 VERBATIM: r'''\noindent
701 \begin{verbatim}%(verb)s\end{verbatim}''',
703 VERSION: program_version,
705 FILTER: r'''\begin{lilypond}[%(options)s]
712 FILTER: r'''@lilypond[%(options)s]
718 @include %(base)s-systems.texi
722 OUTPUTIMAGE: r'''@noindent
724 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
728 <a href="%(base)s.ly">
730 border="0" src="%(image)s" alt="%(alt)s">
738 <a href="%(base)s.ly">
746 QUOTE: r'''@quotation
747 %(str)s@end quotation
754 VERBATIM: r'''@exampleindent 0
756 %(verb)s@end verbatim
759 VERSION: program_version,
761 ADDVERSION: r'''@example
762 \version @w{"@version{}"}
769 # Maintain line numbers.
774 for f in [HTML, LATEX]:
775 for s in (QUOTE, VERBATIM):
776 output[f][s] = output[f][s].replace("\n"," ")
779 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
780 %%%% Options: [%(option_string)s]
781 \\include "lilypond-book-preamble.ly"
784 %% ****************************************************************
785 %% Start cut-&-pastable-section
786 %% ****************************************************************
791 #(define dump-extents #t)
792 %(font_dump_setting)s
794 force-assignment = #""
795 line-width = #(- line-width (* mm %(padding_mm)f))
808 %% ****************************************************************
809 %% ly snippet contents follows:
810 %% ****************************************************************
814 %% ****************************************************************
816 %% ****************************************************************
823 %% ****************************************************************
825 %% ****************************************************************
829 %% ****************************************************************
831 %% ****************************************************************
834 texinfo_line_widths = {
835 '@afourpaper': '160\\mm',
836 '@afourwide': '6.5\\in',
837 '@afourlatex': '150\\mm',
838 '@smallbook': '5\\in',
839 '@letterpaper': '6\\in',
842 def classic_lilypond_book_compatibility (key, value):
843 if key == 'singleline' and value == None:
844 return (RAGGED_RIGHT, None)
846 m = re.search ('relative\s*([-0-9])', key)
848 return ('relative', m.group (1))
850 m = re.match ('([0-9]+)pt', key)
852 return ('staffsize', m.group (1))
854 if key == 'indent' or key == 'line-width':
855 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
857 f = float (m.group (1))
858 return (key, '%f\\%s' % (f, m.group (2)))
862 def find_file (name, raise_error=True):
863 for i in global_options.include_path:
864 full = os.path.join (i, name)
865 if os.path.exists (full):
869 error (_ ("file not found: %s") % name + '\n')
873 def verbatim_html (s):
874 return re.sub ('>', '>',
876 re.sub ('&', '&', s)))
878 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
879 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
880 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
881 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
883 def ly_comment_gettext (t, m):
884 return m.group (1) + t (m.group (2))
886 def verb_ly_gettext (s):
887 if not document_language:
890 t = langdefs.translation[document_language]
894 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
896 for v in ly_var_def_re.findall (s):
897 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
898 "\\1" + t (v) + "\\2",
900 for id in ly_context_id_re.findall (s):
901 s = re.sub (r'(\s+|")%s(\s+|")' % id,
902 "\\1" + t (id) + "\\2",
906 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
907 def set_default_options (source, default_ly_options, format):
908 global document_language
909 if LINE_WIDTH not in default_ly_options:
911 textwidth = get_latex_textwidth (source)
912 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
913 elif format == TEXINFO:
914 m = texinfo_lang_re.search (source)
915 if m and not m.group (1).startswith ('en'):
916 document_language = m.group (1)
918 document_language = ''
919 for regex in texinfo_line_widths:
920 # FIXME: @layout is usually not in
923 # \input texinfo @c -*-texinfo-*-
925 # Bluntly search first K items of
927 # s = chunks[0].replacement_text ()
928 if re.search (regex, source[:1024]):
929 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
933 def replacement_text (self):
936 def filter_text (self):
937 return self.replacement_text ()
942 class Substring (Chunk):
943 """A string that does not require extra memory."""
944 def __init__ (self, source, start, end, line_number):
948 self.line_number = line_number
949 self.override_text = None
954 def replacement_text (self):
955 if self.override_text:
956 return self.override_text
958 return self.source[self.start:self.end]
960 class Snippet (Chunk):
961 def __init__ (self, type, match, format, line_number):
965 self.option_dict = {}
967 self.line_number = line_number
969 def replacement_text (self):
970 return self.match.group ('match')
972 def substring (self, s):
973 return self.match.group (s)
976 return `self.__class__` + ' type = ' + self.type
978 class IncludeSnippet (Snippet):
979 def processed_filename (self):
980 f = self.substring ('filename')
981 return os.path.splitext (f)[0] + format2ext[self.format]
983 def replacement_text (self):
984 s = self.match.group ('match')
985 f = self.substring ('filename')
987 return re.sub (f, self.processed_filename (), s)
989 class LilypondSnippet (Snippet):
990 def __init__ (self, type, match, format, line_number):
991 Snippet.__init__ (self, type, match, format, line_number)
992 os = match.group ('options')
993 self.do_options (os, self.type)
996 return verb_ly_gettext (self.substring ('code'))
999 contents = self.substring ('code')
1000 return ('\\sourcefileline %d\n%s'
1001 % (self.line_number - 1, contents))
1006 return self.compose_ly (s)
1009 def split_options (self, option_string):
1011 if self.format == HTML:
1012 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1014 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1018 return re.split (format_res[self.format]['option_sep'],
1022 def do_options (self, option_string, type):
1023 self.option_dict = {}
1025 options = self.split_options (option_string)
1027 for option in options:
1029 (key, value) = re.split ('\s*=\s*', option)
1030 self.option_dict[key] = value
1032 if option in no_options:
1033 if no_options[option] in self.option_dict:
1034 del self.option_dict[no_options[option]]
1036 self.option_dict[option] = None
1038 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1039 no_line_width_value = 0
1041 # If LINE_WIDTH is used without parameter, set it to default.
1042 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1043 no_line_width_value = 1
1044 del self.option_dict[LINE_WIDTH]
1046 for k in default_ly_options:
1047 if k not in self.option_dict:
1048 self.option_dict[k] = default_ly_options[k]
1050 # RELATIVE does not work without FRAGMENT;
1051 # make RELATIVE imply FRAGMENT
1052 has_relative = self.option_dict.has_key (RELATIVE)
1053 if has_relative and not self.option_dict.has_key (FRAGMENT):
1054 self.option_dict[FRAGMENT] = None
1056 if not has_line_width:
1057 if type == 'lilypond' or FRAGMENT in self.option_dict:
1058 self.option_dict[RAGGED_RIGHT] = None
1060 if type == 'lilypond':
1061 if LINE_WIDTH in self.option_dict:
1062 del self.option_dict[LINE_WIDTH]
1064 if RAGGED_RIGHT in self.option_dict:
1065 if LINE_WIDTH in self.option_dict:
1066 del self.option_dict[LINE_WIDTH]
1068 if QUOTE in self.option_dict or type == 'lilypond':
1069 if LINE_WIDTH in self.option_dict:
1070 del self.option_dict[LINE_WIDTH]
1072 if not INDENT in self.option_dict:
1073 self.option_dict[INDENT] = '0\\mm'
1075 # The QUOTE pattern from ly_options only emits the `line-width'
1077 if has_line_width and QUOTE in self.option_dict:
1078 if no_line_width_value:
1079 del self.option_dict[LINE_WIDTH]
1081 del self.option_dict[QUOTE]
1083 def compose_ly (self, code):
1084 if FRAGMENT in self.option_dict:
1092 # The original concept of the `exampleindent' option is broken.
1093 # It is not possible to get a sane value for @exampleindent at all
1094 # without processing the document itself. Saying
1102 # causes ugly results with the DVI backend of texinfo since the
1103 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1104 # value). Executing the above code changes the environment
1105 # indentation to an unknown value because we don't know the amount
1106 # of 1em in advance since it is font-dependent. Modifying
1107 # @exampleindent in the middle of a document is simply not
1108 # supported within texinfo.
1110 # As a consequence, the only function of @exampleindent is now to
1111 # specify the amount of indentation for the `quote' option.
1113 # To set @exampleindent locally to zero, we use the @format
1114 # environment for non-quoted snippets.
1115 override[EXAMPLEINDENT] = r'0.4\in'
1116 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1117 override.update (default_ly_options)
1120 for (key, value) in self.option_dict.items ():
1122 option_list.append (key)
1124 option_list.append (key + '=' + value)
1125 option_string = ','.join (option_list)
1128 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1129 for a in compose_types:
1130 compose_dict[a] = []
1132 for (key, value) in self.option_dict.items ():
1133 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1137 _ ("deprecated ly-option used: %s=%s") % (key, value))
1139 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1142 _ ("deprecated ly-option used: %s") % key)
1144 _ ("compatibility mode translation: %s") % c_key)
1146 (key, value) = (c_key, c_value)
1149 override[key] = value
1151 if not override.has_key (key):
1152 override[key] = None
1155 for type in compose_types:
1156 if ly_options[type].has_key (key):
1157 compose_dict[type].append (ly_options[type][key])
1161 if not found and key not in simple_options:
1162 warning (_ ("ignoring unknown ly option: %s") % key)
1165 if RELATIVE in override and override[RELATIVE]:
1166 relative = int (override[RELATIVE])
1168 relative_quotes = ''
1172 relative_quotes += ',' * (- relative)
1174 relative_quotes += "'" * relative
1176 paper_string = '\n '.join (compose_dict[PAPER]) % override
1177 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1178 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1179 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1180 padding_mm = global_options.padding_mm
1181 font_dump_setting = ''
1182 if FONTLOAD in self.option_dict:
1183 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1185 d = globals().copy()
1187 return (PREAMBLE_LY + body) % d
1189 def get_checksum (self):
1190 if not self.checksum:
1191 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1193 ## let's not create too long names.
1194 self.checksum = hash.hexdigest ()[:10]
1196 return self.checksum
1198 def basename (self):
1199 cs = self.get_checksum ()
1200 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1203 def write_ly (self):
1204 base = self.basename ()
1205 path = os.path.join (global_options.lily_output_dir, base)
1206 directory = os.path.split(path)[0]
1207 if not os.path.isdir (directory):
1208 os.makedirs (directory)
1209 out = file (path + '.ly', 'w')
1210 out.write (self.full_ly ())
1211 file (path + '.txt', 'w').write ('image of music')
1213 def relevant_contents (self, ly):
1214 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1216 def link_all_output_files (self, output_dir, output_dir_files, destination):
1217 existing, missing = self.all_output_files (output_dir, output_dir_files)
1219 print '\nMissing', missing
1220 raise CompileError(self.basename())
1221 for name in existing:
1223 os.unlink (os.path.join (destination, name))
1227 src = os.path.join (output_dir, name)
1228 dst = os.path.join (destination, name)
1229 dst_path = os.path.split(dst)[0]
1230 if not os.path.isdir (dst_path):
1231 os.makedirs (dst_path)
1235 def all_output_files (self, output_dir, output_dir_files):
1236 """Return all files generated in lily_output_dir, a set.
1238 output_dir_files is the list of files in the output directory.
1242 base = self.basename()
1243 full = os.path.join (output_dir, base)
1244 def consider_file (name):
1245 if name in output_dir_files:
1248 def require_file (name):
1249 if name in output_dir_files:
1254 # UGH - junk global_options
1255 skip_lily = global_options.skip_lilypond_run
1256 for required in [base + '.ly',
1258 require_file (required)
1260 require_file (base + '-systems.count')
1262 if 'ddump-profile' in global_options.process_cmd:
1263 require_file (base + '.profile')
1264 if 'dseparate-log-file' in global_options.process_cmd:
1265 require_file (base + '.log')
1267 map (consider_file, [base + '.tex',
1271 base + '-systems.texi',
1272 base + '-systems.tex',
1273 base + '-systems.pdftexi'])
1274 if document_language:
1276 [base + '.texidoc' + document_language,
1277 base + '.doctitle' + document_language])
1279 # UGH - junk global_options
1280 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1281 and not global_options.skip_png_check):
1282 page_count = ps_page_count (full + '.eps')
1284 require_file (base + '.png')
1286 for page in range (1, page_count + 1):
1287 require_file (base + '-page%d.png' % page)
1290 if not skip_lily and not missing:
1291 system_count = int(file (full + '-systems.count').read())
1293 for number in range(1, system_count + 1):
1294 systemfile = '%s-%d' % (base, number)
1295 require_file (systemfile + '.eps')
1296 consider_file (systemfile + '.pdf')
1298 # We can't require signatures, since books and toplevel
1299 # markups do not output a signature.
1300 if 'ddump-signature' in global_options.process_cmd:
1301 consider_file (systemfile + '.signature')
1304 return (result, missing)
1306 def is_outdated (self, output_dir, current_files):
1307 found, missing = self.all_output_files (output_dir, current_files)
1310 def filter_text (self):
1311 """Run snippet bodies through a command (say: convert-ly).
1313 This functionality is rarely used, and this code must have bitrot.
1315 code = self.substring ('code')
1316 s = filter_pipe (code, global_options.filter_cmd)
1319 'options': self.match.group ('options')
1322 return output[self.format][FILTER] % d
1324 def replacement_text (self):
1325 func = LilypondSnippet.__dict__['output_' + self.format]
1328 def get_images (self):
1329 base = self.basename ()
1331 single = '%(base)s.png' % vars ()
1332 multiple = '%(base)s-page1.png' % vars ()
1334 if (os.path.exists (multiple)
1335 and (not os.path.exists (single)
1336 or (os.stat (multiple)[stat.ST_MTIME]
1337 > os.stat (single)[stat.ST_MTIME]))):
1338 count = ps_page_count ('%(base)s.eps' % vars ())
1339 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1340 images = tuple (images)
1344 def output_docbook (self):
1346 base = self.basename ()
1347 for image in self.get_images ():
1348 (base, ext) = os.path.splitext (image)
1349 str += output[DOCBOOK][OUTPUT] % vars ()
1350 str += self.output_print_filename (DOCBOOK)
1351 if (self.substring('inline') == 'inline'):
1352 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1354 str = '<mediaobject>' + str + '</mediaobject>'
1355 if VERBATIM in self.option_dict:
1356 verb = verbatim_html (self.verb_ly ())
1357 str = output[DOCBOOK][VERBATIM] % vars () + str
1360 def output_html (self):
1362 base = self.basename ()
1363 if self.format == HTML:
1364 str += self.output_print_filename (HTML)
1365 if VERBATIM in self.option_dict:
1366 verb = verbatim_html (self.verb_ly ())
1367 str += output[HTML][VERBATIM] % vars ()
1368 if QUOTE in self.option_dict:
1369 str = output[HTML][QUOTE] % vars ()
1371 str += output[HTML][BEFORE] % vars ()
1372 for image in self.get_images ():
1373 (base, ext) = os.path.splitext (image)
1374 alt = self.option_dict[ALT]
1375 str += output[HTML][OUTPUT] % vars ()
1376 str += output[HTML][AFTER] % vars ()
1379 def output_info (self):
1381 for image in self.get_images ():
1382 (base, ext) = os.path.splitext (image)
1384 # URG, makeinfo implicitly prepends dot to extension.
1385 # Specifying no extension is most robust.
1387 alt = self.option_dict[ALT]
1388 info_image_path = os.path.join (global_options.info_images_dir, base)
1389 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1391 base = self.basename ()
1392 str += output[self.format][OUTPUT] % vars ()
1395 def output_latex (self):
1397 base = self.basename ()
1398 if self.format == LATEX:
1399 str += self.output_print_filename (LATEX)
1400 if VERBATIM in self.option_dict:
1401 verb = self.verb_ly ()
1402 str += (output[LATEX][VERBATIM] % vars ())
1404 str += (output[LATEX][OUTPUT] % vars ())
1406 ## todo: maintain breaks
1408 breaks = self.ly ().count ("\n")
1409 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1411 if QUOTE in self.option_dict:
1412 str = output[LATEX][QUOTE] % vars ()
1415 def output_print_filename (self, format):
1417 if PRINTFILENAME in self.option_dict:
1418 base = self.basename ()
1419 filename = os.path.basename (self.substring ('filename'))
1420 str = output[format][PRINTFILENAME] % vars ()
1424 def output_texinfo (self):
1425 str = self.output_print_filename (TEXINFO)
1426 base = self.basename ()
1427 if DOCTITLE in self.option_dict:
1428 doctitle = base + '.doctitle'
1429 translated_doctitle = doctitle + document_language
1430 if os.path.exists (translated_doctitle):
1431 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1432 elif os.path.exists (doctitle):
1433 str += '@lydoctitle %s\n' % open (doctitle).read ()
1434 if TEXIDOC in self.option_dict:
1435 texidoc = base + '.texidoc'
1436 translated_texidoc = texidoc + document_language
1437 if os.path.exists (translated_texidoc):
1438 str += '@include %(translated_texidoc)s\n\n' % vars ()
1439 elif os.path.exists (texidoc):
1440 str += '@include %(texidoc)s\n\n' % vars ()
1443 if VERBATIM in self.option_dict:
1445 if ADDVERSION in self.option_dict:
1446 version = output[TEXINFO][ADDVERSION]
1447 verb = self.verb_ly ()
1448 substr = output[TEXINFO][VERBATIM] % vars ()
1449 substr += self.output_info ()
1450 if LILYQUOTE in self.option_dict:
1451 substr = output[TEXINFO][QUOTE] % {'str':substr}
1454 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1455 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1456 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1458 if QUOTE in self.option_dict:
1459 str = output[TEXINFO][QUOTE] % vars ()
1461 # need par after image
1466 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1467 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1469 class LilypondFileSnippet (LilypondSnippet):
1470 def __init__ (self, type, match, format, line_number):
1471 LilypondSnippet.__init__ (self, type, match, format, line_number)
1472 self.contents = file (find_file (self.substring ('filename'))).read ()
1476 s = re_begin_verbatim.split (s)[-1]
1477 s = re_end_verbatim.split (s)[0]
1478 return verb_ly_gettext (s)
1481 name = self.substring ('filename')
1482 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1483 % (name, self.contents))
1486 class LilyPondVersionString (Snippet):
1487 """A string that does not require extra memory."""
1488 def __init__ (self, type, match, format, line_number):
1489 Snippet.__init__ (self, type, match, format, line_number)
1491 def replacement_text (self):
1492 return output[self.format][self.type]
1495 snippet_type_to_class = {
1496 'lilypond_file': LilypondFileSnippet,
1497 'lilypond_block': LilypondSnippet,
1498 'lilypond': LilypondSnippet,
1499 'include': IncludeSnippet,
1500 'lilypondversion': LilyPondVersionString,
1503 def find_linestarts (s):
1508 i = s.find ('\n', start)
1516 nls.append (len (s))
1519 def find_toplevel_snippets (input_string, format, types):
1522 res[t] = re.compile (snippet_res[format][t])
1526 found = dict ([(t, None) for t in types])
1528 line_starts = find_linestarts (input_string)
1530 # We want to search for multiple regexes, without searching
1531 # the string multiple times for one regex.
1532 # Hence, we use earlier results to limit the string portion
1534 # Since every part of the string is traversed at most once for
1535 # every type of snippet, this is linear.
1541 if not found[type] or found[type][0] < index:
1544 m = res[type].search (input_string[index:endex])
1549 if type in snippet_type_to_class:
1550 klass = snippet_type_to_class[type]
1552 start = index + m.start ('match')
1553 line_number = line_start_idx
1554 while (line_starts[line_number] < start):
1558 snip = klass (type, m, format, line_number)
1560 found[type] = (start, snip)
1564 or found[type][0] < found[first][0])):
1569 # Limiting the search space is a cute
1570 # idea, but this *requires* to search
1571 # for possible containing blocks
1572 # first, at least as long as we do not
1573 # search for the start of blocks, but
1574 # always/directly for the entire
1575 # @block ... @end block.
1577 endex = found[first][0]
1580 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1583 while (start > line_starts[line_start_idx+1]):
1586 (start, snip) = found[first]
1587 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1588 snippets.append (snip)
1590 index = start + len (snip.match.group ('match'))
1594 def filter_pipe (input, cmd):
1595 """Pass input through cmd, and return the result."""
1597 if global_options.verbose:
1598 progress (_ ("Opening filter `%s'") % cmd)
1600 (stdin, stdout, stderr) = os.popen3 (cmd)
1602 status = stdin.close ()
1606 output = stdout.read ()
1607 status = stdout.close ()
1608 error = stderr.read ()
1612 signal = 0x0f & status
1613 if status or (not output and error):
1614 exit_status = status >> 8
1615 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1616 error (_ ("The error log is as follows:"))
1617 ly.stderr_write (error)
1618 ly.stderr_write (stderr.read ())
1621 if global_options.verbose:
1626 def system_in_directory (cmd, directory):
1627 """Execute a command in a different directory.
1629 Because of win32 compatibility, we can't simply use subprocess.
1632 current = os.getcwd()
1633 os.chdir (directory)
1634 ly.system(cmd, be_verbose=global_options.verbose,
1639 def process_snippets (cmd, snippets,
1640 format, lily_output_dir):
1641 """Run cmd on all of the .ly files from snippets."""
1646 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1647 cmd += ' --formats=png '
1648 elif format in (DOCBOOK) and '--formats' not in cmd:
1649 cmd += ' --formats=png,pdf '
1651 checksum = snippet_list_checksum (snippets)
1652 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1653 + [snip.basename() + '.ly' for snip in snippets])
1654 name = os.path.join (lily_output_dir,
1655 'snippet-names-%d.ly' % checksum)
1656 file (name, 'wb').write (contents)
1658 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1663 # Retrieve dimensions from LaTeX
1664 LATEX_INSPECTION_DOCUMENT = r'''
1668 \typeout{textwidth=\the\textwidth}
1669 \typeout{columnsep=\the\columnsep}
1670 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1674 # Do we need anything else besides `textwidth'?
1675 def get_latex_textwidth (source):
1676 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1678 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1680 ## what's a sensible default?
1683 preamble = source[:m.start (0)]
1684 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1686 (handle, tmpfile) = tempfile.mkstemp('.tex')
1687 logfile = os.path.splitext (tmpfile)[0] + '.log'
1688 logfile = os.path.split (logfile)[1]
1690 tmp_handle = os.fdopen (handle,'w')
1691 tmp_handle.write (latex_document)
1694 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1695 be_verbose=global_options.verbose)
1696 parameter_string = file (logfile).read()
1702 m = re.search ('columns=([0-9.]*)', parameter_string)
1704 columns = int (m.group (1))
1707 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1709 columnsep = float (m.group (1))
1712 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1714 textwidth = float (m.group (1))
1716 textwidth = (textwidth - columnsep) / columns
1720 def modify_preamble (chunk):
1721 str = chunk.replacement_text ()
1722 if (re.search (r"\\begin *{document}", str)
1723 and not re.search ("{graphic[sx]", str)):
1724 str = re.sub (r"\\begin{document}",
1725 r"\\usepackage{graphics}" + '\n'
1726 + r"\\begin{document}",
1728 chunk.override_text = str
1733 # TEXINFO: '.texinfo',
1739 class CompileError(Exception):
1742 def snippet_list_checksum (snippets):
1743 return hash (' '.join([l.basename() for l in snippets]))
1745 def write_file_map (lys, name):
1746 snippet_map = file (os.path.join (
1747 global_options.lily_output_dir,
1748 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1750 snippet_map.write ("""
1751 #(define version-seen #t)
1752 #(define output-empty-score-list #f)
1753 #(ly:add-file-name-alist '(%s
1755 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1758 def split_output_files(directory):
1759 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1761 Return value is a set of strings.
1764 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1765 base_subdir = os.path.split (subdir)[1]
1766 sub_files = [os.path.join (base_subdir, name)
1767 for name in os.listdir (subdir)]
1771 def do_process_cmd (chunks, input_name, options):
1772 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1774 output_files = split_output_files (options.lily_output_dir)
1775 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1777 write_file_map (outdated, input_name)
1778 progress (_ ("Writing snippets..."))
1779 for snippet in outdated:
1784 progress (_ ("Processing..."))
1786 process_snippets (options.process_cmd, outdated,
1787 options.format, options.lily_output_dir)
1790 progress (_ ("All snippets are up to date..."))
1792 if options.lily_output_dir != options.output_dir:
1793 output_files = split_output_files (options.lily_output_dir)
1794 for snippet in snippets:
1795 snippet.link_all_output_files (options.lily_output_dir,
1803 # Format guessing data
1812 '.texinfo': TEXINFO,
1817 def guess_format (input_filename):
1819 e = os.path.splitext (input_filename)[1]
1822 format = ext2format[e]
1824 error (_ ("cannot determine format for: %s"
1829 def write_if_updated (file_name, lines):
1831 f = file (file_name)
1833 new_str = ''.join (lines)
1834 if oldstr == new_str:
1835 progress (_ ("%s is up to date.") % file_name)
1838 # this prevents make from always rerunning lilypond-book:
1839 # output file must be touched in order to be up to date
1840 os.utime (file_name, None)
1845 output_dir = os.path.dirname (file_name)
1846 if not os.path.exists (output_dir):
1847 os.makedirs (output_dir)
1849 progress (_ ("Writing `%s'...") % file_name)
1850 file (file_name, 'w').writelines (lines)
1854 def note_input_file (name, inputs=[]):
1855 ## hack: inputs is mutable!
1856 inputs.append (name)
1859 def samefile (f1, f2):
1861 return os.path.samefile (f1, f2)
1862 except AttributeError: # Windoze
1863 f1 = re.sub ("//*", "/", f1)
1864 f2 = re.sub ("//*", "/", f2)
1867 def do_file (input_filename, included=False):
1869 if not input_filename or input_filename == '-':
1870 in_handle = sys.stdin
1871 input_fullname = '<stdin>'
1873 if os.path.exists (input_filename):
1874 input_fullname = input_filename
1875 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1876 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1878 input_fullname = find_file (input_filename)
1880 note_input_file (input_fullname)
1881 in_handle = file (input_fullname)
1883 if input_filename == '-':
1884 input_base = 'stdin'
1886 input_base = os.path.splitext (input_filename)[0]
1888 input_base = os.path.basename (
1889 os.path.splitext (input_filename)[0])
1891 # don't complain when global_options.output_dir is existing
1892 if not global_options.output_dir:
1893 global_options.output_dir = os.getcwd()
1895 global_options.output_dir = os.path.abspath(global_options.output_dir)
1897 if not os.path.isdir (global_options.output_dir):
1898 os.mkdir (global_options.output_dir, 0777)
1899 os.chdir (global_options.output_dir)
1901 output_filename = os.path.join(global_options.output_dir,
1902 input_base + format2ext[global_options.format])
1903 if (os.path.exists (input_filename)
1904 and os.path.exists (output_filename)
1905 and samefile (output_filename, input_fullname)):
1907 _ ("Output would overwrite input file; use --output."))
1911 progress (_ ("Reading %s...") % input_fullname)
1912 source = in_handle.read ()
1915 set_default_options (source, default_ly_options, global_options.format)
1918 # FIXME: Containing blocks must be first, see
1919 # find_toplevel_snippets.
1921 'multiline_comment',
1925 'singleline_comment',
1931 progress (_ ("Dissecting..."))
1932 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1934 if global_options.format == LATEX:
1936 if (c.is_plain () and
1937 re.search (r"\\begin *{document}", c.replacement_text())):
1942 if global_options.filter_cmd:
1943 write_if_updated (output_filename,
1944 [c.filter_text () for c in chunks])
1945 elif global_options.process_cmd:
1946 do_process_cmd (chunks, input_fullname, global_options)
1947 progress (_ ("Compiling %s...") % output_filename)
1949 write_if_updated (output_filename,
1950 [s.replacement_text ()
1953 def process_include (snippet):
1954 os.chdir (original_dir)
1955 name = snippet.substring ('filename')
1956 progress (_ ("Processing include: %s") % name)
1958 return do_file (name, included=True)
1960 include_chunks = map (process_include,
1961 filter (lambda x: isinstance (x, IncludeSnippet),
1964 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1966 except CompileError:
1967 os.chdir (original_dir)
1968 progress (_ ("Removing `%s'") % output_filename)
1973 global global_options
1975 opt_parser = get_option_parser()
1976 (global_options, args) = opt_parser.parse_args ()
1977 if global_options.format in ('texi-html', 'texi'):
1978 global_options.format = TEXINFO
1980 global_options.include_path = map (os.path.abspath, global_options.include_path)
1982 if global_options.warranty:
1985 if not args or len (args) > 1:
1986 opt_parser.print_help ()
1992 # FIXME: 85 lines of `main' macramee??
1993 files = do_options ()
1995 basename = os.path.splitext (files[0])[0]
1996 basename = os.path.split (basename)[1]
1998 if not global_options.format:
1999 global_options.format = guess_format (files[0])
2002 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2005 if global_options.process_cmd == '':
2006 global_options.process_cmd = (lilypond_binary
2007 + ' --formats=%s -dbackend=eps ' % formats)
2009 if global_options.process_cmd:
2010 includes = global_options.include_path
2011 if global_options.lily_output_dir:
2012 # This must be first, so lilypond prefers to read .ly
2013 # files in the other lybookdb dir.
2014 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2015 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2018 if global_options.format in (TEXINFO, LATEX):
2019 ## prevent PDF from being switched on by default.
2020 global_options.process_cmd += ' --formats=eps '
2021 if global_options.create_pdf:
2022 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2024 if global_options.verbose:
2025 global_options.process_cmd += " --verbose "
2027 if global_options.padding_mm:
2028 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2030 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2032 if global_options.lily_output_dir:
2033 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2034 if not os.path.isdir (global_options.lily_output_dir):
2035 os.makedirs (global_options.lily_output_dir)
2037 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2042 chunks = do_file (files[0])
2043 except CompileError:
2046 inputs = note_input_file ('')
2049 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2050 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2051 final_output_file = os.path.join (global_options.output_dir,
2053 + '.%s' % global_options.format)
2055 os.chdir (original_dir)
2056 file (dep_file, 'w').write ('%s: %s'
2057 % (final_output_file, ' '.join (inputs)))
2059 if __name__ == '__main__':