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