]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond.py
(ic_p.make_include_option): set error_p for
[lilypond.git] / scripts / lilypond.py
1 #!@PYTHON@
2 # lilypond.py -- frontend for lilypond-bin
3 #
4 # source file of the GNU LilyPond music typesetter
5
6 # (c) 1998--2004  Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 #                 Jan Nieuwenhuizen <janneke@gnu.org>
8 #
9 # Run lilypond-bin, generate printable document
10 # Invokes: lilypond-bin, latex (or pdflatex), dvips, ps2pdf, gs
11
12
13 # This is the third incarnation of ly2dvi, renamed to lilypond.
14 #
15 # Earlier incarnations of ly2dvi were written by
16 # Jeffrey B. Reed<daboys@austin.rr.com> (Python versioan)
17 # Jan Arne Fagertun <Jan.A.Fagertun@@energy.sintef.no> (Bourne shell script)
18 #
19
20 # Note: gettext work best if we use ' for program/docstrings and "
21 #       for gettextable strings.
22 #       USE ''' for docstrings.
23
24
25 '''
26 TODO:
27
28   * cleanup
29
30   * figure out which set of command line options should make lilypond:
31
32       na: create tex only?  
33       na: create latex only? 
34       na: create tex and latex
35       default: create dvi only
36       na: create tex, latex and dvi
37       -P: create dvi and ps
38       -p: create pdf
39       na: * create ps only
40
41      etc.
42
43   * dvi from lilypond .tex output?  This is hairy, because we create dvi
44     from lilypond .tex *and* header output.
45
46 '''
47
48 import operator
49 import stat
50 import string
51 import traceback
52 import glob
53
54 ################################################################
55 # Users of python modules should include this snippet
56 # and customize variables below.
57
58 # We'll suffer this path init stuff as long as we don't install our
59 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
60 # it as we do with teTeX on Red Hat Linux: set some environment var
61 # (PYTHONPATH) in profile)
62
63 # If set, LILYPONDPREFIX must take prevalence
64 # if datadir is not set, we're doing a build and LILYPONDPREFIX
65 import getopt, os, sys
66 datadir = '@local_lilypond_datadir@'
67 if not os.path.isdir (datadir):
68         datadir = '@lilypond_datadir@'
69 if os.environ.has_key ('LILYPONDPREFIX') :
70         datadir = os.environ['LILYPONDPREFIX']
71         while datadir[-1] == os.sep:
72                 datadir= datadir[:-1]
73
74
75 sys.path.insert (0, os.path.join (datadir, 'python'))
76
77 # Customize these
78 #if __name__ == '__main__':
79
80 import lilylib as ly
81 global _;_=ly._
82 global re;re = ly.re
83
84 # lilylib globals
85 program_name = 'lilypond'
86 program_version = '@TOPLEVEL_VERSION@'
87 # input without \book, use classic latex definitions
88 classic_p = 0
89 verbose_p = 0
90 pseudo_filter_p = 0
91 original_dir = os.getcwd ()
92 temp_dir = os.path.join (original_dir,  '%s.dir' % program_name)
93 keep_temp_dir_p = 0
94 preview_resolution = 90
95 debug_p = 0
96
97 TEX_PREAMBLE = '%%%% Generated by %(program_name)s (v%(program_version)s)' \
98                % vars ()
99
100 ## FIXME
101 ## do -P or -p by default?
102 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
103 help_summary = _ ("Run LilyPond, generate printable document.")
104 copyright = ('Han-Wen Nienhuys <hanwen@cs.uu.nl',
105              'Jan Nieuwenhuizen <janneke@gnu.org')
106
107 option_definitions = [
108         ('', 'h', 'help', _ ("print this help")),
109         ('', '', 'debug', _ ("print even more output")),
110         (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
111         ('','', 'html', _("make HTML file with links to all output")),
112         (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
113         ('', 'k', 'keep',
114          _ ("keep all output, output to directory %s.dir") % program_name),
115         ('', '', 'no-lily', _ ("don't run LilyPond")),
116         ('', 'm', 'no-paper', _ ("produce MIDI output only")),
117         (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
118         (_ ('RES'), '', 'preview-resolution',
119          _ ("set the resolution of the preview to RES")),
120         ('', '', 'no-pdf', _ ("do not generate PDF output")),
121         ('', '', 'no-ps', _ ("do not generate PostScript output")),
122         ('', 'p', 'pdf', _ ("generate PDF output")),
123         ('', 'P', 'postscript', _ ("generate PostScript output")),
124         ('', '', 'pdftex', _ ("use pdflatex to generate PDF output")),
125         ('', '', 'png', _("generate PNG page images")),
126         ('', '', 'preview', _ ("make a picture of the first system")),
127         ('', '', 'psgz', _ ("generate PS.GZ")),
128         ('', 's', 'safe-mode', _ ("run in safe-mode")),
129         (_ ("KEY=VAL"), 'S', 'set', _ ("change global setting KEY to VAL")),
130         ('', 'V', 'verbose', _ ("be verbose")),
131         ('', 'v', 'version', _ ("print version number")),
132         ('', 'w', 'warranty', _ ("show warranty and copyright")),
133         ]
134
135 # other globals
136 safe_mode_p = 0
137 preview_p = 0
138 page_images_p = 0
139
140 # need global variable. sys.exit() raises an exception, which is handled
141 # to do cleanups.
142 lilypond_error_p = 0
143 html_p = 0
144
145 # Pdftex support
146 pdftex_p = 0
147 latex_cmd = 'latex'
148
149
150 tex_extension = '.tex'  ## yuk.
151
152 #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' }
153
154 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
155
156 # only use installed binary  when we're installed too.
157 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
158         lilypond_binary = 'lilypond-bin'
159
160
161 ## Init to empty; values here take precedence over values in the file
162 extra_init = {
163         'language' : [],
164         'latexheaders' : [],
165         'latexoptions' : [],
166         'latexpackages' :  [],
167         'linewidth' : [],
168         'orientation' : [],
169         'papersize' : [],
170         'unit' : ['pt'],
171 }
172
173 header_fields = extra_init.keys ()
174
175 include_path = ['.']
176 lily_p = 1
177 paper_p = 1
178
179 output_name = ''
180
181 # Output formats that lilypond should create
182 targets = ['DVI', 'LATEX', 'MIDI', 'TEX', 'PDF', 'PS']
183
184 dependency_files = []
185
186 #what a name.
187 def set_setting (dict, key, val):
188         try:
189                 val = string.atoi (val)
190         except ValueError:
191                 #ly.warning (_ ("invalid value: %s") % `val`)
192                 pass
193
194         if type(val) == type ('hoi'):
195                 try:
196                         val = string.atof (val)
197                 except ValueError:
198                         #ly.warning (_ ("invalid value: %s") % `val`)
199                         pass
200
201         try:
202                 dict[key].append (val)
203         except KeyError:
204                 ly.warning (_ ("no such setting: `%s'") % `key`)
205                 dict[key] = [val]
206
207
208 def escape_shell (x):
209         return re.sub ("(\s|[`'\"\\\\])", r'\\\1',x)
210
211 def run_lilypond (files, dep_prefix):
212         
213         def make_include_option (x):
214                 return '-I %s' %   escape_shell (x)
215         
216         opts = ' ' + string.join (map (make_include_option, include_path))
217         
218         ## UGHr
219         if pseudo_filter_p:
220                 opts += ' --output=lelie'
221         if paper_p:
222                 opts += ' ' + string.join (map (lambda x : '--header=' + x,
223                                                 header_fields))
224         else:
225                 opts = opts + ' --no-paper'
226         if pdftex_p:
227                 opts = opts + ' -f pdftex'              
228         if safe_mode_p:
229                 opts = opts + ' --safe-mode'
230
231         fs = string.join (map (escape_shell, files))
232
233         global verbose_p
234         if verbose_p:
235                 opts = opts + ' --verbose'
236
237         if debug_p:
238                 ly.print_environment ()
239                 
240         cmd = string.join ((lilypond_binary, opts, fs))
241         status = ly.system (cmd, ignore_error = 1, progress_p = 1)
242         signal = 0x0f & status
243         exit_status = status >> 8
244
245         # 2 == user interrupt.
246         if signal and signal != 2:
247                 sys.stderr.write ('\n\n')
248                 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
249                 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
250                 ly.exit (status)
251                         
252         if status:
253                 global lilypond_error_p
254                 sys.stderr.write ('\n')
255                 if len (files) == 1:
256                         ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
257                         lilypond_error_p = 1
258                         ly.exit (1)
259                 else:
260                         ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
261                         ly.error (_ ("Continuing..."))
262                         lilypond_error_p = 1
263                 
264
265 def analyse_lilypond_output (filename, extra):
266         
267         # urg
268         '''Grep FILENAME for interesting stuff, and
269         put relevant info into EXTRA.'''
270         filename = filename + tex_extension
271         ly.progress (_ ("Analyzing %s...") % filename)
272         s = open (filename).read ()
273
274         # search only the first 10k
275         s = s[:10240]
276         for x in header_fields:
277                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}' % x, s)
278                 if m:
279                         set_setting (extra, x, m.group (1))
280
281         global classic_p
282         if s.find ('\\def\\lilypondclassic{1}') >= 0:
283                 classic_p = 1
284         
285         ly.progress ('\n')
286
287 def find_tex_files_for_base (base, extra):
288
289         if os.path.exists (base  +'.dep'):
290                 dependency_files.append (base + '.dep')
291
292         for f in header_fields:
293                 fn =base + '.' + f
294                 if os.path.exists (fn):
295                         extra[f].append (open (fn).read ())
296         
297         return (base + tex_extension, {})
298          
299
300 def find_tex_files (files, extra):
301         '''
302         Find all .tex files whose prefixes start with some name in FILES. 
303
304         '''
305         
306         tfiles = []
307         
308         for f in files:
309                 x = 0
310                 while 1:
311                         fname = os.path.basename (f)
312                         fname = ly.strip_extension (fname, '.ly')
313                         if x:
314                                 fname = fname + '-%d' % x
315
316                         if os.path.exists (fname + tex_extension):
317                                 tfiles.append (find_tex_files_for_base (fname, extra))
318                                 analyse_lilypond_output (fname, extra)
319                         else:
320                                 break
321
322                         x = x + 1
323         if not x:
324                 fstr = string.join (files, ', ')
325                 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
326         return tfiles
327
328 def one_latex_definition (defn, first):
329         s = '\n'
330         for (k, v) in defn[1].items ():
331                 val = open (v).read ()
332                 if (string.strip (val)):
333                         s += r'''\def\lilypond%s{%s}''' % (k, val)
334                 else:
335                         s += r'''\let\lilypond%s\relax''' % k
336                 s += '\n'
337
338         if classic_p and not first:
339                 s += '\interscoreline'
340
341         s += '%%PREVIEW%%\n'
342         s += '\\input %s\n' % defn[0]
343         return s
344
345                 
346 ## FIXME: copied from tex/lilyponddefs.tex
347 LATEX_PREAMBLE = '''
348 %% Nullify [La]TeX page layout settings, page layout by LilyPond.
349 \\topmargin-1in
350 \\headheight0pt\\headsep0pt
351 \\oddsidemargin-1in
352 \\evensidemargin\oddsidemargin
353 \\parindent 0pt'''
354
355 CLASSIC_LATEX_PREAMBLE = '''
356 %% FIXME: cannot do this, dimens in header part of lilypond output
357 %% Center staves horizontally on page
358 \\ifdim\\lypylinewidth\\lypyunit > 0pt
359 \\hsize\\lypylinewidth\\lypyunit
360 \\newdimen\\lypytempdim
361 \\lypytempdim\\paperwidth
362 \\advance\\lypytempdim-\\the\\hsize
363 \\lypytempdim0.5\\lypytempdim
364 \\advance\\lypytempdim -1in
365 \\oddsidemargin\\lypytempdim
366 \\evensidemargin\\lypytempdim
367 \\fi
368 \\parindent 0pt'''
369
370 def global_latex_preamble (extra):
371         '''construct preamble from EXTRA,'''
372         
373         s = TEX_PREAMBLE
374         s += '\n'
375
376         options = ''
377
378         if extra['latexoptions']:
379                 options = options + ',' + extra['latexoptions'][-1]
380
381         s += '\\documentclass[%s]{article}\n' % options
382
383         if safe_mode_p:
384                 s += '\\nofiles\n'
385
386         if classic_p:
387                 if extra['linewidth']:
388                         s += '\\def\\lypylinewidth{%s}\n' \
389                              % extra['linewidth'][-1]
390                 else:
391                         s += '\\let\\lypylinewidth\\texwidth\n'
392                 s += '\\def\\lypyunit{%s}\n' % extra['unit'][-1]
393
394         if extra['language']:
395                 s += '\\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
396
397         s += '\\usepackage{%s}\n' \
398                 % string.join (extra['latexpackages'], ',')
399
400         if extra['latexheaders']:
401                 s += '\\include{%s}\n' \
402                         % string.join (extra['latexheaders'], '}\n\\include{')
403
404         unit = extra['unit'][-1]
405
406         # FIXME, must (only) from lilypond-bin
407         s += r'''
408 \usepackage{inputenc}
409 \pagestyle{empty}
410 %%PREVIEW%%'''
411         
412         if classic_p:
413                 s += CLASSIC_LATEX_PREAMBLE
414         else:
415                 s += LATEX_PREAMBLE
416         return s
417
418         
419 def global_latex_definition (tfiles, extra):
420         '''construct preamble from EXTRA, dump Latex stuff for each
421 lily output file in TFILES after that, and return the Latex file constructed.  '''
422         s = global_latex_preamble (extra) + '\\begin{document}\n'
423         s += '\\parindent 0pt'
424
425         first = 1
426         for t in tfiles:
427                 s += one_latex_definition (t, first)
428                 first = 0
429         s += '\\end{document}\n'
430         return s
431
432 def run_latex (files, outbase, extra):
433         '''Construct latex file, for FILES and EXTRA, dump it into
434 OUTBASE.latex.  Run LaTeX on it.
435 '''
436
437         latex_fn = outbase + '.latex'
438         
439         wfs = find_tex_files (files, extra)
440         s = global_latex_definition (wfs, extra)
441
442         f = open (latex_fn, 'w')
443         f.write (s)
444         f.close ()
445
446         cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
447         
448         # Ugh.  (La)TeX writes progress and error messages on stdout
449         # Redirect to stderr
450         cmd = '(( %s  >&2 ) >&- )' % cmd
451         status = ly.system (cmd, ignore_error = 1)
452         signal = 0xf & status
453         exit_status = status >> 8
454
455         if exit_status:
456
457                 logstr = ''
458                 try:
459                         logstr = open (outbase + '.log').read ()
460                         m = re.search ("\n!", logstr)
461                         start = m.start (0)
462                         logstr = logstr[start:start+200]
463                 except:
464                         pass
465                         
466                 ly.error (_ ("LaTeX failed on the output file."))
467                 ly.error (_ ("The error log is as follows:"))
468                 sys.stderr.write (logstr + '\n')
469                 ly.exit (1)
470         
471         if preview_p:
472                 # make a preview by rendering only the 1st line
473                 # of each score
474                 for score in find_tex_files (files, extra):
475                         preview_base = ly.strip_extension (score[0], '.tex')
476                         preview_fn = preview_base + '.preview.tex'
477                         s = global_latex_definition ((score,), extra)
478                         s = re.sub ('%%PREVIEW%%',
479                                     r'''\def\interscoreline{\endinput}''', s)
480                         f = open (preview_fn, 'w')
481                         f.write (s)
482                         f.close ()
483                         cmd = '%s \\\\nonstopmode \\\\input %s' \
484                               % (latex_cmd, preview_fn)
485                         ly.system (cmd)
486
487
488 def run_dvips (outbase, extra):
489         '''Run dvips using the correct options taken from EXTRA,
490 leaving a PS file in OUTBASE.ps
491 '''
492         #FIXME: papersize, orientation must come from lilypond-bin
493         opts = ''
494         if extra['papersize']:
495                 opts = ' -t%s' % extra['papersize'][0]
496                 
497         if extra['orientation'] and extra['orientation'][0] == 'landscape':
498                 opts = opts + ' -tlandscape'
499
500         if 'PDF' in targets:
501                 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
502
503                 pfa_file  = None
504                 if where:
505                         try: 
506                                 pfa_file = open (where, 'r')
507                         except IOError:
508                                 pass
509
510                 if pfa_file:
511                         #opts = opts + ' -Ppdf -G0 -u +lm.map -u +lilypond.map'
512                         opts = opts + ' -Ppdf -G0 -u +ec-mftrace.map -u +lilypond.map'
513                 else:
514                         ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
515 Using bitmap fonts instead. This will look bad.'''))
516
517         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
518         ly.system (cmd)
519
520         if preview_p:
521                 for score in find_tex_files (files, extra):
522                         preview_base = ly.strip_extension (score[0], '.tex')
523                         cmd = 'dvips -E -Ppdf -u+ec-mftrace.map -u+lilypond.map -o%s %s' \
524                               % (preview_base + '.preview.ps',
525                                  preview_base + '.preview.dvi')
526                         ly.system (cmd)
527
528         if 'PDF' in targets:
529                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
530                 ly.system (cmd)
531                 
532 def generate_dependency_file (depfile, outname):
533         df = open (depfile, 'w')
534         df.write (outname + ':' )
535         
536         for d in dependency_files:
537                 s = open (d).read ()
538                 s = re.sub ('#[^\n]*\n', '', s)
539                 s = re.sub (r'\\\n', ' ', s)
540                 m = re.search ('.*:(.*)\n', s)
541
542                 # ugh. Different targets?
543                 if m:
544                         df.write ( m.group (1)  + ' ' )
545
546         df.write ('\n')
547         df.close ();
548
549 def find_file_in_path (path, name):
550         for d in string.split (path, os.pathsep):
551                 if not d:
552                         d = original_dir
553                 if name in os.listdir (d):
554                         return os.path.join (d, name)
555
556 def find_pfa_fonts (name):
557         PS = '%!PS-Adobe'
558         s = open (name).read ()
559         if s[:len (PS)] != PS:
560                 # no ps header?
561                 ly.error (_ ("not a PostScript file: `%s\'" % name))
562                 ly.exit (1)
563         here = 0
564         m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
565         pfa = []
566         while m:
567                 here = here + m.end (0)
568                 pfa.append (m.group (1))
569                 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
570         return pfa
571
572
573 def make_html_menu_file (html_file, files_found):
574         exts = {
575                 'pdf' : "Print (PDF, %s)",
576                 'ps.gz' : "Print (gzipped PostScript, %s)",
577                 'png' : "View (PNG, %s)",
578                 'midi' : "Listen (MIDI, %s)",
579                 'ly' : "View source code (%s)", 
580                 }
581         html_str = ''
582
583         pages = filter (lambda x : re.search ('page[0-9]+.png',  x),
584                         files_found)
585         rest =  filter (lambda x : not re.search ('page[0-9]+.png',  x),
586                         files_found)
587
588         preview = filter (lambda x: re.search ('.png$', x), rest)
589         if preview:
590                 html_str = '<img src="%s">' % preview[0]
591
592         for p in pages:
593                 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
594                 page = page % 'unknown size'
595                 
596                 html_str += '<li><a href="%s">%s</a>' % (p, page)
597                 
598                 
599         for e in ['pdf', 'ps.gz', 'midi', 'ly']:
600                 fs = filter (lambda x: re.search ('.%s$' % e, x), rest)
601                 for f in fs:
602                         entry = exts[e] % 'unknown size' # todo
603                         html_str += '<li><a href="%s">%s</a>\n\n' % (f, entry)
604
605         html_str += "\n\n</li>"
606         ly.progress (_("Writing HTML menu `%s'") % html_file)
607         ly.progress ('\n')
608         open (html_file, 'w').write (html_str)
609         
610 ################################################################
611 ## MAIN
612 ################################################################
613
614 (sh, long) = ly.getopt_args (option_definitions)
615 try:
616         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
617 except getopt.error, s:
618         sys.stderr.write ('\n')
619         ly.error (_ ("getopt says: `%s\'" % s))
620         sys.stderr.write ('\n')
621         ly.help ()
622         ly.exit (2)
623         
624 for opt in options:
625         o = opt[0]
626         a = opt[1]
627
628         if 0:
629                 pass
630         elif o == '--help' or o == '-h':
631                 ly.help ()
632                 sys.exit (0)
633         elif o == '--find-pfa' or o == '-f':
634                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
635                 files = map (lambda x:
636                              find_file_in_path (os.environ['GS_FONTPATH'], x),
637                              fonts)
638                 print string.join (files, ' ')
639                 sys.exit (0)
640         elif o == '--include' or o == '-I':
641                 include_path.append (a)
642         elif o == '--postscript' or o == '-P':
643                 if 'PDF' in targets:
644                         targets.remove ('PDF')
645                 if 'PS' not in targets:
646                         targets.append ('PS')
647         elif o == '--pdf' or o == '-p':
648                 if 'PDF' not in targets:
649                         targets.append ('PDF')
650         elif o == '--no-pdf':
651                 if 'PDF' in targets:
652                         targets.remove ('PDF')
653         elif o == '--no-ps':
654                 if 'PS' in targets:
655                         targets.remove ('PS')
656                 if 'PDF' in targets:
657                         targets.remove ('PDF')
658         elif o == '--keep' or o == '-k':
659                 keep_temp_dir_p = 1
660         elif o == '--debug':
661                 verbose_p = 1
662                 debug_p = 1 
663         elif o == '--no-lily':
664                 lily_p = 0
665         elif o == '--preview':
666                 preview_p = 1
667                 if 'PNG' not in targets:
668                         targets.append ('PNG')
669         elif o == '--preview-resolution':
670                 preview_resolution = string.atoi (a)
671         elif o == '--no-paper' or o == '-m':
672                 targets = ['MIDI'] 
673                 paper_p = 0
674         elif o == '--output' or o == '-o':
675                 output_name = a
676         elif o == '--safe-mode' or o == '-s':
677                 safe_mode_p = 1
678         elif o == '--set' or o == '-S':
679                 ss = string.split (a, '=')
680                 set_setting (extra_init, ss[0], ss[1])
681         elif o == '--verbose' or o == '-V':
682                 verbose_p = 1
683         elif o == '--version' or o == '-v':
684                 ly.identify (sys.stdout)
685                 sys.exit (0)
686         elif o == '--pdftex':
687                 latex_cmd = 'pdflatex'
688                 targets.remove ('DVI')
689                 targets.append ('PDFTEX')
690                 pdftex_p = 1
691                 tex_extension = '.pdftex'
692         elif o == '--warranty' or o == '-w':
693                 status = os.system ('%s -w' % lilypond_binary)
694                 if status:
695                         ly.warranty ()
696                 sys.exit (0)
697         elif o == '--html':
698                 html_p = 1
699         elif o == '--png':
700                 page_images_p = 1
701                 if 'PNG' not in targets:
702                         targets.append ('PNG')
703         else:
704                 unimplemented_option () # signal programming error
705
706 # Don't convert input files to abspath, rather prepend '.' to include
707 # path.
708 include_path.insert (0, '.')
709
710 # As a neat trick, add directory part of first input file
711 # to include path.  That way you can do without the clumsy -I in:
712
713 #    lilypond -I foe/bar/baz foo/bar/baz/baz.ly
714 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
715         include_path.append (os.path.dirname (files[0]))
716         
717 include_path = map (ly.abspath, include_path)
718
719 if files and (files[0] == '-' or output_name == '-'):
720         if len (files) == 1:
721                 pseudo_filter_p = 1
722                 output_name = 'lelie'
723                 if verbose_p:
724                         ly.progress (_ ("pseudo filter") + '\n')
725         else:
726                 ly.help ()
727                 ly.error (_ ("pseudo filter only for single input file"))
728                 ly.exit (2)
729                 
730 if not files:
731         ly.help ()
732         ly.error (_ ("no files specified on command line"))
733         ly.exit (2)
734
735 if 1:
736         ly.identify (sys.stderr)
737         ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
738         
739         original_output = output_name
740         
741         # Ugh, maybe make a setup () function
742         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
743
744         # hmmm. Wish I'd 've written comments when I wrote this.
745         # now it looks complicated.
746         
747         (outdir, outbase) = ('','')
748         if not output_name:
749                 outbase = os.path.basename (files[0])
750                 outdir = ly.abspath ('.')
751         elif output_name[-1] == os.sep:
752                 outdir = ly.abspath (output_name)
753                 outbase = os.path.basename (files[0])
754         else:
755                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
756
757         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
758                 output_name = ly.strip_extension (output_name, i)
759                 outbase = ly.strip_extension (outbase, i)
760
761         for i in files[:] + [output_name]:
762                 b = os.path.basename (i)
763                 if string.find (b, ' ') >= 0:
764                         ly.error (_ ("filename should not contain spaces: `%s'") % b)
765                         ly.exit (1)
766                         
767         if os.path.dirname (output_name) != '.':
768                 dep_prefix = os.path.dirname (output_name)
769         else:
770                 dep_prefix = 0
771
772         reldir = os.path.dirname (output_name)
773         if outdir != '.' and targets:
774                 ly.mkdir_p (outdir, 0777)
775
776         tmpdir = ly.setup_temp ()
777         ly.setup_environment ()
778         if safe_mode_p:
779                 os.environ['openout_any'] = 'p'
780
781         # to be sure, add tmpdir *in front* of inclusion path.
782         #os.environ['TEXINPUTS'] =  tmpdir + ':' + os.environ['TEXINPUTS']
783         os.chdir (tmpdir)
784
785         # We catch all exceptions, because we need to do stuff at exit:
786         #   * copy any successfully generated stuff from tempdir and
787         #     notify user of that
788         #   * cleanout tempdir
789         if lily_p:
790                 try:
791                         run_lilypond (files, dep_prefix)
792                 except:
793                         ### ARGH. This also catches python programming errors.
794                         ### this should only catch lilypond nonzero exit  status
795                         ### --hwn
796
797                         # TODO: friendly message about LilyPond setup/failing?
798                         #
799                         targets = []
800                         if verbose_p:
801                                 traceback.print_exc ()
802                         else:
803                                 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
804                                 
805         # Our LilyPond pseudo filter always outputs to 'lelie'
806         # have subsequent stages and use 'lelie' output.
807         if pseudo_filter_p:
808                 files[0] = 'lelie'
809
810         if 'PS.GZ'  in targets:
811                 targets.append ('PS')
812                 
813         if 'PNG' in targets and 'PS' not in targets:
814                 targets.append ('PS')
815         if 'PS' in targets and 'DVI' not in targets:
816                 targets.append('DVI')
817
818         if 'DVI' in targets:
819                 try:
820                         run_latex (files, outbase, extra_init)
821                         # unless: add --tex, or --latex?
822                         targets.remove ('TEX')
823                         targets.remove('LATEX')
824                 except:
825                         # TODO: friendly message about TeX/LaTeX setup,
826                         # trying to run tex/latex by hand
827                         if 'DVI' in targets:
828                                 targets.remove ('DVI')
829                         if 'PS' in targets:
830                                 targets.remove ('PS')
831                         if verbose_p:
832                                 traceback.print_exc ()
833
834         if 'PS' in targets:
835                 try:
836                         run_dvips (outbase, extra_init)
837                         
838                 except: 
839                         if 'PS' in targets:
840                                 targets.remove ('PS')
841                         if verbose_p:
842                                 traceback.print_exc ()
843                         else:
844                                 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
845
846         if preview_p:
847                 for score in find_tex_files (files, extra_init):
848                         preview_base = ly.strip_extension (score[0], '.tex')
849                         ly.make_ps_images (preview_base + '.preview.ps',
850                                            resolution=preview_resolution
851                                            )
852
853         if 'PDFTEX' in targets:
854                 try:
855                         run_latex (files, outbase, extra_init)
856                         # unless: add --tex, or --latex?
857                         targets.remove ('TEX')
858                         targets.remove ('LATEX')
859                         targets.remove ('PDFTEX')
860                         if 'PDF' not in targets:
861                                 targets.append('PDF')
862                 except:
863                         # TODO: friendly message about TeX/LaTeX setup,
864                         # trying to run tex/latex by hand
865                         if 'PDFTEX' in targets:
866                                 targets.remove ('PDFTEX')
867                         if 'PDF' in targets:
868                                 targets.remove ('PDF')
869                         if 'PS' in targets:
870                                 targets.remove ('PS')
871                         if verbose_p:
872                                 traceback.print_exc ()
873                         else:
874                                 ly.warning (_("Running LaTeX failed. Rerun with --verbose for a trace."))
875                                 
876         if page_images_p:
877                 ly.make_ps_images (outbase + '.ps' ,
878                                    resolution = preview_resolution
879                                    )
880
881         if pseudo_filter_p:
882                 main_target = 0
883                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
884                         if i in targets:
885                                 main_target = i
886                                 break
887
888                 ly.progress (_ ("%s output to <stdout>...") % i)
889                 outname = outbase + '.' + string.lower (main_target)
890                 if os.path.isfile (outname):
891                         sys.stdout.write (open (outname).read ())
892                 elif verbose_p:
893                         ly.warning (_ ("can't find file: `%s'") % outname)
894                 targets = []
895                 ly.progress ('\n')
896                 
897         if 'PS.GZ' in targets:
898                 ly.system ("gzip *.ps") 
899                 targets.remove ('PS')
900
901         # Hmm, if this were a function, we could call it the except: clauses
902         files_found = []
903         for i in targets:
904                 ext = string.lower (i)
905
906                 pattern = '%s.%s' % (outbase, ext)
907                 if i == 'PNG':
908                         pattern  = '*.png' 
909                 ls = glob.glob (pattern)
910                 files_found += ls 
911                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
912
913
914                 if ls:
915                         names = string.join (map (lambda x: "`%s'" % x, ls))
916                         ly.progress (_ ("%s output to %s...") % (i, names))
917                         ly.progress ('\n')
918                 elif verbose_p:
919                         ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
920
921         if html_p:
922                 make_html_menu_file (os.path.join (outdir, outbase + ".html"),
923                                      files_found)
924
925         os.chdir (original_dir)
926         ly.cleanup_temp ()
927
928         sys.exit (lilypond_error_p)