]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
* scripts/musedata2ly.py (): idem
[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
534         if 'PDF' in targets:
535                 where = ly.read_pipe ('kpsewhich feta20.pfa')
536
537                 pfa_file  = None
538                 if where:
539                         try: 
540                                 pfa_file = open (where, 'r')
541                         except IOError:
542                                 pass
543
544                 if pfa_file:
545                         opts = opts + ' -Ppdf -G0 -u lilypond.map'
546                 else:
547                         ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
548 Using bitmap fonts instead. This will look poorly.'''))
549                 
550         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
551         ly.system (cmd)
552
553         if preview_p:
554                 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')         
555                 ly.system (cmd)
556
557         if 'PDF' in targets:
558                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
559                 ly.system (cmd)
560                 
561 def generate_dependency_file (depfile, outname):
562         df = open (depfile, 'w')
563         df.write (outname + ':' )
564         
565         for d in dependency_files:
566                 s = open (d).read ()
567                 s = re.sub ('#[^\n]*\n', '', s)
568                 s = re.sub (r'\\\n', ' ', s)
569                 m = re.search ('.*:(.*)\n', s)
570
571                 # ugh. Different targets?
572                 if m:
573                         df.write ( m.group (1)  + ' ' )
574
575         df.write ('\n')
576         df.close ();
577
578 def find_file_in_path (path, name):
579         for d in string.split (path, os.pathsep):
580                 if name in os.listdir (d):
581                         return os.path.join (d, name)
582
583 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
584 # in future too.
585 PS = '%!PS-Adobe'
586 def find_pfa_fonts (name):
587         s = open (name).read ()
588         if s[:len (PS)] != PS:
589                 # no ps header?
590                 ly.error (_ ("not a PostScript file: `%s\'" % name))
591                 ly.exit (1)
592         here = 0
593         m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
594         pfa = []
595         while m:
596                 here = m.end (1)
597                 pfa.append (m.group (1))
598                 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
599         return pfa
600
601         
602 (sh, long) = ly.getopt_args (option_definitions)
603 try:
604         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
605 except getopt.error, s:
606         sys.stderr.write ('\n')
607         ly.error (_ ("getopt says: `%s\'" % s))
608         sys.stderr.write ('\n')
609         ly.help ()
610         ly.exit (2)
611         
612 for opt in options:
613         o = opt[0]
614         a = opt[1]
615
616         if 0:
617                 pass
618         elif o == '--help' or o == '-h':
619                 ly.help ()
620                 sys.exit (0)
621         elif o == '--find-pfa' or o == '-f':
622                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
623                 files = map (lambda x:
624                              find_file_in_path (os.environ['GS_FONTPATH'], x),
625                              fonts)
626                 print string.join (files, ' ')
627                 sys.exit (0)
628         elif o == '--include' or o == '-I':
629                 include_path.append (a)
630         elif o == '--postscript' or o == '-P':
631                 targets.append ('PS')
632         elif o == '--pdf' or o == '-p':
633                 targets.append ('PS')
634                 targets.append ('PDF')
635         elif o == '--keep' or o == '-k':
636                 keep_temp_dir_p = 1
637         elif o == '--no-lily':
638                 lily_p = 0
639         elif o == '--preview':
640                 preview_p = 1
641                 targets.append ('PNG')
642         elif o == '--preview-resolution':
643                 preview_resolution = string.atoi (a)
644         elif o == '--no-paper' or o == '-m':
645                 targets = ['MIDI'] 
646                 paper_p = 0
647         elif o == '--output' or o == '-o':
648                 output_name = a
649         elif o == '--set' or o == '-s':
650                 ss = string.split (a, '=')
651                 set_setting (extra_init, ss[0], ss[1])
652         elif o == '--dependencies' or o == '-d':
653                 track_dependencies_p = 1
654         elif o == '--verbose' or o == '-V':
655                 verbose_p = 1
656         elif o == '--version' or o == '-v':
657                 ly.identify (sys.stdout)
658                 sys.exit (0)
659         elif o == '--pdftex':
660                 latex_cmd = 'pdflatex'
661                 targets.remove('DVI')
662                 targets.append('PDFTEX')
663                 pdftex_p = 1
664                 tex_extension = '.pdftex'
665         elif o == '--warranty' or o == '-w':
666                 status = os.system ('lilypond -w')
667                 if status:
668                         ly.warranty ()
669                 sys.exit (0)
670
671 # Don't convert input files to abspath, rather prepend '.' to include
672 # path.
673 include_path.insert (0, '.')
674
675 # As a neat trick, add directory part of first input file
676 # to include path.  That way you can do without the clumsy -I in:
677
678 #    ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
679 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
680         include_path.append (os.path.dirname (files[0]))
681         
682 include_path = map (ly.abspath, include_path)
683
684 if files and (files[0] == '-' or output_name == '-'):
685         if len (files) == 1:
686                 pseudo_filter_p = 1
687                 output_name = 'lelie'
688                 if verbose_p:
689                         ly.progress (_ ("pseudo filter") + '\n')
690         else:
691                 ly.help ()
692                 ly.error (_ ("pseudo filter only for single input file"))
693                 ly.exit (2)
694                 
695 if not files:
696         ly.help ()
697         ly.error (_ ("no files specified on command line"))
698         ly.exit (2)
699
700 if 1:
701         ly.identify (sys.stderr)
702         original_output = output_name
703         
704         # Ugh, maybe make a setup () function
705         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
706
707         # hmmm. Wish I'd 've written comments when I wrote this.
708         # now it looks complicated.
709         
710         (outdir, outbase) = ('','')
711         if not output_name:
712                 outbase = os.path.basename (files[0])
713                 outdir = ly.abspath ('.')
714         elif output_name[-1] == os.sep:
715                 outdir = ly.abspath (output_name)
716                 outbase = os.path.basename (files[0])
717         else:
718                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
719
720         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
721                 output_name = ly.strip_extension (output_name, i)
722                 outbase = ly.strip_extension (outbase, i)
723
724         for i in files[:] + [output_name]:
725                 if string.find (i, ' ') >= 0:
726                         ly.error (_ ("filename should not contain spaces: `%s'") %
727                                i)
728                         ly.exit (1)
729                         
730         if os.path.dirname (output_name) != '.':
731                 dep_prefix = os.path.dirname (output_name)
732         else:
733                 dep_prefix = 0
734
735         reldir = os.path.dirname (output_name)
736         if outdir != '.' and (track_dependencies_p or targets):
737                 ly.mkdir_p (outdir, 0777)
738
739         tmpdir = ly.setup_temp ()
740         ly.setup_environment ()
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 'PNG' in targets and 'PS' not in targets:
773                 targets.append ('PS')
774         if 'PS' in targets and 'DVI' not in targets:
775                 targets.append('DVI')
776
777         if 'DVI' in targets:
778                 try:
779                         run_latex (files, outbase, extra_init)
780                         # unless: add --tex, or --latex?
781                         targets.remove ('TEX')
782                         targets.remove('LATEX')
783                 except:
784                         # TODO: friendly message about TeX/LaTeX setup,
785                         # trying to run tex/latex by hand
786                         if 'DVI' in targets:
787                                 targets.remove ('DVI')
788                         if 'PS' in targets:
789                                 targets.remove ('PS')
790                         if verbose_p:
791                                 traceback.print_exc ()
792
793         if 'PS' in targets:
794                 try:
795                         run_dvips (outbase, extra_init)
796                         
797                 except: 
798                         if 'PS' in targets:
799                                 targets.remove ('PS')
800                         if verbose_p:
801                                 traceback.print_exc ()
802                         else:
803                                 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
804
805         if 'PNG' in  targets:
806                 ly.make_preview (outbase)
807
808         if 'PDFTEX' in targets:
809                 try:
810                         run_latex (files, outbase, extra_init)
811                         # unless: add --tex, or --latex?
812                         targets.remove ('TEX')
813                         targets.remove ('LATEX')
814                         targets.remove ('PDFTEX')
815                         if 'PDF' not in targets:
816                                 targets.append('PDF')
817                 except:
818                         # TODO: friendly message about TeX/LaTeX setup,
819                         # trying to run tex/latex by hand
820                         if 'PDFTEX' in targets:
821                                 targets.remove ('PDFTEX')
822                         if 'PDF' in targets:
823                                 targets.remove ('PDF')
824                         if 'PS' in targets:
825                                 targets.remove ('PS')
826                         if verbose_p:
827                                 traceback.print_exc ()
828                         else:
829                                 ly.warning (_("Running LaTeX falied. Rerun with --verbose for a trace."))
830                                 
831
832         # add DEP to targets?
833         if track_dependencies_p:
834                 depfile = os.path.join (outdir, outbase + '.dep')
835                 generate_dependency_file (depfile, depfile)
836                 if os.path.isfile (depfile):
837                         ly.progress (_ ("dependencies output to `%s'...") %
838                                   depfile)
839                         ly.progress ('\n')
840
841         if pseudo_filter_p:
842                 main_target = 0
843                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
844                         if i in targets:
845                                 main_target = i
846                                 break
847
848                 ly.progress (_ ("%s output to <stdout>...") % i)
849                 outname = outbase + '.' + string.lower (main_target)
850                 if os.path.isfile (outname):
851                         sys.stdout.write (open (outname).read ())
852                 elif verbose_p:
853                         ly.warning (_ ("can't find file: `%s'") % outname)
854                 targets = []
855                 ly.progress ('\n')
856                 
857         # Hmm, if this were a function, we could call it the except: clauses
858         for i in targets:
859                 ext = string.lower (i)
860                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
861                 outname = outbase + '.' + string.lower (i)
862                 abs = os.path.join (outdir, outname)
863                 if reldir != '.':
864                         outname = os.path.join (reldir, outname)
865                 if os.path.isfile (abs):
866                         ly.progress (_ ("%s output to `%s'...") % (i, outname))
867                         ly.progress ('\n')
868                 elif verbose_p:
869                         ly.warning (_ ("can't find file: `%s'") % outname)
870                         
871         os.chdir (original_dir)
872         ly.cleanup_temp ()
873
874         sys.exit (lilypond_error_p)