3 # ly2dvi.py -- Run LilyPond, add titles to bare score, generate printable
5 # Invokes: lilypond, latex (or pdflatex), dvips, ps2pdf, gs
7 # source file of the GNU LilyPond music typesetter
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.
27 * figure out which set of command line options should make ly2dvi:
30 na: create latex only?
31 na: create tex and latex
32 default: create dvi only
33 na: create tex, latex and dvi
40 * for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
43 * move versatile taglines,
46 beginfooter=\mutopiaPD
47 endfooter=\tagline -> 'lily was here <version>'
50 lilytagline (->lily was here), usertagline, copyright, lily-version
53 * head/header tagline/endfooter
55 * dvi from lilypond .tex output? This is hairy, because we create dvi
56 from lilypond .tex *and* header output.
58 * multiple \score blocks?
60 * Introduce verbosity levels
62 0 = QUIET: mute all command output, no ly2dvi progress
63 1 = BRIEF: mute all command output, only ly2dvi progress
64 2a = NORMAL: show only LilyPond command output, show ly2dvi progress
65 2b = NORMAL: show command output, show ly2dvi progress
66 3 = VERBOSE: show command output, run lilypond --verbose
67 4 = DEBUGGING: show all command output, run lilypond --verbose, print
68 environment and all kinds of client side debugging stuff
70 Currently, we only have 1 and 4, but we kludge to have 2a and 4.
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:
98 sys.path.insert (0, os.path.join (datadir, 'python'))
101 #if __name__ == '__main__':
108 program_name = 'ly2dvi'
111 original_dir = os.getcwd ()
112 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
114 preview_resolution = 90
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")),
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 ('', 'p', 'pdf', _ ("generate PDF output")),
141 ('', '', 'pdftex', _ ("use pdflatex to generate a PDF output")),
142 # FIXME: preview, picture; to indicate creation of a PNG?
143 ('', '', 'preview', _ ("make a picture of the first system")),
144 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
145 ('', 'V', 'verbose', _ ("verbose")),
146 ('', 'v', 'version', _ ("print version number")),
147 ('', 'w', 'warranty', _ ("show warranty and copyright")),
157 tex_extension = '.tex'
159 # Debugging support -- do we need this?
160 lilypond_cmd = 'lilypond'
161 #lilypond_cmd = 'valgrind --suppressions=%(home)s/usr/src/guile-1.6.supp --num-callers=10 %(home)s/usr/src/lilypond/lily/out/lilypond '% { 'home' : '/home/hanwen' }
164 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
165 'footer', 'head', 'composer', 'arranger', 'instrument',
166 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
169 # init to empty; values here take precedence over values in the file
171 ## TODO: change name.
175 'latexpackages' : ['geometry'],
185 extra_fields = extra_init.keys ()
186 fields = layout_fields + extra_fields
194 # Output formats that ly2dvi should create
195 targets = ['DVI', 'LATEX', 'MIDI', 'TEX']
197 track_dependencies_p = 0
198 dependency_files = []
201 def set_setting (dict, key, val):
203 val = string.atoi (val)
205 #ly.warning (_ ("invalid value: %s") % `val`)
208 if type(val) == type ('hoi'):
210 val = string.atof (val)
212 #ly.warning (_ ("invalid value: %s") % `val`)
216 dict[key].append (val)
218 ly.warning (_ ("no such setting: `%s'") % `key`)
222 def run_lilypond (files, dep_prefix):
225 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
228 opts = opts + ' --output=lelie'
230 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
233 opts = opts + ' --no-paper'
236 opts = opts + ' -f pdftex'
238 if track_dependencies_p:
239 opts = opts + " --dependencies"
241 opts = opts + ' --dep-prefix=%s' % dep_prefix
243 fs = string.join (files)
247 opts = opts + ' --verbose'
250 ly.print_environment ()
252 cmd = string.join ((lilypond_cmd,opts, fs))
253 status = ly.system (cmd, ignore_error = 1, progress_p = 1)
254 signal = 0x0f & status
255 exit_status = status >> 8
257 # 2 == user interrupt.
258 if signal and signal != 2:
259 sys.stderr.write ('\n\n')
260 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
261 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
265 sys.stderr.write ('\n')
267 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
270 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
271 ly.error (_ ("Continuing..."))
272 global lilypond_error_p
276 def analyse_lilypond_output (filename, extra):
279 '''Grep FILENAME for interesting stuff, and
280 put relevant info into EXTRA.'''
281 filename = filename+tex_extension
282 ly.progress (_ ("Analyzing %s...") % filename)
283 s = open (filename).read ()
285 # search only the first 10k
287 for x in extra_fields:
288 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
290 set_setting (extra, x, m.group (1))
293 def find_tex_files_for_base (base, extra):
296 Find the \header fields dumped from BASE.
300 for f in layout_fields:
301 if os.path.exists (base + '.' + f):
302 headerfiles[f] = base+'.'+f
304 if os.path.exists (base +'.dep'):
305 dependency_files.append (base + '.dep')
307 for f in extra_fields:
308 if os.path.exists (base + '.' + f):
309 extra[f].append (open (base + '.' + f).read ())
311 return (base+tex_extension,headerfiles)
314 def find_tex_files (files, extra):
316 Find all .tex files whose prefixes start with some name in FILES.
325 fname = os.path.basename (f)
326 fname = ly.strip_extension (fname, '.ly')
328 fname = fname + '-%d' % x
330 if os.path.exists (fname + tex_extension):
331 tfiles.append (find_tex_files_for_base (fname, extra))
332 analyse_lilypond_output (fname, extra)
338 fstr = string.join (files, ', ')
339 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
342 def one_latex_definition (defn, first):
344 for (k,v) in defn[1].items ():
345 val = open (v).read ()
346 if (string.strip (val)):
347 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
349 s = s + r'''\let\lilypond%s\relax''' % k
353 s = s + '\\def\\mustmakelilypondtitle{}\n'
355 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
357 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.
361 ly_paper_to_latexpaper = {
362 'letter' : 'letterpaper',
369 #TODO: should set textheight (enlarge) depending on papersize.
370 def global_latex_preamble (extra):
371 '''construct preamble from EXTRA,'''
373 s = s + '% generation tag\n'
378 if extra['papersize']:
380 options = ly_paper_to_latexpaper[extra['papersize'][0]]
382 ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
385 if extra['latexoptions']:
386 options = options + ',' + extra['latexoptions'][-1]
388 s = s + '\\documentclass[%s]{article}\n' % options
390 if extra['language']:
391 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
394 s = s + '\\usepackage{%s}\n' \
395 % string.join (extra['latexpackages'], ',')
397 if extra['latexheaders']:
398 s = s + '\\include{%s}\n' \
399 % string.join (extra['latexheaders'], '}\n\\include{')
401 unit = extra['unit'][-1]
404 if extra['textheight']:
405 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
407 orientation = 'portrait'
408 if extra['orientation']:
409 orientation = extra['orientation'][0]
411 # set sane geometry width (a4-width) for linewidth = -1.
412 maxlw = max (extra['linewidth'] + [-1])
414 # who the hell is 597 ?
417 linewidth = '%d%s' % (maxlw, unit)
418 s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
420 if extra['latexoptions']:
421 s = s + '\geometry{twosideshift=4mm}\n'
424 \usepackage[latin1]{inputenc}
428 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
429 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
430 s = s + '\\pagestyle{plain}\n'
432 s = s + '\\pagestyle{empty}\n'
438 def global_latex_definition (tfiles, extra):
439 '''construct preamble from EXTRA, dump Latex stuff for each
440 lily output file in TFILES after that, and return the Latex file constructed. '''
443 s = global_latex_preamble (extra) + '\\begin{document}\n'
444 s = s + '\\parindent 0pt\n'
445 s = s + '\\thispagestyle{firstpage}\n'
449 s = s + one_latex_definition (t, first)
453 s = s + '\\thispagestyle{lastpage}\n'
454 s = s + '\\end{document}'
458 def run_latex (files, outbase, extra):
460 '''Construct latex file, for FILES and EXTRA, dump it into
461 OUTBASE.latex. Run LaTeX on it.
468 latex_fn = outbase + '.latex'
470 wfs = find_tex_files (files, extra)
471 s = global_latex_definition (wfs, extra)
473 f = open (latex_fn, 'w')
477 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
478 # Ugh. (La)TeX writes progress and error messages on stdout
480 cmd += ' 1>/dev/stderr'
481 status = ly.system (cmd, ignore_error = 1)
482 signal = 0xf & status
483 exit_status = status >> 8
489 logstr = open (outbase + '.log').read ()
490 m = re.search ("\n!", logstr)
492 logstr = logstr[start:start+200]
496 ly.error (_ ("LaTeX failed on the output file."))
497 ly.error (_ ("The error log is as follows:"))
498 sys.stderr.write (logstr + '\n')
502 # make a preview by rendering only the 1st line.
503 preview_fn = outbase + '.preview.tex'
504 f = open (preview_fn, 'w')
505 wfs = find_tex_files (files, extra)
506 s = global_latex_definition (wfs, extra)
508 s = re.sub ('thispagestyle{firstpage}', r'''thispagestyle{empty}%
509 \\def\\interscoreline{\\endinput}''',s )
510 s = re.sub ('thispagestyle{lastpage}', r'''thispagestyle{empty}%
511 \\def\\interscoreline{\\endinput}''',s )
514 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
518 def run_dvips (outbase, extra):
521 '''Run dvips using the correct options taken from EXTRA,
522 leaving a PS file in OUTBASE.ps
529 if extra['papersize']:
530 opts = opts + ' -t%s' % extra['papersize'][0]
532 if extra['orientation'] and extra['orientation'][0] == 'landscape':
533 opts = opts + ' -tlandscape'
537 where = ly.read_pipe ('kpsewhich feta20.pfa').strip()
542 pfa_file = open (where, 'r')
547 opts = opts + ' -Ppdf -G0 -u lilypond.map'
549 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
550 Using bitmap fonts instead. This will look bad.'''))
552 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
556 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')
560 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
563 def generate_dependency_file (depfile, outname):
564 df = open (depfile, 'w')
565 df.write (outname + ':' )
567 for d in dependency_files:
569 s = re.sub ('#[^\n]*\n', '', s)
570 s = re.sub (r'\\\n', ' ', s)
571 m = re.search ('.*:(.*)\n', s)
573 # ugh. Different targets?
575 df.write ( m.group (1) + ' ' )
580 def find_file_in_path (path, name):
581 for d in string.split (path, os.pathsep):
582 if name in os.listdir (d):
583 return os.path.join (d, name)
585 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
588 def find_pfa_fonts (name):
589 s = open (name).read ()
590 if s[:len (PS)] != PS:
592 ly.error (_ ("not a PostScript file: `%s\'" % name))
595 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
599 pfa.append (m.group (1))
600 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
604 (sh, long) = ly.getopt_args (option_definitions)
606 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
607 except getopt.error, s:
608 sys.stderr.write ('\n')
609 ly.error (_ ("getopt says: `%s\'" % s))
610 sys.stderr.write ('\n')
620 elif o == '--help' or o == '-h':
623 elif o == '--find-pfa' or o == '-f':
624 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
625 files = map (lambda x:
626 find_file_in_path (os.environ['GS_FONTPATH'], x),
628 print string.join (files, ' ')
630 elif o == '--include' or o == '-I':
631 include_path.append (a)
632 elif o == '--postscript' or o == '-P':
633 targets.append ('PS')
634 elif o == '--pdf' or o == '-p':
635 targets.append ('PS')
636 targets.append ('PDF')
637 elif o == '--keep' or o == '-k':
642 elif o == '--no-lily':
644 elif o == '--preview':
646 targets.append ('PNG')
647 elif o == '--preview-resolution':
648 preview_resolution = string.atoi (a)
649 elif o == '--no-paper' or o == '-m':
652 elif o == '--output' or o == '-o':
654 elif o == '--set' or o == '-s':
655 ss = string.split (a, '=')
656 set_setting (extra_init, ss[0], ss[1])
657 elif o == '--dependencies' or o == '-d':
658 track_dependencies_p = 1
659 elif o == '--verbose' or o == '-V':
661 elif o == '--version' or o == '-v':
662 ly.identify (sys.stdout)
664 elif o == '--pdftex':
665 latex_cmd = 'pdflatex'
666 targets.remove('DVI')
667 targets.append('PDFTEX')
669 tex_extension = '.pdftex'
670 elif o == '--warranty' or o == '-w':
671 status = os.system ('lilypond -w')
676 # Don't convert input files to abspath, rather prepend '.' to include
678 include_path.insert (0, '.')
680 # As a neat trick, add directory part of first input file
681 # to include path. That way you can do without the clumsy -I in:
683 # ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
684 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
685 include_path.append (os.path.dirname (files[0]))
687 include_path = map (ly.abspath, include_path)
689 if files and (files[0] == '-' or output_name == '-'):
692 output_name = 'lelie'
694 ly.progress (_ ("pseudo filter") + '\n')
697 ly.error (_ ("pseudo filter only for single input file"))
702 ly.error (_ ("no files specified on command line"))
706 ly.identify (sys.stderr)
707 original_output = output_name
709 # Ugh, maybe make a setup () function
710 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
712 # hmmm. Wish I'd 've written comments when I wrote this.
713 # now it looks complicated.
715 (outdir, outbase) = ('','')
717 outbase = os.path.basename (files[0])
718 outdir = ly.abspath ('.')
719 elif output_name[-1] == os.sep:
720 outdir = ly.abspath (output_name)
721 outbase = os.path.basename (files[0])
723 (outdir, outbase) = os.path.split (ly.abspath (output_name))
725 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
726 output_name = ly.strip_extension (output_name, i)
727 outbase = ly.strip_extension (outbase, i)
729 for i in files[:] + [output_name]:
730 if string.find (i, ' ') >= 0:
731 ly.error (_ ("filename should not contain spaces: `%s'") %
735 if os.path.dirname (output_name) != '.':
736 dep_prefix = os.path.dirname (output_name)
740 reldir = os.path.dirname (output_name)
741 if outdir != '.' and (track_dependencies_p or targets):
742 ly.mkdir_p (outdir, 0777)
744 tmpdir = ly.setup_temp ()
745 ly.setup_environment ()
747 # to be sure, add tmpdir *in front* of inclusion path.
748 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
751 # We catch all exceptions, because we need to do stuff at exit:
752 # * copy any successfully generated stuff from tempdir and
753 # notify user of that
757 run_lilypond (files, dep_prefix)
759 ### ARGH. This also catches python programming errors.
760 ### this should only catch lilypond nonzero exit status
764 # TODO: friendly message about LilyPond setup/failing?
768 traceback.print_exc ()
770 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
772 # Our LilyPond pseudo filter always outputs to 'lelie'
773 # have subsequent stages and use 'lelie' output.
777 if 'PNG' in targets and 'PS' not in targets:
778 targets.append ('PS')
779 if 'PS' in targets and 'DVI' not in targets:
780 targets.append('DVI')
784 run_latex (files, outbase, extra_init)
785 # unless: add --tex, or --latex?
786 targets.remove ('TEX')
787 targets.remove('LATEX')
789 # TODO: friendly message about TeX/LaTeX setup,
790 # trying to run tex/latex by hand
792 targets.remove ('DVI')
794 targets.remove ('PS')
796 traceback.print_exc ()
800 run_dvips (outbase, extra_init)
804 targets.remove ('PS')
806 traceback.print_exc ()
808 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
811 ly.make_preview (outbase)
813 if 'PDFTEX' in targets:
815 run_latex (files, outbase, extra_init)
816 # unless: add --tex, or --latex?
817 targets.remove ('TEX')
818 targets.remove ('LATEX')
819 targets.remove ('PDFTEX')
820 if 'PDF' not in targets:
821 targets.append('PDF')
823 # TODO: friendly message about TeX/LaTeX setup,
824 # trying to run tex/latex by hand
825 if 'PDFTEX' in targets:
826 targets.remove ('PDFTEX')
828 targets.remove ('PDF')
830 targets.remove ('PS')
832 traceback.print_exc ()
834 ly.warning (_("Running LaTeX falied. Rerun with --verbose for a trace."))
837 # add DEP to targets?
838 if track_dependencies_p:
839 depfile = os.path.join (outdir, outbase + '.dep')
840 generate_dependency_file (depfile, depfile)
841 if os.path.isfile (depfile):
842 ly.progress (_ ("dependencies output to `%s'...") %
848 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
853 ly.progress (_ ("%s output to <stdout>...") % i)
854 outname = outbase + '.' + string.lower (main_target)
855 if os.path.isfile (outname):
856 sys.stdout.write (open (outname).read ())
858 ly.warning (_ ("can't find file: `%s'") % outname)
862 # Hmm, if this were a function, we could call it the except: clauses
864 ext = string.lower (i)
865 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
866 outname = outbase + '.' + string.lower (i)
867 abs = os.path.join (outdir, outname)
869 outname = os.path.join (reldir, outname)
870 if os.path.isfile (abs):
871 ly.progress (_ ("%s output to `%s'...") % (i, outname))
874 ly.warning (_ ("can't find file: `%s'") % outname)
876 os.chdir (original_dir)
879 sys.exit (lilypond_error_p)