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')
109 raise _ ("Exiting ... ")
112 def find_file (name):
114 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
119 for a in include_path:
121 nm = os.path.join (a, name)
123 __main__.read_files.append (nm)
128 sys.stderr.write (_ ("Reading `%s'") % nm)
129 sys.stderr.write ('\n');
130 return (f.read (), nm)
132 error (_ ("can't open file: `%s'" % name))
133 sys.stderr.write ('\n');
139 def getopt_args (opts):
140 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
155 def option_help_str (o):
156 '''Transform one option description (4-tuple ) into neatly formatted string'''
174 return ' ' + sh + sep + long + arg
177 def options_help_str (opts):
178 '''Convert a list of options into a neatly formatted string'''
184 s = option_help_str (o)
185 strs.append ((s, o[3]))
191 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
195 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
196 sys.stdout.write ('\n\n')
197 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
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 (_ ("warning: "))
204 sys.stdout.write (_ ("all output is written in the CURRENT directory"))
205 sys.stdout.write ('\n\n')
206 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
207 sys.stdout.write ('\n')
213 temp_dir = 'ly2dvi.dir'
214 if not keep_temp_dir:
215 temp_dir = tempfile.mktemp ('ly2dvi')
218 os.mkdir (temp_dir, 0777)
223 # try not to gen/search MF stuff in temp dir
226 fp = ':' + os.environ['TFMFONTS']
231 os.environ['TFMFONTS'] = original_dir + fp
234 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
237 def system (cmd, ignore_error = 0):
238 sys.stderr.write (_ ("Invoking `%s\'") % cmd)
239 sys.stderr.write ('\n')
242 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
244 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
251 if not keep_temp_dir:
252 progress (_ ('Cleaning up `%s\'') % temp_dir)
253 system ('rm -rf %s' % temp_dir)
256 def run_lilypond (files):
258 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
259 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
261 if track_dependencies_p:
262 opts = opts + " --dependencies "
264 fs = string.join (files)
266 system ('lilypond %s %s ' % (opts, fs))
269 def set_setting (dict, key, val):
271 val = string.atof (val)
276 dict[key].append (val)
281 def analyse_lilypond_output (filename, extra):
282 '''Grep FILENAME for interesting stuff, and
283 put relevant info into EXTRA.'''
284 filename = filename+'.tex'
285 progress (_ ("Analyzing `%s'") % filename)
286 s = open (filename).read ()
288 # search only the first 10k
290 for x in ('textheight', 'linewidth', 'papersizename', 'orientation'):
291 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
293 set_setting (extra, x, m.group (1))
295 def find_tex_files_for_base (base, extra):
297 for f in layout_fields:
298 if os.path.exists (base + '.' + f):
299 headerfiles[f] = base+'.'+f
301 if os.path.exists (base +'.dep'):
302 dependency_files.append (base + '.dep')
304 for f in extra_fields:
305 if os.path.exists (base + '.' + f):
306 extra[f].append (open (base + '.' + f).read ())
308 return (base +'.tex',headerfiles)
311 def find_tex_files (files, extra):
316 fname = os.path.basename (f)
317 fname = os.path.splitext (fname)[0]
319 fname = fname + '-%d' % x
321 if os.path.exists (fname + '.tex'):
322 tfiles.append (find_tex_files_for_base (fname, extra))
323 analyse_lilypond_output (fname, extra)
330 def one_latex_definition (defn, first):
332 for (k,v) in defn[1].items ():
333 val = open (v).read ()
334 if (string.strip (val)):
335 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
337 s = s + r'''\let\lilypond%s\relax''' % k
341 s = s + '\\def\\mustmakelilypondtitle{}\n'
343 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
345 s = s + '\\input %s' % defn[0]
349 ly_paper_to_latexpaper = {
354 def global_latex_definition (tfiles, extra):
355 '''construct preamble from EXTRA,
356 dump lily output files after that, and return result.
361 s = s + '% generation tag\n'
365 if extra['papersizename']:
366 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersizename'][0]]
367 s = s + '\\documentclass%s{article}\n' % paper
369 if extra['language']:
370 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
373 s = s + '\\usepackage{%s}\n' \
374 % string.join (extra['latexpackages'], ',')
376 s = s + string.join (extra['latexheaders'], ' ')
379 if extra['textheight']:
380 textheight = ',textheight=%fpt' % extra['textheight'][0]
382 orientation = 'portrait'
383 if extra['orientation']:
384 orientation = extra['orientation'][0]
386 # set sane geometry width (a4-width) for linewidth = -1.
387 linewidth = extra['linewidth'][0]
390 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
393 \usepackage[latin1]{inputenc}
396 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
398 if extra['pagenumber'] and extra['pagenumber'][-1]:
400 \renewcommand{\@oddhead}{\parbox{\textwidth}%%
401 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%'''
403 s = s + '\\pagestyle{empty}'
405 s = s + '\\begin{document}'
409 s = s + one_latex_definition (t, first)
412 s = s + '\\end{document}'
416 def do_files (fs, extra):
418 '''process the list of filenames in FS, using standard settings in EXTRA.
423 wfs = find_tex_files (fs, extra)
424 s = global_latex_definition (wfs, extra)
426 latex_file ='ly2dvi.out'
427 f = open (latex_file + '.tex', 'w')
432 system ('latex %s' % latex_file)
433 return latex_file + '.dvi'
435 def generate_postscript (dvi_name, extra):
436 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
439 if extra['papersizename']:
440 opts = opts + ' -t %s' % extra['papersizename'][0]
442 if extra['orientation'] and extra['orientation'][0] == 'landscape':
443 opts = opts + ' -t landscape'
445 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
446 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
452 def generate_dependency_file (depfile, outname):
453 df = open (depfile, 'w')
454 df.write (outname + ':' )
456 for d in dependency_files:
458 s = re.sub ('#[^\n]*\n', '', s)
459 s = re.sub (r'\\\n', ' ', s)
460 m = re.search ('.*:(.*)\n', s)
462 # ugh. Different targets?
464 df.write ( m.group (1) + ' ' )
469 (sh, long) = getopt_args (__main__.option_definitions)
471 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
482 elif o == '--help' or o == '-h':
484 elif o == '--include' or o == '-I':
485 include_path.append (a)
486 elif o == '--postscript' or o == '-P':
488 elif o == '--keep' or o == '-k':
490 elif o == '--no-lily':
492 elif o == '--outdir':
494 elif o == '--set' or o == '-s':
495 ss = string.split (a, '=')
496 set_setting (extra_init, ss[0], ss[1])
497 elif o == '--dependencies' or o == '-d':
498 track_dependencies_p = 1
499 elif o == '--version' or o == '-v':
502 elif o == '--warranty' or o == '-w':
507 include_path = map (os.path.abspath, include_path)
508 files = map (os.path.abspath, files)
509 outdir = os.path.abspath (outdir)
511 def strip_ly_suffix (f):
512 (p, e) =os.path.splitext (f)
517 files = map (strip_ly_suffix, files)
523 dvi_name = do_files (files, extra)
526 ps_name = generate_postscript (dvi_name, extra)
530 base = os.path.basename (files[0])
544 dest = os.path.join (outdir, dest)
546 system ('mkdir -p %s' % outdir)
547 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
548 system ('cp *.midi %s' % outdir, ignore_error = 1)
550 depfile = os.path.join (outdir, base + '.dep')
552 if track_dependencies_p:
553 generate_dependency_file (depfile, dest)
555 os.chdir (original_dir)
558 # most insteresting info last
559 progress (_ ("dependencies output to %s...") % depfile)
560 progress (_ ("%s file left in `%s'") % (type, dest))