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