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