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:' + os.getcwd() + ':',
163 'TFMFONTS' : datadir + '/tfm' + ':',
164 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
165 'GS_LIB' : datadir + '/ps',
168 def setup_environment ():
169 for key in environment.keys ():
170 val = environment[key]
171 if os.environ.has_key (key):
172 val = os.environ[key] + os.pathsep + val
173 os.environ[key] = val
176 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
180 sys.stdout.write ('\n')
181 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
182 sys.stdout.write ('\n')
183 sys.stdout.write (' Han-Wen Nienhuys')
184 sys.stdout.write (' Jan Nieuwenhuizen')
185 sys.stdout.write ('\n')
186 sys.stdout.write (_ (r'''
187 Distributed under terms of the GNU General Public License. It comes with
189 sys.stdout.write ('\n')
194 errorport.write (s + '\n')
197 progress (_ ("warning: ") + s)
202 '''Report the error S. Exit by raising an exception. Please
203 do not abuse by trying to catch this error. If you do not want
204 a stack trace, write to the output directly.
212 progress (_ ("error: ") + s)
213 raise _ ("Exiting ... ")
215 def getopt_args (opts):
216 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
231 def option_help_str (o):
232 '''Transform one option description (4-tuple ) into neatly formatted string'''
250 return ' ' + sh + sep + long + arg
253 def options_help_str (opts):
254 '''Convert a list of options into a neatly formatted string'''
260 s = option_help_str (o)
261 strs.append ((s, o[3]))
267 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
271 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
277 (options_help_str (option_definitions)),
279 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
281 map (sys.stdout.write, ls)
285 Create a temporary directory, and return its name.
288 if not keep_temp_dir_p:
289 temp_dir = tempfile.mktemp (program_name)
291 os.mkdir (temp_dir, 0777)
298 def system (cmd, ignore_error = 0):
299 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
307 progress (_ ("Invoking `%s\'") % cmd)
310 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
311 msg = name + ': ' + _ ("command exited with value %d") % st
313 warning (msg + ' ' + _ ("(ignored)") + ' ')
321 if not keep_temp_dir_p:
323 progress (_ ("Cleaning %s...") % temp_dir)
324 shutil.rmtree (temp_dir)
328 def set_setting (dict, key, val):
330 val = string.atof (val)
332 #warning (_ ("invalid value: %s") % `val`)
336 dict[key].append (val)
338 warning (_ ("no such setting: %s") % `key`)
342 def strip_extension (f, ext):
343 (p, e) = os.path.splitext (f)
350 option_definitions = [
351 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
352 ('', 'h', 'help', _ ("this help")),
353 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
354 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
355 ('', '', 'no-lily', _ ("don't run LilyPond")),
356 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
357 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
358 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
360 ('', 'P', 'postscript', _ ("generate PostScript output")),
361 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
362 ('', 'V', 'verbose', _ ("verbose")),
363 ('', 'v', 'version', _ ("print version number")),
364 ('', 'w', 'warranty', _ ("show warranty and copyright")),
367 def run_lilypond (files, outbase, dep_prefix):
369 # opts = opts + '--output=%s.tex' % outbase
370 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
373 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
376 opts = opts + ' --no-paper'
378 if track_dependencies_p:
379 opts = opts + " --dependencies"
381 opts = opts + ' --dep-prefix=%s' % dep_prefix
383 fs = string.join (files)
386 progress ( _("Running %s...") % 'LilyPond')
387 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
389 opts = opts + ' --verbose'
391 system ('lilypond %s %s ' % (opts, fs))
393 def analyse_lilypond_output (filename, extra):
396 '''Grep FILENAME for interesting stuff, and
397 put relevant info into EXTRA.'''
398 filename = filename+'.tex'
399 progress (_ ("Analyzing %s...") % filename)
400 s = open (filename).read ()
402 # search only the first 10k
404 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
405 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
407 set_setting (extra, x, m.group (1))
409 def find_tex_files_for_base (base, extra):
412 Find the \header fields dumped from BASE.
416 for f in layout_fields:
417 if os.path.exists (base + '.' + f):
418 headerfiles[f] = base+'.'+f
420 if os.path.exists (base +'.dep'):
421 dependency_files.append (base + '.dep')
423 for f in extra_fields:
424 if os.path.exists (base + '.' + f):
425 extra[f].append (open (base + '.' + f).read ())
427 return (base +'.tex',headerfiles)
430 def find_tex_files (files, extra):
432 Find all .tex files whose prefixes start with some name in FILES.
441 fname = os.path.basename (f)
442 fname = strip_extension (fname, '.ly')
444 fname = fname + '-%d' % x
446 if os.path.exists (fname + '.tex'):
447 tfiles.append (find_tex_files_for_base (fname, extra))
448 analyse_lilypond_output (fname, extra)
454 fstr = string.join (files, ', ')
455 warning (_ ("no lilypond output found for %s") % fstr)
458 def one_latex_definition (defn, first):
460 for (k,v) in defn[1].items ():
461 val = open (v).read ()
462 if (string.strip (val)):
463 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
465 s = s + r'''\let\lilypond%s\relax''' % k
469 s = s + '\\def\\mustmakelilypondtitle{}\n'
471 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
473 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.
477 ly_paper_to_latexpaper = {
479 'letter' : 'letterpaper',
482 def global_latex_definition (tfiles, extra):
484 '''construct preamble from EXTRA, dump Latex stuff for each
485 lily output file in TFILES after that, and return the Latex file constructed. '''
489 s = s + '% generation tag\n'
493 if extra['papersize']:
495 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
497 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
500 if extra['latexoptions']:
501 options = options + ',' + extra['latexoptions'][-1]
503 s = s + '\\documentclass[%s]{article}\n' % options
505 if extra['language']:
506 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
509 s = s + '\\usepackage{%s}\n' \
510 % string.join (extra['latexpackages'], ',')
512 if extra['latexheaders']:
513 s = s + '\\include{%s}\n' \
514 % string.join (extra['latexheaders'], '}\n\\include{')
517 if extra['textheight']:
518 textheight = ',textheight=%fpt' % extra['textheight'][0]
520 orientation = 'portrait'
521 if extra['orientation']:
522 orientation = extra['orientation'][0]
524 # set sane geometry width (a4-width) for linewidth = -1.
525 maxlw = max (extra['linewidth'] + [-1])
527 # who the hell is 597 ?
531 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
533 if extra['latexoptions']:
534 s = s + '\geometry{twosideshift=4mm}\n'
537 \usepackage[latin1]{inputenc}
541 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
542 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
543 s = s + '\\pagestyle{plain}\n'
545 s = s + '\\pagestyle{empty}\n'
547 s = s + '\\begin{document}\n'
548 s = s + '\\thispagestyle{firstpage}\n'
552 s = s + one_latex_definition (t, first)
556 s = s + '\\thispagestyle{lastpage}\n'
557 s = s + '\\end{document}'
561 def run_latex (files, outbase, extra):
563 """Construct latex file, for FILES and EXTRA, dump it into
564 OUTBASE.latex. Run LaTeX on it.
570 latex_fn = outbase + '.latex'
572 wfs = find_tex_files (files, extra)
573 s = global_latex_definition (wfs, extra)
575 f = open (latex_fn, 'w')
579 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
582 progress ( _("Running %s...") % 'LaTeX')
583 cmd = cmd + ' 1> /dev/null 2> /dev/null'
587 def run_dvips (outbase, extra):
590 """Run dvips using the correct options taken from EXTRA,
591 leaving a PS file in OUTBASE.ps
598 if extra['papersize']:
599 opts = opts + ' -t%s' % extra['papersize'][0]
601 if extra['orientation'] and extra['orientation'][0] == 'landscape':
602 opts = opts + ' -tlandscape'
604 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
607 progress ( _("Running %s...") % 'dvips')
608 cmd = cmd + ' 1> /dev/null 2> /dev/null'
612 def generate_dependency_file (depfile, outname):
613 df = open (depfile, 'w')
614 df.write (outname + ':' )
616 for d in dependency_files:
618 s = re.sub ('#[^\n]*\n', '', s)
619 s = re.sub (r'\\\n', ' ', s)
620 m = re.search ('.*:(.*)\n', s)
622 # ugh. Different targets?
624 df.write ( m.group (1) + ' ' )
629 def find_file_in_path (path, name):
630 for d in string.split (path, os.pathsep):
631 if name in os.listdir (d):
632 return os.path.join (d, name)
634 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
637 def find_pfa_fonts (name):
638 s = open (name).read ()
639 if s[:len (PS)] != PS:
641 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
642 errorport.write ('\n')
645 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
649 pfa.append (m.group (1))
650 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
654 (sh, long) = getopt_args (__main__.option_definitions)
656 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
657 except getopt.error, s:
658 errorport.write ('\n')
659 errorport.write (_( "error: ") + _ ("getopt says: `%s\'" % s))
660 errorport.write ('\n')
661 errorport.write ('\n')
671 elif o == '--help' or o == '-h':
674 elif o == '--find-pfa' or o == '-f':
675 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
676 files = map (lambda x:
677 find_file_in_path (os.environ['GS_FONTPATH'], x),
679 print string.join (files, ' ')
681 elif o == '--include' or o == '-I':
682 include_path.append (a)
683 elif o == '--postscript' or o == '-P':
685 elif o == '--keep' or o == '-k':
687 elif o == '--no-lily':
689 elif o == '--no-paper' or o == '-m':
693 elif o == '--output' or o == '-o':
695 elif o == '--set' or o == '-s':
696 ss = string.split (a, '=')
697 set_setting (extra_init, ss[0], ss[1])
698 elif o == '--dependencies' or o == '-d':
699 track_dependencies_p = 1
700 elif o == '--verbose' or o == '-V':
702 elif o == '--version' or o == '-v':
705 elif o == '--warranty' or o == '-w':
706 status = system ('lilypond -w', ignore_error = 1)
713 def cp_to_dir (pattern, dir):
714 "Copy files matching re PATTERN from cwd to DIR"
715 # Duh. Python style portable: cp *.EXT OUTDIR
716 # system ('cp *.%s %s' % (ext, outdir), 1)
717 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
718 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
720 # Python < 1.5.2 compatibility
722 # On most platforms, this is equivalent to
723 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
724 if os.path.__dict__.has_key ('abspath'):
725 abspath = os.path.abspath
728 return os.path.normpath (os.path.join (os.getcwd (), path))
730 if os.__dict__.has_key ('makedirs'):
731 makedirs = os.makedirs
733 def makedirs (dir, mode=0777):
734 system ('mkdir -p %s' % dir)
736 def mkdir_p (dir, mode=0777):
737 if not os.path.isdir (dir):
740 include_path = map (abspath, include_path)
742 original_output = output_name
745 if files and files[0] != '-':
747 # Ugh, maybe make a setup () function
748 files = map (lambda x: strip_extension (x, '.ly'), files)
750 (outdir, outbase) = ('','')
752 outbase = os.path.basename (files[0])
753 outdir = abspath('.')
754 elif output_name[-1] == os.sep:
755 outdir = abspath (output_name)
756 outbase = os.path.basename (files[0])
758 (outdir, outbase) = os.path.split (abspath (output_name))
760 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
761 output_name = strip_extension (output_name, i)
763 files = map (abspath, files)
765 if os.path.dirname (output_name) != '.':
766 dep_prefix = os.path.dirname (output_name)
770 reldir = os.path.dirname (output_name)
771 if outdir != '.' and (track_dependencies_p or targets.keys ()):
772 mkdir_p (outdir, 0777)
775 tmpdir = setup_temp ()
778 cp_to_dir (PK_PATTERN, tmpdir)
784 run_lilypond (files, outbase, dep_prefix)
786 # TODO: friendly message about LilyPond setup/failing?
788 # TODO: lilypond should fail with different
790 # - guile setup/startup failure
791 # - font setup failure
792 # - init.ly setup failure
793 # - parse error in .ly
794 # - unexpected: assert/core dump
796 traceback.print_exc ()
798 if targets.has_key ('DVI') or targets.has_key ('PS'):
800 run_latex (files, outbase, extra_init)
801 # unless: add --tex, or --latex?
805 # TODO: friendly message about TeX/LaTeX setup,
806 # trying to run tex/latex by hand
807 if targets.has_key ('DVI'):
809 if targets.has_key ('PS'):
811 traceback.print_exc ()
813 if targets.has_key ('PS'):
815 run_dvips (outbase, extra_init)
817 if targets.has_key ('PS'):
819 traceback.print_exc ()
821 # add DEP to targets?
822 if track_dependencies_p:
823 depfile = os.path.join (outdir, outbase + '.dep')
824 generate_dependency_file (depfile, depfile)
825 if os.path.isfile (depfile):
826 progress (_ ("dependencies output to `%s'...") % depfile)
828 # Hmm, if this were a function, we could call it the except: clauses
829 for i in targets.keys ():
830 ext = string.lower (i)
831 cp_to_dir ('.*\.%s$' % ext, outdir)
832 outname = outbase + '.' + string.lower (i)
833 abs = os.path.join (outdir, outname)
835 outname = os.path.join (reldir, outname)
836 if os.path.isfile (abs):
837 progress (_ ("%s output to `%s'...") % (i, outname))
839 warning (_ ("can't find file: `%s'") % outname)
842 cp_to_dir (PK_PATTERN, outdir)
844 os.chdir (original_dir)
848 # FIXME: read from stdin when files[0] = '-'
850 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')