2 # run lily, setup LaTeX input.
4 # Note: gettext work best if we use ' for docstrings and "
5 # for gettextable strings
12 * dvi from lilypond .tex output? This is hairy, because we create dvi
13 from lilypond .tex *and* header output.
28 sys.path.append ('@datadir@/python')
30 gettext.bindtextdomain ('lilypond', '@localedir@')
31 gettext.textdomain('lilypond')
35 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
36 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
40 # init to empty; values here take precedence over values in the file
44 'latexpackages' : ['geometry'],
52 extra_fields = extra_init.keys ()
54 fields = layout_fields + extra_fields
55 original_dir = os.getcwd ()
61 track_dependencies_p = 0
66 program_version = '@TOPLEVEL_VERSION@'
67 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
68 program_version = '1.3.134'
73 option_definitions = [
74 ('', 'h', 'help', _ ("this help")),
75 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
76 ('', 'P', 'postscript', _ ("generate PostScript output")),
77 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
78 ('', '', 'no-lily', _ ("don't run LilyPond")),
79 ('', 'v', 'version', _ ("print version number")),
80 ('', 'w', 'warranty', _ ("show warranty and copyright")),
81 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
82 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
86 sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
90 sys.stdout.write ('\n')
91 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
92 sys.stdout.write ('\n')
93 sys.stdout.write (' Han-Wen Nienhuys')
94 sys.stdout.write ('\n')
95 sys.stdout.write (_ (r'''
96 Distributed under terms of the GNU General Public License. It comes with
98 sys.stdout.write ('\n')
103 '''Make the progress messages stand out between lilypond stuff'''
104 # Why should they have to stand out? Blend in would be nice too.
105 sys.stderr.write ('*** ' + s+ '\n')
108 sys.stderr.write (_ ("warning: ") + s)
109 sys.stderr.write ('\n')
113 sys.stderr.write (_ ("error: ") + s)
114 sys.stderr.write ('\n')
115 raise _ ("Exiting ... ")
118 def find_file (name):
120 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
125 for a in include_path:
127 nm = os.path.join (a, name)
129 __main__.read_files.append (nm)
134 sys.stderr.write (_ ("Reading `%s'") % nm)
135 sys.stderr.write ('\n');
136 return (f.read (), nm)
138 error (_ ("can't open file: `%s'" % name))
139 sys.stderr.write ('\n');
145 def getopt_args (opts):
146 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
161 def option_help_str (o):
162 '''Transform one option description (4-tuple ) into neatly formatted string'''
180 return ' ' + sh + sep + long + arg
183 def options_help_str (opts):
184 '''Convert a list of options into a neatly formatted string'''
190 s = option_help_str (o)
191 strs.append ((s, o[3]))
197 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
201 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
202 sys.stdout.write ('\n\n')
203 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
204 sys.stdout.write ('\n\n')
205 sys.stdout.write (_ ("Options:"))
206 sys.stdout.write ('\n')
207 sys.stdout.write (options_help_str (option_definitions))
208 sys.stdout.write ('\n\n')
209 warning (_ ("all output is written in the CURRENT directory"))
210 sys.stdout.write ('\n')
211 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
212 sys.stdout.write ('\n')
218 temp_dir = 'ly2dvi.dir'
219 if not keep_temp_dir:
220 temp_dir = tempfile.mktemp ('ly2dvi')
223 os.mkdir (temp_dir, 0777)
228 # try not to gen/search MF stuff in temp dir
231 fp = ':' + os.environ['TFMFONTS']
236 os.environ['TFMFONTS'] = original_dir + fp
239 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
242 def system (cmd, ignore_error = 0):
243 sys.stderr.write (_ ("Invoking `%s\'") % cmd)
244 sys.stderr.write ('\n')
247 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
249 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
256 if not keep_temp_dir:
257 progress (_ ('Cleaning up `%s\'') % temp_dir)
258 system ('rm -rf %s' % temp_dir)
261 def run_lilypond (files):
263 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
264 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
266 if track_dependencies_p:
267 opts = opts + " --dependencies "
269 fs = string.join (files)
271 system ('lilypond %s %s ' % (opts, fs))
274 def set_setting (dict, key, val):
276 val = string.atof (val)
278 #warning (_ ("invalid value: %s") % `val`)
282 dict[key].append (val)
284 warning (_ ("no such setting: %s") % `key`)
288 def analyse_lilypond_output (filename, extra):
289 '''Grep FILENAME for interesting stuff, and
290 put relevant info into EXTRA.'''
291 filename = filename+'.tex'
292 progress (_ ("Analyzing `%s'") % filename)
293 s = open (filename).read ()
295 # search only the first 10k
297 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
298 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
300 set_setting (extra, x, m.group (1))
302 def find_tex_files_for_base (base, extra):
304 for f in layout_fields:
305 if os.path.exists (base + '.' + f):
306 headerfiles[f] = base+'.'+f
308 if os.path.exists (base +'.dep'):
309 dependency_files.append (base + '.dep')
311 for f in extra_fields:
312 if os.path.exists (base + '.' + f):
313 extra[f].append (open (base + '.' + f).read ())
315 return (base +'.tex',headerfiles)
318 def find_tex_files (files, extra):
323 fname = os.path.basename (f)
324 fname = strip_ly_suffix (fname)
326 fname = fname + '-%d' % x
328 if os.path.exists (fname + '.tex'):
329 tfiles.append (find_tex_files_for_base (fname, extra))
330 analyse_lilypond_output (fname, extra)
336 warning (_ ("no lilypond output found for %s") % `files`)
339 def one_latex_definition (defn, first):
341 for (k,v) in defn[1].items ():
342 val = open (v).read ()
343 if (string.strip (val)):
344 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
346 s = s + r'''\let\lilypond%s\relax''' % k
350 s = s + '\\def\\mustmakelilypondtitle{}\n'
352 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
354 s = s + '\\input %s' % defn[0]
358 ly_paper_to_latexpaper = {
360 'letter' : 'letterpaper',
363 def global_latex_definition (tfiles, extra):
364 '''construct preamble from EXTRA,
365 dump lily output files after that, and return result.
370 s = s + '% generation tag\n'
374 if extra['papersize']:
376 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
378 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
381 s = s + '\\documentclass%s{article}\n' % paper
383 if extra['language']:
384 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
387 s = s + '\\usepackage{%s}\n' \
388 % string.join (extra['latexpackages'], ',')
390 s = s + string.join (extra['latexheaders'], ' ')
393 if extra['textheight']:
394 textheight = ',textheight=%fpt' % extra['textheight'][0]
396 orientation = 'portrait'
397 if extra['orientation']:
398 orientation = extra['orientation'][0]
400 # set sane geometry width (a4-width) for linewidth = -1.
401 linewidth = extra['linewidth'][0]
404 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
407 \usepackage[latin1]{inputenc}
410 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
412 if extra['pagenumber'] and extra['pagenumber'][-1]:
414 \renewcommand{\@oddhead}{\parbox{\textwidth}%%
415 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%'''
417 s = s + '\\pagestyle{empty}'
419 s = s + '\\begin{document}'
423 s = s + one_latex_definition (t, first)
426 s = s + '\\end{document}'
430 def do_files (fs, extra):
432 '''process the list of filenames in FS, using standard settings in EXTRA.
437 wfs = find_tex_files (fs, extra)
438 s = global_latex_definition (wfs, extra)
440 latex_file ='ly2dvi.out'
441 f = open (latex_file + '.tex', 'w')
446 system ('latex %s' % latex_file)
447 return latex_file + '.dvi'
449 def generate_postscript (dvi_name, extra):
450 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
453 if extra['papersize']:
454 opts = opts + ' -t %s' % extra['papersize'][0]
456 if extra['orientation'] and extra['orientation'][0] == 'landscape':
457 opts = opts + ' -t landscape'
459 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
460 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
466 def generate_dependency_file (depfile, outname):
467 df = open (depfile, 'w')
468 df.write (outname + ':' )
470 for d in dependency_files:
472 s = re.sub ('#[^\n]*\n', '', s)
473 s = re.sub (r'\\\n', ' ', s)
474 m = re.search ('.*:(.*)\n', s)
476 # ugh. Different targets?
478 df.write ( m.group (1) + ' ' )
483 (sh, long) = getopt_args (__main__.option_definitions)
485 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
496 elif o == '--help' or o == '-h':
498 elif o == '--include' or o == '-I':
499 include_path.append (a)
500 elif o == '--postscript' or o == '-P':
502 elif o == '--keep' or o == '-k':
504 elif o == '--no-lily':
506 elif o == '--outdir':
508 elif o == '--set' or o == '-s':
509 ss = string.split (a, '=')
510 set_setting (extra_init, ss[0], ss[1])
511 elif o == '--dependencies' or o == '-d':
512 track_dependencies_p = 1
513 elif o == '--version' or o == '-v':
516 elif o == '--warranty' or o == '-w':
521 include_path = map (os.path.abspath, include_path)
522 files = map (os.path.abspath, files)
523 outdir = os.path.abspath (outdir)
525 def strip_ly_suffix (f):
526 (p, e) =os.path.splitext (f)
531 files = map (strip_ly_suffix, files)
537 dvi_name = do_files (files, extra)
540 ps_name = generate_postscript (dvi_name, extra)
544 base = os.path.basename (files[0])
558 dest = os.path.join (outdir, dest)
560 system ('mkdir -p %s' % outdir)
561 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
562 system ('cp *.midi %s' % outdir, ignore_error = 1)
564 depfile = os.path.join (outdir, base + '.dep')
566 if track_dependencies_p:
567 generate_dependency_file (depfile, dest)
569 os.chdir (original_dir)
572 # most insteresting info last
573 progress (_ ("dependencies output to %s...") % depfile)
574 progress (_ ("%s file left in `%s'") % (type, dest))