blob: 043ac57f46d712c8836c56c5a5d467d20da23522 [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 Drake9a257b42000-03-31 20:27:36 +000021 --numeric Don't rename the HTML files; just keep node#.html for
22 the filenames.
Fred Drake8b880931999-03-03 20:24:30 +000023
24Other options:
25 --a4 Format for A4 paper.
26 --letter Format for US letter paper (the default).
27 --help, -H Show this text.
28 --logging, -l Log stdout and stderr to a file (*.how).
29 --debugging, -D Echo commands as they are executed.
30 --keep, -k Keep temporary files around.
31 --quiet, -q Do not print command output to stdout.
32 (stderr is also lost, sorry; see *.how for errors)
33"""
34
35import getopt
36import glob
37import os
Fred Drakea871c2e1999-05-06 19:37:38 +000038import re
Fred Drake8b880931999-03-03 20:24:30 +000039import shutil
40import string
41import sys
42import tempfile
43
44
45MYDIR = os.path.normpath(os.path.join(os.getcwd(), sys.path[0]))
46TOPDIR = os.path.normpath(os.path.join(MYDIR, os.pardir))
47
48ISTFILE = os.path.join(TOPDIR, "texinputs", "python.ist")
49NODE2LABEL_SCRIPT = os.path.join(MYDIR, "node2label.pl")
50L2H_INIT_FILE = os.path.join(TOPDIR, "perl", "l2hinit.perl")
51
52BIBTEX_BINARY = "bibtex"
53DVIPS_BINARY = "dvips"
54LATEX_BINARY = "latex"
55LATEX2HTML_BINARY = "latex2html"
56LYNX_BINARY = "lynx"
57MAKEINDEX_BINARY = "makeindex"
58PDFLATEX_BINARY = "pdflatex"
59PERL_BINARY = "perl"
60PYTHON_BINARY = "python"
61
62
63def usage(options):
64 print __doc__ % options
65
66def error(options, message, err=2):
67 sys.stdout = sys.stderr
68 print message
69 print
70 usage(options)
71 sys.exit(2)
72
73
74class Options:
75 program = os.path.basename(sys.argv[0])
76 #
77 address = ''
78 debugging = 0
79 discard_temps = 1
80 have_temps = 0
81 icon_server = None
Fred Drake52ea0ce1999-09-22 19:55:35 +000082 image_type = "gif"
Fred Drake8b880931999-03-03 20:24:30 +000083 logging = 0
84 max_link_depth = 3
85 max_split_depth = 6
86 paper = "letter"
87 quiet = 0
Fred Drake52ea0ce1999-09-22 19:55:35 +000088 runs = 0
Fred Drake9a257b42000-03-31 20:27:36 +000089 numeric = 0
Fred Drake8b880931999-03-03 20:24:30 +000090 style_file = os.path.join(TOPDIR, "html", "style.css")
Fred Drakecf1b06e1999-09-23 16:55:09 +000091 about_file = os.path.join(TOPDIR, "html", "about.dat")
Fred Drake8b880931999-03-03 20:24:30 +000092 #
93 DEFAULT_FORMATS = ("pdf",)
94 ALL_FORMATS = ("dvi", "html", "pdf", "ps", "text")
95
96 def __init__(self):
97 self.config_files = []
98 self.formats = []
99
100 def __getitem__(self, key):
101 # This is used when formatting the usage message.
102 try:
103 return getattr(self, key)
104 except AttributeError:
105 raise KeyError, key
106
107 def parse(self, args):
Fred Drake52ea0ce1999-09-22 19:55:35 +0000108 opts, args = getopt.getopt(args, "Hi:a:s:lDkqr:",
Fred Drake8b880931999-03-03 20:24:30 +0000109 ["all", "postscript", "help", "iconserver=",
110 "address=", "a4", "l2h-config=", "letter",
111 "link=", "split=", "logging", "debugging",
Fred Drakecf1b06e1999-09-23 16:55:09 +0000112 "keep", "quiet", "runs=", "image-type=",
Fred Drake9a257b42000-03-31 20:27:36 +0000113 "about=", "numeric"]
Fred Drake52ea0ce1999-09-22 19:55:35 +0000114 + list(self.ALL_FORMATS))
Fred Drake8b880931999-03-03 20:24:30 +0000115 for opt, arg in opts:
116 if opt == "--all":
117 self.formats = list(self.ALL_FORMATS)
118 elif opt in ("-H", "--help"):
119 usage(self)
120 sys.exit()
121 elif opt == "--iconserver":
122 self.icon_server = arg
123 elif opt in ("-a", "--address"):
124 self.address = arg
125 elif opt == "--a4":
126 self.paper = "a4"
127 elif opt == "--letter":
128 self.paper = "letter"
129 elif opt == "--l2h-config":
130 self.config_files.append(arg)
131 elif opt == "--link":
132 self.max_link_depth = int(arg)
133 elif opt in ("-s", "--split"):
134 self.max_split_depth = int(arg)
135 elif opt in ("-l", "--logging"):
136 self.logging = self.logging + 1
137 elif opt in ("-D", "--debugging"):
138 self.debugging = self.debugging + 1
139 elif opt in ("-k", "--keep"):
140 self.discard_temps = 0
141 elif opt in ("-q", "--quiet"):
142 self.quiet = 1
Fred Drake52ea0ce1999-09-22 19:55:35 +0000143 elif opt in ("-r", "--runs"):
144 self.runs = int(arg)
145 elif opt == "--image-type":
146 self.image_type = arg
Fred Drakecf1b06e1999-09-23 16:55:09 +0000147 elif opt == "--about":
148 # always make this absolute:
149 self.about_file = os.path.normpath(
150 os.path.join(os.getcwd(), arg))
Fred Drake9a257b42000-03-31 20:27:36 +0000151 elif opt == "--numeric":
152 self.numeric = 1
Fred Drake8b880931999-03-03 20:24:30 +0000153 #
154 # Format specifiers:
155 #
156 elif opt[2:] in self.ALL_FORMATS:
157 self.add_format(opt[2:])
158 elif opt == "--postscript":
159 # synonym for --ps
160 self.add_format("ps")
161 self.initialize()
162 #
163 # return the args to allow the caller access:
164 #
165 return args
166
167 def add_format(self, format):
168 """Add a format to the formats list if not present."""
169 if not format in self.formats:
170 self.formats.append(format)
171
172 def initialize(self):
173 """Complete initialization. This is needed if parse() isn't used."""
174 # add the default format if no formats were specified:
175 if not self.formats:
176 self.formats = self.DEFAULT_FORMATS
177 # determine the base set of texinputs directories:
178 texinputs = string.split(os.environ.get("TEXINPUTS", ""), os.pathsep)
179 if not texinputs:
180 texinputs = ['']
181 self.base_texinputs = [
182 os.path.join(TOPDIR, "paper-" + self.paper),
183 os.path.join(TOPDIR, "texinputs"),
184 ] + texinputs
185
186
187class Job:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000188 latex_runs = 0
189
Fred Drake8b880931999-03-03 20:24:30 +0000190 def __init__(self, options, path):
191 self.options = options
Fred Drakea871c2e1999-05-06 19:37:38 +0000192 self.doctype = get_doctype(path)
Fred Drake8b880931999-03-03 20:24:30 +0000193 self.filedir, self.doc = split_pathname(path)
194 self.log_filename = self.doc + ".how"
195 if os.path.exists(self.log_filename):
196 os.unlink(self.log_filename)
197 if os.path.exists(self.doc + ".l2h"):
198 self.l2h_aux_init_file = tempfile.mktemp()
199 else:
200 self.l2h_aux_init_file = self.doc + ".l2h"
201 self.write_l2h_aux_init_file()
202
203 def build(self):
204 self.setup_texinputs()
205 formats = self.options.formats
206 if "dvi" in formats or "ps" in formats:
207 self.build_dvi()
208 if "pdf" in formats:
209 self.build_pdf()
210 if "ps" in formats:
211 self.build_ps()
212 if "html" in formats:
213 self.require_temps()
214 self.build_html(self.doc)
215 if self.options.icon_server == ".":
Fred Drake52ea0ce1999-09-22 19:55:35 +0000216 pattern = os.path.join(TOPDIR, "html", "icons",
217 "*." + self.options.image_type)
218 imgs = glob.glob(pattern)
219 if not imgs:
220 self.warning(
221 "Could not locate support images of type %s."
222 % `self.options.image_type`)
223 for fn in imgs:
Fred Drake8b880931999-03-03 20:24:30 +0000224 new_fn = os.path.join(self.doc, os.path.basename(fn))
225 shutil.copyfile(fn, new_fn)
226 if "text" in formats:
227 self.require_temps()
228 tempdir = self.doc
229 need_html = "html" not in formats
230 if self.options.max_split_depth != 1:
231 fp = open(self.l2h_aux_init_file, "a")
232 fp.write("# re-hack this file for --text:\n")
233 l2hoption(fp, "MAX_SPLIT_DEPTH", "1")
234 fp.write("1;\n")
235 fp.close()
236 tempdir = self.doc + "-temp-html"
237 need_html = 1
238 if need_html:
239 self.build_html(tempdir, max_split_depth=1)
240 self.build_text(tempdir)
241 if self.options.discard_temps:
242 self.cleanup()
243
244 def setup_texinputs(self):
245 texinputs = [self.filedir] + list(self.options.base_texinputs)
246 os.environ["TEXINPUTS"] = string.join(texinputs, os.pathsep)
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000247 self.message("TEXINPUTS=" + os.environ["TEXINPUTS"])
Fred Drake8b880931999-03-03 20:24:30 +0000248
Fred Drake8b880931999-03-03 20:24:30 +0000249 def build_aux(self, binary=None):
250 if binary is None:
251 binary = LATEX_BINARY
252 new_index( "%s.ind" % self.doc, "genindex")
253 new_index("mod%s.ind" % self.doc, "modindex")
254 self.run("%s %s" % (binary, self.doc))
255 self.use_bibtex = check_for_bibtex(self.doc + ".aux")
Fred Drake52ea0ce1999-09-22 19:55:35 +0000256 self.latex_runs = 1
Fred Drake8b880931999-03-03 20:24:30 +0000257
258 def build_dvi(self):
259 self.use_latex(LATEX_BINARY)
260
261 def build_pdf(self):
262 self.use_latex(PDFLATEX_BINARY)
263
264 def use_latex(self, binary):
265 self.require_temps(binary=binary)
266 if os.path.isfile("mod%s.idx" % self.doc):
267 self.run("%s mod%s.idx" % (MAKEINDEX_BINARY, self.doc))
268 if os.path.isfile(self.doc + ".idx"):
269 # call to Doc/tools/fix_hack omitted; doesn't appear necessary
270 self.run("%s %s.idx" % (MAKEINDEX_BINARY, self.doc))
271 import indfix
272 indfix.process(self.doc + ".ind")
273 if self.use_bibtex:
274 self.run("%s %s" % (BIBTEX_BINARY, self.doc))
Fred Drakea871c2e1999-05-06 19:37:38 +0000275 self.process_synopsis_files()
276 #
277 # let the doctype-specific handler do some intermediate work:
278 #
279 if self.doctype == "manual":
280 self.use_latex_manual(binary=binary)
281 elif self.doctype == "howto":
282 self.use_latex_howto(binary=binary)
283 else:
284 raise RuntimeError, "unsupported document type: " + self.doctype
285 #
286 # and now finish it off:
287 #
288 if os.path.isfile(self.doc + ".toc") and binary == PDFLATEX_BINARY:
289 import toc2bkm
290 toc2bkm.process(self.doc + ".toc", self.doc + ".bkm", "section")
291 if self.use_bibtex:
292 self.run("%s %s" % (BIBTEX_BINARY, self.doc))
293 self.run("%s %s" % (binary, self.doc))
294
295 def use_latex_howto(self, binary):
Fred Drake8b880931999-03-03 20:24:30 +0000296 self.run("%s %s" % (binary, self.doc))
297 if os.path.isfile("mod%s.idx" % self.doc):
298 self.run("%s -s %s mod%s.idx"
299 % (MAKEINDEX_BINARY, ISTFILE, self.doc))
300 if os.path.isfile(self.doc + ".idx"):
301 self.run("%s -s %s %s.idx" % (MAKEINDEX_BINARY, ISTFILE, self.doc))
Fred Drakea871c2e1999-05-06 19:37:38 +0000302 self.process_synopsis_files()
303
304 def use_latex_manual(self, binary):
305 pass
306
307 def process_synopsis_files(self):
308 synopsis_files = glob.glob(self.doc + "*.syn")
309 for path in synopsis_files:
310 uniqify_module_table(path)
Fred Drake8b880931999-03-03 20:24:30 +0000311
312 def build_ps(self):
313 self.run("%s -N0 -o %s.ps %s" % (DVIPS_BINARY, self.doc, self.doc))
314
315 def build_html(self, builddir=None, max_split_depth=None):
316 if builddir is None:
317 builddir = self.doc
318 if max_split_depth is None:
319 max_split_depth = self.options.max_split_depth
320 texfile = None
321 for p in string.split(os.environ["TEXINPUTS"], os.pathsep):
322 fn = os.path.join(p, self.doc + ".tex")
323 if os.path.isfile(fn):
324 texfile = fn
325 break
326 if not texfile:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000327 self.warning("Could not locate %s.tex; aborting." % self.doc)
Fred Drake8b880931999-03-03 20:24:30 +0000328 sys.exit(1)
329 # remove leading ./ (or equiv.); might avoid problems w/ dvips
330 if texfile[:2] == os.curdir + os.sep:
331 texfile = texfile[2:]
332 # build the command line and run LaTeX2HTML:
Fred Drakeba828782000-04-03 04:19:14 +0000333 if not os.path.isdir(builddir):
334 os.mkdir(builddir)
Fred Drake8b880931999-03-03 20:24:30 +0000335 args = [LATEX2HTML_BINARY,
336 "-init_file", L2H_INIT_FILE,
337 "-init_file", self.l2h_aux_init_file,
338 "-dir", builddir,
339 texfile
340 ]
341 self.run(string.join(args)) # XXX need quoting!
342 # ... postprocess
343 shutil.copyfile(self.options.style_file,
344 os.path.join(builddir, self.doc + ".css"))
Fred Drake4437fdf1999-05-03 14:29:07 +0000345 shutil.copyfile(os.path.join(builddir, self.doc + ".html"),
346 os.path.join(builddir, "index.html"))
Fred Drake9a257b42000-03-31 20:27:36 +0000347 if max_split_depth != 1 and not self.options.numeric:
Fred Drake8b880931999-03-03 20:24:30 +0000348 pwd = os.getcwd()
349 try:
350 os.chdir(builddir)
351 self.run("%s %s *.html" % (PERL_BINARY, NODE2LABEL_SCRIPT))
352 finally:
353 os.chdir(pwd)
354
355 def build_text(self, tempdir=None):
356 if tempdir is None:
357 tempdir = self.doc
358 indexfile = os.path.join(tempdir, "index.html")
359 self.run("%s -nolist -dump %s >%s.txt"
360 % (LYNX_BINARY, indexfile, self.doc))
361
362 def require_temps(self, binary=None):
Fred Drake52ea0ce1999-09-22 19:55:35 +0000363 if not self.latex_runs:
Fred Drake8b880931999-03-03 20:24:30 +0000364 self.build_aux(binary=binary)
365
366 def write_l2h_aux_init_file(self):
367 fp = open(self.l2h_aux_init_file, "w")
368 fp.write("# auxillary init file for latex2html\n"
369 "# generated by mkhowto\n"
Fred Drake4437fdf1999-05-03 14:29:07 +0000370 "$NO_AUTO_LINK = 1;\n"
Fred Drake8b880931999-03-03 20:24:30 +0000371 )
372 options = self.options
373 for fn in options.config_files:
374 fp.write(open(fn).read())
375 fp.write("\n"
376 "\n"
377 'print "\nInitializing from file: %s\";\n\n'
378 % string_to_perl(fn))
Fred Drakecf1b06e1999-09-23 16:55:09 +0000379 l2hoption(fp, "ABOUT_FILE", options.about_file)
Fred Drake8b880931999-03-03 20:24:30 +0000380 l2hoption(fp, "ICONSERVER", options.icon_server)
Fred Drake52ea0ce1999-09-22 19:55:35 +0000381 l2hoption(fp, "IMAGE_TYPE", options.image_type)
Fred Drake8b880931999-03-03 20:24:30 +0000382 l2hoption(fp, "ADDRESS", options.address)
383 l2hoption(fp, "MAX_LINK_DEPTH", options.max_link_depth)
384 l2hoption(fp, "MAX_SPLIT_DEPTH", options.max_split_depth)
Fred Drake52ea0ce1999-09-22 19:55:35 +0000385 # this line needed in case $IMAGE_TYPE changed
386 fp.write("adjust_icon_information();\n")
Fred Drake8b880931999-03-03 20:24:30 +0000387 fp.write("1;\n")
388 fp.close()
389
390 def cleanup(self):
391 self.__have_temps = 0
392 for pattern in ("%s.aux", "%s.log", "%s.out", "%s.toc", "%s.bkm",
Fred Drakea871c2e1999-05-06 19:37:38 +0000393 "%s.idx", "%s.ilg", "%s.ind", "%s.pla",
Fred Drake8b880931999-03-03 20:24:30 +0000394 "%s.bbl", "%s.blg",
395 "mod%s.idx", "mod%s.ind", "mod%s.ilg",
396 ):
397 safe_unlink(pattern % self.doc)
Fred Drakea871c2e1999-05-06 19:37:38 +0000398 map(safe_unlink, glob.glob(self.doc + "*.syn"))
Fred Drake8b880931999-03-03 20:24:30 +0000399 for spec in ("IMG*", "*.pl", "WARNINGS", "index.dat", "modindex.dat"):
400 pattern = os.path.join(self.doc, spec)
401 map(safe_unlink, glob.glob(pattern))
402 if "dvi" not in self.options.formats:
403 safe_unlink(self.doc + ".dvi")
404 if os.path.isdir(self.doc + "-temp-html"):
405 shutil.rmtree(self.doc + "-temp-html", ignore_errors=1)
406 if not self.options.logging:
407 os.unlink(self.log_filename)
408 if not self.options.debugging:
409 os.unlink(self.l2h_aux_init_file)
410
411 def run(self, command):
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000412 self.message(command)
413 rc = os.system("(%s) </dev/null >>%s 2>&1"
414 % (command, self.log_filename))
Fred Drake8b880931999-03-03 20:24:30 +0000415 if rc:
Fred Drake52ea0ce1999-09-22 19:55:35 +0000416 self.warning(
417 "Session transcript and error messages are in %s."
Fred Drake8b880931999-03-03 20:24:30 +0000418 % self.log_filename)
419 sys.exit(rc)
420
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000421 def message(self, msg):
422 msg = "+++ " + msg
423 if not self.options.quiet:
424 print msg
Fred Drake52ea0ce1999-09-22 19:55:35 +0000425 self.log(msg + "\n")
426
427 def warning(self, msg):
428 msg = "*** %s\n" % msg
429 sys.stderr.write(msg)
430 self.log(msg)
431
432 def log(self, msg):
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000433 fp = open(self.log_filename, "a")
Fred Drake52ea0ce1999-09-22 19:55:35 +0000434 fp.write(msg)
Fred Drakeaaa0d9a1999-03-03 21:57:58 +0000435 fp.close()
436
Fred Drake8b880931999-03-03 20:24:30 +0000437
438def safe_unlink(path):
439 try:
440 os.unlink(path)
441 except os.error:
442 pass
443
444
Fred Drakea871c2e1999-05-06 19:37:38 +0000445def split_pathname(path):
446 path = os.path.normpath(os.path.join(os.getcwd(), path))
447 dirname, basename = os.path.split(path)
Fred Drake8b880931999-03-03 20:24:30 +0000448 if basename[-4:] == ".tex":
449 basename = basename[:-4]
450 return dirname, basename
451
452
Fred Drakea871c2e1999-05-06 19:37:38 +0000453_doctype_rx = re.compile(r"\\documentclass(?:\[[^]]*\])?{([a-zA-Z]*)}")
454def get_doctype(path):
455 fp = open(path)
456 doctype = None
457 while 1:
458 line = fp.readline()
459 if not line:
460 break
461 m = _doctype_rx.match(line)
462 if m:
463 doctype = m.group(1)
464 break
465 fp.close()
466 return doctype
467
468
Fred Drake8b880931999-03-03 20:24:30 +0000469def main():
470 options = Options()
471 try:
472 args = options.parse(sys.argv[1:])
473 except getopt.error, msg:
474 error(options, msg)
475 if not args:
476 # attempt to locate single .tex file in current directory:
477 args = glob.glob("*.tex")
478 if not args:
479 error(options, "No file to process.")
480 if len(args) > 1:
481 error(options, "Could not deduce which files should be processed.")
482 #
483 # parameters are processed, let's go!
484 #
485 for path in args:
486 Job(options, path).build()
487
488
489def l2hoption(fp, option, value):
490 if value:
491 fp.write('$%s = "%s";\n' % (option, string_to_perl(str(value))))
492
493
494_to_perl = {}
495for c in map(chr, range(1, 256)):
496 _to_perl[c] = c
497_to_perl["@"] = "\\@"
498_to_perl["$"] = "\\$"
499_to_perl['"'] = '\\"'
500
501def string_to_perl(s):
502 return string.join(map(_to_perl.get, s), '')
503
504
505def check_for_bibtex(filename):
506 fp = open(filename)
507 pos = string.find(fp.read(), r"\bibdata{")
508 fp.close()
509 return pos >= 0
510
511def uniqify_module_table(filename):
512 lines = open(filename).readlines()
513 if len(lines) > 1:
514 if lines[-1] == lines[-2]:
515 del lines[-1]
516 open(filename, "w").writelines(lines)
517
518
519def new_index(filename, label="genindex"):
520 fp = open(filename, "w")
521 fp.write(r"""\
522\begin{theindex}
523\label{%s}
524\end{theindex}
525""" % label)
526 fp.close()
527
528
529if __name__ == "__main__":
530 main()