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 program_name = 'ly2dvi'
65 help_summary = _("Generate .dvi with LaTeX for LilyPond")
70 track_dependencies_p = 0
80 # lily_py.py -- options and stuff
82 # source file of the GNU LilyPond music typesetter
84 # BEGIN Library for these?
85 # cut-n-paste from ly2dvi
87 program_version = '@TOPLEVEL_VERSION@'
88 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
89 program_version = '1.3.142'
92 original_dir = os.getcwd ()
93 temp_dir = '%s.dir' % program_name
98 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
102 sys.stdout.write ('\n')
103 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
104 sys.stdout.write ('\n')
105 sys.stdout.write (' Han-Wen Nienhuys')
106 sys.stdout.write (' Jan Nieuwenhuizen')
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')
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 ... ")
126 def getopt_args (opts):
127 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
142 def option_help_str (o):
143 '''Transform one option description (4-tuple ) into neatly formatted string'''
161 return ' ' + sh + sep + long + arg
164 def options_help_str (opts):
165 '''Convert a list of options into a neatly formatted string'''
171 s = option_help_str (o)
172 strs.append ((s, o[3]))
178 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
182 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % program_name)
183 sys.stdout.write ('\n\n')
184 sys.stdout.write (help_summary)
185 sys.stdout.write ('\n\n')
186 sys.stdout.write (_ ("Options:"))
187 sys.stdout.write ('\n')
188 sys.stdout.write (options_help_str (option_definitions))
189 sys.stdout.write ('\n\n')
190 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
191 sys.stdout.write ('\n')
197 if not keep_temp_dir_p:
198 temp_dir = tempfile.mktemp (program_name)
200 os.mkdir (temp_dir, 0777)
205 def system (cmd, ignore_error = 0):
207 progress (_ ("Invoking `%s\'") % cmd)
210 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
212 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
220 if not keep_temp_dir_p:
222 progress (_ ('Cleaning up `%s\'') % temp_dir)
223 system ('rm -rf %s' % temp_dir)
226 def set_setting (dict, key, val):
228 val = string.atof (val)
230 #warning (_ ("invalid value: %s") % `val`)
234 dict[key].append (val)
236 warning (_ ("no such setting: %s") % `key`)
241 option_definitions = [
242 ('', 'h', 'help', _ ("this help")),
243 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
244 ('', 'P', 'postscript', _ ("generate PostScript output")),
245 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
246 ('', '', 'no-lily', _ ("don't run LilyPond")),
247 ('', 'V', 'verbose', _ ("verbose")),
248 ('', 'v', 'version', _ ("print version number")),
249 ('', 'w', 'warranty', _ ("show warranty and copyright")),
250 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
251 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
254 def run_lilypond (files):
256 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
257 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
259 if track_dependencies_p:
260 opts = opts + " --dependencies "
262 fs = string.join (files)
264 system ('lilypond %s %s ' % (opts, fs))
266 def analyse_lilypond_output (filename, extra):
267 '''Grep FILENAME for interesting stuff, and
268 put relevant info into EXTRA.'''
269 filename = filename+'.tex'
270 progress (_ ("Analyzing `%s'") % filename)
271 s = open (filename).read ()
273 # search only the first 10k
275 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
276 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
278 set_setting (extra, x, m.group (1))
280 def find_tex_files_for_base (base, extra):
282 for f in layout_fields:
283 if os.path.exists (base + '.' + f):
284 headerfiles[f] = base+'.'+f
286 if os.path.exists (base +'.dep'):
287 dependency_files.append (base + '.dep')
289 for f in extra_fields:
290 if os.path.exists (base + '.' + f):
291 extra[f].append (open (base + '.' + f).read ())
293 return (base +'.tex',headerfiles)
296 def find_tex_files (files, extra):
301 fname = os.path.basename (f)
302 fname = strip_ly_suffix (fname)
304 fname = fname + '-%d' % x
306 if os.path.exists (fname + '.tex'):
307 tfiles.append (find_tex_files_for_base (fname, extra))
308 analyse_lilypond_output (fname, extra)
314 warning (_ ("no lilypond output found for %s") % `files`)
317 def one_latex_definition (defn, first):
319 for (k,v) in defn[1].items ():
320 val = open (v).read ()
321 if (string.strip (val)):
322 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
324 s = s + r'''\let\lilypond%s\relax''' % k
328 s = s + '\\def\\mustmakelilypondtitle{}\n'
330 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
332 s = s + '\\input %s' % defn[0]
336 ly_paper_to_latexpaper = {
338 'letter' : 'letterpaper',
341 def global_latex_definition (tfiles, extra):
342 '''construct preamble from EXTRA,
343 dump lily output files after that, and return result.
348 s = s + '% generation tag\n'
352 if extra['papersize']:
354 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
356 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
359 s = s + '\\documentclass%s{article}\n' % paper
361 if extra['language']:
362 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
365 s = s + '\\usepackage{%s}\n' \
366 % string.join (extra['latexpackages'], ',')
368 s = s + string.join (extra['latexheaders'], ' ')
371 if extra['textheight']:
372 textheight = ',textheight=%fpt' % extra['textheight'][0]
374 orientation = 'portrait'
375 if extra['orientation']:
376 orientation = extra['orientation'][0]
378 # set sane geometry width (a4-width) for linewidth = -1.
379 linewidth = extra['linewidth'][0]
382 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
385 \usepackage[latin1]{inputenc}
388 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
391 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
393 \renewcommand{\@oddhead}{\parbox{\textwidth}%
394 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
397 s = s + '\\pagestyle{empty}\n'
399 s = s + '\\makeatother\n'
400 s = s + '\\begin{document}\n'
405 s = s + one_latex_definition (t, first)
410 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
413 s = s + '\\end{document}'
417 def do_files (fs, extra):
419 '''process the list of filenames in FS, using standard settings in EXTRA.
424 wfs = find_tex_files (fs, extra)
425 s = global_latex_definition (wfs, extra)
427 latex_file ='ly2dvi.out'
428 f = open (latex_file + '.tex', 'w')
433 system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
434 return latex_file + '.dvi'
436 def generate_postscript (dvi_name, extra):
437 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
440 if extra['papersize']:
441 opts = opts + ' -t %s' % extra['papersize'][0]
443 if extra['orientation'] and extra['orientation'][0] == 'landscape':
444 opts = opts + ' -t landscape'
446 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
447 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
453 def generate_dependency_file (depfile, outname):
454 df = open (depfile, 'w')
455 df.write (outname + ':' )
457 for d in dependency_files:
459 s = re.sub ('#[^\n]*\n', '', s)
460 s = re.sub (r'\\\n', ' ', s)
461 m = re.search ('.*:(.*)\n', s)
463 # ugh. Different targets?
465 df.write ( m.group (1) + ' ' )
470 (sh, long) = getopt_args (__main__.option_definitions)
472 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
483 elif o == '--help' or o == '-h':
485 elif o == '--include' or o == '-I':
486 include_path.append (a)
487 elif o == '--postscript' or o == '-P':
489 elif o == '--keep' or o == '-k':
491 elif o == '--no-lily':
493 elif o == '--outdir':
495 elif o == '--set' or o == '-s':
496 ss = string.split (a, '=')
497 set_setting (extra_init, ss[0], ss[1])
498 elif o == '--dependencies' or o == '-d':
499 track_dependencies_p = 1
500 elif o == '--verbose' or o == '-V':
502 elif o == '--version' or o == '-v':
505 elif o == '--warranty' or o == '-w':
510 include_path = map (os.path.abspath, include_path)
511 files = map (os.path.abspath, files)
512 outdir = os.path.abspath (outdir)
514 def strip_ly_suffix (f):
515 (p, e) =os.path.splitext (f)
520 files = map (strip_ly_suffix, files)
526 dvi_name = do_files (files, extra)
529 ps_name = generate_postscript (dvi_name, extra)
533 base = os.path.basename (files[0])
547 dest = os.path.join (outdir, dest)
549 system ('mkdir -p %s' % outdir)
550 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
551 if re.match ('[.]midi', string.join (os.listdir ('.'))):
552 system ('cp *.midi %s' % outdir, ignore_error = 1)
554 depfile = os.path.join (outdir, base + '.dep')
556 if track_dependencies_p:
557 generate_dependency_file (depfile, dest)
559 os.chdir (original_dir)
562 # most insteresting info last
563 progress (_ ("dependencies output to %s...") % depfile)
564 progress (_ ("%s output to %s...") % (type, dest))