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 NOGETTEXT = 'nogettext'
257 NOINDENT = 'noindent'
259 NORAGGED_RIGHT = 'noragged-right'
263 OUTPUTIMAGE = 'outputimage'
265 PREAMBLE = 'preamble'
266 PRINTFILENAME = 'printfilename'
268 RAGGED_RIGHT = 'ragged-right'
269 RELATIVE = 'relative'
270 STAFFSIZE = 'staffsize'
271 DOCTITLE = 'doctitle'
274 VERBATIM = 'verbatim'
275 VERSION = 'lilypondversion'
276 FONTLOAD = 'fontload'
277 FILENAME = 'filename'
281 # NOTIME has no opposite so it isn't part of this dictionary.
282 # NOQUOTE is used internally only.
284 NOFRAGMENT: FRAGMENT,
289 # Recognize special sequences in the input.
291 # (?P<name>regex) -- Assign result of REGEX to NAME.
292 # *? -- Match non-greedily.
293 # (?m) -- Multiline regex: Make ^ and $ match at each line.
294 # (?s) -- Make the dot match all characters including newline.
295 # (?x) -- Ignore whitespace in patterns.
306 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
311 <(?P<inline>(inline)?)mediaobject>\s*<textobject.*?>\s*<programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>(?P<code>.*?)</programlisting\s*>\s*</textobject\s*>\s*</(inline)?mediaobject>)''',
316 <(?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>)''',
322 (?P<code><!--\s.*?!-->)
325 'singleline_comment':
346 (\s*(?P<options>.*?)\s*:)?\s*
354 \s*(?P<options>.*?)\s*
363 \s*(?P<options>.*?)\s*
365 \s*(?P<filename>.*?)\s*
372 (?P<code><!--\s.*?!-->)
375 'singleline_comment':
381 (?P<code><pre>.*?</pre>))''',
387 (?P<code><pre>\s.*?</pre>\s))''',
392 <lilypondversion\s*/>)''',
411 \s*(?P<options>.*?)\s*
422 \s*(?P<options>.*?)\s*
426 \\end\s*{lilypond})''',
434 \s*(?P<options>.*?)\s*
442 'singleline_comment':
465 \\end\s*{verbatim}))''',
470 \\lilypondversion)[^a-zA-Z]''',
480 (?P<filename>\S+))''',
484 ^[^\n]*?(?!@c\s+)[^\n]*?
488 \s*(?P<options>.*?)\s*
498 \s*(?P<options>.*?)\s*
501 ^@end\s+lilypond)\s''',
508 \s*(?P<options>.*?)\s*
519 @end\s+ignore))\s''',
521 'singleline_comment':
526 @c([ \t][^\n]*|)\n))''',
528 # Don't do this: It interferes with @code{@{}.
529 # 'verb': r'''(?P<code>@code{.*?})''',
537 @end\s+example\s))''',
542 @lilypondversion)[^a-zA-Z]''',
552 'intertext': r',?\s*intertext=\".*?\"',
556 'intertext': r',?\s*intertext=\".*?\"',
561 'intertext': r',?\s*intertext=\".*?\"',
562 'option_sep': '\s*,\s*',
566 'intertext': r',?\s*intertext=\".*?\"',
567 'option_sep': '\s*,\s*',
571 # Options without a pattern in ly_options.
592 RELATIVE: r'''\relative c%(relative_quotes)s''',
597 INDENT: r'''indent = %(indent)s''',
599 LINE_WIDTH: r'''line-width = %(line-width)s''',
601 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
603 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
605 RAGGED_RIGHT: r'''ragged-right = ##t''',
607 NORAGGED_RIGHT: r'''ragged-right = ##f''',
619 \remove "Time_signature_engraver"
625 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
632 FILTER: r'''<mediaobject><textobject><programlisting language="lilypond" role="%(options)s">%(code)s</programlisting></textobject></mediaobject>''',
635 <imageobject role="latex">
636 <imagedata fileref="%(base)s.pdf" format="PDF"/>
638 <imageobject role="html">
639 <imagedata fileref="%(base)s.png" format="PNG"/></imageobject>''',
641 VERBATIM: r'''<programlisting>%(verb)s</programlisting>''',
643 VERSION: program_version,
645 PRINTFILENAME: '<textobject><simpara><ulink url="%(base)s.ly"><filename>%(filename)s</filename></ulink></simpara></textobject>'
649 FILTER: r'''<lilypond %(options)s>
659 <a href="%(base)s.ly">''',
663 border="0" src="%(image)s" alt="%(alt)s">''',
665 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
667 QUOTE: r'''<blockquote>
675 VERSION: program_version,
682 \ifx\preLilyPondExample \undefined%%
685 \preLilyPondExample%%
687 \def\lilypondbook{}%%
688 \input %(base)s-systems.tex%%
689 \ifx\postLilyPondExample \undefined%%
692 \postLilyPondExample%%
696 PRINTFILENAME: '''\\texttt{%(filename)s}
699 QUOTE: r'''\begin{quotation}%(str)s
702 VERBATIM: r'''\noindent
703 \begin{verbatim}%(verb)s\end{verbatim}''',
705 VERSION: program_version,
707 FILTER: r'''\begin{lilypond}[%(options)s]
714 FILTER: r'''@lilypond[%(options)s]
720 @include %(base)s-systems.texi
724 OUTPUTIMAGE: r'''@noindent
726 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
730 <a href="%(base)s.ly">
732 border="0" src="%(image)s" alt="%(alt)s">
740 <a href="%(base)s.ly">
748 QUOTE: r'''@quotation
749 %(str)s@end quotation
756 VERBATIM: r'''@exampleindent 0
758 %(verb)s@end verbatim
761 VERSION: program_version,
763 ADDVERSION: r'''@example
764 \version @w{"@version{}"}
771 # Maintain line numbers.
776 for f in [HTML, LATEX]:
777 for s in (QUOTE, VERBATIM):
778 output[f][s] = output[f][s].replace("\n"," ")
781 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
782 %%%% Options: [%(option_string)s]
783 \\include "lilypond-book-preamble.ly"
786 %% ****************************************************************
787 %% Start cut-&-pastable-section
788 %% ****************************************************************
793 #(define dump-extents #t)
794 %(font_dump_setting)s
796 force-assignment = #""
797 line-width = #(- line-width (* mm %(padding_mm)f))
810 %% ****************************************************************
811 %% ly snippet contents follows:
812 %% ****************************************************************
816 %% ****************************************************************
818 %% ****************************************************************
825 %% ****************************************************************
827 %% ****************************************************************
831 %% ****************************************************************
833 %% ****************************************************************
836 texinfo_line_widths = {
837 '@afourpaper': '160\\mm',
838 '@afourwide': '6.5\\in',
839 '@afourlatex': '150\\mm',
840 '@smallbook': '5\\in',
841 '@letterpaper': '6\\in',
844 def classic_lilypond_book_compatibility (key, value):
845 if key == 'singleline' and value == None:
846 return (RAGGED_RIGHT, None)
848 m = re.search ('relative\s*([-0-9])', key)
850 return ('relative', m.group (1))
852 m = re.match ('([0-9]+)pt', key)
854 return ('staffsize', m.group (1))
856 if key == 'indent' or key == 'line-width':
857 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
859 f = float (m.group (1))
860 return (key, '%f\\%s' % (f, m.group (2)))
864 def find_file (name, raise_error=True):
865 for i in global_options.include_path:
866 full = os.path.join (i, name)
867 if os.path.exists (full):
871 error (_ ("file not found: %s") % name + '\n')
875 def verbatim_html (s):
876 return re.sub ('>', '>',
878 re.sub ('&', '&', s)))
880 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
881 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
882 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
883 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
885 def ly_comment_gettext (t, m):
886 return m.group (1) + t (m.group (2))
888 def verb_ly_gettext (s):
889 if not document_language:
892 t = langdefs.translation[document_language]
896 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
898 for v in ly_var_def_re.findall (s):
899 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
900 "\\1" + t (v) + "\\2",
902 for id in ly_context_id_re.findall (s):
903 s = re.sub (r'(\s+|")%s(\s+|")' % id,
904 "\\1" + t (id) + "\\2",
908 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
909 def set_default_options (source, default_ly_options, format):
910 global document_language
911 if LINE_WIDTH not in default_ly_options:
913 textwidth = get_latex_textwidth (source)
914 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
915 elif format == TEXINFO:
916 m = texinfo_lang_re.search (source)
917 if m and not m.group (1).startswith ('en'):
918 document_language = m.group (1)
920 document_language = ''
921 for regex in texinfo_line_widths:
922 # FIXME: @layout is usually not in
925 # \input texinfo @c -*-texinfo-*-
927 # Bluntly search first K items of
929 # s = chunks[0].replacement_text ()
930 if re.search (regex, source[:1024]):
931 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
935 def replacement_text (self):
938 def filter_text (self):
939 return self.replacement_text ()
944 class Substring (Chunk):
945 """A string that does not require extra memory."""
946 def __init__ (self, source, start, end, line_number):
950 self.line_number = line_number
951 self.override_text = None
956 def replacement_text (self):
957 if self.override_text:
958 return self.override_text
960 return self.source[self.start:self.end]
962 class Snippet (Chunk):
963 def __init__ (self, type, match, format, line_number):
967 self.option_dict = {}
969 self.line_number = line_number
971 def replacement_text (self):
972 return self.match.group ('match')
974 def substring (self, s):
975 return self.match.group (s)
978 return `self.__class__` + ' type = ' + self.type
980 class IncludeSnippet (Snippet):
981 def processed_filename (self):
982 f = self.substring ('filename')
983 return os.path.splitext (f)[0] + format2ext[self.format]
985 def replacement_text (self):
986 s = self.match.group ('match')
987 f = self.substring ('filename')
989 return re.sub (f, self.processed_filename (), s)
991 class LilypondSnippet (Snippet):
992 def __init__ (self, type, match, format, line_number):
993 Snippet.__init__ (self, type, match, format, line_number)
994 os = match.group ('options')
995 self.do_options (os, self.type)
998 if NOGETTEXT in self.option_dict:
999 return self.substring ('code')
1001 return verb_ly_gettext (self.substring ('code'))
1004 contents = self.substring ('code')
1005 return ('\\sourcefileline %d\n%s'
1006 % (self.line_number - 1, contents))
1011 return self.compose_ly (s)
1014 def split_options (self, option_string):
1016 if self.format == HTML:
1017 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1019 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1023 return re.split (format_res[self.format]['option_sep'],
1027 def do_options (self, option_string, type):
1028 self.option_dict = {}
1030 options = self.split_options (option_string)
1032 for option in options:
1034 (key, value) = re.split ('\s*=\s*', option)
1035 self.option_dict[key] = value
1037 if option in no_options:
1038 if no_options[option] in self.option_dict:
1039 del self.option_dict[no_options[option]]
1041 self.option_dict[option] = None
1043 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1044 no_line_width_value = 0
1046 # If LINE_WIDTH is used without parameter, set it to default.
1047 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1048 no_line_width_value = 1
1049 del self.option_dict[LINE_WIDTH]
1051 for k in default_ly_options:
1052 if k not in self.option_dict:
1053 self.option_dict[k] = default_ly_options[k]
1055 # RELATIVE does not work without FRAGMENT;
1056 # make RELATIVE imply FRAGMENT
1057 has_relative = self.option_dict.has_key (RELATIVE)
1058 if has_relative and not self.option_dict.has_key (FRAGMENT):
1059 self.option_dict[FRAGMENT] = None
1061 if not has_line_width:
1062 if type == 'lilypond' or FRAGMENT in self.option_dict:
1063 self.option_dict[RAGGED_RIGHT] = None
1065 if type == 'lilypond':
1066 if LINE_WIDTH in self.option_dict:
1067 del self.option_dict[LINE_WIDTH]
1069 if RAGGED_RIGHT in self.option_dict:
1070 if LINE_WIDTH in self.option_dict:
1071 del self.option_dict[LINE_WIDTH]
1073 if QUOTE in self.option_dict or type == 'lilypond':
1074 if LINE_WIDTH in self.option_dict:
1075 del self.option_dict[LINE_WIDTH]
1077 if not INDENT in self.option_dict:
1078 self.option_dict[INDENT] = '0\\mm'
1080 # The QUOTE pattern from ly_options only emits the `line-width'
1082 if has_line_width and QUOTE in self.option_dict:
1083 if no_line_width_value:
1084 del self.option_dict[LINE_WIDTH]
1086 del self.option_dict[QUOTE]
1088 def compose_ly (self, code):
1089 if FRAGMENT in self.option_dict:
1097 # The original concept of the `exampleindent' option is broken.
1098 # It is not possible to get a sane value for @exampleindent at all
1099 # without processing the document itself. Saying
1107 # causes ugly results with the DVI backend of texinfo since the
1108 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1109 # value). Executing the above code changes the environment
1110 # indentation to an unknown value because we don't know the amount
1111 # of 1em in advance since it is font-dependent. Modifying
1112 # @exampleindent in the middle of a document is simply not
1113 # supported within texinfo.
1115 # As a consequence, the only function of @exampleindent is now to
1116 # specify the amount of indentation for the `quote' option.
1118 # To set @exampleindent locally to zero, we use the @format
1119 # environment for non-quoted snippets.
1120 override[EXAMPLEINDENT] = r'0.4\in'
1121 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1122 override.update (default_ly_options)
1125 for (key, value) in self.option_dict.items ():
1127 option_list.append (key)
1129 option_list.append (key + '=' + value)
1130 option_string = ','.join (option_list)
1133 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1134 for a in compose_types:
1135 compose_dict[a] = []
1137 for (key, value) in self.option_dict.items ():
1138 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1142 _ ("deprecated ly-option used: %s=%s") % (key, value))
1144 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1147 _ ("deprecated ly-option used: %s") % key)
1149 _ ("compatibility mode translation: %s") % c_key)
1151 (key, value) = (c_key, c_value)
1154 override[key] = value
1156 if not override.has_key (key):
1157 override[key] = None
1160 for type in compose_types:
1161 if ly_options[type].has_key (key):
1162 compose_dict[type].append (ly_options[type][key])
1166 if not found and key not in simple_options:
1167 warning (_ ("ignoring unknown ly option: %s") % key)
1170 if RELATIVE in override and override[RELATIVE]:
1171 relative = int (override[RELATIVE])
1173 relative_quotes = ''
1177 relative_quotes += ',' * (- relative)
1179 relative_quotes += "'" * relative
1181 paper_string = '\n '.join (compose_dict[PAPER]) % override
1182 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1183 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1184 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1185 padding_mm = global_options.padding_mm
1186 font_dump_setting = ''
1187 if FONTLOAD in self.option_dict:
1188 font_dump_setting = '#(define-public force-eps-font-include #t)\n'
1190 d = globals().copy()
1192 return (PREAMBLE_LY + body) % d
1194 def get_checksum (self):
1195 if not self.checksum:
1196 hash = md5.md5 (self.relevant_contents (self.full_ly ()))
1198 ## let's not create too long names.
1199 self.checksum = hash.hexdigest ()[:10]
1201 return self.checksum
1203 def basename (self):
1204 cs = self.get_checksum ()
1205 name = '%s/lily-%s' % (cs[:2], cs[2:10])
1208 def write_ly (self):
1209 base = self.basename ()
1210 path = os.path.join (global_options.lily_output_dir, base)
1211 directory = os.path.split(path)[0]
1212 if not os.path.isdir (directory):
1213 os.makedirs (directory)
1214 out = file (path + '.ly', 'w')
1215 out.write (self.full_ly ())
1216 file (path + '.txt', 'w').write ('image of music')
1218 def relevant_contents (self, ly):
1219 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n|' +
1220 NOGETTEXT + '[,\]]', '', ly)
1222 def link_all_output_files (self, output_dir, output_dir_files, destination):
1223 existing, missing = self.all_output_files (output_dir, output_dir_files)
1225 print '\nMissing', missing
1226 raise CompileError(self.basename())
1227 for name in existing:
1229 os.unlink (os.path.join (destination, name))
1233 src = os.path.join (output_dir, name)
1234 dst = os.path.join (destination, name)
1235 dst_path = os.path.split(dst)[0]
1236 if not os.path.isdir (dst_path):
1237 os.makedirs (dst_path)
1241 def all_output_files (self, output_dir, output_dir_files):
1242 """Return all files generated in lily_output_dir, a set.
1244 output_dir_files is the list of files in the output directory.
1248 base = self.basename()
1249 full = os.path.join (output_dir, base)
1250 def consider_file (name):
1251 if name in output_dir_files:
1254 def require_file (name):
1255 if name in output_dir_files:
1260 # UGH - junk global_options
1261 skip_lily = global_options.skip_lilypond_run
1262 for required in [base + '.ly',
1264 require_file (required)
1266 require_file (base + '-systems.count')
1268 if 'ddump-profile' in global_options.process_cmd:
1269 require_file (base + '.profile')
1270 if 'dseparate-log-file' in global_options.process_cmd:
1271 require_file (base + '.log')
1273 map (consider_file, [base + '.tex',
1277 base + '-systems.texi',
1278 base + '-systems.tex',
1279 base + '-systems.pdftexi'])
1280 if document_language:
1282 [base + '.texidoc' + document_language,
1283 base + '.doctitle' + document_language])
1285 # UGH - junk global_options
1286 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1287 and not global_options.skip_png_check):
1288 page_count = ps_page_count (full + '.eps')
1290 require_file (base + '.png')
1292 for page in range (1, page_count + 1):
1293 require_file (base + '-page%d.png' % page)
1296 if not skip_lily and not missing:
1297 system_count = int(file (full + '-systems.count').read())
1299 for number in range(1, system_count + 1):
1300 systemfile = '%s-%d' % (base, number)
1301 require_file (systemfile + '.eps')
1302 consider_file (systemfile + '.pdf')
1304 # We can't require signatures, since books and toplevel
1305 # markups do not output a signature.
1306 if 'ddump-signature' in global_options.process_cmd:
1307 consider_file (systemfile + '.signature')
1310 return (result, missing)
1312 def is_outdated (self, output_dir, current_files):
1313 found, missing = self.all_output_files (output_dir, current_files)
1316 def filter_text (self):
1317 """Run snippet bodies through a command (say: convert-ly).
1319 This functionality is rarely used, and this code must have bitrot.
1321 code = self.substring ('code')
1322 s = filter_pipe (code, global_options.filter_cmd)
1325 'options': self.match.group ('options')
1328 return output[self.format][FILTER] % d
1330 def replacement_text (self):
1331 func = LilypondSnippet.__dict__['output_' + self.format]
1334 def get_images (self):
1335 base = self.basename ()
1337 single = '%(base)s.png' % vars ()
1338 multiple = '%(base)s-page1.png' % vars ()
1340 if (os.path.exists (multiple)
1341 and (not os.path.exists (single)
1342 or (os.stat (multiple)[stat.ST_MTIME]
1343 > os.stat (single)[stat.ST_MTIME]))):
1344 count = ps_page_count ('%(base)s.eps' % vars ())
1345 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1346 images = tuple (images)
1350 def output_docbook (self):
1352 base = self.basename ()
1353 for image in self.get_images ():
1354 (base, ext) = os.path.splitext (image)
1355 str += output[DOCBOOK][OUTPUT] % vars ()
1356 str += self.output_print_filename (DOCBOOK)
1357 if (self.substring('inline') == 'inline'):
1358 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1360 str = '<mediaobject>' + str + '</mediaobject>'
1361 if VERBATIM in self.option_dict:
1362 verb = verbatim_html (self.verb_ly ())
1363 str = output[DOCBOOK][VERBATIM] % vars () + str
1366 def output_html (self):
1368 base = self.basename ()
1369 if self.format == HTML:
1370 str += self.output_print_filename (HTML)
1371 if VERBATIM in self.option_dict:
1372 verb = verbatim_html (self.verb_ly ())
1373 str += output[HTML][VERBATIM] % vars ()
1374 if QUOTE in self.option_dict:
1375 str = output[HTML][QUOTE] % vars ()
1377 str += output[HTML][BEFORE] % vars ()
1378 for image in self.get_images ():
1379 (base, ext) = os.path.splitext (image)
1380 alt = self.option_dict[ALT]
1381 str += output[HTML][OUTPUT] % vars ()
1382 str += output[HTML][AFTER] % vars ()
1385 def output_info (self):
1387 for image in self.get_images ():
1388 (base, ext) = os.path.splitext (image)
1390 # URG, makeinfo implicitly prepends dot to extension.
1391 # Specifying no extension is most robust.
1393 alt = self.option_dict[ALT]
1394 info_image_path = os.path.join (global_options.info_images_dir, base)
1395 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1397 base = self.basename ()
1398 str += output[self.format][OUTPUT] % vars ()
1401 def output_latex (self):
1403 base = self.basename ()
1404 if self.format == LATEX:
1405 str += self.output_print_filename (LATEX)
1406 if VERBATIM in self.option_dict:
1407 verb = self.verb_ly ()
1408 str += (output[LATEX][VERBATIM] % vars ())
1410 str += (output[LATEX][OUTPUT] % vars ())
1412 ## todo: maintain breaks
1414 breaks = self.ly ().count ("\n")
1415 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1417 if QUOTE in self.option_dict:
1418 str = output[LATEX][QUOTE] % vars ()
1421 def output_print_filename (self, format):
1423 if PRINTFILENAME in self.option_dict:
1424 base = self.basename ()
1425 filename = os.path.basename (self.substring ('filename'))
1426 str = output[format][PRINTFILENAME] % vars ()
1430 def output_texinfo (self):
1431 str = self.output_print_filename (TEXINFO)
1432 base = self.basename ()
1433 if DOCTITLE in self.option_dict:
1434 doctitle = base + '.doctitle'
1435 translated_doctitle = doctitle + document_language
1436 if os.path.exists (translated_doctitle):
1437 str += '@lydoctitle %s\n' % open (translated_doctitle).read ()
1438 elif os.path.exists (doctitle):
1439 str += '@lydoctitle %s\n' % open (doctitle).read ()
1440 if TEXIDOC in self.option_dict:
1441 texidoc = base + '.texidoc'
1442 translated_texidoc = texidoc + document_language
1443 if os.path.exists (translated_texidoc):
1444 str += '@include %(translated_texidoc)s\n\n' % vars ()
1445 elif os.path.exists (texidoc):
1446 str += '@include %(texidoc)s\n\n' % vars ()
1449 if VERBATIM in self.option_dict:
1451 if ADDVERSION in self.option_dict:
1452 version = output[TEXINFO][ADDVERSION]
1453 verb = self.verb_ly ()
1454 substr = output[TEXINFO][VERBATIM] % vars ()
1455 substr += self.output_info ()
1456 if LILYQUOTE in self.option_dict:
1457 substr = output[TEXINFO][QUOTE] % {'str':substr}
1460 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1461 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1462 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1464 if QUOTE in self.option_dict:
1465 str = output[TEXINFO][QUOTE] % vars ()
1467 # need par after image
1472 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1473 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1475 class LilypondFileSnippet (LilypondSnippet):
1476 def __init__ (self, type, match, format, line_number):
1477 LilypondSnippet.__init__ (self, type, match, format, line_number)
1478 self.contents = file (find_file (self.substring ('filename'))).read ()
1482 s = re_begin_verbatim.split (s)[-1]
1483 s = re_end_verbatim.split (s)[0]
1484 return verb_ly_gettext (s)
1487 name = self.substring ('filename')
1488 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1489 % (name, self.contents))
1492 class LilyPondVersionString (Snippet):
1493 """A string that does not require extra memory."""
1494 def __init__ (self, type, match, format, line_number):
1495 Snippet.__init__ (self, type, match, format, line_number)
1497 def replacement_text (self):
1498 return output[self.format][self.type]
1501 snippet_type_to_class = {
1502 'lilypond_file': LilypondFileSnippet,
1503 'lilypond_block': LilypondSnippet,
1504 'lilypond': LilypondSnippet,
1505 'include': IncludeSnippet,
1506 'lilypondversion': LilyPondVersionString,
1509 def find_linestarts (s):
1514 i = s.find ('\n', start)
1522 nls.append (len (s))
1525 def find_toplevel_snippets (input_string, format, types):
1528 res[t] = re.compile (snippet_res[format][t])
1532 found = dict ([(t, None) for t in types])
1534 line_starts = find_linestarts (input_string)
1536 # We want to search for multiple regexes, without searching
1537 # the string multiple times for one regex.
1538 # Hence, we use earlier results to limit the string portion
1540 # Since every part of the string is traversed at most once for
1541 # every type of snippet, this is linear.
1547 if not found[type] or found[type][0] < index:
1550 m = res[type].search (input_string[index:endex])
1555 if type in snippet_type_to_class:
1556 klass = snippet_type_to_class[type]
1558 start = index + m.start ('match')
1559 line_number = line_start_idx
1560 while (line_starts[line_number] < start):
1564 snip = klass (type, m, format, line_number)
1566 found[type] = (start, snip)
1570 or found[type][0] < found[first][0])):
1575 # Limiting the search space is a cute
1576 # idea, but this *requires* to search
1577 # for possible containing blocks
1578 # first, at least as long as we do not
1579 # search for the start of blocks, but
1580 # always/directly for the entire
1581 # @block ... @end block.
1583 endex = found[first][0]
1586 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1589 while (start > line_starts[line_start_idx+1]):
1592 (start, snip) = found[first]
1593 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1594 snippets.append (snip)
1596 index = start + len (snip.match.group ('match'))
1600 def filter_pipe (input, cmd):
1601 """Pass input through cmd, and return the result."""
1603 if global_options.verbose:
1604 progress (_ ("Opening filter `%s'") % cmd)
1606 (stdin, stdout, stderr) = os.popen3 (cmd)
1608 status = stdin.close ()
1612 output = stdout.read ()
1613 status = stdout.close ()
1614 error = stderr.read ()
1618 signal = 0x0f & status
1619 if status or (not output and error):
1620 exit_status = status >> 8
1621 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1622 error (_ ("The error log is as follows:"))
1623 ly.stderr_write (error)
1624 ly.stderr_write (stderr.read ())
1627 if global_options.verbose:
1632 def system_in_directory (cmd, directory):
1633 """Execute a command in a different directory.
1635 Because of win32 compatibility, we can't simply use subprocess.
1638 current = os.getcwd()
1639 os.chdir (directory)
1640 ly.system(cmd, be_verbose=global_options.verbose,
1645 def process_snippets (cmd, snippets,
1646 format, lily_output_dir):
1647 """Run cmd on all of the .ly files from snippets."""
1652 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1653 cmd += ' --formats=png '
1654 elif format in (DOCBOOK) and '--formats' not in cmd:
1655 cmd += ' --formats=png,pdf '
1657 checksum = snippet_list_checksum (snippets)
1658 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1659 + [snip.basename() + '.ly' for snip in snippets])
1660 name = os.path.join (lily_output_dir,
1661 'snippet-names-%d.ly' % checksum)
1662 file (name, 'wb').write (contents)
1664 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1669 # Retrieve dimensions from LaTeX
1670 LATEX_INSPECTION_DOCUMENT = r'''
1674 \typeout{textwidth=\the\textwidth}
1675 \typeout{columnsep=\the\columnsep}
1676 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1680 # Do we need anything else besides `textwidth'?
1681 def get_latex_textwidth (source):
1682 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1684 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1686 ## what's a sensible default?
1689 preamble = source[:m.start (0)]
1690 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1692 (handle, tmpfile) = tempfile.mkstemp('.tex')
1693 logfile = os.path.splitext (tmpfile)[0] + '.log'
1694 logfile = os.path.split (logfile)[1]
1696 tmp_handle = os.fdopen (handle,'w')
1697 tmp_handle.write (latex_document)
1700 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1701 be_verbose=global_options.verbose)
1702 parameter_string = file (logfile).read()
1708 m = re.search ('columns=([0-9.]*)', parameter_string)
1710 columns = int (m.group (1))
1713 m = re.search ('columnsep=([0-9.]*)pt', parameter_string)
1715 columnsep = float (m.group (1))
1718 m = re.search ('textwidth=([0-9.]*)pt', parameter_string)
1720 textwidth = float (m.group (1))
1722 textwidth = (textwidth - columnsep) / columns
1726 def modify_preamble (chunk):
1727 str = chunk.replacement_text ()
1728 if (re.search (r"\\begin *{document}", str)
1729 and not re.search ("{graphic[sx]", str)):
1730 str = re.sub (r"\\begin{document}",
1731 r"\\usepackage{graphics}" + '\n'
1732 + r"\\begin{document}",
1734 chunk.override_text = str
1739 # TEXINFO: '.texinfo',
1745 class CompileError(Exception):
1748 def snippet_list_checksum (snippets):
1749 return hash (' '.join([l.basename() for l in snippets]))
1751 def write_file_map (lys, name):
1752 snippet_map = file (os.path.join (
1753 global_options.lily_output_dir,
1754 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1756 snippet_map.write ("""
1757 #(define version-seen #t)
1758 #(define output-empty-score-list #f)
1759 #(ly:add-file-name-alist '(%s
1761 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1764 def split_output_files(directory):
1765 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1767 Return value is a set of strings.
1770 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1771 base_subdir = os.path.split (subdir)[1]
1772 sub_files = [os.path.join (base_subdir, name)
1773 for name in os.listdir (subdir)]
1777 def do_process_cmd (chunks, input_name, options):
1778 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1780 output_files = split_output_files (options.lily_output_dir)
1781 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1783 write_file_map (outdated, input_name)
1784 progress (_ ("Writing snippets..."))
1785 for snippet in outdated:
1790 progress (_ ("Processing..."))
1792 process_snippets (options.process_cmd, outdated,
1793 options.format, options.lily_output_dir)
1796 progress (_ ("All snippets are up to date..."))
1798 if options.lily_output_dir != options.output_dir:
1799 output_files = split_output_files (options.lily_output_dir)
1800 for snippet in snippets:
1801 snippet.link_all_output_files (options.lily_output_dir,
1809 # Format guessing data
1818 '.texinfo': TEXINFO,
1823 def guess_format (input_filename):
1825 e = os.path.splitext (input_filename)[1]
1828 format = ext2format[e]
1830 error (_ ("cannot determine format for: %s"
1835 def write_if_updated (file_name, lines):
1837 f = file (file_name)
1839 new_str = ''.join (lines)
1840 if oldstr == new_str:
1841 progress (_ ("%s is up to date.") % file_name)
1844 # this prevents make from always rerunning lilypond-book:
1845 # output file must be touched in order to be up to date
1846 os.utime (file_name, None)
1851 output_dir = os.path.dirname (file_name)
1852 if not os.path.exists (output_dir):
1853 os.makedirs (output_dir)
1855 progress (_ ("Writing `%s'...") % file_name)
1856 file (file_name, 'w').writelines (lines)
1860 def note_input_file (name, inputs=[]):
1861 ## hack: inputs is mutable!
1862 inputs.append (name)
1865 def samefile (f1, f2):
1867 return os.path.samefile (f1, f2)
1868 except AttributeError: # Windoze
1869 f1 = re.sub ("//*", "/", f1)
1870 f2 = re.sub ("//*", "/", f2)
1873 def do_file (input_filename, included=False):
1875 if not input_filename or input_filename == '-':
1876 in_handle = sys.stdin
1877 input_fullname = '<stdin>'
1879 if os.path.exists (input_filename):
1880 input_fullname = input_filename
1881 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1882 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1884 input_fullname = find_file (input_filename)
1886 note_input_file (input_fullname)
1887 in_handle = file (input_fullname)
1889 if input_filename == '-':
1890 input_base = 'stdin'
1892 input_base = os.path.splitext (input_filename)[0]
1894 input_base = os.path.basename (
1895 os.path.splitext (input_filename)[0])
1897 # don't complain when global_options.output_dir is existing
1898 if not global_options.output_dir:
1899 global_options.output_dir = os.getcwd()
1901 global_options.output_dir = os.path.abspath(global_options.output_dir)
1903 if not os.path.isdir (global_options.output_dir):
1904 os.mkdir (global_options.output_dir, 0777)
1905 os.chdir (global_options.output_dir)
1907 output_filename = os.path.join(global_options.output_dir,
1908 input_base + format2ext[global_options.format])
1909 if (os.path.exists (input_filename)
1910 and os.path.exists (output_filename)
1911 and samefile (output_filename, input_fullname)):
1913 _ ("Output would overwrite input file; use --output."))
1917 progress (_ ("Reading %s...") % input_fullname)
1918 source = in_handle.read ()
1921 set_default_options (source, default_ly_options, global_options.format)
1924 # FIXME: Containing blocks must be first, see
1925 # find_toplevel_snippets.
1927 'multiline_comment',
1931 'singleline_comment',
1937 progress (_ ("Dissecting..."))
1938 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
1940 if global_options.format == LATEX:
1942 if (c.is_plain () and
1943 re.search (r"\\begin *{document}", c.replacement_text())):
1948 if global_options.filter_cmd:
1949 write_if_updated (output_filename,
1950 [c.filter_text () for c in chunks])
1951 elif global_options.process_cmd:
1952 do_process_cmd (chunks, input_fullname, global_options)
1953 progress (_ ("Compiling %s...") % output_filename)
1955 write_if_updated (output_filename,
1956 [s.replacement_text ()
1959 def process_include (snippet):
1960 os.chdir (original_dir)
1961 name = snippet.substring ('filename')
1962 progress (_ ("Processing include: %s") % name)
1964 return do_file (name, included=True)
1966 include_chunks = map (process_include,
1967 filter (lambda x: isinstance (x, IncludeSnippet),
1970 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
1972 except CompileError:
1973 os.chdir (original_dir)
1974 progress (_ ("Removing `%s'") % output_filename)
1979 global global_options
1981 opt_parser = get_option_parser()
1982 (global_options, args) = opt_parser.parse_args ()
1983 if global_options.format in ('texi-html', 'texi'):
1984 global_options.format = TEXINFO
1986 global_options.include_path = map (os.path.abspath, global_options.include_path)
1988 if global_options.warranty:
1991 if not args or len (args) > 1:
1992 opt_parser.print_help ()
1998 # FIXME: 85 lines of `main' macramee??
1999 files = do_options ()
2001 basename = os.path.splitext (files[0])[0]
2002 basename = os.path.split (basename)[1]
2004 if not global_options.format:
2005 global_options.format = guess_format (files[0])
2008 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2011 if global_options.process_cmd == '':
2012 global_options.process_cmd = (lilypond_binary
2013 + ' --formats=%s -dbackend=eps ' % formats)
2015 if global_options.process_cmd:
2016 includes = global_options.include_path
2017 if global_options.lily_output_dir:
2018 # This must be first, so lilypond prefers to read .ly
2019 # files in the other lybookdb dir.
2020 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2021 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2024 if global_options.format in (TEXINFO, LATEX):
2025 ## prevent PDF from being switched on by default.
2026 global_options.process_cmd += ' --formats=eps '
2027 if global_options.create_pdf:
2028 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2030 if global_options.verbose:
2031 global_options.process_cmd += " --verbose "
2033 if global_options.padding_mm:
2034 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2036 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2038 if global_options.lily_output_dir:
2039 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2040 if not os.path.isdir (global_options.lily_output_dir):
2041 os.makedirs (global_options.lily_output_dir)
2043 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2048 chunks = do_file (files[0])
2049 except CompileError:
2052 inputs = note_input_file ('')
2055 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2056 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2057 final_output_file = os.path.join (global_options.output_dir,
2059 + '.%s' % global_options.format)
2061 os.chdir (original_dir)
2062 file (dep_file, 'w').write ('%s: %s'
2063 % (final_output_file, ' '.join (inputs)))
2065 if __name__ == '__main__':