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.
20 # --> DO NOT USE """ for docstrings.
25 * figure out which set of command line options should make ly2dvi:
28 na: create latex only?
29 na: create tex and latex
30 default: create dvi only
31 na: create tex, latex and dvi
37 for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
39 * move versatile taglines,
42 beginfooter=\mutopiaPD
43 endfooter=\tagline -> 'lily was here <version>'
46 lilytagline (->lily was here), usertagline, copyright etc.
48 * head/header tagline/endfooter
50 * dvi from lilypond .tex output? This is hairy, because we create dvi
51 from lilypond .tex *and* header output.
53 * multiple \score blocks?
74 ################################################################
75 # lilylib.py -- options and stuff
77 # source file of the GNU LilyPond music typesetter
81 gettext.bindtextdomain ('lilypond', localedir)
82 gettext.textdomain ('lilypond')
88 program_version = '@TOPLEVEL_VERSION@'
89 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
90 program_version = '1.5.17'
93 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
97 sys.stdout.write ('\n')
98 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
99 sys.stdout.write ('\n')
100 sys.stdout.write (' Han-Wen Nienhuys')
101 sys.stdout.write (' Jan Nieuwenhuizen')
102 sys.stdout.write ('\n')
103 sys.stdout.write (_ (r'''
104 Distributed under terms of the GNU General Public License. It comes with
106 sys.stdout.write ('\n')
109 errorport.write (s + '\n')
112 progress (_ ("warning: ") + s)
114 def user_error (s, e=1):
115 errorport.write (program_name + ":" + _ ("error: ") + s + '\n')
121 '''Report the error S. Exit by raising an exception. Please
122 do not abuse by trying to catch this error. If you do not want
123 a stack trace, write to the output directly.
131 progress (_ ("error: ") + s)
132 raise _ ("Exiting ... ")
134 def getopt_args (opts):
135 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
150 def option_help_str (o):
151 '''Transform one option description (4-tuple ) into neatly formatted string'''
169 return ' ' + sh + sep + long + arg
172 def options_help_str (opts):
173 '''Convert a list of options into a neatly formatted string'''
179 s = option_help_str (o)
180 strs.append ((s, o[3]))
186 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
190 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
196 (options_help_str (option_definitions)),
198 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
200 map (sys.stdout.write, ls)
204 Create a temporary directory, and return its name.
207 if not keep_temp_dir_p:
208 temp_dir = tempfile.mktemp (program_name)
210 os.mkdir (temp_dir, 0777)
217 def system (cmd, ignore_error = 0):
218 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
226 progress (_ ("Invoking `%s\'") % cmd)
229 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
230 msg = name + ': ' + _ ("command exited with value %d") % st
232 warning (msg + ' ' + _ ("(ignored)") + ' ')
240 if not keep_temp_dir_p:
242 progress (_ ("Cleaning %s...") % temp_dir)
243 shutil.rmtree (temp_dir)
246 def strip_extension (f, ext):
247 (p, e) = os.path.splitext (f)
252 ################################################################
260 # if set, LILYPONDPREFIX must take prevalence
261 # if datadir is not set, we're doing a build and LILYPONDPREFIX
262 datadir = '@datadir@'
265 if os.environ.has_key ('LILYPONDPREFIX') :
266 # huh ? this always leads to exception.
267 # or '@datadir@' == '@' + 'datadir' + '@':
268 datadir = os.environ['LILYPONDPREFIX']
270 datadir = '@datadir@'
273 while datadir[-1] == os.sep:
274 datadir= datadir[:-1]
276 program_name = 'ly2dvi'
278 original_dir = os.getcwd ()
279 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
280 errorport = sys.stderr
286 gettext.bindtextdomain ('lilypond', '@localedir@')
287 gettext.textdomain ('lilypond')
293 # Attempt to fix problems with limited stack size set by Python!
294 # Sets unlimited stack size. Note that the resource module only
295 # is available on UNIX.
298 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
302 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
304 option_definitions = [
305 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
306 ('', 'h', 'help', _ ("this help")),
307 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
308 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
309 ('', '', 'no-lily', _ ("don't run LilyPond")),
310 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
311 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
312 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in 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 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
322 'footer', 'head', 'composer', 'arranger', 'instrument',
323 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
326 # init to empty; values here take precedence over values in the file
328 ## TODO: change name.
332 'latexpackages' : ['geometry'],
341 extra_fields = extra_init.keys ()
342 fields = layout_fields + extra_fields
349 PK_PATTERN='feta.*\.[0-9]+pk'
359 track_dependencies_p = 0
360 dependency_files = []
364 # Try to cater for bad installations of LilyPond, that have
365 # broken TeX setup. Just hope this doesn't hurt good TeX
366 # setups. Maybe we should check if kpsewhich can find
367 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
370 'MFINPUTS' : datadir + '/mf' + ':',
371 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:' + '.:'
373 'TFMFONTS' : datadir + '/tfm' + ':',
374 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
375 'GS_LIB' : datadir + '/ps',
379 def setup_environment ():
380 for key in environment.keys ():
381 val = environment[key]
382 if os.environ.has_key (key):
383 val = os.environ[key] + os.pathsep + val
384 os.environ[key] = val
387 def set_setting (dict, key, val):
389 val = string.atof (val)
391 #warning (_ ("invalid value: %s") % `val`)
395 dict[key].append (val)
397 warning (_ ("no such setting: %s") % `key`)
401 def print_environment ():
402 for (k,v) in os.environ.items ():
403 sys.stderr.write ("%s=\"%s\"\n" % (k,v))
405 def run_lilypond (files, outbase, dep_prefix):
407 # opts = opts + '--output=%s.tex' % outbase
408 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
411 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
414 opts = opts + ' --no-paper'
416 if track_dependencies_p:
417 opts = opts + " --dependencies"
419 opts = opts + ' --dep-prefix=%s' % dep_prefix
421 fs = string.join (files)
424 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
425 progress ( _("Running %s...") % 'LilyPond')
427 opts = opts + ' --verbose'
429 # for better debugging!
432 system ('lilypond %s %s ' % (opts, fs))
434 def analyse_lilypond_output (filename, extra):
437 '''Grep FILENAME for interesting stuff, and
438 put relevant info into EXTRA.'''
439 filename = filename+'.tex'
440 progress (_ ("Analyzing %s...") % filename)
441 s = open (filename).read ()
443 # search only the first 10k
445 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
446 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
448 set_setting (extra, x, m.group (1))
450 def find_tex_files_for_base (base, extra):
453 Find the \header fields dumped from BASE.
457 for f in layout_fields:
458 if os.path.exists (base + '.' + f):
459 headerfiles[f] = base+'.'+f
461 if os.path.exists (base +'.dep'):
462 dependency_files.append (base + '.dep')
464 for f in extra_fields:
465 if os.path.exists (base + '.' + f):
466 extra[f].append (open (base + '.' + f).read ())
468 return (base +'.tex',headerfiles)
471 def find_tex_files (files, extra):
473 Find all .tex files whose prefixes start with some name in FILES.
482 fname = os.path.basename (f)
483 fname = strip_extension (fname, '.ly')
485 fname = fname + '-%d' % x
487 if os.path.exists (fname + '.tex'):
488 tfiles.append (find_tex_files_for_base (fname, extra))
489 analyse_lilypond_output (fname, extra)
495 fstr = string.join (files, ', ')
496 warning (_ ("no lilypond output found for %s") % fstr)
499 def one_latex_definition (defn, first):
501 for (k,v) in defn[1].items ():
502 val = open (v).read ()
503 if (string.strip (val)):
504 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
506 s = s + r'''\let\lilypond%s\relax''' % k
510 s = s + '\\def\\mustmakelilypondtitle{}\n'
512 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
514 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.
518 ly_paper_to_latexpaper = {
520 'letter' : 'letterpaper',
523 def global_latex_definition (tfiles, extra):
525 '''construct preamble from EXTRA, dump Latex stuff for each
526 lily output file in TFILES after that, and return the Latex file constructed. '''
530 s = s + '% generation tag\n'
534 if extra['papersize']:
536 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
538 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
541 if extra['latexoptions']:
542 options = options + ',' + extra['latexoptions'][-1]
544 s = s + '\\documentclass[%s]{article}\n' % options
546 if extra['language']:
547 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
550 s = s + '\\usepackage{%s}\n' \
551 % string.join (extra['latexpackages'], ',')
553 if extra['latexheaders']:
554 s = s + '\\include{%s}\n' \
555 % string.join (extra['latexheaders'], '}\n\\include{')
558 if extra['textheight']:
559 textheight = ',textheight=%fpt' % extra['textheight'][0]
561 orientation = 'portrait'
562 if extra['orientation']:
563 orientation = extra['orientation'][0]
565 # set sane geometry width (a4-width) for linewidth = -1.
566 maxlw = max (extra['linewidth'] + [-1])
568 # who the hell is 597 ?
572 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
574 if extra['latexoptions']:
575 s = s + '\geometry{twosideshift=4mm}\n'
578 \usepackage[latin1]{inputenc}
582 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
583 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
584 s = s + '\\pagestyle{plain}\n'
586 s = s + '\\pagestyle{empty}\n'
588 s = s + '\\begin{document}\n'
589 s = s + '\\thispagestyle{firstpage}\n'
593 s = s + one_latex_definition (t, first)
597 s = s + '\\thispagestyle{lastpage}\n'
598 s = s + '\\end{document}'
602 def run_latex (files, outbase, extra):
604 """Construct latex file, for FILES and EXTRA, dump it into
605 OUTBASE.latex. Run LaTeX on it.
611 latex_fn = outbase + '.latex'
613 wfs = find_tex_files (files, extra)
614 s = global_latex_definition (wfs, extra)
616 f = open (latex_fn, 'w')
620 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
623 progress ( _("Running %s...") % 'LaTeX')
624 cmd = cmd + ' 1> /dev/null 2> /dev/null'
628 def run_dvips (outbase, extra):
631 """Run dvips using the correct options taken from EXTRA,
632 leaving a PS file in OUTBASE.ps
639 if extra['papersize']:
640 opts = opts + ' -t%s' % extra['papersize'][0]
642 if extra['orientation'] and extra['orientation'][0] == 'landscape':
643 opts = opts + ' -tlandscape'
645 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
648 progress ( _("Running %s...") % 'dvips')
649 cmd = cmd + ' 1> /dev/null 2> /dev/null'
653 def generate_dependency_file (depfile, outname):
654 df = open (depfile, 'w')
655 df.write (outname + ':' )
657 for d in dependency_files:
659 s = re.sub ('#[^\n]*\n', '', s)
660 s = re.sub (r'\\\n', ' ', s)
661 m = re.search ('.*:(.*)\n', s)
663 # ugh. Different targets?
665 df.write ( m.group (1) + ' ' )
670 def find_file_in_path (path, name):
671 for d in string.split (path, os.pathsep):
672 if name in os.listdir (d):
673 return os.path.join (d, name)
675 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
678 def find_pfa_fonts (name):
679 s = open (name).read ()
680 if s[:len (PS)] != PS:
682 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
683 errorport.write ('\n')
686 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
690 pfa.append (m.group (1))
691 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
695 (sh, long) = getopt_args (option_definitions)
697 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
698 except getopt.error, s:
699 errorport.write ('\n')
700 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
701 errorport.write ('\n')
702 errorport.write ('\n')
712 elif o == '--help' or o == '-h':
715 elif o == '--find-pfa' or o == '-f':
716 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
717 files = map (lambda x:
718 find_file_in_path (os.environ['GS_FONTPATH'], x),
720 print string.join (files, ' ')
722 elif o == '--include' or o == '-I':
723 include_path.append (a)
724 elif o == '--postscript' or o == '-P':
726 elif o == '--keep' or o == '-k':
728 elif o == '--no-lily':
730 elif o == '--no-paper' or o == '-m':
734 elif o == '--output' or o == '-o':
736 elif o == '--set' or o == '-s':
737 ss = string.split (a, '=')
738 set_setting (extra_init, ss[0], ss[1])
739 elif o == '--dependencies' or o == '-d':
740 track_dependencies_p = 1
741 elif o == '--verbose' or o == '-V':
743 elif o == '--version' or o == '-v':
746 elif o == '--warranty' or o == '-w':
747 status = system ('lilypond -w', ignore_error = 1)
754 def cp_to_dir (pattern, dir):
755 "Copy files matching re PATTERN from cwd to DIR"
756 # Duh. Python style portable: cp *.EXT OUTDIR
757 # system ('cp *.%s %s' % (ext, outdir), 1)
758 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
759 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
761 # Python < 1.5.2 compatibility
763 # On most platforms, this is equivalent to
764 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
765 if os.path.__dict__.has_key ('abspath'):
766 abspath = os.path.abspath
769 return os.path.normpath (os.path.join (os.getcwd (), path))
771 if os.__dict__.has_key ('makedirs'):
772 makedirs = os.makedirs
774 def makedirs (dir, mode=0777):
775 system ('mkdir -p %s' % dir)
777 def mkdir_p (dir, mode=0777):
778 if not os.path.isdir (dir):
781 include_path = map (abspath, include_path)
783 original_output = output_name
786 if files and files[0] != '-':
788 # Ugh, maybe make a setup () function
789 files = map (lambda x: strip_extension (x, '.ly'), files)
791 # hmmm. Wish I'd 've written comments when I wrote this.
792 # now it looks complicated.
794 (outdir, outbase) = ('','')
796 outbase = os.path.basename (files[0])
797 outdir = abspath('.')
798 elif output_name[-1] == os.sep:
799 outdir = abspath (output_name)
800 outbase = os.path.basename (files[0])
802 (outdir, outbase) = os.path.split (abspath (output_name))
804 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
805 output_name = strip_extension (output_name, i)
806 outbase = strip_extension (outbase, i)
807 files = map (abspath, files)
809 for i in files[:] + [output_name]:
810 if string.find (i, ' ') >= 0:
811 user_error (_ ("filename should not contain spaces: `%s'") % i)
813 if os.path.dirname (output_name) != '.':
814 dep_prefix = os.path.dirname (output_name)
818 reldir = os.path.dirname (output_name)
819 if outdir != '.' and (track_dependencies_p or targets.keys ()):
820 mkdir_p (outdir, 0777)
823 tmpdir = setup_temp ()
826 cp_to_dir (PK_PATTERN, tmpdir)
828 # to be sure, add tmpdir *in front* of inclusion path.
829 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
834 run_lilypond (files, outbase, dep_prefix)
836 # TODO: friendly message about LilyPond setup/failing?
838 # TODO: lilypond should fail with different
840 # - guile setup/startup failure
841 # - font setup failure
842 # - init.ly setup failure
843 # - parse error in .ly
844 # - unexpected: assert/core dump
846 traceback.print_exc ()
848 if targets.has_key ('DVI') or targets.has_key ('PS'):
850 run_latex (files, outbase, extra_init)
851 # unless: add --tex, or --latex?
855 # TODO: friendly message about TeX/LaTeX setup,
856 # trying to run tex/latex by hand
857 if targets.has_key ('DVI'):
859 if targets.has_key ('PS'):
861 traceback.print_exc ()
863 if targets.has_key ('PS'):
865 run_dvips (outbase, extra_init)
867 if targets.has_key ('PS'):
869 traceback.print_exc ()
871 # add DEP to targets?
872 if track_dependencies_p:
873 depfile = os.path.join (outdir, outbase + '.dep')
874 generate_dependency_file (depfile, depfile)
875 if os.path.isfile (depfile):
876 progress (_ ("dependencies output to `%s'...") % depfile)
878 # Hmm, if this were a function, we could call it the except: clauses
879 for i in targets.keys ():
880 ext = string.lower (i)
881 cp_to_dir ('.*\.%s$' % ext, outdir)
882 outname = outbase + '.' + string.lower (i)
883 abs = os.path.join (outdir, outname)
885 outname = os.path.join (reldir, outname)
886 if os.path.isfile (abs):
887 progress (_ ("%s output to `%s'...") % (i, outname))
889 warning (_ ("can't find file: `%s'") % outname)
892 cp_to_dir (PK_PATTERN, outdir)
894 os.chdir (original_dir)
898 # FIXME: read from stdin when files[0] = '-'
900 user_error (_ ("no files specified on command line."), 2)