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 = os.path.split (sys.argv[0])[1]
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-layout', _ ("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'
160 lilypond_binary += ' --format=tex '
162 ## Init to empty; values here take precedence over values in the file
167 'latexpackages' : [],
174 header_fields = extra_init.keys ()
181 # Output formats that lilypond should create
182 targets = ['MIDI', 'PDF', 'PS']
183 dependency_files = []
186 def set_setting (dict, key, val):
188 val = string.atoi (val)
190 #ly.warning (_ ("invalid value: %s") % `val`)
193 if type(val) == type ('hoi'):
195 val = string.atof (val)
197 #ly.warning (_ ("invalid value: %s") % `val`)
201 dict[key].append (val)
203 ly.warning (_ ("no such setting: `%s'") % `key`)
207 def escape_shell (x):
208 return re.sub ("(\s|[`'\"\\\\])", r'\\\1',x)
210 def run_lilypond (files, dep_prefix):
212 def make_include_option (x):
213 return '-I %s' % escape_shell (x)
215 opts = ' ' + string.join (map (make_include_option, include_path))
219 opts += ' --output=lelie'
221 opts += ' ' + string.join (map (lambda x : '--header=' + x,
224 opts = opts + ' --no-layout'
226 opts = opts + ' --safe-mode'
228 fs = string.join (map (escape_shell, files))
230 opts = opts + " --format=ps"
234 opts = opts + ' --verbose'
237 ly.print_environment ()
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
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"))
252 global lilypond_error_p
253 sys.stderr.write ('\n')
255 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
259 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
260 ly.error (_ ("Continuing..."))
264 def analyse_lilypond_output (filename, extra):
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 ()
273 # search only the first 10k
275 for x in header_fields:
276 m = re.search (r'\\def\\lilypondlayout%s{([^}]*)}' % x, s)
278 set_setting (extra, x, m.group (1))
281 if s.find ('\\def\\lilypondclassic{1}') >= 0:
286 def find_tex_files_for_base (base, extra):
288 if os.path.exists (base +'.dep'):
289 dependency_files.append (base + '.dep')
291 for f in header_fields:
293 if os.path.exists (fn):
294 extra[f].append (open (fn).read ())
296 return (base + tex_extension, {})
299 def find_tex_files (files, extra):
301 Find all .tex files whose prefixes start with some name in FILES.
310 fname = os.path.basename (f)
311 fname = ly.strip_extension (fname, '.ly')
313 fname = fname + '-%d' % x
315 if os.path.exists (fname + tex_extension):
316 tfiles.append (find_tex_files_for_base (fname, extra))
317 analyse_lilypond_output (fname, extra)
323 fstr = string.join (files, ', ')
324 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
327 def one_latex_definition (defn, first):
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)
334 s += r'''\let\lilypond%s\relax''' % k
337 if classic_p and not first:
338 s += '\interscoreline'
341 s += '\\input %s\n' % defn[0]
345 ## FIXME: copied from tex/lilyponddefs.tex
347 %% Nullify [La]TeX page layout settings, page layout by LilyPond.
349 \\headheight0pt\\headsep0pt
351 \\evensidemargin\oddsidemargin
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
369 def global_latex_preamble (extra):
370 '''construct preamble from EXTRA,'''
377 if extra['latexoptions']:
378 options = options + ',' + extra['latexoptions'][-1]
380 s += '\\documentclass[%s]{article}\n' % options
386 if extra['linewidth']:
387 s += '\\def\\lypylinewidth{%s}\n' \
388 % extra['linewidth'][-1]
390 s += '\\let\\lypylinewidth\\texwidth\n'
391 s += '\\def\\lypyunit{%s}\n' % extra['unit'][-1]
393 if extra['language']:
394 s += '\\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
396 s += '\\usepackage{%s}\n' \
397 % string.join (extra['latexpackages'], ',')
399 if extra['latexheaders']:
400 s += '\\include{%s}\n' \
401 % string.join (extra['latexheaders'], '}\n\\include{')
403 unit = extra['unit'][-1]
405 # FIXME, must (only) from lilypond
407 \usepackage{inputenc}
412 s += CLASSIC_LATEX_PREAMBLE
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'
426 s += one_latex_definition (t, first)
428 s += '\\end{document}\n'
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.
436 latex_fn = outbase + '.latex'
438 wfs = find_tex_files (files, extra)
439 s = global_latex_definition (wfs, extra)
441 f = open (latex_fn, 'w')
445 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
447 # Ugh. (La)TeX writes progress and error messages on stdout
449 cmd = '(( %s >&2 ) >&- )' % cmd
450 status = ly.system (cmd, ignore_error = 1)
451 signal = 0xf & status
452 exit_status = status >> 8
458 logstr = open (outbase + '.log').read ()
459 m = re.search ("\n!", logstr)
461 logstr = logstr[start:start+200]
465 ly.error (_ ("LaTeX failed on the output file."))
466 ly.error (_ ("The error log is as follows:"))
467 sys.stderr.write (logstr + '\n')
471 # make a preview by rendering only the 1st line
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')
482 cmd = '%s \\\\nonstopmode \\\\input %s' \
483 % (latex_cmd, preview_fn)
487 def run_dvips (outbase, extra):
488 '''Run dvips using the correct options taken from EXTRA,
489 leaving a PS file in OUTBASE.ps
491 #FIXME: papersize, orientation must come from lilypond
493 if extra['papersize']:
494 opts = ' -t%s' % extra['papersize'][0]
496 if extra['orientation'] and extra['orientation'][0] == 'landscape':
497 opts = opts + ' -tlandscape'
500 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
505 pfa_file = open (where, 'r')
510 #opts = opts + ' -Ppdf -G0 -u +lm.map -u +lilypond.map'
511 opts = opts + ' -Ppdf -G0 -u +ec-mftrace.map -u +lilypond.map'
513 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
514 Using bitmap fonts instead. This will look bad.'''))
516 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
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')
527 def generate_dependency_file (depfile, outname):
528 df = open (depfile, 'w')
529 df.write (outname + ':' )
531 for d in dependency_files:
533 s = re.sub ('#[^\n]*\n', '', s)
534 s = re.sub (r'\\\n', ' ', s)
535 m = re.search ('.*:(.*)\n', s)
537 # ugh. Different targets?
539 df.write ( m.group (1) + ' ' )
544 def find_file_in_path (path, name):
545 for d in string.split (path, os.pathsep):
548 if name in os.listdir (d):
549 return os.path.join (d, name)
551 def find_pfa_fonts (name):
553 s = open (name).read ()
554 if s[:len (PS)] != PS:
556 ly.error (_ ("not a PostScript file: `%s\'" % name))
559 m = re.match ('.*?/([-a-zA-Z]*(feta|parmesan)[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
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)
567 ################################################################
569 ################################################################
571 (sh, long) = ly.getopt_args (option_definitions)
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')
587 elif o == '--help' or o == '-h':
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),
595 print string.join (files, ' ')
597 elif o == '--include' or o == '-I':
598 include_path.append (a)
599 elif o == '--latex' or o == '-l':
601 targets += ['DVI', 'LATEX', 'TEX']
602 elif o == '--postscript' or o == '-P':
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':
615 elif o == '--preview':
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':
624 elif o == '--output' or o == '-o':
626 elif o == '--safe-mode' or o == '-s':
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':
633 elif o == '--version' or o == '-v':
634 ly.identify (sys.stdout)
636 elif o == '--warranty' or o == '-w':
637 status = os.system ('%s -w' % lilypond_binary)
643 if 'PNG' not in targets:
644 targets.append ('PNG')
646 unimplemented_option () # signal programming error
648 # Don't convert input files to abspath, rather prepend '.' to include
650 include_path.insert (0, '.')
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:
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]))
659 include_path = map (ly.abspath, include_path)
661 if files and (files[0] == '-' or output_name == '-'):
664 output_name = 'lelie'
666 ly.progress (_ ("pseudo filter") + '\n')
669 ly.error (_ ("pseudo filter only for single input file"))
674 ly.error (_ ("no files specified on command line"))
678 ly.identify (sys.stderr)
679 ly.lilypond_version_check (lilypond_binary, '@TOPLEVEL_VERSION@')
681 original_output = output_name
683 # Ugh, maybe make a setup () function
684 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
686 # hmmm. Wish I'd 've written comments when I wrote this.
687 # now it looks complicated.
689 (outdir, outbase) = ('','')
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])
697 (outdir, outbase) = os.path.split (ly.abspath (output_name))
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)
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)
709 if os.path.dirname (output_name) != '.':
710 dep_prefix = os.path.dirname (output_name)
714 reldir = os.path.dirname (output_name)
715 if outdir != '.' and targets:
716 ly.mkdir_p (outdir, 0777)
718 tmpdir = ly.setup_temp ()
719 ly.setup_environment ()
721 os.environ['openout_any'] = 'p'
723 # to be sure, add tmpdir *in front* of inclusion path.
724 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
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
732 run_lilypond (files, dep_prefix)
734 ### ARGH. This also catches python programming errors.
735 ### this should only catch lilypond nonzero exit status
738 # TODO: friendly message about LilyPond setup/failing?
742 traceback.print_exc ()
744 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
746 # Our LilyPond pseudo filter always outputs to 'lelie'
747 # have subsequent stages and use 'lelie' output.
751 if 'PS.GZ' in targets:
752 targets.append ('PS')
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')
762 run_latex (files, outbase, extra_init)
763 # unless: add --tex, or --latex?
764 targets.remove ('TEX')
765 targets.remove('LATEX')
767 # TODO: friendly message about TeX/LaTeX setup,
768 # trying to run tex/latex by hand
770 targets.remove ('DVI')
772 targets.remove ('PS')
774 traceback.print_exc ()
776 if 'PS' in targets and "DVI" in targets:
778 run_dvips (outbase, extra_init)
782 targets.remove ('PS')
784 traceback.print_exc ()
786 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
790 papersize = 'a4' # fixme.
791 cmd = 'ps2pdf -sPAPERSIZE=%s %s.ps %s.pdf' % (papersize, outbase , outbase)
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
804 ly.make_ps_images (outbase + '.ps' ,
805 resolution = preview_resolution
810 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
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 ())
820 ly.warning (_ ("can't find file: `%s'") % outname)
824 if 'PS.GZ' in targets:
825 ly.system ("gzip *.ps")
826 targets.remove ('PS')
828 # Hmm, if this were a function, we could call it the except: clauses
831 ext = string.lower (i)
833 pattern = '%s.%s' % (outbase, ext)
836 ls = glob.glob (pattern)
838 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
842 names = string.join (map (lambda x: "`%s'" % x, ls))
843 ly.progress (_ ("%s output to %s...") % (i, names))
846 ly.warning (_ ("can't find file: `%s.%s'") % (outbase, ext))
849 os.chdir (original_dir)
852 sys.exit (lilypond_error_p)