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)
13 # TODO: should allow to set a central pk cache directory from the command line.
14 # TODO: should allow to switch off pk cache.
18 # Note: gettext work best if we use ' for docstrings and "
19 # for gettextable strings
24 * figure out which set of command line options should make ly2dvi:
27 na: create latex only?
28 na: create tex and latex
29 default: create dvi only
30 na: create tex, latex and dvi
36 for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
38 * move versatile taglines,
41 beginfooter=\mutopiaPD
42 endfooter=\tagline -> 'lily was here <version>'
45 lilytagline (->lily was here), usertagline, copyright etc.
47 * head/header tagline/endfooter
49 * dvi from lilypond .tex output? This is hairy, because we create dvi
50 from lilypond .tex *and* header output.
52 * multiple \score blocks?
69 sys.path.append (datadir + '/python')
72 gettext.bindtextdomain ('lilypond', '@localedir@')
73 gettext.textdomain('lilypond')
80 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
81 'footer', 'head', 'composer', 'arranger', 'instrument',
82 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
85 # init to empty; values here take precedence over values in the file
91 'latexpackages' : ['geometry'],
100 extra_fields = extra_init.keys ()
102 fields = layout_fields + extra_fields
103 program_name = 'ly2dvi'
104 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
111 PK_PATTERN='feta.*\.[0-9]+pk'
121 track_dependencies_p = 0
122 dependency_files = []
125 # lily_py.py -- options and stuff
127 # source file of the GNU LilyPond music typesetter
129 # BEGIN Library for these?
130 # cut-n-paste from ly2dvi
132 program_version = '@TOPLEVEL_VERSION@'
133 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
134 program_version = '1.3.148'
137 original_dir = os.getcwd ()
138 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
144 # Try to cater for bad installations of LilyPond, that have
145 # broken TeX setup. Just hope this doesn't hurt good TeX
146 # setups. Maybe we should check if kpsewhich can find
147 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
150 'MFINPUTS' : ':' + datadir + '/mf',
151 'TEXINPUTS': ':' + datadir + '/tex:' + datadir + '/ps',
152 'TFMFONTS' : ':' + datadir + '/tfm',
153 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
154 'GS_LIB' : datadir + '/ps',
157 def setup_environment ():
158 for key in environment.keys ():
159 val = environment[key]
160 if os.environ.has_key (key):
161 val = os.environ[key] + os.pathsep + val
162 os.environ[key] = val
165 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
169 sys.stdout.write ('\n')
170 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
171 sys.stdout.write ('\n')
172 sys.stdout.write (' Han-Wen Nienhuys')
173 sys.stdout.write (' Jan Nieuwenhuizen')
174 sys.stdout.write ('\n')
175 sys.stdout.write (_ (r'''
176 Distributed under terms of the GNU General Public License. It comes with
178 sys.stdout.write ('\n')
180 if ( os.name == 'posix' ):
186 errorport.write (s + '\n')
189 progress (_ ("warning: ") + s)
194 """Report the error S. Exit by raising an exception. Please
195 do not abuse by trying to catch this error. If you donn't want
196 a stack trace, write to the output directly.
204 progress (_ ("error: ") + s)
205 raise _ ("Exiting ... ")
207 def getopt_args (opts):
208 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
223 def option_help_str (o):
224 '''Transform one option description (4-tuple ) into neatly formatted string'''
242 return ' ' + sh + sep + long + arg
245 def options_help_str (opts):
246 '''Convert a list of options into a neatly formatted string'''
252 s = option_help_str (o)
253 strs.append ((s, o[3]))
259 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
263 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
269 (options_help_str (option_definitions)),
271 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
273 map (sys.stdout.write, ls)
277 Create a temporary directory, and return its name.
280 if not keep_temp_dir_p:
281 temp_dir = tempfile.mktemp (program_name)
283 os.mkdir (temp_dir, 0777)
290 def system (cmd, ignore_error = 0):
291 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
298 if ( os.name != 'posix' ):
299 cmd = re.sub (r'''\\''', r'''\\\\\\''', cmd)
300 cmd = "sh -c \'%s\'" % cmd
304 progress (_ ("Invoking `%s\'") % cmd)
307 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
308 msg = name + ': ' + _ ("command exited with value %d") % st
310 warning (msg + ' ' + _ ("(ignored)") + ' ')
318 if not keep_temp_dir_p:
320 progress (_ ("Cleaning %s...") % temp_dir)
321 shutil.rmtree (temp_dir)
325 def set_setting (dict, key, val):
327 val = string.atof (val)
329 #warning (_ ("invalid value: %s") % `val`)
333 dict[key].append (val)
335 warning (_ ("no such setting: %s") % `key`)
339 def strip_extension (f, ext):
340 (p, e) = os.path.splitext (f)
347 option_definitions = [
348 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
349 ('', 'h', 'help', _ ("this help")),
350 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
351 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
352 ('', '', 'no-lily', _ ("don't run LilyPond")),
353 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
354 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
356 ('', 'P', 'postscript', _ ("generate PostScript output")),
357 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
358 ('', 'V', 'verbose', _ ("verbose")),
359 ('', 'v', 'version', _ ("print version number")),
360 ('', 'w', 'warranty', _ ("show warranty and copyright")),
363 def run_lilypond (files, outbase, dep_prefix):
365 # opts = opts + '--output=%s.tex' % outbase
366 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
369 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
372 opts = opts + ' --no-paper'
374 if track_dependencies_p:
375 opts = opts + " --dependencies"
377 opts = opts + ' --dep-prefix=%s' % dep_prefix
379 fs = string.join (files)
382 progress ( _("Running %s...") % 'LilyPond')
383 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
385 opts = opts + ' --verbose'
387 system ('lilypond %s %s ' % (opts, fs))
389 def analyse_lilypond_output (filename, extra):
392 '''Grep FILENAME for interesting stuff, and
393 put relevant info into EXTRA.'''
394 filename = filename+'.tex'
395 progress (_ ("Analyzing %s...") % filename)
396 s = open (filename).read ()
398 # search only the first 10k
400 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
401 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
403 set_setting (extra, x, m.group (1))
405 def find_tex_files_for_base (base, extra):
408 Find the \header fields dumped from BASE.
412 for f in layout_fields:
413 if os.path.exists (base + '.' + f):
414 headerfiles[f] = base+'.'+f
416 if os.path.exists (base +'.dep'):
417 dependency_files.append (base + '.dep')
419 for f in extra_fields:
420 if os.path.exists (base + '.' + f):
421 extra[f].append (open (base + '.' + f).read ())
423 return (base +'.tex',headerfiles)
426 def find_tex_files (files, extra):
428 Find all .tex files whose prefixes start with some name in FILES.
437 fname = os.path.basename (f)
438 fname = strip_extension (fname, '.ly')
440 fname = fname + '-%d' % x
442 if os.path.exists (fname + '.tex'):
443 tfiles.append (find_tex_files_for_base (fname, extra))
444 analyse_lilypond_output (fname, extra)
450 fstr = string.join (files, ', ')
451 warning (_ ("no lilypond output found for %s") % fstr)
454 def one_latex_definition (defn, first):
456 for (k,v) in defn[1].items ():
457 val = open (v).read ()
458 if (string.strip (val)):
459 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
461 s = s + r'''\let\lilypond%s\relax''' % k
465 s = s + '\\def\\mustmakelilypondtitle{}\n'
467 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
469 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.
473 ly_paper_to_latexpaper = {
475 'letter' : 'letterpaper',
478 def global_latex_definition (tfiles, extra):
480 '''construct preamble from EXTRA, dump Latex stuff for each
481 lily output file in TFILES after that, and return the Latex file constructed. '''
485 s = s + '% generation tag\n'
489 if extra['papersize']:
491 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
493 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
496 if extra['latexoptions']:
497 options = options + ',' + extra['latexoptions'][-1]
499 s = s + '\\documentclass[%s]{article}\n' % options
501 if extra['language']:
502 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
505 s = s + '\\usepackage{%s}\n' \
506 % string.join (extra['latexpackages'], ',')
508 if extra['latexheaders']:
509 s = s + '\\include{%s}\n' \
510 % string.join (extra['latexheaders'], '}\n\\include{')
513 if extra['textheight']:
514 textheight = ',textheight=%fpt' % extra['textheight'][0]
516 orientation = 'portrait'
517 if extra['orientation']:
518 orientation = extra['orientation'][0]
520 # set sane geometry width (a4-width) for linewidth = -1.
521 maxlw = max (extra['linewidth'] + [-1])
523 # who the hell is 597 ?
527 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
529 if extra['latexoptions']:
530 s = s + '\geometry{twosideshift=4mm}\n'
533 \usepackage[latin1]{inputenc}
536 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
537 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
540 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
542 \renewcommand{\@evenhead}{\hbox to\textwidth{\textbf{\thepage}\hfill{\small\theheader}}}
543 \renewcommand{\@oddhead}{\hbox to \textwidth{{\small\theheader}\hfill\textbf{\thepage}}}
546 s = s + '\\pagestyle{empty}\n'
548 s = s + '\\makeatother\n'
549 s = s + '\\begin{document}\n'
554 s = s + one_latex_definition (t, first)
558 %% I do not see why we want to clobber the footer here
559 %% \vfill\hfill\parbox{\textwidth}{\mbox{}\makelilypondtagline}
560 %% Well, maybe you don't submit music to mutopia?
561 %% I would not object to this kind of change, but I don't know how
562 %% to get the last mutopia tagline right (ie: no footer on last page)
563 %% Please check that mutopia footers and endfooter are OK before changing
564 %% this again. -- jcn
565 % the \mbox{} helps latex if people do stupid things in tagline
569 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
571 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
574 \renewcommand{\@thefoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
578 s = s + '\\end{document}'
582 def run_latex (files, outbase, extra):
584 """Construct latex file, for FILES and EXTRA, dump it into
585 OUTBASE.latex. Run LaTeX on it.
591 latex_fn = outbase + '.latex'
593 wfs = find_tex_files (files, extra)
594 s = global_latex_definition (wfs, extra)
596 f = open (latex_fn, 'w')
600 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
602 if not verbose_p and os.name == 'posix':
603 progress ( _("Running %s...") % 'LaTeX')
604 cmd = cmd + ' 1> /dev/null 2> /dev/null'
608 def run_dvips (outbase, extra):
611 """Run dvips using the correct options taken from EXTRA,
612 leaving a PS file in OUTBASE.ps
619 if extra['papersize']:
620 opts = opts + ' -t%s' % extra['papersize'][0]
622 if extra['orientation'] and extra['orientation'][0] == 'landscape':
623 opts = opts + ' -tlandscape'
625 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
627 if not verbose_p and os.name == 'posix':
628 progress ( _("Running %s...") % 'dvips')
629 cmd = cmd + ' 1> /dev/null 2> /dev/null'
633 def generate_dependency_file (depfile, outname):
634 df = open (depfile, 'w')
635 df.write (outname + ':' )
637 for d in dependency_files:
639 s = re.sub ('#[^\n]*\n', '', s)
640 s = re.sub (r'\\\n', ' ', s)
641 m = re.search ('.*:(.*)\n', s)
643 # ugh. Different targets?
645 df.write ( m.group (1) + ' ' )
650 (sh, long) = getopt_args (__main__.option_definitions)
652 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
653 except getopt.error, s:
654 errorport.write ("\nerror: getopt says `%s\'\n\n" % s)
664 elif o == '--help' or o == '-h':
667 elif o == '--include' or o == '-I':
668 include_path.append (a)
669 elif o == '--postscript' or o == '-P':
671 elif o == '--keep' or o == '-k':
673 elif o == '--no-lily':
675 elif o == '--no-paper' or o == '-m':
679 elif o == '--output' or o == '-o':
681 elif o == '--set' or o == '-s':
682 ss = string.split (a, '=')
683 set_setting (extra_init, ss[0], ss[1])
684 elif o == '--dependencies' or o == '-d':
685 track_dependencies_p = 1
686 elif o == '--verbose' or o == '-V':
688 elif o == '--version' or o == '-v':
691 elif o == '--warranty' or o == '-w':
692 status = system ('lilypond -w', ignore_error = 1)
699 def cp_to_dir (pattern, dir):
700 "Copy files matching re PATTERN from cwd to DIR"
701 # Duh. Python style portable: cp *.EXT OUTDIR
702 # system ('cp *.%s %s' % (ext, outdir), 1)
703 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
704 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
706 # Python < 1.5.2 compatibility
708 # On most platforms, this is equivalent to
709 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
710 if os.path.__dict__.has_key ('abspath'):
711 abspath = os.path.abspath
714 return os.path.normpath (os.path.join (os.getcwd (), path))
716 if os.__dict__.has_key ('makedirs'):
717 makedirs = os.makedirs
719 def makedirs (dir, mode=0777):
720 system ('mkdir -p %s' % dir)
722 def mkdir_p (dir, mode=0777):
723 if not os.path.isdir (dir):
726 include_path = map (abspath, include_path)
728 original_output = output_name
730 if files and files[0] != '-':
732 files = map (lambda x: strip_extension (x, '.ly'), files)
734 (outdir, outbase) = ('','')
736 outbase = os.path.basename (files[0])
737 outdir = abspath('.')
738 elif output_name[-1] == os.sep:
739 outdir = abspath (output_name)
740 outbase = os.path.basename (files[0])
742 (outdir, outbase) = os.path.split (abspath (output_name))
744 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
745 output_name = strip_extension (output_name, i)
747 files = map (abspath, files)
749 if os.path.dirname (output_name) != '.':
750 dep_prefix = os.path.dirname (output_name)
754 reldir = os.path.dirname (output_name)
755 if outdir != '.' and (track_dependencies_p or targets.keys ()):
756 mkdir_p (outdir, 0777)
759 tmpdir = setup_temp ()
762 cp_to_dir (PK_PATTERN, tmpdir)
770 run_lilypond (files, outbase, dep_prefix)
772 ## # TODO: friendly message about LilyPond setup/failing?
774 ## # TODO: lilypond should fail with different
775 ## # error codes for:
776 ## # - guile setup/startup failure
777 ## # - font setup failure
778 ## # - init.ly setup failure
779 ## # - parse error in .ly
780 ## # - unexpected: assert/core dump
783 if targets.has_key ('DVI') or targets.has_key ('PS'):
785 run_latex (files, outbase, extra)
786 # unless: add --tex, or --latex?
790 # # TODO: friendly message about TeX/LaTeX setup,
791 # # trying to run tex/latex by hand
792 # if targets.has_key ('DVI'):
794 # if targets.has_key ('PS'):
797 # TODO: does dvips ever fail?
798 if targets.has_key ('PS'):
799 run_dvips (outbase, extra)
801 # add DEP to targets?
802 if track_dependencies_p:
803 depfile = os.path.join (outdir, outbase + '.dep')
804 generate_dependency_file (depfile, depfile)
805 if os.path.isfile (depfile):
806 progress (_ ("dependencies output to `%s'...") % depfile)
808 for i in targets.keys ():
809 ext = string.lower (i)
810 cp_to_dir ('.*\.%s$' % ext, outdir)
811 outname = outbase + '.' + string.lower (i)
812 abs = os.path.join (outdir, outname)
814 outname = os.path.join (reldir, outname)
815 if os.path.isfile (abs):
816 progress (_ ("%s output to `%s'...") % (i, outname))
818 warning (_ ("can't find file: `%s'") % outname)
821 cp_to_dir (PK_PATTERN, outdir)
823 os.chdir (original_dir)
829 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')