]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
patch::: 1.3.140.jcn5
[lilypond.git] / scripts / ly2dvi.py
1 #!@PYTHON@
2 # run lily, setup LaTeX input.
3
4 # Note: gettext work best if we use ' for docstrings and "
5 # for gettextable strings
6
7 '''
8 TODO:
9
10   * check --dependencies
11
12   * move versatile taglines, 
13   
14      \header {
15         beginfooter=\mutopiaPD
16         endfooter=\tagline  -> 'lily was here <version>'
17      }
18
19   * head/header tagline/endfooter
20
21   * dvi from lilypond .tex output?  This is hairy, because we create dvi
22     from lilypond .tex *and* header output.
23
24 '''
25
26
27 import os
28 import stat
29 import string
30 import re
31 import getopt
32 import sys
33 import __main__
34 import operator
35 import tempfile
36
37 sys.path.append ('@datadir@/python')
38 import gettext
39 gettext.bindtextdomain ('lilypond', '@localedir@')
40 gettext.textdomain('lilypond')
41 _ = gettext.gettext
42
43
44 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
45           'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
46           'meter', 'poet']
47
48
49 # init to empty; values here take precedence over values in the file 
50 extra_init = {
51         'language' : [],
52         'latexheaders' : [],
53         'latexpackages' :  ['geometry'],
54         'papersize' : [],
55         'pagenumber' : [1],
56         'textheight' : [], 
57         'linewidth' : [],
58         'orientation' : []
59 }
60
61 extra_fields = extra_init.keys ()
62
63 fields = layout_fields + extra_fields
64 original_dir = os.getcwd ()
65 include_path = ['.']
66 temp_dir = ''
67 keep_temp_dir = 0
68 no_lily = 0
69 outdir = '.'
70 track_dependencies_p = 0
71
72 dependency_files = []
73
74
75 program_version = '@TOPLEVEL_VERSION@'
76 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
77         program_version = '1.3.134'
78
79 # generate ps ?
80 postscript_p = 0
81
82 # be verbose?
83 verbose_p = 0
84
85 option_definitions = [
86         ('', 'h', 'help', _ ("this help")),
87         ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
88         ('', 'P', 'postscript', _ ("generate PostScript output")),
89         ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
90         ('', '', 'no-lily', _ ("don't run LilyPond")),
91         ('', 'V', 'verbose', _ ("verbose")),
92         ('', 'v', 'version', _ ("print version number")),
93         ('', 'w', 'warranty', _ ("show warranty and copyright")),
94         ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
95         ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
96         ]
97
98 def identify ():
99         sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
100
101 def warranty ():
102         identify ()
103         sys.stdout.write ('\n')
104         sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
105         sys.stdout.write ('\n')
106         sys.stdout.write ('  Han-Wen Nienhuys')
107         sys.stdout.write ('\n')
108         sys.stdout.write (_ (r'''
109 Distributed under terms of the GNU General Public License. It comes with
110 NO WARRANTY.'''))
111         sys.stdout.write ('\n')
112
113
114
115 def star_progress (s):
116         '''Progress messages that stand out between lilypond stuff'''
117         progress ('*** ' + s)
118
119 def progress (s):
120         sys.stderr.write (s + '\n')
121
122 def warning (s):
123         sys.stderr.write (_ ("warning: ") + s)
124         sys.stderr.write ('\n')
125         
126                 
127 def error (s):
128         sys.stderr.write (_ ("error: ") + s)
129         sys.stderr.write ('\n')
130         raise _ ("Exiting ... ")
131
132
133 def find_file (name):
134         '''
135         Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
136         '''
137         
138         f = None
139         nm = ''
140         for a in include_path:
141                 try:
142                         nm = os.path.join (a, name)
143                         f = open (nm)
144                         __main__.read_files.append (nm)
145                         break
146                 except IOError:
147                         pass
148         if f:
149                 sys.stderr.write (_ ("Reading %s...") % nm)
150                 sys.stderr.write ('\n');
151                 return (f.read (), nm)
152         else:
153                 error (_ ("can't open file: `%s'" % name))
154                 sys.stderr.write ('\n');
155                 return ('', '')
156
157
158
159
160 def getopt_args (opts):
161         '''Construct arguments (LONG, SHORT) for getopt from  list of options.'''
162         short = ''
163         long = []
164         for o in opts:
165                 if o[1]:
166                         short = short + o[1]
167                         if o[0]:
168                                 short = short + ':'
169                 if o[2]:
170                         l = o[2]
171                         if o[0]:
172                                 l = l + '='
173                         long.append (l)
174         return (short, long)
175
176 def option_help_str (o):
177         '''Transform one option description (4-tuple ) into neatly formatted string'''
178         sh = '  '       
179         if o[1]:
180                 sh = '-%s' % o[1]
181
182         sep = ' '
183         if o[1] and o[2]:
184                 sep = ','
185                 
186         long = ''
187         if o[2]:
188                 long= '--%s' % o[2]
189
190         arg = ''
191         if o[0]:
192                 if o[2]:
193                         arg = '='
194                 arg = arg + o[0]
195         return '  ' + sh + sep + long + arg
196
197
198 def options_help_str (opts):
199         '''Convert a list of options into a neatly formatted string'''
200         w = 0
201         strs =[]
202         helps = []
203
204         for o in opts:
205                 s = option_help_str (o)
206                 strs.append ((s, o[3]))
207                 if len (s) > w:
208                         w = len (s)
209
210         str = ''
211         for s in strs:
212                 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0])  + 3), s[1])
213         return str
214
215 def help ():
216         sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
217         sys.stdout.write ('\n\n')
218         sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
219         sys.stdout.write ('\n\n')
220         sys.stdout.write (_ ("Options:"))
221         sys.stdout.write ('\n')
222         sys.stdout.write (options_help_str (option_definitions))
223         sys.stdout.write ('\n\n')
224         warning (_ ("all output is written in the CURRENT directory"))
225         sys.stdout.write ('\n')
226         sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
227         sys.stdout.write ('\n')
228         sys.exit (0)
229
230
231 def setup_temp ():
232         global temp_dir
233         temp_dir = 'ly2dvi.dir'
234         if not keep_temp_dir:
235                 temp_dir = tempfile.mktemp ('ly2dvi')
236                 
237         try:
238                 os.mkdir (temp_dir, 0777)
239         except OSError:
240                 pass
241                 
242
243         # try not to gen/search MF stuff in temp dir
244         fp = ''
245         try:
246                 fp = ':' + os.environ['TFMFONTS']
247         except KeyError:
248                 fp = '://:'
249
250                 
251         os.environ['TFMFONTS'] =  original_dir + fp
252
253         os.chdir (temp_dir)
254         if verbose_p:
255                 progress (_ ('Temp directory is `%s\'\n') % temp_dir) 
256
257         
258 def system (cmd, ignore_error = 0):
259         if verbose_p:
260                 progress (_ ("Invoking `%s\'") % cmd)
261         st = os.system (cmd)
262         if st:
263                 msg =  ( _ ("error: ") + _ ("command exited with value %d") % st)
264                 if ignore_error:
265                         sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
266                 else:
267                         error (msg)
268
269         return st
270
271 def cleanup_temp ():
272         if not keep_temp_dir:
273                 if verbose_p:
274                         progress (_ ('Cleaning up `%s\'') % temp_dir)
275                 system ('rm -rf %s' % temp_dir)
276         
277
278 def run_lilypond (files):
279         opts = ''
280         opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
281         opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
282
283         if track_dependencies_p:
284                 opts = opts + " --dependencies "
285
286         fs = string.join (files)
287         
288         system ('lilypond  %s %s ' % (opts, fs))
289
290
291 def set_setting (dict, key, val):
292         try:
293                 val = string.atof (val)
294         except ValueError:
295                 #warning (_ ("invalid value: %s") % `val`)
296                 pass
297
298         try:
299                 dict[key].append (val)
300         except KeyError:
301                 warning (_ ("no such setting: %s") % `key`)
302                 dict[key] = [val]
303         
304
305 def analyse_lilypond_output (filename, extra):
306         '''Grep FILENAME for interesting stuff, and
307         put relevant info into EXTRA.'''
308         filename = filename+'.tex'
309         progress (_ ("Analyzing `%s'") % filename)
310         s = open (filename).read ()
311
312         # search only the first 10k
313         s = s[:10240]
314         for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
315                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
316                 if m:
317                         set_setting (extra, x, m.group (1))
318
319 def find_tex_files_for_base (base, extra):
320         headerfiles = {}
321         for f in layout_fields:
322                 if os.path.exists (base + '.' + f):
323                         headerfiles[f] = base+'.'+f
324
325         if os.path.exists (base  +'.dep'):
326                 dependency_files.append (base + '.dep')
327
328         for f in extra_fields:
329                 if os.path.exists (base + '.' + f):
330                         extra[f].append (open (base + '.' + f).read ())
331         
332         return (base  +'.tex',headerfiles)
333          
334
335 def find_tex_files (files, extra):
336         tfiles = []
337         for f in files:
338                 x = 0
339                 while 1:
340                         fname = os.path.basename (f)
341                         fname = strip_ly_suffix (fname)
342                         if x:
343                                 fname = fname + '-%d' % x
344
345                         if os.path.exists (fname + '.tex'):
346                                 tfiles.append (find_tex_files_for_base (fname, extra))
347                                 analyse_lilypond_output (fname, extra)
348                         else:
349                                 break
350
351                         x = x + 1
352         if not x:
353                 warning (_ ("no lilypond output found for %s") % `files`)
354         return tfiles
355
356 def one_latex_definition (defn, first):
357         s = '\n'
358         for (k,v) in defn[1].items ():
359                 val = open (v).read ()
360                 if (string.strip (val)):
361                         s = s + r'''\def\lilypond%s{%s}''' % (k, val)
362                 else:
363                         s = s + r'''\let\lilypond%s\relax''' % k
364                 s = s + '\n'
365
366         if first:
367                 s = s + '\\def\\mustmakelilypondtitle{}\n'
368         else:
369                 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
370                 
371         s = s + '\\input %s' % defn[0]
372         return s
373
374
375 ly_paper_to_latexpaper =  {
376         'a4' : 'a4paper',
377         'letter' : 'letterpaper', 
378 }
379
380 def global_latex_definition (tfiles, extra):
381         '''construct preamble from EXTRA,
382         dump lily output files after that, and return result.
383         '''
384
385
386         s = ""
387         s = s + '% generation tag\n'
388
389         paper = ''
390
391         if extra['papersize']:
392                 try:
393                         paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
394                 except:
395                         warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
396                         pass
397         
398         s = s + '\\documentclass%s{article}\n' % paper
399
400         if extra['language']:
401                 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
402
403
404         s = s + '\\usepackage{%s}\n' \
405                 % string.join (extra['latexpackages'], ',')
406         
407         s = s + string.join (extra['latexheaders'], ' ')
408
409         textheight = ''
410         if extra['textheight']:
411                 textheight = ',textheight=%fpt' % extra['textheight'][0]
412
413         orientation = 'portrait'
414         if extra['orientation']:
415                 orientation = extra['orientation'][0]
416
417         # set sane geometry width (a4-width) for linewidth = -1.
418         linewidth = extra['linewidth'][0]
419         if linewidth < 0:
420                 linewidth = 597
421         s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
422
423         s = s + r'''
424 \usepackage[latin1]{inputenc}
425 \input{titledefs}
426 \makeatletter
427 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
428 '''
429         
430         if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
431                 s = s + r'''
432 \renewcommand{\@oddhead}{\parbox{\textwidth}%
433     {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
434 '''
435         else:
436                 s = s + '\\pagestyle{empty}\n'
437
438         s = s + '\\makeatother\n'
439         s = s + '\\begin{document}\n'
440
441
442         first = 1
443         for t in tfiles:
444                 s = s + one_latex_definition (t, first)
445                 first = 0
446
447         s = s + r'''
448 \makeatletter
449 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
450 \makeatother
451 '''
452         s = s + '\\end{document}'
453
454         return s
455
456 def do_files (fs, extra):
457
458         '''process the list of filenames in FS, using standard settings in EXTRA.
459         '''
460         if not no_lily:
461                 run_lilypond (fs)
462
463         wfs = find_tex_files (fs, extra)
464         s = global_latex_definition (wfs, extra)
465
466         latex_file ='ly2dvi.out'
467         f = open (latex_file + '.tex', 'w')
468         f.write (s)
469         f.close ()
470
471         # todo: nonstopmode
472         system ('latex %s' % latex_file)
473         return latex_file + '.dvi'
474
475 def generate_postscript (dvi_name, extra):
476         '''Run dvips on DVI_NAME, optionally doing -t landscape'''
477
478         opts = ''
479         if extra['papersize']:
480                 opts = opts + ' -t %s' % extra['papersize'][0]
481
482         if extra['orientation'] and extra['orientation'][0] == 'landscape':
483                 opts = opts + ' -t landscape'
484
485         ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
486         system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
487
488         return ps_name
489                 
490
491
492 def generate_dependency_file (depfile, outname):
493         df = open (depfile, 'w')
494         df.write (outname + ':' )
495         
496         for d in dependency_files:
497                 s = open (d).read ()
498                 s = re.sub ('#[^\n]*\n', '', s)
499                 s = re.sub (r'\\\n', ' ', s)
500                 m = re.search ('.*:(.*)\n', s)
501
502                 # ugh. Different targets?
503                 if m:
504                         df.write ( m.group (1)  + ' ' )
505
506         df.write ('\n')
507         df.close ();
508
509 (sh, long) = getopt_args (__main__.option_definitions)
510 try:
511         (options, files) = getopt.getopt(sys.argv[1:], sh, long)
512 except:
513         help ()
514         sys.exit (2)
515         
516 for opt in options:     
517         o = opt[0]
518         a = opt[1]
519
520         if 0:
521                 pass
522         elif o == '--help' or o == '-h':
523                 help ()
524         elif o == '--include' or o == '-I':
525                 include_path.append (a)
526         elif o == '--postscript' or o == '-P':
527                 postscript_p = 1
528         elif o == '--keep' or o == '-k':
529                 keep_temp_dir = 1
530         elif o == '--no-lily':
531                 no_lily = 1
532         elif o == '--outdir':
533                 outdir = a
534         elif o == '--set' or o == '-s':
535                 ss = string.split (a, '=')
536                 set_setting (extra_init, ss[0], ss[1])
537         elif o == '--dependencies' or o == '-d':
538                 track_dependencies_p = 1
539         elif o == '--verbose' or o == '-V':
540                 verbose_p = 1
541         elif o == '--version' or o == '-v':
542                 identify ()
543                 sys.exit (0)
544         elif o == '--warranty' or o == '-w':
545                 warranty ()
546                 sys.exit (0)
547                 
548                 
549 include_path = map (os.path.abspath, include_path)
550 files = map (os.path.abspath, files) 
551 outdir = os.path.abspath (outdir)
552
553 def strip_ly_suffix (f):
554         (p, e) =os.path.splitext (f)
555         if e == '.ly':
556                 e = ''
557         return p +e
558         
559 files = map (strip_ly_suffix, files)
560
561 if files:
562         setup_temp ()
563         extra = extra_init
564         
565         dvi_name = do_files (files, extra)
566
567         if postscript_p:
568                 ps_name = generate_postscript (dvi_name, extra)
569
570
571
572         base = os.path.basename (files[0])
573         dest = base
574         type = 'foobar'
575         srcname = 'foobar'
576         
577         if postscript_p:
578                 srcname = ps_name
579                 dest = dest + '.ps'
580                 type = 'PS'
581         else:
582                 srcname = dvi_name
583                 dest= dest + '.dvi'
584                 type = 'DVI'
585
586         dest = os.path.join (outdir, dest)
587         if outdir != '.':
588                 system ('mkdir -p %s' % outdir)
589         system ('cp \"%s\" \"%s\"' % (srcname, dest ))
590         if re.match ('[.]midi', string.join (os.listdir ('.'))):
591                 system ('cp *.midi %s' % outdir, ignore_error = 1)
592
593         depfile = os.path.join (outdir, base + '.dep')
594
595         if track_dependencies_p:
596                 generate_dependency_file (depfile, dest)
597
598         os.chdir (original_dir)
599         cleanup_temp ()
600
601         # most insteresting info last
602         progress (_ ("dependencies output to %s...") % depfile)
603         progress (_ ("%s output to %s...") % (type, dest))
604
605
606