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