2 # run lily, setup LaTeX input.
4 # Note: gettext work best if we use ' for docstrings and "
5 # for gettextable strings
7 ''' TODO: --dependencies
22 sys.path.append ('@datadir@/python')
24 gettext.bindtextdomain ('lilypond', '@localedir@')
25 gettext.textdomain('lilypond')
29 layout_fields = ['title', 'subtitle', 'subsubtitle', 'footer', 'head',
30 'composer', 'arranger', 'instrument', 'opus', 'piece', 'metre',
34 # init to empty; values here take precedence over values in the file
38 'latexpackages' : ['geometry'],
46 extra_fields = extra_init.keys ()
48 fields = layout_fields + extra_fields
49 original_dir = os.getcwd ()
55 track_dependencies_p = 0
60 program_version = '@TOPLEVEL_VERSION@'
61 if program_version == '@' + 'TOPLEVEL_VERSION' + '@':
62 program_version = '1.3.134'
67 option_definitions = [
68 ('', 'h', 'help', _ ("this help")),
69 ('KEY=VAL', 's', 'set', _ ("change global setting KEY to VAL")),
70 ('', 'P', 'postscript', _ ("generate PostScript output")),
71 ('', 'k', 'keep', _ ("keep all output, and name the directory ly2dvi.dir")),
72 ('', '', 'no-lily', _ ("don't run LilyPond")),
73 ('', 'v', 'version', _ ("print version number")),
74 ('', 'w', 'warranty', _ ("show warranty and copyright")),
75 ('DIR', '', 'outdir', _ ("dump all final output into DIR")),
76 ('', 'd', 'dependencies', _ ("write Makefile dependencies for every input file")),
80 sys.stdout.write ('ly2dvi (GNU LilyPond) %s\n' % program_version)
84 sys.stdout.write ('\n')
85 sys.stdout.write (_ ('Copyright (c) %s by' % ' 1998-2001'))
86 sys.stdout.write ('\n')
87 sys.stdout.write (' Han-Wen Nienhuys')
88 sys.stdout.write ('\n')
89 sys.stdout.write (_ (r'''
90 Distributed under terms of the GNU General Public License. It comes with
92 sys.stdout.write ('\n')
97 '''Make the progress messages stand out between lilypond stuff'''
98 # Why should they have to stand out? Blend in would be nice too.
99 sys.stderr.write ('*** ' + s+ '\n')
103 raise _ ("Exiting ... ")
106 def find_file (name):
108 Search the include path for NAME. If found, return the (CONTENTS, PATH) of the file.
113 for a in include_path:
115 nm = os.path.join (a, name)
117 __main__.read_files.append (nm)
122 sys.stderr.write (_ ("Reading `%s'") % nm)
123 sys.stderr.write ('\n');
124 return (f.read (), nm)
126 error (_ ("can't open file: `%s'" % name))
127 sys.stderr.write ('\n');
133 def getopt_args (opts):
134 '''Construct arguments (LONG, SHORT) for getopt from list of options.'''
149 def option_help_str (o):
150 '''Transform one option description (4-tuple ) into neatly formatted string'''
168 return ' ' + sh + sep + long + arg
171 def options_help_str (opts):
172 '''Convert a list of options into a neatly formatted string'''
178 s = option_help_str (o)
179 strs.append ((s, o[3]))
185 str = str + '%s%s%s\n' % (s[0], ' ' * (w - len(s[0]) + 3), s[1])
189 sys.stdout.write (_ ("Usage: %s [OPTION]... FILE") % 'ly2dvi')
190 sys.stdout.write ('\n\n')
191 sys.stdout.write (_ ("Generate .dvi with LaTeX for LilyPond"))
192 sys.stdout.write ('\n\n')
193 sys.stdout.write (_ ("Options:"))
194 sys.stdout.write ('\n')
195 sys.stdout.write (options_help_str (option_definitions))
196 sys.stdout.write ('\n\n')
197 sys.stdout.write (_ ("warning: "))
198 sys.stdout.write (_ ("all output is written in the CURRENT directory"))
199 sys.stdout.write ('\n\n')
200 sys.stdout.write (_ ("Report bugs to %s") % 'bug-gnu-music@gnu.org')
201 sys.stdout.write ('\n')
207 temp_dir = 'ly2dvi.dir'
208 if not keep_temp_dir:
209 temp_dir = tempfile.mktemp ('ly2dvi')
217 # try not to gen/search MF stuff in temp dir
220 fp = ':' + os.environ['TFMFONTS']
225 os.environ['TFMFONTS'] = original_dir + fp
228 progress (_ ('Temp directory is `%s\'\n') % temp_dir)
231 def system (cmd, ignore_error = 0):
232 sys.stderr.write (_ ("Invoking `%s\'") % cmd)
233 sys.stderr.write ('\n')
236 msg = ( _ ("error: ") + _ ("command exited with value %d") % st)
238 sys.stderr.write (msg + ' ' + _ ("(ignored)") + ' ')
245 if not keep_temp_dir:
246 progress (_ ('Cleaning up `%s\'') % temp_dir)
247 system ('rm -rf %s' % temp_dir)
250 def run_lilypond (files):
252 opts = opts + ' ' + string.join (map (lambda x : '-I ' + x, include_path))
253 opts = opts + ' ' + string.join (map (lambda x : '-H ' + x, fields))
255 if track_dependencies_p:
256 opts = opts + " --dependencies "
258 fs = string.join (files)
260 system ('lilypond %s %s ' % (opts, fs))
263 def set_setting (dict, key, val):
265 val = string.atof (val)
270 dict[key].append (val)
275 def analyse_lilypond_output (filename, extra):
276 '''Grep FILENAME for interesting stuff, and
277 put relevant info into EXTRA.'''
278 filename = filename+'.tex'
279 progress (_ ("Analyzing `%s'") % filename)
280 s = open (filename).read ()
282 # search only the first 10k
284 for x in ('textheight', 'linewidth', 'papersizename', 'orientation'):
285 m = re.search (r'\\def\\lilypondpaper%s{([^}]*)}'%x, s)
287 set_setting (extra, x, m.group (1))
289 def find_tex_files_for_base (base, extra):
291 for f in layout_fields:
292 if os.path.exists (base + '.' + f):
293 headerfiles[f] = base+'.'+f
295 if os.path.exists (base +'.dep'):
296 dependency_files.append (base + '.dep')
298 for f in extra_fields:
299 if os.path.exists (base + '.' + f):
300 extra[f].append (open (base + '.' + f).read ())
302 return (base +'.tex',headerfiles)
305 def find_tex_files (files, extra):
310 fname = os.path.basename (f)
311 fname = os.path.splitext (fname)[0]
313 fname = fname + '-%d' % x
315 if os.path.exists (fname + '.tex'):
316 tfiles.append (find_tex_files_for_base (fname, extra))
317 analyse_lilypond_output (fname, extra)
324 def one_latex_definition (defn, first):
326 for (k,v) in defn[1].items ():
327 val = open (v).read ()
328 if (string.strip (val)):
329 s = s + r'''\def\lilypond%s{%s}''' % (k, val)
331 s = s + r'''\let\lilypond%s\relax''' % k
335 s = s + '\\def\\mustmakelilypondtitle{}\n'
337 s = s + '\\def\\mustmakelilypondpiecetitle{}\n'
339 s = s + '\\input %s' % defn[0]
343 ly_paper_to_latexpaper = {
348 def global_latex_definition (tfiles, extra):
349 '''construct preamble from EXTRA,
350 dump lily output files after that, and return result.
355 s = s + '% generation tag\n'
359 if extra['papersizename']:
360 paper = '[%s]' % ly_paper_to_latexpaper[extra['papersizename'][0]]
361 s = s + '\\documentclass%s{article}\n' % paper
363 if extra['language']:
364 s = s + r'\usepackage[%s]{babel}\n' % extra['language'][-1]
367 s = s + '\\usepackage{%s}\n' \
368 % string.join (extra['latexpackages'], ',')
370 s = s + string.join (extra['latexheaders'], ' ')
373 if extra['textheight']:
374 textheight = ',textheight=%fpt' % extra['textheight'][0]
376 orientation = 'portrait'
377 if extra['orientation']:
378 orientation = extra['orientation'][0]
380 s = s + '\geometry{width=%spt%s,headheight=2mm,headsep=0pt,footskip=2mm,%s}\n' % (extra['linewidth'][0], textheight, orientation)
383 \usepackage[latin1]{inputenc}
386 \renewcommand{\@oddfoot}{\parbox{\textwidth}{\mbox{}\thefooter}}%%
388 if extra['pagenumber'] and extra['pagenumber'][-1]:
390 \renewcommand{\@oddhead}{\parbox{\textwidth}%%
391 {\mbox{}\small\theheader\hfill\textbf{\thepage}}}%%'''
393 s = s + '\\pagestyle{empty}'
395 s = s + '\\begin{document}'
399 s = s + one_latex_definition (t, first)
402 s = s + '\\end{document}'
406 def do_files (fs, extra):
408 '''process the list of filenames in FS, using standard settings in EXTRA.
413 wfs = find_tex_files (fs, extra)
414 s = global_latex_definition (wfs, extra)
416 latex_file ='ly2dvi.out'
417 f = open (latex_file + '.tex', 'w')
422 system ('latex %s' % latex_file)
423 return latex_file + '.dvi'
425 def generate_postscript (dvi_name, extra):
426 '''Run dvips on DVI_NAME, optionally doing -t landscape'''
429 if extra['papersizename']:
430 opts = opts + ' -t %s' % extra['papersizename'][0]
432 if extra['orientation'] and extra['orientation'][0] == 'landscape':
433 opts = opts + ' -t landscape'
435 ps_name = re.sub (r'\.dvi', r'.ps', dvi_name)
436 system ('dvips %s -o %s %s' % (opts, ps_name, dvi_name))
442 def generate_dependency_file (depfile, outname):
443 df = open (depfile, 'w')
444 df.write (outname + ':' )
446 for d in dependency_files:
448 s = re.sub ('#[^\n]*\n', '', s)
449 s = re.sub (r'\\\n', ' ', s)
450 m = re.search ('.*:(.*)\n', s)
452 # ugh. Different targets?
454 df.write ( m.group (1) + ' ' )
459 (sh, long) = getopt_args (__main__.option_definitions)
461 (options, files) = getopt.getopt(sys.argv[1:], sh, long)
472 elif o == '--help' or o == '-h':
474 elif o == '--include' or o == '-I':
475 include_path.append (a)
476 elif o == '--postscript' or o == '-P':
478 elif o == '--keep' or o == '-k':
480 elif o == '--no-lily':
482 elif o == '--outdir':
484 elif o == '--set' or o == '-s':
485 ss = string.split (a, '=')
486 set_setting (extra_init, ss[0], ss[1])
487 elif o == '--dependencies' or o == '-d':
488 track_dependencies_p = 1
489 elif o == '--version' or o == '-v':
492 elif o == '--warranty' or o == '-w':
497 include_path = map (os.path.abspath, include_path)
498 files = map (os.path.abspath, files)
499 outdir = os.path.abspath (outdir)
501 def strip_ly_suffix (f):
502 (p, e) =os.path.splitext (f)
507 files = map (strip_ly_suffix, files)
513 dvi_name = do_files (files, extra)
516 ps_name = generate_postscript (dvi_name, extra)
520 base = os.path.basename (files[0])
534 dest = os.path.join (outdir, dest)
535 system ('cp \"%s\" \"%s\"' % (srcname, dest ))
536 system ('cp *.midi %s' % outdir, ignore_error = 1)
538 depfile = os.path.join (outdir, base + '.dep')
540 if track_dependencies_p:
541 generate_dependency_file (depfile, dest)
545 # most insteresting info last
546 progress (_ ("dependencies output to %s...") % depfile)
547 progress (_ ("%s file left in `%s'") % (type, dest))