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?
70 sys.path.append (datadir + '/python')
73 gettext.bindtextdomain ('lilypond', '@localedir@')
74 gettext.textdomain('lilypond')
81 layout_fields = ['dedication', 'title', 'subtitle', 'subsubtitle',
82 'footer', 'head', 'composer', 'arranger', 'instrument',
83 'opus', 'piece', 'metre', 'meter', 'poet', 'texttranslator']
86 # init to empty; values here take precedence over values in the file
92 'latexpackages' : ['geometry'],
101 extra_fields = extra_init.keys ()
103 fields = layout_fields + extra_fields
104 program_name = 'ly2dvi'
105 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
112 PK_PATTERN='feta.*\.[0-9]+pk'
122 track_dependencies_p = 0
123 dependency_files = []
126 # lily_py.py -- options and stuff
128 # source file of the GNU LilyPond music typesetter
130 # BEGIN Library for these?
131 # cut-n-paste from ly2dvi
133 program_version = '@TOPLEVEL_VERSION@'
134 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
135 program_version = '1.3.148'
138 original_dir = os.getcwd ()
139 temp_dir = os.path.join (original_dir, '%s.dir' % program_name)
145 # Try to cater for bad installations of LilyPond, that have
146 # broken TeX setup. Just hope this doesn't hurt good TeX
147 # setups. Maybe we should check if kpsewhich can find
148 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
151 'MFINPUTS' : datadir + '/mf' + ':',
152 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps' + ':',
153 'TFMFONTS' : datadir + '/tfm' + ':',
154 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
155 'GS_LIB' : datadir + '/ps',
158 def setup_environment ():
159 for key in environment.keys ():
160 val = environment[key]
161 if os.environ.has_key (key):
162 val = os.environ[key] + os.pathsep + val
163 os.environ[key] = val
166 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
170 sys.stdout.write ('\n')
171 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
172 sys.stdout.write ('\n')
173 sys.stdout.write (' Han-Wen Nienhuys')
174 sys.stdout.write (' Jan Nieuwenhuizen')
175 sys.stdout.write ('\n')
176 sys.stdout.write (_ (r'''
177 Distributed under terms of the GNU General Public License. It comes with
179 sys.stdout.write ('\n')
181 if ( os.name == 'posix' ):
187 errorport.write (s + '\n')
190 progress (_ ("warning: ") + s)
195 '''Report the error S. Exit by raising an exception. Please
196 do not abuse by trying to catch this error. If you do not want
197 a stack trace, write to the output directly.
205 progress (_ ("error: ") + s)
206 raise _ ("Exiting ... ")
208 def getopt_args (opts):
209 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
224 def option_help_str (o):
225 '''Transform one option description (4-tuple ) into neatly formatted string'''
243 return ' ' + sh + sep + long + arg
246 def options_help_str (opts):
247 '''Convert a list of options into a neatly formatted string'''
253 s = option_help_str (o)
254 strs.append ((s, o[3]))
260 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
264 ls = [(_ ("Usage: %s [OPTION]... FILE") % program_name),
270 (options_help_str (option_definitions)),
272 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org'),
274 map (sys.stdout.write, ls)
278 Create a temporary directory, and return its name.
281 if not keep_temp_dir_p:
282 temp_dir = tempfile.mktemp (program_name)
284 os.mkdir (temp_dir, 0777)
291 def system (cmd, ignore_error = 0):
292 """Run CMD. If IGNORE_ERROR is set, don't complain when CMD returns non zero.
299 if ( os.name != 'posix' ):
300 cmd = re.sub (r'''\\''', r'''\\\\\\''', cmd)
301 cmd = "sh -c \'%s\'" % cmd
305 progress (_ ("Invoking `%s\'") % cmd)
308 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
309 msg = name + ': ' + _ ("command exited with value %d") % st
311 warning (msg + ' ' + _ ("(ignored)") + ' ')
319 if not keep_temp_dir_p:
321 progress (_ ("Cleaning %s...") % temp_dir)
322 shutil.rmtree (temp_dir)
326 def set_setting (dict, key, val):
328 val = string.atof (val)
330 #warning (_ ("invalid value: %s") % `val`)
334 dict[key].append (val)
336 warning (_ ("no such setting: %s") % `key`)
340 def strip_extension (f, ext):
341 (p, e) = os.path.splitext (f)
348 option_definitions = [
349 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
350 ('', 'h', 'help', _ ("this help")),
351 (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
352 ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
353 ('', '', 'no-lily', _ ("don't run LilyPond")),
354 ('', 'm', 'no-paper', _ ("produce MIDI output only")),
355 (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
357 ('', 'P', 'postscript', _ ("generate PostScript output")),
358 (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
359 ('', 'V', 'verbose', _ ("verbose")),
360 ('', 'v', 'version', _ ("print version number")),
361 ('', 'w', 'warranty', _ ("show warranty and copyright")),
364 def run_lilypond (files, outbase, dep_prefix):
366 # opts = opts + '--output=%s.tex' % outbase
367 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x,
370 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x,
373 opts = opts + ' --no-paper'
375 if track_dependencies_p:
376 opts = opts + " --dependencies"
378 opts = opts + ' --dep-prefix=%s' % dep_prefix
380 fs = string.join (files)
383 progress ( _("Running %s...") % 'LilyPond')
384 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
386 opts = opts + ' --verbose'
388 system ('lilypond %s %s ' % (opts, fs))
390 def analyse_lilypond_output (filename, extra):
393 '''Grep FILENAME for interesting stuff, and
394 put relevant info into EXTRA.'''
395 filename = filename+'.tex'
396 progress (_ ("Analyzing %s...") % filename)
397 s = open (filename).read ()
399 # search only the first 10k
401 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
402 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
404 set_setting (extra, x, m.group (1))
406 def find_tex_files_for_base (base, extra):
409 Find the \header fields dumped from BASE.
413 for f in layout_fields:
414 if os.path.exists (base + '.' + f):
415 headerfiles[f] = base+'.'+f
417 if os.path.exists (base +'.dep'):
418 dependency_files.append (base + '.dep')
420 for f in extra_fields:
421 if os.path.exists (base + '.' + f):
422 extra[f].append (open (base + '.' + f).read ())
424 return (base +'.tex',headerfiles)
427 def find_tex_files (files, extra):
429 Find all .tex files whose prefixes start with some name in FILES.
438 fname = os.path.basename (f)
439 fname = strip_extension (fname, '.ly')
441 fname = fname + '-%d' % x
443 if os.path.exists (fname + '.tex'):
444 tfiles.append (find_tex_files_for_base (fname, extra))
445 analyse_lilypond_output (fname, extra)
451 fstr = string.join (files, ', ')
452 warning (_ ("no lilypond output found for %s") % fstr)
455 def one_latex_definition (defn, first):
457 for (k,v) in defn[1].items ():
458 val = open (v).read ()
459 if (string.strip (val)):
460 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
462 s = s + r'''\let\lilypond%s\relax''' % k
466 s = s + '\\def\\mustmakelilypondtitle{}\n'
468 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
470 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.
474 ly_paper_to_latexpaper = {
476 'letter' : 'letterpaper',
479 def global_latex_definition (tfiles, extra):
481 '''construct preamble from EXTRA, dump Latex stuff for each
482 lily output file in TFILES after that, and return the Latex file constructed. '''
486 s = s + '% generation tag\n'
490 if extra['papersize']:
492 options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
494 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
497 if extra['latexoptions']:
498 options = options + ',' + extra['latexoptions'][-1]
500 s = s + '\\documentclass[%s]{article}\n' % options
502 if extra['language']:
503 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
506 s = s + '\\usepackage{%s}\n' \
507 % string.join (extra['latexpackages'], ',')
509 if extra['latexheaders']:
510 s = s + '\\include{%s}\n' \
511 % string.join (extra['latexheaders'], '}\n\\include{')
514 if extra['textheight']:
515 textheight = ',textheight=%fpt' % extra['textheight'][0]
517 orientation = 'portrait'
518 if extra['orientation']:
519 orientation = extra['orientation'][0]
521 # set sane geometry width (a4-width) for linewidth = -1.
522 maxlw = max (extra['linewidth'] + [-1])
524 # who the hell is 597 ?
528 s = s + '\geometry{width=%spt%s,headheight=2mm,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
530 if extra['latexoptions']:
531 s = s + '\geometry{twosideshift=4mm}\n'
534 \usepackage[latin1]{inputenc}
537 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
538 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
541 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
543 \renewcommand{\@evenhead}{\hbox to\textwidth{\textbf{\thepage}\hfill{\small\theheader}}}
544 \renewcommand{\@oddhead}{\hbox to \textwidth{{\small\theheader}\hfill\textbf{\thepage}}}
547 s = s + '\\pagestyle{empty}\n'
549 s = s + '\\makeatother\n'
550 s = s + '\\begin{document}\n'
555 s = s + one_latex_definition (t, first)
559 %% I do not see why we want to clobber the footer here
560 %% \vfill\hfill\parbox{\textwidth}{\mbox{}\makelilypondtagline}
561 %% Well, maybe you don't submit music to mutopia?
562 %% I would not object to this kind of change, but I don't know how
563 %% to get the last mutopia tagline right (ie: no footer on last page)
564 %% Please check that mutopia footers and endfooter are OK before changing
565 %% this again. -- jcn
566 % the \mbox{} helps latex if people do stupid things in tagline
570 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
572 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
575 \renewcommand{\@thefoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
579 s = s + '\\end{document}'
583 def run_latex (files, outbase, extra):
585 """Construct latex file, for FILES and EXTRA, dump it into
586 OUTBASE.latex. Run LaTeX on it.
592 latex_fn = outbase + '.latex'
594 wfs = find_tex_files (files, extra)
595 s = global_latex_definition (wfs, extra)
597 f = open (latex_fn, 'w')
601 cmd = 'latex \\\\nonstopmode \\\\input %s' % latex_fn
603 if not verbose_p and os.name == 'posix':
604 progress ( _("Running %s...") % 'LaTeX')
605 cmd = cmd + ' 1> /dev/null 2> /dev/null'
609 def run_dvips (outbase, extra):
612 """Run dvips using the correct options taken from EXTRA,
613 leaving a PS file in OUTBASE.ps
620 if extra['papersize']:
621 opts = opts + ' -t%s' % extra['papersize'][0]
623 if extra['orientation'] and extra['orientation'][0] == 'landscape':
624 opts = opts + ' -tlandscape'
626 cmd = 'dvips %s -o%s %s' % (opts, outbase + '.ps', outbase + '.dvi')
628 if not verbose_p and os.name == 'posix':
629 progress ( _("Running %s...") % 'dvips')
630 cmd = cmd + ' 1> /dev/null 2> /dev/null'
634 def generate_dependency_file (depfile, outname):
635 df = open (depfile, 'w')
636 df.write (outname + ':' )
638 for d in dependency_files:
640 s = re.sub ('#[^\n]*\n', '', s)
641 s = re.sub (r'\\\n', ' ', s)
642 m = re.search ('.*:(.*)\n', s)
644 # ugh. Different targets?
646 df.write ( m.group (1) + ' ' )
651 (sh, long) = getopt_args (__main__.option_definitions)
653 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
654 except getopt.error, s:
655 errorport.write ("\nerror: getopt says `%s\'\n\n" % s)
665 elif o == '--help' or o == '-h':
668 elif o == '--include' or o == '-I':
669 include_path.append (a)
670 elif o == '--postscript' or o == '-P':
672 elif o == '--keep' or o == '-k':
674 elif o == '--no-lily':
676 elif o == '--no-paper' or o == '-m':
680 elif o == '--output' or o == '-o':
682 elif o == '--set' or o == '-s':
683 ss = string.split (a, '=')
684 set_setting (extra_init, ss[0], ss[1])
685 elif o == '--dependencies' or o == '-d':
686 track_dependencies_p = 1
687 elif o == '--verbose' or o == '-V':
689 elif o == '--version' or o == '-v':
692 elif o == '--warranty' or o == '-w':
693 status = system ('lilypond -w', ignore_error = 1)
700 def cp_to_dir (pattern, dir):
701 "Copy files matching re PATTERN from cwd to DIR"
702 # Duh. Python style portable: cp *.EXT OUTDIR
703 # system ('cp *.%s %s' % (ext, outdir), 1)
704 files = filter (lambda x, p=pattern: re.match (p, x), os.listdir ('.'))
705 map (lambda x, d=dir: shutil.copy2 (x, os.path.join (d, x)), files)
707 # Python < 1.5.2 compatibility
709 # On most platforms, this is equivalent to
710 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
711 if os.path.__dict__.has_key ('abspath'):
712 abspath = os.path.abspath
715 return os.path.normpath (os.path.join (os.getcwd (), path))
717 if os.__dict__.has_key ('makedirs'):
718 makedirs = os.makedirs
720 def makedirs (dir, mode=0777):
721 system ('mkdir -p %s' % dir)
723 def mkdir_p (dir, mode=0777):
724 if not os.path.isdir (dir):
727 include_path = map (abspath, include_path)
729 original_output = output_name
731 if files and files[0] != '-':
733 files = map (lambda x: strip_extension (x, '.ly'), files)
735 (outdir, outbase) = ('','')
737 outbase = os.path.basename (files[0])
738 outdir = abspath('.')
739 elif output_name[-1] == os.sep:
740 outdir = abspath (output_name)
741 outbase = os.path.basename (files[0])
743 (outdir, outbase) = os.path.split (abspath (output_name))
745 for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
746 output_name = strip_extension (output_name, i)
748 files = map (abspath, files)
750 if os.path.dirname (output_name) != '.':
751 dep_prefix = os.path.dirname (output_name)
755 reldir = os.path.dirname (output_name)
756 if outdir != '.' and (track_dependencies_p or targets.keys ()):
757 mkdir_p (outdir, 0777)
760 tmpdir = setup_temp ()
763 cp_to_dir (PK_PATTERN, tmpdir)
771 run_lilypond (files, outbase, dep_prefix)
773 ## # TODO: friendly message about LilyPond setup/failing?
775 ## # TODO: lilypond should fail with different
776 ## # error codes for:
777 ## # - guile setup/startup failure
778 ## # - font setup failure
779 ## # - init.ly setup failure
780 ## # - parse error in .ly
781 ## # - unexpected: assert/core dump
784 if targets.has_key ('DVI') or targets.has_key ('PS'):
786 run_latex (files, outbase, extra)
787 # unless: add --tex, or --latex?
791 # # TODO: friendly message about TeX/LaTeX setup,
792 # # trying to run tex/latex by hand
793 # if targets.has_key ('DVI'):
795 # if targets.has_key ('PS'):
798 # TODO: does dvips ever fail?
799 if targets.has_key ('PS'):
800 run_dvips (outbase, extra)
802 # add DEP to targets?
803 if track_dependencies_p:
804 depfile = os.path.join (outdir, outbase + '.dep')
805 generate_dependency_file (depfile, depfile)
806 if os.path.isfile (depfile):
807 progress (_ ("dependencies output to `%s'...") % depfile)
809 for i in targets.keys ():
810 ext = string.lower (i)
811 cp_to_dir ('.*\.%s$' % ext, outdir)
812 outname = outbase + '.' + string.lower (i)
813 abs = os.path.join (outdir, outname)
815 outname = os.path.join (reldir, outname)
816 if os.path.isfile (abs):
817 progress (_ ("%s output to `%s'...") % (i, outname))
819 warning (_ ("can't find file: `%s'") % outname)
822 cp_to_dir (PK_PATTERN, outdir)
824 os.chdir (original_dir)
830 errorport.write ("ly2dvi: " + _ ("error: ") + _ ("no files specified on command line.") + '\n')