]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond.py
* lily/paper-book.cc (classic_output):
[lilypond.git] / scripts / lilypond.py
1 #!@PYTHON@
2 # lilypond.py -- frontend for lilypond-bin
3 #
4 # source file of the GNU LilyPond music typesetter
5
6 # (c) 1998--2004  Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8 #
9 # Run lilypond-bin, generate printable document
10 # Invokes: lilypond-bin, latex (or pdflatex), dvips, ps2pdf, gs
11
12
13 # This is the third incarnation of ly2dvi, renamed to lilypond.
14 #
15 # Earlier incarnations of ly2dvi were written by
16 # Jeffrey B. Reed<daboys@austin.rr.com> (Python versioan)
17 # Jan Arne Fagertun <Jan.A.Fagertun@@energy.sintef.no> (Bourne shell script)
18 #
19
20 # Note: gettext work best if we use ' for program/docstrings and "
21 #       for gettextable strings.
22 #       USE ''' for docstrings.
23
24
25 '''
26 TODO:
27
28   * cleanup
29
30   * figure out which set of command line options should make lilypond:
31
32       na: create tex only?  
33       na: create latex only? 
34       na: create tex and latex
35       default: create dvi only
36       na: create tex, latex and dvi
37       -P: create dvi and ps
38       -p: create pdf
39       na: * create ps only
40
41      etc.
42
43   * dvi from lilypond .tex output?  This is hairy, because we create dvi
44     from lilypond .tex *and* header output.
45
46 '''
47
48 import operator
49 import stat
50 import string
51 import traceback
52 import glob
53
54 ################################################################
55 # Users of python modules should include this snippet
56 # and customize variables below.
57
58 # We'll suffer this path init stuff as long as we don't install our
59 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
60 # it as we do with teTeX on Red Hat Linux: set some environment var
61 # (PYTHONPATH) in profile)
62
63 # If set, LILYPONDPREFIX must take prevalence
64 # if datadir is not set, we're doing a build and LILYPONDPREFIX
65 import getopt, os, sys
66 datadir = '@local_lilypond_datadir@'
67 if not os.path.isdir (datadir):
68         datadir = '@lilypond_datadir@'
69 if os.environ.has_key ('LILYPONDPREFIX') :
70         datadir = os.environ['LILYPONDPREFIX']
71         while datadir[-1] == os.sep:
72                 datadir= datadir[:-1]
73
74
75 sys.path.insert (0, os.path.join (datadir, 'python'))
76
77 # Customize these
78 #if __name__ == '__main__':
79
80 import lilylib as ly
81 global _;_=ly._
82 global re;re = ly.re
83
84 # lilylib globals
85 program_name = 'lilypond'
86 program_version = '@TOPLEVEL_VERSION@'
87 verbose_p = 0
88 pseudo_filter_p = 0
89 original_dir = os.getcwd ()
90 temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
91 keep_temp_dir_p = 0
92 preview_resolution = 90
93 debug_p = 0
94
95 TEX_PREAMBLE = '%%%% Generated by %(program_name)s (v%(program_version)s)' \
96                % vars ()
97
98 ## FIXME
99 ## do -P or -p by default?
100 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
101 help_summary = _ ("Run LilyPond, generate printable document.")
102 copyright = ('Han-Wen Nienhuys <hanwen@cs.uu.nl',
103              'Jan Nieuwenhuizen <janneke@gnu.org')
104
105 option_definitions = [
106         ('', 'd', 'dependencies',
107          _ ("write Makefile dependencies for every input file")),
108         ('', 'h', 'help', _ ("print this help")),
109         ('', '', 'debug', _ ("print even more output")),
110         (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
111         ('','', 'html', _("make HTML file with links to all output")),
112         (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
113         ('', 'k', 'keep',
114          _ ("keep all output, output to directory %s.dir") % program_name),
115         ('', '', 'no-lily', _ ("don't run LilyPond")),
116         ('', 'm', 'no-paper', _ ("produce MIDI output only")),
117         (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
118         (_ ('RES'), '', 'preview-resolution',
119          _ ("set the resolution of the preview to RES")),
120         ('', '', 'no-pdf', _ ("do not generate PDF output")),
121         ('', '', 'no-ps', _ ("do not generate PostScript output")),
122         ('', 'p', 'pdf', _ ("generate PDF output")),
123         ('', 'P', 'postscript', _ ("generate PostScript output")),
124         ('', '', 'pdftex', _ ("use pdflatex to generate PDF output")),
125         ('', '', 'png', _("generate PNG page images")),
126         ('', '', 'preview', _ ("make a picture of the first system")),
127         ('', '', 'psgz', _ ("generate PS.GZ")),
128         ('', 's', 'safe-mode', _ ("run in safe-mode")),
129         (_ ("KEY=VAL"), 'S', 'set', _ ("change global setting KEY to VAL")),
130         ('', 'V', 'verbose', _ ("be verbose")),
131         ('', 'v', 'version', _ ("print version number")),
132         ('', 'w', 'warranty', _ ("show warranty and copyright")),
133         ]
134
135 # other globals
136 safe_mode_p = 0
137 preview_p = 0
138 page_images_p = 0
139 lilypond_error_p = 0
140 html_p = 0
141
142 # Pdftex support
143 pdftex_p = 0
144 latex_cmd = 'latex'
145
146
147 tex_extension = '.tex'  ## yuk.
148
149 #lilypond_binary = 'valgrind --suppressions=%(home)s/usr/src/guile-1.6.supp --num-callers=10 %(home)s/usr/src/lilypond/lily/out/lilypond '% { 'home' : '/home/hanwen' }
150
151 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
152
153 # only use installed binary  when we're installed too.
154 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
155         lilypond_binary = 'lilypond-bin'
156
157
158 ## Init to empty; values here take precedence over values in the file
159 extra_init = {
160         'language' : [],
161         'latexheaders' : [],
162         'latexoptions' : [],
163         'latexpackages' :  [],
164         'orientation' : [],
165         'papersize' : [],
166         'unit' : ['pt'],
167 }
168
169 header_fields = extra_init.keys ()
170
171 include_path = ['.']
172 lily_p = 1
173 paper_p = 1
174
175 output_name = ''
176
177 # Output formats that lilypond should create
178 targets = ['DVI', 'LATEX', 'MIDI', 'TEX', 'PDF', 'PS']
179
180 track_dependencies_p = 0
181 dependency_files = []
182
183 #what a name.
184 def set_setting (dict, key, val):
185         try:
186                 val = string.atoi (val)
187         except ValueError:
188                 #ly.warning (_ ("invalid value: %s") % `val`)
189                 pass
190
191         if type(val) == type ('hoi'):
192                 try:
193                         val = string.atof (val)
194                 except ValueError:
195                         #ly.warning (_ ("invalid value: %s") % `val`)
196                         pass
197
198         try:
199                 dict[key].append (val)
200         except KeyError:
201                 ly.warning (_ ("no such setting: `%s'") % `key`)
202                 dict[key] = [val]
203
204
205 def escape_shell (x):
206         return re.sub ("(\s|[`'\"\\\\])", r'\\\1',x)
207
208 def run_lilypond (files, dep_prefix):
209         
210         def make_include_option (x):
211                 return '-I %s' %   escape_shell (x)
212         
213         opts = ' ' + string.join (map (make_include_option, include_path))
214         
215         ## UGHr
216         if pseudo_filter_p:
217                 opts += ' --output=lelie'
218         if paper_p:
219                 opts += ' ' + string.join (map (lambda x : '--header=' + x,
220                                                 header_fields))
221         else:
222                 opts = opts + ' --no-paper'
223         if pdftex_p:
224                 opts = opts + ' -f pdftex'              
225         if safe_mode_p:
226                 opts = opts + ' --safe-mode'
227         if track_dependencies_p:
228                 opts = opts + " --dependencies"
229                 if dep_prefix:
230                         opts = opts + ' --dep-prefix=%s' % dep_prefix
231
232         fs = string.join (map (escape_shell, files))
233
234         global verbose_p
235         if verbose_p:
236                 opts = opts + ' --verbose'
237
238         if debug_p:
239                 ly.print_environment ()
240                 
241         cmd = string.join ((lilypond_binary, opts, fs))
242         status = ly.system (cmd, ignore_error = 1, progress_p = 1)
243         signal = 0x0f & status
244         exit_status = status >> 8
245
246         # 2 == user interrupt.
247         if signal and signal != 2:
248                 sys.stderr.write ('\n\n')
249                 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
250                 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
251                 ly.exit (status)
252                         
253         if status:
254                 sys.stderr.write ('\n')
255                 if len (files) == 1:
256                         ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
257                         ly.exit (status)
258                 else:
259                         ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
260                         ly.error (_ ("Continuing..."))
261                         global lilypond_error_p
262                         lilypond_error_p = 1
263                 
264
265 def analyse_lilypond_output (filename, extra):
266         
267         # urg
268         '''Grep FILENAME for interesting stuff, and
269         put relevant info into EXTRA.'''
270         filename = filename + tex_extension
271         ly.progress (_ ("Analyzing %s...") % filename)
272         s = open (filename).read ()
273
274         # search only the first 10k
275         s = s[:10240]
276         for x in header_fields:
277                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
278                 if m:
279                         set_setting (extra, x, m.group (1))
280         ly.progress ('\n')
281
282 def find_tex_files_for_base (base, extra):
283
284         if os.path.exists (base  +'.dep'):
285                 dependency_files.append (base + '.dep')
286
287         for f in header_fields:
288                 fn =base + '.' + f
289                 if os.path.exists (fn):
290                         extra[f].append (open (fn).read ())
291         
292         return (base + tex_extension, {})
293          
294
295 def find_tex_files (files, extra):
296         '''
297         Find all .tex files whose prefixes start with some name in FILES. 
298
299         '''
300         
301         tfiles = []
302         
303         for f in files:
304                 x = 0
305                 while 1:
306                         fname = os.path.basename (f)
307                         fname = ly.strip_extension (fname, '.ly')
308                         if x:
309                                 fname = fname + '-%d' % x
310
311                         if os.path.exists (fname + tex_extension):
312                                 tfiles.append (find_tex_files_for_base (fname, extra))
313                                 analyse_lilypond_output (fname, extra)
314                         else:
315                                 break
316
317                         x = x + 1
318         if not x:
319                 fstr = string.join (files, ', ')
320                 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
321         return tfiles
322
323 def one_latex_definition (defn, first):
324         s = '\n'
325         for (k, v) in defn[1].items ():
326                 val = open (v).read ()
327                 if (string.strip (val)):
328                         s += r'''\def\lilypond%s{%s}''' % (k, val)
329                 else:
330                         s += r'''\let\lilypond%s\relax''' % k
331                 s += '\n'
332
333         s += '%%PREVIEW%%\n'
334         s += '\\input %s\n' % defn[0]
335         return s
336
337 def global_latex_preamble (extra):
338         '''construct preamble from EXTRA,'''
339         
340         s = TEX_PREAMBLE
341         s += '\n'
342
343         options = ''
344
345         if extra['latexoptions']:
346                 options = options + ',' + extra['latexoptions'][-1]
347
348         s += '\\documentclass[%s]{article}\n' % options
349
350         if safe_mode_p:
351                 s += '\\nofiles\n'
352
353         if extra['language']:
354                 s += r'\usepackage[%s]{babel}' \
355                     % extra['language'][-1] + '\n'
356
357         s += '\\usepackage{%s}\n' \
358                 % string.join (extra['latexpackages'], ',')
359
360         if extra['latexheaders']:
361                 s += '\\include{%s}\n' \
362                         % string.join (extra['latexheaders'], '}\n\\include{')
363
364         unit = extra['unit'][-1]
365
366         # FIXME, must (only) from lilypond-bin
367         s += r'''
368 \usepackage[latin1]{inputenc}
369 \pagestyle{empty}
370 %%PREVIEW%%
371 %% Nullify [La]TeX page layout settings, page layout by LilyPond.
372 \pagestyle{empty}
373 \topmargin-1in
374 \headheight0pt\headsep0pt
375 \oddsidemargin-1in
376 \evensidemargin\oddsidemargin
377 \parindent 0pt
378 '''
379         return s
380
381         
382 def global_latex_definition (tfiles, extra):
383         '''construct preamble from EXTRA, dump Latex stuff for each
384 lily output file in TFILES after that, and return the Latex file constructed.  '''
385         s = global_latex_preamble (extra) + '\\begin{document}\n'
386         s += '\\parindent 0pt'
387
388         first = 1
389         for t in tfiles:
390                 s += one_latex_definition (t, first)
391                 first = 0
392         s += '\\end{document}\n'
393         return s
394
395 def run_latex (files, outbase, extra):
396         '''Construct latex file, for FILES and EXTRA, dump it into
397 OUTBASE.latex.  Run LaTeX on it.
398 '''
399
400         latex_fn = outbase + '.latex'
401         
402         wfs = find_tex_files (files, extra)
403         s = global_latex_definition (wfs, extra)
404
405         f = open (latex_fn, 'w')
406         f.write (s)
407         f.close ()
408
409         cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
410         
411         # Ugh.  (La)TeX writes progress and error messages on stdout
412         # Redirect to stderr
413         cmd = '(( %s  >&2 ) >&- )' % cmd
414         status = ly.system (cmd, ignore_error = 1)
415         signal = 0xf & status
416         exit_status = status >> 8
417
418         if exit_status:
419
420                 logstr = ''
421                 try:
422                         logstr = open (outbase + '.log').read ()
423                         m = re.search ("\n!", logstr)
424                         start = m.start (0)
425                         logstr = logstr[start:start+200]
426                 except:
427                         pass
428                         
429                 ly.error (_ ("LaTeX failed on the output file."))
430                 ly.error (_ ("The error log is as follows:"))
431                 sys.stderr.write (logstr + '\n')
432                 ly.exit (1)
433         
434         if preview_p:
435                 # make a preview by rendering only the 1st line
436                 # of each score
437                 for score in find_tex_files (files, extra):
438                         preview_base = ly.strip_extension (score[0], '.tex')
439                         preview_fn = preview_base + '.preview.tex'
440                         s = global_latex_definition ((score,), extra)
441                         s = re.sub ('%%PREVIEW%%',
442                                     r'''\def\interscoreline{\endinput}''', s)
443                         f = open (preview_fn, 'w')
444                         f.write (s)
445                         f.close ()
446                         cmd = '%s \\\\nonstopmode \\\\input %s' \
447                               % (latex_cmd, preview_fn)
448                         ly.system (cmd)
449
450
451 def run_dvips (outbase, extra):
452         '''Run dvips using the correct options taken from EXTRA,
453 leaving a PS file in OUTBASE.ps
454 '''
455         #FIXME: papersize, orientation must come from lilypond-bin
456         opts = ' -t%s' % extra['papersize'][0]
457         if extra['orientation'] and extra['orientation'][0] == 'landscape':
458                 opts = opts + ' -tlandscape'
459
460         if 'PDF' in targets:
461                 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
462
463                 pfa_file  = None
464                 if where:
465                         try: 
466                                 pfa_file = open (where, 'r')
467                         except IOError:
468                                 pass
469
470                 if pfa_file:
471                         opts = opts + ' -Ppdf -G0 -u +lilypond.map'
472                 else:
473                         ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
474 Using bitmap fonts instead. This will look bad.'''))
475
476         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
477         ly.system (cmd)
478
479         if preview_p:
480                 for score in find_tex_files (files, extra):
481                         preview_base = ly.strip_extension (score[0], '.tex')
482                         cmd = 'dvips -E -Ppdf -u+lilypond.map -o%s %s' \
483                               % (preview_base + '.preview.ps',
484                                  preview_base + '.preview.dvi')
485                         ly.system (cmd)
486
487         if 'PDF' in targets:
488                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
489                 ly.system (cmd)
490                 
491 def generate_dependency_file (depfile, outname):
492         df = open (depfile, 'w')
493         df.write (outname + ':' )
494         
495         for d in dependency_files:
496                 s = open (d).read ()
497                 s = re.sub ('#[^\n]*\n', '', s)
498                 s = re.sub (r'\\\n', ' ', s)
499                 m = re.search ('.*:(.*)\n', s)
500
501                 # ugh. Different targets?
502                 if m:
503                         df.write ( m.group (1)  + ' ' )
504
505         df.write ('\n')
506         df.close ();
507
508 def find_file_in_path (path, name):
509         for d in string.split (path, os.pathsep):
510                 if not d:
511                         d = original_dir
512                 if name in os.listdir (d):
513                         return os.path.join (d, name)
514
515 def find_pfa_fonts (name):
516         PS = '%!PS-Adobe'
517         s = open (name).read ()
518         if s[:len (PS)] != PS:
519                 # no ps header?
520                 ly.error (_ ("not a PostScript file: `%s\'" % name))
521                 ly.exit (1)
522         here = 0
523         m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
524         pfa = []
525         while m:
526                 here = here + m.end (0)
527                 pfa.append (m.group (1))
528                 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
529         return pfa
530
531
532 def make_html_menu_file (html_file, files_found):
533         exts = {
534                 'pdf' : "Print (PDF, %s)",
535                 'ps.gz' : "Print (gzipped PostScript, %s)",
536                 'png' : "View (PNG, %s)",
537                 'midi' : "Listen (MIDI, %s)",
538                 'ly' : "View source code (%s)", 
539                 }
540         html_str = ''
541
542         pages = filter (lambda x : re.search ('page[0-9]+.png',  x),
543                         files_found)
544         rest =  filter (lambda x : not re.search ('page[0-9]+.png',  x),
545                         files_found)
546
547         preview = filter (lambda x: re.search ('.png$', x), rest)
548         if preview:
549                 html_str = '<img src="%s">' % preview[0]
550
551         for p in pages:
552                 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
553                 page = page % 'unknown size'
554                 
555                 html_str += '<li><a href="%s">%s</a>' % (p, page)
556                 
557                 
558         for e in ['pdf', 'ps.gz', 'midi', 'ly']:
559                 fs = filter (lambda x: re.search ('.%s$' % e, x), rest)
560                 for f in fs:
561                         entry = exts[e] % 'unknown size' # todo
562                         html_str += '<li><a href="%s">%s</a>\n\n' % (f, entry)
563
564         html_str += "\n\n</li>"
565         ly.progress (_("Writing HTML menu `%s'") % html_file)
566         ly.progress ('\n')
567         open (html_file, 'w').write (html_str)
568         
569 ################################################################
570 ## MAIN
571 ################################################################
572
573 (sh, long) = ly.getopt_args (option_definitions)
574 try:
575         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
576 except getopt.error, s:
577         sys.stderr.write ('\n')
578         ly.error (_ ("getopt says: `%s\'" % s))
579         sys.stderr.write ('\n')
580         ly.help ()
581         ly.exit (2)
582         
583 for opt in options:
584         o = opt[0]
585         a = opt[1]
586
587         if 0:
588                 pass
589         elif o == '--help' or o == '-h':
590                 ly.help ()
591                 sys.exit (0)
592         elif o == '--find-pfa' or o == '-f':
593                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
594                 files = map (lambda x:
595                              find_file_in_path (os.environ['GS_FONTPATH'], x),
596                              fonts)
597                 print string.join (files, ' ')
598                 sys.exit (0)
599         elif o == '--include' or o == '-I':
600                 include_path.append (a)
601         elif o == '--postscript' or o == '-P':
602                 if 'PDF' in targets:
603                         targets.remove ('PDF')
604                 if 'PS' not in targets:
605                         targets.append ('PS')
606         elif o == '--pdf' or o == '-p':
607                 if 'PDF' not in targets:
608                         targets.append ('PDF')
609         elif o == '--no-pdf':
610                 if 'PDF' in targets:
611                         targets.remove ('PDF')
612         elif o == '--no-ps':
613                 if 'PS' in targets:
614                         targets.remove ('PS')
615                 if 'PDF' in targets:
616                         targets.remove ('PDF')
617         elif o == '--keep' or o == '-k':
618                 keep_temp_dir_p = 1
619         elif o == '--debug':
620                 verbose_p = 1
621                 debug_p = 1 
622         elif o == '--no-lily':
623                 lily_p = 0
624         elif o == '--preview':
625                 preview_p = 1
626                 if 'PNG' not in targets:
627                         targets.append ('PNG')
628         elif o == '--preview-resolution':
629                 preview_resolution = string.atoi (a)
630         elif o == '--no-paper' or o == '-m':
631                 targets = ['MIDI'] 
632                 paper_p = 0
633         elif o == '--output' or o == '-o':
634                 output_name = a
635         elif o == '--safe-mode' or o == '-s':
636                 safe_mode_p = 1
637         elif o == '--set' or o == '-S':
638                 ss = string.split (a, '=')
639                 set_setting (extra_init, ss[0], ss[1])
640         elif o == '--dependencies' or o == '-d':
641                 track_dependencies_p = 1
642         elif o == '--verbose' or o == '-V':
643                 verbose_p = 1
644         elif o == '--version' or o == '-v':
645                 ly.identify (sys.stdout)
646                 sys.exit (0)
647         elif o == '--pdftex':
648                 latex_cmd = 'pdflatex'
649                 targets.remove ('DVI')
650                 targets.append ('PDFTEX')
651                 pdftex_p = 1
652                 tex_extension = '.pdftex'
653         elif o == '--warranty' or o == '-w':
654                 status = os.system ('%s -w' % lilypond_binary)
655                 if status:
656                         ly.warranty ()
657                 sys.exit (0)
658         elif o == '--html':
659                 html_p = 1
660         elif o == '--png':
661                 page_images_p = 1
662                 if 'PNG' not in targets:
663                         targets.append ('PNG')
664         else:
665                 unimplemented_option () # signal programming error
666
667 # Don't convert input files to abspath, rather prepend '.' to include
668 # path.
669 include_path.insert (0, '.')
670
671 # As a neat trick, add directory part of first input file
672 # to include path.  That way you can do without the clumsy -I in:
673
674 #    lilypond -I foe/bar/baz foo/bar/baz/baz.ly
675 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
676         include_path.append (os.path.dirname (files[0]))
677         
678 include_path = map (ly.abspath, include_path)
679
680 if files and (files[0] == '-' or output_name == '-'):
681         if len (files) == 1:
682                 pseudo_filter_p = 1
683                 output_name = 'lelie'
684                 if verbose_p:
685                         ly.progress (_ ("pseudo filter") + '\n')
686         else:
687                 ly.help ()
688                 ly.error (_ ("pseudo filter only for single input file"))
689                 ly.exit (2)
690                 
691 if not files:
692         ly.help ()
693         ly.error (_ ("no files specified on command line"))
694         ly.exit (2)
695
696 if 1:
697         ly.identify (sys.stderr)
698         ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
699         
700         original_output = output_name
701         
702         # Ugh, maybe make a setup () function
703         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
704
705         # hmmm. Wish I'd 've written comments when I wrote this.
706         # now it looks complicated.
707         
708         (outdir, outbase) = ('','')
709         if not output_name:
710                 outbase = os.path.basename (files[0])
711                 outdir = ly.abspath ('.')
712         elif output_name[-1] == os.sep:
713                 outdir = ly.abspath (output_name)
714                 outbase = os.path.basename (files[0])
715         else:
716                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
717
718         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
719                 output_name = ly.strip_extension (output_name, i)
720                 outbase = ly.strip_extension (outbase, i)
721
722         for i in files[:] + [output_name]:
723                 b = os.path.basename (i)
724                 if string.find (b, ' ') >= 0:
725                         ly.error (_ ("filename should not contain spaces: `%s'") % b)
726                         ly.exit (1)
727                         
728         if os.path.dirname (output_name) != '.':
729                 dep_prefix = os.path.dirname (output_name)
730         else:
731                 dep_prefix = 0
732
733         reldir = os.path.dirname (output_name)
734         if outdir != '.' and (track_dependencies_p or targets):
735                 ly.mkdir_p (outdir, 0777)
736
737         tmpdir = ly.setup_temp ()
738         ly.setup_environment ()
739         if safe_mode_p:
740                 os.environ['openout_any'] = 'p'
741
742         # to be sure, add tmpdir *in front* of inclusion path.
743         #os.environ['TEXINPUTS'] =  tmpdir + ':' + os.environ['TEXINPUTS']
744         os.chdir (tmpdir)
745
746         # We catch all exceptions, because we need to do stuff at exit:
747         #   * copy any successfully generated stuff from tempdir and
748         #     notify user of that
749         #   * cleanout tempdir
750         if lily_p:
751                 try:
752                         run_lilypond (files, dep_prefix)
753                 except:
754                         ### ARGH. This also catches python programming errors.
755                         ### this should only catch lilypond nonzero exit  status
756                         ### --hwn
757
758                         
759                         # TODO: friendly message about LilyPond setup/failing?
760                         #
761                         targets = []
762                         if verbose_p:
763                                 traceback.print_exc ()
764                         else:
765                                 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
766                                 
767         # Our LilyPond pseudo filter always outputs to 'lelie'
768         # have subsequent stages and use 'lelie' output.
769         if pseudo_filter_p:
770                 files[0] = 'lelie'
771
772         if 'PS.GZ'  in targets:
773                 targets.append ('PS')
774                 
775         if 'PNG' in targets and 'PS' not in targets:
776                 targets.append ('PS')
777         if 'PS' in targets and 'DVI' not in targets:
778                 targets.append('DVI')
779
780         if 'DVI' in targets:
781                 try:
782                         run_latex (files, outbase, extra_init)
783                         # unless: add --tex, or --latex?
784                         targets.remove ('TEX')
785                         targets.remove('LATEX')
786                 except:
787                         # TODO: friendly message about TeX/LaTeX setup,
788                         # trying to run tex/latex by hand
789                         if 'DVI' in targets:
790                                 targets.remove ('DVI')
791                         if 'PS' in targets:
792                                 targets.remove ('PS')
793                         if verbose_p:
794                                 traceback.print_exc ()
795
796         if 'PS' in targets:
797                 try:
798                         run_dvips (outbase, extra_init)
799                         
800                 except: 
801                         if 'PS' in targets:
802                                 targets.remove ('PS')
803                         if verbose_p:
804                                 traceback.print_exc ()
805                         else:
806                                 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
807
808         if preview_p:
809                 for score in find_tex_files (files, extra_init):
810                         preview_base = ly.strip_extension (score[0], '.tex')
811                         ly.make_ps_images (preview_base + '.preview.ps',
812                                            resolution=preview_resolution
813                                            )
814
815         if 'PDFTEX' in targets:
816                 try:
817                         run_latex (files, outbase, extra_init)
818                         # unless: add --tex, or --latex?
819                         targets.remove ('TEX')
820                         targets.remove ('LATEX')
821                         targets.remove ('PDFTEX')
822                         if 'PDF' not in targets:
823                                 targets.append('PDF')
824                 except:
825                         # TODO: friendly message about TeX/LaTeX setup,
826                         # trying to run tex/latex by hand
827                         if 'PDFTEX' in targets:
828                                 targets.remove ('PDFTEX')
829                         if 'PDF' in targets:
830                                 targets.remove ('PDF')
831                         if 'PS' in targets:
832                                 targets.remove ('PS')
833                         if verbose_p:
834                                 traceback.print_exc ()
835                         else:
836                                 ly.warning (_("Running LaTeX failed. Rerun with --verbose for a trace."))
837                                 
838         if page_images_p:
839                 ly.make_ps_images (outbase + '.ps' ,
840                                    resolution = preview_resolution
841                                    )
842
843         # add DEP to targets?
844         if track_dependencies_p:
845                 depfile = os.path.join (outdir, outbase + '.dep')
846                 generate_dependency_file (depfile, depfile)
847                 if os.path.isfile (depfile):
848                         ly.progress (_ ("dependencies output to `%s'...") %
849                                      depfile)
850                         ly.progress ('\n')
851
852         if pseudo_filter_p:
853                 main_target = 0
854                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
855                         if i in targets:
856                                 main_target = i
857                                 break
858
859                 ly.progress (_ ("%s output to <stdout>...") % i)
860                 outname = outbase + '.' + string.lower (main_target)
861                 if os.path.isfile (outname):
862                         sys.stdout.write (open (outname).read ())
863                 elif verbose_p:
864                         ly.warning (_ ("can't find file: `%s'") % outname)
865                 targets = []
866                 ly.progress ('\n')
867                 
868         if 'PS.GZ' in targets:
869                 ly.system ("gzip *.ps") 
870                 targets.remove ('PS')
871
872         # Hmm, if this were a function, we could call it the except: clauses
873         files_found = []
874         for i in targets:
875                 ext = string.lower (i)
876
877                 pattern = '%s.%s' % (outbase, ext)
878                 if i == 'PNG':
879                         pattern  = '*.png' 
880                 ls = glob.glob (pattern)
881                 files_found += ls 
882                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
883
884
885                 if ls:
886                         names = string.join (map (lambda x: "`%s'" % x, ls))
887                         ly.progress (_ ("%s output to %s...") % (i, names))
888                         ly.progress ('\n')
889                 elif verbose_p:
890                         ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
891
892         if html_p:
893                 make_html_menu_file (os.path.join (outdir, outbase + ".html"),
894                                      files_found)
895
896         os.chdir (original_dir)
897         ly.cleanup_temp ()
898
899         sys.exit (lilypond_error_p)