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