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')
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 do not 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.
298 progress (_ ("Invoking `%s\'") % cmd)
301 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
302 msg = name + ': ' + _ ("command exited with value %d") % st
304 warning (msg + ' ' + _ ("(ignored)") + ' ')
312 if not keep_temp_dir_p:
314 progress (_ ("Cleaning %s...") % temp_dir)
315 shutil.rmtree (temp_dir)
319 def set_setting (dict, key, val):
321 val = string.atof (val)
323 #warning (_ ("invalid value: %s") % `val`)
327 dict[key].append (val)
329 warning (_ ("no such setting: %s") % `key`)
333 def strip_extension (f, ext):
334 (p, e) = os.path.splitext (f)
341 option_definitions = [
342 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
343 ('', 'h', 'help', _ ("this help")),
344 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
345 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
346 ('', '', 'no-lily', _ ("don't run LilyPond")),
347 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
348 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
349 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
351 ('', 'P', 'postscript', _ ("generate PostScript output")),
352 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
353 ('', 'V', 'verbose', _ ("verbose")),
354 ('', 'v', 'version', _ ("print version number")),
355 ('', 'w', 'warranty', _ ("show warranty and copyright")),
358 def run_lilypond (files, outbase, dep_prefix):
360 # opts = opts + '--output=%s.tex' % outbase
361 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
364 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
367 opts = opts + ' --no-paper'
369 if track_dependencies_p:
370 opts = opts + " --dependencies"
372 opts = opts + ' --dep-prefix=%s' % dep_prefix
374 fs = string.join (files)
377 progress ( _("Running %s...") % 'LilyPond')
378 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
380 opts = opts + ' --verbose'
382 system ('lilypond %s %s ' % (opts, fs))
384 def analyse_lilypond_output (filename, extra):
387 '''Grep FILENAME for interesting stuff, and
388 put relevant info into EXTRA.'''
389 filename = filename+'.tex'
390 progress (_ ("Analyzing %s...") % filename)
391 s = open (filename).read ()
393 # search only the first 10k
395 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
396 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
398 set_setting (extra, x, m.group (1))
400 def find_tex_files_for_base (base, extra):
403 Find the \header fields dumped from BASE.
407 for f in layout_fields:
408 if os.path.exists (base + '.' + f):
409 headerfiles[f] = base+'.'+f
411 if os.path.exists (base +'.dep'):
412 dependency_files.append (base + '.dep')
414 for f in extra_fields:
415 if os.path.exists (base + '.' + f):
416 extra[f].append (open (base + '.' + f).read ())
418 return (base +'.tex',headerfiles)
421 def find_tex_files (files, extra):
423 Find all .tex files whose prefixes start with some name in FILES.
432 fname = os.path.basename (f)
433 fname = strip_extension (fname, '.ly')
435 fname = fname + '-%d' % x
437 if os.path.exists (fname + '.tex'):
438 tfiles.append (find_tex_files_for_base (fname, extra))
439 analyse_lilypond_output (fname, extra)
445 fstr = string.join (files, ', ')
446 warning (_ ("no lilypond output found for %s") % fstr)
449 def one_latex_definition (defn, first):
451 for (k,v) in defn[1].items ():
452 val = open (v).read ()
453 if (string.strip (val)):
454 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
456 s = s + r'''\let\lilypond%s\relax''' % k
460 s = s + '\\def\\mustmakelilypondtitle{}\n'
462 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
464 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.
468 ly_paper_to_latexpaper = {
470 'letter' : 'letterpaper',
473 def global_latex_definition (tfiles, extra):
475 '''construct preamble from EXTRA, dump Latex stuff for each
476 lily output file in TFILES after that, and return the Latex file constructed. '''
480 s = s + '% generation tag\n'
484 if extra['papersize']:
486 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
488 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
491 if extra['latexoptions']:
492 options = options + ',' + extra['latexoptions'][-1]
494 s = s + '\\documentclass[%s]{article}\n' % options
496 if extra['language']:
497 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
500 s = s + '\\usepackage{%s}\n' \
501 % string.join (extra['latexpackages'], ',')
503 if extra['latexheaders']:
504 s = s + '\\include{%s}\n' \
505 % string.join (extra['latexheaders'], '}\n\\include{')
508 if extra['textheight']:
509 textheight = ',textheight=%fpt' % extra['textheight'][0]
511 orientation = 'portrait'
512 if extra['orientation']:
513 orientation = extra['orientation'][0]
515 # set sane geometry width (a4-width) for linewidth = -1.
516 maxlw = max (extra['linewidth'] + [-1])
518 # who the hell is 597 ?
522 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
524 if extra['latexoptions']:
525 s = s + '\geometry{twosideshift=4mm}\n'
528 \usepackage[latin1]{inputenc}
532 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
533 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
534 s = s + '\\pagestyle{plain}\n'
536 s = s + '\\pagestyle{empty}\n'
538 s = s + '\\begin{document}\n'
539 s = s + '\\thispagestyle{firstpage}\n'
543 s = s + one_latex_definition (t, first)
547 s = s + '\\thispagestyle{lastpage}\n'
548 s = s + '\\end{document}'
552 def run_latex (files, outbase, extra):
554 """Construct latex file, for FILES and EXTRA, dump it into
555 OUTBASE.latex. Run LaTeX on it.
561 latex_fn = outbase + '.latex'
563 wfs = find_tex_files (files, extra)
564 s = global_latex_definition (wfs, extra)
566 f = open (latex_fn, 'w')
570 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
573 progress ( _("Running %s...") % 'LaTeX')
574 cmd = cmd + ' 1> /dev/null 2> /dev/null'
578 def run_dvips (outbase, extra):
581 """Run dvips using the correct options taken from EXTRA,
582 leaving a PS file in OUTBASE.ps
589 if extra['papersize']:
590 opts = opts + ' -t%s' % extra['papersize'][0]
592 if extra['orientation'] and extra['orientation'][0] == 'landscape':
593 opts = opts + ' -tlandscape'
595 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
598 progress ( _("Running %s...") % 'dvips')
599 cmd = cmd + ' 1> /dev/null 2> /dev/null'
603 def generate_dependency_file (depfile, outname):
604 df = open (depfile, 'w')
605 df.write (outname + ':' )
607 for d in dependency_files:
609 s = re.sub ('#[^\n]*\n', '', s)
610 s = re.sub (r'\\\n', ' ', s)
611 m = re.search ('.*:(.*)\n', s)
613 # ugh. Different targets?
615 df.write ( m.group (1) + ' ' )
620 def find_file_in_path (path, name):
621 for d in string.split (path, os.pathsep):
622 if name in os.listdir (d):
623 return os.path.join (d, name)
625 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
628 def find_pfa_fonts (name):
629 s = open (name).read ()
630 if s[:len (PS)] != PS:
632 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
633 errorport.write ('\n')
636 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
640 pfa.append (m.group (1))
641 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
645 (sh, long) = getopt_args (__main__.option_definitions)
647 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
648 except getopt.error, s:
649 errorport.write ('\n')
650 errorport.write (_( "error: ") + _ ("getopt says: `%s\'" % s))
651 errorport.write ('\n')
652 errorport.write ('\n')
662 elif o == '--help' or o == '-h':
665 elif o == '--find-pfa' or o == '-f':
666 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
667 files = map (lambda x:
668 find_file_in_path (os.environ['GS_FONTPATH'], x),
670 print string.join (files, ' ')
672 elif o == '--include' or o == '-I':
673 include_path.append (a)
674 elif o == '--postscript' or o == '-P':
676 elif o == '--keep' or o == '-k':
678 elif o == '--no-lily':
680 elif o == '--no-paper' or o == '-m':
684 elif o == '--output' or o == '-o':
686 elif o == '--set' or o == '-s':
687 ss = string.split (a, '=')
688 set_setting (extra_init, ss[0], ss[1])
689 elif o == '--dependencies' or o == '-d':
690 track_dependencies_p = 1
691 elif o == '--verbose' or o == '-V':
693 elif o == '--version' or o == '-v':
696 elif o == '--warranty' or o == '-w':
697 status = system ('lilypond -w', ignore_error = 1)
704 def cp_to_dir (pattern, dir):
705 "Copy files matching re PATTERN from cwd to DIR"
706 # Duh. Python style portable: cp *.EXT OUTDIR
707 # system ('cp *.%s %s' % (ext, outdir), 1)
708 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
709 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
711 # Python < 1.5.2 compatibility
713 # On most platforms, this is equivalent to
714 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
715 if os.path.__dict__.has_key ('abspath'):
716 abspath = os.path.abspath
719 return os.path.normpath (os.path.join (os.getcwd (), path))
721 if os.__dict__.has_key ('makedirs'):
722 makedirs = os.makedirs
724 def makedirs (dir, mode=0777):
725 system ('mkdir -p %s' % dir)
727 def mkdir_p (dir, mode=0777):
728 if not os.path.isdir (dir):
731 include_path = map (abspath, include_path)
733 original_output = output_name
736 if files and files[0] != '-':
738 # Ugh, maybe make a setup () function
739 files = map (lambda x: strip_extension (x, '.ly'), files)
741 (outdir, outbase) = ('','')
743 outbase = os.path.basename (files[0])
744 outdir = abspath('.')
745 elif output_name[-1] == os.sep:
746 outdir = abspath (output_name)
747 outbase = os.path.basename (files[0])
749 (outdir, outbase) = os.path.split (abspath (output_name))
751 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
752 output_name = strip_extension (output_name, i)
754 files = map (abspath, files)
756 if os.path.dirname (output_name) != '.':
757 dep_prefix = os.path.dirname (output_name)
761 reldir = os.path.dirname (output_name)
762 if outdir != '.' and (track_dependencies_p or targets.keys ()):
763 mkdir_p (outdir, 0777)
766 tmpdir = setup_temp ()
769 cp_to_dir (PK_PATTERN, tmpdir)
775 run_lilypond (files, outbase, dep_prefix)
777 # TODO: friendly message about LilyPond setup/failing?
779 # TODO: lilypond should fail with different
781 # - guile setup/startup failure
782 # - font setup failure
783 # - init.ly setup failure
784 # - parse error in .ly
785 # - unexpected: assert/core dump
787 traceback.print_exc ()
789 if targets.has_key ('DVI') or targets.has_key ('PS'):
791 run_latex (files, outbase, extra_init)
792 # unless: add --tex, or --latex?
796 # TODO: friendly message about TeX/LaTeX setup,
797 # trying to run tex/latex by hand
798 if targets.has_key ('DVI'):
800 if targets.has_key ('PS'):
802 traceback.print_exc ()
804 if targets.has_key ('PS'):
806 run_dvips (outbase, extra_init)
808 if targets.has_key ('PS'):
810 traceback.print_exc ()
812 # add DEP to targets?
813 if track_dependencies_p:
814 depfile = os.path.join (outdir, outbase + '.dep')
815 generate_dependency_file (depfile, depfile)
816 if os.path.isfile (depfile):
817 progress (_ ("dependencies output to `%s'...") % depfile)
819 # Hmm, if this were a function, we could call it the except: clauses
820 for i in targets.keys ():
821 ext = string.lower (i)
822 cp_to_dir ('.*\.%s$' % ext, outdir)
823 outname = outbase + '.' + string.lower (i)
824 abs = os.path.join (outdir, outname)
826 outname = os.path.join (reldir, outname)
827 if os.path.isfile (abs):
828 progress (_ ("%s output to `%s'...") % (i, outname))
830 warning (_ ("can't find file: `%s'") % outname)
833 cp_to_dir (PK_PATTERN, outdir)
835 os.chdir (original_dir)
839 # FIXME: read from stdin when files[0] = '-'
841 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')