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')
81 # Attempt to fix problems with limited stack size set by Python!
82 # Sets unlimited stack size. Note that the resource module only
83 # is available on UNIX.
86 resource.setrlimit(resource.RLIMIT_STACK, (-1,-1))
91 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
92 'footer', 'head', 'composer', 'arranger', 'instrument',
93 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
96 # init to empty; values here take precedence over values in the file
102 'latexpackages' : ['geometry'],
111 extra_fields = extra_init.keys ()
113 fields = layout_fields + extra_fields
114 program_name = 'ly2dvi'
115 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
122 PK_PATTERN='feta.*\.[0-9]+pk'
132 track_dependencies_p = 0
133 dependency_files = []
136 # lily_py.py -- options and stuff
138 # source file of the GNU LilyPond music typesetter
140 # BEGIN Library for these?
141 # cut-n-paste from ly2dvi
143 program_version = '@TOPLEVEL_VERSION@'
144 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
145 program_version = '1.3.148'
148 original_dir = os.getcwd ()
149 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
155 # Try to cater for bad installations of LilyPond, that have
156 # broken TeX setup. Just hope this doesn't hurt good TeX
157 # setups. Maybe we should check if kpsewhich can find
158 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
161 'MFINPUTS' : datadir + '/mf' + ':',
162 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:' + '.:'
164 'TFMFONTS' : datadir + '/tfm' + ':',
165 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
166 'GS_LIB' : datadir + '/ps',
169 def setup_environment ():
170 for key in environment.keys ():
171 val = environment[key]
172 if os.environ.has_key (key):
173 val = os.environ[key] + os.pathsep + val
174 os.environ[key] = val
177 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
181 sys.stdout.write ('\n')
182 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
183 sys.stdout.write ('\n')
184 sys.stdout.write (' Han-Wen Nienhuys')
185 sys.stdout.write (' Jan Nieuwenhuizen')
186 sys.stdout.write ('\n')
187 sys.stdout.write (_ (r'''
188 Distributed under terms of the GNU General Public License. It comes with
190 sys.stdout.write ('\n')
195 errorport.write (s + '\n')
198 progress (_ ("warning: ") + s)
203 '''Report the error S. Exit by raising an exception. Please
204 do not abuse by trying to catch this error. If you do not want
205 a stack trace, write to the output directly.
213 progress (_ ("error: ") + s)
214 raise _ ("Exiting ... ")
216 def getopt_args (opts):
217 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
232 def option_help_str (o):
233 '''Transform one option description (4-tuple ) into neatly formatted string'''
251 return ' ' + sh + sep + long + arg
254 def options_help_str (opts):
255 '''Convert a list of options into a neatly formatted string'''
261 s = option_help_str (o)
262 strs.append ((s, o[3]))
268 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
272 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
278 (options_help_str (option_definitions)),
280 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
282 map (sys.stdout.write, ls)
286 Create a temporary directory, and return its name.
289 if not keep_temp_dir_p:
290 temp_dir = tempfile.mktemp (program_name)
292 os.mkdir (temp_dir, 0777)
299 def system (cmd, ignore_error = 0):
300 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
308 progress (_ ("Invoking `%s\'") % cmd)
311 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
312 msg = name + ': ' + _ ("command exited with value %d") % st
314 warning (msg + ' ' + _ ("(ignored)") + ' ')
322 if not keep_temp_dir_p:
324 progress (_ ("Cleaning %s...") % temp_dir)
325 shutil.rmtree (temp_dir)
329 def set_setting (dict, key, val):
331 val = string.atof (val)
333 #warning (_ ("invalid value: %s") % `val`)
337 dict[key].append (val)
339 warning (_ ("no such setting: %s") % `key`)
343 def strip_extension (f, ext):
344 (p, e) = os.path.splitext (f)
351 option_definitions = [
352 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
353 ('', 'h', 'help', _ ("this help")),
354 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
355 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
356 ('', '', 'no-lily', _ ("don't run LilyPond")),
357 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
358 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
359 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
361 ('', 'P', 'postscript', _ ("generate PostScript output")),
362 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
363 ('', 'V', 'verbose', _ ("verbose")),
364 ('', 'v', 'version', _ ("print version number")),
365 ('', 'w', 'warranty', _ ("show warranty and copyright")),
368 def run_lilypond (files, outbase, dep_prefix):
370 # opts = opts + '--output=%s.tex' % outbase
371 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
374 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
377 opts = opts + ' --no-paper'
379 if track_dependencies_p:
380 opts = opts + " --dependencies"
382 opts = opts + ' --dep-prefix=%s' % dep_prefix
384 fs = string.join (files)
387 progress ( _("Running %s...") % 'LilyPond')
388 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
390 opts = opts + ' --verbose'
392 system ('lilypond %s %s ' % (opts, fs))
394 def analyse_lilypond_output (filename, extra):
397 '''Grep FILENAME for interesting stuff, and
398 put relevant info into EXTRA.'''
399 filename = filename+'.tex'
400 progress (_ ("Analyzing %s...") % filename)
401 s = open (filename).read ()
403 # search only the first 10k
405 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
406 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
408 set_setting (extra, x, m.group (1))
410 def find_tex_files_for_base (base, extra):
413 Find the \header fields dumped from BASE.
417 for f in layout_fields:
418 if os.path.exists (base + '.' + f):
419 headerfiles[f] = base+'.'+f
421 if os.path.exists (base +'.dep'):
422 dependency_files.append (base + '.dep')
424 for f in extra_fields:
425 if os.path.exists (base + '.' + f):
426 extra[f].append (open (base + '.' + f).read ())
428 return (base +'.tex',headerfiles)
431 def find_tex_files (files, extra):
433 Find all .tex files whose prefixes start with some name in FILES.
442 fname = os.path.basename (f)
443 fname = strip_extension (fname, '.ly')
445 fname = fname + '-%d' % x
447 if os.path.exists (fname + '.tex'):
448 tfiles.append (find_tex_files_for_base (fname, extra))
449 analyse_lilypond_output (fname, extra)
455 fstr = string.join (files, ', ')
456 warning (_ ("no lilypond output found for %s") % fstr)
459 def one_latex_definition (defn, first):
461 for (k,v) in defn[1].items ():
462 val = open (v).read ()
463 if (string.strip (val)):
464 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
466 s = s + r'''\let\lilypond%s\relax''' % k
470 s = s + '\\def\\mustmakelilypondtitle{}\n'
472 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
474 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.
478 ly_paper_to_latexpaper = {
480 'letter' : 'letterpaper',
483 def global_latex_definition (tfiles, extra):
485 '''construct preamble from EXTRA, dump Latex stuff for each
486 lily output file in TFILES after that, and return the Latex file constructed. '''
490 s = s + '% generation tag\n'
494 if extra['papersize']:
496 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
498 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
501 if extra['latexoptions']:
502 options = options + ',' + extra['latexoptions'][-1]
504 s = s + '\\documentclass[%s]{article}\n' % options
506 if extra['language']:
507 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
510 s = s + '\\usepackage{%s}\n' \
511 % string.join (extra['latexpackages'], ',')
513 if extra['latexheaders']:
514 s = s + '\\include{%s}\n' \
515 % string.join (extra['latexheaders'], '}\n\\include{')
518 if extra['textheight']:
519 textheight = ',textheight=%fpt' % extra['textheight'][0]
521 orientation = 'portrait'
522 if extra['orientation']:
523 orientation = extra['orientation'][0]
525 # set sane geometry width (a4-width) for linewidth = -1.
526 maxlw = max (extra['linewidth'] + [-1])
528 # who the hell is 597 ?
532 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
534 if extra['latexoptions']:
535 s = s + '\geometry{twosideshift=4mm}\n'
538 \usepackage[latin1]{inputenc}
542 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
543 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
544 s = s + '\\pagestyle{plain}\n'
546 s = s + '\\pagestyle{empty}\n'
548 s = s + '\\begin{document}\n'
549 s = s + '\\thispagestyle{firstpage}\n'
553 s = s + one_latex_definition (t, first)
557 s = s + '\\thispagestyle{lastpage}\n'
558 s = s + '\\end{document}'
562 def run_latex (files, outbase, extra):
564 """Construct latex file, for FILES and EXTRA, dump it into
565 OUTBASE.latex. Run LaTeX on it.
571 latex_fn = outbase + '.latex'
573 wfs = find_tex_files (files, extra)
574 s = global_latex_definition (wfs, extra)
576 f = open (latex_fn, 'w')
580 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
583 progress ( _("Running %s...") % 'LaTeX')
584 cmd = cmd + ' 1> /dev/null 2> /dev/null'
588 def run_dvips (outbase, extra):
591 """Run dvips using the correct options taken from EXTRA,
592 leaving a PS file in OUTBASE.ps
599 if extra['papersize']:
600 opts = opts + ' -t%s' % extra['papersize'][0]
602 if extra['orientation'] and extra['orientation'][0] == 'landscape':
603 opts = opts + ' -tlandscape'
605 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
608 progress ( _("Running %s...") % 'dvips')
609 cmd = cmd + ' 1> /dev/null 2> /dev/null'
613 def generate_dependency_file (depfile, outname):
614 df = open (depfile, 'w')
615 df.write (outname + ':' )
617 for d in dependency_files:
619 s = re.sub ('#[^\n]*\n', '', s)
620 s = re.sub (r'\\\n', ' ', s)
621 m = re.search ('.*:(.*)\n', s)
623 # ugh. Different targets?
625 df.write ( m.group (1) + ' ' )
630 def find_file_in_path (path, name):
631 for d in string.split (path, os.pathsep):
632 if name in os.listdir (d):
633 return os.path.join (d, name)
635 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
638 def find_pfa_fonts (name):
639 s = open (name).read ()
640 if s[:len (PS)] != PS:
642 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
643 errorport.write ('\n')
646 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
650 pfa.append (m.group (1))
651 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
655 (sh, long) = getopt_args (__main__.option_definitions)
657 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
658 except getopt.error, s:
659 errorport.write ('\n')
660 errorport.write (_( "error: ") + _ ("getopt says: `%s\'" % s))
661 errorport.write ('\n')
662 errorport.write ('\n')
672 elif o == '--help' or o == '-h':
675 elif o == '--find-pfa' or o == '-f':
676 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
677 files = map (lambda x:
678 find_file_in_path (os.environ['GS_FONTPATH'], x),
680 print string.join (files, ' ')
682 elif o == '--include' or o == '-I':
683 include_path.append (a)
684 elif o == '--postscript' or o == '-P':
686 elif o == '--keep' or o == '-k':
688 elif o == '--no-lily':
690 elif o == '--no-paper' or o == '-m':
694 elif o == '--output' or o == '-o':
696 elif o == '--set' or o == '-s':
697 ss = string.split (a, '=')
698 set_setting (extra_init, ss[0], ss[1])
699 elif o == '--dependencies' or o == '-d':
700 track_dependencies_p = 1
701 elif o == '--verbose' or o == '-V':
703 elif o == '--version' or o == '-v':
706 elif o == '--warranty' or o == '-w':
707 status = system ('lilypond -w', ignore_error = 1)
714 def cp_to_dir (pattern, dir):
715 "Copy files matching re PATTERN from cwd to DIR"
716 # Duh. Python style portable: cp *.EXT OUTDIR
717 # system ('cp *.%s %s' % (ext, outdir), 1)
718 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
719 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
721 # Python < 1.5.2 compatibility
723 # On most platforms, this is equivalent to
724 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
725 if os.path.__dict__.has_key ('abspath'):
726 abspath = os.path.abspath
729 return os.path.normpath (os.path.join (os.getcwd (), path))
731 if os.__dict__.has_key ('makedirs'):
732 makedirs = os.makedirs
734 def makedirs (dir, mode=0777):
735 system ('mkdir -p %s' % dir)
737 def mkdir_p (dir, mode=0777):
738 if not os.path.isdir (dir):
741 include_path = map (abspath, include_path)
743 original_output = output_name
746 if files and files[0] != '-':
748 # Ugh, maybe make a setup () function
749 files = map (lambda x: strip_extension (x, '.ly'), files)
751 (outdir, outbase) = ('','')
753 outbase = os.path.basename (files[0])
754 outdir = abspath('.')
755 elif output_name[-1] == os.sep:
756 outdir = abspath (output_name)
757 outbase = os.path.basename (files[0])
759 (outdir, outbase) = os.path.split (abspath (output_name))
761 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
762 output_name = strip_extension (output_name, i)
764 files = map (abspath, files)
766 if os.path.dirname (output_name) != '.':
767 dep_prefix = os.path.dirname (output_name)
771 reldir = os.path.dirname (output_name)
772 if outdir != '.' and (track_dependencies_p or targets.keys ()):
773 mkdir_p (outdir, 0777)
776 tmpdir = setup_temp ()
779 cp_to_dir (PK_PATTERN, tmpdir)
785 run_lilypond (files, outbase, dep_prefix)
787 # TODO: friendly message about LilyPond setup/failing?
789 # TODO: lilypond should fail with different
791 # - guile setup/startup failure
792 # - font setup failure
793 # - init.ly setup failure
794 # - parse error in .ly
795 # - unexpected: assert/core dump
797 traceback.print_exc ()
799 if targets.has_key ('DVI') or targets.has_key ('PS'):
801 run_latex (files, outbase, extra_init)
802 # unless: add --tex, or --latex?
806 # TODO: friendly message about TeX/LaTeX setup,
807 # trying to run tex/latex by hand
808 if targets.has_key ('DVI'):
810 if targets.has_key ('PS'):
812 traceback.print_exc ()
814 if targets.has_key ('PS'):
816 run_dvips (outbase, extra_init)
818 if targets.has_key ('PS'):
820 traceback.print_exc ()
822 # add DEP to targets?
823 if track_dependencies_p:
824 depfile = os.path.join (outdir, outbase + '.dep')
825 generate_dependency_file (depfile, depfile)
826 if os.path.isfile (depfile):
827 progress (_ ("dependencies output to `%s'...") % depfile)
829 # Hmm, if this were a function, we could call it the except: clauses
830 for i in targets.keys ():
831 ext = string.lower (i)
832 cp_to_dir ('.*\.%s$' % ext, outdir)
833 outname = outbase + '.' + string.lower (i)
834 abs = os.path.join (outdir, outname)
836 outname = os.path.join (reldir, outname)
837 if os.path.isfile (abs):
838 progress (_ ("%s output to `%s'...") % (i, outname))
840 warning (_ ("can't find file: `%s'") % outname)
843 cp_to_dir (PK_PATTERN, outdir)
845 os.chdir (original_dir)
849 # FIXME: read from stdin when files[0] = '-'
851 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')