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