* Documentation/topdocs/AUTHORS.texi (AUTHORS): Updated contact
[lilypond.git] / scripts / ly2dvi.py
blob1359a745b6c779fe2d5a0e3ed6eea4da95031b56
1 #!@PYTHON@
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--2002 Han-Wen Nienhuys <hanwen@cs.uu.nl>
10 # Jan Nieuwenhuizen <janneke@gnu.org>
12 # This is the third incarnation of ly2dvi.
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)
19 # Note: gettext work best if we use ' for docstrings and "
20 # for gettextable strings.
21 # --> DO NOT USE ''' for docstrings.
24 '''
25 TODO:
27 * figure out which set of command line options should make ly2dvi:
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
38 etc.
40 * for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
42 * move versatile taglines,
44 \header {
45 beginfooter=\mutopiaPD
46 endfooter=\tagline -> 'lily was here <version>'
49 lilytagline (->lily was here), usertagline, copyright, lily-version
50 etc.
52 * head/header tagline/endfooter
54 * dvi from lilypond .tex output? This is hairy, because we create dvi
55 from lilypond .tex *and* header output.
57 * multiple \score blocks?
59 * Introduce verbosity levels
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
69 Currently, we only have 1 and 4, but we kludge to have 2a and 4.
70 '''
72 import operator
73 import stat
74 import string
75 import traceback
76 import glob
78 ################################################################
79 # Users of python modules should include this snippet
80 # and customize variables below.
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)
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]
98 sys.path.insert (0, os.path.join (datadir, 'python'))
100 # Customize these
101 #if __name__ == '__main__':
103 import lilylib as ly
104 global _;_=ly._
105 global re;re = ly.re
107 # lilylib globals
108 program_name = 'ly2dvi'
109 verbose_p = 0
110 pseudo_filter_p = 0
111 original_dir = os.getcwd ()
112 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
113 keep_temp_dir_p = 0
114 preview_resolution = 90
115 debug_p = 0
117 ## FIXME
118 ## ly2dvi: silly name?
119 ## do -P or -p by default?
120 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
121 help_summary = _ ("Run LilyPond, add titles, generate printable document")
122 copyright = ('Han-Wen Nienhuys <hanwen@cs.uu.nl',
123 'Jan Nieuwenhuizen <janneke@gnu.org')
125 option_definitions = [
126 ('', 'd', 'dependencies',
127 _ ("write Makefile dependencies for every input file")),
128 ('', 'h', 'help', _ ("this help")),
129 ('', '', 'debug', _ ("print even more output")),
130 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
131 ('', 'k', 'keep',
132 _ ("keep all output, output to directory %s.dir") % program_name),
133 ('', '', 'no-lily', _ ("don't run LilyPond")),
134 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
135 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
136 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
137 (_ ('RES'), '', 'preview-resolution',
138 _ ("set the resolution of the preview to RES")),
139 ('', 'P', 'postscript', _ ("generate PostScript output")),
140 ('', '', 'png', _("generate PNG page images")),
141 ('', '', 'psgz', _("generate PS.GZ")),
142 ('', 'p', 'pdf', _ ("generate PDF output")),
143 ('', '', 'pdftex', _ ("use pdflatex to generate a PDF output")),
144 # FIXME: preview, picture; to indicate creation of a PNG?
145 ('', '', 'preview', _ ("make a picture of the first system")),
146 ('','', 'html', _("make HTML file with links to all output")),
147 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
148 ('', 'V', 'verbose', _ ("verbose")),
149 ('', 'v', 'version', _ ("print version number")),
150 ('', 'w', 'warranty', _ ("show warranty and copyright")),
153 # other globals
154 preview_p = 0
155 page_images_p = 0
156 lilypond_error_p = 0
157 html_p = 0
159 # Pdftex support
160 pdftex_p = 0
161 latex_cmd = 'latex'
164 tex_extension = '.tex' ## yuk.
166 #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' }
168 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
170 # only use installed binary when we're installed too.
171 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
172 lilypond_binary = 'lilypond'
175 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
176 'footer', 'head', 'composer', 'arranger', 'instrument',
177 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
180 # init to empty; values here take precedence over values in the file
182 ## TODO: change name.
183 extra_init = {
184 'language' : [],
185 'latexheaders' : [],
186 'latexpackages' : ['geometry'],
187 'latexoptions' : [],
188 'papersize' : [],
189 'pagenumber' : [1],
190 'textheight' : [],
191 'linewidth' : [],
192 'orientation' : [],
193 'unit' : ['pt'],
196 extra_fields = extra_init.keys ()
197 fields = layout_fields + extra_fields
199 include_path = ['.']
200 lily_p = 1
201 paper_p = 1
203 output_name = ''
205 # Output formats that ly2dvi should create
206 targets = ['DVI', 'LATEX', 'MIDI', 'TEX']
208 track_dependencies_p = 0
209 dependency_files = []
211 #what a name.
212 def set_setting (dict, key, val):
213 try:
214 val = string.atoi (val)
215 except ValueError:
216 #ly.warning (_ ("invalid value: %s") % `val`)
217 pass
219 if type(val) == type ('hoi'):
220 try:
221 val = string.atof (val)
222 except ValueError:
223 #ly.warning (_ ("invalid value: %s") % `val`)
224 pass
226 try:
227 dict[key].append (val)
228 except KeyError:
229 ly.warning (_ ("no such setting: `%s'") % `key`)
230 dict[key] = [val]
233 def run_lilypond (files, dep_prefix):
235 opts = ''
236 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
237 include_path))
238 if pseudo_filter_p:
239 opts = opts + ' --output=lelie'
240 if paper_p:
241 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
242 fields))
243 else:
244 opts = opts + ' --no-paper'
246 if pdftex_p:
247 opts = opts + ' -f pdftex'
249 if track_dependencies_p:
250 opts = opts + " --dependencies"
251 if dep_prefix:
252 opts = opts + ' --dep-prefix=%s' % dep_prefix
254 fs = string.join (files)
256 global verbose_p
257 if verbose_p:
258 opts = opts + ' --verbose'
260 if debug_p:
261 ly.print_environment ()
263 cmd = string.join ((lilypond_binary, opts, fs))
264 status = ly.system (cmd, ignore_error = 1, progress_p = 1)
265 signal = 0x0f & status
266 exit_status = status >> 8
268 # 2 == user interrupt.
269 if signal and signal != 2:
270 sys.stderr.write ('\n\n')
271 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
272 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
273 ly.exit (status)
275 if status:
276 sys.stderr.write ('\n')
277 if len (files) == 1:
278 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
279 ly.exit (status)
280 else:
281 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
282 ly.error (_ ("Continuing..."))
283 global lilypond_error_p
284 lilypond_error_p = 1
287 def analyse_lilypond_output (filename, extra):
289 # urg
290 '''Grep FILENAME for interesting stuff, and
291 put relevant info into EXTRA.'''
292 filename = filename + tex_extension
293 ly.progress (_ ("Analyzing %s...") % filename)
294 s = open (filename).read ()
296 # search only the first 10k
297 s = s[:10240]
298 for x in extra_fields:
299 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
300 if m:
301 set_setting (extra, x, m.group (1))
302 ly.progress ('\n')
304 def find_tex_files_for_base (base, extra):
306 Find the \header fields dumped from BASE.
309 headerfiles = {}
310 for f in layout_fields:
311 fn = base + '.' + f
312 if os.path.exists (fn):
313 headerfiles[f] = fn
315 if os.path.exists (base +'.dep'):
316 dependency_files.append (base + '.dep')
318 for f in extra_fields:
319 fn =base + '.' + f
320 if os.path.exists (fn):
321 extra[f].append (open (fn).read ())
323 return (base + tex_extension, headerfiles)
326 def find_tex_files (files, extra):
328 Find all .tex files whose prefixes start with some name in FILES.
332 tfiles = []
334 for f in files:
335 x = 0
336 while 1:
337 fname = os.path.basename (f)
338 fname = ly.strip_extension (fname, '.ly')
339 if x:
340 fname = fname + '-%d' % x
342 if os.path.exists (fname + tex_extension):
343 tfiles.append (find_tex_files_for_base (fname, extra))
344 analyse_lilypond_output (fname, extra)
345 else:
346 break
348 x = x + 1
349 if not x:
350 fstr = string.join (files, ', ')
351 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
352 return tfiles
354 def one_latex_definition (defn, first):
355 s = '\n'
356 for (k,v) in defn[1].items ():
357 val = open (v).read ()
358 if (string.strip (val)):
359 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
360 else:
361 s = s + r'''\let\lilypond%s\relax''' % k
362 s = s + '\n'
364 if first:
365 s = s + '\\def\\mustmakelilypondtitle{}\n'
366 else:
367 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
369 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.
370 return s
373 ly_paper_to_latexpaper = {
374 'letter' : 'letterpaper',
375 'a3' : 'a3paper',
376 'a4' : 'a4paper',
377 'a5' : 'a5paper',
378 'a6' : 'a6paper',
381 #TODO: should set textheight (enlarge) depending on papersize.
382 def global_latex_preamble (extra):
383 '''construct preamble from EXTRA,'''
384 s = ""
385 s = s + '% generation tag\n'
387 options = ''
390 if extra['papersize']:
391 try:
392 options = ly_paper_to_latexpaper[extra['papersize'][0]]
393 except KeyError:
394 ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
395 pass
397 if extra['latexoptions']:
398 options = options + ',' + extra['latexoptions'][-1]
400 s = s + '\\documentclass[%s]{article}\n' % options
402 if extra['language']:
403 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
406 s = s + '\\usepackage{%s}\n' \
407 % string.join (extra['latexpackages'], ',')
409 if extra['latexheaders']:
410 s = s + '\\include{%s}\n' \
411 % string.join (extra['latexheaders'], '}\n\\include{')
413 unit = extra['unit'][-1]
415 textheight = ''
416 if extra['textheight']:
417 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
419 orientation = 'portrait'
420 if extra['orientation']:
421 orientation = extra['orientation'][0]
423 # set sane geometry width (a4-width) for linewidth = -1.
424 maxlw = max (extra['linewidth'] + [-1])
425 if maxlw < 0:
426 # who the hell is 597 ?
427 linewidth = '597pt'
428 else:
429 linewidth = '%d%s' % (maxlw, unit)
430 s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
432 if extra['latexoptions']:
433 s = s + '\geometry{twosideshift=4mm}\n'
435 s = s + r'''
436 \usepackage[latin1]{inputenc}
437 \input{titledefs}
440 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
441 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
442 s = s + '\\pagestyle{plain}\n'
443 else:
444 s = s + '\\pagestyle{empty}\n'
447 return s
450 def global_latex_definition (tfiles, extra):
451 '''construct preamble from EXTRA, dump Latex stuff for each
452 lily output file in TFILES after that, and return the Latex file constructed. '''
455 s = global_latex_preamble (extra) + '\\begin{document}\n'
456 s = s + '\\parindent 0pt\n'
457 s = s + '\\thispagestyle{firstpage}\n'
459 first = 1
460 for t in tfiles:
461 s = s + one_latex_definition (t, first)
462 first = 0
465 s = s + '\\thispagestyle{lastpage}\n'
466 s = s + '\\end{document}'
468 return s
470 def run_latex (files, outbase, extra):
472 '''Construct latex file, for FILES and EXTRA, dump it into
473 OUTBASE.latex. Run LaTeX on it.
475 RETURN VALUE
477 None
480 latex_fn = outbase + '.latex'
482 wfs = find_tex_files (files, extra)
483 s = global_latex_definition (wfs, extra)
485 f = open (latex_fn, 'w')
486 f.write (s)
487 f.close ()
489 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
490 # Ugh. (La)TeX writes progress and error messages on stdout
491 # Redirect to stderr
492 cmd += ' 1>/dev/stderr'
493 status = ly.system (cmd, ignore_error = 1)
494 signal = 0xf & status
495 exit_status = status >> 8
497 if exit_status:
499 logstr = ''
500 try:
501 logstr = open (outbase + '.log').read ()
502 m = re.search ("\n!", logstr)
503 start = m.start (0)
504 logstr = logstr[start:start+200]
505 except:
506 pass
508 ly.error (_ ("LaTeX failed on the output file."))
509 ly.error (_ ("The error log is as follows:"))
510 sys.stderr.write (logstr + '\n')
511 ly.exit (1)
513 if preview_p:
514 # make a preview by rendering only the 1st line.
515 preview_fn = outbase + '.preview.tex'
516 f = open (preview_fn, 'w')
517 wfs = find_tex_files (files, extra)
518 s = global_latex_definition (wfs, extra)
520 s = re.sub ('thispagestyle{firstpage}', r'''thispagestyle{empty}%
521 \\def\\interscoreline{\\endinput}''',s )
522 s = re.sub ('thispagestyle{lastpage}', r'''thispagestyle{empty}%
523 \\def\\interscoreline{\\endinput}''',s )
524 f.write (s)
525 f.close()
526 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
527 ly.system (cmd)
530 def run_dvips (outbase, extra):
533 '''Run dvips using the correct options taken from EXTRA,
534 leaving a PS file in OUTBASE.ps
536 RETURN VALUE
538 None.
540 opts = ''
541 if extra['papersize']:
542 opts = opts + ' -t%s' % extra['papersize'][0]
544 if extra['orientation'] and extra['orientation'][0] == 'landscape':
545 opts = opts + ' -tlandscape'
548 if 'PDF' in targets:
549 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
551 pfa_file = None
552 if where:
553 try:
554 pfa_file = open (where, 'r')
555 except IOError:
556 pass
558 if pfa_file:
559 opts = opts + ' -Ppdf -G0 -u +lilypond.map'
560 else:
561 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
562 Using bitmap fonts instead. This will look bad.'''))
564 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
565 ly.system (cmd)
567 if preview_p:
568 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')
569 ly.system (cmd)
571 if 'PDF' in targets:
572 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
573 ly.system (cmd)
575 def generate_dependency_file (depfile, outname):
576 df = open (depfile, 'w')
577 df.write (outname + ':' )
579 for d in dependency_files:
580 s = open (d).read ()
581 s = re.sub ('#[^\n]*\n', '', s)
582 s = re.sub (r'\\\n', ' ', s)
583 m = re.search ('.*:(.*)\n', s)
585 # ugh. Different targets?
586 if m:
587 df.write ( m.group (1) + ' ' )
589 df.write ('\n')
590 df.close ();
592 def find_file_in_path (path, name):
593 for d in string.split (path, os.pathsep):
594 if name in os.listdir (d):
595 return os.path.join (d, name)
597 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
598 # in future too.
599 PS = '%!PS-Adobe'
600 def find_pfa_fonts (name):
601 s = open (name).read ()
602 if s[:len (PS)] != PS:
603 # no ps header?
604 ly.error (_ ("not a PostScript file: `%s\'" % name))
605 ly.exit (1)
606 here = 0
607 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
608 pfa = []
609 while m:
610 here = m.end (1)
611 pfa.append (m.group (1))
612 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
613 return pfa
616 def make_html_menu_file (html_file, files_found):
617 exts = {
618 'pdf' : "Print (PDF, %s)",
619 'ps.gz' : "Print (gzipped PostScript, %s)",
620 'png' : "View (PNG, %s)",
621 'midi' : "Listen (MIDI, %s)",
622 'ly' : "View source code (%s)",
624 html_str = ''
626 pages = filter (lambda x : re.search ('page[0-9]+.png', x),
627 files_found)
628 rest = filter (lambda x : not re.search ('page[0-9]+.png', x),
629 files_found)
631 preview = filter (lambda x: re.search ('.png$', x), rest)
632 if preview:
633 html_str = '<img src="%s">' % preview[0]
635 for p in pages:
636 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
637 page = page % 'unknown size'
639 html_str += '<li><a href="%s">%s</a>' % (p, page)
642 for e in ['pdf', 'ps.gz', 'midi', 'ly']:
643 fs = filter (lambda x: re.search ('.%s$' % e, x), rest)
644 for f in fs:
645 entry = exts[e] % 'unknown size' # todo
646 html_str += '<li><a href="%s">%s</a>\n\n' % (f, entry)
648 html_str += "\n\n</li>"
649 ly.progress (_("Writing HTML menu `%s'") % html_file)
650 ly.progress ('\n')
651 open (html_file, 'w').write (html_str)
653 ################################################################
654 ## MAIN
655 ################################################################
657 (sh, long) = ly.getopt_args (option_definitions)
658 try:
659 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
660 except getopt.error, s:
661 sys.stderr.write ('\n')
662 ly.error (_ ("getopt says: `%s\'" % s))
663 sys.stderr.write ('\n')
664 ly.help ()
665 ly.exit (2)
667 for opt in options:
668 o = opt[0]
669 a = opt[1]
671 if 0:
672 pass
673 elif o == '--help' or o == '-h':
674 ly.help ()
675 sys.exit (0)
676 elif o == '--find-pfa' or o == '-f':
677 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
678 files = map (lambda x:
679 find_file_in_path (os.environ['GS_FONTPATH'], x),
680 fonts)
681 print string.join (files, ' ')
682 sys.exit (0)
683 elif o == '--include' or o == '-I':
684 include_path.append (a)
685 elif o == '--postscript' or o == '-P':
686 targets.append ('PS')
687 elif o == '--pdf' or o == '-p':
688 targets.append ('PS')
689 targets.append ('PDF')
690 elif o == '--keep' or o == '-k':
691 keep_temp_dir_p = 1
692 elif o == '--debug':
693 verbose_p = 1
694 debug_p = 1
695 elif o == '--no-lily':
696 lily_p = 0
697 elif o == '--preview':
698 preview_p = 1
699 if 'PNG' not in targets:
700 targets.append ('PNG')
701 elif o == '--preview-resolution':
702 preview_resolution = string.atoi (a)
703 elif o == '--no-paper' or o == '-m':
704 targets = ['MIDI']
705 paper_p = 0
706 elif o == '--output' or o == '-o':
707 output_name = a
708 elif o == '--set' or o == '-s':
709 ss = string.split (a, '=')
710 set_setting (extra_init, ss[0], ss[1])
711 elif o == '--dependencies' or o == '-d':
712 track_dependencies_p = 1
713 elif o == '--verbose' or o == '-V':
714 verbose_p = 1
715 elif o == '--version' or o == '-v':
716 ly.identify (sys.stdout)
717 sys.exit (0)
718 elif o == '--pdftex':
719 latex_cmd = 'pdflatex'
720 targets.remove('DVI')
721 targets.append('PDFTEX')
722 pdftex_p = 1
723 tex_extension = '.pdftex'
724 elif o == '--warranty' or o == '-w':
725 status = os.system ('%s -w' % lilypond_binary)
726 if status:
727 ly.warranty ()
728 sys.exit (0)
729 elif o == '--html':
730 html_p = 1
731 elif o == '--png':
732 page_images_p = 1
733 if 'PNG' not in targets:
734 targets.append ('PNG')
735 elif o == '--psgz':
736 targets.append ('PS.GZ')
737 else:
738 unimplemented_option () # signal programming error
740 # Don't convert input files to abspath, rather prepend '.' to include
741 # path.
742 include_path.insert (0, '.')
744 # As a neat trick, add directory part of first input file
745 # to include path. That way you can do without the clumsy -I in:
747 # ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
748 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
749 include_path.append (os.path.dirname (files[0]))
751 include_path = map (ly.abspath, include_path)
753 if files and (files[0] == '-' or output_name == '-'):
754 if len (files) == 1:
755 pseudo_filter_p = 1
756 output_name = 'lelie'
757 if verbose_p:
758 ly.progress (_ ("pseudo filter") + '\n')
759 else:
760 ly.help ()
761 ly.error (_ ("pseudo filter only for single input file"))
762 ly.exit (2)
764 if not files:
765 ly.help ()
766 ly.error (_ ("no files specified on command line"))
767 ly.exit (2)
769 if 1:
770 ly.identify (sys.stderr)
771 original_output = output_name
773 # Ugh, maybe make a setup () function
774 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
776 # hmmm. Wish I'd 've written comments when I wrote this.
777 # now it looks complicated.
779 (outdir, outbase) = ('','')
780 if not output_name:
781 outbase = os.path.basename (files[0])
782 outdir = ly.abspath ('.')
783 elif output_name[-1] == os.sep:
784 outdir = ly.abspath (output_name)
785 outbase = os.path.basename (files[0])
786 else:
787 (outdir, outbase) = os.path.split (ly.abspath (output_name))
789 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
790 output_name = ly.strip_extension (output_name, i)
791 outbase = ly.strip_extension (outbase, i)
793 for i in files[:] + [output_name]:
794 if string.find (i, ' ') >= 0:
795 ly.error (_ ("filename should not contain spaces: `%s'") %
797 ly.exit (1)
799 if os.path.dirname (output_name) != '.':
800 dep_prefix = os.path.dirname (output_name)
801 else:
802 dep_prefix = 0
804 reldir = os.path.dirname (output_name)
805 if outdir != '.' and (track_dependencies_p or targets):
806 ly.mkdir_p (outdir, 0777)
808 tmpdir = ly.setup_temp ()
809 ly.setup_environment ()
811 # to be sure, add tmpdir *in front* of inclusion path.
812 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
813 os.chdir (tmpdir)
815 # We catch all exceptions, because we need to do stuff at exit:
816 # * copy any successfully generated stuff from tempdir and
817 # notify user of that
818 # * cleanout tempdir
819 if lily_p:
820 try:
821 run_lilypond (files, dep_prefix)
822 except:
823 ### ARGH. This also catches python programming errors.
824 ### this should only catch lilypond nonzero exit status
825 ### --hwn
828 # TODO: friendly message about LilyPond setup/failing?
830 targets = []
831 if verbose_p:
832 traceback.print_exc ()
833 else:
834 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
836 # Our LilyPond pseudo filter always outputs to 'lelie'
837 # have subsequent stages and use 'lelie' output.
838 if pseudo_filter_p:
839 files[0] = 'lelie'
841 if 'PS.GZ' in targets:
842 targets.append ('PS')
844 if 'PNG' in targets and 'PS' not in targets:
845 targets.append ('PS')
846 if 'PS' in targets and 'DVI' not in targets:
847 targets.append('DVI')
849 if 'DVI' in targets:
850 try:
851 run_latex (files, outbase, extra_init)
852 # unless: add --tex, or --latex?
853 targets.remove ('TEX')
854 targets.remove('LATEX')
855 except:
856 # TODO: friendly message about TeX/LaTeX setup,
857 # trying to run tex/latex by hand
858 if 'DVI' in targets:
859 targets.remove ('DVI')
860 if 'PS' in targets:
861 targets.remove ('PS')
862 if verbose_p:
863 traceback.print_exc ()
865 if 'PS' in targets:
866 try:
867 run_dvips (outbase, extra_init)
869 except:
870 if 'PS' in targets:
871 targets.remove ('PS')
872 if verbose_p:
873 traceback.print_exc ()
874 else:
875 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
877 if preview_p:
878 ly.make_preview (outbase)
880 if 'PDFTEX' in targets:
881 try:
882 run_latex (files, outbase, extra_init)
883 # unless: add --tex, or --latex?
884 targets.remove ('TEX')
885 targets.remove ('LATEX')
886 targets.remove ('PDFTEX')
887 if 'PDF' not in targets:
888 targets.append('PDF')
889 except:
890 # TODO: friendly message about TeX/LaTeX setup,
891 # trying to run tex/latex by hand
892 if 'PDFTEX' in targets:
893 targets.remove ('PDFTEX')
894 if 'PDF' in targets:
895 targets.remove ('PDF')
896 if 'PS' in targets:
897 targets.remove ('PS')
898 if verbose_p:
899 traceback.print_exc ()
900 else:
901 ly.warning (_("Running LaTeX falied. Rerun with --verbose for a trace."))
903 if page_images_p:
904 ly.make_page_images (outbase)
906 # add DEP to targets?
907 if track_dependencies_p:
908 depfile = os.path.join (outdir, outbase + '.dep')
909 generate_dependency_file (depfile, depfile)
910 if os.path.isfile (depfile):
911 ly.progress (_ ("dependencies output to `%s'...") %
912 depfile)
913 ly.progress ('\n')
915 if pseudo_filter_p:
916 main_target = 0
917 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
918 if i in targets:
919 main_target = i
920 break
922 ly.progress (_ ("%s output to <stdout>...") % i)
923 outname = outbase + '.' + string.lower (main_target)
924 if os.path.isfile (outname):
925 sys.stdout.write (open (outname).read ())
926 elif verbose_p:
927 ly.warning (_ ("can't find file: `%s'") % outname)
928 targets = []
929 ly.progress ('\n')
931 if 'PS.GZ' in targets:
932 ly.system ("gzip *.ps")
933 targets.remove ('PS')
935 # Hmm, if this were a function, we could call it the except: clauses
936 files_found = []
937 for i in targets:
938 ext = string.lower (i)
940 pattern = '%s.%s' % (outbase, ext)
941 if i == 'PNG':
942 pattern = '*.png'
943 ls = glob.glob (pattern)
944 files_found += ls
945 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
948 if ls:
949 names = string.join (map (lambda x: "`%s'" % x, ls))
950 ly.progress (_ ("%s output to %s...") % (i, names))
951 ly.progress ('\n')
952 elif verbose_p:
953 ly.warning (_ ("can't find file: `%s'") % outname)
955 if html_p:
956 make_html_menu_file (os.path.join (outdir, outbase + ".html"), files_found)
958 os.chdir (original_dir)
959 ly.cleanup_temp ()
961 sys.exit (lilypond_error_p)