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'
263 PREAMBLE = 'preamble'
264 PRINTFILENAME = 'printfilename'
266 RAGGED_RIGHT = 'ragged-right'
267 RELATIVE = 'relative'
268 STAFFSIZE = 'staffsize'
269 DOCTITLE = 'doctitle'
272 VERBATIM = 'verbatim'
273 VERSION = 'lilypondversion'
274 FONTLOAD = 'fontload'
275 FILENAME = 'filename'
279 # NOTIME has no opposite so it isn't part of this dictionary.
280 # NOQUOTE is used internally only.
282 NOFRAGMENT: FRAGMENT,
287 # Recognize special sequences in the input.
289 # (?P<name>regex) -- Assign result of REGEX to NAME.
290 # *? -- Match non-greedily.
291 # (?m) -- Multiline regex: Make ^ and $ match at each line.
292 # (?s) -- Make the dot match all characters including newline.
293 # (?x) -- Ignore whitespace in patterns.
304 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
309 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
314 <(?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>)''',
320 (?P<code><!--\s.*?!-->)
323 'singleline_comment':
344 (\s*(?P<options>.*?)\s*:)?\s*
352 \s*(?P<options>.*?)\s*
361 \s*(?P<options>.*?)\s*
363 \s*(?P<filename>.*?)\s*
370 (?P<code><!--\s.*?!-->)
373 'singleline_comment':
379 (?P<code><pre>.*?</pre>))''',
385 (?P<code><pre>\s.*?</pre>\s))''',
390 <lilypondversion\s*/>)''',
409 \s*(?P<options>.*?)\s*
420 \s*(?P<options>.*?)\s*
424 \\end\s*{lilypond})''',
432 \s*(?P<options>.*?)\s*
440 'singleline_comment':
463 \\end\s*{verbatim}))''',
468 \\lilypondversion)[^a-zA-Z]''',
478 (?P<filename>\S+))''',
482 ^[^\n]*?(?!@c\s+)[^\n]*?
486 \s*(?P<options>.*?)\s*
496 \s*(?P<options>.*?)\s*
499 ^@end\s+lilypond)\s''',
506 \s*(?P<options>.*?)\s*
517 @end\s+ignore))\s''',
519 'singleline_comment':
524 @c([ \t][^\n]*|)\n))''',
526 # Don't do this: It interferes with @code{@{}.
527 # 'verb': r'''(?P<code>@code{.*?})''',
535 @end\s+example\s))''',
540 @lilypondversion)[^a-zA-Z]''',
550 'intertext': r',?\s*intertext=\".*?\"',
554 'intertext': r',?\s*intertext=\".*?\"',
559 'intertext': r',?\s*intertext=\".*?\"',
560 'option_sep': '\s*,\s*',
564 'intertext': r',?\s*intertext=\".*?\"',
565 'option_sep': '\s*,\s*',
569 # Options without a pattern in ly_options.
589 RELATIVE: r'''\relative c%(relative_quotes)s''',
594 INDENT: r'''indent = %(indent)s''',
596 LINE_WIDTH: r'''line-width = %(line-width)s''',
598 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
600 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
602 RAGGED_RIGHT: r'''ragged-right = ##t''',
604 NORAGGED_RIGHT: r'''ragged-right = ##f''',
616 \remove "Time_signature_engraver"
622 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
629 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
632 <imageobject role="latex">
633 <imagedata fileref="%(base)s.pdf" format="PDF"/>
635 <imageobject role="html">
636 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
638 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
640 VERSION: program_version,
642 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
646 FILTER: r'''<lilypond %(options)s>
656 <a href="%(base)s.ly">''',
660 border="0" src="%(image)s" alt="%(alt)s">''',
662 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
664 QUOTE: r'''<blockquote>
672 VERSION: program_version,
679 \ifx\preLilyPondExample \undefined%%
682 \preLilyPondExample%%
684 \def\lilypondbook{}%%
685 \input %(base)s-systems.tex%%
686 \ifx\postLilyPondExample \undefined%%
689 \postLilyPondExample%%
693 PRINTFILENAME: '''\\texttt{%(filename)s}
696 QUOTE: r'''\begin{quotation}%(str)s
699 VERBATIM: r'''\noindent
700 \begin{verbatim}%(verb)s\end{verbatim}''',
702 VERSION: program_version,
704 FILTER: r'''\begin{lilypond}[%(options)s]
711 FILTER: r'''@lilypond[%(options)s]
717 @include %(base)s-systems.texi
721 OUTPUTIMAGE: r'''@noindent
723 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
727 <a href="%(base)s.ly">
729 border="0" src="%(image)s" alt="%(alt)s">
737 <a href="%(base)s.ly">
745 QUOTE: r'''@quotation
746 %(str)s@end quotation
753 VERBATIM: r'''@exampleindent 0
755 %(verb)s@end verbatim
758 VERSION: program_version,
760 ADDVERSION: r'''@example
761 \version @w{"@version{}"}
768 # Maintain line numbers.
773 for f in [HTML, LATEX]:
774 for s in (QUOTE, VERBATIM):
775 output[f][s] = output[f][s].replace("\n"," ")
778 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
779 %%%% Options: [%(option_string)s]
780 \\include "lilypond-book-preamble.ly"
783 %% ****************************************************************
784 %% Start cut-&-pastable-section
785 %% ****************************************************************
790 #(define dump-extents #t)
791 %(font_dump_setting)s
793 force-assignment = #""
794 line-width = #(- line-width (* mm %(padding_mm)f))
807 %% ****************************************************************
808 %% ly snippet contents follows:
809 %% ****************************************************************
813 %% ****************************************************************
815 %% ****************************************************************
822 %% ****************************************************************
824 %% ****************************************************************
828 %% ****************************************************************
830 %% ****************************************************************
833 texinfo_line_widths = {
834 '@afourpaper': '160\\mm',
835 '@afourwide': '6.5\\in',
836 '@afourlatex': '150\\mm',
837 '@smallbook': '5\\in',
838 '@letterpaper': '6\\in',
841 def classic_lilypond_book_compatibility (key, value):
842 if key == 'singleline' and value == None:
843 return (RAGGED_RIGHT, None)
845 m = re.search ('relative\s*([-0-9])', key)
847 return ('relative', m.group (1))
849 m = re.match ('([0-9]+)pt', key)
851 return ('staffsize', m.group (1))
853 if key == 'indent' or key == 'line-width':
854 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
856 f = float (m.group (1))
857 return (key, '%f\\%s' % (f, m.group (2)))
861 def find_file (name, raise_error=True):
862 for i in global_options.include_path:
863 full = os.path.join (i, name)
864 if os.path.exists (full):
868 error (_ ("file not found: %s") % name + '\n')
872 def verbatim_html (s):
873 return re.sub ('>', '>',
875 re.sub ('&', '&', s)))
877 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
878 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
879 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
880 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
882 def ly_comment_gettext (t, m):
883 return m.group (1) + t (m.group (2))
885 def verb_ly_gettext (s):
886 if not document_language:
889 t = langdefs.translation[document_language]
893 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
895 for v in ly_var_def_re.findall (s):
896 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
897 "\\1" + t (v) + "\\2",
899 for id in ly_context_id_re.findall (s):
900 s = re.sub (r'(\s+|")%s(\s+|")' % id,
901 "\\1" + t (id) + "\\2",
905 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
906 def set_default_options (source, default_ly_options, format):
907 global document_language
908 if LINE_WIDTH not in default_ly_options:
910 textwidth = get_latex_textwidth (source)
911 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
912 elif format == TEXINFO:
913 m = texinfo_lang_re.search (source)
914 if m and not m.group (1).startswith ('en'):
915 document_language = m.group (1)
917 document_language = ''
918 for regex in texinfo_line_widths:
919 # FIXME: @layout is usually not in
922 # \input texinfo @c -*-texinfo-*-
924 # Bluntly search first K items of
926 # s = chunks[0].replacement_text ()
927 if re.search (regex, source[:1024]):
928 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
932 def replacement_text (self):
935 def filter_text (self):
936 return self.replacement_text ()
941 class Substring (Chunk):
942 """A string that does not require extra memory."""
943 def __init__ (self, source, start, end, line_number):
947 self.line_number = line_number
948 self.override_text = None
953 def replacement_text (self):
954 if self.override_text:
955 return self.override_text
957 return self.source[self.start:self.end]
959 class Snippet (Chunk):
960 def __init__ (self, type, match, format, line_number):
964 self.option_dict = {}
966 self.line_number = line_number
968 def replacement_text (self):
969 return self.match.group ('match')
971 def substring (self, s):
972 return self.match.group (s)
975 return `self.__class__` + ' type = ' + self.type
977 class IncludeSnippet (Snippet):
978 def processed_filename (self):
979 f = self.substring ('filename')
980 return os.path.splitext (f)[0] + format2ext[self.format]
982 def replacement_text (self):
983 s = self.match.group ('match')
984 f = self.substring ('filename')
986 return re.sub (f, self.processed_filename (), s)
988 class LilypondSnippet (Snippet):
989 def __init__ (self, type, match, format, line_number):
990 Snippet.__init__ (self, type, match, format, line_number)
991 os = match.group ('options')
992 self.do_options (os, self.type)
995 return verb_ly_gettext (self.substring ('code'))
998 contents = self.substring ('code')
999 return ('\\sourcefileline %d\n%s'
1000 % (self.line_number - 1, contents))
1005 return self.compose_ly (s)
1008 def split_options (self, option_string):
1010 if self.format == HTML:
1011 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1013 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1017 return re.split (format_res[self.format]['option_sep'],
1021 def do_options (self, option_string, type):
1022 self.option_dict = {}
1024 options = self.split_options (option_string)
1026 for option in options:
1028 (key, value) = re.split ('\s*=\s*', option)
1029 self.option_dict[key] = value
1031 if option in no_options:
1032 if no_options[option] in self.option_dict:
1033 del self.option_dict[no_options[option]]
1035 self.option_dict[option] = None
1037 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1038 no_line_width_value = 0
1040 # If LINE_WIDTH is used without parameter, set it to default.
1041 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1042 no_line_width_value = 1
1043 del self.option_dict[LINE_WIDTH]
1045 for k in default_ly_options:
1046 if k not in self.option_dict:
1047 self.option_dict[k] = default_ly_options[k]
1049 # RELATIVE does not work without FRAGMENT;
1050 # make RELATIVE imply FRAGMENT
1051 has_relative = self.option_dict.has_key (RELATIVE)
1052 if has_relative and not self.option_dict.has_key (FRAGMENT):
1053 self.option_dict[FRAGMENT] = None
1055 if not has_line_width:
1056 if type == 'lilypond' or FRAGMENT in self.option_dict:
1057 self.option_dict[RAGGED_RIGHT] = None
1059 if type == 'lilypond':
1060 if LINE_WIDTH in self.option_dict:
1061 del self.option_dict[LINE_WIDTH]
1063 if RAGGED_RIGHT in self.option_dict:
1064 if LINE_WIDTH in self.option_dict:
1065 del self.option_dict[LINE_WIDTH]
1067 if QUOTE in self.option_dict or type == 'lilypond':
1068 if LINE_WIDTH in self.option_dict:
1069 del self.option_dict[LINE_WIDTH]
1071 if not INDENT in self.option_dict:
1072 self.option_dict[INDENT] = '0\\mm'
1074 # The QUOTE pattern from ly_options only emits the `line-width'
1076 if has_line_width and QUOTE in self.option_dict:
1077 if no_line_width_value:
1078 del self.option_dict[LINE_WIDTH]
1080 del self.option_dict[QUOTE]
1082 def compose_ly (self, code):
1083 if FRAGMENT in self.option_dict:
1091 # The original concept of the `exampleindent' option is broken.
1092 # It is not possible to get a sane value for @exampleindent at all
1093 # without processing the document itself. Saying
1101 # causes ugly results with the DVI backend of texinfo since the
1102 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1103 # value). Executing the above code changes the environment
1104 # indentation to an unknown value because we don't know the amount
1105 # of 1em in advance since it is font-dependent. Modifying
1106 # @exampleindent in the middle of a document is simply not
1107 # supported within texinfo.
1109 # As a consequence, the only function of @exampleindent is now to
1110 # specify the amount of indentation for the `quote' option.
1112 # To set @exampleindent locally to zero, we use the @format
1113 # environment for non-quoted snippets.
1114 override[EXAMPLEINDENT] = r'0.4\in'
1115 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1116 override.update (default_ly_options)
1119 for (key, value) in self.option_dict.items ():
1121 option_list.append (key)
1123 option_list.append (key + '=' + value)
1124 option_string = ','.join (option_list)
1127 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1128 for a in compose_types:
1129 compose_dict[a] = []
1131 for (key, value) in self.option_dict.items ():
1132 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1136 _ ("deprecated ly-option used: %s=%s") % (key, value))
1138 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1141 _ ("deprecated ly-option used: %s") % key)
1143 _ ("compatibility mode translation: %s") % c_key)
1145 (key, value) = (c_key, c_value)
1148 override[key] = value
1150 if not override.has_key (key):
1151 override[key] = None
1154 for type in compose_types:
1155 if ly_options[type].has_key (key):
1156 compose_dict[type].append (ly_options[type][key])
1160 if not found and key not in simple_options:
1161 warning (_ ("ignoring unknown ly option: %s") % key)
1164 if RELATIVE in override and override[RELATIVE]:
1165 relative = int (override[RELATIVE])
1167 relative_quotes = ''
1171 relative_quotes += ',' * (- relative)
1173 relative_quotes += "'" * relative
1175 paper_string = '\n '.join (compose_dict[PAPER]) % override
1176 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1177 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1178 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1179 padding_mm = global_options.padding_mm
1180 font_dump_setting = ''
1181 if FONTLOAD in self.option_dict:
1182 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1184 d = globals().copy()
1186 return (PREAMBLE_LY + body) % d
1188 def get_checksum (self):
1189 if not self.checksum:
1190 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1192 ## let's not create too long names.
1193 self.checksum = hash.hexdigest ()[:10]
1195 return self.checksum
1197 def basename (self):
1198 cs = self.get_checksum ()
1199 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1202 def write_ly (self):
1203 base = self.basename ()
1204 path = os.path.join (global_options.lily_output_dir, base)
1205 directory = os.path.split(path)[0]
1206 if not os.path.isdir (directory):
1207 os.makedirs (directory)
1208 out = file (path + '.ly', 'w')
1209 out.write (self.full_ly ())
1210 file (path + '.txt', 'w').write ('image of music')
1212 def relevant_contents (self, ly):
1213 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1215 def link_all_output_files (self, output_dir, output_dir_files, destination):
1216 existing, missing = self.all_output_files (output_dir, output_dir_files)
1218 print '\nMissing', missing
1219 raise CompileError(self.basename())
1220 for name in existing:
1222 os.unlink (os.path.join (destination, name))
1226 src = os.path.join (output_dir, name)
1227 dst = os.path.join (destination, name)
1228 dst_path = os.path.split(dst)[0]
1229 if not os.path.isdir (dst_path):
1230 os.makedirs (dst_path)
1234 def all_output_files (self, output_dir, output_dir_files):
1235 """Return all files generated in lily_output_dir, a set.
1237 output_dir_files is the list of files in the output directory.
1241 base = self.basename()
1242 full = os.path.join (output_dir, base)
1243 def consider_file (name):
1244 if name in output_dir_files:
1247 def require_file (name):
1248 if name in output_dir_files:
1253 # UGH - junk global_options
1254 skip_lily = global_options.skip_lilypond_run
1255 for required in [base + '.ly',
1257 require_file (required)
1259 require_file (base + '-systems.count')
1261 if 'ddump-profile' in global_options.process_cmd:
1262 require_file (base + '.profile')
1263 if 'dseparate-log-file' in global_options.process_cmd:
1264 require_file (base + '.log')
1266 map (consider_file, [base + '.tex',
1270 base + '-systems.texi',
1271 base + '-systems.tex',
1272 base + '-systems.pdftexi'])
1273 if document_language:
1275 [base + '.texidoc' + document_language,
1276 base + '.doctitle' + document_language])
1278 # UGH - junk global_options
1279 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1280 and not global_options.skip_png_check):
1281 page_count = ps_page_count (full + '.eps')
1283 require_file (base + '.png')
1285 for page in range (1, page_count + 1):
1286 require_file (base + '-page%d.png' % page)
1289 if not skip_lily and not missing:
1290 system_count = int(file (full + '-systems.count').read())
1292 for number in range(1, system_count + 1):
1293 systemfile = '%s-%d' % (base, number)
1294 require_file (systemfile + '.eps')
1295 consider_file (systemfile + '.pdf')
1297 # We can't require signatures, since books and toplevel
1298 # markups do not output a signature.
1299 if 'ddump-signature' in global_options.process_cmd:
1300 consider_file (systemfile + '.signature')
1303 return (result, missing)
1305 def is_outdated (self, output_dir, current_files):
1306 found, missing = self.all_output_files (output_dir, current_files)
1309 def filter_text (self):
1310 """Run snippet bodies through a command (say: convert-ly).
1312 This functionality is rarely used, and this code must have bitrot.
1314 code = self.substring ('code')
1315 s = filter_pipe (code, global_options.filter_cmd)
1318 'options': self.match.group ('options')
1321 return output[self.format][FILTER] % d
1323 def replacement_text (self):
1324 func = LilypondSnippet.__dict__['output_' + self.format]
1327 def get_images (self):
1328 base = self.basename ()
1330 single = '%(base)s.png' % vars ()
1331 multiple = '%(base)s-page1.png' % vars ()
1333 if (os.path.exists (multiple)
1334 and (not os.path.exists (single)
1335 or (os.stat (multiple)[stat.ST_MTIME]
1336 > os.stat (single)[stat.ST_MTIME]))):
1337 count = ps_page_count ('%(base)s.eps' % vars ())
1338 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1339 images = tuple (images)
1343 def output_docbook (self):
1345 base = self.basename ()
1346 for image in self.get_images ():
1347 (base, ext) = os.path.splitext (image)
1348 str += output[DOCBOOK][OUTPUT] % vars ()
1349 str += self.output_print_filename (DOCBOOK)
1350 if (self.substring('inline') == 'inline'):
1351 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1353 str = '<mediaobject>' + str + '</mediaobject>'
1354 if VERBATIM in self.option_dict:
1355 verb = verbatim_html (self.verb_ly ())
1356 str = output[DOCBOOK][VERBATIM] % vars () + str
1359 def output_html (self):
1361 base = self.basename ()
1362 if self.format == HTML:
1363 str += self.output_print_filename (HTML)
1364 if VERBATIM in self.option_dict:
1365 verb = verbatim_html (self.verb_ly ())
1366 str += output[HTML][VERBATIM] % vars ()
1367 if QUOTE in self.option_dict:
1368 str = output[HTML][QUOTE] % vars ()
1370 str += output[HTML][BEFORE] % vars ()
1371 for image in self.get_images ():
1372 (base, ext) = os.path.splitext (image)
1373 alt = self.option_dict[ALT]
1374 str += output[HTML][OUTPUT] % vars ()
1375 str += output[HTML][AFTER] % vars ()
1378 def output_info (self):
1380 for image in self.get_images ():
1381 (base, ext) = os.path.splitext (image)
1383 # URG, makeinfo implicitly prepends dot to extension.
1384 # Specifying no extension is most robust.
1386 alt = self.option_dict[ALT]
1387 info_image_path = os.path.join (global_options.info_images_dir, base)
1388 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1390 base = self.basename ()
1391 str += output[self.format][OUTPUT] % vars ()
1394 def output_latex (self):
1396 base = self.basename ()
1397 if self.format == LATEX:
1398 str += self.output_print_filename (LATEX)
1399 if VERBATIM in self.option_dict:
1400 verb = self.verb_ly ()
1401 str += (output[LATEX][VERBATIM] % vars ())
1403 str += (output[LATEX][OUTPUT] % vars ())
1405 ## todo: maintain breaks
1407 breaks = self.ly ().count ("\n")
1408 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1410 if QUOTE in self.option_dict:
1411 str = output[LATEX][QUOTE] % vars ()
1414 def output_print_filename (self, format):
1416 if PRINTFILENAME in self.option_dict:
1417 base = self.basename ()
1418 filename = os.path.basename (self.substring ('filename'))
1419 str = output[format][PRINTFILENAME] % vars ()
1423 def output_texinfo (self):
1424 str = self.output_print_filename (TEXINFO)
1425 base = self.basename ()
1426 if DOCTITLE in self.option_dict:
1427 doctitle = base + '.doctitle'
1428 translated_doctitle = doctitle + document_language
1429 if os.path.exists (translated_doctitle):
1430 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1431 elif os.path.exists (doctitle):
1432 str += '@lydoctitle %s\n' % open (doctitle).read ()
1433 if TEXIDOC in self.option_dict:
1434 texidoc = base + '.texidoc'
1435 translated_texidoc = texidoc + document_language
1436 if os.path.exists (translated_texidoc):
1437 str += '@include %(translated_texidoc)s\n\n' % vars ()
1438 elif os.path.exists (texidoc):
1439 str += '@include %(texidoc)s\n\n' % vars ()
1442 if VERBATIM in self.option_dict:
1444 if ADDVERSION in self.option_dict:
1445 version = output[TEXINFO][ADDVERSION]
1446 verb = self.verb_ly ()
1447 substr = output[TEXINFO][VERBATIM] % vars ()
1448 substr += self.output_info ()
1449 if LILYQUOTE in self.option_dict:
1450 substr = output[TEXINFO][QUOTE] % {'str':substr}
1453 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1454 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1455 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1457 if QUOTE in self.option_dict:
1458 str = output[TEXINFO][QUOTE] % vars ()
1460 # need par after image
1465 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1466 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1468 class LilypondFileSnippet (LilypondSnippet):
1469 def __init__ (self, type, match, format, line_number):
1470 LilypondSnippet.__init__ (self, type, match, format, line_number)
1471 self.contents = file (find_file (self.substring ('filename'))).read ()
1475 s = re_begin_verbatim.split (s)[-1]
1476 s = re_end_verbatim.split (s)[0]
1477 return verb_ly_gettext (s)
1480 name = self.substring ('filename')
1481 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1482 % (name, self.contents))
1485 class LilyPondVersionString (Snippet):
1486 """A string that does not require extra memory."""
1487 def __init__ (self, type, match, format, line_number):
1488 Snippet.__init__ (self, type, match, format, line_number)
1490 def replacement_text (self):
1491 return output[self.format][self.type]
1494 snippet_type_to_class = {
1495 'lilypond_file': LilypondFileSnippet,
1496 'lilypond_block': LilypondSnippet,
1497 'lilypond': LilypondSnippet,
1498 'include': IncludeSnippet,
1499 'lilypondversion': LilyPondVersionString,
1502 def find_linestarts (s):
1507 i = s.find ('\n', start)
1515 nls.append (len (s))
1518 def find_toplevel_snippets (input_string, format, types):
1521 res[t] = re.compile (snippet_res[format][t])
1525 found = dict ([(t, None) for t in types])
1527 line_starts = find_linestarts (input_string)
1529 # We want to search for multiple regexes, without searching
1530 # the string multiple times for one regex.
1531 # Hence, we use earlier results to limit the string portion
1533 # Since every part of the string is traversed at most once for
1534 # every type of snippet, this is linear.
1540 if not found[type] or found[type][0] < index:
1543 m = res[type].search (input_string[index:endex])
1548 if type in snippet_type_to_class:
1549 klass = snippet_type_to_class[type]
1551 start = index + m.start ('match')
1552 line_number = line_start_idx
1553 while (line_starts[line_number] < start):
1557 snip = klass (type, m, format, line_number)
1559 found[type] = (start, snip)
1563 or found[type][0] < found[first][0])):
1568 # Limiting the search space is a cute
1569 # idea, but this *requires* to search
1570 # for possible containing blocks
1571 # first, at least as long as we do not
1572 # search for the start of blocks, but
1573 # always/directly for the entire
1574 # @block ... @end block.
1576 endex = found[first][0]
1579 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1582 while (start > line_starts[line_start_idx+1]):
1585 (start, snip) = found[first]
1586 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1587 snippets.append (snip)
1589 index = start + len (snip.match.group ('match'))
1593 def filter_pipe (input, cmd):
1594 """Pass input through cmd, and return the result."""
1596 if global_options.verbose:
1597 progress (_ ("Opening filter `%s'") % cmd)
1599 (stdin, stdout, stderr) = os.popen3 (cmd)
1601 status = stdin.close ()
1605 output = stdout.read ()
1606 status = stdout.close ()
1607 error = stderr.read ()
1611 signal = 0x0f & status
1612 if status or (not output and error):
1613 exit_status = status >> 8
1614 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1615 error (_ ("The error log is as follows:"))
1616 ly.stderr_write (error)
1617 ly.stderr_write (stderr.read ())
1620 if global_options.verbose:
1625 def system_in_directory (cmd, directory):
1626 """Execute a command in a different directory.
1628 Because of win32 compatibility, we can't simply use subprocess.
1631 current = os.getcwd()
1632 os.chdir (directory)
1633 ly.system(cmd, be_verbose=global_options.verbose,
1638 def process_snippets (cmd, snippets,
1639 format, lily_output_dir):
1640 """Run cmd on all of the .ly files from snippets."""
1645 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1646 cmd += ' --formats=png '
1647 elif format in (DOCBOOK) and '--formats' not in cmd:
1648 cmd += ' --formats=png,pdf '
1650 checksum = snippet_list_checksum (snippets)
1651 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1652 + [snip.basename() + '.ly' for snip in snippets])
1653 name = os.path.join (lily_output_dir,
1654 'snippet-names-%d.ly' % checksum)
1655 file (name, 'wb').write (contents)
1657 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1662 # Retrieve dimensions from LaTeX
1663 LATEX_INSPECTION_DOCUMENT = r'''
1667 \typeout{textwidth=\the\textwidth}
1668 \typeout{columnsep=\the\columnsep}
1669 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1673 # Do we need anything else besides `textwidth'?
1674 def get_latex_textwidth (source):
1675 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1677 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1679 ## what's a sensible default?
1682 preamble = source[:m.start (0)]
1683 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1685 (handle, tmpfile) = tempfile.mkstemp('.tex')
1686 logfile = os.path.splitext (tmpfile)[0] + '.log'
1687 logfile = os.path.split (logfile)[1]
1689 tmp_handle = os.fdopen (handle,'w')
1690 tmp_handle.write (latex_document)
1693 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1694 be_verbose=global_options.verbose)
1695 parameter_string = file (logfile).read()
1701 m = re.search ('columns=([0-9.]*)', parameter_string)
1703 columns = int (m.group (1))
1706 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1708 columnsep = float (m.group (1))
1711 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1713 textwidth = float (m.group (1))
1715 textwidth = (textwidth - columnsep) / columns
1719 def modify_preamble (chunk):
1720 str = chunk.replacement_text ()
1721 if (re.search (r"\\begin *{document}", str)
1722 and not re.search ("{graphic[sx]", str)):
1723 str = re.sub (r"\\begin{document}",
1724 r"\\usepackage{graphics}" + '\n'
1725 + r"\\begin{document}",
1727 chunk.override_text = str
1732 # TEXINFO: '.texinfo',
1738 class CompileError(Exception):
1741 def snippet_list_checksum (snippets):
1742 return hash (' '.join([l.basename() for l in snippets]))
1744 def write_file_map (lys, name):
1745 snippet_map = file (os.path.join (
1746 global_options.lily_output_dir,
1747 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1749 snippet_map.write ("""
1750 #(define version-seen #t)
1751 #(define output-empty-score-list #f)
1752 #(ly:add-file-name-alist '(%s
1754 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1757 def split_output_files(directory):
1758 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1760 Return value is a set of strings.
1763 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1764 base_subdir = os.path.split (subdir)[1]
1765 sub_files = [os.path.join (base_subdir, name)
1766 for name in os.listdir (subdir)]
1770 def do_process_cmd (chunks, input_name, options):
1771 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1773 output_files = split_output_files (options.lily_output_dir)
1774 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1776 write_file_map (outdated, input_name)
1777 progress (_ ("Writing snippets..."))
1778 for snippet in outdated:
1783 progress (_ ("Processing..."))
1785 process_snippets (options.process_cmd, outdated,
1786 options.format, options.lily_output_dir)
1789 progress (_ ("All snippets are up to date..."))
1791 if options.lily_output_dir != options.output_dir:
1792 output_files = split_output_files (options.lily_output_dir)
1793 for snippet in snippets:
1794 snippet.link_all_output_files (options.lily_output_dir,
1802 # Format guessing data
1811 '.texinfo': TEXINFO,
1816 def guess_format (input_filename):
1818 e = os.path.splitext (input_filename)[1]
1821 format = ext2format[e]
1823 error (_ ("cannot determine format for: %s"
1828 def write_if_updated (file_name, lines):
1830 f = file (file_name)
1832 new_str = ''.join (lines)
1833 if oldstr == new_str:
1834 progress (_ ("%s is up to date.") % file_name)
1837 # this prevents make from always rerunning lilypond-book:
1838 # output file must be touched in order to be up to date
1839 os.utime (file_name, None)
1844 output_dir = os.path.dirname (file_name)
1845 if not os.path.exists (output_dir):
1846 os.makedirs (output_dir)
1848 progress (_ ("Writing `%s'...") % file_name)
1849 file (file_name, 'w').writelines (lines)
1853 def note_input_file (name, inputs=[]):
1854 ## hack: inputs is mutable!
1855 inputs.append (name)
1858 def samefile (f1, f2):
1860 return os.path.samefile (f1, f2)
1861 except AttributeError: # Windoze
1862 f1 = re.sub ("//*", "/", f1)
1863 f2 = re.sub ("//*", "/", f2)
1866 def do_file (input_filename, included=False):
1868 if not input_filename or input_filename == '-':
1869 in_handle = sys.stdin
1870 input_fullname = '<stdin>'
1872 if os.path.exists (input_filename):
1873 input_fullname = input_filename
1874 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1875 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1877 input_fullname = find_file (input_filename)
1879 note_input_file (input_fullname)
1880 in_handle = file (input_fullname)
1882 if input_filename == '-':
1883 input_base = 'stdin'
1885 input_base = os.path.splitext (input_filename)[0]
1887 input_base = os.path.basename (
1888 os.path.splitext (input_filename)[0])
1890 # don't complain when global_options.output_dir is existing
1891 if not global_options.output_dir:
1892 global_options.output_dir = os.getcwd()
1894 global_options.output_dir = os.path.abspath(global_options.output_dir)
1896 if not os.path.isdir (global_options.output_dir):
1897 os.mkdir (global_options.output_dir, 0777)
1898 os.chdir (global_options.output_dir)
1900 output_filename = os.path.join(global_options.output_dir,
1901 input_base + format2ext[global_options.format])
1902 if (os.path.exists (input_filename)
1903 and os.path.exists (output_filename)
1904 and samefile (output_filename, input_fullname)):
1906 _ ("Output would overwrite input file; use --output."))
1910 progress (_ ("Reading %s...") % input_fullname)
1911 source = in_handle.read ()
1914 set_default_options (source, default_ly_options, global_options.format)
1917 # FIXME: Containing blocks must be first, see
1918 # find_toplevel_snippets.
1920 'multiline_comment',
1924 'singleline_comment',
1930 progress (_ ("Dissecting..."))
1931 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1933 if global_options.format == LATEX:
1935 if (c.is_plain () and
1936 re.search (r"\\begin *{document}", c.replacement_text())):
1941 if global_options.filter_cmd:
1942 write_if_updated (output_filename,
1943 [c.filter_text () for c in chunks])
1944 elif global_options.process_cmd:
1945 do_process_cmd (chunks, input_fullname, global_options)
1946 progress (_ ("Compiling %s...") % output_filename)
1948 write_if_updated (output_filename,
1949 [s.replacement_text ()
1952 def process_include (snippet):
1953 os.chdir (original_dir)
1954 name = snippet.substring ('filename')
1955 progress (_ ("Processing include: %s") % name)
1957 return do_file (name, included=True)
1959 include_chunks = map (process_include,
1960 filter (lambda x: isinstance (x, IncludeSnippet),
1963 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1965 except CompileError:
1966 os.chdir (original_dir)
1967 progress (_ ("Removing `%s'") % output_filename)
1972 global global_options
1974 opt_parser = get_option_parser()
1975 (global_options, args) = opt_parser.parse_args ()
1976 if global_options.format in ('texi-html', 'texi'):
1977 global_options.format = TEXINFO
1979 global_options.include_path = map (os.path.abspath, global_options.include_path)
1981 if global_options.warranty:
1984 if not args or len (args) > 1:
1985 opt_parser.print_help ()
1991 # FIXME: 85 lines of `main' macramee??
1992 files = do_options ()
1994 basename = os.path.splitext (files[0])[0]
1995 basename = os.path.split (basename)[1]
1997 if not global_options.format:
1998 global_options.format = guess_format (files[0])
2001 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2004 if global_options.process_cmd == '':
2005 global_options.process_cmd = (lilypond_binary
2006 + ' --formats=%s -dbackend=eps ' % formats)
2008 if global_options.process_cmd:
2009 includes = global_options.include_path
2010 if global_options.lily_output_dir:
2011 # This must be first, so lilypond prefers to read .ly
2012 # files in the other lybookdb dir.
2013 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2014 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2017 if global_options.format in (TEXINFO, LATEX):
2018 ## prevent PDF from being switched on by default.
2019 global_options.process_cmd += ' --formats=eps '
2020 if global_options.create_pdf:
2021 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2023 if global_options.verbose:
2024 global_options.process_cmd += " --verbose "
2026 if global_options.padding_mm:
2027 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2029 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2031 if global_options.lily_output_dir:
2032 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2033 if not os.path.isdir (global_options.lily_output_dir):
2034 os.makedirs (global_options.lily_output_dir)
2036 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2041 chunks = do_file (files[0])
2042 except CompileError:
2045 inputs = note_input_file ('')
2048 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2049 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2050 final_output_file = os.path.join (global_options.output_dir,
2052 + '.%s' % global_options.format)
2054 os.chdir (original_dir)
2055 file (dep_file, 'w').write ('%s: %s'
2056 % (final_output_file, ' '.join (inputs)))
2058 if __name__ == '__main__':