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