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