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.
24 * windows compatibility: rm -rf, cp file... dir
39 sys.path.append ('@datadir@/python')
41 gettext.bindtextdomain ('lilypond', '@localedir@')
42 gettext.textdomain('lilypond')
46 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
47 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
51 # init to empty; values here take precedence over values in the file
55 'latexpackages' : ['geometry'],
63 extra_fields = extra_init.keys ()
65 fields = layout_fields + extra_fields
66 program_name = 'ly2dvi'
67 help_summary = _("Generate .dvi with LaTeX for LilyPond")
72 track_dependencies_p = 0
82 # lily_py.py -- options and stuff
84 # source file of the GNU LilyPond music typesetter
86 # BEGIN Library for these?
87 # cut-n-paste from ly2dvi
89 program_version = '@TOPLEVEL_VERSION@'
90 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
91 program_version = '1.3.142'
94 original_dir = os.getcwd ()
95 temp_dir = '%s.dir' % program_name
100 sys.stdout.write ('%s (GNU LilyPond) %s\n' % (program_name, program_version))
104 sys.stdout.write ('\n')
105 sys.stdout.write (_ ('Copyright (c) %s by' % ' 2001'))
106 sys.stdout.write ('\n')
107 sys.stdout.write (' Han-Wen Nienhuys')
108 sys.stdout.write (' Jan Nieuwenhuizen')
109 sys.stdout.write ('\n')
110 sys.stdout.write (_ (r'''
111 Distributed under terms of the GNU General Public License. It comes with
113 sys.stdout.write ('\n')
116 sys.stderr.write (s + '\n')
119 sys.stderr.write (_ ("warning: ") + s)
120 sys.stderr.write ('\n')
124 sys.stderr.write (_ ("error: ") + s)
125 sys.stderr.write ('\n')
126 raise _ ("Exiting ... ")
128 def getopt_args (opts):
129 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
144 def option_help_str (o):
145 '''Transform one option description (4-tuple ) into neatly formatted string'''
163 return ' ' + sh + sep + long + arg
166 def options_help_str (opts):
167 '''Convert a list of options into a neatly formatted string'''
173 s = option_help_str (o)
174 strs.append ((s, o[3]))
180 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
184 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % program_name)
185 sys.stdout.write ('\n\n')
186 sys.stdout.write (help_summary)
187 sys.stdout.write ('\n\n')
188 sys.stdout.write (_ ("Options:"))
189 sys.stdout.write ('\n')
190 sys.stdout.write (options_help_str (option_definitions))
191 sys.stdout.write ('\n\n')
192 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
193 sys.stdout.write ('\n')
199 if not keep_temp_dir_p:
200 temp_dir = tempfile.mktemp (program_name)
202 os.mkdir (temp_dir, 0777)
208 def system (cmd, ignore_error = 0):
210 progress (_ ("Invoking `%s\'") % cmd)
213 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
215 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
223 if not keep_temp_dir_p:
225 progress (_ ('Cleaning up `%s\'') % temp_dir)
226 system ('rm -rf %s' % temp_dir)
229 def set_setting (dict, key, val):
231 val = string.atof (val)
233 #warning (_ ("invalid value: %s") % `val`)
237 dict[key].append (val)
239 warning (_ ("no such setting: %s") % `key`)
242 def strip_extension (f, ext):
243 (p, e) = os.path.splitext (f)
250 option_definitions = [
251 ('', 'h', 'help', _ ("this help")),
252 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
253 ('DIR', 'I', 'include', _ ("add DIR to LilyPond\'s search path")),
254 ('', 'P', 'postscript', _ ("generate PostScript output")),
255 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
256 ('', '', 'no-lily', _ ("don't run LilyPond")),
257 ('', 'V', 'verbose', _ ("verbose")),
258 ('', 'v', 'version', _ ("print version number")),
259 ('', 'w', 'warranty', _ ("show warranty and copyright")),
260 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
261 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
264 def run_lilypond (files):
266 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
267 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
269 if track_dependencies_p:
270 opts = opts + " --dependencies "
272 fs = string.join (files)
274 system ('lilypond %s %s ' % (opts, fs))
276 def analyse_lilypond_output (filename, extra):
277 '''Grep FILENAME for interesting stuff, and
278 put relevant info into EXTRA.'''
279 filename = filename+'.tex'
280 progress (_ ("Analyzing `%s'") % filename)
281 s = open (filename).read ()
283 # search only the first 10k
285 for x in ('textheight', 'linewidth', 'papersize', 'orientation'):
286 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
288 set_setting (extra, x, m.group (1))
290 def find_tex_files_for_base (base, extra):
292 for f in layout_fields:
293 if os.path.exists (base + '.' + f):
294 headerfiles[f] = base+'.'+f
296 if os.path.exists (base +'.dep'):
297 dependency_files.append (base + '.dep')
299 for f in extra_fields:
300 if os.path.exists (base + '.' + f):
301 extra[f].append (open (base + '.' + f).read ())
303 return (base +'.tex',headerfiles)
306 def find_tex_files (files, extra):
311 fname = os.path.basename (f)
312 fname = strip_extension (fname, '.ly')
314 fname = fname + '-%d' % x
316 if os.path.exists (fname + '.tex'):
317 tfiles.append (find_tex_files_for_base (fname, extra))
318 analyse_lilypond_output (fname, extra)
324 warning (_ ("no lilypond output found for %s") % `files`)
327 def one_latex_definition (defn, first):
329 for (k,v) in defn[1].items ():
330 val = open (v).read ()
331 if (string.strip (val)):
332 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
334 s = s + r'''\let\lilypond%s\relax''' % k
338 s = s + '\\def\\mustmakelilypondtitle{}\n'
340 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
342 s = s + '\\input %s' % defn[0]
346 ly_paper_to_latexpaper = {
348 'letter' : 'letterpaper',
351 def global_latex_definition (tfiles, extra):
352 '''construct preamble from EXTRA,
353 dump lily output files after that, and return result.
358 s = s + '% generation tag\n'
362 if extra['papersize']:
364 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersize'][0]]
366 warning (_ ("invalid value: %s") % `extra['papersize'][0]`)
369 s = s + '\\documentclass%s{article}\n' % paper
371 if extra['language']:
372 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
375 s = s + '\\usepackage{%s}\n' \
376 % string.join (extra['latexpackages'], ',')
378 if extra['latexheaders']:
379 s = s + '\\include{%s}\n' \
380 % string.join (extra['latexheaders'], '}\n\\include{')
383 if extra['textheight']:
384 textheight = ',textheight=%fpt' % extra['textheight'][0]
386 orientation = 'portrait'
387 if extra['orientation']:
388 orientation = extra['orientation'][0]
390 # set sane geometry width (a4-width) for linewidth = -1.
391 linewidth = extra['linewidth'][0]
394 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (linewidth, textheight, orientation)
397 \usepackage[latin1]{inputenc}
400 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%
403 if extra['pagenumber'] and extra['pagenumber'][-1] and extra['pagenumber'][-1] != 'no':
405 \renewcommand{\@oddhead}{\parbox{\textwidth}%
406 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}
409 s = s + '\\pagestyle{empty}\n'
411 s = s + '\\makeatother\n'
412 s = s + '\\begin{document}\n'
417 s = s + one_latex_definition (t, first)
422 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\lilypondtagline}}%
425 s = s + '\\end{document}'
429 def do_files (fs, extra):
431 '''process the list of filenames in FS, using standard settings in EXTRA.
436 wfs = find_tex_files (fs, extra)
437 s = global_latex_definition (wfs, extra)
439 latex_file ='ly2dvi.out'
440 f = open (latex_file + '.tex', 'w')
445 system ('latex \\\\nonstopmode \\\\input %s' % latex_file)
446 return latex_file + '.dvi'
448 def generate_postscript (dvi_name, extra):
449 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
452 if extra['papersize']:
453 opts = opts + ' -t %s' % extra['papersize'][0]
455 if extra['orientation'] and extra['orientation'][0] == 'landscape':
456 opts = opts + ' -t landscape'
458 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
459 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
465 def generate_dependency_file (depfile, outname):
466 df = open (depfile, 'w')
467 df.write (outname + ':' )
469 for d in dependency_files:
471 s = re.sub ('#[^\n]*\n', '', s)
472 s = re.sub (r'\\\n', ' ', s)
473 m = re.search ('.*:(.*)\n', s)
475 # ugh. Different targets?
477 df.write ( m.group (1) + ' ' )
482 (sh, long) = getopt_args (__main__.option_definitions)
484 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
495 elif o == '--help' or o == '-h':
497 elif o == '--include' or o == '-I':
498 include_path.append (a)
499 elif o == '--postscript' or o == '-P':
501 elif o == '--keep' or o == '-k':
503 elif o == '--no-lily':
505 elif o == '--outdir':
507 elif o == '--set' or o == '-s':
508 ss = string.split (a, '=')
509 set_setting (extra_init, ss[0], ss[1])
510 elif o == '--dependencies' or o == '-d':
511 track_dependencies_p = 1
512 elif o == '--verbose' or o == '-V':
514 elif o == '--version' or o == '-v':
517 elif o == '--warranty' or o == '-w':
521 # On most platforms, this is equivalent to
522 #`normpath(join(os.getcwd()), PATH)'. *Added in Python version 1.5.2*
523 def compat_abspath (path):
524 return os.path.normpath (os.path.join (os.getcwd (), path))
526 include_path = map (compat_abspath, include_path)
527 files = map (compat_abspath, files)
528 outdir = compat_abspath (outdir)
531 files = map (lambda x: strip_extension (x, '.ly'), files)
537 dvi_name = do_files (files, extra)
540 ps_name = generate_postscript (dvi_name, extra)
544 base = os.path.basename (files[0])
558 dest = os.path.join (outdir, dest)
560 system ('mkdir -p %s' % outdir)
561 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
562 if re.match ('[.]midi', string.join (os.listdir ('.'))):
563 system ('cp *.midi %s' % outdir, ignore_error = 1)
565 depfile = os.path.join (outdir, base + '.dep')
567 if track_dependencies_p:
568 generate_dependency_file (depfile, dest)
570 os.chdir (original_dir)
573 # most insteresting info last
574 progress (_ ("dependencies output to %s...") % depfile)
575 progress (_ ("%s output to %s...") % (type, dest))