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 = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
81 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
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 = '%s.dir' % program_name
143 # Try to cater for bad installations of LilyPond, that have
144 # broken TeX setup. Just hope this doesn't hurt good TeX
145 # setups. Maybe we should check if kpsewhich can find
146 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
149 'MFINPUTS' : ':' + datadir + '/mf',
150 'TEXINPUTS': ':' + datadir + '/tex:' + datadir + '/ps',
151 'TFMFONTS' : ':' + datadir + '/tfm',
152 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
153 'GS_LIB' : datadir + '/ps',
156 def setup_environment ():
157 for key in environment.keys ():
158 val = environment[key]
159 if os.environ.has_key (key):
160 val = os.environ[key] + os.pathsep + val
161 os.environ[key] = val
164 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
168 sys.stdout.write ('\n')
169 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
170 sys.stdout.write ('\n')
171 sys.stdout.write (' Han-Wen Nienhuys')
172 sys.stdout.write (' Jan Nieuwenhuizen')
173 sys.stdout.write ('\n')
174 sys.stdout.write (_ (r'''
175 Distributed under terms of the GNU General Public License. It comes with
177 sys.stdout.write ('\n')
179 if ( os.name == 'posix' ):
185 errorport.write (s + '\n')
188 progress (_ ("warning: ") + s)
193 """Report the error S. Exit by raising an exception. Please
194 do not abuse by trying to catch this error. If you donn't want
195 a stack trace, write to the output directly.
203 progress (_ ("error: ") + s)
204 raise _ ("Exiting ... ")
206 def getopt_args (opts):
207 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
222 def option_help_str (o):
223 '''Transform one option description (4-tuple ) into neatly formatted string'''
241 return ' ' + sh + sep + long + arg
244 def options_help_str (opts):
245 '''Convert a list of options into a neatly formatted string'''
251 s = option_help_str (o)
252 strs.append ((s, o[3]))
258 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
262 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
268 (options_help_str (option_definitions)),
270 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
272 map (sys.stdout.write, ls)
276 Create a temporary directory, and return its name.
279 if not keep_temp_dir_p:
280 temp_dir = tempfile.mktemp (program_name)
282 os.mkdir (temp_dir, 0777)
289 def system (cmd, ignore_error = 0):
290 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
297 if ( os.name != 'posix' ):
298 cmd = re.sub (r'''\\''', r'''\\\\\\''', cmd)
299 cmd = "sh -c \'%s\'" % cmd
301 progress (_ ("Invoking `%s\'") % cmd)
304 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
305 msg = name + ': ' + _ ("command exited with value %d") % st
307 warning (msg + ' ' + _ ("(ignored)") + ' ')
315 if not keep_temp_dir_p:
317 progress (_ ("Cleaning %s...") % temp_dir)
318 shutil.rmtree (temp_dir)
322 def set_setting (dict, key, val):
324 val = string.atof (val)
326 #warning (_ ("invalid value: %s") % `val`)
330 dict[key].append (val)
332 warning (_ ("no such setting: %s") % `key`)
336 def strip_extension (f, ext):
337 (p, e) = os.path.splitext (f)
344 option_definitions = [
345 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
346 ('', 'h', 'help', _ ("this help")),
347 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
348 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
349 ('', '', 'no-lily', _ ("don't run LilyPond")),
350 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
351 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
353 ('', 'P', 'postscript', _ ("generate PostScript output")),
354 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
355 ('', 'V', 'verbose', _ ("verbose")),
356 ('', 'v', 'version', _ ("print version number")),
357 ('', 'w', 'warranty', _ ("show warranty and copyright")),
360 def run_lilypond (files, outbase, dep_prefix):
362 # opts = opts + '--output=%s.tex' % outbase
363 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
366 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
369 opts = opts + ' --no-paper'
371 if track_dependencies_p:
372 opts = opts + " --dependencies"
374 opts = opts + ' --dep-prefix=%s' % dep_prefix
376 fs = string.join (files)
379 progress ( _("Running %s...") % 'LilyPond')
380 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
382 opts = opts + ' --verbose'
384 system ('lilypond %s %s ' % (opts, fs))
386 def analyse_lilypond_output (filename, extra):
389 '''Grep FILENAME for interesting stuff, and
390 put relevant info into EXTRA.'''
391 filename = filename+'.tex'
392 progress (_ ("Analyzing %s...") % filename)
393 s = open (filename).read ()
395 # search only the first 10k
397 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
398 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
400 set_setting (extra, x, m.group (1))
402 def find_tex_files_for_base (base, extra):
405 Find the \header fields dumped from BASE.
409 for f in layout_fields:
410 if os.path.exists (base + '.' + f):
411 headerfiles[f] = base+'.'+f
413 if os.path.exists (base +'.dep'):
414 dependency_files.append (base + '.dep')
416 for f in extra_fields:
417 if os.path.exists (base + '.' + f):
418 extra[f].append (open (base + '.' + f).read ())
420 return (base +'.tex',headerfiles)
423 def find_tex_files (files, extra):
425 Find all .tex files whose prefixes start with some name in FILES.
434 fname = os.path.basename (f)
435 fname = strip_extension (fname, '.ly')
437 fname = fname + '-%d' % x
439 if os.path.exists (fname + '.tex'):
440 tfiles.append (find_tex_files_for_base (fname, extra))
441 analyse_lilypond_output (fname, extra)
447 fstr = string.join (files, ', ')
448 warning (_ ("no lilypond output found for %s") % fstr)
451 def one_latex_definition (defn, first):
453 for (k,v) in defn[1].items ():
454 val = open (v).read ()
455 if (string.strip (val)):
456 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
458 s = s + r'''\let\lilypond%s\relax''' % k
462 s = s + '\\def\\mustmakelilypondtitle{}\n'
464 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
466 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.
470 ly_paper_to_latexpaper = {
472 'letter' : 'letterpaper',
475 def global_latex_definition (tfiles, extra):
477 '''construct preamble from EXTRA, dump Latex stuff for each
478 lily output file in TFILES after that, and return the Latex file constructed. '''
482 s = s + '% generation tag\n'
486 if extra['papersize']:
488 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
490 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
493 if extra['latexoptions']:
494 options = options + ',' + extra['latexoptions'][-1]
496 s = s + '\\documentclass[%s]{article}\n' % options
498 if extra['language']:
499 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
502 s = s + '\\usepackage{%s}\n' \
503 % string.join (extra['latexpackages'], ',')
505 if extra['latexheaders']:
506 s = s + '\\include{%s}\n' \
507 % string.join (extra['latexheaders'], '}\n\\include{')
510 if extra['textheight']:
511 textheight = ',textheight=%fpt' % extra['textheight'][0]
513 orientation = 'portrait'
514 if extra['orientation']:
515 orientation = extra['orientation'][0]
517 # set sane geometry width (a4-width) for linewidth = -1.
518 maxlw = max (extra['linewidth'] + [-1])
520 # who the hell is 597 ?
524 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
526 if extra['latexoptions']:
527 s = s + '\geometry{twosideshift=4mm}\n'
530 \usepackage[latin1]{inputenc}
533 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
534 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
537 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
539 \renewcommand{\@evenhead}{\hbox to\textwidth{\textbf{\thepage}\hfill{\small\theheader}}}
540 \renewcommand{\@oddhead}{\hbox to \textwidth{{\small\theheader}\hfill\textbf{\thepage}}}
543 s = s + '\\pagestyle{empty}\n'
545 s = s + '\\makeatother\n'
546 s = s + '\\begin{document}\n'
551 s = s + one_latex_definition (t, first)
555 %% I do not see why we want to clobber the footer here
556 %% \vfill\hfill\parbox{\textwidth}{\mbox{}\makelilypondtagline}
557 %% Well, maybe you don't submit music to mutopia?
558 %% I would not object to this kind of change, but I don't know how
559 %% to get the last mutopia tagline right (ie: no footer on last page)
560 %% Please check that mutopia footers and endfooter are OK before changing
561 %% this again. -- jcn
562 % the \mbox{} helps latex if people do stupid things in tagline
566 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
568 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
571 \renewcommand{\@thefoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
575 s = s + '\\end{document}'
579 def run_latex (files, outbase, extra):
581 """Construct latex file, for FILES and EXTRA, dump it into
582 OUTBASE.latex. Run LaTeX on it.
588 latex_fn = outbase + '.latex'
590 wfs = find_tex_files (files, extra)
591 s = global_latex_definition (wfs, extra)
593 f = open (latex_fn, 'w')
597 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
599 if not verbose_p and os.name == 'posix':
600 progress ( _("Running %s...") % 'LaTeX')
601 cmd = cmd + ' 1> /dev/null 2> /dev/null'
605 def run_dvips (outbase, extra):
608 """Run dvips using the correct options taken from EXTRA,
609 leaving a PS file in OUTBASE.ps
616 if extra['papersize']:
617 opts = opts + ' -t%s' % extra['papersize'][0]
619 if extra['orientation'] and extra['orientation'][0] == 'landscape':
620 opts = opts + ' -tlandscape'
622 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
624 if not verbose_p and os.name == 'posix':
625 progress ( _("Running %s...") % 'dvips')
626 cmd = cmd + ' 1> /dev/null 2> /dev/null'
630 def generate_dependency_file (depfile, outname):
631 df = open (depfile, 'w')
632 df.write (outname + ':' )
634 for d in dependency_files:
636 s = re.sub ('#[^\n]*\n', '', s)
637 s = re.sub (r'\\\n', ' ', s)
638 m = re.search ('.*:(.*)\n', s)
640 # ugh. Different targets?
642 df.write ( m.group (1) + ' ' )
647 (sh, long) = getopt_args (__main__.option_definitions)
649 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
650 except getopt.error, s:
651 errorport.write ("\nerror: getopt says `%s\'\n\n" % s)
661 elif o == '--help' or o == '-h':
664 elif o == '--include' or o == '-I':
665 include_path.append (a)
666 elif o == '--postscript' or o == '-P':
668 elif o == '--keep' or o == '-k':
670 elif o == '--no-lily':
672 elif o == '--no-paper' or o == '-m':
676 elif o == '--output' or o == '-o':
678 elif o == '--set' or o == '-s':
679 ss = string.split (a, '=')
680 set_setting (extra_init, ss[0], ss[1])
681 elif o == '--dependencies' or o == '-d':
682 track_dependencies_p = 1
683 elif o == '--verbose' or o == '-V':
685 elif o == '--version' or o == '-v':
688 elif o == '--warranty' or o == '-w':
689 status = system ('lilypond -w', ignore_error = 1)
696 def cp_to_dir (pattern, dir):
697 "Copy files matching re PATTERN from cwd to DIR"
698 # Duh. Python style portable: cp *.EXT OUTDIR
699 # system ('cp *.%s %s' % (ext, outdir), 1)
700 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
701 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
703 # Python < 1.5.2 compatibility
705 # On most platforms, this is equivalent to
706 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
707 if os.path.__dict__.has_key ('abspath'):
708 abspath = os.path.abspath
711 return os.path.normpath (os.path.join (os.getcwd (), path))
713 if os.__dict__.has_key ('makedirs'):
714 makedirs = os.makedirs
716 def makedirs (dir, mode=0777):
717 system ('mkdir -p %s' % dir)
719 def mkdir_p (dir, mode=0777):
720 if not os.path.isdir (dir):
723 include_path = map (abspath, include_path)
725 original_output = output_name
727 if files and files[0] != '-':
729 files = map (lambda x: strip_extension (x, '.ly'), files)
732 output_name = os.path.basename (files[0])
734 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
735 output_name = strip_extension (output_name, i)
737 files = map (abspath, files)
739 if os.path.dirname (output_name) != '.':
740 dep_prefix = os.path.dirname (output_name)
744 reldir = os.path.dirname (output_name)
746 (outdir, outbase) = os.path.split (abspath (output_name))
747 if outdir != '.' and (track_dependencies_p or targets.keys ()):
748 mkdir_p (outdir, 0777)
751 tmpdir = setup_temp ()
754 cp_to_dir (PK_PATTERN, tmpdir)
762 run_lilypond (files, outbase, dep_prefix)
764 ## # TODO: friendly message about LilyPond setup/failing?
766 ## # TODO: lilypond should fail with different
767 ## # error codes for:
768 ## # - guile setup/startup failure
769 ## # - font setup failure
770 ## # - init.ly setup failure
771 ## # - parse error in .ly
772 ## # - unexpected: assert/core dump
775 if targets.has_key ('DVI') or targets.has_key ('PS'):
777 run_latex (files, outbase, extra)
778 # unless: add --tex, or --latex?
782 # # TODO: friendly message about TeX/LaTeX setup,
783 # # trying to run tex/latex by hand
784 # if targets.has_key ('DVI'):
786 # if targets.has_key ('PS'):
789 # TODO: does dvips ever fail?
790 if targets.has_key ('PS'):
791 run_dvips (outbase, extra)
793 # add DEP to targets?
794 if track_dependencies_p:
795 depfile = os.path.join (outdir, outbase + '.dep')
796 generate_dependency_file (depfile, depfile)
797 if os.path.isfile (depfile):
798 progress (_ ("dependencies output to `%s'...") % depfile)
800 for i in targets.keys ():
801 ext = string.lower (i)
802 cp_to_dir ('.*\.%s$' % ext, outdir)
803 outname = outbase + '.' + string.lower (i)
804 abs = os.path.join (outdir, outname)
806 outname = os.path.join (reldir, outname)
807 if os.path.isfile (abs):
808 progress (_ ("%s output to `%s'...") % (i, outname))
810 warning (_ ("can't find file: `%s'") % outname)
813 cp_to_dir (PK_PATTERN, outdir)
815 os.chdir (original_dir)
821 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')