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