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 = {
358 'letter' : 'letterpaper',
365 #TODO: should set textheight (enlarge) depending on papersize.
366 def global_latex_preamble (extra):
367 '''construct preamble from EXTRA,'''
369 s = s + '% generation tag\n'
374 if extra['papersize']:
376 options = ly_paper_to_latexpaper[extra['papersize'][0]]
378 ly.warning (_ ("invalid value: `%s'") % `extra['papersize'][0]`)
381 if extra['latexoptions']:
382 options = options + ',' + extra['latexoptions'][-1]
384 s = s + '\\documentclass[%s]{article}\n' % options
386 if extra['language']:
387 s = s + r'\usepackage[%s]{babel}' % extra['language'][-1] + '\n'
390 s = s + '\\usepackage{%s}\n' \
391 % string.join (extra['latexpackages'], ',')
393 if extra['latexheaders']:
394 s = s + '\\include{%s}\n' \
395 % string.join (extra['latexheaders'], '}\n\\include{')
397 unit = extra['unit'][-1]
400 if extra['textheight']:
401 textheight = ',textheight=%f%s' % (extra['textheight'][0], unit)
403 orientation = 'portrait'
404 if extra['orientation']:
405 orientation = extra['orientation'][0]
407 # set sane geometry width (a4-width) for linewidth = -1.
408 maxlw = max (extra['linewidth'] + [-1])
410 # who the hell is 597 ?
413 linewidth = '%d%s' % (maxlw, unit)
414 s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
416 if extra['latexoptions']:
417 s = s + '\geometry{twosideshift=4mm}\n'
420 \usepackage[latin1]{inputenc}
424 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
425 s = s + '\setcounter{page}{%d}\n' % (extra['pagenumber'][-1])
426 s = s + '\\pagestyle{plain}\n'
428 s = s + '\\pagestyle{empty}\n'
434 def global_latex_definition (tfiles, extra):
435 '''construct preamble from EXTRA, dump Latex stuff for each
436 lily output file in TFILES after that, and return the Latex file constructed. '''
439 s = global_latex_preamble (extra) + '\\begin{document}\n'
440 s = s + '\\parindent 0pt\n'
441 s = s + '\\thispagestyle{firstpage}\n'
445 s = s + one_latex_definition (t, first)
449 s = s + '\\thispagestyle{lastpage}\n'
450 s = s + '\\end{document}'
454 def run_latex (files, outbase, extra):
456 '''Construct latex file, for FILES and EXTRA, dump it into
457 OUTBASE.latex. Run LaTeX on it.
464 latex_fn = outbase + '.latex'
466 wfs = find_tex_files (files, extra)
467 s = global_latex_definition (wfs, extra)
469 f = open (latex_fn, 'w')
473 cmd = latex_cmd + ' \\\\nonstopmode \\\\input %s' % latex_fn
474 # Ugh. (La)TeX writes progress and error messages on stdout
476 cmd += ' 1>/dev/stderr'
477 status = ly.system (cmd, ignore_error = 1)
478 signal = 0xf & status
479 exit_status = status >> 8
485 logstr = open (outbase + '.log').read ()
486 m = re.search ("\n!", logstr)
488 logstr = logstr[start:start+200]
492 ly.error (_ ("LaTeX failed on the output file."))
493 ly.error (_ ("The error log is as follows:"))
494 sys.stderr.write (logstr + '\n')
498 # make a preview by rendering only the 1st line.
499 preview_fn = outbase + '.preview.tex'
500 f = open (preview_fn, 'w')
506 \def\interscoreline{\endinput}
509 ''' % (global_latex_preamble (extra), outbase))
512 cmd = '%s \\\\nonstopmode \\\\input %s' % (latex_cmd, preview_fn)
516 def run_dvips (outbase, extra):
519 '''Run dvips using the correct options taken from EXTRA,
520 leaving a PS file in OUTBASE.ps
527 if extra['papersize']:
528 opts = opts + ' -t%s' % extra['papersize'][0]
530 if extra['orientation'] and extra['orientation'][0] == 'landscape':
531 opts = opts + ' -tlandscape'
535 where = ly.read_pipe ('kpsewhich feta20.pfa')
540 pfa_file = open (where, 'r')
545 opts = opts + ' -Ppdf -G0 -u lilypond.map'
547 ly.warning (_ ('''Trying create PDF, but no PFA fonts found.
548 Using bitmap fonts instead. This will look poorly.'''))
550 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
554 cmd = 'dvips -E -o%s %s' % ( outbase + '.preview.ps', outbase + '.preview.dvi')
558 cmd = 'ps2pdf %s.ps %s.pdf' % (outbase , outbase)
561 def generate_dependency_file (depfile, outname):
562 df = open (depfile, 'w')
563 df.write (outname + ':' )
565 for d in dependency_files:
567 s = re.sub ('#[^\n]*\n', '', s)
568 s = re.sub (r'\\\n', ' ', s)
569 m = re.search ('.*:(.*)\n', s)
571 # ugh. Different targets?
573 df.write ( m.group (1) + ' ' )
578 def find_file_in_path (path, name):
579 for d in string.split (path, os.pathsep):
580 if name in os.listdir (d):
581 return os.path.join (d, name)
583 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
586 def find_pfa_fonts (name):
587 s = open (name).read ()
588 if s[:len (PS)] != PS:
590 ly.error (_ ("not a PostScript file: `%s\'" % name))
593 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
597 pfa.append (m.group (1))
598 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
602 (sh, long) = ly.getopt_args (option_definitions)
604 (options, files) = getopt.getopt (sys.argv[1:], sh, long)
605 except getopt.error, s:
606 sys.stderr.write ('\n')
607 ly.error (_ ("getopt says: `%s\'" % s))
608 sys.stderr.write ('\n')
618 elif o == '--help' or o == '-h':
621 elif o == '--find-pfa' or o == '-f':
622 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
623 files = map (lambda x:
624 find_file_in_path (os.environ['GS_FONTPATH'], x),
626 print string.join (files, ' ')
628 elif o == '--include' or o == '-I':
629 include_path.append (a)
630 elif o == '--postscript' or o == '-P':
631 targets.append ('PS')
632 elif o == '--pdf' or o == '-p':
633 targets.append ('PS')
634 targets.append ('PDF')
635 elif o == '--keep' or o == '-k':
637 elif o == '--no-lily':
639 elif o == '--preview':
641 targets.append ('PNG')
642 elif o == '--preview-resolution':
643 preview_resolution = string.atoi (a)
644 elif o == '--no-paper' or o == '-m':
647 elif o == '--output' or o == '-o':
649 elif o == '--set' or o == '-s':
650 ss = string.split (a, '=')
651 set_setting (extra_init, ss[0], ss[1])
652 elif o == '--dependencies' or o == '-d':
653 track_dependencies_p = 1
654 elif o == '--verbose' or o == '-V':
656 elif o == '--version' or o == '-v':
657 ly.identify (sys.stdout)
659 elif o == '--pdftex':
660 latex_cmd = 'pdflatex'
661 targets.remove('DVI')
662 targets.append('PDFTEX')
664 tex_extension = '.pdftex'
665 elif o == '--warranty' or o == '-w':
666 status = os.system ('lilypond -w')
671 # Don't convert input files to abspath, rather prepend '.' to include
673 include_path.insert (0, '.')
675 # As a neat trick, add directory part of first input file
676 # to include path. That way you can do without the clumsy -I in:
678 # ly2dvi -I foe/bar/baz foo/bar/baz/baz.ly
679 if files and files[0] != '-' and os.path.dirname (files[0]) != '.':
680 include_path.append (os.path.dirname (files[0]))
682 include_path = map (ly.abspath, include_path)
684 if files and (files[0] == '-' or output_name == '-'):
687 output_name = 'lelie'
689 ly.progress (_ ("pseudo filter") + '\n')
692 ly.error (_ ("pseudo filter only for single input file"))
697 ly.error (_ ("no files specified on command line"))
701 ly.identify (sys.stderr)
702 original_output = output_name
704 # Ugh, maybe make a setup () function
705 files = map (lambda x: ly.strip_extension (x, '.ly'), files)
707 # hmmm. Wish I'd 've written comments when I wrote this.
708 # now it looks complicated.
710 (outdir, outbase) = ('','')
712 outbase = os.path.basename (files[0])
713 outdir = ly.abspath ('.')
714 elif output_name[-1] == os.sep:
715 outdir = ly.abspath (output_name)
716 outbase = os.path.basename (files[0])
718 (outdir, outbase) = os.path.split (ly.abspath (output_name))
720 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex', '.pdftex'):
721 output_name = ly.strip_extension (output_name, i)
722 outbase = ly.strip_extension (outbase, i)
724 for i in files[:] + [output_name]:
725 if string.find (i, ' ') >= 0:
726 ly.error (_ ("filename should not contain spaces: `%s'") %
730 if os.path.dirname (output_name) != '.':
731 dep_prefix = os.path.dirname (output_name)
735 reldir = os.path.dirname (output_name)
736 if outdir != '.' and (track_dependencies_p or targets):
737 ly.mkdir_p (outdir, 0777)
739 tmpdir = ly.setup_temp ()
740 ly.setup_environment ()
742 # to be sure, add tmpdir *in front* of inclusion path.
743 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
746 # We catch all exceptions, because we need to do stuff at exit:
747 # * copy any successfully generated stuff from tempdir and
748 # notify user of that
752 run_lilypond (files, dep_prefix)
754 ### ARGH. This also catches python programming errors.
755 ### this should only catch lilypond nonzero exit status
759 # TODO: friendly message about LilyPond setup/failing?
763 traceback.print_exc ()
765 ly.warning (_("Running LilyPond failed. Rerun with --verbose for a trace."))
767 # Our LilyPond pseudo filter always outputs to 'lelie'
768 # have subsequent stages and use 'lelie' output.
772 if 'PNG' in targets and 'PS' not in targets:
773 targets.append ('PS')
774 if 'PS' in targets and 'DVI' not in targets:
775 targets.append('DVI')
779 run_latex (files, outbase, extra_init)
780 # unless: add --tex, or --latex?
781 targets.remove ('TEX')
782 targets.remove('LATEX')
784 # TODO: friendly message about TeX/LaTeX setup,
785 # trying to run tex/latex by hand
787 targets.remove ('DVI')
789 targets.remove ('PS')
791 traceback.print_exc ()
795 run_dvips (outbase, extra_init)
799 targets.remove ('PS')
801 traceback.print_exc ()
803 ly.warning (_("Failed to make PS file. Rerun with --verbose for a trace."))
806 ly.make_preview (outbase)
808 if 'PDFTEX' in targets:
810 run_latex (files, outbase, extra_init)
811 # unless: add --tex, or --latex?
812 targets.remove ('TEX')
813 targets.remove ('LATEX')
814 targets.remove ('PDFTEX')
815 if 'PDF' not in targets:
816 targets.append('PDF')
818 # TODO: friendly message about TeX/LaTeX setup,
819 # trying to run tex/latex by hand
820 if 'PDFTEX' in targets:
821 targets.remove ('PDFTEX')
823 targets.remove ('PDF')
825 targets.remove ('PS')
827 traceback.print_exc ()
829 ly.warning (_("Running LaTeX falied. Rerun with --verbose for a trace."))
832 # add DEP to targets?
833 if track_dependencies_p:
834 depfile = os.path.join (outdir, outbase + '.dep')
835 generate_dependency_file (depfile, depfile)
836 if os.path.isfile (depfile):
837 ly.progress (_ ("dependencies output to `%s'...") %
843 for i in 'PDF', 'PS', 'PNG', 'DVI', 'LATEX':
848 ly.progress (_ ("%s output to <stdout>...") % i)
849 outname = outbase + '.' + string.lower (main_target)
850 if os.path.isfile (outname):
851 sys.stdout.write (open (outname).read ())
853 ly.warning (_ ("can't find file: `%s'") % outname)
857 # Hmm, if this were a function, we could call it the except: clauses
859 ext = string.lower (i)
860 ly.cp_to_dir ('.*\.%s$' % ext, outdir)
861 outname = outbase + '.' + string.lower (i)
862 abs = os.path.join (outdir, outname)
864 outname = os.path.join (reldir, outname)
865 if os.path.isfile (abs):
866 ly.progress (_ ("%s output to `%s'...") % (i, outname))
869 ly.warning (_ ("can't find file: `%s'") % outname)
871 os.chdir (original_dir)
874 sys.exit (lilypond_error_p)