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