3 # Run lilypond, latex, dvips.
5 # This is the third incarnation of ly2dvi.
7 # Earlier incarnations of ly2dvi were written by
8 # Jeffrey B. Reed<daboys@austin.rr.com> (Python version)
9 # Jan Arne Fagertun <Jan.A.Fagertun@@energy.sintef.no> (Bourne shell script)
13 # Note: gettext work best if we use ' for docstrings and "
14 # for gettextable strings.
15 # --> DO NOT USE """ for docstrings.
20 * figure out which set of command line options should make ly2dvi:
23 na: create latex only?
24 na: create tex and latex
25 default: create dvi only
26 na: create tex, latex and dvi
32 for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
34 * move versatile taglines,
37 beginfooter=\mutopiaPD
38 endfooter=\tagline -> 'lily was here <version>'
41 lilytagline (->lily was here), usertagline, copyright etc.
43 * head/header tagline/endfooter
45 * dvi from lilypond .tex output? This is hairy, because we create dvi
46 from lilypond .tex *and* header output.
48 * multiple \score blocks?
69 ################################################################
70 # lilylib.py -- options and stuff
72 # source file of the GNU LilyPond music typesetter
76 gettext.bindtextdomain ('lilypond', localedir)
77 gettext.textdomain ('lilypond')
83 program_version = '@TOPLEVEL_VERSION@'
84 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
85 program_version = '1.5.17'
88 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
92 sys.stdout.write ('\n')
93 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001--2002'))
94 sys.stdout.write ('\n')
95 sys.stdout.write (' Han-Wen Nienhuys')
96 sys.stdout.write (' Jan Nieuwenhuizen')
97 sys.stdout.write ('\n')
98 sys.stdout.write (_ (r'''
99 Distributed under terms of the GNU General Public License. It comes with
101 sys.stdout.write ('\n')
104 errorport.write (s + '\n')
107 progress (_ ("warning: ") + s)
109 def user_error (s, e=1):
110 errorport.write (program_name + ":" + _ ("error: ") + s + '\n')
116 '''Report the error S. Exit by raising an exception. Please
117 do not abuse by trying to catch this error. If you do not want
118 a stack trace, write to the output directly.
126 progress (_ ("error: ") + s)
127 raise _ ("Exiting ... ")
129 def getopt_args (opts):
130 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
145 def option_help_str (o):
146 '''Transform one option description (4-tuple ) into neatly formatted string'''
164 return ' ' + sh + sep + long + arg
167 def options_help_str (opts):
168 '''Convert a list of options into a neatly formatted string'''
174 s = option_help_str (o)
175 strs.append ((s, o[3]))
181 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
185 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
191 (options_help_str (option_definitions)),
193 (_ ("Report bugs to %s") % 'bug-lilypond@gnu.org'),
195 map (sys.stdout.write, ls)
199 Create a temporary directory, and return its name.
202 if not keep_temp_dir_p:
203 temp_dir = tempfile.mktemp (program_name)
205 os.mkdir (temp_dir, 0777)
212 def system (cmd, ignore_error = 0):
213 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
221 progress (_ ("Invoking `%s\'") % cmd)
224 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
225 msg = name + ': ' + _ ("command exited with value %d") % st
227 warning (msg + ' ' + _ ("(ignored)") + ' ')
235 if not keep_temp_dir_p:
237 progress (_ ("Cleaning %s...") % temp_dir)
238 shutil.rmtree (temp_dir)
241 def strip_extension (f, ext):
242 (p, e) = os.path.splitext (f)
247 ################################################################
255 # if set, LILYPONDPREFIX must take prevalence
256 # if datadir is not set, we're doing a build and LILYPONDPREFIX
257 datadir = '@datadir@'
260 if os.environ.has_key ('LILYPONDPREFIX') :
261 datadir = os.environ['LILYPONDPREFIX']
263 datadir = '@datadir@'
266 while datadir[-1] == os.sep:
267 datadir= datadir[:-1]
269 program_name = 'ly2dvi'
271 original_dir = os.getcwd ()
272 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
273 errorport = sys.stderr
279 gettext.bindtextdomain ('lilypond', '@localedir@')
280 gettext.textdomain ('lilypond')
286 # Attempt to fix problems with limited stack size set by Python!
287 # Sets unlimited stack size. Note that the resource module only
288 # is available on UNIX.
291 resource.setrlimit (resource.RLIMIT_STACK, (-1, -1))
295 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
297 option_definitions = [
298 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
299 ('', 'h', 'help', _ ("this help")),
300 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
301 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
302 ('', '', 'no-lily', _ ("don't run LilyPond")),
303 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
304 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
305 (_ ("FILE"), 'f', 'find-pfa', _ ("find pfa fonts used in FILE")),
307 ('', 'P', 'postscript', _ ("generate PostScript output")),
308 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
309 ('', 'V', 'verbose', _ ("verbose")),
310 ('', 'v', 'version', _ ("print version number")),
311 ('', 'w', 'warranty', _ ("show warranty and copyright")),
314 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
315 'footer', 'head', 'composer', 'arranger', 'instrument',
316 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
319 # init to empty; values here take precedence over values in the file
321 ## TODO: change name.
325 'latexpackages' : ['geometry'],
335 extra_fields = extra_init.keys ()
336 fields = layout_fields + extra_fields
350 track_dependencies_p = 0
351 dependency_files = []
355 kpse = os.popen ('kpsexpand \$TEXMF').read()
356 kpse = re.sub('[ \t\n]+$','', kpse)
357 type1_paths = os.popen ('kpsewhich -expand-path=\$T1FONTS').read ()
360 ## todo: prevent multiple addition.
361 'TEXMF' : "{%s,%s}" % (datadir, kpse) ,
362 'GS_FONTPATH' : type1_paths,
363 'GS_LIB' : datadir + '/ps',
366 # tex needs lots of memory, more than it gets by default on Debian
367 non_path_environment = {
368 'extra_mem_top' : '1000000',
369 'extra_mem_bottom' : '1000000',
370 'pool_size' : '250000',
373 def setup_environment ():
374 for key in environment.keys ():
375 val = environment[key]
376 if os.environ.has_key (key):
377 val = os.environ[key] + os.pathsep + val
378 os.environ[key] = val
380 for key in non_path_environment.keys ():
381 val = non_path_environment[key]
382 os.environ[key] = val
385 def set_setting (dict, key, val):
387 val = string.atof (val)
389 #warning (_ ("invalid value: %s") % `val`)
393 dict[key].append (val)
395 warning (_ ("no such setting: %s") % `key`)
399 def print_environment ():
400 for (k,v) in os.environ.items ():
401 sys.stderr.write ("%s=\"%s\"\n" % (k,v))
403 def run_lilypond (files, outbase, dep_prefix):
405 # opts = opts + '--output=%s.tex' % outbase
406 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
409 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
412 opts = opts + ' --no-paper'
414 if track_dependencies_p:
415 opts = opts + " --dependencies"
417 opts = opts + ' --dep-prefix=%s' % dep_prefix
419 fs = string.join (files)
422 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
423 progress ( _("Running %s...") % 'LilyPond')
425 opts = opts + ' --verbose'
427 # for better debugging!
430 system ('lilypond %s %s ' % (opts, fs))
432 def analyse_lilypond_output (filename, extra):
435 '''Grep FILENAME for interesting stuff, and
436 put relevant info into EXTRA.'''
437 filename = filename+'.tex'
438 progress (_ ("Analyzing %s...") % filename)
439 s = open (filename).read ()
441 # search only the first 10k
443 for x in extra_fields:
444 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
446 set_setting (extra, x, m.group (1))
448 def find_tex_files_for_base (base, extra):
451 Find the \header fields dumped from BASE.
455 for f in layout_fields:
456 if os.path.exists (base + '.' + f):
457 headerfiles[f] = base+'.'+f
459 if os.path.exists (base +'.dep'):
460 dependency_files.append (base + '.dep')
462 for f in extra_fields:
463 if os.path.exists (base + '.' + f):
464 extra[f].append (open (base + '.' + f).read ())
466 return (base +'.tex',headerfiles)
469 def find_tex_files (files, extra):
471 Find all .tex files whose prefixes start with some name in FILES.
480 fname = os.path.basename (f)
481 fname = strip_extension (fname, '.ly')
483 fname = fname + '-%d' % x
485 if os.path.exists (fname + '.tex'):
486 tfiles.append (find_tex_files_for_base (fname, extra))
487 analyse_lilypond_output (fname, extra)
493 fstr = string.join (files, ', ')
494 warning (_ ("no lilypond output found for %s") % fstr)
497 def one_latex_definition (defn, first):
499 for (k,v) in defn[1].items ():
500 val = open (v).read ()
501 if (string.strip (val)):
502 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
504 s = s + r'''\let\lilypond%s\relax''' % k
508 s = s + '\\def\\mustmakelilypondtitle{}\n'
510 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
512 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.
516 ly_paper_to_latexpaper = {
518 'letter' : 'letterpaper',
521 def global_latex_definition (tfiles, extra):
523 '''construct preamble from EXTRA, dump Latex stuff for each
524 lily output file in TFILES after that, and return the Latex file constructed. '''
528 s = s + '% generation tag\n'
532 if extra['papersize']:
534 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
536 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
539 if extra['latexoptions']:
540 options = options + ',' + extra['latexoptions'][-1]
542 s = s + '\\documentclass[%s]{article}\n' % options
544 if extra['language']:
545 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
548 s = s + '\\usepackage{%s}\n' \
549 % string.join (extra['latexpackages'], ',')
551 if extra['latexheaders']:
552 s = s + '\\include{%s}\n' \
553 % string.join (extra['latexheaders'], '}\n\\include{')
556 if extra['textheight']:
557 textheight = ',textheight=%fpt' % extra['textheight'][0]
559 orientation = 'portrait'
560 if extra['orientation']:
561 orientation = extra['orientation'][0]
563 unit = extra['unit'][-1]
564 # set sane geometry width (a4-width) for linewidth = -1.
565 maxlw = max (extra['linewidth'] + [-1])
567 # who the hell is 597 ?
570 linewidth = '%d%s' % (maxlw, unit)
571 s = s + '\geometry{width=%s%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
573 if extra['latexoptions']:
574 s = s + '\geometry{twosideshift=4mm}\n'
577 \usepackage[latin1]{inputenc}
581 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
582 s = s + '\setcounter{page}{%s}\n' % (extra['pagenumber'][-1])
583 s = s + '\\pagestyle{plain}\n'
585 s = s + '\\pagestyle{empty}\n'
587 s = s + '\\begin{document}\n'
588 s = s + '\\thispagestyle{firstpage}\n'
592 s = s + one_latex_definition (t, first)
596 s = s + '\\thispagestyle{lastpage}\n'
597 s = s + '\\end{document}'
601 def run_latex (files, outbase, extra):
603 """Construct latex file, for FILES and EXTRA, dump it into
604 OUTBASE.latex. Run LaTeX on it.
610 latex_fn = outbase + '.latex'
612 wfs = find_tex_files (files, extra)
613 s = global_latex_definition (wfs, extra)
615 f = open (latex_fn, 'w')
619 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
622 progress ( _("Running %s...") % 'LaTeX')
623 cmd = cmd + ' 1> /dev/null 2> /dev/null'
627 def run_dvips (outbase, extra):
630 """Run dvips using the correct options taken from EXTRA,
631 leaving a PS file in OUTBASE.ps
638 if extra['papersize']:
639 opts = opts + ' -t%s' % extra['papersize'][0]
641 if extra['orientation'] and extra['orientation'][0] == 'landscape':
642 opts = opts + ' -tlandscape'
644 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
647 progress ( _("Running %s...") % 'dvips')
648 cmd = cmd + ' 1> /dev/null 2> /dev/null'
652 def generate_dependency_file (depfile, outname):
653 df = open (depfile, 'w')
654 df.write (outname + ':' )
656 for d in dependency_files:
658 s = re.sub ('#[^\n]*\n', '', s)
659 s = re.sub (r'\\\n', ' ', s)
660 m = re.search ('.*:(.*)\n', s)
662 # ugh. Different targets?
664 df.write ( m.group (1) + ' ' )
669 def find_file_in_path (path, name):
670 for d in string.split (path, os.pathsep):
671 if name in os.listdir (d):
672 return os.path.join (d, name)
674 # Added as functionality to ly2dvi, because ly2dvi may well need to do this
677 def find_pfa_fonts (name):
678 s = open (name).read ()
679 if s[:len (PS)] != PS:
681 errorport.write (_( "error: ") + _ ("not a PostScript file: `%s\'" % name))
682 errorport.write ('\n')
685 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
689 pfa.append (m.group (1))
690 m = re.match ('.*?/(feta[-a-z0-9]+) +findfont', s[here:], re.DOTALL)
694 (sh, long) = getopt_args (option_definitions)
696 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
697 except getopt.error, s:
698 errorport.write ('\n')
699 errorport.write (_ ("error: ") + _ ("getopt says: `%s\'" % s))
700 errorport.write ('\n')
701 errorport.write ('\n')
711 elif o == '--help' or o == '-h':
714 elif o == '--find-pfa' or o == '-f':
715 fonts = map (lambda x: x + '.pfa', find_pfa_fonts (a))
716 files = map (lambda x:
717 find_file_in_path (os.environ['GS_FONTPATH'], x),
719 print string.join (files, ' ')
721 elif o == '--include' or o == '-I':
722 include_path.append (a)
723 elif o == '--postscript' or o == '-P':
725 elif o == '--keep' or o == '-k':
727 elif o == '--no-lily':
729 elif o == '--no-paper' or o == '-m':
733 elif o == '--output' or o == '-o':
735 elif o == '--set' or o == '-s':
736 ss = string.split (a, '=')
737 set_setting (extra_init, ss[0], ss[1])
738 elif o == '--dependencies' or o == '-d':
739 track_dependencies_p = 1
740 elif o == '--verbose' or o == '-V':
742 elif o == '--version' or o == '-v':
745 elif o == '--warranty' or o == '-w':
746 status = system ('lilypond -w', ignore_error = 1)
753 def cp_to_dir (pattern, dir):
754 "Copy files matching re PATTERN from cwd to DIR"
755 # Duh. Python style portable: cp *.EXT OUTDIR
756 # system ('cp *.%s %s' % (ext, outdir), 1)
757 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
758 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
760 # Python < 1.5.2 compatibility
762 # On most platforms, this is equivalent to
763 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
764 if os.path.__dict__.has_key ('abspath'):
765 abspath = os.path.abspath
768 return os.path.normpath (os.path.join (os.getcwd (), path))
770 if os.__dict__.has_key ('makedirs'):
771 makedirs = os.makedirs
773 def makedirs (dir, mode=0777):
774 system ('mkdir -p %s' % dir)
776 def mkdir_p (dir, mode=0777):
777 if not os.path.isdir (dir):
780 include_path = map (abspath, include_path)
782 original_output = output_name
785 if files and files[0] != '-':
787 # Ugh, maybe make a setup () function
788 files = map (lambda x: strip_extension (x, '.ly'), files)
790 # hmmm. Wish I'd 've written comments when I wrote this.
791 # now it looks complicated.
793 (outdir, outbase) = ('','')
795 outbase = os.path.basename (files[0])
796 outdir = abspath('.')
797 elif output_name[-1] == os.sep:
798 outdir = abspath (output_name)
799 outbase = os.path.basename (files[0])
801 (outdir, outbase) = os.path.split (abspath (output_name))
803 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
804 output_name = strip_extension (output_name, i)
805 outbase = strip_extension (outbase, i)
806 files = map (abspath, files)
808 for i in files[:] + [output_name]:
809 if string.find (i, ' ') >= 0:
810 user_error (_ ("filename should not contain spaces: `%s'") % i)
812 if os.path.dirname (output_name) != '.':
813 dep_prefix = os.path.dirname (output_name)
817 reldir = os.path.dirname (output_name)
818 if outdir != '.' and (track_dependencies_p or targets.keys ()):
819 mkdir_p (outdir, 0777)
822 tmpdir = setup_temp ()
824 # to be sure, add tmpdir *in front* of inclusion path.
825 #os.environ['TEXINPUTS'] = tmpdir + ':' + os.environ['TEXINPUTS']
830 run_lilypond (files, outbase, dep_prefix)
832 # TODO: friendly message about LilyPond setup/failing?
834 # TODO: lilypond should fail with different
836 # - guile setup/startup failure
837 # - font setup failure
838 # - init.ly setup failure
839 # - parse error in .ly
840 # - unexpected: assert/core dump
842 traceback.print_exc ()
844 if targets.has_key ('DVI') or targets.has_key ('PS'):
846 run_latex (files, outbase, extra_init)
847 # unless: add --tex, or --latex?
851 # TODO: friendly message about TeX/LaTeX setup,
852 # trying to run tex/latex by hand
853 if targets.has_key ('DVI'):
855 if targets.has_key ('PS'):
857 traceback.print_exc ()
859 if targets.has_key ('PS'):
861 run_dvips (outbase, extra_init)
863 if targets.has_key ('PS'):
865 traceback.print_exc ()
867 # add DEP to targets?
868 if track_dependencies_p:
869 depfile = os.path.join (outdir, outbase + '.dep')
870 generate_dependency_file (depfile, depfile)
871 if os.path.isfile (depfile):
872 progress (_ ("dependencies output to `%s'...") % depfile)
874 # Hmm, if this were a function, we could call it the except: clauses
875 for i in targets.keys ():
876 ext = string.lower (i)
877 cp_to_dir ('.*\.%s$' % ext, outdir)
878 outname = outbase + '.' + string.lower (i)
879 abs = os.path.join (outdir, outname)
881 outname = os.path.join (reldir, outname)
882 if os.path.isfile (abs):
883 progress (_ ("%s output to `%s'...") % (i, outname))
885 warning (_ ("can't find file: `%s'") % outname)
887 os.chdir (original_dir)
891 # FIXME: read from stdin when files[0] = '-'
893 user_error (_ ("no files specified on command line."), 2)