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