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?
74 ################################################################
75 # lilylib.py -- options and stuff
77 # source file of the GNU LilyPond music typesetter
81 gettext.bindtextdomain ('lilypond', localedir)
82 gettext.textdomain ('lilypond')
88 program_version = '@TOPLEVEL_VERSION@'
89 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
90 program_version = '1.5.17'
93 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
97 sys.stdout.write ('\n')
98 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
99 sys.stdout.write ('\n')
100 sys.stdout.write (' Han-Wen Nienhuys')
101 sys.stdout.write (' Jan Nieuwenhuizen')
102 sys.stdout.write ('\n')
103 sys.stdout.write (_ (r'''
104 Distributed under terms of the GNU General Public License. It comes with
106 sys.stdout.write ('\n')
109 errorport.write (s + '\n')
112 progress (_ ("warning: ") + s)
117 '''Report the error S. Exit by raising an exception. Please
118 do not abuse by trying to catch this error. If you do not want
119 a stack trace, write to the output directly.
127 progress (_ ("error: ") + s)
128 raise _ ("Exiting ... ")
130 def getopt_args (opts):
131 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
146 def option_help_str (o):
147 '''Transform one option description (4-tuple ) into neatly formatted string'''
165 return ' ' + sh + sep + long + arg
168 def options_help_str (opts):
169 '''Convert a list of options into a neatly formatted string'''
175 s = option_help_str (o)
176 strs.append ((s, o[3]))
182 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
186 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
192 (options_help_str (option_definitions)),
194 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
196 map (sys.stdout.write, ls)
200 Create a temporary directory, and return its name.
203 if not keep_temp_dir_p:
204 temp_dir = tempfile.mktemp (program_name)
206 os.mkdir (temp_dir, 0777)
213 def system (cmd, ignore_error = 0):
214 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
222 progress (_ ("Invoking `%s\'") % cmd)
225 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
226 msg = name + ': ' + _ ("command exited with value %d") % st
228 warning (msg + ' ' + _ ("(ignored)") + ' ')
236 if not keep_temp_dir_p:
238 progress (_ ("Cleaning %s...") % temp_dir)
239 shutil.rmtree (temp_dir)
242 def strip_extension (f, ext):
243 (p, e) = os.path.splitext (f)
248 ################################################################
256 # if set, LILYPONDPREFIX must take prevalence
257 # if datadir is not set, we're doing a build and LILYPONDPREFIX
258 datadir = '@datadir@'
261 if os.environ.has_key ('LILYPONDPREFIX') :
262 # huh ? this always leads to exception.
263 # or '@datadir@' == '@' + 'datadir' + '@':
264 datadir = os.environ['LILYPONDPREFIX']
266 datadir = '@datadir@'
269 while datadir[-1] == os.sep:
270 datadir= datadir[:-1]
272 program_name = 'ly2dvi'
274 original_dir = os.getcwd ()
275 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
276 errorport = sys.stderr
282 gettext.bindtextdomain ('lilypond', '@localedir@')
283 gettext.textdomain ('lilypond')
289 # Attempt to fix problems with limited stack size set by Python!
290 # Sets unlimited stack size. Note that the resource module only
291 # is available on UNIX.
294 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
298 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
300 option_definitions = [
301 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
302 ('', 'h', 'help', _ ("this help")),
303 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
304 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
305 ('', '', 'no-lily', _ ("don't run LilyPond")),
306 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
307 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
308 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
310 ('', 'P', 'postscript', _ ("generate PostScript output")),
311 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
312 ('', 'V', 'verbose', _ ("verbose")),
313 ('', 'v', 'version', _ ("print version number")),
314 ('', 'w', 'warranty', _ ("show warranty and copyright")),
317 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
318 'footer', 'head', 'composer', 'arranger', 'instrument',
319 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
322 # init to empty; values here take precedence over values in the file
324 ## TODO: change name.
328 'latexpackages' : ['geometry'],
337 extra_fields = extra_init.keys ()
338 fields = layout_fields + extra_fields
345 PK_PATTERN='feta.*\.[0-9]+pk'
355 track_dependencies_p = 0
356 dependency_files = []
360 # Try to cater for bad installations of LilyPond, that have
361 # broken TeX setup. Just hope this doesn't hurt good TeX
362 # setups. Maybe we should check if kpsewhich can find
363 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
366 'MFINPUTS' : datadir + '/mf' + ':',
367 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:' + '.:'
369 'TFMFONTS' : datadir + '/tfm' + ':',
370 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
371 'GS_LIB' : datadir + '/ps',
375 def setup_environment ():
376 for key in environment.keys ():
377 val = environment[key]
378 if os.environ.has_key (key):
379 val = os.environ[key] + os.pathsep + val
380 os.environ[key] = val
383 def set_setting (dict, key, val):
385 val = string.atof (val)
387 #warning (_ ("invalid value: %s") % `val`)
391 dict[key].append (val)
393 warning (_ ("no such setting: %s") % `key`)
397 def print_environment ():
398 for (k,v) in os.environ.items ():
399 sys.stderr.write ("%s=\"%s\"\n" % (k,v))
401 def run_lilypond (files, outbase, dep_prefix):
403 # opts = opts + '--output=%s.tex' % outbase
404 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
407 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
410 opts = opts + ' --no-paper'
412 if track_dependencies_p:
413 opts = opts + " --dependencies"
415 opts = opts + ' --dep-prefix=%s' % dep_prefix
417 fs = string.join (files)
420 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
421 progress ( _("Running %s...") % 'LilyPond')
423 opts = opts + ' --verbose'
425 # for better debugging!
428 system ('lilypond %s %s ' % (opts, fs))
430 def analyse_lilypond_output (filename, extra):
433 '''Grep FILENAME for interesting stuff, and
434 put relevant info into EXTRA.'''
435 filename = filename+'.tex'
436 progress (_ ("Analyzing %s...") % filename)
437 s = open (filename).read ()
439 # search only the first 10k
441 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
442 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
444 set_setting (extra, x, m.group (1))
446 def find_tex_files_for_base (base, extra):
449 Find the \header fields dumped from BASE.
453 for f in layout_fields:
454 if os.path.exists (base + '.' + f):
455 headerfiles[f] = base+'.'+f
457 if os.path.exists (base +'.dep'):
458 dependency_files.append (base + '.dep')
460 for f in extra_fields:
461 if os.path.exists (base + '.' + f):
462 extra[f].append (open (base + '.' + f).read ())
464 return (base +'.tex',headerfiles)
467 def find_tex_files (files, extra):
469 Find all .tex files whose prefixes start with some name in FILES.
478 fname = os.path.basename (f)
479 fname = strip_extension (fname, '.ly')
481 fname = fname + '-%d' % x
483 if os.path.exists (fname + '.tex'):
484 tfiles.append (find_tex_files_for_base (fname, extra))
485 analyse_lilypond_output (fname, extra)
491 fstr = string.join (files, ', ')
492 warning (_ ("no lilypond output found for %s") % fstr)
495 def one_latex_definition (defn, first):
497 for (k,v) in defn[1].items ():
498 val = open (v).read ()
499 if (string.strip (val)):
500 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
502 s = s + r'''\let\lilypond%s\relax''' % k
506 s = s + '\\def\\mustmakelilypondtitle{}\n'
508 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
510 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.
514 ly_paper_to_latexpaper = {
516 'letter' : 'letterpaper',
519 def global_latex_definition (tfiles, extra):
521 '''construct preamble from EXTRA, dump Latex stuff for each
522 lily output file in TFILES after that, and return the Latex file constructed. '''
526 s = s + '% generation tag\n'
530 if extra['papersize']:
532 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
534 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
537 if extra['latexoptions']:
538 options = options + ',' + extra['latexoptions'][-1]
540 s = s + '\\documentclass[%s]{article}\n' % options
542 if extra['language']:
543 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
546 s = s + '\\usepackage{%s}\n' \
547 % string.join (extra['latexpackages'], ',')
549 if extra['latexheaders']:
550 s = s + '\\include{%s}\n' \
551 % string.join (extra['latexheaders'], '}\n\\include{')
554 if extra['textheight']:
555 textheight = ',textheight=%fpt' % extra['textheight'][0]
557 orientation = 'portrait'
558 if extra['orientation']:
559 orientation = extra['orientation'][0]
561 # set sane geometry width (a4-width) for linewidth = -1.
562 maxlw = max (extra['linewidth'] + [-1])
564 # who the hell is 597 ?
568 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
570 if extra['latexoptions']:
571 s = s + '\geometry{twosideshift=4mm}\n'
574 \usepackage[latin1]{inputenc}
578 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
579 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
580 s = s + '\\pagestyle{plain}\n'
582 s = s + '\\pagestyle{empty}\n'
584 s = s + '\\begin{document}\n'
585 s = s + '\\thispagestyle{firstpage}\n'
589 s = s + one_latex_definition (t, first)
593 s = s + '\\thispagestyle{lastpage}\n'
594 s = s + '\\end{document}'
598 def run_latex (files, outbase, extra):
600 """Construct latex file, for FILES and EXTRA, dump it into
601 OUTBASE.latex. Run LaTeX on it.
607 latex_fn = outbase + '.latex'
609 wfs = find_tex_files (files, extra)
610 s = global_latex_definition (wfs, extra)
612 f = open (latex_fn, 'w')
616 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
619 progress ( _("Running %s...") % 'LaTeX')
620 cmd = cmd + ' 1> /dev/null 2> /dev/null'
624 def run_dvips (outbase, extra):
627 """Run dvips using the correct options taken from EXTRA,
628 leaving a PS file in OUTBASE.ps
635 if extra['papersize']:
636 opts = opts + ' -t%s' % extra['papersize'][0]
638 if extra['orientation'] and extra['orientation'][0] == 'landscape':
639 opts = opts + ' -tlandscape'
641 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
644 progress ( _("Running %s...") % 'dvips')
645 cmd = cmd + ' 1> /dev/null 2> /dev/null'
649 def generate_dependency_file (depfile, outname):
650 df = open (depfile, 'w')
651 df.write (outname + ':' )
653 for d in dependency_files:
655 s = re.sub ('#[^\n]*\n', '', s)
656 s = re.sub (r'\\\n', ' ', s)
657 m = re.search ('.*:(.*)\n', s)
659 # ugh. Different targets?
661 df.write ( m.group (1) + ' ' )
666 def find_file_in_path (path, name):
667 for d in string.split (path, os.pathsep):
668 if name in os.listdir (d):
669 return os.path.join (d, name)
671 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
674 def find_pfa_fonts (name):
675 s = open (name).read ()
676 if s[:len (PS)] != PS:
678 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
679 errorport.write ('\n')
682 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
686 pfa.append (m.group (1))
687 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
691 (sh, long) = getopt_args (option_definitions)
693 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
694 except getopt.error, s:
695 errorport.write ('\n')
696 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
697 errorport.write ('\n')
698 errorport.write ('\n')
708 elif o == '--help' or o == '-h':
711 elif o == '--find-pfa' or o == '-f':
712 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
713 files = map (lambda x:
714 find_file_in_path (os.environ['GS_FONTPATH'], x),
716 print string.join (files, ' ')
718 elif o == '--include' or o == '-I':
719 include_path.append (a)
720 elif o == '--postscript' or o == '-P':
722 elif o == '--keep' or o == '-k':
724 elif o == '--no-lily':
726 elif o == '--no-paper' or o == '-m':
730 elif o == '--output' or o == '-o':
732 elif o == '--set' or o == '-s':
733 ss = string.split (a, '=')
734 set_setting (extra_init, ss[0], ss[1])
735 elif o == '--dependencies' or o == '-d':
736 track_dependencies_p = 1
737 elif o == '--verbose' or o == '-V':
739 elif o == '--version' or o == '-v':
742 elif o == '--warranty' or o == '-w':
743 status = system ('lilypond -w', ignore_error = 1)
750 def cp_to_dir (pattern, dir):
751 "Copy files matching re PATTERN from cwd to DIR"
752 # Duh. Python style portable: cp *.EXT OUTDIR
753 # system ('cp *.%s %s' % (ext, outdir), 1)
754 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
755 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
757 # Python < 1.5.2 compatibility
759 # On most platforms, this is equivalent to
760 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
761 if os.path.__dict__.has_key ('abspath'):
762 abspath = os.path.abspath
765 return os.path.normpath (os.path.join (os.getcwd (), path))
767 if os.__dict__.has_key ('makedirs'):
768 makedirs = os.makedirs
770 def makedirs (dir, mode=0777):
771 system ('mkdir -p %s' % dir)
773 def mkdir_p (dir, mode=0777):
774 if not os.path.isdir (dir):
777 include_path = map (abspath, include_path)
779 original_output = output_name
782 if files and files[0] != '-':
784 # Ugh, maybe make a setup () function
785 files = map (lambda x: strip_extension (x, '.ly'), files)
787 # hmmm. Wish I'd 've written comments when I wrote this.
788 # now it looks complicated.
790 (outdir, outbase) = ('','')
792 outbase = os.path.basename (files[0])
793 outdir = abspath('.')
794 elif output_name[-1] == os.sep:
795 outdir = abspath (output_name)
796 outbase = os.path.basename (files[0])
798 (outdir, outbase) = os.path.split (abspath (output_name))
800 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
801 output_name = strip_extension (output_name, i)
802 outbase = strip_extension (outbase, i)
803 files = map (abspath, files)
805 if os.path.dirname (output_name) != '.':
806 dep_prefix = os.path.dirname (output_name)
810 reldir = os.path.dirname (output_name)
811 if outdir != '.' and (track_dependencies_p or targets.keys ()):
812 mkdir_p (outdir, 0777)
815 tmpdir = setup_temp ()
818 cp_to_dir (PK_PATTERN, tmpdir)
820 # to be sure, add tmpdir *in front* of inclusion path.
821 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
826 run_lilypond (files, outbase, dep_prefix)
828 # TODO: friendly message about LilyPond setup/failing?
830 # TODO: lilypond should fail with different
832 # - guile setup/startup failure
833 # - font setup failure
834 # - init.ly setup failure
835 # - parse error in .ly
836 # - unexpected: assert/core dump
838 traceback.print_exc ()
840 if targets.has_key ('DVI') or targets.has_key ('PS'):
842 run_latex (files, outbase, extra_init)
843 # unless: add --tex, or --latex?
847 # TODO: friendly message about TeX/LaTeX setup,
848 # trying to run tex/latex by hand
849 if targets.has_key ('DVI'):
851 if targets.has_key ('PS'):
853 traceback.print_exc ()
855 if targets.has_key ('PS'):
857 run_dvips (outbase, extra_init)
859 if targets.has_key ('PS'):
861 traceback.print_exc ()
863 # add DEP to targets?
864 if track_dependencies_p:
865 depfile = os.path.join (outdir, outbase + '.dep')
866 generate_dependency_file (depfile, depfile)
867 if os.path.isfile (depfile):
868 progress (_ ("dependencies output to `%s'...") % depfile)
870 # Hmm, if this were a function, we could call it the except: clauses
871 for i in targets.keys ():
872 ext = string.lower (i)
873 cp_to_dir ('.*\.%s$' % ext, outdir)
874 outname = outbase + '.' + string.lower (i)
875 abs = os.path.join (outdir, outname)
877 outname = os.path.join (reldir, outname)
878 if os.path.isfile (abs):
879 progress (_ ("%s output to `%s'...") % (i, outname))
881 warning (_ ("can't find file: `%s'") % outname)
884 cp_to_dir (PK_PATTERN, outdir)
886 os.chdir (original_dir)
890 # FIXME: read from stdin when files[0] = '-'
892 errorport.write (program_name + ":" + _ ("error: ") + _ ("no files specified on command line.") + '\n')