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
117 ## ly2dvi: silly name?
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', _ ("this help")),
128 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
130 _ ("keep all output, output to directory %s.dir") % program_name),
131 ('', '', 'no-lily', _ ("don't run LilyPond")),
132 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
133 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
134 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
135 (_ ('RES'), '', 'preview-resolution',
136 _ ("set the resolution of the preview to RES")),
137 ('', 'P', 'postscript', _ ("generate PostScript output")),
138 ('', 'p', 'pdf', _ ("generate PDF output")),
139 ('', '', 'pdftex', _ ("use pdflatex to generate a PDF output")),
140 # FIXME: preview, picture; to indicate creation of a PNG?
141 ('', '', 'preview', _ ("make a picture of the first system")),
142 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
143 ('', 'V', 'verbose', _ ("verbose")),
144 ('', 'v', 'version', _ ("print version number")),
145 ('', 'w', 'warranty', _ ("show warranty and copyright")),
155 tex_extension = '.tex'
157 # Debugging support -- do we need this?
158 lilypond_cmd = 'lilypond'
159 #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' }
162 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
163 'footer', 'head', 'composer', 'arranger', 'instrument',
164 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
167 # init to empty; values here take precedence over values in the file
169 ## TODO: change name.
173 'latexpackages' : ['geometry'],
183 extra_fields = extra_init.keys ()
184 fields = layout_fields + extra_fields
192 # Output formats that ly2dvi should create
193 targets = ['DVI', 'LATEX', 'MIDI', 'TEX']
195 track_dependencies_p = 0
196 dependency_files = []
199 def set_setting (dict, key, val):
201 val = string.atoi (val)
203 #ly.warning (_ ("invalid value: %s") % `val`)
206 if type(val) == type ('hoi'):
208 val = string.atof (val)
210 #ly.warning (_ ("invalid value: %s") % `val`)
214 dict[key].append (val)
216 ly.warning (_ ("no such setting: `%s'") % `key`)
220 def run_lilypond (files, dep_prefix):
223 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
226 opts = opts + ' --output=lelie'
228 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
231 opts = opts + ' --no-paper'
234 opts = opts + ' -f pdftex'
236 if track_dependencies_p:
237 opts = opts + " --dependencies"
239 opts = opts + ' --dep-prefix=%s' % dep_prefix
241 fs = string.join (files)
245 opts = opts + ' --verbose'
246 ly.print_environment ()
248 cmd = string.join ((lilypond_cmd,opts, fs))
249 status = ly.system (cmd, ignore_error = 1, progress_p = 1)
250 signal = 0x0f & status
251 exit_status = status >> 8
253 # 2 == user interrupt.
254 if signal and signal != 2:
255 sys.stderr.write ('\n\n')
256 ly.error (_ ("LilyPond crashed (signal %d).") % signal)
257 ly.error (_ ("Please submit a bug report to bug-lilypond@gnu.org"))
261 sys.stderr.write ('\n')
263 ly.error (_ ("LilyPond failed on input file %s (exit status %d)") % (files[0], exit_status))
266 ly.error (_ ("LilyPond failed on an input file (exit status %d)") % exit_status)
267 ly.error (_ ("Continuing..."))
268 global lilypond_error_p
272 def analyse_lilypond_output (filename, extra):
275 '''Grep FILENAME for interesting stuff, and
276 put relevant info into EXTRA.'''
277 filename = filename+tex_extension
278 ly.progress (_ ("Analyzing %s...") % filename)
279 s = open (filename).read ()
281 # search only the first 10k
283 for x in extra_fields:
284 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
286 set_setting (extra, x, m.group (1))
289 def find_tex_files_for_base (base, extra):
292 Find the \header fields dumped from BASE.
296 for f in layout_fields:
297 if os.path.exists (base + '.' + f):
298 headerfiles[f] = base+'.'+f
300 if os.path.exists (base +'.dep'):
301 dependency_files.append (base + '.dep')
303 for f in extra_fields:
304 if os.path.exists (base + '.' + f):
305 extra[f].append (open (base + '.' + f).read ())
307 return (base+tex_extension,headerfiles)
310 def find_tex_files (files, extra):
312 Find all .tex files whose prefixes start with some name in FILES.
321 fname = os.path.basename (f)
322 fname = ly.strip_extension (fname, '.ly')
324 fname = fname + '-%d' % x
326 if os.path.exists (fname + tex_extension):
327 tfiles.append (find_tex_files_for_base (fname, extra))
328 analyse_lilypond_output (fname, extra)
334 fstr = string.join (files, ', ')
335 ly.warning (_ ("no LilyPond output found for `%s'") % fstr)
338 def one_latex_definition (defn, first):
340 for (k,v) in defn[1].items ():
341 val = open (v).read ()
342 if (string.strip (val)):
343 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
345 s = s + r'''\let\lilypond%s\relax''' % k
349 s = s + '\\def\\mustmakelilypondtitle{}\n'
351 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
353 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.
357 ly_paper_to_latexpaper = {
359 'letter' : 'letterpaper',
363 #TODO: should set textheight (enlarge) depending on papersize.
364 def global_latex_preamble (extra):
365 '''construct preamble from EXTRA,'''
367 s = s + '% generation tag\n'
372 if extra['papersize']:
374 options = ly_paper_to_latexpaper[extra['papersize'][0]]
376 ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
379 if extra['latexoptions']:
380 options = options + ',' + extra['latexoptions'][-1]
382 s = s + '\\documentclass[%s]{article}\n' % options
384 if extra['language']:
385 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
388 s = s + '\\usepackage{%s}\n' \
389 % string.join (extra['latexpackages'], ',')
391 if extra['latexheaders']:
392 s = s + '\\include{%s}\n' \
393 % string.join (extra['latexheaders'], '}\n\\include{')
395 unit = extra['unit'][-1]
398 if extra['textheight']:
399 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
401 orientation = 'portrait'
402 if extra['orientation']:
403 orientation = extra['orientation'][0]
405 # set sane geometry width (a4-width) for linewidth = -1.
406 maxlw = max (extra['linewidth'] + [-1])
408 # who the hell is 597 ?
411 linewidth = '%d%s' % (maxlw, unit)
412 s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
414 if extra['latexoptions']:
415 s = s + '\geometry{twosideshift=4mm}\n'
418 \usepackage[latin1]{inputenc}
422 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
423 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
424 s = s + '\\pagestyle{plain}\n'
426 s = s + '\\pagestyle{empty}\n'
432 def global_latex_definition (tfiles, extra):
433 '''construct preamble from EXTRA, dump Latex stuff for each
434 lily output file in TFILES after that, and return the Latex file constructed. '''
437 s = global_latex_preamble (extra) + '\\begin{document}\n'
438 s = s + '\\parindent 0pt\n'
439 s = s + '\\thispagestyle{firstpage}\n'
443 s = s + one_latex_definition (t, first)
447 s = s + '\\thispagestyle{lastpage}\n'
448 s = s + '\\end{document}'
452 def run_latex (files, outbase, extra):
454 '''Construct latex file, for FILES and EXTRA, dump it into
455 OUTBASE.latex. Run LaTeX on it.
462 latex_fn = outbase + '.latex'
464 wfs = find_tex_files (files, extra)
465 s = global_latex_definition (wfs, extra)
467 f = open (latex_fn, 'w')
471 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
472 # Ugh. (La)TeX writes progress and error messages on stdout
474 cmd += ' 1>/dev/stderr'
475 status = ly.system (cmd, ignore_error = 1)
476 signal = 0xf & status
477 exit_status = status >> 8
483 logstr = open (outbase + '.log').read ()
484 m = re.search ("\n!", logstr)
486 logstr = logstr[start:start+200]
490 ly.error (_ ("LaTeX failed on the output file."))
491 ly.error (_ ("The error log is as follows:"))
492 sys.stderr.write (logstr + '\n')
496 # make a preview by rendering only the 1st line.
497 preview_fn = outbase + '.preview.tex'
498 f = open (preview_fn, 'w')
504 \def\interscoreline{\endinput}
507 ''' % (global_latex_preamble (extra), outbase))
510 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
514 def run_dvips (outbase, extra):
517 '''Run dvips using the correct options taken from EXTRA,
518 leaving a PS file in OUTBASE.ps
525 if extra['papersize']:
526 opts = opts + ' -t%s' % extra['papersize'][0]
528 if extra['orientation'] and extra['orientation'][0] == 'landscape':
529 opts = opts + ' -tlandscape'
532 opts = opts + ' -Ppdf -G0 -u lilypond.map'
534 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
538 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')
542 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
545 def generate_dependency_file (depfile, outname):
546 df = open (depfile, 'w')
547 df.write (outname + ':' )
549 for d in dependency_files:
551 s = re.sub ('#[^\n]*\n', '', s)
552 s = re.sub (r'\\\n', ' ', s)
553 m = re.search ('.*:(.*)\n', s)
555 # ugh. Different targets?
557 df.write ( m.group (1) + ' ' )
562 def find_file_in_path (path, name):
563 for d in string.split (path, os.pathsep):
564 if name in os.listdir (d):
565 return os.path.join (d, name)
567 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
570 def find_pfa_fonts (name):
571 s = open (name).read ()
572 if s[:len (PS)] != PS:
574 ly.error (_ ("not a PostScript file: `%s\'" % name))
577 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
581 pfa.append (m.group (1))
582 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
586 (sh, long) = ly.getopt_args (option_definitions)
588 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
589 except getopt.error, s:
590 sys.stderr.write ('\n')
591 ly.error (_ ("getopt says: `%s\'" % s))
592 sys.stderr.write ('\n')
602 elif o == '--help' or o == '-h':
605 elif o == '--find-pfa' or o == '-f':
606 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
607 files = map (lambda x:
608 find_file_in_path (os.environ['GS_FONTPATH'], x),
610 print string.join (files, ' ')
612 elif o == '--include' or o == '-I':
613 include_path.append (a)
614 elif o == '--postscript' or o == '-P':
615 targets.append ('PS')
616 elif o == '--pdf' or o == '-p':
617 targets.append ('PS')
618 targets.append ('PDF')
619 elif o == '--keep' or o == '-k':
621 elif o == '--no-lily':
623 elif o == '--preview':
625 targets.append ('PNG')
626 elif o == '--preview-resolution':
627 preview_resolution = string.atoi (a)
628 elif o == '--no-paper' or o == '-m':
631 elif o == '--output' or o == '-o':
633 elif o == '--set' or o == '-s':
634 ss = string.split (a, '=')
635 set_setting (extra_init, ss[0], ss[1])
636 elif o == '--dependencies' or o == '-d':
637 track_dependencies_p = 1
638 elif o == '--verbose' or o == '-V':
640 elif o == '--version' or o == '-v':
641 ly.identify (sys.stdout)
643 elif o == '--pdftex':
644 latex_cmd = 'pdflatex'
645 targets.remove('DVI')
646 targets.append('PDFTEX')
648 tex_extension = '.pdftex'
649 elif o == '--warranty' or o == '-w':
650 status = os.system ('lilypond -w')
655 # Don't convert input files to abspath, rather prepend '.' to include
657 include_path.insert (0, '.')
659 # As a neat trick, add directory part of first input file
660 # to include path. That way you can do without the clumsy -I in:
662 # ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
663 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
664 include_path.append (os.path.dirname (files[0]))
666 include_path = map (ly.abspath, include_path)
668 if files and (files[0] == '-' or output_name == '-'):
671 output_name = 'lelie'
673 ly.progress (_ ("pseudo filter") + '\n')
676 ly.error (_ ("pseudo filter only for single input file"))
681 ly.error (_ ("no files specified on command line"))
685 ly.identify (sys.stderr)
686 original_output = output_name
688 # Ugh, maybe make a setup () function
689 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
691 # hmmm. Wish I'd 've written comments when I wrote this.
692 # now it looks complicated.
694 (outdir, outbase) = ('','')
696 outbase = os.path.basename (files[0])
697 outdir = ly.abspath ('.')
698 elif output_name[-1] == os.sep:
699 outdir = ly.abspath (output_name)
700 outbase = os.path.basename (files[0])
702 (outdir, outbase) = os.path.split (ly.abspath (output_name))
704 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
705 output_name = ly.strip_extension (output_name, i)
706 outbase = ly.strip_extension (outbase, i)
708 for i in files[:] + [output_name]:
709 if string.find (i, ' ') >= 0:
710 ly.error (_ ("filename should not contain spaces: `%s'") %
714 if os.path.dirname (output_name) != '.':
715 dep_prefix = os.path.dirname (output_name)
719 reldir = os.path.dirname (output_name)
720 if outdir != '.' and (track_dependencies_p or targets):
721 ly.mkdir_p (outdir, 0777)
723 tmpdir = ly.setup_temp ()
724 ly.setup_environment ()
726 # to be sure, add tmpdir *in front* of inclusion path.
727 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
730 # We catch all exceptions, because we need to do stuff at exit:
731 # * copy any successfully generated stuff from tempdir and
732 # notify user of that
736 run_lilypond (files, dep_prefix)
738 # TODO: friendly message about LilyPond setup/failing?
740 # TODO: lilypond should fail with different
742 # - guile setup/startup failure
743 # - font setup failure
744 # - init.ly setup failure
745 # - parse error in .ly
746 # - unexpected: assert/core dump
749 traceback.print_exc ()
751 # Our LilyPond pseudo filter always outputs to 'lelie'
752 # have subsequent stages and use 'lelie' output.
756 if 'PNG' in targets and 'PS' not in targets:
757 targets.append ('PS')
758 if 'PS' in targets and 'DVI' not in targets:
759 targets.append('DVI')
763 run_latex (files, outbase, extra_init)
764 # unless: add --tex, or --latex?
765 targets.remove ('TEX')
766 targets.remove('LATEX')
768 # TODO: friendly message about TeX/LaTeX setup,
769 # trying to run tex/latex by hand
771 targets.remove ('DVI')
773 targets.remove ('PS')
775 traceback.print_exc ()
779 run_dvips (outbase, extra_init)
782 targets.remove ('PS')
784 traceback.print_exc ()
787 ly.make_preview (outbase)
789 if 'PDFTEX' in targets:
791 run_latex (files, outbase, extra_init)
792 # unless: add --tex, or --latex?
793 targets.remove ('TEX')
794 targets.remove ('LATEX')
795 targets.remove ('PDFTEX')
796 if 'PDF' not in targets:
797 targets.append('PDF')
799 # TODO: friendly message about TeX/LaTeX setup,
800 # trying to run tex/latex by hand
801 if 'PDFTEX' in targets:
802 targets.remove ('PDFTEX')
804 targets.remove ('PDF')
806 targets.remove ('PS')
808 traceback.print_exc ()
810 # add DEP to targets?
811 if track_dependencies_p:
812 depfile = os.path.join (outdir, outbase + '.dep')
813 generate_dependency_file (depfile, depfile)
814 if os.path.isfile (depfile):
815 ly.progress (_ ("dependencies output to `%s'...") %
821 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
826 ly.progress (_ ("%s output to <stdout>...") % i)
827 outname = outbase + '.' + string.lower (main_target)
828 if os.path.isfile (outname):
829 sys.stdout.write (open (outname).read ())
831 ly.warning (_ ("can't find file: `%s'") % outname)
835 # Hmm, if this were a function, we could call it the except: clauses
837 ext = string.lower (i)
838 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
839 outname = outbase + '.' + string.lower (i)
840 abs = os.path.join (outdir, outname)
842 outname = os.path.join (reldir, outname)
843 if os.path.isfile (abs):
844 ly.progress (_ ("%s output to `%s'...") % (i, outname))
847 ly.warning (_ ("can't find file: `%s'") % outname)
849 os.chdir (original_dir)
852 sys.exit (lilypond_error_p)