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')
72 sys.path.append ('@datadir@/buildscripts/out')
76 gettext.bindtextdomain ('lilypond', '@localedir@')
77 gettext.textdomain ('lilypond')
83 # Attempt to fix problems with limited stack size set by Python!
84 # Sets unlimited stack size. Note that the resource module only
85 # is available on UNIX.
88 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
92 program_name = 'ly2dvi'
93 package_name = 'lilypond'
94 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
96 option_definitions = [
97 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
98 ('', 'h', 'help', _ ("this help")),
99 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
100 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
101 ('', '', 'no-lily', _ ("don't run LilyPond")),
102 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
103 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
104 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
106 ('', 'P', 'postscript', _ ("generate PostScript output")),
107 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
108 ('', 'V', 'verbose', _ ("verbose")),
109 ('', 'v', 'version', _ ("print version number")),
110 ('', 'w', 'warranty', _ ("show warranty and copyright")),
113 from lilylib import *
116 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
117 'footer', 'head', 'composer', 'arranger', 'instrument',
118 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
121 # init to empty; values here take precedence over values in the file
123 ## TODO: change name.
127 'latexpackages' : ['geometry'],
136 extra_fields = extra_init.keys ()
137 fields = layout_fields + extra_fields
144 PK_PATTERN='feta.*\.[0-9]+pk'
154 track_dependencies_p = 0
155 dependency_files = []
159 # Try to cater for bad installations of LilyPond, that have
160 # broken TeX setup. Just hope this doesn't hurt good TeX
161 # setups. Maybe we should check if kpsewhich can find
162 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
165 'MFINPUTS' : datadir + '/mf' + ':',
166 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:' + '.:'
168 'TFMFONTS' : datadir + '/tfm' + ':',
169 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
170 'GS_LIB' : datadir + '/ps',
173 def setup_environment ():
174 for key in environment.keys ():
175 val = environment[key]
176 if os.environ.has_key (key):
177 val = os.environ[key] + os.pathsep + val
178 os.environ[key] = val
180 def run_lilypond (files, outbase, dep_prefix):
182 # opts = opts + '--output=%s.tex' % outbase
183 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
186 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
189 opts = opts + ' --no-paper'
191 if track_dependencies_p:
192 opts = opts + " --dependencies"
194 opts = opts + ' --dep-prefix=%s' % dep_prefix
196 fs = string.join (files)
199 progress ( _("Running %s...") % 'LilyPond')
200 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
202 opts = opts + ' --verbose'
204 system ('lilypond %s %s ' % (opts, fs))
206 def analyse_lilypond_output (filename, extra):
209 '''Grep FILENAME for interesting stuff, and
210 put relevant info into EXTRA.'''
211 filename = filename+'.tex'
212 progress (_ ("Analyzing %s...") % filename)
213 s = open (filename).read ()
215 # search only the first 10k
217 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
218 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
220 set_setting (extra, x, m.group (1))
222 def find_tex_files_for_base (base, extra):
225 Find the \header fields dumped from BASE.
229 for f in layout_fields:
230 if os.path.exists (base + '.' + f):
231 headerfiles[f] = base+'.'+f
233 if os.path.exists (base +'.dep'):
234 dependency_files.append (base + '.dep')
236 for f in extra_fields:
237 if os.path.exists (base + '.' + f):
238 extra[f].append (open (base + '.' + f).read ())
240 return (base +'.tex',headerfiles)
243 def find_tex_files (files, extra):
245 Find all .tex files whose prefixes start with some name in FILES.
254 fname = os.path.basename (f)
255 fname = strip_extension (fname, '.ly')
257 fname = fname + '-%d' % x
259 if os.path.exists (fname + '.tex'):
260 tfiles.append (find_tex_files_for_base (fname, extra))
261 analyse_lilypond_output (fname, extra)
267 fstr = string.join (files, ', ')
268 warning (_ ("no lilypond output found for %s") % fstr)
271 def one_latex_definition (defn, first):
273 for (k,v) in defn[1].items ():
274 val = open (v).read ()
275 if (string.strip (val)):
276 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
278 s = s + r'''\let\lilypond%s\relax''' % k
282 s = s + '\\def\\mustmakelilypondtitle{}\n'
284 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
286 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.
290 ly_paper_to_latexpaper = {
292 'letter' : 'letterpaper',
295 def global_latex_definition (tfiles, extra):
297 '''construct preamble from EXTRA, dump Latex stuff for each
298 lily output file in TFILES after that, and return the Latex file constructed. '''
302 s = s + '% generation tag\n'
306 if extra['papersize']:
308 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
310 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
313 if extra['latexoptions']:
314 options = options + ',' + extra['latexoptions'][-1]
316 s = s + '\\documentclass[%s]{article}\n' % options
318 if extra['language']:
319 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
322 s = s + '\\usepackage{%s}\n' \
323 % string.join (extra['latexpackages'], ',')
325 if extra['latexheaders']:
326 s = s + '\\include{%s}\n' \
327 % string.join (extra['latexheaders'], '}\n\\include{')
330 if extra['textheight']:
331 textheight = ',textheight=%fpt' % extra['textheight'][0]
333 orientation = 'portrait'
334 if extra['orientation']:
335 orientation = extra['orientation'][0]
337 # set sane geometry width (a4-width) for linewidth = -1.
338 maxlw = max (extra['linewidth'] + [-1])
340 # who the hell is 597 ?
344 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
346 if extra['latexoptions']:
347 s = s + '\geometry{twosideshift=4mm}\n'
350 \usepackage[latin1]{inputenc}
354 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
355 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
356 s = s + '\\pagestyle{plain}\n'
358 s = s + '\\pagestyle{empty}\n'
360 s = s + '\\begin{document}\n'
361 s = s + '\\thispagestyle{firstpage}\n'
365 s = s + one_latex_definition (t, first)
369 s = s + '\\thispagestyle{lastpage}\n'
370 s = s + '\\end{document}'
374 def run_latex (files, outbase, extra):
376 """Construct latex file, for FILES and EXTRA, dump it into
377 OUTBASE.latex. Run LaTeX on it.
383 latex_fn = outbase + '.latex'
385 wfs = find_tex_files (files, extra)
386 s = global_latex_definition (wfs, extra)
388 f = open (latex_fn, 'w')
392 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
395 progress ( _("Running %s...") % 'LaTeX')
396 cmd = cmd + ' 1> /dev/null 2> /dev/null'
400 def run_dvips (outbase, extra):
403 """Run dvips using the correct options taken from EXTRA,
404 leaving a PS file in OUTBASE.ps
411 if extra['papersize']:
412 opts = opts + ' -t%s' % extra['papersize'][0]
414 if extra['orientation'] and extra['orientation'][0] == 'landscape':
415 opts = opts + ' -tlandscape'
417 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
420 progress ( _("Running %s...") % 'dvips')
421 cmd = cmd + ' 1> /dev/null 2> /dev/null'
425 def generate_dependency_file (depfile, outname):
426 df = open (depfile, 'w')
427 df.write (outname + ':' )
429 for d in dependency_files:
431 s = re.sub ('#[^\n]*\n', '', s)
432 s = re.sub (r'\\\n', ' ', s)
433 m = re.search ('.*:(.*)\n', s)
435 # ugh. Different targets?
437 df.write ( m.group (1) + ' ' )
442 def find_file_in_path (path, name):
443 for d in string.split (path, os.pathsep):
444 if name in os.listdir (d):
445 return os.path.join (d, name)
447 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
450 def find_pfa_fonts (name):
451 s = open (name).read ()
452 if s[:len (PS)] != PS:
454 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
455 errorport.write ('\n')
458 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
462 pfa.append (m.group (1))
463 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
467 (sh, long) = getopt_args (__main__.option_definitions)
469 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
470 except getopt.error, s:
471 errorport.write ('\n')
472 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
473 errorport.write ('\n')
474 errorport.write ('\n')
484 elif o == '--help' or o == '-h':
487 elif o == '--find-pfa' or o == '-f':
488 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
489 files = map (lambda x:
490 find_file_in_path (os.environ['GS_FONTPATH'], x),
492 print string.join (files, ' ')
494 elif o == '--include' or o == '-I':
495 include_path.append (a)
496 elif o == '--postscript' or o == '-P':
498 elif o == '--keep' or o == '-k':
500 elif o == '--no-lily':
502 elif o == '--no-paper' or o == '-m':
506 elif o == '--output' or o == '-o':
508 elif o == '--set' or o == '-s':
509 ss = string.split (a, '=')
510 set_setting (extra_init, ss[0], ss[1])
511 elif o == '--dependencies' or o == '-d':
512 track_dependencies_p = 1
513 elif o == '--verbose' or o == '-V':
515 elif o == '--version' or o == '-v':
518 elif o == '--warranty' or o == '-w':
519 status = system ('lilypond -w', ignore_error = 1)
526 def cp_to_dir (pattern, dir):
527 "Copy files matching re PATTERN from cwd to DIR"
528 # Duh. Python style portable: cp *.EXT OUTDIR
529 # system ('cp *.%s %s' % (ext, outdir), 1)
530 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
531 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
533 # Python < 1.5.2 compatibility
535 # On most platforms, this is equivalent to
536 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
537 if os.path.__dict__.has_key ('abspath'):
538 abspath = os.path.abspath
541 return os.path.normpath (os.path.join (os.getcwd (), path))
543 if os.__dict__.has_key ('makedirs'):
544 makedirs = os.makedirs
546 def makedirs (dir, mode=0777):
547 system ('mkdir -p %s' % dir)
549 def mkdir_p (dir, mode=0777):
550 if not os.path.isdir (dir):
553 include_path = map (abspath, include_path)
555 original_output = output_name
558 if files and files[0] != '-':
560 # Ugh, maybe make a setup () function
561 files = map (lambda x: strip_extension (x, '.ly'), files)
563 (outdir, outbase) = ('','')
565 outbase = os.path.basename (files[0])
566 outdir = abspath('.')
567 elif output_name[-1] == os.sep:
568 outdir = abspath (output_name)
569 outbase = os.path.basename (files[0])
571 (outdir, outbase) = os.path.split (abspath (output_name))
573 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
574 output_name = strip_extension (output_name, i)
576 files = map (abspath, files)
578 if os.path.dirname (output_name) != '.':
579 dep_prefix = os.path.dirname (output_name)
583 reldir = os.path.dirname (output_name)
584 if outdir != '.' and (track_dependencies_p or targets.keys ()):
585 mkdir_p (outdir, 0777)
588 tmpdir = setup_temp ()
591 cp_to_dir (PK_PATTERN, tmpdir)
593 # to be sure, add tmpdir *in front* of inclusion path.
594 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
599 run_lilypond (files, outbase, dep_prefix)
601 # TODO: friendly message about LilyPond setup/failing?
603 # TODO: lilypond should fail with different
605 # - guile setup/startup failure
606 # - font setup failure
607 # - init.ly setup failure
608 # - parse error in .ly
609 # - unexpected: assert/core dump
611 traceback.print_exc ()
613 if targets.has_key ('DVI') or targets.has_key ('PS'):
615 run_latex (files, outbase, extra_init)
616 # unless: add --tex, or --latex?
620 # TODO: friendly message about TeX/LaTeX setup,
621 # trying to run tex/latex by hand
622 if targets.has_key ('DVI'):
624 if targets.has_key ('PS'):
626 traceback.print_exc ()
628 if targets.has_key ('PS'):
630 run_dvips (outbase, extra_init)
632 if targets.has_key ('PS'):
634 traceback.print_exc ()
636 # add DEP to targets?
637 if track_dependencies_p:
638 depfile = os.path.join (outdir, outbase + '.dep')
639 generate_dependency_file (depfile, depfile)
640 if os.path.isfile (depfile):
641 progress (_ ("dependencies output to `%s'...") % depfile)
643 # Hmm, if this were a function, we could call it the except: clauses
644 for i in targets.keys ():
645 ext = string.lower (i)
646 cp_to_dir ('.*\.%s$' % ext, outdir)
647 outname = outbase + '.' + string.lower (i)
648 abs = os.path.join (outdir, outname)
650 outname = os.path.join (reldir, outname)
651 if os.path.isfile (abs):
652 progress (_ ("%s output to `%s'...") % (i, outname))
654 warning (_ ("can't find file: `%s'") % outname)
657 cp_to_dir (PK_PATTERN, outdir)
659 os.chdir (original_dir)
663 # FIXME: read from stdin when files[0] = '-'
665 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')