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