2 # Run lilypond, latex, dvips.
4 # This is the third incarnation of ly2dvi.
6 # Earlier incarnations of ly2dvi were written by
7 # Jeffrey B. Reed<daboys@austin.rr.com> (Python version)
8 # Jan Arne Fagertun <Jan.A.Fagertun@@energy.sintef.no> (Bourne shell script)
12 # Note: gettext work best if we use ' for docstrings and "
13 # for gettextable strings
18 * figure out which set of command line options should make ly2dvi:
21 na: create latex only?
22 na: create tex and latex
23 default: create dvi only
24 na: create tex, latex and dvi
30 for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
32 * move versatile taglines,
35 beginfooter=\mutopiaPD
36 endfooter=\tagline -> 'lily was here <version>'
39 lilytagline (->lily was here), usertagline, copyright etc.
41 * head/header tagline/endfooter
43 * dvi from lilypond .tex output? This is hairy, because we create dvi
44 from lilypond .tex *and* header output.
46 * multiple \score blocks?
48 * windows-sans-cygwin compatibility? rm -rf, cp file... dir
64 sys.path.append (datadir + '/python')
67 gettext.bindtextdomain ('lilypond', '@localedir@')
68 gettext.textdomain('lilypond')
75 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
76 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
80 # init to empty; values here take precedence over values in the file
84 'latexpackages' : ['geometry'],
92 extra_fields = extra_init.keys ()
94 fields = layout_fields + extra_fields
95 program_name = 'ly2dvi'
96 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
110 track_dependencies_p = 0
111 dependency_files = []
117 # lily_py.py -- options and stuff
119 # source file of the GNU LilyPond music typesetter
121 # BEGIN Library for these?
122 # cut-n-paste from ly2dvi
124 program_version = '@TOPLEVEL_VERSION@'
125 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
126 program_version = '1.3.142'
129 original_dir = os.getcwd ()
130 temp_dir = '%s.dir' % program_name
135 # Try to cater for bad installations of LilyPond, that have
136 # broken TeX setup. Just hope this doesn't hurt good TeX
137 # setups. Maybe we should check if kpsewhich can find
138 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
141 'MFINPUTS' : datadir + '/mf:',
142 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:.:',
143 'TFMFONTS' : datadir + '/tfm:',
144 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
145 'GS_LIB' : datadir + '/ps',
148 def setup_environment ():
149 for key in environment.keys ():
150 val = environment[key]
151 if os.environ.has_key (key):
152 val = val + os.pathsep + os.environ[key]
153 os.environ[key] = val
156 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
160 sys.stdout.write ('\n')
161 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
162 sys.stdout.write ('\n')
163 sys.stdout.write (' Han-Wen Nienhuys')
164 sys.stdout.write (' Jan Nieuwenhuizen')
165 sys.stdout.write ('\n')
166 sys.stdout.write (_ (r'''
167 Distributed under terms of the GNU General Public License. It comes with
169 sys.stdout.write ('\n')
172 sys.stderr.write (s + '\n')
175 sys.stderr.write (_ ("warning: ") + s)
176 sys.stderr.write ('\n')
180 sys.stderr.write (_ ("error: ") + s)
181 sys.stderr.write ('\n')
182 raise _ ("Exiting ... ")
184 def getopt_args (opts):
185 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
200 def option_help_str (o):
201 '''Transform one option description (4-tuple ) into neatly formatted string'''
219 return ' ' + sh + sep + long + arg
222 def options_help_str (opts):
223 '''Convert a list of options into a neatly formatted string'''
229 s = option_help_str (o)
230 strs.append ((s, o[3]))
236 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
240 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % program_name)
241 sys.stdout.write ('\n\n')
242 sys.stdout.write (help_summary)
243 sys.stdout.write ('\n\n')
244 sys.stdout.write (_ ("Options:"))
245 sys.stdout.write ('\n')
246 sys.stdout.write (options_help_str (option_definitions))
247 sys.stdout.write ('\n\n')
248 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
249 sys.stdout.write ('\n')
253 if not keep_temp_dir_p:
254 temp_dir = tempfile.mktemp (program_name)
256 os.mkdir (temp_dir, 0777)
262 def system (cmd, ignore_error = 0):
264 progress (_ ("Invoking `%s\'") % cmd)
265 st = os.system (cmd) >> 8
267 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
268 msg = name + ': ' + _ ("command exited with value %d") % st
270 warning (msg + ' ' + _ ("(ignored)") + ' ')
278 if not keep_temp_dir_p:
280 progress (_ ("Cleaning %s...") % temp_dir)
281 system ('rm -rf %s' % temp_dir)
284 def set_setting (dict, key, val):
286 val = string.atof (val)
288 #warning (_ ("invalid value: %s") % `val`)
292 dict[key].append (val)
294 warning (_ ("no such setting: %s") % `key`)
297 def strip_extension (f, ext):
298 (p, e) = os.path.splitext (f)
305 option_definitions = [
306 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
307 ('', 'h', 'help', _ ("this help")),
308 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
309 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
310 ('', '', 'no-lily', _ ("don't run LilyPond")),
311 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
312 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
314 ('', 'P', 'postscript', _ ("generate PostScript output")),
315 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
316 ('', 'V', 'verbose', _ ("verbose")),
317 ('', 'v', 'version', _ ("print version number")),
318 ('', 'w', 'warranty', _ ("show warranty and copyright")),
321 def run_lilypond (files, outbase, dep_prefix):
322 opts = '--output=%s.tex' % outbase
323 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
325 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
327 opts = opts + ' --no-paper'
329 if track_dependencies_p:
330 opts = opts + " --dependencies"
332 opts = opts + ' --dep-prefix=%s' % dep_prefix
334 fs = string.join (files)
337 progress ( _("Running %s...") % 'LilyPond')
338 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
340 opts = opts + ' --verbose'
342 system ('lilypond %s %s ' % (opts, fs))
344 def analyse_lilypond_output (filename, extra):
347 '''Grep FILENAME for interesting stuff, and
348 put relevant info into EXTRA.'''
349 filename = filename+'.tex'
350 progress (_ ("Analyzing %s...") % filename)
351 s = open (filename).read ()
353 # search only the first 10k
355 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
356 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
358 set_setting (extra, x, m.group (1))
360 def find_tex_files_for_base (base, extra):
362 for f in layout_fields:
363 if os.path.exists (base + '.' + f):
364 headerfiles[f] = base+'.'+f
366 if os.path.exists (base +'.dep'):
367 dependency_files.append (base + '.dep')
369 for f in extra_fields:
370 if os.path.exists (base + '.' + f):
371 extra[f].append (open (base + '.' + f).read ())
373 return (base +'.tex',headerfiles)
376 def find_tex_files (files, extra):
382 fname = os.path.basename (f)
383 fname = strip_extension (fname, '.ly')
385 fname = fname + '-%d' % x
387 if os.path.exists (fname + '.tex'):
388 tfiles.append (find_tex_files_for_base (fname, extra))
389 analyse_lilypond_output (fname, extra)
395 warning (_ ("no lilypond output found for %s") % `files`)
398 def one_latex_definition (defn, first):
400 for (k,v) in defn[1].items ():
401 val = open (v).read ()
402 if (string.strip (val)):
403 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
405 s = s + r'''\let\lilypond%s\relax''' % k
409 s = s + '\\def\\mustmakelilypondtitle{}\n'
411 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
413 s = s + '\\input %s' % defn[0]
417 ly_paper_to_latexpaper = {
419 'letter' : 'letterpaper',
422 def global_latex_definition (tfiles, extra):
423 '''construct preamble from EXTRA,
424 dump lily output files after that, and return result.
429 s = s + '% generation tag\n'
433 if extra['papersize']:
435 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
437 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
440 s = s + '\\documentclass%s{article}\n' % paper
442 if extra['language']:
443 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
446 s = s + '\\usepackage{%s}\n' \
447 % string.join (extra['latexpackages'], ',')
449 if extra['latexheaders']:
450 s = s + '\\include{%s}\n' \
451 % string.join (extra['latexheaders'], '}\n\\include{')
454 if extra['textheight']:
455 textheight = ',textheight=%fpt' % extra['textheight'][0]
457 orientation = 'portrait'
458 if extra['orientation']:
459 orientation = extra['orientation'][0]
461 # set sane geometry width (a4-width) for linewidth = -1.
462 if not extra['linewidth'] or extra['linewidth'][0] < 0:
465 linewidth = extra['linewidth'][0]
466 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
469 \usepackage[latin1]{inputenc}
472 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
475 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
477 \renewcommand{\@oddhead}{\parbox{\textwidth}%
478 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
481 s = s + '\\pagestyle{empty}\n'
483 s = s + '\\makeatother\n'
484 s = s + '\\begin{document}\n'
489 s = s + one_latex_definition (t, first)
494 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
497 s = s + '\\end{document}'
501 def run_latex (files, outbase, extra):
502 wfs = find_tex_files ([outbase] + files[1:], extra)
503 s = global_latex_definition (wfs, extra)
505 f = open (outbase + '.latex', 'w')
509 cmd = 'latex \\\\nonstopmode \\\\input %s' % outbase + '.latex'
511 progress ( _("Running %s...") % 'LaTeX')
512 cmd = cmd + ' 1> /dev/null 2> /dev/null'
516 def run_dvips (outbase, extra):
519 if extra['papersize']:
520 opts = opts + ' -t %s' % extra['papersize'][0]
522 if extra['orientation'] and extra['orientation'][0] == 'landscape':
523 opts = opts + ' -t landscape'
525 cmd = 'dvips %s -o %s %s' % (opts, outbase + '.ps', outbase + '.dvi')
528 progress ( _("Running %s...") % 'dvips')
529 cmd = cmd + ' 2> /dev/null'
533 def generate_dependency_file (depfile, outname):
534 df = open (depfile, 'w')
535 df.write (outname + ':' )
537 for d in dependency_files:
539 s = re.sub ('#[^\n]*\n', '', s)
540 s = re.sub (r'\\\n', ' ', s)
541 m = re.search ('.*:(.*)\n', s)
543 # ugh. Different targets?
545 df.write ( m.group (1) + ' ' )
550 (sh, long) = getopt_args (__main__.option_definitions)
552 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
563 elif o == '--help' or o == '-h':
566 elif o == '--include' or o == '-I':
567 include_path.append (a)
568 elif o == '--postscript' or o == '-P':
570 elif o == '--keep' or o == '-k':
572 elif o == '--no-lily':
574 elif o == '--no-paper' or o == '-m':
578 elif o == '--output' or o == '-o':
580 elif o == '--set' or o == '-s':
581 ss = string.split (a, '=')
582 set_setting (extra_init, ss[0], ss[1])
583 elif o == '--dependencies' or o == '-d':
584 track_dependencies_p = 1
585 elif o == '--verbose' or o == '-V':
587 elif o == '--version' or o == '-v':
590 elif o == '--warranty' or o == '-w':
592 system ('lilypond -w')
597 # On most platforms, this is equivalent to
598 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
599 def compat_abspath (path):
600 return os.path.normpath (os.path.join (os.getcwd (), path))
602 include_path = map (compat_abspath, include_path)
604 original_output = output
606 if files and files[0] != '-':
608 files = map (lambda x: strip_extension (x, '.ly'), files)
611 output = os.path.basename (files[0])
613 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
614 output = strip_extension (output, i)
616 files = map (compat_abspath, files)
618 if os.path.dirname (output) != '.':
619 dep_prefix = os.path.dirname (output)
623 reldir = os.path.dirname (output)
624 (outdir, outbase) = os.path.split (compat_abspath (output))
633 run_lilypond (files, outbase, dep_prefix)
635 # TODO: friendly message about LilyPond setup/failing?
637 # TODO: lilypond should fail with different
639 # - guile setup/startup failure
640 # - font setup failure
641 # - init.ly setup failure
642 # - parse error in .ly
643 # - unexpected: assert/core dump
646 if targets.has_key ('DVI') or targets.has_key ('PS'):
648 run_latex (files, outbase, extra)
649 # unless: add --tex, or --latex?
653 # TODO: friendly message about TeX/LaTeX setup,
654 # trying to run tex/latex by hand
655 if targets.has_key ('DVI'):
657 if targets.has_key ('PS'):
660 # TODO: does dvips ever fail?
661 if targets.has_key ('PS'):
662 run_dvips (outbase, extra)
664 if outdir != '.' and (track_dependencies_p or targets.keys ()):
665 system ('mkdir -p %s' % outdir)
667 # add DEP to targets?
668 if track_dependencies_p:
669 depfile = os.path.join (outdir, outbase + '.dep')
670 generate_dependency_file (depfile, depfile)
671 if os.path.isfile (depfile):
672 progress (_ ("dependencies output to %s...") % depfile)
674 for i in targets.keys ():
675 ext = string.lower (i)
676 if re.match ('.*[.]%s' % ext, string.join (os.listdir ('.'))):
677 system ('cp *.%s %s' % (ext, outdir))
678 outname = outbase + '.' + string.lower (i)
679 abs = os.path.join (outdir, outname)
681 outname = os.path.join (reldir, outname)
682 if os.path.isfile (abs):
683 progress (_ ("%s output to %s...") % (i, outname))
685 warning (_ ("can't find file: `%s'") % outname)
687 os.chdir (original_dir)
693 sys.stderr.write ('\n')
695 error (_ ("no FILEs specified, can't invoke as filter"))