2 # run lily, setup LaTeX input.
4 # Note: gettext work best if we use ' for docstrings and "
5 # for gettextable strings
10 * check --dependencies
12 * move versatile taglines,
15 beginfooter=\mutopiaPD
16 endfooter=\tagline -> 'lily was here <version>'
19 * head/header tagline/endfooter
21 * dvi from lilypond .tex output? This is hairy, because we create dvi
22 from lilypond .tex *and* header output.
37 sys.path.append ('@datadir@/python')
39 gettext.bindtextdomain ('lilypond', '@localedir@')
40 gettext.textdomain('lilypond')
44 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
45 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
49 # init to empty; values here take precedence over values in the file
53 'latexpackages' : ['geometry'],
61 extra_fields = extra_init.keys ()
63 fields = layout_fields + extra_fields
64 original_dir = os.getcwd ()
70 track_dependencies_p = 0
75 program_version = '@TOPLEVEL_VERSION@'
76 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
77 program_version = '1.3.134'
82 option_definitions = [
83 ('', 'h', 'help', _ ("this help")),
84 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
85 ('', 'P', 'postscript', _ ("generate PostScript output")),
86 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
87 ('', '', 'no-lily', _ ("don't run LilyPond")),
88 ('', 'v', 'version', _ ("print version number")),
89 ('', 'w', 'warranty', _ ("show warranty and copyright")),
90 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
91 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
95 sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
99 sys.stdout.write ('\n')
100 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
101 sys.stdout.write ('\n')
102 sys.stdout.write (' Han-Wen Nienhuys')
103 sys.stdout.write ('\n')
104 sys.stdout.write (_ (r'''
105 Distributed under terms of the GNU General Public License. It comes with
107 sys.stdout.write ('\n')
112 '''Make the progress messages stand out between lilypond stuff'''
113 # Why should they have to stand out? Blend in would be nice too.
114 sys.stderr.write ('*** ' + s+ '\n')
117 sys.stderr.write (_ ("warning: ") + s)
118 sys.stderr.write ('\n')
122 sys.stderr.write (_ ("error: ") + s)
123 sys.stderr.write ('\n')
124 raise _ ("Exiting ... ")
127 def find_file (name):
129 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
134 for a in include_path:
136 nm = os.path.join (a, name)
138 __main__.read_files.append (nm)
143 sys.stderr.write (_ ("Reading `%s'") % nm)
144 sys.stderr.write ('\n');
145 return (f.read (), nm)
147 error (_ ("can't open file: `%s'" % name))
148 sys.stderr.write ('\n');
154 def getopt_args (opts):
155 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
170 def option_help_str (o):
171 '''Transform one option description (4-tuple ) into neatly formatted string'''
189 return ' ' + sh + sep + long + arg
192 def options_help_str (opts):
193 '''Convert a list of options into a neatly formatted string'''
199 s = option_help_str (o)
200 strs.append ((s, o[3]))
206 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
210 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
211 sys.stdout.write ('\n\n')
212 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
213 sys.stdout.write ('\n\n')
214 sys.stdout.write (_ ("Options:"))
215 sys.stdout.write ('\n')
216 sys.stdout.write (options_help_str (option_definitions))
217 sys.stdout.write ('\n\n')
218 warning (_ ("all output is written in the CURRENT directory"))
219 sys.stdout.write ('\n')
220 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
221 sys.stdout.write ('\n')
227 temp_dir = 'ly2dvi.dir'
228 if not keep_temp_dir:
229 temp_dir = tempfile.mktemp ('ly2dvi')
232 os.mkdir (temp_dir, 0777)
237 # try not to gen/search MF stuff in temp dir
240 fp = ':' + os.environ['TFMFONTS']
245 os.environ['TFMFONTS'] = original_dir + fp
248 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
251 def system (cmd, ignore_error = 0):
252 sys.stderr.write (_ ("Invoking `%s\'") % cmd)
253 sys.stderr.write ('\n')
256 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
258 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
265 if not keep_temp_dir:
266 progress (_ ('Cleaning up `%s\'') % temp_dir)
267 system ('rm -rf %s' % temp_dir)
270 def run_lilypond (files):
272 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
273 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
275 if track_dependencies_p:
276 opts = opts + " --dependencies "
278 fs = string.join (files)
280 system ('lilypond %s %s ' % (opts, fs))
283 def set_setting (dict, key, val):
285 val = string.atof (val)
287 #warning (_ ("invalid value: %s") % `val`)
291 dict[key].append (val)
293 warning (_ ("no such setting: %s") % `key`)
297 def analyse_lilypond_output (filename, extra):
298 '''Grep FILENAME for interesting stuff, and
299 put relevant info into EXTRA.'''
300 filename = filename+'.tex'
301 progress (_ ("Analyzing `%s'") % filename)
302 s = open (filename).read ()
304 # search only the first 10k
306 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
307 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
309 set_setting (extra, x, m.group (1))
311 def find_tex_files_for_base (base, extra):
313 for f in layout_fields:
314 if os.path.exists (base + '.' + f):
315 headerfiles[f] = base+'.'+f
317 if os.path.exists (base +'.dep'):
318 dependency_files.append (base + '.dep')
320 for f in extra_fields:
321 if os.path.exists (base + '.' + f):
322 extra[f].append (open (base + '.' + f).read ())
324 return (base +'.tex',headerfiles)
327 def find_tex_files (files, extra):
332 fname = os.path.basename (f)
333 fname = strip_ly_suffix (fname)
335 fname = fname + '-%d' % x
337 if os.path.exists (fname + '.tex'):
338 tfiles.append (find_tex_files_for_base (fname, extra))
339 analyse_lilypond_output (fname, extra)
345 warning (_ ("no lilypond output found for %s") % `files`)
348 def one_latex_definition (defn, first):
350 for (k,v) in defn[1].items ():
351 val = open (v).read ()
352 if (string.strip (val)):
353 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
355 s = s + r'''\let\lilypond%s\relax''' % k
359 s = s + '\\def\\mustmakelilypondtitle{}\n'
361 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
363 s = s + '\\input %s' % defn[0]
367 ly_paper_to_latexpaper = {
369 'letter' : 'letterpaper',
372 def global_latex_definition (tfiles, extra):
373 '''construct preamble from EXTRA,
374 dump lily output files after that, and return result.
379 s = s + '% generation tag\n'
383 if extra['papersize']:
385 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
387 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
390 s = s + '\\documentclass%s{article}\n' % paper
392 if extra['language']:
393 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
396 s = s + '\\usepackage{%s}\n' \
397 % string.join (extra['latexpackages'], ',')
399 s = s + string.join (extra['latexheaders'], ' ')
402 if extra['textheight']:
403 textheight = ',textheight=%fpt' % extra['textheight'][0]
405 orientation = 'portrait'
406 if extra['orientation']:
407 orientation = extra['orientation'][0]
409 # set sane geometry width (a4-width) for linewidth = -1.
410 linewidth = extra['linewidth'][0]
413 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
416 \usepackage[latin1]{inputenc}
419 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondfooter}}%
422 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
424 \renewcommand{\@oddhead}{\parbox{\textwidth}%
425 {\mbox{}\small\makelilypondheader\hfill\textbf{\thepage}}}
428 s = s + '\\pagestyle{empty}\n'
430 s = s + '\\makeatother\n'
431 s = s + '\\begin{document}\n'
436 s = s + one_latex_definition (t, first)
441 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
444 s = s + '\\end{document}'
448 def do_files (fs, extra):
450 '''process the list of filenames in FS, using standard settings in EXTRA.
455 wfs = find_tex_files (fs, extra)
456 s = global_latex_definition (wfs, extra)
458 latex_file ='ly2dvi.out'
459 f = open (latex_file + '.tex', 'w')
464 system ('latex %s' % latex_file)
465 return latex_file + '.dvi'
467 def generate_postscript (dvi_name, extra):
468 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
471 if extra['papersize']:
472 opts = opts + ' -t %s' % extra['papersize'][0]
474 if extra['orientation'] and extra['orientation'][0] == 'landscape':
475 opts = opts + ' -t landscape'
477 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
478 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
484 def generate_dependency_file (depfile, outname):
485 df = open (depfile, 'w')
486 df.write (outname + ':' )
488 for d in dependency_files:
490 s = re.sub ('#[^\n]*\n', '', s)
491 s = re.sub (r'\\\n', ' ', s)
492 m = re.search ('.*:(.*)\n', s)
494 # ugh. Different targets?
496 df.write ( m.group (1) + ' ' )
501 (sh, long) = getopt_args (__main__.option_definitions)
503 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
514 elif o == '--help' or o == '-h':
516 elif o == '--include' or o == '-I':
517 include_path.append (a)
518 elif o == '--postscript' or o == '-P':
520 elif o == '--keep' or o == '-k':
522 elif o == '--no-lily':
524 elif o == '--outdir':
526 elif o == '--set' or o == '-s':
527 ss = string.split (a, '=')
528 set_setting (extra_init, ss[0], ss[1])
529 elif o == '--dependencies' or o == '-d':
530 track_dependencies_p = 1
531 elif o == '--version' or o == '-v':
534 elif o == '--warranty' or o == '-w':
539 include_path = map (os.path.abspath, include_path)
540 files = map (os.path.abspath, files)
541 outdir = os.path.abspath (outdir)
543 def strip_ly_suffix (f):
544 (p, e) =os.path.splitext (f)
549 files = map (strip_ly_suffix, files)
555 dvi_name = do_files (files, extra)
558 ps_name = generate_postscript (dvi_name, extra)
562 base = os.path.basename (files[0])
576 dest = os.path.join (outdir, dest)
578 system ('mkdir -p %s' % outdir)
579 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
580 system ('cp *.midi %s' % outdir, ignore_error = 1)
582 depfile = os.path.join (outdir, base + '.dep')
584 if track_dependencies_p:
585 generate_dependency_file (depfile, dest)
587 os.chdir (original_dir)
590 # most insteresting info last
591 progress (_ ("dependencies output to %s...") % depfile)
592 progress (_ ("%s file left in `%s'") % (type, dest))