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?
63 sys.path.append (datadir + '/python')
66 gettext.bindtextdomain ('lilypond', '@localedir@')
67 gettext.textdomain('lilypond')
74 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
75 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
79 # init to empty; values here take precedence over values in the file
83 '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 = []
114 # lily_py.py -- options and stuff
116 # source file of the GNU LilyPond music typesetter
118 # BEGIN Library for these?
119 # cut-n-paste from ly2dvi
121 program_version = '@TOPLEVEL_VERSION@'
122 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
123 program_version = '1.3.148'
126 original_dir = os.getcwd ()
127 temp_dir = '%s.dir' % program_name
132 # Try to cater for bad installations of LilyPond, that have
133 # broken TeX setup. Just hope this doesn't hurt good TeX
134 # setups. Maybe we should check if kpsewhich can find
135 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
138 'MFINPUTS' : datadir + '/mf:',
139 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:.:',
140 'TFMFONTS' : datadir + '/tfm:',
141 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
142 'GS_LIB' : datadir + '/ps',
145 def setup_environment ():
146 for key in environment.keys ():
147 val = environment[key]
148 if os.environ.has_key (key):
149 val = val + os.pathsep + os.environ[key]
150 os.environ[key] = val
153 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
157 sys.stdout.write ('\n')
158 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
159 sys.stdout.write ('\n')
160 sys.stdout.write (' Han-Wen Nienhuys')
161 sys.stdout.write (' Jan Nieuwenhuizen')
162 sys.stdout.write ('\n')
163 sys.stdout.write (_ (r'''
164 Distributed under terms of the GNU General Public License. It comes with
166 sys.stdout.write ('\n')
168 if ( os.name == 'posix' ):
174 errorport.write (s + '\n')
177 progress (_ ("warning: ") + s)
182 """Report the error S. Exit by raising an exception. Please
183 do not abuse by trying to catch this error. If you donn't want
184 a stack trace, write to the output directly.
192 progress (_ ("error: ") + s)
193 raise _ ("Exiting ... ")
195 def getopt_args (opts):
196 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
211 def option_help_str (o):
212 '''Transform one option description (4-tuple ) into neatly formatted string'''
230 return ' ' + sh + sep + long + arg
233 def options_help_str (opts):
234 '''Convert a list of options into a neatly formatted string'''
240 s = option_help_str (o)
241 strs.append ((s, o[3]))
247 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
251 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
257 (options_help_str (option_definitions)),
259 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
261 map (sys.stdout.write, ls)
265 if not keep_temp_dir_p:
266 temp_dir = tempfile.mktemp (program_name)
268 os.mkdir (temp_dir, 0777)
274 def system (cmd, ignore_error = 0):
275 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
282 if ( os.name != 'posix' ):
283 cmd = re.sub (r'''\\''', r'''\\\\\\''', cmd)
284 cmd = "sh -c \'%s\'" % cmd
286 progress (_ ("Invoking `%s\'") % cmd)
287 st = os.system (cmd) >> 8
289 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
290 msg = name + ': ' + _ ("command exited with value %d") % st
292 warning (msg + ' ' + _ ("(ignored)") + ' ')
300 if not keep_temp_dir_p:
302 progress (_ ("Cleaning %s...") % temp_dir)
303 shutil.rmtree (temp_dir)
307 def set_setting (dict, key, val):
309 val = string.atof (val)
311 #warning (_ ("invalid value: %s") % `val`)
315 dict[key].append (val)
317 warning (_ ("no such setting: %s") % `key`)
321 def strip_extension (f, ext):
322 (p, e) = os.path.splitext (f)
329 option_definitions = [
330 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
331 ('', 'h', 'help', _ ("this help")),
332 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
333 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
334 ('', '', 'no-lily', _ ("don't run LilyPond")),
335 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
336 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
338 ('', 'P', 'postscript', _ ("generate PostScript output")),
339 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
340 ('', 'V', 'verbose', _ ("verbose")),
341 ('', 'v', 'version', _ ("print version number")),
342 ('', 'w', 'warranty', _ ("show warranty and copyright")),
345 def run_lilypond (files, outbase, dep_prefix):
347 # opts = opts + '--output=%s.tex' % outbase
348 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
351 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
354 opts = opts + ' --no-paper'
356 if track_dependencies_p:
357 opts = opts + " --dependencies"
359 opts = opts + ' --dep-prefix=%s' % dep_prefix
361 fs = string.join (files)
364 progress ( _("Running %s...") % 'LilyPond')
365 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
367 opts = opts + ' --verbose'
369 system ('lilypond %s %s ' % (opts, fs))
371 def analyse_lilypond_output (filename, extra):
374 '''Grep FILENAME for interesting stuff, and
375 put relevant info into EXTRA.'''
376 filename = filename+'.tex'
377 progress (_ ("Analyzing %s...") % filename)
378 s = open (filename).read ()
380 # search only the first 10k
382 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
383 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
385 set_setting (extra, x, m.group (1))
387 def find_tex_files_for_base (base, extra):
390 Find the \header fields dumped from BASE.
394 for f in layout_fields:
395 if os.path.exists (base + '.' + f):
396 headerfiles[f] = base+'.'+f
398 if os.path.exists (base +'.dep'):
399 dependency_files.append (base + '.dep')
401 for f in extra_fields:
402 if os.path.exists (base + '.' + f):
403 extra[f].append (open (base + '.' + f).read ())
405 return (base +'.tex',headerfiles)
408 def find_tex_files (files, extra):
410 Find all .tex files whose prefixes start with some name in FILES.
419 fname = os.path.basename (f)
420 fname = strip_extension (fname, '.ly')
422 fname = fname + '-%d' % x
424 if os.path.exists (fname + '.tex'):
425 tfiles.append (find_tex_files_for_base (fname, extra))
426 analyse_lilypond_output (fname, extra)
432 fstr = string.join (files, ', ')
433 warning (_ ("no lilypond output found for %s") % fstr)
436 def one_latex_definition (defn, first):
438 for (k,v) in defn[1].items ():
439 val = open (v).read ()
440 if (string.strip (val)):
441 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
443 s = s + r'''\let\lilypond%s\relax''' % k
447 s = s + '\\def\\mustmakelilypondtitle{}\n'
449 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
451 s = s + '\\input %s' % defn[0]
455 ly_paper_to_latexpaper = {
457 'letter' : 'letterpaper',
460 def global_latex_definition (tfiles, extra):
462 '''construct preamble from EXTRA, dump Latex stuff for each
463 lily output file in TFILES after that, and return the Latex file constructed. '''
467 s = s + '% generation tag\n'
471 if extra['papersize']:
473 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
475 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
478 if extra['latexoptions']:
479 options = options + ',' + extra['latexoptions'][-1]
481 s = s + '\\documentclass[%s]{article}\n' % options
483 if extra['language']:
484 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
487 s = s + '\\usepackage{%s}\n' \
488 % string.join (extra['latexpackages'], ',')
490 if extra['latexheaders']:
491 s = s + '\\include{%s}\n' \
492 % string.join (extra['latexheaders'], '}\n\\include{')
495 if extra['textheight']:
496 textheight = ',textheight=%fpt' % extra['textheight'][0]
498 orientation = 'portrait'
499 if extra['orientation']:
500 orientation = extra['orientation'][0]
502 # set sane geometry width (a4-width) for linewidth = -1.
503 if not extra['linewidth'] or extra['linewidth'][0] < 0:
506 linewidth = extra['linewidth'][0]
507 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=12pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
509 if extra['latexoptions']:
510 s = s + '\geometry{twosideshift=4mm}\n'
513 \usepackage[latin1]{inputenc}
516 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
517 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
520 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
522 \renewcommand{\@evenhead}{\hbox to\textwidth{\textbf{\thepage}\hfill{\small\theheader}}}
523 \renewcommand{\@oddhead}{\hbox to \textwidth{{\small\theheader}\hfill\textbf{\thepage}}}
526 s = s + '\\pagestyle{empty}\n'
528 s = s + '\\makeatother\n'
529 s = s + '\\begin{document}\n'
534 s = s + one_latex_definition (t, first)
538 %% I do not see why we want to clobber the footer here
539 %% \vfill\hfill\parbox{\textwidth}{\mbox{}\makelilypondtagline}
540 %% Well, maybe you don't submit music to mutopia?
541 %% I would not object to this kind of change, but I don't know how
542 %% to get the last mutopia tagline right (ie: no footer on last page)
543 %% Please check that mutopia footers and endfooter are OK before changing
544 %% this again. -- jcn
546 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\makelilypondtagline}}%
549 s = s + '\\end{document}'
553 def run_latex (files, outbase, extra):
555 """Construct latex file, for FILES and EXTRA, dump it into
556 OUTBASE.latex. Run LaTeX on it.
562 latex_fn = outbase + '.latex'
564 wfs = find_tex_files (files, extra)
565 s = global_latex_definition (wfs, extra)
567 f = open (latex_fn, 'w')
571 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
573 if not verbose_p and os.name == 'posix':
574 progress ( _("Running %s...") % 'LaTeX')
575 cmd = cmd + ' 1> /dev/null 2> /dev/null'
579 def run_dvips (outbase, extra):
582 """Run dvips using the correct options taken from EXTRA,
583 leaving a PS file in OUTBASE.ps
590 if extra['papersize']:
591 opts = opts + ' -t%s' % extra['papersize'][0]
593 if extra['orientation'] and extra['orientation'][0] == 'landscape':
594 opts = opts + ' -tlandscape'
596 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
598 if not verbose_p and os.name == 'posix':
599 progress ( _("Running %s...") % 'dvips')
600 cmd = cmd + ' 1> /dev/null 2> /dev/null'
604 def generate_dependency_file (depfile, outname):
605 df = open (depfile, 'w')
606 df.write (outname + ':' )
608 for d in dependency_files:
610 s = re.sub ('#[^\n]*\n', '', s)
611 s = re.sub (r'\\\n', ' ', s)
612 m = re.search ('.*:(.*)\n', s)
614 # ugh. Different targets?
616 df.write ( m.group (1) + ' ' )
621 (sh, long) = getopt_args (__main__.option_definitions)
623 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
624 except getopt.error, s:
625 errorport.write ("\nerror: getopt says `%s\'\n\n" % s)
635 elif o == '--help' or o == '-h':
638 elif o == '--include' or o == '-I':
639 include_path.append (a)
640 elif o == '--postscript' or o == '-P':
642 elif o == '--keep' or o == '-k':
644 elif o == '--no-lily':
646 elif o == '--no-paper' or o == '-m':
650 elif o == '--output' or o == '-o':
652 elif o == '--set' or o == '-s':
653 ss = string.split (a, '=')
654 set_setting (extra_init, ss[0], ss[1])
655 elif o == '--dependencies' or o == '-d':
656 track_dependencies_p = 1
657 elif o == '--verbose' or o == '-V':
659 elif o == '--version' or o == '-v':
662 elif o == '--warranty' or o == '-w':
663 status = system ('lilypond -w', ignore_error = 1)
670 def cp_to_dir (pattern, dir):
671 "Copy files matching re PATTERN from cwd to DIR"
672 # Duh. Python style portable: cp *.EXT OUTDIR
673 # system ('cp *.%s %s' % (ext, outdir), 1)
674 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
675 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
677 # Python < 1.5.2 compatibility
679 # On most platforms, this is equivalent to
680 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
681 if os.path.__dict__.has_key ('abspath'):
682 abspath = os.path.abspath
685 return os.path.normpath (os.path.join (os.getcwd (), path))
687 if os.__dict__.has_key ('makedirs'):
688 makedirs = os.makedirs
690 def makedirs (dir, mode=0777):
691 system ('mkdir -p %s' % dir)
693 def mkdir_p (dir, mode=0777):
694 if not os.path.isdir (dir):
697 include_path = map (abspath, include_path)
699 original_output = output_name
701 if files and files[0] != '-':
703 files = map (lambda x: strip_extension (x, '.ly'), files)
706 output_name = os.path.basename (files[0])
708 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
709 output_name = strip_extension (output_name, i)
711 files = map (abspath, files)
713 if os.path.dirname (output_name) != '.':
714 dep_prefix = os.path.dirname (output_name)
718 reldir = os.path.dirname (output_name)
719 (outdir, outbase) = os.path.split (abspath (output_name))
728 run_lilypond (files, outbase, dep_prefix)
730 ## # TODO: friendly message about LilyPond setup/failing?
732 ## # TODO: lilypond should fail with different
733 ## # error codes for:
734 ## # - guile setup/startup failure
735 ## # - font setup failure
736 ## # - init.ly setup failure
737 ## # - parse error in .ly
738 ## # - unexpected: assert/core dump
741 if targets.has_key ('DVI') or targets.has_key ('PS'):
743 run_latex (files, outbase, extra)
744 # unless: add --tex, or --latex?
748 # # TODO: friendly message about TeX/LaTeX setup,
749 # # trying to run tex/latex by hand
750 # if targets.has_key ('DVI'):
752 # if targets.has_key ('PS'):
755 # TODO: does dvips ever fail?
756 if targets.has_key ('PS'):
757 run_dvips (outbase, extra)
759 if outdir != '.' and (track_dependencies_p or targets.keys ()):
760 mkdir_p (outdir, 0777)
762 # add DEP to targets?
763 if track_dependencies_p:
764 depfile = os.path.join (outdir, outbase + '.dep')
765 generate_dependency_file (depfile, depfile)
766 if os.path.isfile (depfile):
767 progress (_ ("dependencies output to %s...") % depfile)
769 for i in targets.keys ():
770 ext = string.lower (i)
771 cp_to_dir ('.*\.%s$' % ext, outdir)
772 outname = outbase + '.' + string.lower (i)
773 abs = os.path.join (outdir, outname)
775 outname = os.path.join (reldir, outname)
776 if os.path.isfile (abs):
777 progress (_ ("%s output to %s...") % (i, outname))
779 warning (_ ("can't find file: `%s'") % outname)
781 os.chdir (original_dir)
787 errorport.write ("ly2dvi: error: " + _ ("no files specified on command line.\n"))