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 original_dir = os.getcwd ()
58 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
62 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
63 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
64 $ lilypond-book --process='lilypond -I include' %(BOOK)s
65 ''' % {'BOOK': _ ("BOOK")})
67 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
68 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
70 ################################################################
72 if global_options.verbose:
73 raise Exception (_ ('Exiting (%d)...') % i)
78 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
80 progress = ly.progress
83 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
86 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
88 def ps_page_count (ps_name):
89 header = file (ps_name).read (1024)
90 m = re.search ('\n%%Pages: ([0-9]+)', header)
92 return int (m.group (1))
97 ly.encoded_write (sys.stdout, '''
104 ''' % ( _ ('Copyright (c) %s by') % '2001--2007',
106 _ ("Distributed under terms of the GNU General Public License."),
107 _ ("It comes with NO WARRANTY.")))
109 def get_option_parser ():
110 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
111 description=help_summary,
112 add_help_option=False)
114 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
117 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
120 p.add_option ('-f', '--format',
121 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
122 metavar=_ ("FORMAT"),
125 p.add_option("-h", "--help",
127 help=_ ("show this help and exit"))
129 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
131 action='append', dest='include_path',
132 default=[os.path.abspath (os.getcwd ())])
134 p.add_option ('--info-images-dir',
135 help=_ ("format Texinfo output so that Info will "
136 "look for images of music in DIR"),
138 action='store', dest='info_images_dir',
141 p.add_option ('--latex-program',
142 help=_ ("run executable PROG instead of latex"),
144 action='store', dest='latex_program',
147 p.add_option ('--left-padding',
150 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
154 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
156 action='store', dest='output_dir',
159 p.add_option ('--skip-lily-check',
160 help=_ ("do not fail if no lilypond output is found"),
162 action='store_true', dest='skip_lilypond_run',
165 p.add_option ('--skip-png-check',
166 help=_ ("do not fail if no PNG images are found for EPS files"),
168 action='store_true', dest='skip_png_check',
171 p.add_option ('--lily-output-dir',
172 help=_ ("write lily-XXX files to DIR, link into --output dir"),
174 action='store', dest='lily_output_dir',
177 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
178 help = _ ("process ly_files using COMMAND FILE..."),
180 dest='process_cmd', default='')
182 p.add_option ('--pdf',
185 help=_ ("create PDF files for use with PDFTeX"),
188 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
193 p.version = "@TOPLEVEL_VERSION@"
194 p.add_option("--version",
196 help=_ ("show version number and exit"))
198 p.add_option ('-w', '--warranty',
199 help=_ ("show warranty and copyright"),
201 p.add_option_group ('',
203 _ ("Report bugs via")
204 + ' http://post.gmane.org/post.php?group=gmane.comp.gnu.lilypond.bugs\n'))
207 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
209 # If we are called with full path, try to use lilypond binary
210 # installed in the same path; this is needed in GUB binaries, where
211 # @bindir is always different from the installed binary path.
212 if 'bindir' in globals () and bindir:
213 lilypond_binary = os.path.join (bindir, 'lilypond')
215 # Only use installed binary when we are installed too.
216 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
217 lilypond_binary = 'lilypond'
219 global_options = None
222 default_ly_options = { 'alt': "[image of music]" }
224 document_language = ''
227 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
229 ADDVERSION = 'addversion'
233 EXAMPLEINDENT = 'exampleindent'
235 FRAGMENT = 'fragment'
241 LINE_WIDTH = 'line-width'
242 LILYQUOTE = 'lilyquote'
243 NOFRAGMENT = 'nofragment'
244 NOINDENT = 'noindent'
246 NORAGGED_RIGHT = 'noragged-right'
250 OUTPUTIMAGE = 'outputimage'
253 PREAMBLE = 'preamble'
254 PRINTFILENAME = 'printfilename'
256 RAGGED_RIGHT = 'ragged-right'
257 RELATIVE = 'relative'
258 STAFFSIZE = 'staffsize'
259 DOCTITLE = 'doctitle'
262 VERBATIM = 'verbatim'
263 FONTLOAD = 'fontload'
264 FILENAME = 'filename'
268 # NOTIME has no opposite so it isn't part of this dictionary.
269 # NOQUOTE is used internally only.
271 NOFRAGMENT: FRAGMENT,
276 # Recognize special sequences in the input.
278 # (?P<name>regex) -- Assign result of REGEX to NAME.
279 # *? -- Match non-greedily.
280 # (?m) -- Multiline regex: Make ^ and $ match at each line.
281 # (?s) -- Make the dot match all characters including newline.
282 # (?x) -- Ignore whitespace in patterns.
293 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
298 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
303 <(?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>)''',
309 (?P<code><!--\s.*?!-->)
312 'singleline_comment':
331 (\s*(?P<options>.*?)\s*:)?\s*
339 \s*(?P<options>.*?)\s*
348 \s*(?P<options>.*?)\s*
350 \s*(?P<filename>.*?)\s*
357 (?P<code><!--\s.*?!-->)
360 'singleline_comment':
366 (?P<code><pre>.*?</pre>))''',
372 (?P<code><pre>\s.*?</pre>\s))''',
391 \s*(?P<options>.*?)\s*
402 \s*(?P<options>.*?)\s*
406 \\end\s*{lilypond})''',
414 \s*(?P<options>.*?)\s*
422 'singleline_comment':
445 \\end\s*{verbatim}))''',
454 (?P<filename>\S+))''',
458 ^[^\n]*?(?!@c\s+)[^\n]*?
462 \s*(?P<options>.*?)\s*
472 \s*(?P<options>.*?)\s*
475 ^@end\s+lilypond)\s''',
482 \s*(?P<options>.*?)\s*
493 @end\s+ignore))\s''',
495 'singleline_comment':
500 @c([ \t][^\n]*|)\n))''',
502 # Don't do this: It interferes with @code{@{}.
503 # 'verb': r'''(?P<code>@code{.*?})''',
511 @end\s+example\s))''',
520 'intertext': r',?\s*intertext=\".*?\"',
524 'intertext': r',?\s*intertext=\".*?\"',
529 'intertext': r',?\s*intertext=\".*?\"',
530 'option_sep': '\s*,\s*',
534 'intertext': r',?\s*intertext=\".*?\"',
535 'option_sep': '\s*,\s*',
539 # Options without a pattern in ly_options.
559 RELATIVE: r'''\relative c%(relative_quotes)s''',
564 INDENT: r'''indent = %(indent)s''',
566 LINE_WIDTH: r'''line-width = %(line-width)s''',
568 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
570 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
572 RAGGED_RIGHT: r'''ragged-right = ##t''',
574 NORAGGED_RIGHT: r'''ragged-right = ##f''',
576 PACKED: r'''packed = ##t''',
588 \remove "Time_signature_engraver"
594 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
601 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
604 <imageobject role="latex">
605 <imagedata fileref="%(base)s.pdf" format="PDF"/>
607 <imageobject role="html">
608 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
610 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
612 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
616 FILTER: r'''<lilypond %(options)s>
626 <a href="%(base)s.ly">''',
630 border="0" src="%(image)s" alt="%(alt)s">''',
632 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
634 QUOTE: r'''<blockquote>
647 \ifx\preLilyPondExample \undefined%%
650 \preLilyPondExample%%
652 \def\lilypondbook{}%%
653 \input %(base)s-systems.tex%%
654 \ifx\postLilyPondExample \undefined%%
657 \postLilyPondExample%%
661 PRINTFILENAME: '''\\texttt{%(filename)s}
664 QUOTE: r'''\begin{quotation}%(str)s
667 VERBATIM: r'''\noindent
668 \begin{verbatim}%(verb)s\end{verbatim}''',
670 FILTER: r'''\begin{lilypond}[%(options)s]
677 FILTER: r'''@lilypond[%(options)s]
683 @include %(base)s-systems.texi
687 OUTPUTIMAGE: r'''@noindent
689 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
693 <a href="%(base)s.ly">
695 border="0" src="%(image)s" alt="%(alt)s">
703 <a href="%(base)s.ly">
711 QUOTE: r'''@quotation
712 %(str)s@end quotation
719 VERBATIM: r'''@exampleindent 0
721 %(verb)s@end verbatim
724 ADDVERSION: r'''@example
725 \version @w{"@version{}"}
732 # Maintain line numbers.
737 for f in [HTML, LATEX]:
738 for s in (QUOTE, VERBATIM):
739 output[f][s] = output[f][s].replace("\n"," ")
742 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
743 %%%% Options: [%(option_string)s]
744 \\include "lilypond-book-preamble.ly"
747 %% ****************************************************************
748 %% Start cut-&-pastable-section
749 %% ****************************************************************
754 #(define dump-extents #t)
755 %(font_dump_setting)s
757 force-assignment = #""
758 line-width = #(- line-width (* mm %(padding_mm)f))
771 %% ****************************************************************
772 %% ly snippet contents follows:
773 %% ****************************************************************
777 %% ****************************************************************
779 %% ****************************************************************
786 %% ****************************************************************
788 %% ****************************************************************
792 %% ****************************************************************
794 %% ****************************************************************
797 texinfo_line_widths = {
798 '@afourpaper': '160\\mm',
799 '@afourwide': '6.5\\in',
800 '@afourlatex': '150\\mm',
801 '@smallbook': '5\\in',
802 '@letterpaper': '6\\in',
805 def classic_lilypond_book_compatibility (key, value):
806 if key == 'singleline' and value == None:
807 return (RAGGED_RIGHT, None)
809 m = re.search ('relative\s*([-0-9])', key)
811 return ('relative', m.group (1))
813 m = re.match ('([0-9]+)pt', key)
815 return ('staffsize', m.group (1))
817 if key == 'indent' or key == 'line-width':
818 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
820 f = float (m.group (1))
821 return (key, '%f\\%s' % (f, m.group (2)))
825 def find_file (name, raise_error=True):
826 for i in global_options.include_path:
827 full = os.path.join (i, name)
828 if os.path.exists (full):
832 error (_ ("file not found: %s") % name + '\n')
836 def verbatim_html (s):
837 return re.sub ('>', '>',
839 re.sub ('&', '&', s)))
841 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
842 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
844 def ly_comment_gettext (t, m):
845 return m.group (1) + t (m.group (2))
847 def verb_ly_gettext (s):
848 if not document_language:
851 t = langdefs.translation[document_language]
855 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
857 for v in ly_var_def_re.findall (s):
858 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
859 "\\1" + t (v) + "\\2",
863 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
864 def set_default_options (source, default_ly_options, format):
865 global document_language
866 if LINE_WIDTH not in default_ly_options:
868 textwidth = get_latex_textwidth (source)
869 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
870 elif format == TEXINFO:
871 m = texinfo_lang_re.search (source)
872 if m and not m.group (1).startswith ('en'):
873 document_language = m.group (1)
875 document_language = ''
876 for regex in texinfo_line_widths:
877 # FIXME: @layout is usually not in
880 # \input texinfo @c -*-texinfo-*-
882 # Bluntly search first K items of
884 # s = chunks[0].replacement_text ()
885 if re.search (regex, source[:1024]):
886 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
890 def replacement_text (self):
893 def filter_text (self):
894 return self.replacement_text ()
899 class Substring (Chunk):
900 """A string that does not require extra memory."""
901 def __init__ (self, source, start, end, line_number):
905 self.line_number = line_number
906 self.override_text = None
911 def replacement_text (self):
912 if self.override_text:
913 return self.override_text
915 return self.source[self.start:self.end]
917 class Snippet (Chunk):
918 def __init__ (self, type, match, format, line_number):
922 self.option_dict = {}
924 self.line_number = line_number
926 def replacement_text (self):
927 return self.match.group ('match')
929 def substring (self, s):
930 return self.match.group (s)
933 return `self.__class__` + ' type = ' + self.type
935 class IncludeSnippet (Snippet):
936 def processed_filename (self):
937 f = self.substring ('filename')
938 return os.path.splitext (f)[0] + format2ext[self.format]
940 def replacement_text (self):
941 s = self.match.group ('match')
942 f = self.substring ('filename')
944 return re.sub (f, self.processed_filename (), s)
946 class LilypondSnippet (Snippet):
947 def __init__ (self, type, match, format, line_number):
948 Snippet.__init__ (self, type, match, format, line_number)
949 os = match.group ('options')
950 self.do_options (os, self.type)
953 return verb_ly_gettext (self.substring ('code'))
956 contents = self.substring ('code')
957 return ('\\sourcefileline %d\n%s'
958 % (self.line_number - 1, contents))
963 return self.compose_ly (s)
966 def split_options (self, option_string):
968 if self.format == HTML:
969 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
971 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
975 return re.split (format_res[self.format]['option_sep'],
979 def do_options (self, option_string, type):
980 self.option_dict = {}
982 options = self.split_options (option_string)
984 for option in options:
986 (key, value) = re.split ('\s*=\s*', option)
987 self.option_dict[key] = value
989 if option in no_options:
990 if no_options[option] in self.option_dict:
991 del self.option_dict[no_options[option]]
993 self.option_dict[option] = None
995 has_line_width = self.option_dict.has_key (LINE_WIDTH)
996 no_line_width_value = 0
998 # If LINE_WIDTH is used without parameter, set it to default.
999 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1000 no_line_width_value = 1
1001 del self.option_dict[LINE_WIDTH]
1003 for k in default_ly_options:
1004 if k not in self.option_dict:
1005 self.option_dict[k] = default_ly_options[k]
1007 # RELATIVE does not work without FRAGMENT;
1008 # make RELATIVE imply FRAGMENT
1009 has_relative = self.option_dict.has_key (RELATIVE)
1010 if has_relative and not self.option_dict.has_key (FRAGMENT):
1011 self.option_dict[FRAGMENT] = None
1013 if not has_line_width:
1014 if type == 'lilypond' or FRAGMENT in self.option_dict:
1015 self.option_dict[RAGGED_RIGHT] = None
1017 if type == 'lilypond':
1018 if LINE_WIDTH in self.option_dict:
1019 del self.option_dict[LINE_WIDTH]
1021 if RAGGED_RIGHT in self.option_dict:
1022 if LINE_WIDTH in self.option_dict:
1023 del self.option_dict[LINE_WIDTH]
1025 if QUOTE in self.option_dict or type == 'lilypond':
1026 if LINE_WIDTH in self.option_dict:
1027 del self.option_dict[LINE_WIDTH]
1029 if not INDENT in self.option_dict:
1030 self.option_dict[INDENT] = '0\\mm'
1032 # The QUOTE pattern from ly_options only emits the `line-width'
1034 if has_line_width and QUOTE in self.option_dict:
1035 if no_line_width_value:
1036 del self.option_dict[LINE_WIDTH]
1038 del self.option_dict[QUOTE]
1040 def compose_ly (self, code):
1041 if FRAGMENT in self.option_dict:
1049 # The original concept of the `exampleindent' option is broken.
1050 # It is not possible to get a sane value for @exampleindent at all
1051 # without processing the document itself. Saying
1059 # causes ugly results with the DVI backend of texinfo since the
1060 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1061 # value). Executing the above code changes the environment
1062 # indentation to an unknown value because we don't know the amount
1063 # of 1em in advance since it is font-dependent. Modifying
1064 # @exampleindent in the middle of a document is simply not
1065 # supported within texinfo.
1067 # As a consequence, the only function of @exampleindent is now to
1068 # specify the amount of indentation for the `quote' option.
1070 # To set @exampleindent locally to zero, we use the @format
1071 # environment for non-quoted snippets.
1072 override[EXAMPLEINDENT] = r'0.4\in'
1073 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1074 override.update (default_ly_options)
1077 for (key, value) in self.option_dict.items ():
1079 option_list.append (key)
1081 option_list.append (key + '=' + value)
1082 option_string = ','.join (option_list)
1085 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1086 for a in compose_types:
1087 compose_dict[a] = []
1089 for (key, value) in self.option_dict.items ():
1090 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1094 _ ("deprecated ly-option used: %s=%s") % (key, value))
1096 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1099 _ ("deprecated ly-option used: %s") % key)
1101 _ ("compatibility mode translation: %s") % c_key)
1103 (key, value) = (c_key, c_value)
1106 override[key] = value
1108 if not override.has_key (key):
1109 override[key] = None
1112 for type in compose_types:
1113 if ly_options[type].has_key (key):
1114 compose_dict[type].append (ly_options[type][key])
1118 if not found and key not in simple_options:
1119 warning (_ ("ignoring unknown ly option: %s") % key)
1122 if RELATIVE in override and override[RELATIVE]:
1123 relative = int (override[RELATIVE])
1125 relative_quotes = ''
1129 relative_quotes += ',' * (- relative)
1131 relative_quotes += "'" * relative
1133 paper_string = '\n '.join (compose_dict[PAPER]) % override
1134 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1135 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1136 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1137 padding_mm = global_options.padding_mm
1138 font_dump_setting = ''
1139 if FONTLOAD in self.option_dict:
1140 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1142 d = globals().copy()
1144 return (PREAMBLE_LY + body) % d
1146 def get_checksum (self):
1147 if not self.checksum:
1148 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1150 ## let's not create too long names.
1151 self.checksum = hash.hexdigest ()[:10]
1153 return self.checksum
1155 def basename (self):
1156 cs = self.get_checksum ()
1157 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1160 def write_ly (self):
1161 base = self.basename ()
1162 path = os.path.join (global_options.lily_output_dir, base)
1163 directory = os.path.split(path)[0]
1164 if not os.path.isdir (directory):
1165 os.makedirs (directory)
1166 out = file (path + '.ly', 'w')
1167 out.write (self.full_ly ())
1168 file (path + '.txt', 'w').write ('image of music')
1170 def relevant_contents (self, ly):
1171 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1173 def link_all_output_files (self, output_dir, output_dir_files, destination):
1174 existing, missing = self.all_output_files (output_dir, output_dir_files)
1176 print '\nMissing', missing
1177 raise CompileError(self.basename())
1178 for name in existing:
1180 os.unlink (os.path.join (destination, name))
1184 src = os.path.join (output_dir, name)
1185 dst = os.path.join (destination, name)
1186 dst_path = os.path.split(dst)[0]
1187 if not os.path.isdir (dst_path):
1188 os.makedirs (dst_path)
1192 def all_output_files (self, output_dir, output_dir_files):
1193 """Return all files generated in lily_output_dir, a set.
1195 output_dir_files is the list of files in the output directory.
1199 base = self.basename()
1200 full = os.path.join (output_dir, base)
1201 def consider_file (name):
1202 if name in output_dir_files:
1205 def require_file (name):
1206 if name in output_dir_files:
1211 # UGH - junk global_options
1212 skip_lily = global_options.skip_lilypond_run
1213 for required in [base + '.ly',
1215 require_file (required)
1217 require_file (base + '-systems.count')
1219 if 'ddump-profile' in global_options.process_cmd:
1220 require_file (base + '.profile')
1221 if 'dseparate-log-file' in global_options.process_cmd:
1222 require_file (base + '.log')
1224 map (consider_file, [base + '.tex',
1228 base + '-systems.texi',
1229 base + '-systems.tex',
1230 base + '-systems.pdftexi'])
1231 if document_language:
1233 [base + '.texidoc' + document_language,
1234 base + '.doctitle' + document_language])
1236 # UGH - junk global_options
1237 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1238 and not global_options.skip_png_check):
1239 page_count = ps_page_count (full + '.eps')
1241 require_file (base + '.png')
1243 for page in range (1, page_count + 1):
1244 require_file (base + '-page%d.png' % page)
1247 if not skip_lily and not missing:
1248 system_count = int(file (full + '-systems.count').read())
1250 for number in range(1, system_count + 1):
1251 systemfile = '%s-%d' % (base, number)
1252 require_file (systemfile + '.eps')
1253 consider_file (systemfile + '.pdf')
1255 # We can't require signatures, since books and toplevel
1256 # markups do not output a signature.
1257 if 'ddump-signature' in global_options.process_cmd:
1258 consider_file (systemfile + '.signature')
1261 return (result, missing)
1263 def is_outdated (self, output_dir, current_files):
1264 found, missing = self.all_output_files (output_dir, current_files)
1267 def filter_text (self):
1268 """Run snippet bodies through a command (say: convert-ly).
1270 This functionality is rarely used, and this code must have bitrot.
1272 code = self.substring ('code')
1273 s = filter_pipe (code, global_options.filter_cmd)
1276 'options': self.match.group ('options')
1279 return output[self.format][FILTER] % d
1281 def replacement_text (self):
1282 func = LilypondSnippet.__dict__['output_' + self.format]
1285 def get_images (self):
1286 base = self.basename ()
1288 single = '%(base)s.png' % vars ()
1289 multiple = '%(base)s-page1.png' % vars ()
1291 if (os.path.exists (multiple)
1292 and (not os.path.exists (single)
1293 or (os.stat (multiple)[stat.ST_MTIME]
1294 > os.stat (single)[stat.ST_MTIME]))):
1295 count = ps_page_count ('%(base)s.eps' % vars ())
1296 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1297 images = tuple (images)
1301 def output_docbook (self):
1303 base = self.basename ()
1304 for image in self.get_images ():
1305 (base, ext) = os.path.splitext (image)
1306 str += output[DOCBOOK][OUTPUT] % vars ()
1307 str += self.output_print_filename (DOCBOOK)
1308 if (self.substring('inline') == 'inline'):
1309 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1311 str = '<mediaobject>' + str + '</mediaobject>'
1312 if VERBATIM in self.option_dict:
1313 verb = verbatim_html (self.verb_ly ())
1314 str = output[DOCBOOK][VERBATIM] % vars () + str
1317 def output_html (self):
1319 base = self.basename ()
1320 if self.format == HTML:
1321 str += self.output_print_filename (HTML)
1322 if VERBATIM in self.option_dict:
1323 verb = verbatim_html (self.verb_ly ())
1324 str += output[HTML][VERBATIM] % vars ()
1325 if QUOTE in self.option_dict:
1326 str = output[HTML][QUOTE] % vars ()
1328 str += output[HTML][BEFORE] % vars ()
1329 for image in self.get_images ():
1330 (base, ext) = os.path.splitext (image)
1331 alt = self.option_dict[ALT]
1332 str += output[HTML][OUTPUT] % vars ()
1333 str += output[HTML][AFTER] % vars ()
1336 def output_info (self):
1338 for image in self.get_images ():
1339 (base, ext) = os.path.splitext (image)
1341 # URG, makeinfo implicitly prepends dot to extension.
1342 # Specifying no extension is most robust.
1344 alt = self.option_dict[ALT]
1345 info_image_path = os.path.join (global_options.info_images_dir, base)
1346 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1348 base = self.basename ()
1349 str += output[self.format][OUTPUT] % vars ()
1352 def output_latex (self):
1354 base = self.basename ()
1355 if self.format == LATEX:
1356 str += self.output_print_filename (LATEX)
1357 if VERBATIM in self.option_dict:
1358 verb = self.verb_ly ()
1359 str += (output[LATEX][VERBATIM] % vars ())
1361 str += (output[LATEX][OUTPUT] % vars ())
1363 ## todo: maintain breaks
1365 breaks = self.ly ().count ("\n")
1366 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1368 if QUOTE in self.option_dict:
1369 str = output[LATEX][QUOTE] % vars ()
1372 def output_print_filename (self, format):
1374 if PRINTFILENAME in self.option_dict:
1375 base = self.basename ()
1376 filename = os.path.basename (self.substring ('filename'))
1377 str = output[format][PRINTFILENAME] % vars ()
1381 def output_texinfo (self):
1382 str = self.output_print_filename (TEXINFO)
1383 base = self.basename ()
1384 if DOCTITLE in self.option_dict:
1385 doctitle = base + '.doctitle'
1386 translated_doctitle = doctitle + document_language
1387 if os.path.exists (translated_doctitle):
1388 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1389 elif os.path.exists (doctitle):
1390 str += '@lydoctitle %s\n' % open (doctitle).read ()
1391 if TEXIDOC in self.option_dict:
1392 texidoc = base + '.texidoc'
1393 translated_texidoc = texidoc + document_language
1394 if os.path.exists (translated_texidoc):
1395 str += '@include %(translated_texidoc)s\n\n' % vars ()
1396 elif os.path.exists (texidoc):
1397 str += '@include %(texidoc)s\n\n' % vars ()
1400 if VERBATIM in self.option_dict:
1402 if ADDVERSION in self.option_dict:
1403 version = output[TEXINFO][ADDVERSION]
1404 verb = self.verb_ly ()
1405 substr = output[TEXINFO][VERBATIM] % vars ()
1406 substr += self.output_info ()
1407 if LILYQUOTE in self.option_dict:
1408 substr = output[TEXINFO][QUOTE] % {'str':substr}
1411 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1412 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1413 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1415 if QUOTE in self.option_dict:
1416 str = output[TEXINFO][QUOTE] % vars ()
1418 # need par after image
1423 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1424 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1426 class LilypondFileSnippet (LilypondSnippet):
1427 def __init__ (self, type, match, format, line_number):
1428 LilypondSnippet.__init__ (self, type, match, format, line_number)
1429 self.contents = file (find_file (self.substring ('filename'))).read ()
1433 s = re_begin_verbatim.split (s)[-1]
1434 s = re_end_verbatim.split (s)[0]
1435 return verb_ly_gettext (s)
1438 name = self.substring ('filename')
1439 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1440 % (name, self.contents))
1443 snippet_type_to_class = {
1444 'lilypond_file': LilypondFileSnippet,
1445 'lilypond_block': LilypondSnippet,
1446 'lilypond': LilypondSnippet,
1447 'include': IncludeSnippet,
1450 def find_linestarts (s):
1455 i = s.find ('\n', start)
1463 nls.append (len (s))
1466 def find_toplevel_snippets (input_string, format, types):
1469 res[t] = re.compile (snippet_res[format][t])
1473 found = dict ([(t, None) for t in types])
1475 line_starts = find_linestarts (input_string)
1477 # We want to search for multiple regexes, without searching
1478 # the string multiple times for one regex.
1479 # Hence, we use earlier results to limit the string portion
1481 # Since every part of the string is traversed at most once for
1482 # every type of snippet, this is linear.
1488 if not found[type] or found[type][0] < index:
1491 m = res[type].search (input_string[index:endex])
1496 if type in snippet_type_to_class:
1497 klass = snippet_type_to_class[type]
1499 start = index + m.start ('match')
1500 line_number = line_start_idx
1501 while (line_starts[line_number] < start):
1505 snip = klass (type, m, format, line_number)
1507 found[type] = (start, snip)
1511 or found[type][0] < found[first][0])):
1516 # Limiting the search space is a cute
1517 # idea, but this *requires* to search
1518 # for possible containing blocks
1519 # first, at least as long as we do not
1520 # search for the start of blocks, but
1521 # always/directly for the entire
1522 # @block ... @end block.
1524 endex = found[first][0]
1527 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1530 while (start > line_starts[line_start_idx+1]):
1533 (start, snip) = found[first]
1534 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1535 snippets.append (snip)
1537 index = start + len (snip.match.group ('match'))
1541 def filter_pipe (input, cmd):
1542 """Pass input through cmd, and return the result."""
1544 if global_options.verbose:
1545 progress (_ ("Opening filter `%s'") % cmd)
1547 (stdin, stdout, stderr) = os.popen3 (cmd)
1549 status = stdin.close ()
1553 output = stdout.read ()
1554 status = stdout.close ()
1555 error = stderr.read ()
1559 signal = 0x0f & status
1560 if status or (not output and error):
1561 exit_status = status >> 8
1562 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1563 error (_ ("The error log is as follows:"))
1564 ly.stderr_write (error)
1565 ly.stderr_write (stderr.read ())
1568 if global_options.verbose:
1573 def system_in_directory (cmd, directory):
1574 """Execute a command in a different directory.
1576 Because of win32 compatibility, we can't simply use subprocess.
1579 current = os.getcwd()
1580 os.chdir (directory)
1581 ly.system(cmd, be_verbose=global_options.verbose,
1586 def process_snippets (cmd, snippets,
1587 format, lily_output_dir):
1588 """Run cmd on all of the .ly files from snippets."""
1593 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1594 cmd += ' --formats=png '
1595 elif format in (DOCBOOK) and '--formats' not in cmd:
1596 cmd += ' --formats=png,pdf '
1598 checksum = snippet_list_checksum (snippets)
1599 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1600 + [snip.basename() + '.ly' for snip in snippets])
1601 name = os.path.join (lily_output_dir,
1602 'snippet-names-%d.ly' % checksum)
1603 file (name, 'wb').write (contents)
1605 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1610 # Retrieve dimensions from LaTeX
1611 LATEX_INSPECTION_DOCUMENT = r'''
1615 \typeout{textwidth=\the\textwidth}
1616 \typeout{columnsep=\the\columnsep}
1617 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1621 # Do we need anything else besides `textwidth'?
1622 def get_latex_textwidth (source):
1623 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1625 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1627 ## what's a sensible default?
1630 preamble = source[:m.start (0)]
1631 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1633 (handle, tmpfile) = tempfile.mkstemp('.tex')
1634 logfile = os.path.splitext (tmpfile)[0] + '.log'
1635 logfile = os.path.split (logfile)[1]
1637 tmp_handle = os.fdopen (handle,'w')
1638 tmp_handle.write (latex_document)
1641 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1642 be_verbose=global_options.verbose)
1643 parameter_string = file (logfile).read()
1649 m = re.search ('columns=([0-9.]*)', parameter_string)
1651 columns = int (m.group (1))
1654 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1656 columnsep = float (m.group (1))
1659 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1661 textwidth = float (m.group (1))
1663 textwidth = (textwidth - columnsep) / columns
1667 def modify_preamble (chunk):
1668 str = chunk.replacement_text ()
1669 if (re.search (r"\\begin *{document}", str)
1670 and not re.search ("{graphic[sx]", str)):
1671 str = re.sub (r"\\begin{document}",
1672 r"\\usepackage{graphics}" + '\n'
1673 + r"\\begin{document}",
1675 chunk.override_text = str
1680 # TEXINFO: '.texinfo',
1686 class CompileError(Exception):
1689 def snippet_list_checksum (snippets):
1690 return hash (' '.join([l.basename() for l in snippets]))
1692 def write_file_map (lys, name):
1693 snippet_map = file (os.path.join (
1694 global_options.lily_output_dir,
1695 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1697 snippet_map.write ("""
1698 #(define version-seen #t)
1699 #(define output-empty-score-list #f)
1700 #(ly:add-file-name-alist '(%s
1702 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1705 def split_output_files(directory):
1706 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1708 Return value is a set of strings.
1711 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1712 base_subdir = os.path.split (subdir)[1]
1713 sub_files = [os.path.join (base_subdir, name)
1714 for name in os.listdir (subdir)]
1718 def do_process_cmd (chunks, input_name, options):
1719 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1721 output_files = split_output_files (options.lily_output_dir)
1722 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1724 write_file_map (outdated, input_name)
1725 progress (_ ("Writing snippets..."))
1726 for snippet in outdated:
1731 progress (_ ("Processing..."))
1733 process_snippets (options.process_cmd, outdated,
1734 options.format, options.lily_output_dir)
1737 progress (_ ("All snippets are up to date..."))
1739 if options.lily_output_dir != options.output_dir:
1740 output_files = split_output_files (options.lily_output_dir)
1741 for snippet in snippets:
1742 snippet.link_all_output_files (options.lily_output_dir,
1750 # Format guessing data
1759 '.texinfo': TEXINFO,
1764 def guess_format (input_filename):
1766 e = os.path.splitext (input_filename)[1]
1769 format = ext2format[e]
1771 error (_ ("cannot determine format for: %s"
1776 def write_if_updated (file_name, lines):
1778 f = file (file_name)
1780 new_str = ''.join (lines)
1781 if oldstr == new_str:
1782 progress (_ ("%s is up to date.") % file_name)
1785 # this prevents make from always rerunning lilypond-book:
1786 # output file must be touched in order to be up to date
1787 os.utime (file_name, None)
1792 output_dir = os.path.dirname (file_name)
1793 if not os.path.exists (output_dir):
1794 os.makedirs (output_dir)
1796 progress (_ ("Writing `%s'...") % file_name)
1797 file (file_name, 'w').writelines (lines)
1801 def note_input_file (name, inputs=[]):
1802 ## hack: inputs is mutable!
1803 inputs.append (name)
1806 def samefile (f1, f2):
1808 return os.path.samefile (f1, f2)
1809 except AttributeError: # Windoze
1810 f1 = re.sub ("//*", "/", f1)
1811 f2 = re.sub ("//*", "/", f2)
1814 def do_file (input_filename, included=False):
1816 if not input_filename or input_filename == '-':
1817 in_handle = sys.stdin
1818 input_fullname = '<stdin>'
1820 if os.path.exists (input_filename):
1821 input_fullname = input_filename
1822 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1823 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1825 input_fullname = find_file (input_filename)
1827 note_input_file (input_fullname)
1828 in_handle = file (input_fullname)
1830 if input_filename == '-':
1831 input_base = 'stdin'
1833 input_base = os.path.splitext (input_filename)[0]
1835 input_base = os.path.basename (
1836 os.path.splitext (input_filename)[0])
1838 # don't complain when global_options.output_dir is existing
1839 if not global_options.output_dir:
1840 global_options.output_dir = os.getcwd()
1842 global_options.output_dir = os.path.abspath(global_options.output_dir)
1844 if not os.path.isdir (global_options.output_dir):
1845 os.mkdir (global_options.output_dir, 0777)
1846 os.chdir (global_options.output_dir)
1848 output_filename = os.path.join(global_options.output_dir,
1849 input_base + format2ext[global_options.format])
1850 if (os.path.exists (input_filename)
1851 and os.path.exists (output_filename)
1852 and samefile (output_filename, input_fullname)):
1854 _ ("Output would overwrite input file; use --output."))
1858 progress (_ ("Reading %s...") % input_fullname)
1859 source = in_handle.read ()
1862 set_default_options (source, default_ly_options, global_options.format)
1865 # FIXME: Containing blocks must be first, see
1866 # find_toplevel_snippets.
1868 'multiline_comment',
1872 'singleline_comment',
1877 progress (_ ("Dissecting..."))
1878 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1880 if global_options.format == LATEX:
1882 if (c.is_plain () and
1883 re.search (r"\\begin *{document}", c.replacement_text())):
1888 if global_options.filter_cmd:
1889 write_if_updated (output_filename,
1890 [c.filter_text () for c in chunks])
1891 elif global_options.process_cmd:
1892 do_process_cmd (chunks, input_fullname, global_options)
1893 progress (_ ("Compiling %s...") % output_filename)
1895 write_if_updated (output_filename,
1896 [s.replacement_text ()
1899 def process_include (snippet):
1900 os.chdir (original_dir)
1901 name = snippet.substring ('filename')
1902 progress (_ ("Processing include: %s") % name)
1904 return do_file (name, included=True)
1906 include_chunks = map (process_include,
1907 filter (lambda x: isinstance (x, IncludeSnippet),
1910 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1912 except CompileError:
1913 os.chdir (original_dir)
1914 progress (_ ("Removing `%s'") % output_filename)
1919 global global_options
1921 opt_parser = get_option_parser()
1922 (global_options, args) = opt_parser.parse_args ()
1923 if global_options.format in ('texi-html', 'texi'):
1924 global_options.format = TEXINFO
1926 global_options.include_path = map (os.path.abspath, global_options.include_path)
1928 if global_options.warranty:
1931 if not args or len (args) > 1:
1932 opt_parser.print_help ()
1938 # FIXME: 85 lines of `main' macramee??
1939 files = do_options ()
1941 basename = os.path.splitext (files[0])[0]
1942 basename = os.path.split (basename)[1]
1944 if not global_options.format:
1945 global_options.format = guess_format (files[0])
1948 if global_options.format in (TEXINFO, HTML, DOCBOOK):
1951 if global_options.process_cmd == '':
1952 global_options.process_cmd = (lilypond_binary
1953 + ' --formats=%s -dbackend=eps ' % formats)
1955 if global_options.process_cmd:
1956 includes = global_options.include_path
1957 if global_options.lily_output_dir:
1958 # This must be first, so lilypond prefers to read .ly
1959 # files in the other lybookdb dir.
1960 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
1961 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
1964 if global_options.format in (TEXINFO, LATEX):
1965 ## prevent PDF from being switched on by default.
1966 global_options.process_cmd += ' --formats=eps '
1967 if global_options.create_pdf:
1968 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
1970 if global_options.verbose:
1971 global_options.process_cmd += " --verbose "
1973 if global_options.padding_mm:
1974 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
1976 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
1978 if global_options.lily_output_dir:
1979 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
1980 if not os.path.isdir (global_options.lily_output_dir):
1981 os.makedirs (global_options.lily_output_dir)
1983 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
1988 chunks = do_file (files[0])
1989 except CompileError:
1992 inputs = note_input_file ('')
1995 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
1996 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
1997 final_output_file = os.path.join (global_options.output_dir,
1999 + '.%s' % global_options.format)
2001 os.chdir (original_dir)
2002 file (dep_file, 'w').write ('%s: %s'
2003 % (final_output_file, ' '.join (inputs)))
2005 if __name__ == '__main__':