]> git.donarmstrong.com Git - lilypond.git/blob - scripts/lilypond.py
($(outdir)-$(PAPERSIZE)/%.dvi): incude
[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[latin1]{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 = ' -t%s' % extra['papersize'][0]
490         if extra['orientation'] and extra['orientation'][0] == 'landscape':
491                 opts = opts + ' -tlandscape'
492
493         if 'PDF' in targets:
494                 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
495
496                 pfa_file  = None
497                 if where:
498                         try: 
499                                 pfa_file = open (where, 'r')
500                         except IOError:
501                                 pass
502
503                 if pfa_file:
504                         opts = opts + ' -Ppdf -G0 -u +ec-mftrace.map -u +lilypond.map'
505                 else:
506                         ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
507 Using bitmap fonts instead. This will look bad.'''))
508
509         cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
510         ly.system (cmd)
511
512         if preview_p:
513                 for score in find_tex_files (files, extra):
514                         preview_base = ly.strip_extension (score[0], '.tex')
515                         cmd = 'dvips -E -Ppdf -u+ec-mftrace.map -u+lilypond.map -o%s %s' \
516                               % (preview_base + '.preview.ps',
517                                  preview_base + '.preview.dvi')
518                         ly.system (cmd)
519
520         if 'PDF' in targets:
521                 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
522                 ly.system (cmd)
523                 
524 def generate_dependency_file (depfile, outname):
525         df = open (depfile, 'w')
526         df.write (outname + ':' )
527         
528         for d in dependency_files:
529                 s = open (d).read ()
530                 s = re.sub ('#[^\n]*\n', '', s)
531                 s = re.sub (r'\\\n', ' ', s)
532                 m = re.search ('.*:(.*)\n', s)
533
534                 # ugh. Different targets?
535                 if m:
536                         df.write ( m.group (1)  + ' ' )
537
538         df.write ('\n')
539         df.close ();
540
541 def find_file_in_path (path, name):
542         for d in string.split (path, os.pathsep):
543                 if not d:
544                         d = original_dir
545                 if name in os.listdir (d):
546                         return os.path.join (d, name)
547
548 def find_pfa_fonts (name):
549         PS = '%!PS-Adobe'
550         s = open (name).read ()
551         if s[:len (PS)] != PS:
552                 # no ps header?
553                 ly.error (_ ("not a PostScript file: `%s\'" % name))
554                 ly.exit (1)
555         here = 0
556         m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
557         pfa = []
558         while m:
559                 here = here + m.end (0)
560                 pfa.append (m.group (1))
561                 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
562         return pfa
563
564
565 def make_html_menu_file (html_file, files_found):
566         exts = {
567                 'pdf' : "Print (PDF, %s)",
568                 'ps.gz' : "Print (gzipped PostScript, %s)",
569                 'png' : "View (PNG, %s)",
570                 'midi' : "Listen (MIDI, %s)",
571                 'ly' : "View source code (%s)", 
572                 }
573         html_str = ''
574
575         pages = filter (lambda x : re.search ('page[0-9]+.png',  x),
576                         files_found)
577         rest =  filter (lambda x : not re.search ('page[0-9]+.png',  x),
578                         files_found)
579
580         preview = filter (lambda x: re.search ('.png$', x), rest)
581         if preview:
582                 html_str = '<img src="%s">' % preview[0]
583
584         for p in pages:
585                 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
586                 page = page % 'unknown size'
587                 
588                 html_str += '<li><a href="%s">%s</a>' % (p, page)
589                 
590                 
591         for e in ['pdf', 'ps.gz', 'midi', 'ly']:
592                 fs = filter (lambda x: re.search ('.%s$' % e, x), rest)
593                 for f in fs:
594                         entry = exts[e] % 'unknown size' # todo
595                         html_str += '<li><a href="%s">%s</a>\n\n' % (f, entry)
596
597         html_str += "\n\n</li>"
598         ly.progress (_("Writing HTML menu `%s'") % html_file)
599         ly.progress ('\n')
600         open (html_file, 'w').write (html_str)
601         
602 ################################################################
603 ## MAIN
604 ################################################################
605
606 (sh, long) = ly.getopt_args (option_definitions)
607 try:
608         (options, files) = getopt.getopt (sys.argv[1:], sh, long)
609 except getopt.error, s:
610         sys.stderr.write ('\n')
611         ly.error (_ ("getopt says: `%s\'" % s))
612         sys.stderr.write ('\n')
613         ly.help ()
614         ly.exit (2)
615         
616 for opt in options:
617         o = opt[0]
618         a = opt[1]
619
620         if 0:
621                 pass
622         elif o == '--help' or o == '-h':
623                 ly.help ()
624                 sys.exit (0)
625         elif o == '--find-pfa' or o == '-f':
626                 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
627                 files = map (lambda x:
628                              find_file_in_path (os.environ['GS_FONTPATH'], x),
629                              fonts)
630                 print string.join (files, ' ')
631                 sys.exit (0)
632         elif o == '--include' or o == '-I':
633                 include_path.append (a)
634         elif o == '--postscript' or o == '-P':
635                 if 'PDF' in targets:
636                         targets.remove ('PDF')
637                 if 'PS' not in targets:
638                         targets.append ('PS')
639         elif o == '--pdf' or o == '-p':
640                 if 'PDF' not in targets:
641                         targets.append ('PDF')
642         elif o == '--no-pdf':
643                 if 'PDF' in targets:
644                         targets.remove ('PDF')
645         elif o == '--no-ps':
646                 if 'PS' in targets:
647                         targets.remove ('PS')
648                 if 'PDF' in targets:
649                         targets.remove ('PDF')
650         elif o == '--keep' or o == '-k':
651                 keep_temp_dir_p = 1
652         elif o == '--debug':
653                 verbose_p = 1
654                 debug_p = 1 
655         elif o == '--no-lily':
656                 lily_p = 0
657         elif o == '--preview':
658                 preview_p = 1
659                 if 'PNG' not in targets:
660                         targets.append ('PNG')
661         elif o == '--preview-resolution':
662                 preview_resolution = string.atoi (a)
663         elif o == '--no-paper' or o == '-m':
664                 targets = ['MIDI'] 
665                 paper_p = 0
666         elif o == '--output' or o == '-o':
667                 output_name = a
668         elif o == '--safe-mode' or o == '-s':
669                 safe_mode_p = 1
670         elif o == '--set' or o == '-S':
671                 ss = string.split (a, '=')
672                 set_setting (extra_init, ss[0], ss[1])
673         elif o == '--verbose' or o == '-V':
674                 verbose_p = 1
675         elif o == '--version' or o == '-v':
676                 ly.identify (sys.stdout)
677                 sys.exit (0)
678         elif o == '--pdftex':
679                 latex_cmd = 'pdflatex'
680                 targets.remove ('DVI')
681                 targets.append ('PDFTEX')
682                 pdftex_p = 1
683                 tex_extension = '.pdftex'
684         elif o == '--warranty' or o == '-w':
685                 status = os.system ('%s -w' % lilypond_binary)
686                 if status:
687                         ly.warranty ()
688                 sys.exit (0)
689         elif o == '--html':
690                 html_p = 1
691         elif o == '--png':
692                 page_images_p = 1
693                 if 'PNG' not in targets:
694                         targets.append ('PNG')
695         else:
696                 unimplemented_option () # signal programming error
697
698 # Don't convert input files to abspath, rather prepend '.' to include
699 # path.
700 include_path.insert (0, '.')
701
702 # As a neat trick, add directory part of first input file
703 # to include path.  That way you can do without the clumsy -I in:
704
705 #    lilypond -I foe/bar/baz foo/bar/baz/baz.ly
706 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
707         include_path.append (os.path.dirname (files[0]))
708         
709 include_path = map (ly.abspath, include_path)
710
711 if files and (files[0] == '-' or output_name == '-'):
712         if len (files) == 1:
713                 pseudo_filter_p = 1
714                 output_name = 'lelie'
715                 if verbose_p:
716                         ly.progress (_ ("pseudo filter") + '\n')
717         else:
718                 ly.help ()
719                 ly.error (_ ("pseudo filter only for single input file"))
720                 ly.exit (2)
721                 
722 if not files:
723         ly.help ()
724         ly.error (_ ("no files specified on command line"))
725         ly.exit (2)
726
727 if 1:
728         ly.identify (sys.stderr)
729         ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
730         
731         original_output = output_name
732         
733         # Ugh, maybe make a setup () function
734         files = map (lambda x: ly.strip_extension (x, '.ly'), files)
735
736         # hmmm. Wish I'd 've written comments when I wrote this.
737         # now it looks complicated.
738         
739         (outdir, outbase) = ('','')
740         if not output_name:
741                 outbase = os.path.basename (files[0])
742                 outdir = ly.abspath ('.')
743         elif output_name[-1] == os.sep:
744                 outdir = ly.abspath (output_name)
745                 outbase = os.path.basename (files[0])
746         else:
747                 (outdir, outbase) = os.path.split (ly.abspath (output_name))
748
749         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
750                 output_name = ly.strip_extension (output_name, i)
751                 outbase = ly.strip_extension (outbase, i)
752
753         for i in files[:] + [output_name]:
754                 b = os.path.basename (i)
755                 if string.find (b, ' ') >= 0:
756                         ly.error (_ ("filename should not contain spaces: `%s'") % b)
757                         ly.exit (1)
758                         
759         if os.path.dirname (output_name) != '.':
760                 dep_prefix = os.path.dirname (output_name)
761         else:
762                 dep_prefix = 0
763
764         reldir = os.path.dirname (output_name)
765         if outdir != '.' and targets:
766                 ly.mkdir_p (outdir, 0777)
767
768         tmpdir = ly.setup_temp ()
769         ly.setup_environment ()
770         if safe_mode_p:
771                 os.environ['openout_any'] = 'p'
772
773         # to be sure, add tmpdir *in front* of inclusion path.
774         #os.environ['TEXINPUTS'] =  tmpdir + ':' + os.environ['TEXINPUTS']
775         os.chdir (tmpdir)
776
777         # We catch all exceptions, because we need to do stuff at exit:
778         #   * copy any successfully generated stuff from tempdir and
779         #     notify user of that
780         #   * cleanout tempdir
781         if lily_p:
782                 try:
783                         run_lilypond (files, dep_prefix)
784                 except:
785                         ### ARGH. This also catches python programming errors.
786                         ### this should only catch lilypond nonzero exit  status
787                         ### --hwn
788
789                         
790                         # TODO: friendly message about LilyPond setup/failing?
791                         #
792                         targets = []
793                         if verbose_p:
794                                 traceback.print_exc ()
795                         else:
796                                 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
797                                 
798         # Our LilyPond pseudo filter always outputs to 'lelie'
799         # have subsequent stages and use 'lelie' output.
800         if pseudo_filter_p:
801                 files[0] = 'lelie'
802
803         if 'PS.GZ'  in targets:
804                 targets.append ('PS')
805                 
806         if 'PNG' in targets and 'PS' not in targets:
807                 targets.append ('PS')
808         if 'PS' in targets and 'DVI' not in targets:
809                 targets.append('DVI')
810
811         if 'DVI' in targets:
812                 try:
813                         run_latex (files, outbase, extra_init)
814                         # unless: add --tex, or --latex?
815                         targets.remove ('TEX')
816                         targets.remove('LATEX')
817                 except:
818                         # TODO: friendly message about TeX/LaTeX setup,
819                         # trying to run tex/latex by hand
820                         if 'DVI' in targets:
821                                 targets.remove ('DVI')
822                         if 'PS' in targets:
823                                 targets.remove ('PS')
824                         if verbose_p:
825                                 traceback.print_exc ()
826
827         if 'PS' in targets:
828                 try:
829                         run_dvips (outbase, extra_init)
830                         
831                 except: 
832                         if 'PS' in targets:
833                                 targets.remove ('PS')
834                         if verbose_p:
835                                 traceback.print_exc ()
836                         else:
837                                 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
838
839         if preview_p:
840                 for score in find_tex_files (files, extra_init):
841                         preview_base = ly.strip_extension (score[0], '.tex')
842                         ly.make_ps_images (preview_base + '.preview.ps',
843                                            resolution=preview_resolution
844                                            )
845
846         if 'PDFTEX' in targets:
847                 try:
848                         run_latex (files, outbase, extra_init)
849                         # unless: add --tex, or --latex?
850                         targets.remove ('TEX')
851                         targets.remove ('LATEX')
852                         targets.remove ('PDFTEX')
853                         if 'PDF' not in targets:
854                                 targets.append('PDF')
855                 except:
856                         # TODO: friendly message about TeX/LaTeX setup,
857                         # trying to run tex/latex by hand
858                         if 'PDFTEX' in targets:
859                                 targets.remove ('PDFTEX')
860                         if 'PDF' in targets:
861                                 targets.remove ('PDF')
862                         if 'PS' in targets:
863                                 targets.remove ('PS')
864                         if verbose_p:
865                                 traceback.print_exc ()
866                         else:
867                                 ly.warning (_("Running LaTeX failed. Rerun with --verbose for a trace."))
868                                 
869         if page_images_p:
870                 ly.make_ps_images (outbase + '.ps' ,
871                                    resolution = preview_resolution
872                                    )
873
874         if pseudo_filter_p:
875                 main_target = 0
876                 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
877                         if i in targets:
878                                 main_target = i
879                                 break
880
881                 ly.progress (_ ("%s output to <stdout>...") % i)
882                 outname = outbase + '.' + string.lower (main_target)
883                 if os.path.isfile (outname):
884                         sys.stdout.write (open (outname).read ())
885                 elif verbose_p:
886                         ly.warning (_ ("can't find file: `%s'") % outname)
887                 targets = []
888                 ly.progress ('\n')
889                 
890         if 'PS.GZ' in targets:
891                 ly.system ("gzip *.ps") 
892                 targets.remove ('PS')
893
894         # Hmm, if this were a function, we could call it the except: clauses
895         files_found = []
896         for i in targets:
897                 ext = string.lower (i)
898
899                 pattern = '%s.%s' % (outbase, ext)
900                 if i == 'PNG':
901                         pattern  = '*.png' 
902                 ls = glob.glob (pattern)
903                 files_found += ls 
904                 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
905
906
907                 if ls:
908                         names = string.join (map (lambda x: "`%s'" % x, ls))
909                         ly.progress (_ ("%s output to %s...") % (i, names))
910                         ly.progress ('\n')
911                 elif verbose_p:
912                         ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
913
914         if html_p:
915                 make_html_menu_file (os.path.join (outdir, outbase + ".html"),
916                                      files_found)
917
918         os.chdir (original_dir)
919         ly.cleanup_temp ()
920
921         sys.exit (lilypond_error_p)