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