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?
71 sys.path.append (datadir + '/python')
74 gettext.bindtextdomain ('lilypond', '@localedir@')
75 gettext.textdomain('lilypond')
82 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
83 'footer', 'head', 'composer', 'arranger', 'instrument',
84 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
87 # init to empty; values here take precedence over values in the file
93 'latexpackages' : ['geometry'],
102 extra_fields = extra_init.keys ()
104 fields = layout_fields + extra_fields
105 program_name = 'ly2dvi'
106 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
113 PK_PATTERN='feta.*\.[0-9]+pk'
123 track_dependencies_p = 0
124 dependency_files = []
127 # lily_py.py -- options and stuff
129 # source file of the GNU LilyPond music typesetter
131 # BEGIN Library for these?
132 # cut-n-paste from ly2dvi
134 program_version = '@TOPLEVEL_VERSION@'
135 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
136 program_version = '1.3.148'
139 original_dir = os.getcwd ()
140 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
146 # Try to cater for bad installations of LilyPond, that have
147 # broken TeX setup. Just hope this doesn't hurt good TeX
148 # setups. Maybe we should check if kpsewhich can find
149 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
152 'MFINPUTS' : datadir + '/mf' + ':',
153 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps' + ':',
154 'TFMFONTS' : datadir + '/tfm' + ':',
155 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
156 'GS_LIB' : datadir + '/ps',
159 def setup_environment ():
160 for key in environment.keys ():
161 val = environment[key]
162 if os.environ.has_key (key):
163 val = os.environ[key] + os.pathsep + val
164 os.environ[key] = val
167 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
171 sys.stdout.write ('\n')
172 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
173 sys.stdout.write ('\n')
174 sys.stdout.write (' Han-Wen Nienhuys')
175 sys.stdout.write (' Jan Nieuwenhuizen')
176 sys.stdout.write ('\n')
177 sys.stdout.write (_ (r'''
178 Distributed under terms of the GNU General Public License. It comes with
180 sys.stdout.write ('\n')
182 if ( os.name == 'posix' ):
188 errorport.write (s + '\n')
191 progress (_ ("warning: ") + s)
196 '''Report the error S. Exit by raising an exception. Please
197 do not abuse by trying to catch this error. If you do not want
198 a stack trace, write to the output directly.
206 progress (_ ("error: ") + s)
207 raise _ ("Exiting ... ")
209 def getopt_args (opts):
210 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
225 def option_help_str (o):
226 '''Transform one option description (4-tuple ) into neatly formatted string'''
244 return ' ' + sh + sep + long + arg
247 def options_help_str (opts):
248 '''Convert a list of options into a neatly formatted string'''
254 s = option_help_str (o)
255 strs.append ((s, o[3]))
261 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
265 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
271 (options_help_str (option_definitions)),
273 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
275 map (sys.stdout.write, ls)
279 Create a temporary directory, and return its name.
282 if not keep_temp_dir_p:
283 temp_dir = tempfile.mktemp (program_name)
285 os.mkdir (temp_dir, 0777)
292 def system (cmd, ignore_error = 0):
293 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
300 if ( os.name != 'posix' ):
301 cmd = re.sub (r'''\\''', r'''\\\\\\''', cmd)
302 cmd = "sh -c \'%s\'" % cmd
306 progress (_ ("Invoking `%s\'") % cmd)
309 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
310 msg = name + ': ' + _ ("command exited with value %d") % st
312 warning (msg + ' ' + _ ("(ignored)") + ' ')
320 if not keep_temp_dir_p:
322 progress (_ ("Cleaning %s...") % temp_dir)
323 shutil.rmtree (temp_dir)
327 def set_setting (dict, key, val):
329 val = string.atof (val)
331 #warning (_ ("invalid value: %s") % `val`)
335 dict[key].append (val)
337 warning (_ ("no such setting: %s") % `key`)
341 def strip_extension (f, ext):
342 (p, e) = os.path.splitext (f)
349 option_definitions = [
350 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
351 ('', 'h', 'help', _ ("this help")),
352 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
353 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
354 ('', '', 'no-lily', _ ("don't run LilyPond")),
355 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
356 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
357 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
359 ('', 'P', 'postscript', _ ("generate PostScript output")),
360 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
361 ('', 'V', 'verbose', _ ("verbose")),
362 ('', 'v', 'version', _ ("print version number")),
363 ('', 'w', 'warranty', _ ("show warranty and copyright")),
366 def run_lilypond (files, outbase, dep_prefix):
368 # opts = opts + '--output=%s.tex' % outbase
369 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
372 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
375 opts = opts + ' --no-paper'
377 if track_dependencies_p:
378 opts = opts + " --dependencies"
380 opts = opts + ' --dep-prefix=%s' % dep_prefix
382 fs = string.join (files)
385 progress ( _("Running %s...") % 'LilyPond')
386 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
388 opts = opts + ' --verbose'
390 system ('lilypond %s %s ' % (opts, fs))
392 def analyse_lilypond_output (filename, extra):
395 '''Grep FILENAME for interesting stuff, and
396 put relevant info into EXTRA.'''
397 filename = filename+'.tex'
398 progress (_ ("Analyzing %s...") % filename)
399 s = open (filename).read ()
401 # search only the first 10k
403 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
404 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
406 set_setting (extra, x, m.group (1))
408 def find_tex_files_for_base (base, extra):
411 Find the \header fields dumped from BASE.
415 for f in layout_fields:
416 if os.path.exists (base + '.' + f):
417 headerfiles[f] = base+'.'+f
419 if os.path.exists (base +'.dep'):
420 dependency_files.append (base + '.dep')
422 for f in extra_fields:
423 if os.path.exists (base + '.' + f):
424 extra[f].append (open (base + '.' + f).read ())
426 return (base +'.tex',headerfiles)
429 def find_tex_files (files, extra):
431 Find all .tex files whose prefixes start with some name in FILES.
440 fname = os.path.basename (f)
441 fname = strip_extension (fname, '.ly')
443 fname = fname + '-%d' % x
445 if os.path.exists (fname + '.tex'):
446 tfiles.append (find_tex_files_for_base (fname, extra))
447 analyse_lilypond_output (fname, extra)
453 fstr = string.join (files, ', ')
454 warning (_ ("no lilypond output found for %s") % fstr)
457 def one_latex_definition (defn, first):
459 for (k,v) in defn[1].items ():
460 val = open (v).read ()
461 if (string.strip (val)):
462 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
464 s = s + r'''\let\lilypond%s\relax''' % k
468 s = s + '\\def\\mustmakelilypondtitle{}\n'
470 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
472 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.
476 ly_paper_to_latexpaper = {
478 'letter' : 'letterpaper',
481 def global_latex_definition (tfiles, extra):
483 '''construct preamble from EXTRA, dump Latex stuff for each
484 lily output file in TFILES after that, and return the Latex file constructed. '''
488 s = s + '% generation tag\n'
492 if extra['papersize']:
494 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
496 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
499 if extra['latexoptions']:
500 options = options + ',' + extra['latexoptions'][-1]
502 s = s + '\\documentclass[%s]{article}\n' % options
504 if extra['language']:
505 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
508 s = s + '\\usepackage{%s}\n' \
509 % string.join (extra['latexpackages'], ',')
511 if extra['latexheaders']:
512 s = s + '\\include{%s}\n' \
513 % string.join (extra['latexheaders'], '}\n\\include{')
516 if extra['textheight']:
517 textheight = ',textheight=%fpt' % extra['textheight'][0]
519 orientation = 'portrait'
520 if extra['orientation']:
521 orientation = extra['orientation'][0]
523 # set sane geometry width (a4-width) for linewidth = -1.
524 maxlw = max (extra['linewidth'] + [-1])
526 # who the hell is 597 ?
530 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
532 if extra['latexoptions']:
533 s = s + '\geometry{twosideshift=4mm}\n'
536 \usepackage[latin1]{inputenc}
540 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
541 s = s + '\\pagestyle{plain}\n'
543 s = s + '\\pagestyle{empty}\n'
545 s = s + '\\begin{document}\n'
546 s = s + '\\thispagestyle{firstpage}\n'
550 s = s + one_latex_definition (t, first)
554 s = s + '\\thispagestyle{lastpage}\n'
555 s = s + '\\end{document}'
559 def run_latex (files, outbase, extra):
561 """Construct latex file, for FILES and EXTRA, dump it into
562 OUTBASE.latex. Run LaTeX on it.
568 latex_fn = outbase + '.latex'
570 wfs = find_tex_files (files, extra)
571 s = global_latex_definition (wfs, extra)
573 f = open (latex_fn, 'w')
577 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
579 if not verbose_p and os.name == 'posix':
580 progress ( _("Running %s...") % 'LaTeX')
581 cmd = cmd + ' 1> /dev/null 2> /dev/null'
585 def run_dvips (outbase, extra):
588 """Run dvips using the correct options taken from EXTRA,
589 leaving a PS file in OUTBASE.ps
596 if extra['papersize']:
597 opts = opts + ' -t%s' % extra['papersize'][0]
599 if extra['orientation'] and extra['orientation'][0] == 'landscape':
600 opts = opts + ' -tlandscape'
602 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
604 if not verbose_p and os.name == 'posix':
605 progress ( _("Running %s...") % 'dvips')
606 cmd = cmd + ' 1> /dev/null 2> /dev/null'
610 def generate_dependency_file (depfile, outname):
611 df = open (depfile, 'w')
612 df.write (outname + ':' )
614 for d in dependency_files:
616 s = re.sub ('#[^\n]*\n', '', s)
617 s = re.sub (r'\\\n', ' ', s)
618 m = re.search ('.*:(.*)\n', s)
620 # ugh. Different targets?
622 df.write ( m.group (1) + ' ' )
627 def find_file_in_path (path, name):
628 for d in string.split (path, os.pathsep):
629 if name in os.listdir (d):
630 return os.path.join (d, name)
632 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
635 def find_pfa_fonts (name):
636 s = open (name).read ()
637 if s[:len (PS)] != PS:
639 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
640 errorport.write ('\n')
643 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
647 pfa.append (m.group (1))
648 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
652 (sh, long) = getopt_args (__main__.option_definitions)
654 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
655 except getopt.error, s:
656 errorport.write ('\n')
657 errorport.write (_( "error: ") + _ ("getopt says: `%s\'" % s))
658 errorport.write ('\n')
659 errorport.write ('\n')
669 elif o == '--help' or o == '-h':
672 elif o == '--find-pfa' or o == '-f':
673 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
674 files = map (lambda x:
675 find_file_in_path (os.environ['GS_FONTPATH'], x),
677 print string.join (files, ' ')
679 elif o == '--include' or o == '-I':
680 include_path.append (a)
681 elif o == '--postscript' or o == '-P':
683 elif o == '--keep' or o == '-k':
685 elif o == '--no-lily':
687 elif o == '--no-paper' or o == '-m':
691 elif o == '--output' or o == '-o':
693 elif o == '--set' or o == '-s':
694 ss = string.split (a, '=')
695 set_setting (extra_init, ss[0], ss[1])
696 elif o == '--dependencies' or o == '-d':
697 track_dependencies_p = 1
698 elif o == '--verbose' or o == '-V':
700 elif o == '--version' or o == '-v':
703 elif o == '--warranty' or o == '-w':
704 status = system ('lilypond -w', ignore_error = 1)
711 def cp_to_dir (pattern, dir):
712 "Copy files matching re PATTERN from cwd to DIR"
713 # Duh. Python style portable: cp *.EXT OUTDIR
714 # system ('cp *.%s %s' % (ext, outdir), 1)
715 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
716 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
718 # Python < 1.5.2 compatibility
720 # On most platforms, this is equivalent to
721 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
722 if os.path.__dict__.has_key ('abspath'):
723 abspath = os.path.abspath
726 return os.path.normpath (os.path.join (os.getcwd (), path))
728 if os.__dict__.has_key ('makedirs'):
729 makedirs = os.makedirs
731 def makedirs (dir, mode=0777):
732 system ('mkdir -p %s' % dir)
734 def mkdir_p (dir, mode=0777):
735 if not os.path.isdir (dir):
738 include_path = map (abspath, include_path)
740 original_output = output_name
743 if files and files[0] != '-':
745 # Ugh, maybe make a setup () function
746 files = map (lambda x: strip_extension (x, '.ly'), files)
748 (outdir, outbase) = ('','')
750 outbase = os.path.basename (files[0])
751 outdir = abspath('.')
752 elif output_name[-1] == os.sep:
753 outdir = abspath (output_name)
754 outbase = os.path.basename (files[0])
756 (outdir, outbase) = os.path.split (abspath (output_name))
758 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
759 output_name = strip_extension (output_name, i)
761 files = map (abspath, files)
763 if os.path.dirname (output_name) != '.':
764 dep_prefix = os.path.dirname (output_name)
768 reldir = os.path.dirname (output_name)
769 if outdir != '.' and (track_dependencies_p or targets.keys ()):
770 mkdir_p (outdir, 0777)
773 tmpdir = setup_temp ()
776 cp_to_dir (PK_PATTERN, tmpdir)
782 run_lilypond (files, outbase, dep_prefix)
784 # TODO: friendly message about LilyPond setup/failing?
786 # TODO: lilypond should fail with different
788 # - guile setup/startup failure
789 # - font setup failure
790 # - init.ly setup failure
791 # - parse error in .ly
792 # - unexpected: assert/core dump
794 traceback.print_exc ()
796 if targets.has_key ('DVI') or targets.has_key ('PS'):
798 run_latex (files, outbase, extra_init)
799 # unless: add --tex, or --latex?
803 # TODO: friendly message about TeX/LaTeX setup,
804 # trying to run tex/latex by hand
805 if targets.has_key ('DVI'):
807 if targets.has_key ('PS'):
809 traceback.print_exc ()
811 if targets.has_key ('PS'):
813 run_dvips (outbase, extra_init)
815 if targets.has_key ('PS'):
817 traceback.print_exc ()
819 # add DEP to targets?
820 if track_dependencies_p:
821 depfile = os.path.join (outdir, outbase + '.dep')
822 generate_dependency_file (depfile, depfile)
823 if os.path.isfile (depfile):
824 progress (_ ("dependencies output to `%s'...") % depfile)
826 # Hmm, if this were a function, we could call it the except: clauses
827 for i in targets.keys ():
828 ext = string.lower (i)
829 cp_to_dir ('.*\.%s$' % ext, outdir)
830 outname = outbase + '.' + string.lower (i)
831 abs = os.path.join (outdir, outname)
833 outname = os.path.join (reldir, outname)
834 if os.path.isfile (abs):
835 progress (_ ("%s output to `%s'...") % (i, outname))
837 warning (_ ("can't find file: `%s'") % outname)
840 cp_to_dir (PK_PATTERN, outdir)
842 os.chdir (original_dir)
846 # FIXME: read from stdin when files[0] = '-'
848 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')