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 * check/set TEXINPUTS: see to it that/warn if not/
24 kpathsea can find titledefs.tex?
26 * dvi from lilypond .tex output? This is hairy, because we create dvi
27 from lilypond .tex *and* header output.
29 * multiple \score blocks?
31 * windows-sans-cygwin compatibility? rm -rf, cp file... dir
46 sys.path.append ('@datadir@/python')
49 gettext.bindtextdomain ('lilypond', '@localedir@')
50 gettext.textdomain('lilypond')
57 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
58 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
62 # init to empty; values here take precedence over values in the file
66 'latexpackages' : ['geometry'],
74 extra_fields = extra_init.keys ()
76 fields = layout_fields + extra_fields
77 program_name = 'ly2dvi'
78 help_summary = _("Generate .dvi with LaTeX for LilyPond")
83 track_dependencies_p = 0
93 # lily_py.py -- options and stuff
95 # source file of the GNU LilyPond music typesetter
97 # BEGIN Library for these?
98 # cut-n-paste from ly2dvi
100 program_version = '@TOPLEVEL_VERSION@'
101 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
102 program_version = '1.3.142'
105 original_dir = os.getcwd ()
106 temp_dir = '%s.dir' % program_name
111 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
115 sys.stdout.write ('\n')
116 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
117 sys.stdout.write ('\n')
118 sys.stdout.write (' Han-Wen Nienhuys')
119 sys.stdout.write (' Jan Nieuwenhuizen')
120 sys.stdout.write ('\n')
121 sys.stdout.write (_ (r'''
122 Distributed under terms of the GNU General Public License. It comes with
124 sys.stdout.write ('\n')
127 sys.stderr.write (s + '\n')
130 sys.stderr.write (_ ("warning: ") + s)
131 sys.stderr.write ('\n')
135 sys.stderr.write (_ ("error: ") + s)
136 sys.stderr.write ('\n')
137 raise _ ("Exiting ... ")
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") % program_name)
196 sys.stdout.write ('\n\n')
197 sys.stdout.write (help_summary)
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 (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
204 sys.stdout.write ('\n')
210 if not keep_temp_dir_p:
211 temp_dir = tempfile.mktemp (program_name)
213 os.mkdir (temp_dir, 0777)
219 def system (cmd, ignore_error = 0):
221 progress (_ ("Invoking `%s\'") % cmd)
224 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
226 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
234 if not keep_temp_dir_p:
236 progress (_ ("Cleaning %s...") % temp_dir)
237 system ('rm -rf %s' % temp_dir)
240 def set_setting (dict, key, val):
242 val = string.atof (val)
244 #warning (_ ("invalid value: %s") % `val`)
248 dict[key].append (val)
250 warning (_ ("no such setting: %s") % `key`)
253 def strip_extension (f, ext):
254 (p, e) = os.path.splitext (f)
261 option_definitions = [
262 ('', 'h', 'help', _ ("this help")),
263 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
264 ('DIR', 'I', 'include', _ ("add DIR to LilyPond\'s search path")),
265 ('', 'P', 'postscript', _ ("generate PostScript output")),
266 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
267 ('', '', 'no-lily', _ ("don't run LilyPond")),
268 ('', 'V', 'verbose', _ ("verbose")),
269 ('', 'v', 'version', _ ("print version number")),
270 ('', 'w', 'warranty', _ ("show warranty and copyright")),
271 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
272 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
275 def run_lilypond (files):
277 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
278 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
280 if track_dependencies_p:
281 opts = opts + " --dependencies "
283 fs = string.join (files)
285 system ('lilypond %s %s ' % (opts, fs))
287 def analyse_lilypond_output (filename, extra):
288 '''Grep FILENAME for interesting stuff, and
289 put relevant info into EXTRA.'''
290 filename = filename+'.tex'
291 progress (_ ("Analyzing `%s'") % filename)
292 s = open (filename).read ()
294 # search only the first 10k
296 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
297 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
299 set_setting (extra, x, m.group (1))
301 def find_tex_files_for_base (base, extra):
303 for f in layout_fields:
304 if os.path.exists (base + '.' + f):
305 headerfiles[f] = base+'.'+f
307 if os.path.exists (base +'.dep'):
308 dependency_files.append (base + '.dep')
310 for f in extra_fields:
311 if os.path.exists (base + '.' + f):
312 extra[f].append (open (base + '.' + f).read ())
314 return (base +'.tex',headerfiles)
317 def find_tex_files (files, extra):
322 fname = os.path.basename (f)
323 fname = strip_extension (fname, '.ly')
325 fname = fname + '-%d' % x
327 if os.path.exists (fname + '.tex'):
328 tfiles.append (find_tex_files_for_base (fname, extra))
329 analyse_lilypond_output (fname, extra)
335 warning (_ ("no lilypond output found for %s") % `files`)
338 def one_latex_definition (defn, first):
340 for (k,v) in defn[1].items ():
341 val = open (v).read ()
342 if (string.strip (val)):
343 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
345 s = s + r'''\let\lilypond%s\relax''' % k
349 s = s + '\\def\\mustmakelilypondtitle{}\n'
351 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
353 s = s + '\\input %s' % defn[0]
357 ly_paper_to_latexpaper = {
359 'letter' : 'letterpaper',
362 def global_latex_definition (tfiles, extra):
363 '''construct preamble from EXTRA,
364 dump lily output files after that, and return result.
369 s = s + '% generation tag\n'
373 if extra['papersize']:
375 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
377 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
380 s = s + '\\documentclass%s{article}\n' % paper
382 if extra['language']:
383 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
386 s = s + '\\usepackage{%s}\n' \
387 % string.join (extra['latexpackages'], ',')
389 if extra['latexheaders']:
390 s = s + '\\include{%s}\n' \
391 % string.join (extra['latexheaders'], '}\n\\include{')
394 if extra['textheight']:
395 textheight = ',textheight=%fpt' % extra['textheight'][0]
397 orientation = 'portrait'
398 if extra['orientation']:
399 orientation = extra['orientation'][0]
401 # set sane geometry width (a4-width) for linewidth = -1.
402 if not extra['linewidth'] or extra['linewidth'][0] < 0:
405 linewidth = extra['linewidth'][0]
406 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
409 \usepackage[latin1]{inputenc}
412 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
415 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
417 \renewcommand{\@oddhead}{\parbox{\textwidth}%
418 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
421 s = s + '\\pagestyle{empty}\n'
423 s = s + '\\makeatother\n'
424 s = s + '\\begin{document}\n'
429 s = s + one_latex_definition (t, first)
434 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\makelilypondtagline}}%
437 s = s + '\\end{document}'
441 def do_files (fs, extra):
443 '''process the list of filenames in FS, using standard settings in EXTRA.
448 wfs = find_tex_files (fs, extra)
449 s = global_latex_definition (wfs, extra)
451 latex_file ='ly2dvi.out'
452 f = open (latex_file + '.tex', 'w')
457 system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
458 return latex_file + '.dvi'
460 def generate_postscript (dvi_name, extra):
461 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
464 if extra['papersize']:
465 opts = opts + ' -t %s' % extra['papersize'][0]
467 if extra['orientation'] and extra['orientation'][0] == 'landscape':
468 opts = opts + ' -t landscape'
470 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
471 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
477 def generate_dependency_file (depfile, outname):
478 df = open (depfile, 'w')
479 df.write (outname + ':' )
481 for d in dependency_files:
483 s = re.sub ('#[^\n]*\n', '', s)
484 s = re.sub (r'\\\n', ' ', s)
485 m = re.search ('.*:(.*)\n', s)
487 # ugh. Different targets?
489 df.write ( m.group (1) + ' ' )
494 (sh, long) = getopt_args (__main__.option_definitions)
496 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
507 elif o == '--help' or o == '-h':
509 elif o == '--include' or o == '-I':
510 include_path.append (a)
511 elif o == '--postscript' or o == '-P':
513 elif o == '--keep' or o == '-k':
515 elif o == '--no-lily':
517 elif o == '--outdir':
519 elif o == '--set' or o == '-s':
520 ss = string.split (a, '=')
521 set_setting (extra_init, ss[0], ss[1])
522 elif o == '--dependencies' or o == '-d':
523 track_dependencies_p = 1
524 elif o == '--verbose' or o == '-V':
526 elif o == '--version' or o == '-v':
529 elif o == '--warranty' or o == '-w':
533 # On most platforms, this is equivalent to
534 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
535 def compat_abspath (path):
536 return os.path.normpath (os.path.join (os.getcwd (), path))
538 include_path = map (compat_abspath, include_path)
539 files = map (compat_abspath, files)
540 outdir = compat_abspath (outdir)
543 files = map (lambda x: strip_extension (x, '.ly'), files)
549 dvi_name = do_files (files, extra)
552 ps_name = generate_postscript (dvi_name, extra)
556 base = os.path.basename (files[0])
570 dest = os.path.join (outdir, dest)
571 midi = base + '.midi'
572 midi = os.path.join (outdir, midi)
575 system ('mkdir -p %s' % outdir)
577 #if re.match ('.*[.]dvi', string.join (os.listdir ('.'))):
578 if os.path.isfile (srcname):
579 # huh, and what bout all other (-1, -2) scores?
580 system ('cp \"%s\" \"%s\"' % (srcname, dest))
583 if re.match ('.*[.]midi', string.join (os.listdir ('.'))):
584 system ('cp *.midi %s' % outdir)
588 depfile = os.path.join (outdir, base + '.dep')
590 if track_dependencies_p:
591 generate_dependency_file (depfile, dest)
593 os.chdir (original_dir)
596 # most insteresting info last
597 # don't say silly things
598 if os.path.isfile (depfile):
599 progress (_ ("dependencies output to %s...") % depfile)
600 if dest and os.path.isfile (dest):
601 progress (_ ("%s output to %s...") % (type, dest))
602 if midi and os.path.isfile (midi):
603 progress (_ ("%s output to %s...") % ('MIDI', midi))