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--2009',
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"),
169 action='store', dest='latex_program',
172 p.add_option ('--left-padding',
175 help=_ ("pad left side of music to align music inspite of uneven bar numbers (in mm)"),
179 p.add_option ('--lily-output-dir',
180 help=_ ("write lily-XXX files to DIR, link into --output dir"),
182 action='store', dest='lily_output_dir',
185 p.add_option ("-o", '--output', help=_ ("write output to DIR"),
187 action='store', dest='output_dir',
190 p.add_option ('--pdf',
193 help=_ ("create PDF files for use with PDFTeX"),
196 p.add_option ('-P', '--process', metavar=_ ("COMMAND"),
197 help = _ ("process ly_files using COMMAND FILE..."),
199 dest='process_cmd', default='')
201 p.add_option ('--skip-lily-check',
202 help=_ ("do not fail if no lilypond output is found"),
204 action='store_true', dest='skip_lilypond_run',
207 p.add_option ('--skip-png-check',
208 help=_ ("do not fail if no PNG images are found for EPS files"),
210 action='store_true', dest='skip_png_check',
213 p.add_option ('-V', '--verbose', help=_ ("be verbose"),
218 p.version = "@TOPLEVEL_VERSION@"
219 p.add_option("--version",
221 help=_ ("show version number and exit"))
223 p.add_option ('-w', '--warranty',
224 help=_ ("show warranty and copyright"),
226 p.add_option_group ('',
228 _ ("Report bugs via %s")
229 % ' http://post.gmane.org/post.php'
230 '?group=gmane.comp.gnu.lilypond.bugs') + '\n')
233 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
235 # If we are called with full path, try to use lilypond binary
236 # installed in the same path; this is needed in GUB binaries, where
237 # @bindir is always different from the installed binary path.
238 if 'bindir' in globals () and bindir:
239 lilypond_binary = os.path.join (bindir, 'lilypond')
241 # Only use installed binary when we are installed too.
242 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
243 lilypond_binary = 'lilypond'
245 global_options = None
248 default_ly_options = { 'alt': "[image of music]" }
250 document_language = ''
253 # Is this pythonic? Personally, I find this rather #define-nesque. --hwn
255 ADDVERSION = 'addversion'
259 EXAMPLEINDENT = 'exampleindent'
261 FRAGMENT = 'fragment'
267 LINE_WIDTH = 'line-width'
268 LILYQUOTE = 'lilyquote'
269 NOFRAGMENT = 'nofragment'
270 NOGETTEXT = 'nogettext'
271 NOINDENT = 'noindent'
273 NORAGGED_RIGHT = 'noragged-right'
277 OUTPUTIMAGE = 'outputimage'
279 PREAMBLE = 'preamble'
280 PRINTFILENAME = 'printfilename'
282 RAGGED_RIGHT = 'ragged-right'
283 RELATIVE = 'relative'
284 STAFFSIZE = 'staffsize'
285 DOCTITLE = 'doctitle'
288 VERBATIM = 'verbatim'
289 VERSION = 'lilypondversion'
290 FILENAME = 'filename'
294 # NOTIME and NOGETTEXT have no opposite so they aren't part of this
296 # NOQUOTE is used internally only.
298 NOFRAGMENT: FRAGMENT,
302 # Options that have no impact on processing by lilypond (or --process
304 PROCESSING_INDEPENDENT_OPTIONS = (
305 ALT, NOGETTEXT, VERBATIM, ADDVERSION,
306 TEXIDOC, DOCTITLE, VERSION, PRINTFILENAME)
308 # Recognize special sequences in the input.
310 # (?P<name>regex) -- Assign result of REGEX to NAME.
311 # *? -- Match non-greedily.
312 # (?!...) -- Match if `...' doesn't match next (without consuming
315 # (?m) -- Multiline regex: Make ^ and $ match at each line.
316 # (?s) -- Make the dot match all characters including newline.
317 # (?x) -- Ignore whitespace in patterns.
328 <(?P<inline>(inline)?)mediaobject>\s*
330 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
332 </programlisting\s*>\s*
334 </(inline)?mediaobject>)''',
339 <(?P<inline>(inline)?)mediaobject>\s*
341 <programlisting\s+language="lilypond".*?(role="(?P<options>.*?)")?>
343 </programlisting\s*>\s*
345 </(inline)?mediaobject>)''',
350 <(?P<inline>(inline)?)mediaobject>\s*
353 fileref="(?P<filename>.*?\.ly)"\s*
354 (role="(?P<options>.*?)")?\s*
355 (/>|>\s*</imagedata>)\s*
357 </(inline)?mediaobject>)''',
363 (?P<code><!--\s.*?!-->)
366 'singleline_comment':
387 (\s*(?P<options>.*?)\s*:)?\s*
395 \s*(?P<options>.*?)\s*
404 \s*(?P<options>.*?)\s*
406 \s*(?P<filename>.*?)\s*
413 (?P<code><!--\s.*?!-->)
416 'singleline_comment':
422 (?P<code><pre>.*?</pre>))''',
428 (?P<code><pre>\s.*?</pre>\s))''',
433 <lilypondversion\s*/>)''',
452 \s*(?P<options>.*?)\s*
463 \s*(?P<options>.*?)\s*
467 \\end\s*{lilypond})''',
475 \s*(?P<options>.*?)\s*
483 'singleline_comment':
506 \\end\s*{verbatim}))''',
511 \\lilypondversion)[^a-zA-Z]''',
521 (?P<filename>\S+))''',
525 ^[^\n]*?(?!@c\s+)[^\n]*?
529 \s*(?P<options>.*?)\s*
539 \s*(?P<options>.*?)\s*
542 ^@end\s+lilypond)\s''',
549 \s*(?P<options>.*?)\s*
560 @end\s+ignore))\s''',
562 'singleline_comment':
567 @c([ \t][^\n]*|)\n))''',
569 # Don't do this: It interferes with @code{@{}.
570 # 'verb': r'''(?P<code>@code{.*?})''',
578 @end\s+example\s))''',
583 @lilypondversion)[^a-zA-Z]''',
591 'intertext': r',?\s*intertext=\".*?\"',
595 'intertext': r',?\s*intertext=\".*?\"',
600 'intertext': r',?\s*intertext=\".*?\"',
601 'option_sep': '\s*,\s*',
605 'intertext': r',?\s*intertext=\".*?\"',
606 'option_sep': '\s*,\s*',
611 # Options without a pattern in ly_options.
631 RELATIVE: r'''\relative c%(relative_quotes)s''',
636 INDENT: r'''indent = %(indent)s''',
638 LINE_WIDTH: r'''line-width = %(line-width)s''',
640 QUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
642 LILYQUOTE: r'''line-width = %(line-width)s - 2.0 * %(exampleindent)s''',
644 RAGGED_RIGHT: r'''ragged-right = ##t''',
646 NORAGGED_RIGHT: r'''ragged-right = ##f''',
658 \remove "Time_signature_engraver"
664 STAFFSIZE: r'''#(set-global-staff-size %(staffsize)s)''',
671 FILTER: r'''<mediaobject>
673 <programlisting language="lilypond"
680 OUTPUT: r'''<imageobject role="latex">
681 <imagedata fileref="%(base)s.pdf" format="PDF"/>
683 <imageobject role="html">
684 <imagedata fileref="%(base)s.png" format="PNG"/>
687 VERBATIM: r'''<programlisting>
688 %(verb)s</programlisting>''',
690 VERSION: program_version,
692 PRINTFILENAME: r'''<textobject>
694 <ulink url="%(base)s.ly">
704 FILTER: r'''<lilypond %(options)s>
714 <a href="%(base)s.ly">''',
722 PRINTFILENAME: '<p><tt><a href="%(base)s.ly">%(filename)s</a></tt></p>',
724 QUOTE: r'''<blockquote>
732 VERSION: program_version,
739 \ifx\preLilyPondExample \undefined
741 \expandafter\preLilyPondExample
743 \def\lilypondbook{}%%
744 \input %(base)s-systems.tex
745 \ifx\postLilyPondExample \undefined
747 \expandafter\postLilyPondExample
751 PRINTFILENAME: '''\\texttt{%(filename)s}
754 QUOTE: r'''\begin{quotation}
758 VERBATIM: r'''\noindent
759 \begin{verbatim}%(verb)s\end{verbatim}
762 VERSION: program_version,
764 FILTER: r'''\begin{lilypond}[%(options)s]
771 FILTER: r'''@lilypond[%(options)s]
777 @include %(base)s-systems.texi
781 OUTPUTIMAGE: r'''@noindent
783 @image{%(info_image_path)s,,,%(alt)s,%(ext)s}
787 <a href="%(base)s.ly">
799 <a href="%(base)s.ly">
807 QUOTE: r'''@quotation
808 %(str)s@end quotation
815 VERBATIM: r'''@exampleindent 0
817 %(verb)s@end verbatim
820 VERSION: program_version,
822 ADDVERSION: r'''@example
823 \version @w{"@version{}"}
830 # Maintain line numbers.
835 for f in [HTML, LATEX]:
836 for s in (QUOTE, VERBATIM):
837 output[f][s] = output[f][s].replace("\n"," ")
840 PREAMBLE_LY = '''%%%% Generated by %(program_name)s
841 %%%% Options: [%(option_string)s]
842 \\include "lilypond-book-preamble.ly"
845 %% ****************************************************************
846 %% Start cut-&-pastable-section
847 %% ****************************************************************
853 force-assignment = #""
854 line-width = #(- line-width (* mm %(padding_mm)f))
867 %% ****************************************************************
868 %% ly snippet contents follows:
869 %% ****************************************************************
873 %% ****************************************************************
875 %% ****************************************************************
882 %% ****************************************************************
884 %% ****************************************************************
888 %% ****************************************************************
890 %% ****************************************************************
893 texinfo_line_widths = {
894 '@afourpaper': '160\\mm',
895 '@afourwide': '6.5\\in',
896 '@afourlatex': '150\\mm',
897 '@smallbook': '5\\in',
898 '@letterpaper': '6\\in',
901 def classic_lilypond_book_compatibility (key, value):
902 if key == 'singleline' and value == None:
903 return (RAGGED_RIGHT, None)
905 m = re.search ('relative\s*([-0-9])', key)
907 return ('relative', m.group (1))
909 m = re.match ('([0-9]+)pt', key)
911 return ('staffsize', m.group (1))
913 if key == 'indent' or key == 'line-width':
914 m = re.match ('([-.0-9]+)(cm|in|mm|pt|staffspace)', value)
916 f = float (m.group (1))
917 return (key, '%f\\%s' % (f, m.group (2)))
921 def find_file (name, raise_error=True):
922 for i in global_options.include_path:
923 full = os.path.join (i, name)
924 if os.path.exists (full):
928 error (_ ("file not found: %s") % name + '\n')
932 def verbatim_html (s):
933 return re.sub ('>', '>',
935 re.sub ('&', '&', s)))
937 ly_var_def_re = re.compile (r'^([a-zA-Z]+)[\t ]*=', re.M)
938 ly_comment_re = re.compile (r'(%+[\t ]*)(.*)$', re.M)
939 ly_context_id_re = re.compile ('\\\\(?:new|context)\\s+(?:[a-zA-Z]*?(?:Staff\
940 (?:Group)?|Voice|FiguredBass|FretBoards|Names|Devnull))\\s+=\\s+"?([a-zA-Z]+)"?\\s+')
942 def ly_comment_gettext (t, m):
943 return m.group (1) + t (m.group (2))
945 def verb_ly_gettext (s):
946 if not document_language:
949 t = langdefs.translation[document_language]
953 s = ly_comment_re.sub (lambda m: ly_comment_gettext (t, m), s)
955 if langdefs.LANGDICT[document_language].enable_ly_identifier_l10n:
956 for v in ly_var_def_re.findall (s):
957 s = re.sub (r"(?m)(^|[' \\#])%s([^a-zA-Z])" % v,
958 "\\1" + t (v) + "\\2",
960 for id in ly_context_id_re.findall (s):
961 s = re.sub (r'(\s+|")%s(\s+|")' % id,
962 "\\1" + t (id) + "\\2",
966 texinfo_lang_re = re.compile ('(?m)^@documentlanguage (.*?)( |$)')
967 def set_default_options (source, default_ly_options, format):
968 global document_language
969 if LINE_WIDTH not in default_ly_options:
971 textwidth = get_latex_textwidth (source)
972 default_ly_options[LINE_WIDTH] = '%.0f\\pt' % textwidth
973 elif format == TEXINFO:
974 m = texinfo_lang_re.search (source)
975 if m and not m.group (1).startswith ('en'):
976 document_language = m.group (1)
978 document_language = ''
979 for regex in texinfo_line_widths:
980 # FIXME: @layout is usually not in
983 # \input texinfo @c -*-texinfo-*-
985 # Bluntly search first K items of
987 # s = chunks[0].replacement_text ()
988 if re.search (regex, source[:1024]):
989 default_ly_options[LINE_WIDTH] = texinfo_line_widths[regex]
993 def replacement_text (self):
996 def filter_text (self):
997 return self.replacement_text ()
1002 class Substring (Chunk):
1003 """A string that does not require extra memory."""
1004 def __init__ (self, source, start, end, line_number):
1005 self.source = source
1008 self.line_number = line_number
1009 self.override_text = None
1011 def is_plain (self):
1014 def replacement_text (self):
1015 if self.override_text:
1016 return self.override_text
1018 return self.source[self.start:self.end]
1020 class Snippet (Chunk):
1021 def __init__ (self, type, match, format, line_number):
1025 self.option_dict = {}
1026 self.format = format
1027 self.line_number = line_number
1029 def replacement_text (self):
1030 return self.match.group ('match')
1032 def substring (self, s):
1033 return self.match.group (s)
1035 def __repr__ (self):
1036 return `self.__class__` + ' type = ' + self.type
1038 class IncludeSnippet (Snippet):
1039 def processed_filename (self):
1040 f = self.substring ('filename')
1041 return os.path.splitext (f)[0] + format2ext[self.format]
1043 def replacement_text (self):
1044 s = self.match.group ('match')
1045 f = self.substring ('filename')
1047 return re.sub (f, self.processed_filename (), s)
1049 class LilypondSnippet (Snippet):
1050 def __init__ (self, type, match, format, line_number):
1051 Snippet.__init__ (self, type, match, format, line_number)
1052 os = match.group ('options')
1053 self.do_options (os, self.type)
1056 verb_text = self.substring ('code')
1057 if not NOGETTEXT in self.option_dict:
1058 verb_text = verb_ly_gettext (verb_text)
1059 if not verb_text.endswith ('\n'):
1064 contents = self.substring ('code')
1065 return ('\\sourcefileline %d\n%s'
1066 % (self.line_number - 1, contents))
1071 return self.compose_ly (s)
1074 def split_options (self, option_string):
1076 if self.format == HTML:
1077 options = re.findall('[\w\.-:]+(?:\s*=\s*(?:"[^"]*"|\'[^\']*\'|\S+))?',
1079 options = [re.sub('^([^=]+=\s*)(?P<q>["\'])(.*)(?P=q)', '\g<1>\g<3>', opt)
1083 return re.split (format_res[self.format]['option_sep'],
1087 def do_options (self, option_string, type):
1088 self.option_dict = {}
1090 options = self.split_options (option_string)
1092 for option in options:
1094 (key, value) = re.split ('\s*=\s*', option)
1095 self.option_dict[key] = value
1097 if option in no_options:
1098 if no_options[option] in self.option_dict:
1099 del self.option_dict[no_options[option]]
1101 self.option_dict[option] = None
1103 has_line_width = self.option_dict.has_key (LINE_WIDTH)
1104 no_line_width_value = 0
1106 # If LINE_WIDTH is used without parameter, set it to default.
1107 if has_line_width and self.option_dict[LINE_WIDTH] == None:
1108 no_line_width_value = 1
1109 del self.option_dict[LINE_WIDTH]
1111 for k in default_ly_options:
1112 if k not in self.option_dict:
1113 self.option_dict[k] = default_ly_options[k]
1115 # RELATIVE does not work without FRAGMENT;
1116 # make RELATIVE imply FRAGMENT
1117 has_relative = self.option_dict.has_key (RELATIVE)
1118 if has_relative and not self.option_dict.has_key (FRAGMENT):
1119 self.option_dict[FRAGMENT] = None
1121 if not has_line_width:
1122 if type == 'lilypond' or FRAGMENT in self.option_dict:
1123 self.option_dict[RAGGED_RIGHT] = None
1125 if type == 'lilypond':
1126 if LINE_WIDTH in self.option_dict:
1127 del self.option_dict[LINE_WIDTH]
1129 if RAGGED_RIGHT in self.option_dict:
1130 if LINE_WIDTH in self.option_dict:
1131 del self.option_dict[LINE_WIDTH]
1133 if QUOTE in self.option_dict or type == 'lilypond':
1134 if LINE_WIDTH in self.option_dict:
1135 del self.option_dict[LINE_WIDTH]
1137 if not INDENT in self.option_dict:
1138 self.option_dict[INDENT] = '0\\mm'
1140 # Set a default line-width if there is none. We need this, because
1141 # lilypond-book has set left-padding by default and therefore does
1142 # #(define line-width (- line-width (* 3 mm)))
1143 # TODO: Junk this ugly hack if the code gets rewritten to concatenate
1144 # all settings before writing them in the \paper block.
1145 if not LINE_WIDTH in self.option_dict:
1146 if not QUOTE in self.option_dict:
1147 if not LILYQUOTE in self.option_dict:
1148 self.option_dict[LINE_WIDTH] = "#(- paper-width \
1149 left-margin-default right-margin-default)"
1151 def get_option_list (self):
1152 if not 'option_list' in self.__dict__:
1154 for (key, value) in self.option_dict.items ():
1156 option_list.append (key)
1158 option_list.append (key + '=' + value)
1160 self.option_list = option_list
1161 return self.option_list
1163 def compose_ly (self, code):
1164 if FRAGMENT in self.option_dict:
1172 # The original concept of the `exampleindent' option is broken.
1173 # It is not possible to get a sane value for @exampleindent at all
1174 # without processing the document itself. Saying
1182 # causes ugly results with the DVI backend of texinfo since the
1183 # default value for @exampleindent isn't 5em but 0.4in (or a smaller
1184 # value). Executing the above code changes the environment
1185 # indentation to an unknown value because we don't know the amount
1186 # of 1em in advance since it is font-dependent. Modifying
1187 # @exampleindent in the middle of a document is simply not
1188 # supported within texinfo.
1190 # As a consequence, the only function of @exampleindent is now to
1191 # specify the amount of indentation for the `quote' option.
1193 # To set @exampleindent locally to zero, we use the @format
1194 # environment for non-quoted snippets.
1195 override[EXAMPLEINDENT] = r'0.4\in'
1196 override[LINE_WIDTH] = texinfo_line_widths['@smallbook']
1197 override.update (default_ly_options)
1200 for option in self.get_option_list ():
1201 for name in PROCESSING_INDEPENDENT_OPTIONS:
1202 if not option.startswith (name):
1203 option_list.append (option)
1204 option_string = ','.join (option_list)
1207 compose_types = [NOTES, PREAMBLE, LAYOUT, PAPER]
1208 for a in compose_types:
1209 compose_dict[a] = []
1211 option_names = self.option_dict.keys ()
1212 option_names.sort ()
1213 for key in option_names:
1214 value = self.option_dict[key]
1215 (c_key, c_value) = classic_lilypond_book_compatibility (key, value)
1219 _ ("deprecated ly-option used: %s=%s") % (key, value))
1221 _ ("compatibility mode translation: %s=%s") % (c_key, c_value))
1224 _ ("deprecated ly-option used: %s") % key)
1226 _ ("compatibility mode translation: %s") % c_key)
1228 (key, value) = (c_key, c_value)
1231 override[key] = value
1233 if not override.has_key (key):
1234 override[key] = None
1237 for type in compose_types:
1238 if ly_options[type].has_key (key):
1239 compose_dict[type].append (ly_options[type][key])
1243 if not found and key not in simple_options:
1244 warning (_ ("ignoring unknown ly option: %s") % key)
1247 if RELATIVE in override and override[RELATIVE]:
1248 relative = int (override[RELATIVE])
1250 relative_quotes = ''
1254 relative_quotes += ',' * (- relative)
1256 relative_quotes += "'" * relative
1258 paper_string = '\n '.join (compose_dict[PAPER]) % override
1259 layout_string = '\n '.join (compose_dict[LAYOUT]) % override
1260 notes_string = '\n '.join (compose_dict[NOTES]) % vars ()
1261 preamble_string = '\n '.join (compose_dict[PREAMBLE]) % override
1262 padding_mm = global_options.padding_mm
1264 d = globals().copy()
1266 return (PREAMBLE_LY + body) % d
1268 def get_checksum (self):
1269 if not self.checksum:
1270 # Work-around for md5 module deprecation warning in python 2.5+:
1272 from hashlib import md5
1276 # We only want to calculate the hash based on the snippet
1277 # code plus fragment options relevant to processing by
1278 # lilypond, not the snippet + preamble
1279 hash = md5 (self.relevant_contents (self.ly ()))
1280 for option in self.get_option_list ():
1281 for name in PROCESSING_INDEPENDENT_OPTIONS:
1282 if not option.startswith (name):
1283 hash.update (option)
1285 ## let's not create too long names.
1286 self.checksum = hash.hexdigest ()[:10]
1288 return self.checksum
1290 def basename (self):
1291 cs = self.get_checksum ()
1292 name = '%s/lily-%s' % (cs[:2], cs[2:])
1295 def write_ly (self):
1296 base = self.basename ()
1297 path = os.path.join (global_options.lily_output_dir, base)
1298 directory = os.path.split(path)[0]
1299 if not os.path.isdir (directory):
1300 os.makedirs (directory)
1301 filename = path + '.ly'
1302 if os.path.exists (filename):
1303 diff_against_existing = filter_pipe (self.full_ly (), 'diff -u %s -' % filename)
1304 if not diff_against_existing.startswith ('\n'):
1305 warning ("%s: duplicate filename but different contents of orginal file,\n\
1306 printing diff against existing file." % filename)
1307 ly.stderr_write (diff_against_existing)
1309 out = file (filename, 'w')
1310 out.write (self.full_ly ())
1311 file (path + '.txt', 'w').write ('image of music')
1313 def relevant_contents (self, ly):
1314 return re.sub (r'\\(version|sourcefileline|sourcefilename)[^\n]*\n', '', ly)
1316 def link_all_output_files (self, output_dir, output_dir_files, destination):
1317 existing, missing = self.all_output_files (output_dir, output_dir_files)
1319 print '\nMissing', missing
1320 raise CompileError(self.basename())
1321 for name in existing:
1323 os.unlink (os.path.join (destination, name))
1327 src = os.path.join (output_dir, name)
1328 dst = os.path.join (destination, name)
1329 dst_path = os.path.split(dst)[0]
1330 if not os.path.isdir (dst_path):
1331 os.makedirs (dst_path)
1335 def all_output_files (self, output_dir, output_dir_files):
1336 """Return all files generated in lily_output_dir, a set.
1338 output_dir_files is the list of files in the output directory.
1342 base = self.basename()
1343 full = os.path.join (output_dir, base)
1344 def consider_file (name):
1345 if name in output_dir_files:
1348 def require_file (name):
1349 if name in output_dir_files:
1354 # UGH - junk global_options
1355 skip_lily = global_options.skip_lilypond_run
1356 for required in [base + '.ly',
1358 require_file (required)
1360 require_file (base + '-systems.count')
1362 if 'ddump-profile' in global_options.process_cmd:
1363 require_file (base + '.profile')
1364 if 'dseparate-log-file' in global_options.process_cmd:
1365 require_file (base + '.log')
1367 map (consider_file, [base + '.tex',
1371 base + '-systems.texi',
1372 base + '-systems.tex',
1373 base + '-systems.pdftexi'])
1374 if document_language:
1376 [base + '.texidoc' + document_language,
1377 base + '.doctitle' + document_language])
1379 # UGH - junk global_options
1380 if (base + '.eps' in result and self.format in (HTML, TEXINFO)
1381 and not global_options.skip_png_check):
1382 page_count = ps_page_count (full + '.eps')
1384 require_file (base + '.png')
1386 for page in range (1, page_count + 1):
1387 require_file (base + '-page%d.png' % page)
1390 if not skip_lily and not missing:
1391 system_count = int(file (full + '-systems.count').read())
1393 for number in range(1, system_count + 1):
1394 systemfile = '%s-%d' % (base, number)
1395 require_file (systemfile + '.eps')
1396 consider_file (systemfile + '.pdf')
1398 # We can't require signatures, since books and toplevel
1399 # markups do not output a signature.
1400 if 'ddump-signature' in global_options.process_cmd:
1401 consider_file (systemfile + '.signature')
1404 return (result, missing)
1406 def is_outdated (self, output_dir, current_files):
1407 found, missing = self.all_output_files (output_dir, current_files)
1410 def filter_text (self):
1411 """Run snippet bodies through a command (say: convert-ly).
1413 This functionality is rarely used, and this code must have bitrot.
1415 code = self.substring ('code')
1416 s = filter_pipe (code, global_options.filter_cmd)
1419 'options': self.match.group ('options')
1422 return output[self.format][FILTER] % d
1424 def replacement_text (self):
1425 func = LilypondSnippet.__dict__['output_' + self.format]
1428 def get_images (self):
1429 base = self.basename ()
1431 single = '%(base)s.png' % vars ()
1432 multiple = '%(base)s-page1.png' % vars ()
1434 if (os.path.exists (multiple)
1435 and (not os.path.exists (single)
1436 or (os.stat (multiple)[stat.ST_MTIME]
1437 > os.stat (single)[stat.ST_MTIME]))):
1438 count = ps_page_count ('%(base)s.eps' % vars ())
1439 images = ['%s-page%d.png' % (base, page) for page in range (1, count+1)]
1440 images = tuple (images)
1444 def output_docbook (self):
1446 base = self.basename ()
1447 for image in self.get_images ():
1448 (base, ext) = os.path.splitext (image)
1449 str += output[DOCBOOK][OUTPUT] % vars ()
1450 str += self.output_print_filename (DOCBOOK)
1451 if (self.substring('inline') == 'inline'):
1452 str = '<inlinemediaobject>' + str + '</inlinemediaobject>'
1454 str = '<mediaobject>' + str + '</mediaobject>'
1455 if VERBATIM in self.option_dict:
1456 verb = verbatim_html (self.verb_ly ())
1457 str = output[DOCBOOK][VERBATIM] % vars () + str
1460 def output_html (self):
1462 base = self.basename ()
1463 if self.format == HTML:
1464 str += self.output_print_filename (HTML)
1465 if VERBATIM in self.option_dict:
1466 verb = verbatim_html (self.verb_ly ())
1467 str += output[HTML][VERBATIM] % vars ()
1468 if QUOTE in self.option_dict:
1469 str = output[HTML][QUOTE] % vars ()
1471 str += output[HTML][BEFORE] % vars ()
1472 for image in self.get_images ():
1473 (base, ext) = os.path.splitext (image)
1474 alt = self.option_dict[ALT]
1475 str += output[HTML][OUTPUT] % vars ()
1476 str += output[HTML][AFTER] % vars ()
1479 def output_info (self):
1481 for image in self.get_images ():
1482 (base, ext) = os.path.splitext (image)
1484 # URG, makeinfo implicitly prepends dot to extension.
1485 # Specifying no extension is most robust.
1487 alt = self.option_dict[ALT]
1488 info_image_path = os.path.join (global_options.info_images_dir, base)
1489 str += output[TEXINFO][OUTPUTIMAGE] % vars ()
1491 base = self.basename ()
1492 str += output[self.format][OUTPUT] % vars ()
1495 def output_latex (self):
1497 base = self.basename ()
1498 if self.format == LATEX:
1499 str += self.output_print_filename (LATEX)
1500 if VERBATIM in self.option_dict:
1501 verb = self.verb_ly ()
1502 str += (output[LATEX][VERBATIM] % vars ())
1504 str += (output[LATEX][OUTPUT] % vars ())
1506 ## todo: maintain breaks
1508 breaks = self.ly ().count ("\n")
1509 str += "".ljust (breaks, "\n").replace ("\n","%\n")
1511 if QUOTE in self.option_dict:
1512 str = output[LATEX][QUOTE] % vars ()
1515 def output_print_filename (self, format):
1517 if PRINTFILENAME in self.option_dict:
1518 base = self.basename ()
1519 filename = os.path.basename (self.substring ('filename'))
1520 str = output[format][PRINTFILENAME] % vars ()
1524 def output_texinfo (self):
1525 str = self.output_print_filename (TEXINFO)
1526 base = self.basename ()
1527 if DOCTITLE in self.option_dict:
1528 doctitle = base + '.doctitle'
1529 translated_doctitle = doctitle + document_language
1530 if os.path.exists (translated_doctitle):
1531 str += '@lydoctitle %s\n\n' % open (translated_doctitle).read ()
1532 elif os.path.exists (doctitle):
1533 str += '@lydoctitle %s\n\n' % open (doctitle).read ()
1534 if TEXIDOC in self.option_dict:
1535 texidoc = base + '.texidoc'
1536 translated_texidoc = texidoc + document_language
1537 if os.path.exists (translated_texidoc):
1538 str += '@include %(translated_texidoc)s\n\n' % vars ()
1539 elif os.path.exists (texidoc):
1540 str += '@include %(texidoc)s\n\n' % vars ()
1543 if VERBATIM in self.option_dict:
1545 if ADDVERSION in self.option_dict:
1546 version = output[TEXINFO][ADDVERSION]
1547 verb = self.verb_ly ()
1548 substr = output[TEXINFO][VERBATIM] % vars ()
1549 substr += self.output_info ()
1550 if LILYQUOTE in self.option_dict:
1551 substr = output[TEXINFO][QUOTE] % {'str':substr}
1554 # str += ('@ifinfo\n' + self.output_info () + '\n@end ifinfo\n')
1555 # str += ('@tex\n' + self.output_latex () + '\n@end tex\n')
1556 # str += ('@html\n' + self.output_html () + '\n@end html\n')
1558 if QUOTE in self.option_dict:
1559 str = output[TEXINFO][QUOTE] % vars ()
1561 # need par after image
1566 re_begin_verbatim = re.compile (r'\s+%.*?begin verbatim.*\n*', re.M)
1567 re_end_verbatim = re.compile (r'\s+%.*?end verbatim.*$', re.M)
1569 class LilypondFileSnippet (LilypondSnippet):
1570 def __init__ (self, type, match, format, line_number):
1571 LilypondSnippet.__init__ (self, type, match, format, line_number)
1572 self.contents = file (find_file (self.substring ('filename'))).read ()
1576 s = re_begin_verbatim.split (s)[-1]
1577 s = re_end_verbatim.split (s)[0]
1578 if not NOGETTEXT in self.option_dict:
1579 s = verb_ly_gettext (s)
1580 if not s.endswith ('\n'):
1585 name = self.substring ('filename')
1586 return ('\\sourcefilename \"%s\"\n\\sourcefileline 0\n%s'
1587 % (name, self.contents))
1590 class LilyPondVersionString (Snippet):
1591 """A string that does not require extra memory."""
1592 def __init__ (self, type, match, format, line_number):
1593 Snippet.__init__ (self, type, match, format, line_number)
1595 def replacement_text (self):
1596 return output[self.format][self.type]
1599 snippet_type_to_class = {
1600 'lilypond_file': LilypondFileSnippet,
1601 'lilypond_block': LilypondSnippet,
1602 'lilypond': LilypondSnippet,
1603 'include': IncludeSnippet,
1604 'lilypondversion': LilyPondVersionString,
1607 def find_linestarts (s):
1612 i = s.find ('\n', start)
1620 nls.append (len (s))
1623 def find_toplevel_snippets (input_string, format, types):
1626 res[t] = re.compile (snippet_res[format][t])
1630 found = dict ([(t, None) for t in types])
1632 line_starts = find_linestarts (input_string)
1634 # We want to search for multiple regexes, without searching
1635 # the string multiple times for one regex.
1636 # Hence, we use earlier results to limit the string portion
1638 # Since every part of the string is traversed at most once for
1639 # every type of snippet, this is linear.
1645 if not found[type] or found[type][0] < index:
1648 m = res[type].search (input_string[index:endex])
1653 if type in snippet_type_to_class:
1654 klass = snippet_type_to_class[type]
1656 start = index + m.start ('match')
1657 line_number = line_start_idx
1658 while (line_starts[line_number] < start):
1662 snip = klass (type, m, format, line_number)
1664 found[type] = (start, snip)
1668 or found[type][0] < found[first][0])):
1673 # Limiting the search space is a cute
1674 # idea, but this *requires* to search
1675 # for possible containing blocks
1676 # first, at least as long as we do not
1677 # search for the start of blocks, but
1678 # always/directly for the entire
1679 # @block ... @end block.
1681 endex = found[first][0]
1684 snippets.append (Substring (input_string, index, len (input_string), line_start_idx))
1687 while (start > line_starts[line_start_idx+1]):
1690 (start, snip) = found[first]
1691 snippets.append (Substring (input_string, index, start, line_start_idx + 1))
1692 snippets.append (snip)
1694 index = start + len (snip.match.group ('match'))
1698 def filter_pipe (input, cmd):
1699 """Pass input through cmd, and return the result."""
1701 if global_options.verbose:
1702 progress (_ ("Opening filter `%s'") % cmd)
1704 (stdin, stdout, stderr) = os.popen3 (cmd)
1706 status = stdin.close ()
1710 output = stdout.read ()
1711 status = stdout.close ()
1712 error = stderr.read ()
1716 signal = 0x0f & status
1717 if status or (not output and error):
1718 exit_status = status >> 8
1719 error (_ ("`%s' failed (%d)") % (cmd, exit_status))
1720 error (_ ("The error log is as follows:"))
1721 ly.stderr_write (error)
1722 ly.stderr_write (stderr.read ())
1725 if global_options.verbose:
1730 def system_in_directory (cmd, directory):
1731 """Execute a command in a different directory.
1733 Because of win32 compatibility, we can't simply use subprocess.
1736 current = os.getcwd()
1737 os.chdir (directory)
1738 ly.system(cmd, be_verbose=global_options.verbose,
1743 def process_snippets (cmd, snippets,
1744 format, lily_output_dir):
1745 """Run cmd on all of the .ly files from snippets."""
1750 if format in (HTML, TEXINFO) and '--formats' not in cmd:
1751 cmd += ' --formats=png '
1752 elif format in (DOCBOOK) and '--formats' not in cmd:
1753 cmd += ' --formats=png,pdf '
1755 checksum = snippet_list_checksum (snippets)
1756 contents = '\n'.join (['snippet-map-%d.ly' % checksum]
1757 + list (set ([snip.basename() + '.ly' for snip in snippets])))
1758 name = os.path.join (lily_output_dir,
1759 'snippet-names-%d.ly' % checksum)
1760 file (name, 'wb').write (contents)
1762 system_in_directory (' '.join ([cmd, ly.mkarg (name)]),
1767 # Retrieve dimensions from LaTeX
1768 LATEX_INSPECTION_DOCUMENT = r'''
1772 \typeout{textwidth=\the\textwidth}
1773 \typeout{columnsep=\the\columnsep}
1774 \makeatletter\if@twocolumn\typeout{columns=2}\fi\makeatother
1778 # Do we need anything else besides `textwidth'?
1779 def get_latex_textwidth (source):
1780 m = re.search (r'''(?P<preamble>\\begin\s*{document})''', source)
1782 warning (_ ("cannot find \\begin{document} in LaTeX document"))
1784 ## what's a sensible default?
1787 preamble = source[:m.start (0)]
1788 latex_document = LATEX_INSPECTION_DOCUMENT % vars ()
1790 (handle, tmpfile) = tempfile.mkstemp('.tex')
1791 logfile = os.path.splitext (tmpfile)[0] + '.log'
1792 logfile = os.path.split (logfile)[1]
1794 tmp_handle = os.fdopen (handle,'w')
1795 tmp_handle.write (latex_document)
1798 ly.system ('%s %s' % (global_options.latex_program, tmpfile),
1799 be_verbose=global_options.verbose)
1800 parameter_string = file (logfile).read()
1806 m = re.search ('columns=([0-9.]+)', parameter_string)
1808 columns = int (m.group (1))
1811 m = re.search ('columnsep=([0-9.]+)pt', parameter_string)
1813 columnsep = float (m.group (1))
1816 m = re.search ('textwidth=([0-9.]+)pt', parameter_string)
1818 textwidth = float (m.group (1))
1820 textwidth = (textwidth - columnsep) / columns
1824 def modify_preamble (chunk):
1825 str = chunk.replacement_text ()
1826 if (re.search (r"\\begin *{document}", str)
1827 and not re.search ("{graphic[sx]", str)):
1828 str = re.sub (r"\\begin{document}",
1829 r"\\usepackage{graphics}" + '\n'
1830 + r"\\begin{document}",
1832 chunk.override_text = str
1837 # TEXINFO: '.texinfo',
1843 class CompileError(Exception):
1846 def snippet_list_checksum (snippets):
1847 return hash (' '.join([l.basename() for l in snippets]))
1849 def write_file_map (lys, name):
1850 snippet_map = file (os.path.join (
1851 global_options.lily_output_dir,
1852 'snippet-map-%d.ly' % snippet_list_checksum (lys)), 'w')
1854 snippet_map.write ("""
1855 #(define version-seen #t)
1856 #(define output-empty-score-list #f)
1857 #(ly:add-file-name-alist '(%s
1859 """ % '\n'.join(['("%s.ly" . "%s")\n' % (ly.basename (), name)
1862 def split_output_files(directory):
1863 """Returns directory entries in DIRECTORY/XX/ , where XX are hex digits.
1865 Return value is a set of strings.
1868 for subdir in glob.glob (os.path.join (directory, '[a-f0-9][a-f0-9]')):
1869 base_subdir = os.path.split (subdir)[1]
1870 sub_files = [os.path.join (base_subdir, name)
1871 for name in os.listdir (subdir)]
1875 def do_process_cmd (chunks, input_name, options):
1876 snippets = [c for c in chunks if isinstance (c, LilypondSnippet)]
1878 output_files = split_output_files (options.lily_output_dir)
1879 outdated = [c for c in snippets if c.is_outdated (options.lily_output_dir, output_files)]
1881 write_file_map (outdated, input_name)
1882 progress (_ ("Writing snippets..."))
1883 for snippet in outdated:
1888 progress (_ ("Processing..."))
1890 process_snippets (options.process_cmd, outdated,
1891 options.format, options.lily_output_dir)
1894 progress (_ ("All snippets are up to date..."))
1896 if options.lily_output_dir != options.output_dir:
1897 output_files = split_output_files (options.lily_output_dir)
1898 for snippet in snippets:
1899 snippet.link_all_output_files (options.lily_output_dir,
1907 # Format guessing data
1916 '.texinfo': TEXINFO,
1921 def guess_format (input_filename):
1923 e = os.path.splitext (input_filename)[1]
1926 format = ext2format[e]
1928 error (_ ("cannot determine format for: %s"
1933 def write_if_updated (file_name, lines):
1935 f = file (file_name)
1937 new_str = ''.join (lines)
1938 if oldstr == new_str:
1939 progress (_ ("%s is up to date.") % file_name)
1942 # this prevents make from always rerunning lilypond-book:
1943 # output file must be touched in order to be up to date
1944 os.utime (file_name, None)
1949 output_dir = os.path.dirname (file_name)
1950 if not os.path.exists (output_dir):
1951 os.makedirs (output_dir)
1953 progress (_ ("Writing `%s'...") % file_name)
1954 file (file_name, 'w').writelines (lines)
1958 def note_input_file (name, inputs=[]):
1959 ## hack: inputs is mutable!
1960 inputs.append (name)
1963 def samefile (f1, f2):
1965 return os.path.samefile (f1, f2)
1966 except AttributeError: # Windoze
1967 f1 = re.sub ("//*", "/", f1)
1968 f2 = re.sub ("//*", "/", f2)
1971 def do_file (input_filename, included=False):
1973 if not input_filename or input_filename == '-':
1974 in_handle = sys.stdin
1975 input_fullname = '<stdin>'
1977 if os.path.exists (input_filename):
1978 input_fullname = input_filename
1979 elif global_options.format == LATEX and ly.search_exe_path ('kpsewhich'):
1980 input_fullname = os.popen ('kpsewhich ' + input_filename).read()[:-1]
1982 input_fullname = find_file (input_filename)
1984 note_input_file (input_fullname)
1985 in_handle = file (input_fullname)
1987 if input_filename == '-':
1988 input_base = 'stdin'
1990 input_base = os.path.splitext (input_filename)[0]
1992 input_base = os.path.basename (
1993 os.path.splitext (input_filename)[0])
1995 # don't complain when global_options.output_dir is existing
1996 if not global_options.output_dir:
1997 global_options.output_dir = os.getcwd()
1999 global_options.output_dir = os.path.abspath(global_options.output_dir)
2001 if not os.path.isdir (global_options.output_dir):
2002 os.mkdir (global_options.output_dir, 0777)
2003 os.chdir (global_options.output_dir)
2005 output_filename = os.path.join(global_options.output_dir,
2006 input_base + format2ext[global_options.format])
2007 if (os.path.exists (input_filename)
2008 and os.path.exists (output_filename)
2009 and samefile (output_filename, input_fullname)):
2011 _ ("Output would overwrite input file; use --output."))
2015 progress (_ ("Reading %s...") % input_fullname)
2016 source = in_handle.read ()
2019 set_default_options (source, default_ly_options, global_options.format)
2022 # FIXME: Containing blocks must be first, see
2023 # find_toplevel_snippets.
2025 'multiline_comment',
2029 'singleline_comment',
2035 progress (_ ("Dissecting..."))
2036 chunks = find_toplevel_snippets (source, global_options.format, snippet_types)
2038 if global_options.format == LATEX:
2040 if (c.is_plain () and
2041 re.search (r"\\begin *{document}", c.replacement_text())):
2046 if global_options.filter_cmd:
2047 write_if_updated (output_filename,
2048 [c.filter_text () for c in chunks])
2049 elif global_options.process_cmd:
2050 do_process_cmd (chunks, input_fullname, global_options)
2051 progress (_ ("Compiling %s...") % output_filename)
2053 write_if_updated (output_filename,
2054 [s.replacement_text ()
2057 def process_include (snippet):
2058 os.chdir (original_dir)
2059 name = snippet.substring ('filename')
2060 progress (_ ("Processing include: %s") % name)
2062 return do_file (name, included=True)
2064 include_chunks = map (process_include,
2065 filter (lambda x: isinstance (x, IncludeSnippet),
2068 return chunks + reduce (lambda x, y: x + y, include_chunks, [])
2070 except CompileError:
2071 os.chdir (original_dir)
2072 progress (_ ("Removing `%s'") % output_filename)
2077 global global_options
2079 opt_parser = get_option_parser()
2080 (global_options, args) = opt_parser.parse_args ()
2081 if global_options.format in ('texi-html', 'texi'):
2082 global_options.format = TEXINFO
2084 global_options.include_path = map (os.path.abspath, global_options.include_path)
2086 if global_options.warranty:
2089 if not args or len (args) > 1:
2090 opt_parser.print_help ()
2096 # FIXME: 85 lines of `main' macramee??
2097 files = do_options ()
2099 basename = os.path.splitext (files[0])[0]
2100 basename = os.path.split (basename)[1]
2102 if not global_options.format:
2103 global_options.format = guess_format (files[0])
2106 if global_options.format in (TEXINFO, HTML, DOCBOOK):
2109 if global_options.process_cmd == '':
2110 global_options.process_cmd = (lilypond_binary
2111 + ' --formats=%s -dbackend=eps ' % formats)
2113 if global_options.process_cmd:
2114 includes = global_options.include_path
2115 if global_options.lily_output_dir:
2116 # This must be first, so lilypond prefers to read .ly
2117 # files in the other lybookdb dir.
2118 includes = [os.path.abspath(global_options.lily_output_dir)] + includes
2119 global_options.process_cmd += ' '.join ([' -I %s' % ly.mkarg (p)
2122 if global_options.format in (TEXINFO, LATEX):
2123 ## prevent PDF from being switched on by default.
2124 global_options.process_cmd += ' --formats=eps '
2125 if global_options.create_pdf:
2126 global_options.process_cmd += "--pdf -dinclude-eps-fonts -dgs-load-fonts "
2128 if global_options.verbose:
2129 global_options.process_cmd += " --verbose "
2131 if global_options.padding_mm:
2132 global_options.process_cmd += " -deps-box-padding=%f " % global_options.padding_mm
2134 global_options.process_cmd += " -dread-file-list -dno-strip-output-dir"
2136 if global_options.lily_output_dir:
2137 global_options.lily_output_dir = os.path.abspath(global_options.lily_output_dir)
2138 if not os.path.isdir (global_options.lily_output_dir):
2139 os.makedirs (global_options.lily_output_dir)
2141 global_options.lily_output_dir = os.path.abspath(global_options.output_dir)
2146 chunks = do_file (files[0])
2147 except CompileError:
2150 inputs = note_input_file ('')
2153 base_file_name = os.path.splitext (os.path.basename (files[0]))[0]
2154 dep_file = os.path.join (global_options.output_dir, base_file_name + '.dep')
2155 final_output_file = os.path.join (global_options.output_dir,
2157 + '.%s' % global_options.format)
2159 os.chdir (original_dir)
2160 file (dep_file, 'w').write ('%s: %s'
2161 % (final_output_file, ' '.join (inputs)))
2163 if __name__ == '__main__':