blob: fccafe9c8f859460e6fc588cab14dce8fca725da [file] [log] [blame]
Fred Drake8b880931999-03-03 20:24:30 +00001#! /usr/bin/env python
2# -*- Python -*-
3"""usage: %(program)s [options...] file ...
4
5Options specifying formats to build:
6 --html HyperText Markup Language
7 --pdf Portable Document Format (default)
8 --ps PostScript
9 --dvi 'DeVice Indepentent' format from TeX
10 --text ASCII text (requires lynx)
11
12 More than one output format may be specified, or --all.
13
14HTML options:
15 --address, -a Specify an address for page footers.
16 --link Specify the number of levels to include on each page.
17 --split, -s Specify a section level for page splitting, default: %(max_split_depth)s.
18 --iconserver, -i Specify location of icons (default: ../).
Fred Drake52ea0ce1999-09-22 19:55:35 +000019 --image-type Specify the image type to use in HTML output;
20 values: gif (default), png.
Fred Drake8b880931999-03-03 20:24:30 +000021
22Other options:
23 --a4 Format for A4 paper.
24 --letter Format for US letter paper (the default).
25 --help, -H Show this text.
26 --logging, -l Log stdout and stderr to a file (*.how).
27 --debugging, -D Echo commands as they are executed.
28 --keep, -k Keep temporary files around.
29 --quiet, -q Do not print command output to stdout.
30 (stderr is also lost, sorry; see *.how for errors)
31"""
32
33import getopt
34import glob
35import os
Fred Drakea871c2e1999-05-06 19:37:38 +000036import re
Fred Drake8b880931999-03-03 20:24:30 +000037import shutil
38import string
39import sys
40import tempfile
41
42
43MYDIR = os.path.normpath(os.path.join(os.getcwd(), sys.path[0]))
44TOPDIR = os.path.normpath(os.path.join(MYDIR, os.pardir))
45
46ISTFILE = os.path.join(TOPDIR, "texinputs", "python.ist")
47NODE2LABEL_SCRIPT = os.path.join(MYDIR, "node2label.pl")
48L2H_INIT_FILE = os.path.join(TOPDIR, "perl", "l2hinit.perl")
49
50BIBTEX_BINARY = "bibtex"
51DVIPS_BINARY = "dvips"
52LATEX_BINARY = "latex"
53LATEX2HTML_BINARY = "latex2html"
54LYNX_BINARY = "lynx"
55MAKEINDEX_BINARY = "makeindex"
56PDFLATEX_BINARY = "pdflatex"
57PERL_BINARY = "perl"
58PYTHON_BINARY = "python"
59
60
61def usage(options):
62 print __doc__ % options
63
64def error(options, message, err=2):
65 sys.stdout = sys.stderr
66 print message
67 print
68 usage(options)
69 sys.exit(2)
70
71
72class Options:
73 program = os.path.basename(sys.argv[0])
74 #
75 address = ''
76 debugging = 0
77 discard_temps = 1
78 have_temps = 0
79 icon_server = None
Fred Drake52ea0ce1999-09-22 19:55:35 +000080 image_type = "gif"
Fred Drake8b880931999-03-03 20:24:30 +000081 logging = 0
82 max_link_depth = 3
83 max_split_depth = 6
84 paper = "letter"
85 quiet = 0
Fred Drake52ea0ce1999-09-22 19:55:35 +000086 runs = 0
Fred Drake8b880931999-03-03 20:24:30 +000087 style_file = os.path.join(TOPDIR, "html", "style.css")
88 #
89 DEFAULT_FORMATS = ("pdf",)
90 ALL_FORMATS = ("dvi", "html", "pdf", "ps", "text")
91
92 def __init__(self):
93 self.config_files = []
94 self.formats = []
95
96 def __getitem__(self, key):
97 # This is used when formatting the usage message.
98 try:
99 return getattr(self, key)
100 except AttributeError:
101 raise KeyError, key
102
103 def parse(self, args):
Fred Drake52ea0ce1999-09-22 19:55:35 +0000104 opts, args = getopt.getopt(args, "Hi:a:s:lDkqr:",
Fred Drake8b880931999-03-03 20:24:30 +0000105 ["all", "postscript", "help", "iconserver=",
106 "address=", "a4", "l2h-config=", "letter",
107 "link=", "split=", "logging", "debugging",
Fred Drake52ea0ce1999-09-22 19:55:35 +0000108 "keep", "quiet", "runs=", "image-type="]
109 + list(self.ALL_FORMATS))
Fred Drake8b880931999-03-03 20:24:30 +0000110 for opt, arg in opts:
111 if opt == "--all":
112 self.formats = list(self.ALL_FORMATS)
113 elif opt in ("-H", "--help"):
114 usage(self)
115 sys.exit()
116 elif opt == "--iconserver":
117 self.icon_server = arg
118 elif opt in ("-a", "--address"):
119 self.address = arg
120 elif opt == "--a4":
121 self.paper = "a4"
122 elif opt == "--letter":
123 self.paper = "letter"
124 elif opt == "--l2h-config":
125 self.config_files.append(arg)
126 elif opt == "--link":
127 self.max_link_depth = int(arg)
128 elif opt in ("-s", "--split"):
129 self.max_split_depth = int(arg)
130 elif opt in ("-l", "--logging"):
131 self.logging = self.logging + 1
132 elif opt in ("-D", "--debugging"):
133 self.debugging = self.debugging + 1
134 elif opt in ("-k", "--keep"):
135 self.discard_temps = 0
136 elif opt in ("-q", "--quiet"):
137 self.quiet = 1
Fred Drake52ea0ce1999-09-22 19:55:35 +0000138 elif opt in ("-r", "--runs"):
139 self.runs = int(arg)
140 elif opt == "--image-type":
141 self.image_type = arg
Fred Drake8b880931999-03-03 20:24:30 +0000142 #
143 # Format specifiers:
144 #
145 elif opt[2:] in self.ALL_FORMATS:
146 self.add_format(opt[2:])
147 elif opt == "--postscript":
148 # synonym for --ps
149 self.add_format("ps")
150 self.initialize()
151 #
152 # return the args to allow the caller access:
153 #
154 return args
155
156 def add_format(self, format):
157 """Add a format to the formats list if not present."""
158 if not format in self.formats:
159 self.formats.append(format)
160
161 def initialize(self):
162 """Complete initialization. This is needed if parse() isn't used."""
163 # add the default format if no formats were specified:
164 if not self.formats:
165 self.formats = self.DEFAULT_FORMATS
166 # determine the base set of texinputs directories:
167 texinputs = string.split(os.environ.get("TEXINPUTS", ""), os.pathsep)
168 if not texinputs:
169 texinputs = ['']
170 self.base_texinputs = [
171 os.path.join(TOPDIR, "paper-" + self.paper),
172 os.path.join(TOPDIR, "texinputs"),
173 ] + texinputs
174
175
176class Job:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000177 latex_runs = 0
178
Fred Drake8b880931999-03-03 20:24:30 +0000179 def __init__(self, options, path):
180 self.options = options
Fred Drakea871c2e1999-05-06 19:37:38 +0000181 self.doctype = get_doctype(path)
Fred Drake8b880931999-03-03 20:24:30 +0000182 self.filedir, self.doc = split_pathname(path)
183 self.log_filename = self.doc + ".how"
184 if os.path.exists(self.log_filename):
185 os.unlink(self.log_filename)
186 if os.path.exists(self.doc + ".l2h"):
187 self.l2h_aux_init_file = tempfile.mktemp()
188 else:
189 self.l2h_aux_init_file = self.doc + ".l2h"
190 self.write_l2h_aux_init_file()
191
192 def build(self):
193 self.setup_texinputs()
194 formats = self.options.formats
195 if "dvi" in formats or "ps" in formats:
196 self.build_dvi()
197 if "pdf" in formats:
198 self.build_pdf()
199 if "ps" in formats:
200 self.build_ps()
201 if "html" in formats:
202 self.require_temps()
203 self.build_html(self.doc)
204 if self.options.icon_server == ".":
Fred Drake52ea0ce1999-09-22 19:55:35 +0000205 pattern = os.path.join(TOPDIR, "html", "icons",
206 "*." + self.options.image_type)
207 imgs = glob.glob(pattern)
208 if not imgs:
209 self.warning(
210 "Could not locate support images of type %s."
211 % `self.options.image_type`)
212 for fn in imgs:
Fred Drake8b880931999-03-03 20:24:30 +0000213 new_fn = os.path.join(self.doc, os.path.basename(fn))
214 shutil.copyfile(fn, new_fn)
215 if "text" in formats:
216 self.require_temps()
217 tempdir = self.doc
218 need_html = "html" not in formats
219 if self.options.max_split_depth != 1:
220 fp = open(self.l2h_aux_init_file, "a")
221 fp.write("# re-hack this file for --text:\n")
222 l2hoption(fp, "MAX_SPLIT_DEPTH", "1")
223 fp.write("1;\n")
224 fp.close()
225 tempdir = self.doc + "-temp-html"
226 need_html = 1
227 if need_html:
228 self.build_html(tempdir, max_split_depth=1)
229 self.build_text(tempdir)
230 if self.options.discard_temps:
231 self.cleanup()
232
233 def setup_texinputs(self):
234 texinputs = [self.filedir] + list(self.options.base_texinputs)
235 os.environ["TEXINPUTS"] = string.join(texinputs, os.pathsep)
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000236 self.message("TEXINPUTS=" + os.environ["TEXINPUTS"])
Fred Drake8b880931999-03-03 20:24:30 +0000237
Fred Drake8b880931999-03-03 20:24:30 +0000238 def build_aux(self, binary=None):
239 if binary is None:
240 binary = LATEX_BINARY
241 new_index( "%s.ind" % self.doc, "genindex")
242 new_index("mod%s.ind" % self.doc, "modindex")
243 self.run("%s %s" % (binary, self.doc))
244 self.use_bibtex = check_for_bibtex(self.doc + ".aux")
Fred Drake52ea0ce1999-09-22 19:55:35 +0000245 self.latex_runs = 1
Fred Drake8b880931999-03-03 20:24:30 +0000246
247 def build_dvi(self):
248 self.use_latex(LATEX_BINARY)
249
250 def build_pdf(self):
251 self.use_latex(PDFLATEX_BINARY)
252
253 def use_latex(self, binary):
254 self.require_temps(binary=binary)
255 if os.path.isfile("mod%s.idx" % self.doc):
256 self.run("%s mod%s.idx" % (MAKEINDEX_BINARY, self.doc))
257 if os.path.isfile(self.doc + ".idx"):
258 # call to Doc/tools/fix_hack omitted; doesn't appear necessary
259 self.run("%s %s.idx" % (MAKEINDEX_BINARY, self.doc))
260 import indfix
261 indfix.process(self.doc + ".ind")
262 if self.use_bibtex:
263 self.run("%s %s" % (BIBTEX_BINARY, self.doc))
Fred Drakea871c2e1999-05-06 19:37:38 +0000264 self.process_synopsis_files()
265 #
266 # let the doctype-specific handler do some intermediate work:
267 #
268 if self.doctype == "manual":
269 self.use_latex_manual(binary=binary)
270 elif self.doctype == "howto":
271 self.use_latex_howto(binary=binary)
272 else:
273 raise RuntimeError, "unsupported document type: " + self.doctype
274 #
275 # and now finish it off:
276 #
277 if os.path.isfile(self.doc + ".toc") and binary == PDFLATEX_BINARY:
278 import toc2bkm
279 toc2bkm.process(self.doc + ".toc", self.doc + ".bkm", "section")
280 if self.use_bibtex:
281 self.run("%s %s" % (BIBTEX_BINARY, self.doc))
282 self.run("%s %s" % (binary, self.doc))
283
284 def use_latex_howto(self, binary):
Fred Drake8b880931999-03-03 20:24:30 +0000285 self.run("%s %s" % (binary, self.doc))
286 if os.path.isfile("mod%s.idx" % self.doc):
287 self.run("%s -s %s mod%s.idx"
288 % (MAKEINDEX_BINARY, ISTFILE, self.doc))
289 if os.path.isfile(self.doc + ".idx"):
290 self.run("%s -s %s %s.idx" % (MAKEINDEX_BINARY, ISTFILE, self.doc))
Fred Drakea871c2e1999-05-06 19:37:38 +0000291 self.process_synopsis_files()
292
293 def use_latex_manual(self, binary):
294 pass
295
296 def process_synopsis_files(self):
297 synopsis_files = glob.glob(self.doc + "*.syn")
298 for path in synopsis_files:
299 uniqify_module_table(path)
Fred Drake8b880931999-03-03 20:24:30 +0000300
301 def build_ps(self):
302 self.run("%s -N0 -o %s.ps %s" % (DVIPS_BINARY, self.doc, self.doc))
303
304 def build_html(self, builddir=None, max_split_depth=None):
305 if builddir is None:
306 builddir = self.doc
307 if max_split_depth is None:
308 max_split_depth = self.options.max_split_depth
309 texfile = None
310 for p in string.split(os.environ["TEXINPUTS"], os.pathsep):
311 fn = os.path.join(p, self.doc + ".tex")
312 if os.path.isfile(fn):
313 texfile = fn
314 break
315 if not texfile:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000316 self.warning("Could not locate %s.tex; aborting." % self.doc)
Fred Drake8b880931999-03-03 20:24:30 +0000317 sys.exit(1)
318 # remove leading ./ (or equiv.); might avoid problems w/ dvips
319 if texfile[:2] == os.curdir + os.sep:
320 texfile = texfile[2:]
321 # build the command line and run LaTeX2HTML:
322 args = [LATEX2HTML_BINARY,
323 "-init_file", L2H_INIT_FILE,
324 "-init_file", self.l2h_aux_init_file,
325 "-dir", builddir,
326 texfile
327 ]
328 self.run(string.join(args)) # XXX need quoting!
329 # ... postprocess
330 shutil.copyfile(self.options.style_file,
331 os.path.join(builddir, self.doc + ".css"))
Fred Drake4437fdf1999-05-03 14:29:07 +0000332 shutil.copyfile(os.path.join(builddir, self.doc + ".html"),
333 os.path.join(builddir, "index.html"))
Fred Drake8b880931999-03-03 20:24:30 +0000334 if max_split_depth != 1:
335 pwd = os.getcwd()
336 try:
337 os.chdir(builddir)
338 self.run("%s %s *.html" % (PERL_BINARY, NODE2LABEL_SCRIPT))
339 finally:
340 os.chdir(pwd)
341
342 def build_text(self, tempdir=None):
343 if tempdir is None:
344 tempdir = self.doc
345 indexfile = os.path.join(tempdir, "index.html")
346 self.run("%s -nolist -dump %s >%s.txt"
347 % (LYNX_BINARY, indexfile, self.doc))
348
349 def require_temps(self, binary=None):
Fred Drake52ea0ce1999-09-22 19:55:35 +0000350 if not self.latex_runs:
Fred Drake8b880931999-03-03 20:24:30 +0000351 self.build_aux(binary=binary)
352
353 def write_l2h_aux_init_file(self):
354 fp = open(self.l2h_aux_init_file, "w")
355 fp.write("# auxillary init file for latex2html\n"
356 "# generated by mkhowto\n"
Fred Drake4437fdf1999-05-03 14:29:07 +0000357 "$NO_AUTO_LINK = 1;\n"
Fred Drake8b880931999-03-03 20:24:30 +0000358 )
359 options = self.options
360 for fn in options.config_files:
361 fp.write(open(fn).read())
362 fp.write("\n"
363 "\n"
364 'print "\nInitializing from file: %s\";\n\n'
365 % string_to_perl(fn))
366 l2hoption(fp, "ICONSERVER", options.icon_server)
Fred Drake52ea0ce1999-09-22 19:55:35 +0000367 l2hoption(fp, "IMAGE_TYPE", options.image_type)
Fred Drake8b880931999-03-03 20:24:30 +0000368 l2hoption(fp, "ADDRESS", options.address)
369 l2hoption(fp, "MAX_LINK_DEPTH", options.max_link_depth)
370 l2hoption(fp, "MAX_SPLIT_DEPTH", options.max_split_depth)
Fred Drake52ea0ce1999-09-22 19:55:35 +0000371 # this line needed in case $IMAGE_TYPE changed
372 fp.write("adjust_icon_information();\n")
Fred Drake8b880931999-03-03 20:24:30 +0000373 fp.write("1;\n")
374 fp.close()
375
376 def cleanup(self):
377 self.__have_temps = 0
378 for pattern in ("%s.aux", "%s.log", "%s.out", "%s.toc", "%s.bkm",
Fred Drakea871c2e1999-05-06 19:37:38 +0000379 "%s.idx", "%s.ilg", "%s.ind", "%s.pla",
Fred Drake8b880931999-03-03 20:24:30 +0000380 "%s.bbl", "%s.blg",
381 "mod%s.idx", "mod%s.ind", "mod%s.ilg",
382 ):
383 safe_unlink(pattern % self.doc)
Fred Drakea871c2e1999-05-06 19:37:38 +0000384 map(safe_unlink, glob.glob(self.doc + "*.syn"))
Fred Drake8b880931999-03-03 20:24:30 +0000385 for spec in ("IMG*", "*.pl", "WARNINGS", "index.dat", "modindex.dat"):
386 pattern = os.path.join(self.doc, spec)
387 map(safe_unlink, glob.glob(pattern))
388 if "dvi" not in self.options.formats:
389 safe_unlink(self.doc + ".dvi")
390 if os.path.isdir(self.doc + "-temp-html"):
391 shutil.rmtree(self.doc + "-temp-html", ignore_errors=1)
392 if not self.options.logging:
393 os.unlink(self.log_filename)
394 if not self.options.debugging:
395 os.unlink(self.l2h_aux_init_file)
396
397 def run(self, command):
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000398 self.message(command)
399 rc = os.system("(%s) </dev/null >>%s 2>&1"
400 % (command, self.log_filename))
Fred Drake8b880931999-03-03 20:24:30 +0000401 if rc:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000402 self.warning(
403 "Session transcript and error messages are in %s."
Fred Drake8b880931999-03-03 20:24:30 +0000404 % self.log_filename)
405 sys.exit(rc)
406
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000407 def message(self, msg):
408 msg = "+++ " + msg
409 if not self.options.quiet:
410 print msg
Fred Drake52ea0ce1999-09-22 19:55:35 +0000411 self.log(msg + "\n")
412
413 def warning(self, msg):
414 msg = "*** %s\n" % msg
415 sys.stderr.write(msg)
416 self.log(msg)
417
418 def log(self, msg):
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000419 fp = open(self.log_filename, "a")
Fred Drake52ea0ce1999-09-22 19:55:35 +0000420 fp.write(msg)
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000421 fp.close()
422
Fred Drake8b880931999-03-03 20:24:30 +0000423
424def safe_unlink(path):
425 try:
426 os.unlink(path)
427 except os.error:
428 pass
429
430
Fred Drakea871c2e1999-05-06 19:37:38 +0000431def split_pathname(path):
432 path = os.path.normpath(os.path.join(os.getcwd(), path))
433 dirname, basename = os.path.split(path)
Fred Drake8b880931999-03-03 20:24:30 +0000434 if basename[-4:] == ".tex":
435 basename = basename[:-4]
436 return dirname, basename
437
438
Fred Drakea871c2e1999-05-06 19:37:38 +0000439_doctype_rx = re.compile(r"\\documentclass(?:\[[^]]*\])?{([a-zA-Z]*)}")
440def get_doctype(path):
441 fp = open(path)
442 doctype = None
443 while 1:
444 line = fp.readline()
445 if not line:
446 break
447 m = _doctype_rx.match(line)
448 if m:
449 doctype = m.group(1)
450 break
451 fp.close()
452 return doctype
453
454
Fred Drake8b880931999-03-03 20:24:30 +0000455def main():
456 options = Options()
457 try:
458 args = options.parse(sys.argv[1:])
459 except getopt.error, msg:
460 error(options, msg)
461 if not args:
462 # attempt to locate single .tex file in current directory:
463 args = glob.glob("*.tex")
464 if not args:
465 error(options, "No file to process.")
466 if len(args) > 1:
467 error(options, "Could not deduce which files should be processed.")
468 #
469 # parameters are processed, let's go!
470 #
471 for path in args:
472 Job(options, path).build()
473
474
475def l2hoption(fp, option, value):
476 if value:
477 fp.write('$%s = "%s";\n' % (option, string_to_perl(str(value))))
478
479
480_to_perl = {}
481for c in map(chr, range(1, 256)):
482 _to_perl[c] = c
483_to_perl["@"] = "\\@"
484_to_perl["$"] = "\\$"
485_to_perl['"'] = '\\"'
486
487def string_to_perl(s):
488 return string.join(map(_to_perl.get, s), '')
489
490
491def check_for_bibtex(filename):
492 fp = open(filename)
493 pos = string.find(fp.read(), r"\bibdata{")
494 fp.close()
495 return pos >= 0
496
497def uniqify_module_table(filename):
498 lines = open(filename).readlines()
499 if len(lines) > 1:
500 if lines[-1] == lines[-2]:
501 del lines[-1]
502 open(filename, "w").writelines(lines)
503
504
505def new_index(filename, label="genindex"):
506 fp = open(filename, "w")
507 fp.write(r"""\
508\begin{theindex}
509\label{%s}
510\end{theindex}
511""" % label)
512 fp.close()
513
514
515if __name__ == "__main__":
516 main()