release commit
[lilypond.git] / scripts / lilypond.py
blob9d34ad5c6a4135cd812b84b76f4a5eb495627b21
1 #!@PYTHON@
3 # lilypond.py -- Run LilyPond, add titles to bare score, generate printable
4 # document
5 # Invokes: lilypond, latex (or pdflatex), dvips, ps2pdf, gs
6 #
7 # source file of the GNU LilyPond music typesetter
8 #
9 # (c) 1998--2003 Han-Wen Nienhuys <hanwen@cs.uu.nl>
10 # Jan Nieuwenhuizen <janneke@gnu.org>
12 # This is the third incarnation of lilypond, now renamed lilypond.
14 # Earlier incarnations of lilypond 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 lilypond:
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 * move versatile taglines,
42 \header {
43 beginfooter=\mutopiaPD
44 endfooter=\tagline -> 'lily was here <version>'
47 lilytagline (->lily was here), usertagline, copyright, lily-version
48 etc.
50 * head/header tagline/endfooter
52 * dvi from lilypond .tex output? This is hairy, because we create dvi
53 from lilypond .tex *and* header output.
55 * multiple \score blocks?
57 * Introduce verbosity levels
59 0 = QUIET: mute all command output, no lilypond progress
60 1 = BRIEF: mute all command output, only lilypond progress
61 2a = NORMAL: show only LilyPond command output, show lilypond progress
62 2b = NORMAL: show command output, show lilypond progress
63 3 = VERBOSE: show command output, run lilypond --verbose
64 4 = DEBUGGING: show all command output, run lilypond --verbose, print
65 environment and all kinds of client side debugging stuff
67 Currently, we only have 1 and 4, but we kludge to have 2a and 4.
68 '''
70 import operator
71 import stat
72 import string
73 import traceback
74 import glob
76 ################################################################
77 # Users of python modules should include this snippet
78 # and customize variables below.
80 # We'll suffer this path init stuff as long as we don't install our
81 # python packages in <prefix>/lib/pythonx.y (and don't kludge around
82 # it as we do with teTeX on Red Hat Linux: set some environment var
83 # (PYTHONPATH) in profile)
85 # If set, LILYPONDPREFIX must take prevalence
86 # if datadir is not set, we're doing a build and LILYPONDPREFIX
87 import getopt, os, sys
88 datadir = '@local_lilypond_datadir@'
89 if not os.path.isdir (datadir):
90 datadir = '@lilypond_datadir@'
91 if os.environ.has_key ('LILYPONDPREFIX') :
92 datadir = os.environ['LILYPONDPREFIX']
93 while datadir[-1] == os.sep:
94 datadir= datadir[:-1]
97 sys.path.insert (0, os.path.join (datadir, 'python'))
99 # Customize these
100 #if __name__ == '__main__':
102 import lilylib as ly
103 global _;_=ly._
104 global re;re = ly.re
106 # lilylib globals
107 program_name = 'lilypond'
108 program_version = '@TOPLEVEL_VERSION@'
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 ## do -P or -p by default?
119 ##help_summary = _ ("Run LilyPond using LaTeX for titling")
120 help_summary = _ ("Run LilyPond, add titles, generate printable document.")
121 copyright = ('Han-Wen Nienhuys <hanwen@cs.uu.nl',
122 'Jan Nieuwenhuizen <janneke@gnu.org')
124 option_definitions = [
125 ('', 'd', 'dependencies',
126 _ ("write Makefile dependencies for every input file")),
127 ('', 'h', 'help', _ ("print this help")),
128 ('', '', 'debug', _ ("print even more output")),
129 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
130 ('', 'k', 'keep',
131 _ ("keep all output, output to directory %s.dir") % program_name),
132 ('', '', 'no-lily', _ ("don't run LilyPond")),
133 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
134 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
135 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
136 (_ ('RES'), '', 'preview-resolution',
137 _ ("set the resolution of the preview to RES")),
138 ('', 'P', 'postscript', _ ("generate PostScript output")),
139 ('', '', 'png', _("generate PNG page images")),
140 ('', '', 'psgz', _("generate PS.GZ")),
141 # separate options for PDF / PS / DVI ?
142 ('', '', 'pdftex', _ ("use pdflatex to generate a PDF output")),
143 # FIXME: preview, picture; to indicate creation of a PNG?
144 ('', '', 'preview', _ ("make a picture of the first system")),
145 ('','', 'html', _("make HTML file with links to all output")),
146 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
147 ('', 'V', 'verbose', _ ("be verbose")),
148 ('', 'v', 'version', _ ("print version number")),
149 ('', 'w', 'warranty', _ ("show warranty and copyright")),
152 # other globals
153 preview_p = 0
154 page_images_p = 0
155 lilypond_error_p = 0
156 html_p = 0
158 # Pdftex support
159 pdftex_p = 0
160 latex_cmd = 'latex'
163 tex_extension = '.tex' ## yuk.
165 #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' }
167 lilypond_binary = os.path.join ('@bindir@', 'lilypond-bin')
169 # only use installed binary when we're installed too.
170 if '@bindir@' == ('@' + 'bindir@') or not os.path.exists (lilypond_binary):
171 lilypond_binary = 'lilypond-bin'
174 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
175 'footer', 'head', 'composer', 'arranger', 'instrument',
176 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
179 # init to empty; values here take precedence over values in the file
181 ## TODO: change name.
182 extra_init = {
183 'language' : [],
184 'latexheaders' : [],
185 'latexpackages' : ['geometry'],
187 # for geometry v3
188 'latexoptions' : ['compat2'],
190 'papersize' : [],
191 'pagenumber' : [1],
192 'textheight' : [],
193 'linewidth' : [],
194 'orientation' : [],
195 'unit' : ['pt'],
198 extra_fields = extra_init.keys ()
199 fields = layout_fields + extra_fields
201 include_path = ['.']
202 lily_p = 1
203 paper_p = 1
205 output_name = ''
207 # Output formats that lilypond should create
208 targets = ['DVI', 'LATEX', 'MIDI', 'TEX', 'PDF', 'PS']
210 track_dependencies_p = 0
211 dependency_files = []
213 #what a name.
214 def set_setting (dict, key, val):
215 try:
216 val = string.atoi (val)
217 except ValueError:
218 #ly.warning (_ ("invalid value: %s") % `val`)
219 pass
221 if type(val) == type ('hoi'):
222 try:
223 val = string.atof (val)
224 except ValueError:
225 #ly.warning (_ ("invalid value: %s") % `val`)
226 pass
228 try:
229 dict[key].append (val)
230 except KeyError:
231 ly.warning (_ ("no such setting: `%s'") % `key`)
232 dict[key] = [val]
235 def escape_shell (x):
236 return re.sub ("(\s|[`'\"\\\\])", r'\\\1',x)
239 def run_lilypond (files, dep_prefix):
240 def make_include_option (x):
241 return '-I %s' % escape_shell (x)
243 opts = ''
244 opts = opts + ' ' + string.join (map (make_include_option, include_path))
245 if pseudo_filter_p:
246 opts = opts + ' --output=lelie'
247 if paper_p:
248 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
249 fields))
250 else:
251 opts = opts + ' --no-paper'
253 if pdftex_p:
254 opts = opts + ' -f pdftex'
256 if track_dependencies_p:
257 opts = opts + " --dependencies"
258 if dep_prefix:
259 opts = opts + ' --dep-prefix=%s' % dep_prefix
261 fs = string.join (map (escape_shell, files))
263 global verbose_p
264 if verbose_p:
265 opts = opts + ' --verbose'
267 if debug_p:
268 ly.print_environment ()
270 cmd = string.join ((lilypond_binary, opts, fs))
271 status = ly.system (cmd, ignore_error = 1, progress_p = 1)
272 signal = 0x0f & status
273 exit_status = status >> 8
275 # 2 == user interrupt.
276 if signal and signal != 2:
277 sys.stderr.write ('\n\n')
278 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
279 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
280 ly.exit (status)
282 if status:
283 sys.stderr.write ('\n')
284 if len (files) == 1:
285 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
286 ly.exit (status)
287 else:
288 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
289 ly.error (_ ("Continuing..."))
290 global lilypond_error_p
291 lilypond_error_p = 1
294 def analyse_lilypond_output (filename, extra):
296 # urg
297 '''Grep FILENAME for interesting stuff, and
298 put relevant info into EXTRA.'''
299 filename = filename + tex_extension
300 ly.progress (_ ("Analyzing %s...") % filename)
301 s = open (filename).read ()
303 # search only the first 10k
304 s = s[:10240]
305 for x in extra_fields:
306 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
307 if m:
308 set_setting (extra, x, m.group (1))
309 ly.progress ('\n')
311 def find_tex_files_for_base (base, extra):
313 Find the \header fields dumped from BASE.
316 headerfiles = {}
317 for f in layout_fields:
318 fn = base + '.' + f
319 if os.path.exists (fn):
320 headerfiles[f] = fn
322 if os.path.exists (base +'.dep'):
323 dependency_files.append (base + '.dep')
325 for f in extra_fields:
326 fn =base + '.' + f
327 if os.path.exists (fn):
328 extra[f].append (open (fn).read ())
330 return (base + tex_extension, headerfiles)
333 def find_tex_files (files, extra):
335 Find all .tex files whose prefixes start with some name in FILES.
339 tfiles = []
341 for f in files:
342 x = 0
343 while 1:
344 fname = os.path.basename (f)
345 fname = ly.strip_extension (fname, '.ly')
346 if x:
347 fname = fname + '-%d' % x
349 if os.path.exists (fname + tex_extension):
350 tfiles.append (find_tex_files_for_base (fname, extra))
351 analyse_lilypond_output (fname, extra)
352 else:
353 break
355 x = x + 1
356 if not x:
357 fstr = string.join (files, ', ')
358 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
359 return tfiles
361 def one_latex_definition (defn, first):
362 s = '\n'
363 for (k,v) in defn[1].items ():
364 val = open (v).read ()
365 if (string.strip (val)):
366 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
367 else:
368 s = s + r'''\let\lilypond%s\relax''' % k
369 s = s + '\n'
371 if first:
372 s = s + '\\def\\mustmakelilypondtitle{}\n'
373 else:
374 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
376 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.
377 return s
380 ly_paper_to_latexpaper = {
381 'letter' : 'letterpaper',
382 'a3' : 'a3paper',
383 'a4' : 'a4paper',
384 'a5' : 'a5paper',
385 'a6' : 'a6paper',
386 'legal' : 'legalpaper',
387 'tabloid' : 'papersize={11in,17in}',
390 #TODO: should set textheight (enlarge) depending on papersize.
391 def global_latex_preamble (extra):
392 '''construct preamble from EXTRA,'''
393 s = ""
394 s = s + '% generation tag\n'
396 options = ''
399 if extra['latexoptions']:
400 options = options + ',' + extra['latexoptions'][-1]
402 s = s + '\\documentclass[%s]{article}\n' % options
404 if extra['language']:
405 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
408 s = s + '\\usepackage{%s}\n' \
409 % string.join (extra['latexpackages'], ',')
411 if extra['latexheaders']:
412 s = s + '\\include{%s}\n' \
413 % string.join (extra['latexheaders'], '}\n\\include{')
415 unit = extra['unit'][-1]
418 papersize = ''
419 if extra['papersize']:
420 try:
421 papersize = ly_paper_to_latexpaper[extra['papersize'][0]] + ','
422 except KeyError:
423 ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
424 pass
426 textheight = ''
427 if extra['textheight']:
428 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
430 orientation = 'portrait'
431 if extra['orientation']:
432 orientation = extra['orientation'][0]
434 # set sane geometry width (a4-width) for linewidth = -1.
435 maxlw = max (extra['linewidth'] + [-1])
436 if maxlw < 0:
437 # who the hell is 597 ?
438 linewidth = '597pt'
439 else:
440 linewidth = '%d%s' % (maxlw, unit)
441 s = s + '\geometry{%swidth=%s%s,includehead,bottom=20mm,headsep=2mm,top=12mm,headheight=2mm,footskip=2mm,%s}\n' % (papersize, linewidth, textheight, orientation)
444 if 'twoside' in extra['latexoptions'] :
445 s = s + '\geometry{twosideshift=4mm}\n'
447 s = s + r'''
448 \usepackage[latin1]{inputenc}
449 \input{titledefs}
452 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
453 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
454 s = s + '\\pagestyle{plain}\n'
455 else:
456 s = s + '\\pagestyle{empty}\n'
459 return s
462 def global_latex_definition (tfiles, extra):
463 '''construct preamble from EXTRA, dump Latex stuff for each
464 lily output file in TFILES after that, and return the Latex file constructed. '''
467 s = global_latex_preamble (extra) + '\\begin{document}\n'
468 s = s + '\\parindent 0pt\n'
469 s = s + '\\thispagestyle{firstpage}\n'
471 first = 1
472 for t in tfiles:
473 s = s + one_latex_definition (t, first)
474 first = 0
477 s = s + '\\thispagestyle{lastpage}\n'
478 s = s + '\\end{document}'
480 return s
482 def run_latex (files, outbase, extra):
484 '''Construct latex file, for FILES and EXTRA, dump it into
485 OUTBASE.latex. Run LaTeX on it.
487 RETURN VALUE
489 None
492 latex_fn = outbase + '.latex'
494 wfs = find_tex_files (files, extra)
495 s = global_latex_definition (wfs, extra)
497 f = open (latex_fn, 'w')
498 f.write (s)
499 f.close ()
501 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
503 # Ugh. (La)TeX writes progress and error messages on stdout
504 # Redirect to stderr
505 cmd = '(( %s >&2 ) >&- )' % cmd
506 status = ly.system (cmd, ignore_error = 1)
507 signal = 0xf & status
508 exit_status = status >> 8
510 if exit_status:
512 logstr = ''
513 try:
514 logstr = open (outbase + '.log').read ()
515 m = re.search ("\n!", logstr)
516 start = m.start (0)
517 logstr = logstr[start:start+200]
518 except:
519 pass
521 ly.error (_ ("LaTeX failed on the output file."))
522 ly.error (_ ("The error log is as follows:"))
523 sys.stderr.write (logstr + '\n')
524 ly.exit (1)
526 if preview_p:
527 # make a preview by rendering only the 1st line
528 # of each score
529 for score in find_tex_files (files, extra):
530 preview_base = ly.strip_extension (score[0], '.tex')
531 preview_fn = preview_base + '.preview.tex'
532 s = global_latex_definition ((score,), extra)
533 s = re.sub ('thispagestyle{firstpage}',
534 r'''thispagestyle{empty}%
535 \\def\\interscoreline{\\endinput}''', s)
536 s = re.sub ('thispagestyle{lastpage}',
537 r'''thispagestyle{empty}%
538 \\def\\interscoreline{\\endinput}''', s)
539 f = open (preview_fn, 'w')
540 f.write (s)
541 f.close ()
542 cmd = '%s \\\\nonstopmode \\\\input %s' \
543 % (latex_cmd, preview_fn)
544 ly.system (cmd)
547 def run_dvips (outbase, extra):
550 '''Run dvips using the correct options taken from EXTRA,
551 leaving a PS file in OUTBASE.ps
553 RETURN VALUE
555 None.
557 opts = ''
558 if extra['papersize']:
559 opts = opts + ' -t%s' % extra['papersize'][0]
561 if extra['orientation'] and extra['orientation'][0] == 'landscape':
562 opts = opts + ' -tlandscape'
565 if 'PDF' in targets:
566 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
568 pfa_file = None
569 if where:
570 try:
571 pfa_file = open (where, 'r')
572 except IOError:
573 pass
575 if pfa_file:
576 opts = opts + ' -Ppdf -G0 -u +lilypond.map'
577 else:
578 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
579 Using bitmap fonts instead. This will look bad.'''))
581 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
582 ly.system (cmd)
584 if preview_p:
585 for score in find_tex_files (files, extra):
586 preview_base = ly.strip_extension (score[0], '.tex')
587 cmd = 'dvips -E -Ppdf -u+lilypond.map -o%s %s' \
588 % (preview_base + '.preview.ps',
589 preview_base + '.preview.dvi')
590 ly.system (cmd)
592 if 'PDF' in targets:
593 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
594 ly.system (cmd)
596 def generate_dependency_file (depfile, outname):
597 df = open (depfile, 'w')
598 df.write (outname + ':' )
600 for d in dependency_files:
601 s = open (d).read ()
602 s = re.sub ('#[^\n]*\n', '', s)
603 s = re.sub (r'\\\n', ' ', s)
604 m = re.search ('.*:(.*)\n', s)
606 # ugh. Different targets?
607 if m:
608 df.write ( m.group (1) + ' ' )
610 df.write ('\n')
611 df.close ();
613 def find_file_in_path (path, name):
614 for d in string.split (path, os.pathsep):
615 if name in os.listdir (d):
616 return os.path.join (d, name)
618 # Added as functionality to lilypond, because lilypond may well need to do this
619 # in future too.
620 PS = '%!PS-Adobe'
621 def find_pfa_fonts (name):
622 s = open (name).read ()
623 if s[:len (PS)] != PS:
624 # no ps header?
625 ly.error (_ ("not a PostScript file: `%s\'" % name))
626 ly.exit (1)
627 here = 0
628 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
629 pfa = []
630 while m:
631 here = m.end (1)
632 pfa.append (m.group (1))
633 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
634 return pfa
637 def make_html_menu_file (html_file, files_found):
638 exts = {
639 'pdf' : "Print (PDF, %s)",
640 'ps.gz' : "Print (gzipped PostScript, %s)",
641 'png' : "View (PNG, %s)",
642 'midi' : "Listen (MIDI, %s)",
643 'ly' : "View source code (%s)",
645 html_str = ''
647 pages = filter (lambda x : re.search ('page[0-9]+.png', x),
648 files_found)
649 rest = filter (lambda x : not re.search ('page[0-9]+.png', x),
650 files_found)
652 preview = filter (lambda x: re.search ('.png$', x), rest)
653 if preview:
654 html_str = '<img src="%s">' % preview[0]
656 for p in pages:
657 page = re.sub ('.*page([0-9])+.*', 'View page \\1 (PNG picture, %s)\n', p)
658 page = page % 'unknown size'
660 html_str += '<li><a href="%s">%s</a>' % (p, page)
663 for e in ['pdf', 'ps.gz', 'midi', 'ly']:
664 fs = filter (lambda x: re.search ('.%s$' % e, x), rest)
665 for f in fs:
666 entry = exts[e] % 'unknown size' # todo
667 html_str += '<li><a href="%s">%s</a>\n\n' % (f, entry)
669 html_str += "\n\n</li>"
670 ly.progress (_("Writing HTML menu `%s'") % html_file)
671 ly.progress ('\n')
672 open (html_file, 'w').write (html_str)
674 ################################################################
675 ## MAIN
676 ################################################################
678 (sh, long) = ly.getopt_args (option_definitions)
679 try:
680 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
681 except getopt.error, s:
682 sys.stderr.write ('\n')
683 ly.error (_ ("getopt says: `%s\'" % s))
684 sys.stderr.write ('\n')
685 ly.help ()
686 ly.exit (2)
688 for opt in options:
689 o = opt[0]
690 a = opt[1]
692 if 0:
693 pass
694 elif o == '--help' or o == '-h':
695 ly.help ()
696 sys.exit (0)
697 elif o == '--find-pfa' or o == '-f':
698 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
699 files = map (lambda x:
700 find_file_in_path (os.environ['GS_FONTPATH'], x),
701 fonts)
702 print string.join (files, ' ')
703 sys.exit (0)
704 elif o == '--include' or o == '-I':
705 include_path.append (a)
706 elif o == '--postscript' or o == '-P':
707 targets.append ('PS')
708 elif o == '--no-ps':
709 targets.remove ('PS')
710 targets.remove ('PDF')
711 elif o == '--keep' or o == '-k':
712 keep_temp_dir_p = 1
713 elif o == '--debug':
714 verbose_p = 1
715 debug_p = 1
716 elif o == '--no-lily':
717 lily_p = 0
718 elif o == '--preview':
719 preview_p = 1
720 if 'PNG' not in targets:
721 targets.append ('PNG')
722 elif o == '--preview-resolution':
723 preview_resolution = string.atoi (a)
724 elif o == '--no-paper' or o == '-m':
725 targets = ['MIDI']
726 paper_p = 0
727 elif o == '--output' or o == '-o':
728 output_name = a
729 elif o == '--set' or o == '-s':
730 ss = string.split (a, '=')
731 set_setting (extra_init, ss[0], ss[1])
732 elif o == '--dependencies' or o == '-d':
733 track_dependencies_p = 1
734 elif o == '--verbose' or o == '-V':
735 verbose_p = 1
736 elif o == '--version' or o == '-v':
737 ly.identify (sys.stdout)
738 sys.exit (0)
739 elif o == '--pdftex':
740 latex_cmd = 'pdflatex'
741 targets.remove('DVI')
742 targets.append('PDFTEX')
743 pdftex_p = 1
744 tex_extension = '.pdftex'
745 elif o == '--warranty' or o == '-w':
746 status = os.system ('%s -w' % lilypond_binary)
747 if status:
748 ly.warranty ()
749 sys.exit (0)
750 elif o == '--html':
751 html_p = 1
752 elif o == '--png':
753 page_images_p = 1
754 if 'PNG' not in targets:
755 targets.append ('PNG')
756 elif o == '--psgz':
757 targets.append ('PS.GZ')
758 else:
759 unimplemented_option () # signal programming error
761 # Don't convert input files to abspath, rather prepend '.' to include
762 # path.
763 include_path.insert (0, '.')
765 # As a neat trick, add directory part of first input file
766 # to include path. That way you can do without the clumsy -I in:
768 # lilypond -I foe/bar/baz foo/bar/baz/baz.ly
769 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
770 include_path.append (os.path.dirname (files[0]))
772 include_path = map (ly.abspath, include_path)
774 if files and (files[0] == '-' or output_name == '-'):
775 if len (files) == 1:
776 pseudo_filter_p = 1
777 output_name = 'lelie'
778 if verbose_p:
779 ly.progress (_ ("pseudo filter") + '\n')
780 else:
781 ly.help ()
782 ly.error (_ ("pseudo filter only for single input file"))
783 ly.exit (2)
785 if not files:
786 ly.help ()
787 ly.error (_ ("no files specified on command line"))
788 ly.exit (2)
790 if 1:
791 ly.identify (sys.stderr)
792 ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
794 original_output = output_name
796 # Ugh, maybe make a setup () function
797 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
799 # hmmm. Wish I'd 've written comments when I wrote this.
800 # now it looks complicated.
802 (outdir, outbase) = ('','')
803 if not output_name:
804 outbase = os.path.basename (files[0])
805 outdir = ly.abspath ('.')
806 elif output_name[-1] == os.sep:
807 outdir = ly.abspath (output_name)
808 outbase = os.path.basename (files[0])
809 else:
810 (outdir, outbase) = os.path.split (ly.abspath (output_name))
812 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
813 output_name = ly.strip_extension (output_name, i)
814 outbase = ly.strip_extension (outbase, i)
816 for i in files[:] + [output_name]:
817 b = os.path.basename (i)
818 if string.find (b, ' ') >= 0:
819 ly.error (_ ("filename should not contain spaces: `%s'") % b)
820 ly.exit (1)
822 if os.path.dirname (output_name) != '.':
823 dep_prefix = os.path.dirname (output_name)
824 else:
825 dep_prefix = 0
827 reldir = os.path.dirname (output_name)
828 if outdir != '.' and (track_dependencies_p or targets):
829 ly.mkdir_p (outdir, 0777)
831 tmpdir = ly.setup_temp ()
832 ly.setup_environment ()
834 # to be sure, add tmpdir *in front* of inclusion path.
835 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
836 os.chdir (tmpdir)
838 # We catch all exceptions, because we need to do stuff at exit:
839 # * copy any successfully generated stuff from tempdir and
840 # notify user of that
841 # * cleanout tempdir
842 if lily_p:
843 try:
844 run_lilypond (files, dep_prefix)
845 except:
846 ### ARGH. This also catches python programming errors.
847 ### this should only catch lilypond nonzero exit status
848 ### --hwn
851 # TODO: friendly message about LilyPond setup/failing?
853 targets = []
854 if verbose_p:
855 traceback.print_exc ()
856 else:
857 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
859 # Our LilyPond pseudo filter always outputs to 'lelie'
860 # have subsequent stages and use 'lelie' output.
861 if pseudo_filter_p:
862 files[0] = 'lelie'
864 if 'PS.GZ' in targets:
865 targets.append ('PS')
867 if 'PNG' in targets and 'PS' not in targets:
868 targets.append ('PS')
869 if 'PS' in targets and 'DVI' not in targets:
870 targets.append('DVI')
872 if 'DVI' in targets:
873 try:
874 run_latex (files, outbase, extra_init)
875 # unless: add --tex, or --latex?
876 targets.remove ('TEX')
877 targets.remove('LATEX')
878 except:
879 # TODO: friendly message about TeX/LaTeX setup,
880 # trying to run tex/latex by hand
881 if 'DVI' in targets:
882 targets.remove ('DVI')
883 if 'PS' in targets:
884 targets.remove ('PS')
885 if verbose_p:
886 traceback.print_exc ()
888 if 'PS' in targets:
889 try:
890 run_dvips (outbase, extra_init)
892 except:
893 if 'PS' in targets:
894 targets.remove ('PS')
895 if verbose_p:
896 traceback.print_exc ()
897 else:
898 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
900 if preview_p:
901 for score in find_tex_files (files, extra_init):
902 preview_base = ly.strip_extension (score[0], '.tex')
903 ly.make_ps_images (preview_base + '.preview.ps',
904 resolution=preview_resolution
907 if 'PDFTEX' in targets:
908 try:
909 run_latex (files, outbase, extra_init)
910 # unless: add --tex, or --latex?
911 targets.remove ('TEX')
912 targets.remove ('LATEX')
913 targets.remove ('PDFTEX')
914 if 'PDF' not in targets:
915 targets.append('PDF')
916 except:
917 # TODO: friendly message about TeX/LaTeX setup,
918 # trying to run tex/latex by hand
919 if 'PDFTEX' in targets:
920 targets.remove ('PDFTEX')
921 if 'PDF' in targets:
922 targets.remove ('PDF')
923 if 'PS' in targets:
924 targets.remove ('PS')
925 if verbose_p:
926 traceback.print_exc ()
927 else:
928 ly.warning (_("Running LaTeX failed. Rerun with --verbose for a trace."))
930 if page_images_p:
931 ly.make_ps_images (outbase + '.ps' ,
932 resolution = preview_resolution
935 # add DEP to targets?
936 if track_dependencies_p:
937 depfile = os.path.join (outdir, outbase + '.dep')
938 generate_dependency_file (depfile, depfile)
939 if os.path.isfile (depfile):
940 ly.progress (_ ("dependencies output to `%s'...") %
941 depfile)
942 ly.progress ('\n')
944 if pseudo_filter_p:
945 main_target = 0
946 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
947 if i in targets:
948 main_target = i
949 break
951 ly.progress (_ ("%s output to <stdout>...") % i)
952 outname = outbase + '.' + string.lower (main_target)
953 if os.path.isfile (outname):
954 sys.stdout.write (open (outname).read ())
955 elif verbose_p:
956 ly.warning (_ ("can't find file: `%s'") % outname)
957 targets = []
958 ly.progress ('\n')
960 if 'PS.GZ' in targets:
961 ly.system ("gzip *.ps")
962 targets.remove ('PS')
964 # Hmm, if this were a function, we could call it the except: clauses
965 files_found = []
966 for i in targets:
967 ext = string.lower (i)
969 pattern = '%s.%s' % (outbase, ext)
970 if i == 'PNG':
971 pattern = '*.png'
972 ls = glob.glob (pattern)
973 files_found += ls
974 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
977 if ls:
978 names = string.join (map (lambda x: "`%s'" % x, ls))
979 ly.progress (_ ("%s output to %s...") % (i, names))
980 ly.progress ('\n')
981 elif verbose_p:
982 ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
984 if html_p:
985 make_html_menu_file (os.path.join (outdir, outbase + ".html"),
986 files_found)
988 os.chdir (original_dir)
989 ly.cleanup_temp ()
991 sys.exit (lilypond_error_p)