]> git.donarmstrong.com Git - lilypond.git/blob - scripts/ly2dvi.py
patch::: 1.3.141.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   * 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 # END Library
243
244 option_definitions = [
245         ('', 'h', 'help', _ ("this help")),
246         ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
247         ('DIR', 'I', 'include', _ ("add DIR to LilyPond\'s search path")),
248         ('', 'P', 'postscript', _ ("generate PostScript output")),
249         ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
250         ('', '', 'no-lily', _ ("don't run LilyPond")),
251         ('', 'V', 'verbose', _ ("verbose")),
252         ('', 'v', 'version', _ ("print version number")),
253         ('', 'w', 'warranty', _ ("show warranty and copyright")),
254         ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
255         ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
256         ]
257
258 def run_lilypond (files):
259         opts = ''
260         opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
261         opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
262
263         if track_dependencies_p:
264                 opts = opts + " --dependencies "
265
266         fs = string.join (files)
267         
268         system ('lilypond  %s %s ' % (opts, fs))
269
270 def analyse_lilypond_output (filename, extra):
271         '''Grep FILENAME for interesting stuff, and
272         put relevant info into EXTRA.'''
273         filename = filename+'.tex'
274         progress (_ ("Analyzing `%s'") % filename)
275         s = open (filename).read ()
276
277         # search only the first 10k
278         s = s[:10240]
279         for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
280                 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
281                 if m:
282                         set_setting (extra, x, m.group (1))
283
284 def find_tex_files_for_base (base, extra):
285         headerfiles = {}
286         for f in layout_fields:
287                 if os.path.exists (base + '.' + f):
288                         headerfiles[f] = base+'.'+f
289
290         if os.path.exists (base  +'.dep'):
291                 dependency_files.append (base + '.dep')
292
293         for f in extra_fields:
294                 if os.path.exists (base + '.' + f):
295                         extra[f].append (open (base + '.' + f).read ())
296         
297         return (base  +'.tex',headerfiles)
298          
299
300 def find_tex_files (files, extra):
301         tfiles = []
302         for f in files:
303                 x = 0
304                 while 1:
305                         fname = os.path.basename (f)
306                         fname = strip_ly_suffix (fname)
307                         if x:
308                                 fname = fname + '-%d' % x
309
310                         if os.path.exists (fname + '.tex'):
311                                 tfiles.append (find_tex_files_for_base (fname, extra))
312                                 analyse_lilypond_output (fname, extra)
313                         else:
314                                 break
315
316                         x = x + 1
317         if not x:
318                 warning (_ ("no lilypond output found for %s") % `files`)
319         return tfiles
320
321 def one_latex_definition (defn, first):
322         s = '\n'
323         for (k,v) in defn[1].items ():
324                 val = open (v).read ()
325                 if (string.strip (val)):
326                         s = s + r'''\def\lilypond%s{%s}''' % (k, val)
327                 else:
328                         s = s + r'''\let\lilypond%s\relax''' % k
329                 s = s + '\n'
330
331         if first:
332                 s = s + '\\def\\mustmakelilypondtitle{}\n'
333         else:
334                 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
335                 
336         s = s + '\\input %s' % defn[0]
337         return s
338
339
340 ly_paper_to_latexpaper =  {
341         'a4' : 'a4paper',
342         'letter' : 'letterpaper', 
343 }
344
345 def global_latex_definition (tfiles, extra):
346         '''construct preamble from EXTRA,
347         dump lily output files after that, and return result.
348         '''
349
350
351         s = ""
352         s = s + '% generation tag\n'
353
354         paper = ''
355
356         if extra['papersize']:
357                 try:
358                         paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
359                 except:
360                         warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
361                         pass
362         
363         s = s + '\\documentclass%s{article}\n' % paper
364
365         if extra['language']:
366                 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
367
368
369         s = s + '\\usepackage{%s}\n' \
370                 % string.join (extra['latexpackages'], ',')
371
372         if extra['latexheaders']:
373                 s = s + '\\include{%s}\n' \
374                         % string.join (extra['latexheaders'], '}\n\\include{')
375
376         textheight = ''
377         if extra['textheight']:
378                 textheight = ',textheight=%fpt' % extra['textheight'][0]
379
380         orientation = 'portrait'
381         if extra['orientation']:
382                 orientation = extra['orientation'][0]
383
384         # set sane geometry width (a4-width) for linewidth = -1.
385         linewidth = extra['linewidth'][0]
386         if linewidth < 0:
387                 linewidth = 597
388         s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
389
390         s = s + r'''
391 \usepackage[latin1]{inputenc}
392 \input{titledefs}
393 \makeatletter
394 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
395 '''
396         
397         if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
398                 s = s + r'''
399 \renewcommand{\@oddhead}{\parbox{\textwidth}%
400     {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
401 '''
402         else:
403                 s = s + '\\pagestyle{empty}\n'
404
405         s = s + '\\makeatother\n'
406         s = s + '\\begin{document}\n'
407
408
409         first = 1
410         for t in tfiles:
411                 s = s + one_latex_definition (t, first)
412                 first = 0
413
414         s = s + r'''
415 \makeatletter
416 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
417 \makeatother
418 '''
419         s = s + '\\end{document}'
420
421         return s
422
423 def do_files (fs, extra):
424
425         '''process the list of filenames in FS, using standard settings in EXTRA.
426         '''
427         if not no_lily:
428                 run_lilypond (fs)
429
430         wfs = find_tex_files (fs, extra)
431         s = global_latex_definition (wfs, extra)
432
433         latex_file ='ly2dvi.out'
434         f = open (latex_file + '.tex', 'w')
435         f.write (s)
436         f.close ()
437
438         # todo: nonstopmode
439         system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
440         return latex_file + '.dvi'
441
442 def generate_postscript (dvi_name, extra):
443         '''Run dvips on DVI_NAME, optionally doing -t landscape'''
444
445         opts = ''
446         if extra['papersize']:
447                 opts = opts + ' -t %s' % extra['papersize'][0]
448
449         if extra['orientation'] and extra['orientation'][0] == 'landscape':
450                 opts = opts + ' -t landscape'
451
452         ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
453         system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
454
455         return ps_name
456                 
457
458
459 def generate_dependency_file (depfile, outname):
460         df = open (depfile, 'w')
461         df.write (outname + ':' )
462         
463         for d in dependency_files:
464                 s = open (d).read ()
465                 s = re.sub ('#[^\n]*\n', '', s)
466                 s = re.sub (r'\\\n', ' ', s)
467                 m = re.search ('.*:(.*)\n', s)
468
469                 # ugh. Different targets?
470                 if m:
471                         df.write ( m.group (1)  + ' ' )
472
473         df.write ('\n')
474         df.close ();
475
476 (sh, long) = getopt_args (__main__.option_definitions)
477 try:
478         (options, files) = getopt.getopt(sys.argv[1:], sh, long)
479 except:
480         help ()
481         sys.exit (2)
482         
483 for opt in options:     
484         o = opt[0]
485         a = opt[1]
486
487         if 0:
488                 pass
489         elif o == '--help' or o == '-h':
490                 help ()
491         elif o == '--include' or o == '-I':
492                 include_path.append (a)
493         elif o == '--postscript' or o == '-P':
494                 postscript_p = 1
495         elif o == '--keep' or o == '-k':
496                 keep_temp_dir_p = 1
497         elif o == '--no-lily':
498                 no_lily = 1
499         elif o == '--outdir':
500                 outdir = a
501         elif o == '--set' or o == '-s':
502                 ss = string.split (a, '=')
503                 set_setting (extra_init, ss[0], ss[1])
504         elif o == '--dependencies' or o == '-d':
505                 track_dependencies_p = 1
506         elif o == '--verbose' or o == '-V':
507                 verbose_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 # On most platforms, this is equivalent to
516 #`normpath(join(os.getcwd()), PATH)'.  *Added in Python version 1.5.2*
517 def compat_abspath (path):
518         return os.path.normpath (os.path.join (os.getcwd (), path))
519
520 include_path = map (compat_abspath, include_path)
521 files = map (compat_abspath, files) 
522 outdir = compat_abspath (outdir)
523
524 def strip_ly_suffix (f):
525         (p, e) =os.path.splitext (f)
526         if e == '.ly':
527                 e = ''
528         return p +e
529         
530 files = map (strip_ly_suffix, files)
531
532 if files:
533         setup_temp ()
534         extra = extra_init
535         
536         dvi_name = do_files (files, extra)
537
538         if postscript_p:
539                 ps_name = generate_postscript (dvi_name, extra)
540
541
542
543         base = os.path.basename (files[0])
544         dest = base
545         type = 'foobar'
546         srcname = 'foobar'
547         
548         if postscript_p:
549                 srcname = ps_name
550                 dest = dest + '.ps'
551                 type = 'PS'
552         else:
553                 srcname = dvi_name
554                 dest= dest + '.dvi'
555                 type = 'DVI'
556
557         dest = os.path.join (outdir, dest)
558         if outdir != '.':
559                 system ('mkdir -p %s' % outdir)
560         system ('cp \"%s\" \"%s\"' % (srcname, dest ))
561         if re.match ('[.]midi', string.join (os.listdir ('.'))):
562                 system ('cp *.midi %s' % outdir, ignore_error = 1)
563
564         depfile = os.path.join (outdir, base + '.dep')
565
566         if track_dependencies_p:
567                 generate_dependency_file (depfile, dest)
568
569         os.chdir (original_dir)
570         cleanup_temp ()
571
572         # most insteresting info last
573         progress (_ ("dependencies output to %s...") % depfile)
574         progress (_ ("%s output to %s...") % (type, dest))
575
576
577