]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
release: 1.3.147
[lilypond.git] / scripts / ly2dvi.py
1 #!@PYTHON@
2 # Run lilypond, latex, dvips.
3 #
4 # This is the third incarnation of ly2dvi.
5 #
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)
9 #
10
11
12 # Note: gettext work best if we use ' for docstrings and "
13 # for gettextable strings
14
15 '''
16 TODO:
17
18   * figure out which set of command line options should make ly2dvi:
19
20       na: create tex only?  
21       na: create latex only? 
22       na: create tex and latex
23       default: create dvi only
24       na: create tex, latex and dvi
25       -P: create dvi and ps
26       na: * create ps only
27
28      etc.
29
30      for foo.ly, rename ly2dvi.dir to out-ly2dvi, foo.ly2dvi, foo.dir ?
31      
32   * move versatile taglines, 
33   
34      \header {
35         beginfooter=\mutopiaPD
36         endfooter=\tagline  -> 'lily was here <version>'
37      }
38
39      lilytagline (->lily was here), usertagline, copyright etc.
40
41   * head/header tagline/endfooter
42
43   * dvi from lilypond .tex output?  This is hairy, because we create dvi
44     from lilypond .tex *and* header output.
45
46   * multiple \score blocks?
47   
48   * windows-sans-cygwin compatibility?  rm -rf, cp file... dir
49   
50 '''
51
52
53 import os
54 import stat
55 import string
56 import re
57 import getopt
58 import sys
59 import __main__
60 import operator
61 import tempfile
62
63 datadir = '@datadir@'
64 sys.path.append (datadir + '/python')
65 try:
66         import gettext
67         gettext.bindtextdomain ('lilypond', '@localedir@')
68         gettext.textdomain('lilypond')
69         _ = gettext.gettext
70 except:
71         def _ (s):
72                 return s
73
74
75 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
76           'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
77           'meter', 'poet']
78
79
80 # init to empty; values here take precedence over values in the file 
81 extra_init = {
82         'language' : [],
83         'latexheaders' : [],
84         'latexpackages' :  ['geometry'],
85         'latexoptions' : [],
86         'papersize' : [],
87         'pagenumber' : [1],
88         'textheight' : [], 
89         'linewidth' : [],
90         'orientation' : []
91 }
92
93 extra_fields = extra_init.keys ()
94
95 fields = layout_fields + extra_fields
96 program_name = 'ly2dvi'
97 help_summary = _ ("Generate .dvi with LaTeX for LilyPond")
98
99 include_path = ['.']
100 lily_p = 1
101 paper_p = 1
102
103 output = 0
104 targets = {
105         'DVI' : 0,
106         'LATEX' : 0,
107         'MIDI' : 0,
108         'TEX' : 0,
109         }
110
111 track_dependencies_p = 0
112 dependency_files = []
113
114 # be verbose?
115 verbose_p = 0
116
117
118 # lily_py.py -- options and stuff
119
120 # source file of the GNU LilyPond music typesetter
121
122 # BEGIN Library for these?
123 # cut-n-paste from ly2dvi
124
125 program_version = '@TOPLEVEL_VERSION@'
126 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
127         program_version = '1.3.142'
128
129
130 original_dir = os.getcwd ()
131 temp_dir = '%s.dir' % program_name
132 keep_temp_dir_p = 0
133 verbose_p = 0
134
135 #
136 # Try to cater for bad installations of LilyPond, that have
137 # broken TeX setup.  Just hope this doesn't hurt good TeX
138 # setups.  Maybe we should check if kpsewhich can find
139 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
140 #
141 environment = {
142         'MFINPUTS' : datadir + '/mf:',
143         'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:.:',
144         'TFMFONTS' : datadir + '/tfm:',
145         'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
146         'GS_LIB' : datadir + '/ps',
147 }
148
149 def setup_environment ():
150         for key in environment.keys ():
151                 val = environment[key]
152                 if os.environ.has_key (key):
153                         val = val + os.pathsep + os.environ[key]
154                 os.environ[key] = val
155
156 def identify ():
157         sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
158
159 def warranty ():
160         identify ()
161         sys.stdout.write ('\n')
162         sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
163         sys.stdout.write ('\n')
164         sys.stdout.write ('  Han-Wen Nienhuys')
165         sys.stdout.write ('  Jan Nieuwenhuizen')
166         sys.stdout.write ('\n')
167         sys.stdout.write (_ (r'''
168 Distributed under terms of the GNU General Public License. It comes with
169 NO WARRANTY.'''))
170         sys.stdout.write ('\n')
171
172 def progress (s):
173         sys.stderr.write (s + '\n')
174
175 def warning (s):
176         sys.stderr.write (_ ("warning: ") + s)
177         sys.stderr.write ('\n')
178         
179                 
180 def error (s):
181         sys.stderr.write (_ ("error: ") + s)
182         sys.stderr.write ('\n')
183         raise _ ("Exiting ... ")
184
185 def getopt_args (opts):
186         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
187         short = ''
188         long = []
189         for o in opts:
190                 if o[1]:
191                         short = short + o[1]
192                         if o[0]:
193                                 short = short + ':'
194                 if o[2]:
195                         l = o[2]
196                         if o[0]:
197                                 l = l + '='
198                         long.append (l)
199         return (short, long)
200
201 def option_help_str (o):
202         '''Transform one option description (4-tuple ) into neatly formatted string'''
203         sh = '  '       
204         if o[1]:
205                 sh = '-%s' % o[1]
206
207         sep = ' '
208         if o[1] and o[2]:
209                 sep = ','
210                 
211         long = ''
212         if o[2]:
213                 long= '--%s' % o[2]
214
215         arg = ''
216         if o[0]:
217                 if o[2]:
218                         arg = '='
219                 arg = arg + o[0]
220         return '  ' + sh + sep + long + arg
221
222
223 def options_help_str (opts):
224         '''Convert a list of options into a neatly formatted string'''
225         w = 0
226         strs =[]
227         helps = []
228
229         for o in opts:
230                 s = option_help_str (o)
231                 strs.append ((s, o[3]))
232                 if len (s) > w:
233                         w = len (s)
234
235         str = ''
236         for s in strs:
237                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
238         return str
239
240 def help ():
241         sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % program_name)
242         sys.stdout.write ('\n\n')
243         sys.stdout.write (help_summary)
244         sys.stdout.write ('\n\n')
245         sys.stdout.write (_ ("Options:"))
246         sys.stdout.write ('\n')
247         sys.stdout.write (options_help_str (option_definitions))
248         sys.stdout.write ('\n\n')
249         sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
250         sys.stdout.write ('\n')
251
252 def setup_temp ():
253         global temp_dir
254         if not keep_temp_dir_p:
255                 temp_dir = tempfile.mktemp (program_name)
256         try:
257                 os.mkdir (temp_dir, 0777)
258         except OSError:
259                 pass
260         os.chdir (temp_dir)
261
262
263 def system (cmd, ignore_error = 0):
264         if verbose_p:
265                 progress (_ ("Invoking `%s\'") % cmd)
266         st = os.system (cmd) >> 8
267         if st:
268                 name = re.match ('[ \t]*([^ \t]*)', cmd).group (1)
269                 msg = name + ': ' + _ ("command exited with value %d") % st
270                 if ignore_error:
271                         warning (msg + ' ' + _ ("(ignored)") + ' ')
272                 else:
273                         error (msg)
274
275         return st
276
277
278 def cleanup_temp ():
279         if not keep_temp_dir_p:
280                 if verbose_p:
281                         progress (_ ("Cleaning %s...") % temp_dir)
282                 system ('rm -rf %s' % temp_dir)
283
284
285 def set_setting (dict, key, val):
286         try:
287                 val = string.atof (val)
288         except ValueError:
289                 #warning (_ ("invalid value: %s") % `val`)
290                 pass
291
292         try:
293                 dict[key].append (val)
294         except KeyError:
295                 warning (_ ("no such setting: %s") % `key`)
296                 dict[key] = [val]
297
298 def strip_extension (f, ext):
299         (p, e) = os.path.splitext (f)
300         if e == ext:
301                 e = ''
302         return p + e
303
304 # END Library
305
306 option_definitions = [
307         ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
308         ('', 'h', 'help', _ ("this help")),
309         (_ ("DIR"), 'I', 'include', _ ("add DIR to LilyPond's search path")),
310         ('', 'k', 'keep', _ ("keep all output, and name the directory %s.dir") % program_name),
311         ('', '', 'no-lily', _ ("don't run LilyPond")),
312         ('', 'm', 'no-paper', _ ("produce MIDI output only")),
313         (_ ("FILE"), 'o', 'output', _ ("write ouput to FILE")),
314         # why capital P?
315         ('', 'P', 'postscript', _ ("generate PostScript output")),
316         (_ ("KEY=VAL"), 's', 'set', _ ("change global setting KEY to VAL")),
317         ('', 'V', 'verbose', _ ("verbose")),
318         ('', 'v', 'version', _ ("print version number")),
319         ('', 'w', 'warranty', _ ("show warranty and copyright")),
320         ]
321
322 def run_lilypond (files, outbase, dep_prefix):
323         opts = '--output=%s.tex' % outbase
324         opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
325         if paper_p:
326                 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
327         else:
328                 opts = opts + ' --no-paper'
329                 
330         if track_dependencies_p:
331                 opts = opts + " --dependencies"
332                 if dep_prefix:
333                         opts = opts + ' --dep-prefix=%s' % dep_prefix
334
335         fs = string.join (files)
336
337         if not verbose_p:
338                 progress ( _("Running %s...") % 'LilyPond')
339                 # cmd = cmd + ' 1> /dev/null 2> /dev/null'
340         else:
341                 opts = opts + ' --verbose'
342         
343         system ('lilypond %s %s ' % (opts, fs))
344
345 def analyse_lilypond_output (filename, extra):
346         
347         # urg
348         '''Grep FILENAME for interesting stuff, and
349         put relevant info into EXTRA.'''
350         filename = filename+'.tex'
351         progress (_ ("Analyzing %s...") % filename)
352         s = open (filename).read ()
353
354         # search only the first 10k
355         s = s[:10240]
356         for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
357                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
358                 if m:
359                         set_setting (extra, x, m.group (1))
360
361 def find_tex_files_for_base (base, extra):
362         headerfiles = {}
363         for f in layout_fields:
364                 if os.path.exists (base + '.' + f):
365                         headerfiles[f] = base+'.'+f
366
367         if os.path.exists (base  +'.dep'):
368                 dependency_files.append (base + '.dep')
369
370         for f in extra_fields:
371                 if os.path.exists (base + '.' + f):
372                         extra[f].append (open (base + '.' + f).read ())
373         
374         return (base  +'.tex',headerfiles)
375          
376
377 def find_tex_files (files, extra):
378         tfiles = []
379         
380         for f in files:
381                 x = 0
382                 while 1:
383                         fname = os.path.basename (f)
384                         fname = strip_extension (fname, '.ly')
385                         if x:
386                                 fname = fname + '-%d' % x
387
388                         if os.path.exists (fname + '.tex'):
389                                 tfiles.append (find_tex_files_for_base (fname, extra))
390                                 analyse_lilypond_output (fname, extra)
391                         else:
392                                 break
393
394                         x = x + 1
395         if not x:
396                 warning (_ ("no lilypond output found for %s") % `files`)
397         return tfiles
398
399 def one_latex_definition (defn, first):
400         s = '\n'
401         for (k,v) in defn[1].items ():
402                 val = open (v).read ()
403                 if (string.strip (val)):
404                         s = s + r'''\def\lilypond%s{%s}''' % (k, val)
405                 else:
406                         s = s + r'''\let\lilypond%s\relax''' % k
407                 s = s + '\n'
408
409         if first:
410                 s = s + '\\def\\mustmakelilypondtitle{}\n'
411         else:
412                 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
413                 
414         s = s + '\\input %s' % defn[0]
415         return s
416
417
418 ly_paper_to_latexpaper =  {
419         'a4' : 'a4paper',
420         'letter' : 'letterpaper', 
421 }
422
423 def global_latex_definition (tfiles, extra):
424         '''construct preamble from EXTRA,
425         dump lily output files after that, and return result.
426         '''
427
428
429         s = ""
430         s = s + '% generation tag\n'
431
432         options = ''
433
434         if extra['papersize']:
435                 try:
436                         options = '%s' % ly_paper_to_latexpaper[extra['papersize'][0]]
437                 except:
438                         warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
439                         pass
440
441         if extra['latexoptions']:
442                 options = options + ',' + extra['latexoptions'][-1]
443         
444         s = s + '\\documentclass[%s]{article}\n' % options
445
446         if extra['language']:
447                 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
448
449
450         s = s + '\\usepackage{%s}\n' \
451                 % string.join (extra['latexpackages'], ',')
452
453         if extra['latexheaders']:
454                 s = s + '\\include{%s}\n' \
455                         % string.join (extra['latexheaders'], '}\n\\include{')
456
457         textheight = ''
458         if extra['textheight']:
459                 textheight = ',textheight=%fpt' % extra['textheight'][0]
460
461         orientation = 'portrait'
462         if extra['orientation']:
463                 orientation = extra['orientation'][0]
464
465         # set sane geometry width (a4-width) for linewidth = -1.
466         if not extra['linewidth'] or extra['linewidth'][0] < 0:
467                 linewidth = 597
468         else:
469                 linewidth = extra['linewidth'][0]
470         s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=12pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
471
472         if extra['latexoptions']:
473                 s = s + '\geometry{twosideshift=4mm}\n'
474                 
475         s = s + r'''
476 \usepackage[latin1]{inputenc}
477 \input{titledefs}
478 \makeatletter
479 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
480 \renewcommand{\@evenfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
481 '''
482         
483         if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
484                 s = s + r'''
485 \renewcommand{\@evenhead}{\parbox{\textwidth}%
486     {\mbox{}\textbf{\thepage}\hfill\small\theheader}}
487 \renewcommand{\@oddhead}{\parbox{\textwidth}%
488     {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
489 '''
490         else:
491                 s = s + '\\pagestyle{empty}\n'
492
493         s = s + '\\makeatother\n'
494         s = s + '\\begin{document}\n'
495
496
497         first = 1
498         for t in tfiles:
499                 s = s + one_latex_definition (t, first)
500                 first = 0
501
502         s = s + r'''
503 % I don't see why we want to clobber the footer here
504 \vfill\hfill\parbox{\textwidth}{\mbox{}\makelilypondtagline}
505 %\makeatletter
506 %\renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
507 %\makeatother
508 '''
509         s = s + '\\end{document}'
510
511         return s
512
513 def run_latex (files, outbase, extra):
514         wfs = find_tex_files ([outbase] + files[1:], extra)
515         s = global_latex_definition (wfs, extra)
516
517         f = open (outbase + '.latex', 'w')
518         f.write (s)
519         f.close ()
520
521         cmd = 'latex \\\\nonstopmode \\\\input %s' % outbase + '.latex'
522         if not verbose_p:
523                 progress ( _("Running %s...") % 'LaTeX')
524                 cmd = cmd + ' 1> /dev/null 2> /dev/null'
525
526         system (cmd)
527
528 def run_dvips (outbase, extra):
529
530         opts = ''
531         if extra['papersize']:
532                 opts = opts + ' -t %s' % extra['papersize'][0]
533
534         if extra['orientation'] and extra['orientation'][0] == 'landscape':
535                 opts = opts + ' -t landscape'
536
537         cmd = 'dvips %s -o %s %s' % (opts, outbase + '.ps', outbase + '.dvi')
538         
539         if not verbose_p:
540                 progress ( _("Running %s...") % 'dvips')
541                 cmd = cmd + ' 2> /dev/null'
542                 
543         system (cmd)
544
545 def generate_dependency_file (depfile, outname):
546         df = open (depfile, 'w')
547         df.write (outname + ':' )
548         
549         for d in dependency_files:
550                 s = open (d).read ()
551                 s = re.sub ('#[^\n]*\n', '', s)
552                 s = re.sub (r'\\\n', ' ', s)
553                 m = re.search ('.*:(.*)\n', s)
554
555                 # ugh. Different targets?
556                 if m:
557                         df.write ( m.group (1)  + ' ' )
558
559         df.write ('\n')
560         df.close ();
561
562 (sh, long) = getopt_args (__main__.option_definitions)
563 try:
564         (options, files) = getopt.getopt(sys.argv[1:], sh, long)
565 except:
566         help ()
567         sys.exit (2)
568         
569 for opt in options:     
570         o = opt[0]
571         a = opt[1]
572
573         if 0:
574                 pass
575         elif o == '--help' or o == '-h':
576                 help ()
577                 sys.exit (0)
578         elif o == '--include' or o == '-I':
579                 include_path.append (a)
580         elif o == '--postscript' or o == '-P':
581                 targets['PS'] = 0
582         elif o == '--keep' or o == '-k':
583                 keep_temp_dir_p = 1
584         elif o == '--no-lily':
585                 lily_p = 0
586         elif o == '--no-paper' or o == '-m':
587                 targets = {}
588                 targets['MIDI'] = 0
589                 paper_p = 0
590         elif o == '--output' or o == '-o':
591                 output = a
592         elif o == '--set' or o == '-s':
593                 ss = string.split (a, '=')
594                 set_setting (extra_init, ss[0], ss[1])
595         elif o == '--dependencies' or o == '-d':
596                 track_dependencies_p = 1
597         elif o == '--verbose' or o == '-V':
598                 verbose_p = 1
599         elif o == '--version' or o == '-v':
600                 identify ()
601                 sys.exit (0)
602         elif o == '--warranty' or o == '-w':
603                 try:
604                         system ('lilypond -w')
605                 except:
606                         warranty ()
607                 sys.exit (0)
608
609 # On most platforms, this is equivalent to
610 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
611 def compat_abspath (path):
612         return os.path.normpath (os.path.join (os.getcwd (), path))
613
614 include_path = map (compat_abspath, include_path)
615
616 original_output = output
617
618 if files and files[0] != '-':
619
620         files = map (lambda x: strip_extension (x, '.ly'), files)
621
622         if not output:
623                 output = os.path.basename (files[0])
624
625         for i in ('.dvi', '.latex', '.ly', '.ps', '.tex'):
626                 output = strip_extension (output, i)
627
628         files = map (compat_abspath, files) 
629
630         if os.path.dirname (output) != '.':
631                 dep_prefix = os.path.dirname (output)
632         else:
633                 dep_prefix = 0
634
635         reldir = os.path.dirname (output)
636         (outdir, outbase) = os.path.split (compat_abspath (output))
637         
638         setup_environment ()
639         setup_temp ()
640         
641         extra = extra_init
642         
643         if lily_p:
644                 try:
645                         run_lilypond (files, outbase, dep_prefix)
646                 except:
647                         # TODO: friendly message about LilyPond setup/failing?
648                         #
649                         # TODO: lilypond should fail with different
650                         # error codes for:
651                         #   - guile setup/startup failure
652                         #   - font setup failure
653                         #   - init.ly setup failure
654                         #   - parse error in .ly
655                         #   - unexpected: assert/core dump
656                         targets = {}
657
658         if targets.has_key ('DVI') or targets.has_key ('PS'):
659                 try:
660                         run_latex (files, outbase, extra)
661                         # unless: add --tex, or --latex?
662                         del targets['TEX']
663                         del targets['LATEX']
664                 except:
665                         # TODO: friendly message about TeX/LaTeX setup,
666                         # trying to run tex/latex by hand
667                         if targets.has_key ('DVI'):
668                                 del targets['DVI']
669                         if targets.has_key ('PS'):
670                                 del targets['PS']
671
672         # TODO: does dvips ever fail?
673         if targets.has_key ('PS'):
674                 run_dvips (outbase, extra)
675
676         if outdir != '.' and (track_dependencies_p or targets.keys ()):
677                 system ('mkdir -p %s' % outdir)
678
679         # add DEP to targets?
680         if track_dependencies_p:
681                 depfile = os.path.join (outdir, outbase + '.dep')
682                 generate_dependency_file (depfile, depfile)
683                 if os.path.isfile (depfile):
684                         progress (_ ("dependencies output to %s...") % depfile)
685
686         for i in targets.keys ():
687                 ext = string.lower (i)
688                 if re.match ('.*[.]%s' % ext, string.join (os.listdir ('.'))):
689                         system ('cp *.%s %s' % (ext, outdir))
690                 outname = outbase + '.' + string.lower (i)
691                 abs = os.path.join (outdir, outname)
692                 if reldir != '.':
693                         outname = os.path.join (reldir, outname)
694                 if os.path.isfile (abs):
695                         progress (_ ("%s output to %s...") % (i, outname))
696                 elif verbose_p:
697                         warning (_ ("can't find file: `%s'") % outname)
698
699         os.chdir (original_dir)
700         cleanup_temp ()
701         
702 else:
703         # FIXME
704         help ()
705         sys.stderr.write ('\n')
706         try:
707                 error (_ ("no FILEs specified, can't invoke as filter"))
708         except:
709                 pass
710         sys.exit (2)
711
712
713