3 # This file is part of LilyPond, the GNU music typesetter.
5 # LilyPond is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # LilyPond is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
22 lilypond-book --filter="tr '[a-z]' '[A-Z]'" BOOK
25 lilypond-book --filter="convert-ly --no-version --from=1.6.11 -" BOOK
27 classic lilypond-book:
28 lilypond-book --process="lilypond" BOOK.tely
32 * this script is too complex. Modularize.
34 * ly-options: intertext?
36 * eps in latex / eps by lilypond -b ps?
37 * check latex parameters, twocolumn, multicolumn?
38 * use --png --ps --pdf for making images?
40 * Converting from lilypond-book source, substitute:
41 @mbinclude foo.itely -> @include foo.itely
62 ly.require_python_version ()
65 program_version = '@TOPLEVEL_VERSION@'
66 program_name = os.path.basename (sys.argv[0])
68 # Check if program_version contains @ characters. This will be the case if
69 # the .py file is called directly while building the lilypond documentation.
70 # If so, try to check for the env var LILYPOND_VERSION, which is set by our
71 # makefiles and use its value.
72 at_re = re.compile (r'@')
73 if at_re.match (program_version):
74 if os.environ.has_key('LILYPOND_VERSION'):
75 program_version = os.environ['LILYPOND_VERSION']
77 program_version = "unknown"
79 original_dir = os.getcwd ()
83 _ ("Process LilyPond snippets in hybrid HTML, LaTeX, texinfo or DocBook document.")
87 $ lilypond-book --filter="tr '[a-z]' '[A-Z]'" %(BOOK)s
88 $ lilypond-book -F "convert-ly --no-version --from=2.0.0 -" %(BOOK)s
89 $ lilypond-book --process='lilypond -I include' %(BOOK)s
90 ''' % {'BOOK': _ ("BOOK")})
92 authors = ('Jan Nieuwenhuizen <janneke@gnu.org>',
93 'Han-Wen Nienhuys <hanwen@xs4all.nl>')
95 ################################################################
97 if global_options.verbose:
98 raise Exception (_ ('Exiting (%d)...') % i)
103 ly.encoded_write (sys.stdout, '%s (GNU LilyPond) %s\n' % (program_name, program_version))
105 progress = ly.progress
108 ly.stderr_write (program_name + ": " + _ ("warning: %s") % s + '\n')
111 ly.stderr_write (program_name + ": " + _ ("error: %s") % s + '\n')
113 def ps_page_count (ps_name):
114 header = file (ps_name).read (1024)
115 m = re.search ('\n%%Pages: ([0-9]+)', header)
117 return int (m.group (1))
122 ly.encoded_write (sys.stdout, '''
129 ''' % ( _ ('Copyright (c) %s by') % '2001--2010',
130 '\n '.join (authors),
131 _ ("Distributed under terms of the GNU General Public License."),
132 _ ("It comes with NO WARRANTY.")))
134 def get_option_parser ():
135 p = ly.get_option_parser (usage=_ ("%s [OPTION]... FILE") % 'lilypond-book',
136 description=help_summary,
137 add_help_option=False)
139 p.add_option ('-F', '--filter', metavar=_ ("FILTER"),
142 help=_ ("pipe snippets through FILTER [default: `convert-ly -n -']"),
145 p.add_option ('-f', '--format',
146 help=_ ("use output format FORMAT (texi [default], texi-html, latex, html, docbook)"),
147 metavar=_ ("FORMAT"),
150 p.add_option("-h", "--help",
152 help=_ ("show this help and exit"))
154 p.add_option ("-I", '--include', help=_ ("add DIR to include path"),
156 action='append', dest='include_path',
157 default=[os.path.abspath (os.getcwd ())])
159 p.add_option ('--info-images-dir',
160 help=_ ("format Texinfo output so that Info will "
161 "look for images of music in DIR"),
163 action='store', dest='info_images_dir',
166 p.add_option ('--latex-program',
167 help=_ ("run executable PROG instead of latex, or in\n\
168 case --pdf option is set instead of pdflatex"),
170 action='store', dest='latex_program',
173 p.add_option ('--left-padding',
176 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
180 p.add_option ('--lily-output-dir',
181 help=_ ("write lily-XXX files to DIR, link into --output dir"),
183 action='store', dest='lily_output_dir',
186 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
188 action='store', dest='output_dir',
191 p.add_option ('--pdf',
194 help=_ ("create PDF files for use with PDFTeX"),
197 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
198 help = _ ("process ly_files using COMMAND FILE..."),
200 dest='process_cmd', default='')
202 p.add_option ('--skip-lily-check',
203 help=_ ("do not fail if no lilypond output is found"),
205 action='store_true', dest='skip_lilypond_run',
208 p.add_option ('--skip-png-check',
209 help=_ ("do not fail if no PNG images are found for EPS files"),
211 action='store_true', dest='skip_png_check',
214 p.add_option ('--use-source-file-names',
215 help=_ ("write snippet output files with the same base name as their source file"),
216 action='store_true', dest='use_source_file_names',
219 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
224 p.version = "@TOPLEVEL_VERSION@"
225 p.add_option("--version",
227 help=_ ("show version number and exit"))
229 p.add_option ('-w', '--warranty',
230 help=_ ("show warranty and copyright"),
232 p.add_option_group ('',
234 _ ("Report bugs via %s")
235 % ' http://post.gmane.org/post.php'
236 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
239 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
241 # If we are called with full path, try to use lilypond binary
242 # installed in the same path; this is needed in GUB binaries, where
243 # @bindir is always different from the installed binary path.
244 if 'bindir' in globals () and bindir:
245 lilypond_binary = os.path.join (bindir, 'lilypond')
247 # Only use installed binary when we are installed too.
248 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
249 lilypond_binary = 'lilypond'
251 global_options = None
254 default_ly_options = { 'alt': "[image of music]" }
256 document_language = ''
259 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
261 ADDVERSION = 'addversion'
265 EXAMPLEINDENT = 'exampleindent'
267 FRAGMENT = 'fragment'
273 LINE_WIDTH = 'line-width'
274 LILYQUOTE = 'lilyquote'
275 NOFRAGMENT = 'nofragment'
276 NOGETTEXT = 'nogettext'
277 NOINDENT = 'noindent'
279 NORAGGED_RIGHT = 'noragged-right'
283 OUTPUTIMAGE = 'outputimage'
285 PREAMBLE = 'preamble'
286 PRINTFILENAME = 'printfilename'
288 RAGGED_RIGHT = 'ragged-right'
289 RELATIVE = 'relative'
290 STAFFSIZE = 'staffsize'
291 DOCTITLE = 'doctitle'
294 VERBATIM = 'verbatim'
295 VERSION = 'lilypondversion'
296 FILENAME = 'filename'
300 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
302 # NOQUOTE is used internally only.
304 NOFRAGMENT: FRAGMENT,
308 # Options that have no impact on processing by lilypond (or --process
310 PROCESSING_INDEPENDENT_OPTIONS = (
311 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
312 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
314 # Recognize special sequences in the input.
316 # (?P<name>regex) -- Assign result of REGEX to NAME.
317 # *? -- Match non-greedily.
318 # (?!...) -- Match if `...' doesn't match next (without consuming
321 # (?m) -- Multiline regex: Make ^ and $ match at each line.
322 # (?s) -- Make the dot match all characters including newline.
323 # (?x) -- Ignore whitespace in patterns.
334 <(?P<inline>(inline)?)mediaobject>\s*
336 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
338 </programlisting\s*>\s*
340 </(inline)?mediaobject>)''',
345 <(?P<inline>(inline)?)mediaobject>\s*
347 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
349 </programlisting\s*>\s*
351 </(inline)?mediaobject>)''',
356 <(?P<inline>(inline)?)mediaobject>\s*
359 fileref="(?P<filename>.*?\.ly)"\s*
360 (role="(?P<options>.*?)")?\s*
361 (/>|>\s*</imagedata>)\s*
363 </(inline)?mediaobject>)''',
369 (?P<code><!--\s.*?!-->)
372 'singleline_comment':
393 (\s*(?P<options>.*?)\s*:)?\s*
401 \s*(?P<options>.*?)\s*
410 \s*(?P<options>.*?)\s*
412 \s*(?P<filename>.*?)\s*
419 (?P<code><!--\s.*?!-->)
422 'singleline_comment':
428 (?P<code><pre>.*?</pre>))''',
434 (?P<code><pre>\s.*?</pre>\s))''',
439 <lilypondversion\s*/>)''',
458 \s*(?P<options>.*?)\s*
469 \s*(?P<options>.*?)\s*
473 \\end\s*{lilypond})''',
481 \s*(?P<options>.*?)\s*
489 'singleline_comment':
512 \\end\s*{verbatim}))''',
517 \\lilypondversion)[^a-zA-Z]''',
527 (?P<filename>\S+))''',
531 ^[^\n]*?(?!@c\s+)[^\n]*?
535 \s*(?P<options>.*?)\s*
545 \s*(?P<options>.*?)\s*
548 ^@end\s+lilypond)\s''',
555 \s*(?P<options>.*?)\s*
566 @end\s+ignore))\s''',
568 'singleline_comment':
573 @c([ \t][^\n]*|)\n))''',
575 # Don't do this: It interferes with @code{@{}.
576 # 'verb': r'''(?P<code>@code{.*?})''',
584 @end\s+example\s))''',
589 @lilypondversion)[^a-zA-Z]''',
597 'intertext': r',?\s*intertext=\".*?\"',
601 'intertext': r',?\s*intertext=\".*?\"',
606 'intertext': r',?\s*intertext=\".*?\"',
607 'option_sep': '\s*,\s*',
611 'intertext': r',?\s*intertext=\".*?\"',
612 'option_sep': '\s*,\s*',
617 # Options without a pattern in ly_options.
637 RELATIVE: r'''\relative c%(relative_quotes)s''',
642 INDENT: r'''indent = %(indent)s''',
644 LINE_WIDTH: r'''line-width = %(line-width)s''',
646 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
648 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
650 RAGGED_RIGHT: r'''ragged-right = ##t''',
652 NORAGGED_RIGHT: r'''ragged-right = ##f''',
664 \remove "Time_signature_engraver"
670 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
677 FILTER: r'''<mediaobject>
679 <programlisting language="lilypond"
686 OUTPUT: r'''<imageobject role="latex">
687 <imagedata fileref="%(base)s.pdf" format="PDF"/>
689 <imageobject role="html">
690 <imagedata fileref="%(base)s.png" format="PNG"/>
693 VERBATIM: r'''<programlisting>
694 %(verb)s</programlisting>''',
696 VERSION: program_version,
698 PRINTFILENAME: r'''<textobject>
700 <ulink url="%(base)s.ly">
710 FILTER: r'''<lilypond %(options)s>
720 <a href="%(base)s.ly">''',
728 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
730 QUOTE: r'''<blockquote>
738 VERSION: program_version,
745 \ifx\preLilyPondExample \undefined
747 \expandafter\preLilyPondExample
749 \def\lilypondbook{}%%
750 \input %(base)s-systems.tex
751 \ifx\postLilyPondExample \undefined
753 \expandafter\postLilyPondExample
757 PRINTFILENAME: '''\\texttt{%(filename)s}
760 QUOTE: r'''\begin{quotation}
764 VERBATIM: r'''\noindent
765 \begin{verbatim}%(verb)s\end{verbatim}
768 VERSION: program_version,
770 FILTER: r'''\begin{lilypond}[%(options)s]
777 FILTER: r'''@lilypond[%(options)s]
783 @include %(base)s-systems.texi
787 OUTPUTIMAGE: r'''@noindent
789 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
793 <a href="%(base)s.ly">
805 <a href="%(base)s.ly">
813 QUOTE: r'''@quotation
814 %(str)s@end quotation
821 VERBATIM: r'''@exampleindent 0
823 %(verb)s@end verbatim
826 VERSION: program_version,
828 ADDVERSION: r'''@example
829 \version @w{"@version{}"}
836 # Maintain line numbers.
841 for f in [HTML, LATEX]:
842 for s in (QUOTE, VERBATIM):
843 output[f][s] = output[f][s].replace("\n"," ")
846 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
847 %%%% Options: [%(option_string)s]
848 \\include "lilypond-book-preamble.ly"
851 %% ****************************************************************
852 %% Start cut-&-pastable-section
853 %% ****************************************************************
859 force-assignment = #""
860 line-width = #(- line-width (* mm %(padding_mm)f))
873 %% ****************************************************************
874 %% ly snippet contents follows:
875 %% ****************************************************************
879 %% ****************************************************************
881 %% ****************************************************************
888 %% ****************************************************************
890 %% ****************************************************************
894 %% ****************************************************************
896 %% ****************************************************************
899 texinfo_line_widths = {
900 '@afourpaper': '160\\mm',
901 '@afourwide': '6.5\\in',
902 '@afourlatex': '150\\mm',
903 '@smallbook': '5\\in',
904 '@letterpaper': '6\\in',
907 def classic_lilypond_book_compatibility (key, value):
908 if key == 'singleline' and value == None:
909 return (RAGGED_RIGHT, None)
911 m = re.search ('relative\s*([-0-9])', key)
913 return ('relative', m.group (1))
915 m = re.match ('([0-9]+)pt', key)
917 return ('staffsize', m.group (1))
919 if key == 'indent' or key == 'line-width':
920 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
922 f = float (m.group (1))
923 return (key, '%f\\%s' % (f, m.group (2)))
927 def find_file (name, raise_error=True):
928 for i in global_options.include_path:
929 full = os.path.join (i, name)
930 if os.path.exists (full):
934 error (_ ("file not found: %s") % name + '\n')
938 def verbatim_html (s):
939 return re.sub ('>', '>',
941 re.sub ('&', '&', s)))
943 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
944 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
945 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
946 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
948 def ly_comment_gettext (t, m):
949 return m.group (1) + t (m.group (2))
951 def verb_ly_gettext (s):
952 if not document_language:
955 t = langdefs.translation[document_language]
959 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
961 if langdefs.LANGDICT[document_language].enable_ly_identifier_l10n:
962 for v in ly_var_def_re.findall (s):
963 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
964 "\\1" + t (v) + "\\2",
966 for id in ly_context_id_re.findall (s):
967 s = re.sub (r'(\s+|")%s(\s+|")' % id,
968 "\\1" + t (id) + "\\2",
972 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
973 def set_default_options (source, default_ly_options, format):
974 global document_language
975 if LINE_WIDTH not in default_ly_options:
977 textwidth = get_latex_textwidth (source)
978 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
979 elif format == TEXINFO:
980 m = texinfo_lang_re.search (source)
981 if m and not m.group (1).startswith ('en'):
982 document_language = m.group (1)
984 document_language = ''
985 for regex in texinfo_line_widths:
986 # FIXME: @layout is usually not in
989 # \input texinfo @c -*-texinfo-*-
991 # Bluntly search first K items of
993 # s = chunks[0].replacement_text ()
994 if re.search (regex, source[:1024]):
995 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
999 def replacement_text (self):
1002 def filter_text (self):
1003 return self.replacement_text ()
1005 def is_plain (self):
1008 class Substring (Chunk):
1009 """A string that does not require extra memory."""
1010 def __init__ (self, source, start, end, line_number):
1011 self.source = source
1014 self.line_number = line_number
1015 self.override_text = None
1017 def is_plain (self):
1020 def replacement_text (self):
1021 if self.override_text:
1022 return self.override_text
1024 return self.source[self.start:self.end]
1026 class Snippet (Chunk):
1027 def __init__ (self, type, match, format, line_number):
1031 self.option_dict = {}
1032 self.format = format
1033 self.line_number = line_number
1035 def replacement_text (self):
1036 return self.match.group ('match')
1038 def substring (self, s):
1039 return self.match.group (s)
1041 def __repr__ (self):
1042 return `self.__class__` + ' type = ' + self.type
1044 class IncludeSnippet (Snippet):
1045 def processed_filename (self):
1046 f = self.substring ('filename')
1047 return os.path.splitext (f)[0] + format2ext[self.format]
1049 def replacement_text (self):
1050 s = self.match.group ('match')
1051 f = self.substring ('filename')
1053 return re.sub (f, self.processed_filename (), s)
1055 class LilypondSnippet (Snippet):
1056 def __init__ (self, type, match, format, line_number):
1057 Snippet.__init__ (self, type, match, format, line_number)
1058 os = match.group ('options')
1059 self.do_options (os, self.type)
1062 verb_text = self.substring ('code')
1063 if not NOGETTEXT in self.option_dict:
1064 verb_text = verb_ly_gettext (verb_text)
1065 if not verb_text.endswith ('\n'):
1070 contents = self.substring ('code')
1071 return ('\\sourcefileline %d\n%s'
1072 % (self.line_number - 1, contents))
1077 return self.compose_ly (s)
1080 def split_options (self, option_string):
1082 if self.format == HTML:
1083 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1085 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1089 return re.split (format_res[self.format]['option_sep'],
1093 def do_options (self, option_string, type):
1094 self.option_dict = {}
1096 options = self.split_options (option_string)
1098 for option in options:
1100 (key, value) = re.split ('\s*=\s*', option)
1101 self.option_dict[key] = value
1103 if option in no_options:
1104 if no_options[option] in self.option_dict:
1105 del self.option_dict[no_options[option]]
1107 self.option_dict[option] = None
1109 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1110 no_line_width_value = 0
1112 # If LINE_WIDTH is used without parameter, set it to default.
1113 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1114 no_line_width_value = 1
1115 del self.option_dict[LINE_WIDTH]
1117 for k in default_ly_options:
1118 if k not in self.option_dict:
1119 self.option_dict[k] = default_ly_options[k]
1121 # RELATIVE does not work without FRAGMENT;
1122 # make RELATIVE imply FRAGMENT
1123 has_relative = self.option_dict.has_key (RELATIVE)
1124 if has_relative and not self.option_dict.has_key (FRAGMENT):
1125 self.option_dict[FRAGMENT] = None
1127 if not has_line_width:
1128 if type == 'lilypond' or FRAGMENT in self.option_dict:
1129 self.option_dict[RAGGED_RIGHT] = None
1131 if type == 'lilypond':
1132 if LINE_WIDTH in self.option_dict:
1133 del self.option_dict[LINE_WIDTH]
1135 if RAGGED_RIGHT in self.option_dict:
1136 if LINE_WIDTH in self.option_dict:
1137 del self.option_dict[LINE_WIDTH]
1139 if QUOTE in self.option_dict or type == 'lilypond':
1140 if LINE_WIDTH in self.option_dict:
1141 del self.option_dict[LINE_WIDTH]
1143 if not INDENT in self.option_dict:
1144 self.option_dict[INDENT] = '0\\mm'
1146 # Set a default line-width if there is none. We need this, because
1147 # lilypond-book has set left-padding by default and therefore does
1148 # #(define line-width (- line-width (* 3 mm)))
1149 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
1150 # all settings before writing them in the \paper block.
1151 if not LINE_WIDTH in self.option_dict:
1152 if not QUOTE in self.option_dict:
1153 if not LILYQUOTE in self.option_dict:
1154 self.option_dict[LINE_WIDTH] = "#(- paper-width \
1155 left-margin-default right-margin-default)"
1157 def get_option_list (self):
1158 if not 'option_list' in self.__dict__:
1160 for (key, value) in self.option_dict.items ():
1162 option_list.append (key)
1164 option_list.append (key + '=' + value)
1166 self.option_list = option_list
1167 return self.option_list
1169 def compose_ly (self, code):
1170 if FRAGMENT in self.option_dict:
1178 # The original concept of the `exampleindent' option is broken.
1179 # It is not possible to get a sane value for @exampleindent at all
1180 # without processing the document itself. Saying
1188 # causes ugly results with the DVI backend of texinfo since the
1189 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1190 # value). Executing the above code changes the environment
1191 # indentation to an unknown value because we don't know the amount
1192 # of 1em in advance since it is font-dependent. Modifying
1193 # @exampleindent in the middle of a document is simply not
1194 # supported within texinfo.
1196 # As a consequence, the only function of @exampleindent is now to
1197 # specify the amount of indentation for the `quote' option.
1199 # To set @exampleindent locally to zero, we use the @format
1200 # environment for non-quoted snippets.
1201 override[EXAMPLEINDENT] = r'0.4\in'
1202 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1203 override.update (default_ly_options)
1206 for option in self.get_option_list ():
1207 for name in PROCESSING_INDEPENDENT_OPTIONS:
1208 if not option.startswith (name):
1209 option_list.append (option)
1210 option_string = ','.join (option_list)
1213 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1214 for a in compose_types:
1215 compose_dict[a] = []
1217 option_names = self.option_dict.keys ()
1218 option_names.sort ()
1219 for key in option_names:
1220 value = self.option_dict[key]
1221 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1225 _ ("deprecated ly-option used: %s=%s") % (key, value))
1227 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1230 _ ("deprecated ly-option used: %s") % key)
1232 _ ("compatibility mode translation: %s") % c_key)
1234 (key, value) = (c_key, c_value)
1237 override[key] = value
1239 if not override.has_key (key):
1240 override[key] = None
1243 for type in compose_types:
1244 if ly_options[type].has_key (key):
1245 compose_dict[type].append (ly_options[type][key])
1249 if not found and key not in simple_options:
1250 warning (_ ("ignoring unknown ly option: %s") % key)
1253 if RELATIVE in override and override[RELATIVE]:
1254 relative = int (override[RELATIVE])
1256 relative_quotes = ''
1260 relative_quotes += ',' * (- relative)
1262 relative_quotes += "'" * relative
1264 paper_string = '\n '.join (compose_dict[PAPER]) % override
1265 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1266 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1267 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1268 padding_mm = global_options.padding_mm
1270 d = globals().copy()
1272 return (PREAMBLE_LY + body) % d
1274 def get_checksum (self):
1275 if not self.checksum:
1276 # Work-around for md5 module deprecation warning in python 2.5+:
1278 from hashlib import md5
1282 # We only want to calculate the hash based on the snippet
1283 # code plus fragment options relevant to processing by
1284 # lilypond, not the snippet + preamble
1285 hash = md5 (self.relevant_contents (self.ly ()))
1286 for option in self.get_option_list ():
1287 for name in PROCESSING_INDEPENDENT_OPTIONS:
1288 if not option.startswith (name):
1289 hash.update (option)
1291 ## let's not create too long names.
1292 self.checksum = hash.hexdigest ()[:10]
1294 return self.checksum
1296 def basename (self):
1297 cs = self.get_checksum ()
1298 name = '%s/lily-%s' % (cs[:2], cs[2:])
1301 final_basename = basename
1303 def write_ly (self):
1304 base = self.basename ()
1305 path = os.path.join (global_options.lily_output_dir, base)
1306 directory = os.path.split(path)[0]
1307 if not os.path.isdir (directory):
1308 os.makedirs (directory)
1309 filename = path + '.ly'
1310 if os.path.exists (filename):
1311 diff_against_existing = filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
1312 if diff_against_existing:
1313 warning ("%s: duplicate filename but different contents of orginal file,\n\
1314 printing diff against existing file." % filename)
1315 ly.stderr_write (diff_against_existing)
1317 out = file (filename, 'w')
1318 out.write (self.full_ly ())
1319 file (path + '.txt', 'w').write ('image of music')
1321 def relevant_contents (self, ly):
1322 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1324 def link_all_output_files (self, output_dir, output_dir_files, destination):
1325 existing, missing = self.all_output_files (output_dir, output_dir_files)
1327 print '\nMissing', missing
1328 raise CompileError(self.basename())
1329 for name in existing:
1330 if (global_options.use_source_file_names
1331 and isinstance (self, LilypondFileSnippet)):
1332 base, ext = os.path.splitext (name)
1333 components = base.split ('-')
1334 # ugh, assume filenames with prefix with one dash (lily-xxxx)
1335 if len (components) > 2:
1336 base_suffix = '-' + components[-1]
1339 final_name = self.final_basename () + base_suffix + ext
1343 os.unlink (os.path.join (destination, final_name))
1347 src = os.path.join (output_dir, name)
1348 dst = os.path.join (destination, final_name)
1349 dst_path = os.path.split(dst)[0]
1350 if not os.path.isdir (dst_path):
1351 os.makedirs (dst_path)
1355 def all_output_files (self, output_dir, output_dir_files):
1356 """Return all files generated in lily_output_dir, a set.
1358 output_dir_files is the list of files in the output directory.
1362 base = self.basename()
1363 full = os.path.join (output_dir, base)
1364 def consider_file (name):
1365 if name in output_dir_files:
1368 def require_file (name):
1369 if name in output_dir_files:
1374 # UGH - junk global_options
1375 skip_lily = global_options.skip_lilypond_run
1376 for required in [base + '.ly',
1378 require_file (required)
1380 require_file (base + '-systems.count')
1382 if 'ddump-profile' in global_options.process_cmd:
1383 require_file (base + '.profile')
1384 if 'dseparate-log-file' in global_options.process_cmd:
1385 require_file (base + '.log')
1387 map (consider_file, [base + '.tex',
1391 base + '-systems.texi',
1392 base + '-systems.tex',
1393 base + '-systems.pdftexi'])
1394 if document_language:
1396 [base + '.texidoc' + document_language,
1397 base + '.doctitle' + document_language])
1399 # UGH - junk global_options
1400 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1401 and not global_options.skip_png_check):
1402 page_count = ps_page_count (full + '.eps')
1404 require_file (base + '.png')
1406 for page in range (1, page_count + 1):
1407 require_file (base + '-page%d.png' % page)
1410 if not skip_lily and not missing:
1411 system_count = int(file (full + '-systems.count').read())
1413 for number in range(1, system_count + 1):
1414 systemfile = '%s-%d' % (base, number)
1415 require_file (systemfile + '.eps')
1416 consider_file (systemfile + '.pdf')
1418 # We can't require signatures, since books and toplevel
1419 # markups do not output a signature.
1420 if 'ddump-signature' in global_options.process_cmd:
1421 consider_file (systemfile + '.signature')
1424 return (result, missing)
1426 def is_outdated (self, output_dir, current_files):
1427 found, missing = self.all_output_files (output_dir, current_files)
1430 def filter_text (self):
1431 """Run snippet bodies through a command (say: convert-ly).
1433 This functionality is rarely used, and this code must have bitrot.
1435 code = self.substring ('code')
1436 s = filter_pipe (code, global_options.filter_cmd)
1439 'options': self.match.group ('options')
1442 return output[self.format][FILTER] % d
1444 def replacement_text (self):
1445 func = LilypondSnippet.__dict__['output_' + self.format]
1448 def get_images (self):
1449 base = self.final_basename ()
1451 single = '%(base)s.png' % vars ()
1452 multiple = '%(base)s-page1.png' % vars ()
1454 if (os.path.exists (multiple)
1455 and (not os.path.exists (single)
1456 or (os.stat (multiple)[stat.ST_MTIME]
1457 > os.stat (single)[stat.ST_MTIME]))):
1458 count = ps_page_count ('%(base)s.eps' % vars ())
1459 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1460 images = tuple (images)
1464 def output_docbook (self):
1466 base = self.final_basename ()
1467 for image in self.get_images ():
1468 (base, ext) = os.path.splitext (image)
1469 str += output[DOCBOOK][OUTPUT] % vars ()
1470 str += self.output_print_filename (DOCBOOK)
1471 if (self.substring('inline') == 'inline'):
1472 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1474 str = '<mediaobject>' + str + '</mediaobject>'
1475 if VERBATIM in self.option_dict:
1476 verb = verbatim_html (self.verb_ly ())
1477 str = output[DOCBOOK][VERBATIM] % vars () + str
1480 def output_html (self):
1482 base = self.final_basename ()
1483 if self.format == HTML:
1484 str += self.output_print_filename (HTML)
1485 if VERBATIM in self.option_dict:
1486 verb = verbatim_html (self.verb_ly ())
1487 str += output[HTML][VERBATIM] % vars ()
1488 if QUOTE in self.option_dict:
1489 str = output[HTML][QUOTE] % vars ()
1491 str += output[HTML][BEFORE] % vars ()
1492 for image in self.get_images ():
1493 (base, ext) = os.path.splitext (image)
1494 alt = self.option_dict[ALT]
1495 str += output[HTML][OUTPUT] % vars ()
1496 str += output[HTML][AFTER] % vars ()
1499 def output_info (self):
1501 for image in self.get_images ():
1502 (base, ext) = os.path.splitext (image)
1504 # URG, makeinfo implicitly prepends dot to extension.
1505 # Specifying no extension is most robust.
1507 alt = self.option_dict[ALT]
1508 info_image_path = os.path.join (global_options.info_images_dir, base)
1509 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1511 base = self.final_basename ()
1512 str += output[self.format][OUTPUT] % vars ()
1515 def output_latex (self):
1517 base = self.final_basename ()
1518 if self.format == LATEX:
1519 str += self.output_print_filename (LATEX)
1520 if VERBATIM in self.option_dict:
1521 verb = self.verb_ly ()
1522 str += (output[LATEX][VERBATIM] % vars ())
1524 str += (output[LATEX][OUTPUT] % vars ())
1526 ## todo: maintain breaks
1528 breaks = self.ly ().count ("\n")
1529 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1531 if QUOTE in self.option_dict:
1532 str = output[LATEX][QUOTE] % vars ()
1535 def output_print_filename (self, format):
1537 if PRINTFILENAME in self.option_dict:
1538 base = self.final_basename ()
1539 filename = os.path.basename (self.substring ('filename'))
1540 str = output[format][PRINTFILENAME] % vars ()
1544 def output_texinfo (self):
1545 str = self.output_print_filename (TEXINFO)
1546 base = self.final_basename ()
1547 if DOCTITLE in self.option_dict:
1548 doctitle = base + '.doctitle'
1549 translated_doctitle = doctitle + document_language
1550 if os.path.exists (translated_doctitle):
1551 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
1552 elif os.path.exists (doctitle):
1553 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
1554 if TEXIDOC in self.option_dict:
1555 texidoc = base + '.texidoc'
1556 translated_texidoc = texidoc + document_language
1557 if os.path.exists (translated_texidoc):
1558 str += '@include %(translated_texidoc)s\n\n' % vars ()
1559 elif os.path.exists (texidoc):
1560 str += '@include %(texidoc)s\n\n' % vars ()
1563 if VERBATIM in self.option_dict:
1565 if ADDVERSION in self.option_dict:
1566 version = output[TEXINFO][ADDVERSION]
1567 verb = self.verb_ly ()
1568 substr = output[TEXINFO][VERBATIM] % vars ()
1569 substr += self.output_info ()
1570 if LILYQUOTE in self.option_dict:
1571 substr = output[TEXINFO][QUOTE] % {'str':substr}
1574 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1575 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1576 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1578 if QUOTE in self.option_dict:
1579 str = output[TEXINFO][QUOTE] % vars ()
1581 # need par after image
1586 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1587 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1589 class LilypondFileSnippet (LilypondSnippet):
1590 def __init__ (self, type, match, format, line_number):
1591 LilypondSnippet.__init__ (self, type, match, format, line_number)
1592 self.contents = file (find_file (self.substring ('filename'))).read ()
1596 s = re_begin_verbatim.split (s)[-1]
1597 s = re_end_verbatim.split (s)[0]
1598 if not NOGETTEXT in self.option_dict:
1599 s = verb_ly_gettext (s)
1600 if not s.endswith ('\n'):
1605 name = self.substring ('filename')
1606 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1607 % (name, self.contents))
1609 def final_basename (self):
1610 if global_options.use_source_file_names:
1611 base = os.path.splitext (os.path.basename (self.substring ('filename')))[0]
1614 return self.basename ()
1617 class LilyPondVersionString (Snippet):
1618 """A string that does not require extra memory."""
1619 def __init__ (self, type, match, format, line_number):
1620 Snippet.__init__ (self, type, match, format, line_number)
1622 def replacement_text (self):
1623 return output[self.format][self.type]
1626 snippet_type_to_class = {
1627 'lilypond_file': LilypondFileSnippet,
1628 'lilypond_block': LilypondSnippet,
1629 'lilypond': LilypondSnippet,
1630 'include': IncludeSnippet,
1631 'lilypondversion': LilyPondVersionString,
1634 def find_linestarts (s):
1639 i = s.find ('\n', start)
1647 nls.append (len (s))
1650 def find_toplevel_snippets (input_string, format, types):
1653 res[t] = re.compile (snippet_res[format][t])
1657 found = dict ([(t, None) for t in types])
1659 line_starts = find_linestarts (input_string)
1661 # We want to search for multiple regexes, without searching
1662 # the string multiple times for one regex.
1663 # Hence, we use earlier results to limit the string portion
1665 # Since every part of the string is traversed at most once for
1666 # every type of snippet, this is linear.
1672 if not found[type] or found[type][0] < index:
1675 m = res[type].search (input_string[index:endex])
1680 if type in snippet_type_to_class:
1681 klass = snippet_type_to_class[type]
1683 start = index + m.start ('match')
1684 line_number = line_start_idx
1685 while (line_starts[line_number] < start):
1689 snip = klass (type, m, format, line_number)
1691 found[type] = (start, snip)
1695 or found[type][0] < found[first][0])):
1700 # Limiting the search space is a cute
1701 # idea, but this *requires* to search
1702 # for possible containing blocks
1703 # first, at least as long as we do not
1704 # search for the start of blocks, but
1705 # always/directly for the entire
1706 # @block ... @end block.
1708 endex = found[first][0]
1711 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1714 while (start > line_starts[line_start_idx+1]):
1717 (start, snip) = found[first]
1718 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1719 snippets.append (snip)
1721 index = start + len (snip.match.group ('match'))
1725 def filter_pipe (input, cmd):
1726 """Pass input through cmd, and return the result."""
1728 if global_options.verbose:
1729 progress (_ ("Opening filter `%s'") % cmd)
1731 (stdin, stdout, stderr) = os.popen3 (cmd)
1733 status = stdin.close ()
1737 output = stdout.read ()
1738 status = stdout.close ()
1739 error = stderr.read ()
1743 signal = 0x0f & status
1744 if status or (not output and error):
1745 exit_status = status >> 8
1746 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1747 error (_ ("The error log is as follows:"))
1748 ly.stderr_write (error)
1749 ly.stderr_write (stderr.read ())
1752 if global_options.verbose:
1757 def system_in_directory (cmd, directory):
1758 """Execute a command in a different directory.
1760 Because of win32 compatibility, we can't simply use subprocess.
1763 current = os.getcwd()
1764 os.chdir (directory)
1765 ly.system(cmd, be_verbose=global_options.verbose,
1770 def process_snippets (cmd, snippets,
1771 format, lily_output_dir):
1772 """Run cmd on all of the .ly files from snippets."""
1777 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1778 cmd += ' --formats=png '
1779 elif format in (DOCBOOK) and '--formats' not in cmd:
1780 cmd += ' --formats=png,pdf '
1782 checksum = snippet_list_checksum (snippets)
1783 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1784 + list (set ([snip.basename() + '.ly' for snip in snippets])))
1785 name = os.path.join (lily_output_dir,
1786 'snippet-names-%d.ly' % checksum)
1787 file (name, 'wb').write (contents)
1789 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1794 # Retrieve dimensions from LaTeX
1795 LATEX_INSPECTION_DOCUMENT = r'''
1799 \typeout{textwidth=\the\textwidth}
1800 \typeout{columnsep=\the\columnsep}
1801 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1805 # Do we need anything else besides `textwidth'?
1806 def get_latex_textwidth (source):
1807 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1809 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1811 ## what's a sensible default?
1814 preamble = source[:m.start (0)]
1815 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1817 (handle, tmpfile) = tempfile.mkstemp('.tex')
1818 logfile = os.path.splitext (tmpfile)[0] + '.log'
1819 logfile = os.path.split (logfile)[1]
1821 tmp_handle = os.fdopen (handle,'w')
1822 tmp_handle.write (latex_document)
1825 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1826 be_verbose=global_options.verbose)
1827 parameter_string = file (logfile).read()
1833 m = re.search ('columns=([0-9.]+)', parameter_string)
1835 columns = int (m.group (1))
1838 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
1840 columnsep = float (m.group (1))
1843 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
1845 textwidth = float (m.group (1))
1847 textwidth = (textwidth - columnsep) / columns
1851 def modify_preamble (chunk):
1852 str = chunk.replacement_text ()
1853 if (re.search (r"\\begin *{document}", str)
1854 and not re.search ("{graphic[sx]", str)):
1855 str = re.sub (r"\\begin{document}",
1856 r"\\usepackage{graphics}" + '\n'
1857 + r"\\begin{document}",
1859 chunk.override_text = str
1864 # TEXINFO: '.texinfo',
1870 class CompileError(Exception):
1873 def snippet_list_checksum (snippets):
1874 return hash (' '.join([l.basename() for l in snippets]))
1876 def write_file_map (lys, name):
1877 snippet_map = file (os.path.join (
1878 global_options.lily_output_dir,
1879 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1881 snippet_map.write ("""
1882 #(define version-seen #t)
1883 #(define output-empty-score-list #f)
1884 #(ly:add-file-name-alist '(%s
1886 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1889 def split_output_files(directory):
1890 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1892 Return value is a set of strings.
1895 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1896 base_subdir = os.path.split (subdir)[1]
1897 sub_files = [os.path.join (base_subdir, name)
1898 for name in os.listdir (subdir)]
1902 def do_process_cmd (chunks, input_name, options):
1903 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1905 output_files = split_output_files (options.lily_output_dir)
1906 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1908 write_file_map (outdated, input_name)
1909 progress (_ ("Writing snippets..."))
1910 for snippet in outdated:
1915 progress (_ ("Processing..."))
1917 process_snippets (options.process_cmd, outdated,
1918 options.format, options.lily_output_dir)
1921 progress (_ ("All snippets are up to date..."))
1923 if options.lily_output_dir != options.output_dir:
1924 output_files = split_output_files (options.lily_output_dir)
1925 for snippet in snippets:
1926 snippet.link_all_output_files (options.lily_output_dir,
1934 # Format guessing data
1943 '.texinfo': TEXINFO,
1948 def guess_format (input_filename):
1950 e = os.path.splitext (input_filename)[1]
1953 format = ext2format[e]
1955 error (_ ("cannot determine format for: %s"
1960 def write_if_updated (file_name, lines):
1962 f = file (file_name)
1964 new_str = ''.join (lines)
1965 if oldstr == new_str:
1966 progress (_ ("%s is up to date.") % file_name)
1969 # this prevents make from always rerunning lilypond-book:
1970 # output file must be touched in order to be up to date
1971 os.utime (file_name, None)
1976 output_dir = os.path.dirname (file_name)
1977 if not os.path.exists (output_dir):
1978 os.makedirs (output_dir)
1980 progress (_ ("Writing `%s'...") % file_name)
1981 file (file_name, 'w').writelines (lines)
1985 def note_input_file (name, inputs=[]):
1986 ## hack: inputs is mutable!
1987 inputs.append (name)
1990 def samefile (f1, f2):
1992 return os.path.samefile (f1, f2)
1993 except AttributeError: # Windoze
1994 f1 = re.sub ("//*", "/", f1)
1995 f2 = re.sub ("//*", "/", f2)
1998 def do_file (input_filename, included=False):
2000 if not input_filename or input_filename == '-':
2001 in_handle = sys.stdin
2002 input_fullname = '<stdin>'
2004 if os.path.exists (input_filename):
2005 input_fullname = input_filename
2006 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
2007 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
2009 input_fullname = find_file (input_filename)
2011 note_input_file (input_fullname)
2012 in_handle = file (input_fullname)
2014 if input_filename == '-':
2015 input_base = 'stdin'
2017 input_base = os.path.splitext (input_filename)[0]
2019 input_base = os.path.basename (
2020 os.path.splitext (input_filename)[0])
2022 # don't complain when global_options.output_dir is existing
2023 if not global_options.output_dir:
2024 global_options.output_dir = os.getcwd()
2026 global_options.output_dir = os.path.abspath(global_options.output_dir)
2028 if not os.path.isdir (global_options.output_dir):
2029 os.mkdir (global_options.output_dir, 0777)
2030 os.chdir (global_options.output_dir)
2032 output_filename = os.path.join(global_options.output_dir,
2033 input_base + format2ext[global_options.format])
2034 if (os.path.exists (input_filename)
2035 and os.path.exists (output_filename)
2036 and samefile (output_filename, input_fullname)):
2038 _ ("Output would overwrite input file; use --output."))
2042 progress (_ ("Reading %s...") % input_fullname)
2043 source = in_handle.read ()
2046 set_default_options (source, default_ly_options, global_options.format)
2049 # FIXME: Containing blocks must be first, see
2050 # find_toplevel_snippets.
2052 'multiline_comment',
2056 'singleline_comment',
2062 progress (_ ("Dissecting..."))
2063 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
2065 if global_options.format == LATEX:
2067 if (c.is_plain () and
2068 re.search (r"\\begin *{document}", c.replacement_text())):
2073 if global_options.filter_cmd:
2074 write_if_updated (output_filename,
2075 [c.filter_text () for c in chunks])
2076 elif global_options.process_cmd:
2077 do_process_cmd (chunks, input_fullname, global_options)
2078 progress (_ ("Compiling %s...") % output_filename)
2080 write_if_updated (output_filename,
2081 [s.replacement_text ()
2084 def process_include (snippet):
2085 os.chdir (original_dir)
2086 name = snippet.substring ('filename')
2087 progress (_ ("Processing include: %s") % name)
2089 return do_file (name, included=True)
2091 include_chunks = map (process_include,
2092 filter (lambda x: isinstance (x, IncludeSnippet),
2095 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2097 except CompileError:
2098 os.chdir (original_dir)
2099 progress (_ ("Removing `%s'") % output_filename)
2104 global global_options
2106 opt_parser = get_option_parser()
2107 (global_options, args) = opt_parser.parse_args ()
2108 if global_options.format in ('texi-html', 'texi'):
2109 global_options.format = TEXINFO
2111 global_options.include_path = map (os.path.abspath, global_options.include_path)
2113 if global_options.warranty:
2116 if not args or len (args) > 1:
2117 opt_parser.print_help ()
2123 # FIXME: 85 lines of `main' macramee??
2124 files = do_options ()
2126 basename = os.path.splitext (files[0])[0]
2127 basename = os.path.split (basename)[1]
2129 if not global_options.format:
2130 global_options.format = guess_format (files[0])
2133 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2136 if global_options.process_cmd == '':
2137 global_options.process_cmd = (lilypond_binary
2138 + ' --formats=%s -dbackend=eps ' % formats)
2140 if global_options.process_cmd:
2141 includes = global_options.include_path
2142 if global_options.lily_output_dir:
2143 # This must be first, so lilypond prefers to read .ly
2144 # files in the other lybookdb dir.
2145 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2146 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2149 if global_options.format in (TEXINFO, LATEX):
2150 ## prevent PDF from being switched on by default.
2151 global_options.process_cmd += ' --formats=eps '
2152 if global_options.create_pdf:
2153 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2154 if global_options.latex_program == 'latex':
2155 global_options.latex_program = 'pdflatex'
2157 if global_options.verbose:
2158 global_options.process_cmd += " --verbose "
2160 if global_options.padding_mm:
2161 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2163 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2165 if global_options.lily_output_dir:
2166 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2167 if not os.path.isdir (global_options.lily_output_dir):
2168 os.makedirs (global_options.lily_output_dir)
2170 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2175 chunks = do_file (files[0])
2176 except CompileError:
2179 inputs = note_input_file ('')
2182 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2183 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2184 final_output_file = os.path.join (global_options.output_dir,
2186 + '.%s' % global_options.format)
2188 os.chdir (original_dir)
2189 file (dep_file, 'w').write ('%s: %s'
2190 % (final_output_file, ' '.join (inputs)))
2192 if __name__ == '__main__':