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 lilytagline (->lily was here), usertagline, copyright etc.
21 * head/header tagline/endfooter
23 * dvi from lilypond .tex output? This is hairy, because we create dvi
24 from lilypond .tex *and* header output.
26 * multiple \score blocks?
28 * windows-sans-cygwin compatibility? rm -rf, cp file... dir
44 sys.path.append (datadir + '/python')
47 gettext.bindtextdomain ('lilypond', '@localedir@')
48 gettext.textdomain('lilypond')
55 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
56 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
60 # init to empty; values here take precedence over values in the file
64 'latexpackages' : ['geometry'],
72 extra_fields = extra_init.keys ()
74 fields = layout_fields + extra_fields
75 program_name = 'ly2dvi'
76 help_summary = _("Generate .dvi with LaTeX for LilyPond")
81 track_dependencies_p = 0
91 # lily_py.py -- options and stuff
93 # source file of the GNU LilyPond music typesetter
95 # BEGIN Library for these?
96 # cut-n-paste from ly2dvi
98 program_version = '@TOPLEVEL_VERSION@'
99 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
100 program_version = '1.3.142'
103 original_dir = os.getcwd ()
104 temp_dir = '%s.dir' % program_name
109 # Try to cater for bad installations of LilyPond, that have
110 # broken TeX setup. Just hope this doesn't hurt good TeX
111 # setups. Maybe we should check if kpsewhich can find
112 # feta16.{afm,mf,tex,tfm}, and only set env upon failure.
115 'MFINPUTS' : datadir + '/mf:',
116 'TEXINPUTS': datadir + '/tex:' + datadir + '/ps:.:',
117 'TFMFONTS' : datadir + '/tfm:',
118 'GS_FONTPATH' : datadir + '/afm:' + datadir + '/pfa',
119 'GS_LIB' : datadir + '/ps',
122 def setup_environment ():
123 for key in environment.keys ():
124 val = environment[key]
125 if os.environ.has_key (key):
126 val = val + os.pathsep + os.environ[key]
127 os.environ[key] = val
130 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
134 sys.stdout.write ('\n')
135 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
136 sys.stdout.write ('\n')
137 sys.stdout.write (' Han-Wen Nienhuys')
138 sys.stdout.write (' Jan Nieuwenhuizen')
139 sys.stdout.write ('\n')
140 sys.stdout.write (_ (r'''
141 Distributed under terms of the GNU General Public License. It comes with
143 sys.stdout.write ('\n')
146 sys.stderr.write (s + '\n')
149 sys.stderr.write (_ ("warning: ") + s)
150 sys.stderr.write ('\n')
154 sys.stderr.write (_ ("error: ") + s)
155 sys.stderr.write ('\n')
156 raise _ ("Exiting ... ")
158 def getopt_args (opts):
159 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
174 def option_help_str (o):
175 '''Transform one option description (4-tuple ) into neatly formatted string'''
193 return ' ' + sh + sep + long + arg
196 def options_help_str (opts):
197 '''Convert a list of options into a neatly formatted string'''
203 s = option_help_str (o)
204 strs.append ((s, o[3]))
210 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
214 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % program_name)
215 sys.stdout.write ('\n\n')
216 sys.stdout.write (help_summary)
217 sys.stdout.write ('\n\n')
218 sys.stdout.write (_ ("Options:"))
219 sys.stdout.write ('\n')
220 sys.stdout.write (options_help_str (option_definitions))
221 sys.stdout.write ('\n\n')
222 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
223 sys.stdout.write ('\n')
229 if not keep_temp_dir_p:
230 temp_dir = tempfile.mktemp (program_name)
232 os.mkdir (temp_dir, 0777)
238 def system (cmd, ignore_error = 0):
240 progress (_ ("Invoking `%s\'") % cmd)
243 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
245 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
253 if not keep_temp_dir_p:
255 progress (_ ("Cleaning %s...") % temp_dir)
256 system ('rm -rf %s' % temp_dir)
259 def set_setting (dict, key, val):
261 val = string.atof (val)
263 #warning (_ ("invalid value: %s") % `val`)
267 dict[key].append (val)
269 warning (_ ("no such setting: %s") % `key`)
272 def strip_extension (f, ext):
273 (p, e) = os.path.splitext (f)
280 option_definitions = [
281 ('', 'h', 'help', _ ("this help")),
282 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
283 ('DIR', 'I', 'include', _ ("add DIR to LilyPond\'s search path")),
284 ('', 'P', 'postscript', _ ("generate PostScript output")),
285 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
286 ('', '', 'no-lily', _ ("don't run LilyPond")),
287 ('', 'V', 'verbose', _ ("verbose")),
288 ('', 'v', 'version', _ ("print version number")),
289 ('', 'w', 'warranty', _ ("show warranty and copyright")),
290 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
291 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
294 def run_lilypond (files):
296 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
297 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
299 if track_dependencies_p:
300 opts = opts + " --dependencies "
302 fs = string.join (files)
304 system ('lilypond %s %s ' % (opts, fs))
306 def analyse_lilypond_output (filename, extra):
307 '''Grep FILENAME for interesting stuff, and
308 put relevant info into EXTRA.'''
309 filename = filename+'.tex'
310 progress (_ ("Analyzing `%s'") % filename)
311 s = open (filename).read ()
313 # search only the first 10k
315 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
316 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
318 set_setting (extra, x, m.group (1))
320 def find_tex_files_for_base (base, extra):
322 for f in layout_fields:
323 if os.path.exists (base + '.' + f):
324 headerfiles[f] = base+'.'+f
326 if os.path.exists (base +'.dep'):
327 dependency_files.append (base + '.dep')
329 for f in extra_fields:
330 if os.path.exists (base + '.' + f):
331 extra[f].append (open (base + '.' + f).read ())
333 return (base +'.tex',headerfiles)
336 def find_tex_files (files, extra):
341 fname = os.path.basename (f)
342 fname = strip_extension (fname, '.ly')
344 fname = fname + '-%d' % x
346 if os.path.exists (fname + '.tex'):
347 tfiles.append (find_tex_files_for_base (fname, extra))
348 analyse_lilypond_output (fname, extra)
354 warning (_ ("no lilypond output found for %s") % `files`)
357 def one_latex_definition (defn, first):
359 for (k,v) in defn[1].items ():
360 val = open (v).read ()
361 if (string.strip (val)):
362 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
364 s = s + r'''\let\lilypond%s\relax''' % k
368 s = s + '\\def\\mustmakelilypondtitle{}\n'
370 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
372 s = s + '\\input %s' % defn[0]
376 ly_paper_to_latexpaper = {
378 'letter' : 'letterpaper',
381 def global_latex_definition (tfiles, extra):
382 '''construct preamble from EXTRA,
383 dump lily output files after that, and return result.
388 s = s + '% generation tag\n'
392 if extra['papersize']:
394 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
396 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
399 s = s + '\\documentclass%s{article}\n' % paper
401 if extra['language']:
402 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
405 s = s + '\\usepackage{%s}\n' \
406 % string.join (extra['latexpackages'], ',')
408 if extra['latexheaders']:
409 s = s + '\\include{%s}\n' \
410 % string.join (extra['latexheaders'], '}\n\\include{')
413 if extra['textheight']:
414 textheight = ',textheight=%fpt' % extra['textheight'][0]
416 orientation = 'portrait'
417 if extra['orientation']:
418 orientation = extra['orientation'][0]
420 # set sane geometry width (a4-width) for linewidth = -1.
421 if not extra['linewidth'] or extra['linewidth'][0] < 0:
424 linewidth = extra['linewidth'][0]
425 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
428 \usepackage[latin1]{inputenc}
431 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
434 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
436 \renewcommand{\@oddhead}{\parbox{\textwidth}%
437 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
440 s = s + '\\pagestyle{empty}\n'
442 s = s + '\\makeatother\n'
443 s = s + '\\begin{document}\n'
448 s = s + one_latex_definition (t, first)
453 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
456 s = s + '\\end{document}'
460 def do_files (fs, extra):
462 '''process the list of filenames in FS, using standard settings in EXTRA.
467 wfs = find_tex_files (fs, extra)
468 s = global_latex_definition (wfs, extra)
470 latex_file ='ly2dvi.out'
471 f = open (latex_file + '.tex', 'w')
476 system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
477 return latex_file + '.dvi'
479 def generate_postscript (dvi_name, extra):
480 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
483 if extra['papersize']:
484 opts = opts + ' -t %s' % extra['papersize'][0]
486 if extra['orientation'] and extra['orientation'][0] == 'landscape':
487 opts = opts + ' -t landscape'
489 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
490 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
496 def generate_dependency_file (depfile, outname):
497 df = open (depfile, 'w')
498 df.write (outname + ':' )
500 for d in dependency_files:
502 s = re.sub ('#[^\n]*\n', '', s)
503 s = re.sub (r'\\\n', ' ', s)
504 m = re.search ('.*:(.*)\n', s)
506 # ugh. Different targets?
508 df.write ( m.group (1) + ' ' )
513 (sh, long) = getopt_args (__main__.option_definitions)
515 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
526 elif o == '--help' or o == '-h':
528 elif o == '--include' or o == '-I':
529 include_path.append (a)
530 elif o == '--postscript' or o == '-P':
532 elif o == '--keep' or o == '-k':
534 elif o == '--no-lily':
536 elif o == '--outdir':
538 elif o == '--set' or o == '-s':
539 ss = string.split (a, '=')
540 set_setting (extra_init, ss[0], ss[1])
541 elif o == '--dependencies' or o == '-d':
542 track_dependencies_p = 1
543 elif o == '--verbose' or o == '-V':
545 elif o == '--version' or o == '-v':
548 elif o == '--warranty' or o == '-w':
552 # On most platforms, this is equivalent to
553 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
554 def compat_abspath (path):
555 return os.path.normpath (os.path.join (os.getcwd (), path))
557 include_path = map (compat_abspath, include_path)
558 files = map (compat_abspath, files)
559 outdir = compat_abspath (outdir)
562 files = map (lambda x: strip_extension (x, '.ly'), files)
570 dvi_name = do_files (files, extra)
573 ps_name = generate_postscript (dvi_name, extra)
577 base = os.path.basename (files[0])
591 dest = os.path.join (outdir, dest)
592 midi = base + '.midi'
593 midi = os.path.join (outdir, midi)
596 system ('mkdir -p %s' % outdir)
598 #if re.match ('.*[.]dvi', string.join (os.listdir ('.'))):
599 if os.path.isfile (srcname):
600 # huh, and what bout all other (-1, -2) scores?
601 system ('cp \"%s\" \"%s\"' % (srcname, dest))
604 if re.match ('.*[.]midi', string.join (os.listdir ('.'))):
605 system ('cp *.midi %s' % outdir)
609 depfile = os.path.join (outdir, base + '.dep')
611 if track_dependencies_p:
612 generate_dependency_file (depfile, dest)
614 os.chdir (original_dir)
617 # most insteresting info last
618 # don't say silly things
619 if os.path.isfile (depfile):
620 progress (_ ("dependencies output to %s...") % depfile)
621 if dest and os.path.isfile (dest):
622 progress (_ ("%s output to %s...") % (type, dest))
623 if midi and os.path.isfile (midi):
624 progress (_ ("%s output to %s...") % ('MIDI', midi))