]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
* scripts/ly2dvi.py: Add paper sizes.
[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         'letter' : 'letterpaper', 
359         'a3' : 'a3paper',
360         'a4' : 'a4paper',
361         'a5' : 'a5paper',
362         'a6' : 'a6paper',
363 }
364
365 #TODO: should set textheight (enlarge) depending on papersize. 
366 def global_latex_preamble (extra):
367         '''construct preamble from EXTRA,'''
368         s = ""
369         s = s + '% generation tag\n'
370
371         options = ''
372
373
374         if extra['papersize']:
375                 try:
376                         options = ly_paper_to_latexpaper[extra['papersize'][0]]
377                 except KeyError:
378                         ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
379                         pass
380
381         if extra['latexoptions']:
382                 options = options + ',' + extra['latexoptions'][-1]
383
384         s = s + '\\documentclass[%s]{article}\n' % options
385
386         if extra['language']:
387                 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
388
389
390         s = s + '\\usepackage{%s}\n' \
391                 % string.join (extra['latexpackages'], ',')
392
393         if extra['latexheaders']:
394                 s = s + '\\include{%s}\n' \
395                         % string.join (extra['latexheaders'], '}\n\\include{')
396
397         unit = extra['unit'][-1]
398
399         textheight = ''
400         if extra['textheight']:
401                 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
402
403         orientation = 'portrait'
404         if extra['orientation']:
405                 orientation = extra['orientation'][0]
406
407         # set sane geometry width (a4-width) for linewidth = -1.
408         maxlw = max (extra['linewidth'] + [-1])
409         if maxlw < 0:
410                 # who the hell is 597 ?
411                 linewidth = '597pt'
412         else:
413                 linewidth = '%d%s' % (maxlw, unit)
414         s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
415
416         if extra['latexoptions']:
417                 s = s + '\geometry{twosideshift=4mm}\n'
418
419         s = s + r'''
420 \usepackage[latin1]{inputenc}
421 \input{titledefs}
422 '''
423         
424         if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
425                 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
426                 s = s + '\\pagestyle{plain}\n'
427         else:
428                 s = s + '\\pagestyle{empty}\n'
429
430
431         return s
432
433         
434 def global_latex_definition (tfiles, extra):
435         '''construct preamble from EXTRA, dump Latex stuff for each
436 lily output file in TFILES after that, and return the Latex file constructed.  '''
437
438         
439         s = global_latex_preamble (extra) + '\\begin{document}\n'
440         s = s + '\\parindent 0pt\n'
441         s = s + '\\thispagestyle{firstpage}\n'
442
443         first = 1
444         for t in tfiles:
445                 s = s + one_latex_definition (t, first)
446                 first = 0
447
448
449         s = s + '\\thispagestyle{lastpage}\n'
450         s = s + '\\end{document}'
451
452         return s
453
454 def run_latex (files, outbase, extra):
455
456         '''Construct latex file, for FILES and EXTRA, dump it into
457 OUTBASE.latex. Run LaTeX on it.
458
459 RETURN VALUE
460
461 None
462         '''
463
464         latex_fn = outbase + '.latex'
465         
466         wfs = find_tex_files (files, extra)
467         s = global_latex_definition (wfs, extra)
468
469         f = open (latex_fn, 'w')
470         f.write (s)
471         f.close ()
472
473         cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
474         # Ugh.  (La)TeX writes progress and error messages on stdout
475         # Redirect to stderr
476         cmd += ' 1>/dev/stderr'
477         status = ly.system (cmd, ignore_error = 1)
478         signal = 0xf & status
479         exit_status = status >> 8
480
481         if exit_status:
482
483                 logstr = ''
484                 try:
485                         logstr = open (outbase + '.log').read ()
486                         m = re.search ("\n!", logstr)
487                         start = m.start (0)
488                         logstr = logstr[start:start+200]
489                 except:
490                         pass
491                         
492                 ly.error (_ ("LaTeX failed on the output file."))
493                 ly.error (_ ("The error log is as follows:"))
494                 sys.stderr.write (logstr + '\n')
495                 ly.exit (1)
496         
497         if preview_p:
498                 # make a preview by rendering only the 1st line.
499                 preview_fn = outbase + '.preview.tex'
500                 f = open (preview_fn, 'w')
501                 f.write (r'''
502 %s
503 \input lilyponddefs
504 \pagestyle{empty}
505 \begin{document}
506 \def\interscoreline{\endinput}
507 \input %s
508 \end{document}
509 ''' % (global_latex_preamble (extra), outbase))
510
511                 f.close()
512                 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
513                 ly.system (cmd)
514         
515
516 def run_dvips (outbase, extra):
517
518
519         '''Run dvips using the correct options taken from EXTRA,
520 leaving a PS file in OUTBASE.ps
521
522 RETURN VALUE
523
524 None.
525 '''
526         opts = ''
527         if extra['papersize']:
528                 opts = opts + ' -t%s' % extra['papersize'][0]
529
530         if extra['orientation'] and extra['orientation'][0] == 'landscape':
531                 opts = opts + ' -tlandscape'
532
533         if 'PDF' in targets:
534                 opts = opts + ' -Ppdf -G0 -u lilypond.map'
535                 
536         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
537         ly.system (cmd)
538
539         if preview_p:
540                 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')         
541                 ly.system (cmd)
542
543         if 'PDF' in targets:
544                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
545                 ly.system (cmd)
546                 
547 def generate_dependency_file (depfile, outname):
548         df = open (depfile, 'w')
549         df.write (outname + ':' )
550         
551         for d in dependency_files:
552                 s = open (d).read ()
553                 s = re.sub ('#[^\n]*\n', '', s)
554                 s = re.sub (r'\\\n', ' ', s)
555                 m = re.search ('.*:(.*)\n', s)
556
557                 # ugh. Different targets?
558                 if m:
559                         df.write ( m.group (1)  + ' ' )
560
561         df.write ('\n')
562         df.close ();
563
564 def find_file_in_path (path, name):
565         for d in string.split (path, os.pathsep):
566                 if name in os.listdir (d):
567                         return os.path.join (d, name)
568
569 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
570 # in future too.
571 PS = '%!PS-Adobe'
572 def find_pfa_fonts (name):
573         s = open (name).read ()
574         if s[:len (PS)] != PS:
575                 # no ps header?
576                 ly.error (_ ("not a PostScript file: `%s\'" % name))
577                 ly.exit (1)
578         here = 0
579         m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
580         pfa = []
581         while m:
582                 here = m.end (1)
583                 pfa.append (m.group (1))
584                 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
585         return pfa
586
587         
588 (sh, long) = ly.getopt_args (option_definitions)
589 try:
590         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
591 except getopt.error, s:
592         sys.stderr.write ('\n')
593         ly.error (_ ("getopt says: `%s\'" % s))
594         sys.stderr.write ('\n')
595         ly.help ()
596         ly.exit (2)
597         
598 for opt in options:
599         o = opt[0]
600         a = opt[1]
601
602         if 0:
603                 pass
604         elif o == '--help' or o == '-h':
605                 ly.help ()
606                 sys.exit (0)
607         elif o == '--find-pfa' or o == '-f':
608                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
609                 files = map (lambda x:
610                              find_file_in_path (os.environ['GS_FONTPATH'], x),
611                              fonts)
612                 print string.join (files, ' ')
613                 sys.exit (0)
614         elif o == '--include' or o == '-I':
615                 include_path.append (a)
616         elif o == '--postscript' or o == '-P':
617                 targets.append ('PS')
618         elif o == '--pdf' or o == '-p':
619                 targets.append ('PS')
620                 targets.append ('PDF')
621         elif o == '--keep' or o == '-k':
622                 keep_temp_dir_p = 1
623         elif o == '--no-lily':
624                 lily_p = 0
625         elif o == '--preview':
626                 preview_p = 1
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 == '--set' or o == '-s':
636                 ss = string.split (a, '=')
637                 set_setting (extra_init, ss[0], ss[1])
638         elif o == '--dependencies' or o == '-d':
639                 track_dependencies_p = 1
640         elif o == '--verbose' or o == '-V':
641                 verbose_p = 1
642         elif o == '--version' or o == '-v':
643                 ly.identify (sys.stdout)
644                 sys.exit (0)
645         elif o == '--pdftex':
646                 latex_cmd = 'pdflatex'
647                 targets.remove('DVI')
648                 targets.append('PDFTEX')
649                 pdftex_p = 1
650                 tex_extension = '.pdftex'
651         elif o == '--warranty' or o == '-w':
652                 status = os.system ('lilypond -w')
653                 if status:
654                         ly.warranty ()
655                 sys.exit (0)
656
657 # Don't convert input files to abspath, rather prepend '.' to include
658 # path.
659 include_path.insert (0, '.')
660
661 # As a neat trick, add directory part of first input file
662 # to include path.  That way you can do without the clumsy -I in:
663
664 #    ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
665 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
666         include_path.append (os.path.dirname (files[0]))
667         
668 include_path = map (ly.abspath, include_path)
669
670 if files and (files[0] == '-' or output_name == '-'):
671         if len (files) == 1:
672                 pseudo_filter_p = 1
673                 output_name = 'lelie'
674                 if verbose_p:
675                         ly.progress (_ ("pseudo filter") + '\n')
676         else:
677                 ly.help ()
678                 ly.error (_ ("pseudo filter only for single input file"))
679                 ly.exit (2)
680                 
681 if not files:
682         ly.help ()
683         ly.error (_ ("no files specified on command line"))
684         ly.exit (2)
685
686 if 1:
687         ly.identify (sys.stderr)
688         original_output = output_name
689         
690         # Ugh, maybe make a setup () function
691         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
692
693         # hmmm. Wish I'd 've written comments when I wrote this.
694         # now it looks complicated.
695         
696         (outdir, outbase) = ('','')
697         if not output_name:
698                 outbase = os.path.basename (files[0])
699                 outdir = ly.abspath ('.')
700         elif output_name[-1] == os.sep:
701                 outdir = ly.abspath (output_name)
702                 outbase = os.path.basename (files[0])
703         else:
704                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
705
706         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
707                 output_name = ly.strip_extension (output_name, i)
708                 outbase = ly.strip_extension (outbase, i)
709
710         for i in files[:] + [output_name]:
711                 if string.find (i, ' ') >= 0:
712                         ly.error (_ ("filename should not contain spaces: `%s'") %
713                                i)
714                         ly.exit (1)
715                         
716         if os.path.dirname (output_name) != '.':
717                 dep_prefix = os.path.dirname (output_name)
718         else:
719                 dep_prefix = 0
720
721         reldir = os.path.dirname (output_name)
722         if outdir != '.' and (track_dependencies_p or targets):
723                 ly.mkdir_p (outdir, 0777)
724
725         tmpdir = ly.setup_temp ()
726         ly.setup_environment ()
727
728         # to be sure, add tmpdir *in front* of inclusion path.
729         #os.environ['TEXINPUTS'] =  tmpdir + ':' + os.environ['TEXINPUTS']
730         os.chdir (tmpdir)
731
732         # We catch all exceptions, because we need to do stuff at exit:
733         #   * copy any successfully generated stuff from tempdir and
734         #     notify user of that
735         #   * cleanout tempdir
736         if lily_p:
737                 try:
738                         run_lilypond (files, dep_prefix)
739                 except:
740                         # TODO: friendly message about LilyPond setup/failing?
741                         #
742                         # TODO: lilypond should fail with different
743                         # error codes for:
744                         #   - guile setup/startup failure
745                         #   - font setup failure
746                         #   - init.ly setup failure
747                         #   - parse error in .ly
748                         #   - unexpected: assert/core dump
749                         targets = []
750                         if verbose_p:
751                                 traceback.print_exc ()
752
753         # Our LilyPond pseudo filter always outputs to 'lelie'
754         # have subsequent stages and use 'lelie' output.
755         if pseudo_filter_p:
756                 files[0] = 'lelie'
757                 
758         if 'PNG' in targets and 'PS' not in targets:
759                 targets.append ('PS')
760         if 'PS' in targets and 'DVI' not in targets:
761                 targets.append('DVI')
762
763         if 'DVI' in targets:
764                 try:
765                         run_latex (files, outbase, extra_init)
766                         # unless: add --tex, or --latex?
767                         targets.remove ('TEX')
768                         targets.remove('LATEX')
769                 except:
770                         # TODO: friendly message about TeX/LaTeX setup,
771                         # trying to run tex/latex by hand
772                         if 'DVI' in targets:
773                                 targets.remove ('DVI')
774                         if 'PS' in targets:
775                                 targets.remove ('PS')
776                         if verbose_p:
777                                 traceback.print_exc ()
778
779         if 'PS' in targets:
780                 try:
781                         run_dvips (outbase, extra_init)
782                 except: 
783                         if 'PS' in targets:
784                                 targets.remove ('PS')
785                         if verbose_p:
786                                 traceback.print_exc ()
787
788         if 'PNG' in  targets:
789                 ly.make_preview (outbase)
790
791         if 'PDFTEX' in targets:
792                 try:
793                         run_latex (files, outbase, extra_init)
794                         # unless: add --tex, or --latex?
795                         targets.remove ('TEX')
796                         targets.remove ('LATEX')
797                         targets.remove ('PDFTEX')
798                         if 'PDF' not in targets:
799                                 targets.append('PDF')
800                 except:
801                         # TODO: friendly message about TeX/LaTeX setup,
802                         # trying to run tex/latex by hand
803                         if 'PDFTEX' in targets:
804                                 targets.remove ('PDFTEX')
805                         if 'PDF' in targets:
806                                 targets.remove ('PDF')
807                         if 'PS' in targets:
808                                 targets.remove ('PS')
809                         if verbose_p:
810                                 traceback.print_exc ()
811
812         # add DEP to targets?
813         if track_dependencies_p:
814                 depfile = os.path.join (outdir, outbase + '.dep')
815                 generate_dependency_file (depfile, depfile)
816                 if os.path.isfile (depfile):
817                         ly.progress (_ ("dependencies output to `%s'...") %
818                                   depfile)
819                         ly.progress ('\n')
820
821         if pseudo_filter_p:
822                 main_target = 0
823                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
824                         if i in targets:
825                                 main_target = i
826                                 break
827
828                 ly.progress (_ ("%s output to <stdout>...") % i)
829                 outname = outbase + '.' + string.lower (main_target)
830                 if os.path.isfile (outname):
831                         sys.stdout.write (open (outname).read ())
832                 elif verbose_p:
833                         ly.warning (_ ("can't find file: `%s'") % outname)
834                 targets = []
835                 ly.progress ('\n')
836                 
837         # Hmm, if this were a function, we could call it the except: clauses
838         for i in targets:
839                 ext = string.lower (i)
840                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
841                 outname = outbase + '.' + string.lower (i)
842                 abs = os.path.join (outdir, outname)
843                 if reldir != '.':
844                         outname = os.path.join (reldir, outname)
845                 if os.path.isfile (abs):
846                         ly.progress (_ ("%s output to `%s'...") % (i, outname))
847                         ly.progress ('\n')
848                 elif verbose_p:
849                         ly.warning (_ ("can't find file: `%s'") % outname)
850                         
851         os.chdir (original_dir)
852         ly.cleanup_temp ()
853
854         sys.exit (lilypond_error_p)