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