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