2 # run lily, setup LaTeX input.
4 # Note: gettext work best if we use ' for docstrings and "
5 # for gettextable strings
7 ''' TODO: --dependencies
23 gettext.bindtextdomain ('lilypond', '@localedir@')
24 gettext.textdomain('lilypond')
28 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
29 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
33 # init to empty; values here take precedence over values in the file
37 'latexpackages' : ['geometry'],
45 extra_fields = extra_init.keys ()
47 fields = layout_fields + extra_fields
48 original_dir = os.getcwd ()
54 track_dependencies_p = 0
59 program_version = '@TOPLEVEL_VERSION@'
60 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
61 program_version = '1.3.134'
66 option_definitions = [
67 ('', 'h', 'help', _ ("this help")),
68 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
69 ('', 'P', 'postscript', _ ("generate PostScript output")),
70 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
71 ('', '', 'no-lily', _ ("don't run LilyPond")),
72 ('', 'v', 'version', _ ("print version number")),
73 ('', 'w', 'warranty', _ ("show warranty and copyright")),
74 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
75 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
79 sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
83 sys.stdout.write ('\n')
84 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
85 sys.stdout.write ('\n')
86 sys.stdout.write (' Han-Wen Nienhuys')
87 sys.stdout.write ('\n')
88 sys.stdout.write (_ (r'''
89 Distributed under terms of the GNU General Public License. It comes with
91 sys.stdout.write ('\n')
96 '''Make the progress messages stand out between lilypond stuff'''
97 # Why should they have to stand out? Blend in would be nice too.
98 sys.stderr.write ('*** ' + s+ '\n')
102 raise _ ("Exiting ... ")
105 def find_file (name):
107 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
112 for a in include_path:
114 nm = os.path.join (a, name)
116 __main__.read_files.append (nm)
121 sys.stderr.write (_ ("Reading `%s'") % nm)
122 sys.stderr.write ('\n');
123 return (f.read (), nm)
125 error (_ ("can't open file: `%s'" % name))
126 sys.stderr.write ('\n');
132 def getopt_args (opts):
133 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
148 def option_help_str (o):
149 '''Transform one option description (4-tuple ) into neatly formatted string'''
167 return ' ' + sh + sep + long + arg
170 def options_help_str (opts):
171 '''Convert a list of options into a neatly formatted string'''
177 s = option_help_str (o)
178 strs.append ((s, o[3]))
184 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
188 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
189 sys.stdout.write ('\n\n')
190 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
191 sys.stdout.write ('\n\n')
192 sys.stdout.write (_ ("Options:"))
193 sys.stdout.write ('\n')
194 sys.stdout.write (options_help_str (option_definitions))
195 sys.stdout.write ('\n\n')
196 sys.stdout.write (_ ("warning: "))
197 sys.stdout.write (_ ("all output is written in the CURRENT directory"))
198 sys.stdout.write ('\n\n')
199 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
200 sys.stdout.write ('\n')
206 temp_dir = 'ly2dvi.dir'
207 if not keep_temp_dir:
208 temp_dir = tempfile.mktemp ('ly2dvi')
216 # try not to gen/search MF stuff in temp dir
219 fp = ':' + os.environ['TFMFONTS']
224 os.environ['TFMFONTS'] = original_dir + fp
227 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
230 def system (cmd, ignore_error = 0):
231 sys.stderr.write (_ ("Invoking `%s\'") % cmd)
232 sys.stderr.write ('\n')
235 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
237 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
244 if not keep_temp_dir:
245 progress (_ ('Cleaning up `%s\'') % temp_dir)
246 system ('rm -rf %s' % temp_dir)
249 def run_lilypond (files):
251 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
252 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
254 if track_dependencies_p:
255 opts = opts + " --dependencies "
257 fs = string.join (files)
259 system ('lilypond %s %s ' % (opts, fs))
262 def set_setting (dict, key, val):
264 val = string.atof (val)
269 dict[key].append (val)
274 def analyse_lilypond_output (filename, extra):
275 '''Grep FILENAME for interesting stuff, and
276 put relevant info into EXTRA.'''
277 filename = filename+'.tex'
278 progress (_ ("Analyzing `%s'") % filename)
279 s = open (filename).read ()
281 # search only the first 10k
283 for x in ('textheight', 'linewidth', 'papersizename', 'orientation'):
284 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
286 set_setting (extra, x, m.group (1))
288 def find_tex_files_for_base (base, extra):
290 for f in layout_fields:
291 if os.path.exists (base + '.' + f):
292 headerfiles[f] = base+'.'+f
294 if os.path.exists (base +'.dep'):
295 dependency_files.append (base + '.dep')
297 for f in extra_fields:
298 if os.path.exists (base + '.' + f):
299 extra[f].append (open (base + '.' + f).read ())
301 return (base +'.tex',headerfiles)
304 def find_tex_files (files, extra):
309 fname = os.path.basename (f)
310 fname = os.path.splitext (fname)[0]
312 fname = fname + '-%d' % x
314 if os.path.exists (fname + '.tex'):
315 tfiles.append (find_tex_files_for_base (fname, extra))
316 analyse_lilypond_output (fname, extra)
323 def one_latex_definition (defn, first):
325 for (k,v) in defn[1].items ():
326 s = r'''\def\the%s{%s}''' % (k,open (v).read ())
329 s = s + '\\def\\mustmakelilypondtitle{}\n'
331 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
333 s = s + '\\input %s' % defn[0]
337 ly_paper_to_latexpaper = {
342 def global_latex_definition (tfiles, extra):
343 '''construct preamble from EXTRA,
344 dump lily output files after that, and return result.
349 s = s + '% generation tag\n'
353 if extra['papersizename']:
354 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersizename'][0]]
355 s = s + '\\documentclass%s{article}\n' % paper
357 if extra['language']:
358 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
361 s = s + '\\usepackage{%s}\n' \
362 % string.join (extra['latexpackages'], ',')
364 s = s + string.join (extra['latexheaders'], ' ')
367 if extra['textheight']:
368 textheight = ',textheight=%fpt' % extra['textheight'][0]
370 orientation = 'portrait'
371 if extra['orientation']:
372 orientation = extra['orientation'][0]
374 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (extra['linewidth'][0], textheight, orientation)
377 \usepackage[latin1]{inputenc}
380 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
382 if extra['pagenumber'] and extra['pagenumber'][-1]:
384 \renewcommand{\@oddhead}{\parbox{\textwidth}%%
385 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%'''
387 s = s + '\\pagestyle{empty}'
389 s = s + '\\begin{document}'
393 s = s + one_latex_definition (t, first)
396 s = s + '\\end{document}'
400 def do_files (fs, extra):
402 '''process the list of filenames in FS, using standard settings in EXTRA.
407 wfs = find_tex_files (fs, extra)
408 s = global_latex_definition (wfs, extra)
410 latex_file ='ly2dvi.out'
411 f = open (latex_file + '.tex', 'w')
416 system ('latex %s' % latex_file)
417 return latex_file + '.dvi'
419 def generate_postscript (dvi_name, extra):
420 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
423 if extra['papersizename']:
424 opts = opts + ' -t %s' % extra['papersizename'][0]
426 if extra['orientation'] and extra['orientation'][0] == 'landscape':
427 opts = opts + ' -t landscape'
429 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
430 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
436 def generate_dependency_file (depfile, outname):
437 df = open (depfile, 'w')
438 df.write (outname + ':' )
440 for d in dependency_files:
442 s = re.sub ('#[^\n]*\n', '', s)
443 s = re.sub (r'\\\n', ' ', s)
444 m = re.search ('.*:(.*)\n', s)
446 # ugh. Different targets?
448 df.write ( m.group (1) + ' ' )
453 (sh, long) = getopt_args (__main__.option_definitions)
455 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
466 elif o == '--help' or o == '-h':
468 elif o == '--include' or o == '-I':
469 include_path.append (a)
470 elif o == '--postscript' or o == '-P':
472 elif o == '--keep' or o == '-k':
474 elif o == '--no-lily':
476 elif o == '--outdir':
478 elif o == '--set' or o == '-s':
479 ss = string.split (a, '=')
480 set_setting (extra_init, ss[0], ss[1])
481 elif o == '--dependencies' or o == '-d':
482 track_dependencies_p = 1
483 elif o == '--version' or o == '-v':
486 elif o == '--warranty' or o == '-w':
491 include_path = map (os.path.abspath, include_path)
492 files = map (os.path.abspath, files)
493 outdir = os.path.abspath (outdir)
495 def strip_ly_suffix (f):
496 (p, e) =os.path.splitext (f)
501 files = map (strip_ly_suffix, files)
507 dvi_name = do_files (files, extra)
510 ps_name = generate_postscript (dvi_name, extra)
514 base = os.path.basename (files[0])
528 dest = os.path.join (outdir, dest)
529 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
530 system ('cp *.midi %s' % outdir, ignore_error = 1)
532 depfile = os.path.join (outdir, base + '.dep')
534 if track_dependencies_p:
535 generate_dependency_file (depfile, dest)
539 # most insteresting info last
540 progress (_ ("dependencies output to %s...") % depfile)
541 progress (_ ("%s file left in `%s'") % (type, dest))