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