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'
85 option_definitions = [
86 ('', 'h', 'help', _ ("this help")),
87 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
88 ('', 'P', 'postscript', _ ("generate PostScript output")),
89 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
90 ('', '', 'no-lily', _ ("don't run LilyPond")),
91 ('', 'V', 'verbose', _ ("verbose")),
92 ('', 'v', 'version', _ ("print version number")),
93 ('', 'w', 'warranty', _ ("show warranty and copyright")),
94 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
95 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
99 sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
103 sys.stdout.write ('\n')
104 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
105 sys.stdout.write ('\n')
106 sys.stdout.write (' Han-Wen Nienhuys')
107 sys.stdout.write ('\n')
108 sys.stdout.write (_ (r'''
109 Distributed under terms of the GNU General Public License. It comes with
111 sys.stdout.write ('\n')
115 def star_progress (s):
116 '''Progress messages that stand out between lilypond stuff'''
117 progress ('*** ' + s)
120 sys.stderr.write (s + '\n')
123 sys.stderr.write (_ ("warning: ") + s)
124 sys.stderr.write ('\n')
128 sys.stderr.write (_ ("error: ") + s)
129 sys.stderr.write ('\n')
130 raise _ ("Exiting ... ")
133 def find_file (name):
135 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
140 for a in include_path:
142 nm = os.path.join (a, name)
144 __main__.read_files.append (nm)
149 sys.stderr.write (_ ("Reading %s...") % nm)
150 sys.stderr.write ('\n');
151 return (f.read (), nm)
153 error (_ ("can't open file: `%s'" % name))
154 sys.stderr.write ('\n');
160 def getopt_args (opts):
161 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
176 def option_help_str (o):
177 '''Transform one option description (4-tuple ) into neatly formatted string'''
195 return ' ' + sh + sep + long + arg
198 def options_help_str (opts):
199 '''Convert a list of options into a neatly formatted string'''
205 s = option_help_str (o)
206 strs.append ((s, o[3]))
212 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
216 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
217 sys.stdout.write ('\n\n')
218 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
219 sys.stdout.write ('\n\n')
220 sys.stdout.write (_ ("Options:"))
221 sys.stdout.write ('\n')
222 sys.stdout.write (options_help_str (option_definitions))
223 sys.stdout.write ('\n\n')
224 warning (_ ("all output is written in the CURRENT directory"))
225 sys.stdout.write ('\n')
226 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
227 sys.stdout.write ('\n')
233 temp_dir = 'ly2dvi.dir'
234 if not keep_temp_dir:
235 temp_dir = tempfile.mktemp ('ly2dvi')
238 os.mkdir (temp_dir, 0777)
243 # try not to gen/search MF stuff in temp dir
246 fp = ':' + os.environ['TFMFONTS']
251 os.environ['TFMFONTS'] = original_dir + fp
255 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
258 def system (cmd, ignore_error = 0):
260 progress (_ ("Invoking `%s\'") % cmd)
263 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
265 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
272 if not keep_temp_dir:
274 progress (_ ('Cleaning up `%s\'') % temp_dir)
275 system ('rm -rf %s' % temp_dir)
278 def run_lilypond (files):
280 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
281 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
283 if track_dependencies_p:
284 opts = opts + " --dependencies "
286 fs = string.join (files)
288 system ('lilypond %s %s ' % (opts, fs))
291 def set_setting (dict, key, val):
293 val = string.atof (val)
295 #warning (_ ("invalid value: %s") % `val`)
299 dict[key].append (val)
301 warning (_ ("no such setting: %s") % `key`)
305 def analyse_lilypond_output (filename, extra):
306 '''Grep FILENAME for interesting stuff, and
307 put relevant info into EXTRA.'''
308 filename = filename+'.tex'
309 progress (_ ("Analyzing `%s'") % filename)
310 s = open (filename).read ()
312 # search only the first 10k
314 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
315 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
317 set_setting (extra, x, m.group (1))
319 def find_tex_files_for_base (base, extra):
321 for f in layout_fields:
322 if os.path.exists (base + '.' + f):
323 headerfiles[f] = base+'.'+f
325 if os.path.exists (base +'.dep'):
326 dependency_files.append (base + '.dep')
328 for f in extra_fields:
329 if os.path.exists (base + '.' + f):
330 extra[f].append (open (base + '.' + f).read ())
332 return (base +'.tex',headerfiles)
335 def find_tex_files (files, extra):
340 fname = os.path.basename (f)
341 fname = strip_ly_suffix (fname)
343 fname = fname + '-%d' % x
345 if os.path.exists (fname + '.tex'):
346 tfiles.append (find_tex_files_for_base (fname, extra))
347 analyse_lilypond_output (fname, extra)
353 warning (_ ("no lilypond output found for %s") % `files`)
356 def one_latex_definition (defn, first):
358 for (k,v) in defn[1].items ():
359 val = open (v).read ()
360 if (string.strip (val)):
361 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
363 s = s + r'''\let\lilypond%s\relax''' % k
367 s = s + '\\def\\mustmakelilypondtitle{}\n'
369 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
371 s = s + '\\input %s' % defn[0]
375 ly_paper_to_latexpaper = {
377 'letter' : 'letterpaper',
380 def global_latex_definition (tfiles, extra):
381 '''construct preamble from EXTRA,
382 dump lily output files after that, and return result.
387 s = s + '% generation tag\n'
391 if extra['papersize']:
393 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
395 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
398 s = s + '\\documentclass%s{article}\n' % paper
400 if extra['language']:
401 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
404 s = s + '\\usepackage{%s}\n' \
405 % string.join (extra['latexpackages'], ',')
407 s = s + string.join (extra['latexheaders'], ' ')
410 if extra['textheight']:
411 textheight = ',textheight=%fpt' % extra['textheight'][0]
413 orientation = 'portrait'
414 if extra['orientation']:
415 orientation = extra['orientation'][0]
417 # set sane geometry width (a4-width) for linewidth = -1.
418 linewidth = extra['linewidth'][0]
421 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
424 \usepackage[latin1]{inputenc}
427 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
430 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
432 \renewcommand{\@oddhead}{\parbox{\textwidth}%
433 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
436 s = s + '\\pagestyle{empty}\n'
438 s = s + '\\makeatother\n'
439 s = s + '\\begin{document}\n'
444 s = s + one_latex_definition (t, first)
449 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
452 s = s + '\\end{document}'
456 def do_files (fs, extra):
458 '''process the list of filenames in FS, using standard settings in EXTRA.
463 wfs = find_tex_files (fs, extra)
464 s = global_latex_definition (wfs, extra)
466 latex_file ='ly2dvi.out'
467 f = open (latex_file + '.tex', 'w')
472 system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
473 return latex_file + '.dvi'
475 def generate_postscript (dvi_name, extra):
476 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
479 if extra['papersize']:
480 opts = opts + ' -t %s' % extra['papersize'][0]
482 if extra['orientation'] and extra['orientation'][0] == 'landscape':
483 opts = opts + ' -t landscape'
485 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
486 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
492 def generate_dependency_file (depfile, outname):
493 df = open (depfile, 'w')
494 df.write (outname + ':' )
496 for d in dependency_files:
498 s = re.sub ('#[^\n]*\n', '', s)
499 s = re.sub (r'\\\n', ' ', s)
500 m = re.search ('.*:(.*)\n', s)
502 # ugh. Different targets?
504 df.write ( m.group (1) + ' ' )
509 (sh, long) = getopt_args (__main__.option_definitions)
511 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
522 elif o == '--help' or o == '-h':
524 elif o == '--include' or o == '-I':
525 include_path.append (a)
526 elif o == '--postscript' or o == '-P':
528 elif o == '--keep' or o == '-k':
530 elif o == '--no-lily':
532 elif o == '--outdir':
534 elif o == '--set' or o == '-s':
535 ss = string.split (a, '=')
536 set_setting (extra_init, ss[0], ss[1])
537 elif o == '--dependencies' or o == '-d':
538 track_dependencies_p = 1
539 elif o == '--verbose' or o == '-V':
541 elif o == '--version' or o == '-v':
544 elif o == '--warranty' or o == '-w':
549 include_path = map (os.path.abspath, include_path)
550 files = map (os.path.abspath, files)
551 outdir = os.path.abspath (outdir)
553 def strip_ly_suffix (f):
554 (p, e) =os.path.splitext (f)
559 files = map (strip_ly_suffix, files)
565 dvi_name = do_files (files, extra)
568 ps_name = generate_postscript (dvi_name, extra)
572 base = os.path.basename (files[0])
586 dest = os.path.join (outdir, dest)
588 system ('mkdir -p %s' % outdir)
589 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
590 if re.match ('[.]midi', string.join (os.listdir ('.'))):
591 system ('cp *.midi %s' % outdir, ignore_error = 1)
593 depfile = os.path.join (outdir, base + '.dep')
595 if track_dependencies_p:
596 generate_dependency_file (depfile, dest)
598 os.chdir (original_dir)
601 # most insteresting info last
602 progress (_ ("dependencies output to %s...") % depfile)
603 progress (_ ("%s output to %s...") % (type, dest))