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