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