2 # lilypond.py -- frontend for lilypond
4 # source file of the GNU LilyPond music typesetter
6 # (c) 1998--2004 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7 # Jan Nieuwenhuizen <janneke@gnu.org>
9 # Run lilypond, generate printable document
10 # Invokes: lilypond, latex (or pdflatex), dvips, ps2pdf, gs
13 # This is the third incarnation of ly2dvi, renamed to lilypond.
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)
20 # Note: gettext work best if we use ' for program/docstrings and "
21 # for gettextable strings.
22 # USE ''' for docstrings.
30 * figure out which set of command line options should make lilypond:
33 na: create latex only?
34 na: create tex and latex
35 default: create dvi only
36 na: create tex, latex and dvi
43 * dvi from lilypond .tex output? This is hairy, because we create dvi
44 from lilypond .tex *and* header output.
54 ################################################################
55 # Users of python modules should include this snippet
56 # and customize variables below.
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)
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:
75 sys.path.insert (0, os.path.join (datadir, 'python'))
78 #if __name__ == '__main__':
85 program_name = 'lilypond'
86 program_version = '@TOPLEVEL_VERSION@'
87 # input without \book, use classic latex definitions
92 original_dir = os.getcwd ()
93 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
95 preview_resolution = 90
98 TEX_PREAMBLE = '%%%% Generated by %(program_name)s (v%(program_version)s)' \
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')
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")),
114 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
116 _ ("keep all output, output to directory %s.dir") % program_name),
119 ('', '', 'no-lily', _ ("don't run LilyPond")),
121 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
123 (_ ("FILE"), 'o', 'output', _ ("write output to FILE")),
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")),
143 # need global variable. sys.exit() raises an exception, which is handled
150 tex_extension = '.tex' ## yuk.
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' }
154 lilypond_binary = os.path.join ('@bindir@', 'lilypond')
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'
161 ## Init to empty; values here take precedence over values in the file
166 'latexpackages' : [],
173 header_fields = extra_init.keys ()
180 # Output formats that lilypond should create
181 targets = ['MIDI', 'PDF', 'PS']
182 dependency_files = []
185 def set_setting (dict, key, val):
187 val = string.atoi (val)
189 #ly.warning (_ ("invalid value: %s") % `val`)
192 if type(val) == type ('hoi'):
194 val = string.atof (val)
196 #ly.warning (_ ("invalid value: %s") % `val`)
200 dict[key].append (val)
202 ly.warning (_ ("no such setting: `%s'") % `key`)
206 def escape_shell (x):
207 return re.sub ("(\s|[`'\"\\\\])", r'\\\1',x)
209 def run_lilypond (files, dep_prefix):
211 def make_include_option (x):
212 return '-I %s' % escape_shell (x)
214 opts = ' ' + string.join (map (make_include_option, include_path))
218 opts += ' --output=lelie'
220 opts += ' ' + string.join (map (lambda x : '--header=' + x,
223 opts = opts + ' --no-paper'
225 opts = opts + ' --safe-mode'
227 fs = string.join (map (escape_shell, files))
229 opts = opts + " --format=ps"
233 opts = opts + ' --verbose'
236 ly.print_environment ()
238 cmd = string.join ((lilypond_binary, opts, fs))
239 status = ly.system (cmd, ignore_error = 1, progress_p = 1)
240 signal = 0x0f & status
241 exit_status = status >> 8
243 # 2 == user interrupt.
244 if signal and signal != 2:
245 sys.stderr.write ('\n\n')
246 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
247 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
251 global lilypond_error_p
252 sys.stderr.write ('\n')
254 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
258 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
259 ly.error (_ ("Continuing..."))
263 def analyse_lilypond_output (filename, extra):
266 '''Grep FILENAME for interesting stuff, and
267 put relevant info into EXTRA.'''
268 filename = filename + tex_extension
269 ly.progress (_ ("Analyzing %s...") % filename)
270 s = open (filename).read ()
272 # search only the first 10k
274 for x in header_fields:
275 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}' % x, s)
277 set_setting (extra, x, m.group (1))
280 if s.find ('\\def\\lilypondclassic{1}') >= 0:
285 def find_tex_files_for_base (base, extra):
287 if os.path.exists (base +'.dep'):
288 dependency_files.append (base + '.dep')
290 for f in header_fields:
292 if os.path.exists (fn):
293 extra[f].append (open (fn).read ())
295 return (base + tex_extension, {})
298 def find_tex_files (files, extra):
300 Find all .tex files whose prefixes start with some name in FILES.
309 fname = os.path.basename (f)
310 fname = ly.strip_extension (fname, '.ly')
312 fname = fname + '-%d' % x
314 if os.path.exists (fname + tex_extension):
315 tfiles.append (find_tex_files_for_base (fname, extra))
316 analyse_lilypond_output (fname, extra)
322 fstr = string.join (files, ', ')
323 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
326 def one_latex_definition (defn, first):
328 for (k, v) in defn[1].items ():
329 val = open (v).read ()
330 if (string.strip (val)):
331 s += r'''\def\lilypond%s{%s}''' % (k, val)
333 s += r'''\let\lilypond%s\relax''' % k
336 if classic_p and not first:
337 s += '\interscoreline'
340 s += '\\input %s\n' % defn[0]
344 ## FIXME: copied from tex/lilyponddefs.tex
346 %% Nullify [La]TeX page layout settings, page layout by LilyPond.
348 \\headheight0pt\\headsep0pt
350 \\evensidemargin\oddsidemargin
353 CLASSIC_LATEX_PREAMBLE = '''
354 %% FIXME: cannot do this, dimens in header part of lilypond output
355 %% Center staves horizontally on page
356 \\ifdim\\lypylinewidth\\lypyunit > 0pt
357 \\hsize\\lypylinewidth\\lypyunit
358 \\newdimen\\lypytempdim
359 \\lypytempdim\\paperwidth
360 \\advance\\lypytempdim-\\the\\hsize
361 \\lypytempdim0.5\\lypytempdim
362 \\advance\\lypytempdim -1in
363 \\oddsidemargin\\lypytempdim
364 \\evensidemargin\\lypytempdim
368 def global_latex_preamble (extra):
369 '''construct preamble from EXTRA,'''
376 if extra['latexoptions']:
377 options = options + ',' + extra['latexoptions'][-1]
379 s += '\\documentclass[%s]{article}\n' % options
385 if extra['linewidth']:
386 s += '\\def\\lypylinewidth{%s}\n' \
387 % extra['linewidth'][-1]
389 s += '\\let\\lypylinewidth\\texwidth\n'
390 s += '\\def\\lypyunit{%s}\n' % extra['unit'][-1]
392 if extra['language']:
393 s += '\\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
395 s += '\\usepackage{%s}\n' \
396 % string.join (extra['latexpackages'], ',')
398 if extra['latexheaders']:
399 s += '\\include{%s}\n' \
400 % string.join (extra['latexheaders'], '}\n\\include{')
402 unit = extra['unit'][-1]
404 # FIXME, must (only) from lilypond
406 \usepackage{inputenc}
411 s += CLASSIC_LATEX_PREAMBLE
417 def global_latex_definition (tfiles, extra):
418 '''construct preamble from EXTRA, dump Latex stuff for each
419 lily output file in TFILES after that, and return the Latex file constructed. '''
420 s = global_latex_preamble (extra) + '\\begin{document}\n'
421 s += '\\parindent 0pt'
425 s += one_latex_definition (t, first)
427 s += '\\end{document}\n'
430 def run_latex (files, outbase, extra):
431 '''Construct latex file, for FILES and EXTRA, dump it into
432 OUTBASE.latex. Run LaTeX on it.
435 latex_fn = outbase + '.latex'
437 wfs = find_tex_files (files, extra)
438 s = global_latex_definition (wfs, extra)
440 f = open (latex_fn, 'w')
444 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
446 # Ugh. (La)TeX writes progress and error messages on stdout
448 cmd = '(( %s >&2 ) >&- )' % cmd
449 status = ly.system (cmd, ignore_error = 1)
450 signal = 0xf & status
451 exit_status = status >> 8
457 logstr = open (outbase + '.log').read ()
458 m = re.search ("\n!", logstr)
460 logstr = logstr[start:start+200]
464 ly.error (_ ("LaTeX failed on the output file."))
465 ly.error (_ ("The error log is as follows:"))
466 sys.stderr.write (logstr + '\n')
470 # make a preview by rendering only the 1st line
472 for score in find_tex_files (files, extra):
473 preview_base = ly.strip_extension (score[0], '.tex')
474 preview_fn = preview_base + '.preview.tex'
475 s = global_latex_definition ((score,), extra)
476 s = re.sub ('%%PREVIEW%%',
477 r'''\def\interscoreline{\endinput}''', s)
478 f = open (preview_fn, 'w')
481 cmd = '%s \\\\nonstopmode \\\\input %s' \
482 % (latex_cmd, preview_fn)
486 def run_dvips (outbase, extra):
487 '''Run dvips using the correct options taken from EXTRA,
488 leaving a PS file in OUTBASE.ps
490 #FIXME: papersize, orientation must come from lilypond
492 if extra['papersize']:
493 opts = ' -t%s' % extra['papersize'][0]
495 if extra['orientation'] and extra['orientation'][0] == 'landscape':
496 opts = opts + ' -tlandscape'
499 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
504 pfa_file = open (where, 'r')
509 #opts = opts + ' -Ppdf -G0 -u +lm.map -u +lilypond.map'
510 opts = opts + ' -Ppdf -G0 -u +ec-mftrace.map -u +lilypond.map'
512 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
513 Using bitmap fonts instead. This will look bad.'''))
515 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
519 for score in find_tex_files (files, extra):
520 preview_base = ly.strip_extension (score[0], '.tex')
521 cmd = 'dvips -E -Ppdf -u+ec-mftrace.map -u+lilypond.map -o%s %s' \
522 % (preview_base + '.preview.ps',
523 preview_base + '.preview.dvi')
526 def generate_dependency_file (depfile, outname):
527 df = open (depfile, 'w')
528 df.write (outname + ':' )
530 for d in dependency_files:
532 s = re.sub ('#[^\n]*\n', '', s)
533 s = re.sub (r'\\\n', ' ', s)
534 m = re.search ('.*:(.*)\n', s)
536 # ugh. Different targets?
538 df.write ( m.group (1) + ' ' )
543 def find_file_in_path (path, name):
544 for d in string.split (path, os.pathsep):
547 if name in os.listdir (d):
548 return os.path.join (d, name)
550 def find_pfa_fonts (name):
552 s = open (name).read ()
553 if s[:len (PS)] != PS:
555 ly.error (_ ("not a PostScript file: `%s\'" % name))
558 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
561 here = here + m.end (0)
562 pfa.append (m.group (1))
563 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
566 ################################################################
568 ################################################################
570 (sh, long) = ly.getopt_args (option_definitions)
572 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
573 except getopt.error, s:
574 sys.stderr.write ('\n')
575 ly.error (_ ("getopt says: `%s\'" % s))
576 sys.stderr.write ('\n')
586 elif o == '--help' or o == '-h':
589 elif o == '--find-pfa' or o == '-f':
590 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
591 files = map (lambda x:
592 find_file_in_path (os.environ['GS_FONTPATH'], x),
594 print string.join (files, ' ')
596 elif o == '--include' or o == '-I':
597 include_path.append (a)
598 elif o == '--latex' or o == '-l':
600 targets += ['DVI', 'LATEX', 'TEX']
601 elif o == '--postscript' or o == '-P':
603 targets.remove ('PDF')
604 if 'PS' not in targets:
605 targets.append ('PS')
606 elif o == '--pdf' or o == '-p':
607 if 'PDF' not in targets:
608 targets.append ('PDF')
609 elif o == '--keep' or o == '-k':
614 elif o == '--preview':
616 if 'PNG' not in targets:
617 targets.append ('PNG')
618 elif o == '--preview-resolution':
619 preview_resolution = string.atoi (a)
620 elif o == '--no-paper' or o == '-m':
623 elif o == '--output' or o == '-o':
625 elif o == '--safe-mode' or o == '-s':
627 elif o == '--set' or o == '-S':
628 ss = string.split (a, '=')
629 set_setting (extra_init, ss[0], ss[1])
630 elif o == '--verbose' or o == '-V':
632 elif o == '--version' or o == '-v':
633 ly.identify (sys.stdout)
635 elif o == '--warranty' or o == '-w':
636 status = os.system ('%s -w' % lilypond_binary)
642 if 'PNG' not in targets:
643 targets.append ('PNG')
645 unimplemented_option () # signal programming error
647 # Don't convert input files to abspath, rather prepend '.' to include
649 include_path.insert (0, '.')
651 # As a neat trick, add directory part of first input file
652 # to include path. That way you can do without the clumsy -I in:
654 # lilypond -I foe/bar/baz foo/bar/baz/baz.ly
655 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
656 include_path.append (os.path.dirname (files[0]))
658 include_path = map (ly.abspath, include_path)
660 if files and (files[0] == '-' or output_name == '-'):
663 output_name = 'lelie'
665 ly.progress (_ ("pseudo filter") + '\n')
668 ly.error (_ ("pseudo filter only for single input file"))
673 ly.error (_ ("no files specified on command line"))
677 ly.identify (sys.stderr)
678 ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
680 original_output = output_name
682 # Ugh, maybe make a setup () function
683 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
685 # hmmm. Wish I'd 've written comments when I wrote this.
686 # now it looks complicated.
688 (outdir, outbase) = ('','')
690 outbase = os.path.basename (files[0])
691 outdir = ly.abspath ('.')
692 elif output_name[-1] == os.sep:
693 outdir = ly.abspath (output_name)
694 outbase = os.path.basename (files[0])
696 (outdir, outbase) = os.path.split (ly.abspath (output_name))
698 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
699 output_name = ly.strip_extension (output_name, i)
700 outbase = ly.strip_extension (outbase, i)
702 for i in files[:] + [output_name]:
703 b = os.path.basename (i)
704 if string.find (b, ' ') >= 0:
705 ly.error (_ ("filename should not contain spaces: `%s'") % b)
708 if os.path.dirname (output_name) != '.':
709 dep_prefix = os.path.dirname (output_name)
713 reldir = os.path.dirname (output_name)
714 if outdir != '.' and targets:
715 ly.mkdir_p (outdir, 0777)
717 tmpdir = ly.setup_temp ()
718 ly.setup_environment ()
720 os.environ['openout_any'] = 'p'
722 # to be sure, add tmpdir *in front* of inclusion path.
723 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
726 # We catch all exceptions, because we need to do stuff at exit:
727 # * copy any successfully generated stuff from tempdir and
728 # notify user of that
731 run_lilypond (files, dep_prefix)
733 ### ARGH. This also catches python programming errors.
734 ### this should only catch lilypond nonzero exit status
737 # TODO: friendly message about LilyPond setup/failing?
741 traceback.print_exc ()
743 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
745 # Our LilyPond pseudo filter always outputs to 'lelie'
746 # have subsequent stages and use 'lelie' output.
750 if 'PS.GZ' in targets:
751 targets.append ('PS')
753 if 'PNG' in targets and 'PS' not in targets:
754 targets.append ('PS')
755 if latex_p and 'PS' in targets and 'DVI' not in targets:
756 targets.append('DVI')
761 run_latex (files, outbase, extra_init)
762 # unless: add --tex, or --latex?
763 targets.remove ('TEX')
764 targets.remove('LATEX')
766 # TODO: friendly message about TeX/LaTeX setup,
767 # trying to run tex/latex by hand
769 targets.remove ('DVI')
771 targets.remove ('PS')
773 traceback.print_exc ()
775 if 'PS' in targets and "DVI" in targets:
777 run_dvips (outbase, extra_init)
781 targets.remove ('PS')
783 traceback.print_exc ()
785 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
789 papersize = 'a4' # fixme.
790 cmd = 'ps2pdf -sPAPERSIZE=%s %s.ps %s.pdf' % (papersize, outbase , outbase)
795 for score in find_tex_files (files, extra_init):
796 preview_base = ly.strip_extension (score[0], '.tex')
797 ly.make_ps_images (preview_base + '.preview.ps',
798 resolution=preview_resolution
803 ly.make_ps_images (outbase + '.ps' ,
804 resolution = preview_resolution
809 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
814 ly.progress (_ ("%s output to <stdout>...") % i)
815 outname = outbase + '.' + string.lower (main_target)
816 if os.path.isfile (outname):
817 sys.stdout.write (open (outname).read ())
819 ly.warning (_ ("can't find file: `%s'") % outname)
823 if 'PS.GZ' in targets:
824 ly.system ("gzip *.ps")
825 targets.remove ('PS')
827 # Hmm, if this were a function, we could call it the except: clauses
830 ext = string.lower (i)
832 pattern = '%s.%s' % (outbase, ext)
835 ls = glob.glob (pattern)
837 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
841 names = string.join (map (lambda x: "`%s'" % x, ls))
842 ly.progress (_ ("%s output to %s...") % (i, names))
845 ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
848 os.chdir (original_dir)
851 sys.exit (lilypond_error_p)