[Python-checkins] r47238 - in sandbox/trunk/pdb/Doc: Makefile Makefile.deps commontex commontex/boilerplate.tex commontex/copyright.tex commontex/patchlevel.tex commontex/underscore.sty html html/icons html/icons/blank.gif html/icons/blank.png html/icons/contents.gif html/icons/contents.png html/icons/index.gif html/icons/index.png html/icons/modules.gif html/icons/modules.png html/icons/next.gif html/icons/next.png html/icons/previous.gif html/icons/previous.png html/icons/pyfav.gif html/icons/pyfav.png html/icons/up.gif html/icons/up.png html/stdabout.dat html/style.css info info/Makefile lib lib/Makefile lib/lib-ds.tex lib/lib.tex lib/libmpdb.tex paper-letter perl perl/SynopsisTable.pm perl/l2hinit.perl perl/manual.perl perl/python.perl texinputs texinputs/fncychap.sty texinputs/manual.cls texinputs/pypaper.sty texinputs/python.ist texinputs/python.sty texinputs/underscore.sty tools tools/buildindex.py tools/checkargs.pm tools/getversioninfo tools/indfix.py tools/mkhowto tools/mkinfo tools/node2label.pl tools/patchlevel.h tools/py2texi.el tools/toc2bkm.py

matt.fleming python-checkins at python.org
Wed Jul 5 14:19:21 CEST 2006


Author: matt.fleming
Date: Wed Jul  5 14:19:15 2006
New Revision: 47238

Added:
   sandbox/trunk/pdb/Doc/
      - copied from r47223, sandbox/trunk/pdb/doc/
   sandbox/trunk/pdb/Doc/Makefile
   sandbox/trunk/pdb/Doc/Makefile.deps
   sandbox/trunk/pdb/Doc/commontex/
   sandbox/trunk/pdb/Doc/commontex/boilerplate.tex
   sandbox/trunk/pdb/Doc/commontex/copyright.tex
   sandbox/trunk/pdb/Doc/commontex/patchlevel.tex
   sandbox/trunk/pdb/Doc/commontex/underscore.sty
   sandbox/trunk/pdb/Doc/html/
   sandbox/trunk/pdb/Doc/html/icons/
   sandbox/trunk/pdb/Doc/html/icons/blank.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/blank.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/contents.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/contents.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/index.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/index.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/modules.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/modules.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/next.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/next.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/previous.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/previous.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/pyfav.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/pyfav.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/up.gif   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/icons/up.png   (contents, props changed)
   sandbox/trunk/pdb/Doc/html/stdabout.dat
   sandbox/trunk/pdb/Doc/html/style.css
   sandbox/trunk/pdb/Doc/info/
   sandbox/trunk/pdb/Doc/info/Makefile
   sandbox/trunk/pdb/Doc/lib/
   sandbox/trunk/pdb/Doc/lib/Makefile
   sandbox/trunk/pdb/Doc/lib/lib-ds.tex
   sandbox/trunk/pdb/Doc/lib/lib.tex
   sandbox/trunk/pdb/Doc/lib/libmpdb.tex
   sandbox/trunk/pdb/Doc/paper-letter/
   sandbox/trunk/pdb/Doc/perl/
   sandbox/trunk/pdb/Doc/perl/SynopsisTable.pm
   sandbox/trunk/pdb/Doc/perl/l2hinit.perl
   sandbox/trunk/pdb/Doc/perl/manual.perl
   sandbox/trunk/pdb/Doc/perl/python.perl
   sandbox/trunk/pdb/Doc/texinputs/
   sandbox/trunk/pdb/Doc/texinputs/fncychap.sty
   sandbox/trunk/pdb/Doc/texinputs/manual.cls
   sandbox/trunk/pdb/Doc/texinputs/pypaper.sty
   sandbox/trunk/pdb/Doc/texinputs/python.ist
   sandbox/trunk/pdb/Doc/texinputs/python.sty
   sandbox/trunk/pdb/Doc/texinputs/underscore.sty
   sandbox/trunk/pdb/Doc/tools/
   sandbox/trunk/pdb/Doc/tools/buildindex.py   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/checkargs.pm
   sandbox/trunk/pdb/Doc/tools/getversioninfo   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/indfix.py   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/mkhowto   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/mkinfo   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/node2label.pl   (contents, props changed)
   sandbox/trunk/pdb/Doc/tools/patchlevel.h
   sandbox/trunk/pdb/Doc/tools/py2texi.el
   sandbox/trunk/pdb/Doc/tools/toc2bkm.py   (contents, props changed)
Log:
Added the beginning of documentation


Added: sandbox/trunk/pdb/Doc/Makefile
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/Makefile	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,610 @@
+# Makefile for Python documentation
+# ---------------------------------
+#
+# See also the README file.
+#
+# This is a bit of a mess.  The documents are identified by short names:
+#   api -- Python/C API Reference Manual
+#   doc -- Documenting Python
+#   ext -- Extending and Embedding the Python Interpreter
+#   lib -- Library Reference Manual
+#   mac -- Macintosh Library Modules
+#   ref -- Python Reference Manual
+#   tut -- Python Tutorial
+#   inst -- Installing Python Modules
+#   dist -- Distributing Python Modules
+#
+# The LaTeX sources for each of these documents are in subdirectories
+# with the three-letter designations above as the directory names.
+#
+# The main target creates HTML for each of the documents.  You can
+# also do "make lib" (etc.) to create the HTML versions of individual
+# documents.
+#
+# The document classes and styles are in the texinputs/ directory.
+# These define a number of macros that are similar in name and intent
+# as macros in Texinfo (e.g. \code{...} and \emph{...}), as well as a
+# number of environments for formatting function and data definitions.
+# Documentation for the macros is included in "Documenting Python"; see
+# http://www.python.org/doc/current/doc/doc.html, or the sources for
+# this document in the doc/ directory.
+#
+# Everything is processed by LaTeX.  See the file `README' for more
+# information on the tools needed for processing.
+#
+# There's a problem with generating the index which has been solved by
+# a sed command applied to the index file.  The shell script fix_hack
+# does this (the Makefile takes care of calling it).
+#
+# Additional targets attempt to convert selected LaTeX sources to
+# various other formats.  These are generally site specific because
+# the tools used are all but universal.  These targets are:
+#
+#   ps  -- convert all documents from LaTeX to PostScript
+#   pdf -- convert all documents from LaTeX to the
+#		Portable Document Format
+#
+# See the README file for more information on these targets.
+#
+# The formatted output is located in subdirectories.  For PDF and
+# PostScript, look in the paper-$(PAPER)/ directory.  For HTML, look in
+# the html/ directory.  If you want to fix the GNU info process, look
+# in the info/ directory; please send patches to docs at python.org.
+
+# This Makefile only includes information on how to perform builds; for
+# dependency information, see Makefile.deps.
+srcdir=.
+DISTFILES=lib/lib.tex lib/libmpdb.tex Makefile.in Makefile.deps \
+	html
+
+PYTHON_SRC:=$(shell cd .. && pwd)
+PYTHON_DOC:=$(shell cd . && pwd)
+
+# Customization -- you *may* have to edit this
+
+# You could set this to a4:
+PAPER=letter
+
+# Ideally, you shouldn't need to edit beyond this point
+.PHONY: realclean distclean clean clobber test check
+
+
+INFODIR=	$(srcdir)/info
+TOOLSDIR=	$(srcdir)/tools
+
+# This is the *documentation* release, and is used to construct the
+# file names of the downloadable tarballs.  It is initialized by the
+# getversioninfo script to ensure that the right version number is
+# used; the script will also write commontex/patchlevel.tex if that
+# doesn't exist or needs to be changed.  Documents which depend on the
+# version number should use \input{patchlevel} and include
+# commontex/patchlevel.tex in their dependencies.
+RELEASE:=$(shell $(PYTHON) $(PYTHON_DOC)/tools/getversioninfo)
+
+PYTHON:=	   python
+DVIPS:=	   dvips -N0 -t $(PAPER)
+
+# This is ugly!  The issue here is that there are two different levels
+# in the directory tree at which we execute mkhowto, so we can't
+# define it just once using a relative path (at least not with the
+# current implementation and Makefile structure).  We use the GNUish
+# $(shell) function here to work around that restriction by
+# identifying mkhowto and the commontex/ directory using absolute paths.
+#
+# If your doc build fails immediately, you may need to switch to GNU make.
+# (e.g. OpenBSD needs package gmake installed; use gmake instead of make)
+PWD=$(shell pwd)
+
+# (The trailing colon in the value is needed; TeX places its default
+# set of paths at the location of the empty string in the path list.)
+TEXINPUTS:=$(PWD)/commontex:
+
+# The mkhowto script can be run from the checkout using the first
+# version of this variable definition, or from a preferred version
+# using the second version.  The standard documentation is typically
+# built using the second flavor, where the preferred version is from
+# the Python CVS trunk.
+MKHOWTO=   TEXINPUTS=$(TEXINPUTS) $(PYTHON) $(PWD)/tools/mkhowto
+
+MKDVI=	   $(MKHOWTO) --paper=$(PAPER) --dvi
+MKHTML=	   $(MKHOWTO) --html --about html/stdabout.dat \
+		--iconserver ../icons --favicon ../icons/pyfav.png \
+		--address $(PYTHONDOCS) --up-link ../index.html \
+		--up-title "Python Documentation Index" \
+		--global-module-index "../modindex.html" --dvips-safe
+MKPDF=	   $(MKHOWTO) --paper=$(PAPER) --pdf
+MKPS=	   $(MKHOWTO) --paper=$(PAPER) --ps
+
+BUILDINDEX=$(TOOLSDIR)/buildindex.py
+
+PYTHONDOCS="See <i><a href=\"about.html\">About this document...</a></i> for information on suggesting changes."
+HTMLBASE=  file:`pwd`
+
+# The emacs binary used to build the info docs. GNU Emacs 21 is required.
+EMACS=     emacs
+
+# The end of this should reflect the major/minor version numbers of
+# the release:
+WHATSNEW=whatsnew25
+
+# what's what
+MANDVIFILES=	paper-$(PAPER)/lib.dvi 
+
+MANPDFFILES=	paper-$(PAPER)/lib.pdf
+
+HOWTOPDFFILES=
+
+MANPSFILES=	paper-$(PAPER)/lib.ps
+
+DVIFILES=	$(MANDVIFILES) $(HOWTODVIFILES)
+PDFFILES=	$(MANPDFFILES) $(HOWTOPDFFILES)
+PSFILES=	$(MANPSFILES) $(HOWTOPSFILES)
+
+HTMLCSSFILES=html/lib/lib.css
+
+ISILOCSSFILES=
+
+ALLCSSFILES=$(HTMLCSSFILES) $(ISILOCSSFILES)
+
+INDEXFILES=html/lib/lib.html
+
+ALLHTMLFILES=$(INDEXFILES)
+
+COMMONPERL= $(PYTHON_DOC)/perl/manual.perl $(PYTHON_DOC)/perl/python.perl $(PYTHON_DOC)/perl/l2hinit.perl
+
+ANNOAPI=api/refcounts.dat tools/anno-api.py
+
+include ./Makefile.deps
+
+# These must be declared phony since there
+# are directories with matching names:
+.PHONY: api doc lib ref tut inst dist install
+.PHONY: html info
+
+
+# Main target
+default:	html
+all:		html info dvi ps pdf
+
+dvi:	$(DVIFILES)
+pdf:	$(PDFFILES)
+ps:	$(PSFILES)
+
+# For now, we don't install anything.
+install:
+
+# For now, we don't test/check anything.
+test check:
+
+world:	ps pdf html distfiles
+
+
+# Rules to build PostScript and PDF formats
+.SUFFIXES: .dvi .ps
+
+.dvi.ps:
+	$(DVIPS) -o $@ $<
+
+
+# Targets for each document:
+# Python/C API Reference Manual
+paper-$(PAPER)/api.dvi: $(ANNOAPIFILES)
+	cd paper-$(PAPER) && $(MKDVI) api.tex
+
+paper-$(PAPER)/api.pdf: $(ANNOAPIFILES)
+	cd paper-$(PAPER) && $(MKPDF) api.tex
+
+paper-$(PAPER)/api.tex: api/api.tex
+	cp api/api.tex $@
+
+paper-$(PAPER)/abstract.tex: api/abstract.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/abstract.tex
+
+paper-$(PAPER)/concrete.tex: api/concrete.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/concrete.tex
+
+paper-$(PAPER)/exceptions.tex: api/exceptions.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/exceptions.tex
+
+paper-$(PAPER)/init.tex: api/init.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/init.tex
+
+paper-$(PAPER)/intro.tex: api/intro.tex
+	cp api/intro.tex $@
+
+paper-$(PAPER)/memory.tex: api/memory.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/memory.tex
+
+paper-$(PAPER)/newtypes.tex: api/newtypes.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/newtypes.tex
+
+paper-$(PAPER)/refcounting.tex: api/refcounting.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/refcounting.tex
+
+paper-$(PAPER)/utilities.tex: api/utilities.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/utilities.tex
+
+paper-$(PAPER)/veryhigh.tex: api/veryhigh.tex $(ANNOAPI)
+	$(PYTHON) $(TOOLSDIR)/anno-api.py -o $@ api/veryhigh.tex
+
+# Distributing Python Modules
+paper-$(PAPER)/dist.dvi: $(DISTFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../dist/dist.tex
+
+paper-$(PAPER)/dist.pdf: $(DISTFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../dist/dist.tex
+
+# Documenting Python
+paper-$(PAPER)/doc.dvi: $(DOCFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../doc/doc.tex
+
+paper-$(PAPER)/doc.pdf: $(DOCFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../doc/doc.tex
+
+# Extending and Embedding the Python Interpreter
+paper-$(PAPER)/ext.dvi: $(EXTFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../ext/ext.tex
+
+paper-$(PAPER)/ext.pdf: $(EXTFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../ext/ext.tex
+
+# Installing Python Modules
+paper-$(PAPER)/inst.dvi: $(INSTFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../inst/inst.tex
+
+paper-$(PAPER)/inst.pdf: $(INSTFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../inst/inst.tex
+
+# Python Library Reference
+paper-$(PAPER)/lib.dvi: $(LIBFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../lib/lib.tex
+
+paper-$(PAPER)/lib.pdf: $(LIBFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../lib/lib.tex
+
+# Macintosh Library Modules
+paper-$(PAPER)/mac.dvi: $(MACFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../mac/mac.tex
+
+paper-$(PAPER)/mac.pdf: $(MACFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../mac/mac.tex
+
+# Python Reference Manual
+paper-$(PAPER)/ref.dvi: $(REFFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../ref/ref.tex
+
+paper-$(PAPER)/ref.pdf: $(REFFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../ref/ref.tex
+
+# Python Tutorial
+paper-$(PAPER)/tut.dvi: $(TUTFILES)
+	cd paper-$(PAPER) && $(MKDVI) ../tut/tut.tex
+
+paper-$(PAPER)/tut.pdf: $(TUTFILES)
+	cd paper-$(PAPER) && $(MKPDF) ../tut/tut.tex
+
+# What's New in Python X.Y
+paper-$(PAPER)/$(WHATSNEW).dvi: whatsnew/$(WHATSNEW).tex
+	cd paper-$(PAPER) && $(MKDVI) ../whatsnew/$(WHATSNEW).tex
+
+paper-$(PAPER)/$(WHATSNEW).pdf: whatsnew/$(WHATSNEW).tex
+	cd paper-$(PAPER) && $(MKPDF) ../whatsnew/$(WHATSNEW).tex
+
+# The remaining part of the Makefile is concerned with various
+# conversions, as described above.  See also the README file.
+
+info:
+	cd $(INFODIR) && $(MAKE) EMACS=$(EMACS) WHATSNEW=$(WHATSNEW)
+
+# Targets to convert the manuals to HTML using Nikos Drakos' LaTeX to
+# HTML converter.  For more info on this program, see
+# <URL:http://cbl.leeds.ac.uk/nikos/tex2html/doc/latex2html/latex2html.html>.
+
+# Note that LaTeX2HTML inserts references to an icons directory in
+# each page that it generates.  I have placed a copy of this directory
+# in the distribution to simplify the process of creating a
+# self-contained HTML distribution; for this purpose I have also added
+# a (trivial) index.html.  Change the definition of $ICONSERVER in
+# perl/l2hinit.perl to use a different location for the icons directory.
+
+# If you have the standard LaTeX2HTML icons installed, the versions shipped
+# with this documentation should be stored in a separate directory and used
+# instead.  The standard set does *not* include all the icons used in the
+# Python documentation.
+
+$(ALLCSSFILES): html/style.css
+	cp $< $@
+
+$(INDEXFILES): $(COMMONPERL) \
+	$(PYTHON_DOC)/html/stdabout.dat $(PYTHON_DOC)/tools/node2label.pl
+
+html/acks.html: ACKS $(TOOLSDIR)/support.py $(TOOLSDIR)/mkackshtml
+	$(PYTHON) $(TOOLSDIR)/mkackshtml --address $(PYTHONDOCS) \
+		--favicon icons/pyfav.png \
+		--output html/acks.html <ACKS
+
+
+# html/index.html is dependent on $(INDEXFILES) since we want the date
+# on the front index to be updated whenever any of the child documents
+# are updated and boilerplate.tex uses \today as the date.  The index
+# files are not used to actually generate content.
+
+BOILERPLATE=commontex/boilerplate.tex
+html/index.html: $(INDEXFILES)
+html/index.html: html/index.html.in $(BOILERPLATE) tools/rewrite.py
+	$(PYTHON) tools/rewrite.py $(BOILERPLATE) \
+		RELEASE=$(RELEASE) WHATSNEW=$(WHATSNEW) \
+		<$< >$@
+
+html/modindex.html: $(TOOLSDIR)/support.py $(TOOLSDIR)/mkmodindex
+html/modindex.html: html/dist/dist.html
+html/modindex.html: html/lib/lib.html html/mac/mac.html
+	cd html && \
+	 $(PYTHON) ../$(TOOLSDIR)/mkmodindex --columns 3 \
+		--output modindex.html --address $(PYTHONDOCS) \
+		--favicon icons/pyfav.png \
+		dist/modindex.html \
+		lib/modindex.html mac/modindex.html
+
+html:	$(ALLHTMLFILES)
+
+doc: html/doc/doc.html html/doc/doc.css
+html/doc/doc.html: $(DOCFILES)
+	$(MKHTML) --dir html/doc doc/doc.tex
+
+lib: html/lib/lib.html html/lib/lib.css
+html/lib/lib.html: $(LIBFILES)
+	$(MKHTML) --dir html/lib lib/lib.tex
+
+tut: html/tut/tut.html html/tut/tut.css
+html/tut/tut.html: $(TUTFILES)
+	$(MKHTML) --dir html/tut --numeric --split 3 tut/tut.tex
+
+inst: html/inst/inst.html html/inst/inst.css
+html/inst/inst.html: $(INSTFILES) $(PYTHON_DOC)/perl/distutils.perl
+	$(MKHTML) --dir html/inst --split 4 inst/inst.tex
+
+whatsnew: html/whatsnew/$(WHATSNEW).html
+html/whatsnew/$(WHATSNEW).html: whatsnew/$(WHATSNEW).tex
+	$(MKHTML) --dir html/whatsnew --split 4 whatsnew/$(WHATSNEW).tex
+
+
+# The iSilo format is used by the iSilo document reader for PalmOS devices.
+
+ISILOINDEXFILES=
+
+$(ISILOINDEXFILES): $(COMMONPERL) html/stdabout.dat $(PYTHON_DOC)/perl/isilo.perl
+
+# webchecker needs an extra flag to process the huge index from the libref
+WEBCHECKER=$(PYTHON) ../Tools/webchecker/webchecker.py
+HTMLBASE=  file:`pwd`/html
+
+webcheck: $(ALLHTMLFILES)
+	$(WEBCHECKER) $(HTMLBASE)/api/
+	$(WEBCHECKER) $(HTMLBASE)/doc/
+	$(WEBCHECKER) $(HTMLBASE)/ext/
+	$(WEBCHECKER) -m290000 $(HTMLBASE)/lib/
+	$(WEBCHECKER) $(HTMLBASE)/mac/
+	$(WEBCHECKER) $(HTMLBASE)/ref/
+	$(WEBCHECKER) $(HTMLBASE)/tut/
+	$(WEBCHECKER) $(HTMLBASE)/dist/
+	$(WEBCHECKER) $(HTMLBASE)/inst/
+	$(WEBCHECKER) $(HTMLBASE)/whatsnew/
+
+fastwebcheck: $(ALLHTMLFILES)
+	$(WEBCHECKER) -x $(HTMLBASE)/api/
+	$(WEBCHECKER) -x $(HTMLBASE)/doc/
+	$(WEBCHECKER) -x $(HTMLBASE)/ext/
+	$(WEBCHECKER) -x -m290000 $(HTMLBASE)/lib/
+	$(WEBCHECKER) -x $(HTMLBASE)/mac/
+	$(WEBCHECKER) -x $(HTMLBASE)/ref/
+	$(WEBCHECKER) -x $(HTMLBASE)/tut/
+	$(WEBCHECKER) -x $(HTMLBASE)/dist/
+	$(WEBCHECKER) -x $(HTMLBASE)/inst/
+	$(WEBCHECKER) -x $(HTMLBASE)/whatsnew/
+
+
+# Release packaging targets:
+
+paper-$(PAPER)/README: $(PSFILES) $(TOOLSDIR)/getpagecounts
+	cd paper-$(PAPER) && ../$(TOOLSDIR)/getpagecounts -r $(RELEASE) >../$@
+
+info-$(RELEASE).tgz: info
+	cd $(INFODIR) && tar cf - README python.dir python-*.info* \
+		| gzip -9 >../$@
+
+info-$(RELEASE).tar.bz2: info
+	cd $(INFODIR) && tar cf - README python.dir python-*.info* \
+		| bzip2 -9 >../$@
+
+latex-$(RELEASE).tgz:
+	$(PYTHON) $(TOOLSDIR)/mksourcepkg --gzip $(RELEASE)
+
+latex-$(RELEASE).tar.bz2:
+	$(PYTHON) $(TOOLSDIR)/mksourcepkg --bzip2 $(RELEASE)
+
+latex-$(RELEASE).zip:
+	rm -f $@
+	$(PYTHON) $(TOOLSDIR)/mksourcepkg --zip $(RELEASE)
+
+pdf-$(PAPER)-$(RELEASE).tar: $(PDFFILES)
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/*.pdf Python-Docs-$(RELEASE)
+	tar cf $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+pdf-$(PAPER)-$(RELEASE).tgz: pdf-$(PAPER)-$(RELEASE).tar
+	gzip -9 <$? >$@
+
+pdf-$(PAPER)-$(RELEASE).tar.bz2: pdf-$(PAPER)-$(RELEASE).tar
+	bzip2 -9 <$? >$@
+
+pdf-$(PAPER)-$(RELEASE).zip: pdf
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/*.pdf Python-Docs-$(RELEASE)
+	zip -q -r -9 $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+postscript-$(PAPER)-$(RELEASE).tar: $(PSFILES) paper-$(PAPER)/README
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/*.ps Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/README Python-Docs-$(RELEASE)
+	tar cf $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+postscript-$(PAPER)-$(RELEASE).tar.bz2: postscript-$(PAPER)-$(RELEASE).tar
+	bzip2 -9 <$< >$@
+
+postscript-$(PAPER)-$(RELEASE).tgz: postscript-$(PAPER)-$(RELEASE).tar
+	gzip -9 <$< >$@
+
+postscript-$(PAPER)-$(RELEASE).zip: $(PSFILES) paper-$(PAPER)/README
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/*.ps Python-Docs-$(RELEASE)
+	cp paper-$(PAPER)/README Python-Docs-$(RELEASE)
+	zip -q -r -9 $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+HTMLPKGFILES=*.html */*.css */*.html */*.gif */*.png
+
+html-$(RELEASE).tar:	$(ALLHTMLFILES) $(HTMLCSSFILES)
+	mkdir Python-Docs-$(RELEASE)
+	-find html -name '*.gif' -size 0 | xargs rm -f
+	cd html && tar cf ../temp.tar $(HTMLPKGFILES)
+	cd Python-Docs-$(RELEASE) && tar xf ../temp.tar
+	rm temp.tar
+	tar cf html-$(RELEASE).tar Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+html-$(RELEASE).tgz:	html-$(RELEASE).tar
+	gzip -9 <$? >$@
+
+html-$(RELEASE).tar.bz2: html-$(RELEASE).tar
+	bzip2 -9 <$? >$@
+
+html-$(RELEASE).zip:	$(ALLHTMLFILES) $(HTMLCSSFILES)
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cd html && tar cf ../temp.tar $(HTMLPKGFILES)
+	cd Python-Docs-$(RELEASE) && tar xf ../temp.tar
+	rm temp.tar
+	zip -q -r -9 $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+isilo-$(RELEASE).zip:	isilo
+	rm -f $@
+	mkdir Python-Docs-$(RELEASE)
+	cp isilo/python-*.pdb Python-Docs-$(RELEASE)
+	zip -q -r -9 $@ Python-Docs-$(RELEASE)
+	rm -r Python-Docs-$(RELEASE)
+
+
+# convenience targets:
+
+tarhtml:	html-$(RELEASE).tgz
+tarinfo:	info-$(RELEASE).tgz
+tarps:		postscript-$(PAPER)-$(RELEASE).tgz
+tarpdf:		pdf-$(PAPER)-$(RELEASE).tgz
+tarlatex:	latex-$(RELEASE).tgz
+
+tarballs:	tarpdf tarps tarhtml
+
+ziphtml:	html-$(RELEASE).zip
+zipps:		postscript-$(PAPER)-$(RELEASE).zip
+zippdf:		pdf-$(PAPER)-$(RELEASE).zip
+ziplatex:	latex-$(RELEASE).zip
+
+zips:		zippdf zipps ziphtml
+
+bziphtml:	html-$(RELEASE).tar.bz2
+bzipinfo:	info-$(RELEASE).tar.bz2
+bzipps:		postscript-$(PAPER)-$(RELEASE).tar.bz2
+bzippdf:	pdf-$(PAPER)-$(RELEASE).tar.bz2
+bziplatex:	latex-$(RELEASE).tar.bz2
+
+bzips:		bzippdf bzipps bziphtml
+
+disthtml:	bziphtml ziphtml
+distinfo:	bzipinfo
+distps:		bzipps zipps
+distpdf:	bzippdf zippdf
+distlatex:	bziplatex ziplatex
+
+# We use the "pkglist" target at the end of these to ensure the
+# package list is updated after building either of these; this seems a
+# reasonable compromise between only building it for distfiles or
+# having to build it manually.  Doing it here allows the packages for
+# distribution to be built using either of
+#     make distfiles && make PAPER=a4 paperdist
+#     make paperdist && make PAPER=a4 distfiles
+# The small amount of additional work is a small price to pay for not
+# having to remember which order to do it in. ;)
+paperdist:	distpdf distps pkglist
+edist:		disthtml distinfo zipisilo pkglist
+
+# The pkglist.html file is used as part of the download.html page on
+# python.org; it is not used as intermediate input here or as part of
+# the packages created.
+pkglist:
+	$(TOOLSDIR)/mkpkglist >pkglist.html
+
+distfiles:	paperdist edist
+	$(TOOLSDIR)/mksourcepkg --bzip2 --zip $(RELEASE)
+	$(TOOLSDIR)/mkpkglist >pkglist.html
+
+
+# Housekeeping targets
+
+# Remove temporary files; all except the following:
+# - sources: .tex, .bib, .sty, *.cls
+# - useful results: .dvi, .pdf, .ps, .texi, .info
+clean:
+	-rm -f html-$(RELEASE).tar
+	-rm -f $(INDEXFILES)
+#	cd $(INFODIR) && $(MAKE) clean
+
+# Remove temporaries as well as final products
+clobber: clean
+	-rm -f html-$(RELEASE).tgz info-$(RELEASE).tgz
+	-rm -f pdf-$(RELEASE).tgz postscript-$(RELEASE).tgz
+	-rm -f latex-$(RELEASE).tgz html-$(RELEASE).zip
+	-rm -f pdf-$(RELEASE).zip postscript-$(RELEASE).zip
+	-rm -f $(DVIFILES) $(PSFILES) $(PDFFILES)
+	cd $(INFODIR) && $(MAKE) clobber
+	-rm -f paper-$(PAPER)/*.tex paper-$(PAPER)/*.ind paper-$(PAPER)/*.idx
+	-rm -f paper-$(PAPER)/*.l2h paper-$(PAPER)/*.how paper-$(PAPER)/README
+	-rm -rf html/index.html html/lib/
+
+realclean distclean:  clobber
+
+distdir: $(DISTFILES)
+	@srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; \
+	topsrcdirstrip=`echo "$(top_srcdir)" | sed 's|.|.|g'`; \
+	list='$(DISTFILES)'; for file in $$list; do \
+	  case $$file in \
+	    $(srcdir)/*) file=`echo "$$file" | sed "s|^$$srcdirstrip/||"`;; \
+	    $(top_srcdir)/*) file=`echo "$$file" | sed "s|^$$topsrcdirstrip/|$(top_builddir)/|"`;; \
+	  esac; \
+	  if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
+	  dir=`echo "$$file" | sed -e 's,/[^/]*$$,,'`; \
+	  if test "$$dir" != "$$file" && test "$$dir" != "."; then \
+	    dir="/$$dir"; \
+	    $(mkdir_p) "$(distdir)$$dir"; \
+	  else \
+	    dir=''; \
+	  fi; \
+	  if test -d $$d/$$file; then \
+	    if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
+	      cp -pR $(srcdir)/$$file $(distdir)$$dir || exit 1; \
+	    fi; \
+	    cp -pR $$d/$$file $(distdir)$$dir || exit 1; \
+	  else \
+	    test -f $(distdir)/$$file \
+	    || cp -p $$d/$$file $(distdir)/$$file \
+	    || exit 1; \
+	  fi; \
+	done

Added: sandbox/trunk/pdb/Doc/Makefile.deps
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/Makefile.deps	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,48 @@
+# -*- Makefile -*-
+# LaTeX source dependencies.
+
+COMMONSTYLES= $(PYTHON_DOC)/texinputs/python.sty \
+	$(PYTHON_DOC)/texinputs/pypaper.sty
+
+INDEXSTYLES=$(PYTHON_DOC)/texinputs/python.ist
+
+COMMONTEX=$(PTYHON_DOC)/commontex/copyright.tex \
+	$(PTYHON_DOC)/commontex/license.tex \
+	$(PTYHON_DOC)/commontex/patchlevel.tex \
+	$(PTYHON_DOC)/commontex/boilerplate.tex
+
+MANSTYLES= $(PYTHON_DOC)/texinputs/fncychap.sty \
+	$(PYTHON_DOC)/texinputs/manual.cls \
+	$(COMMONSTYLES)
+
+HOWTOSTYLES=
+APIFILES=
+
+# These files are generated from those listed above, and are used to
+# generate the typeset versions of the manuals.  The list is defined
+# here to make it easier to ensure parallelism.
+ANNOAPIFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
+	$(PTYHON_DOC)/commontex/reportingbugs.tex
+
+DOCFILES= $(HOWTOSTYLES) \
+	$(PTYHON_DOC)/commontex/boilerplate.tex \
+	$(PYTHON_DOC)/texinputs/ltxmarkup.sty \
+	doc/doc.tex
+
+EXTFILES= 
+
+TUTFILES=
+
+# LaTeX source files for the Python Reference Manual
+REFFILES=
+
+# LaTeX source files for the Python Library Reference
+LIBFILES= lib/libmpdb.tex
+
+
+# LaTeX source files for Macintosh Library Modules.
+MACFILES= 
+
+INSTFILES = 
+
+DISTFILES = 

Added: sandbox/trunk/pdb/Doc/commontex/boilerplate.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/commontex/boilerplate.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,8 @@
+\author{Revised by Matt Fleming\\
+	}
+\authoraddress{
+	Email: \email{mattjfleming at googlemail.com}
+}
+
+\date{\today}			% XXX update before final release!
+\input{patchlevel}		% include Python version information

Added: sandbox/trunk/pdb/Doc/commontex/copyright.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/commontex/copyright.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,14 @@
+Copyright \copyright{} 2001-2004 Python Software Foundation.
+All rights reserved.
+
+Copyright \copyright{} 2000 BeOpen.com.
+All rights reserved.
+
+Copyright \copyright{} 1995-2000 Corporation for National Research Initiatives.
+All rights reserved.
+
+Copyright \copyright{} 1991-1995 Stichting Mathematisch Centrum.
+All rights reserved.
+
+See the end of this document for complete license and permissions
+information.

Added: sandbox/trunk/pdb/Doc/commontex/patchlevel.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/commontex/patchlevel.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,6 @@
+% This file is generated by ../tools/getversioninfo;
+% do not edit manually.
+
+\release{2.4.2}
+\setreleaseinfo{mpdb}
+\setshortversion{2.4}

Added: sandbox/trunk/pdb/Doc/commontex/underscore.sty
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/commontex/underscore.sty	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,232 @@
+% underscore.sty     12-Oct-2001   Donald Arseneau   asnd at triumf.ca
+% Make the "_" character print as "\textunderscore" in text.
+% Copyright 1998,2001 Donald Arseneau;  Distribute freely if unchanged.
+% Instructions follow after the definitions.
+
+\ProvidesPackage{underscore}[2001/10/12]
+
+\begingroup
+ \catcode`\_=\active
+ \gdef_{% \relax % No relax gives a small vulnerability in alignments
+   \ifx\if at safe@actives\iftrue % must be outermost test!
+      \string_%
+   \else
+      \ifx\protect\@typeset at protect
+         \ifmmode \sb \else \BreakableUnderscore \fi
+      \else
+         \ifx\protect\@unexpandable at protect \noexpand_%
+         \else \protect_%
+      \fi\fi
+    \fi}
+\endgroup
+
+% At begin: set catcode; fix \long \ttdefault so I can use it in comparisons; 
+\AtBeginDocument{%
+  {\immediate\write\@auxout{\catcode\number\string`\_ \string\active}}%
+  \catcode\string`\_\string=\active
+  \edef\ttdefault{\ttdefault}%
+}
+
+\newcommand{\BreakableUnderscore}{\leavevmode\nobreak\hskip\z at skip
+ \ifx\f at family\ttdefault \string_\else \textunderscore\fi
+ \usc at dischyph\nobreak\hskip\z at skip}
+
+\DeclareRobustCommand{\_}{%
+  \ifmmode \nfss at text{\textunderscore}\else \BreakableUnderscore \fi}
+
+\let\usc at dischyph\@dischyph
+\DeclareOption{nohyphen}{\def\usc at dischyph{\discretionary{}{}{}}}
+\DeclareOption{strings}{\catcode`\_=\active}
+
+\ProcessOptions
+\ifnum\catcode`\_=\active\else \endinput \fi
+
+%%%%%%%%   Redefine commands that use character strings   %%%%%%%%
+
+\@ifundefined{UnderscoreCommands}{\let\UnderscoreCommands\@empty}{}
+\expandafter\def\expandafter\UnderscoreCommands\expandafter{%
+  \UnderscoreCommands
+  \do\include \do\includeonly
+  \do\@input \do\@iinput \do\InputIfFileExists
+  \do\ref \do\pageref \do\newlabel
+  \do\bibitem \do\@bibitem \do\cite \do\nocite \do\bibcite
+}
+
+% Macro to redefine a macro to pre-process its string argument
+% with \protect -> \string.
+\def\do#1{% Avoid double processing if user includes command twice!
+ \@ifundefined{US\string_\expandafter\@gobble\string#1}{%
+   \edef\@tempb{\meaning#1}% Check if macro is just a protection shell...
+   \def\@tempc{\protect}%
+   \edef\@tempc{\meaning\@tempc\string#1\space\space}%
+   \ifx\@tempb\@tempc % just a shell: hook into the protected inner command
+     \expandafter\do
+       \csname \expandafter\@gobble\string#1 \expandafter\endcsname
+   \else % Check if macro takes an optional argument
+     \def\@tempc{\@ifnextchar[}%
+     \edef\@tempa{\def\noexpand\@tempa####1\meaning\@tempc}%
+     \@tempa##2##3\@tempa{##2\relax}%
+     \edef\@tempb{\meaning#1\meaning\@tempc}%
+     \edef\@tempc{\noexpand\@tempd \csname
+        US\string_\expandafter\@gobble\string#1\endcsname}%
+     \if \expandafter\@tempa\@tempb \relax 12\@tempa % then no optional arg
+       \@tempc #1\US at prot
+     \else  % There is optional arg
+       \@tempc #1\US at protopt
+     \fi
+   \fi
+ }{}}
+
+\def\@tempd#1#2#3{\let#1#2\def#2{#3#1}}
+
+\def\US at prot#1#2{\let\@@protect\protect \let\protect\string
+  \edef\US at temp##1{##1{#2}}\restore at protect\US at temp#1}
+\def\US at protopt#1{\@ifnextchar[{\US at protarg#1}{\US at prot#1}}
+\def\US at protarg #1[#2]{\US at prot{{#1[#2]}}}
+
+\UnderscoreCommands
+\let\do\relax \let\@tempd\relax  % un-do
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\endinput
+
+underscore.sty    12-Oct-2001  Donald Arseneau
+
+Features:
+~~~~~~~~~
+\_ prints an underscore so that the hyphenation of constituent words
+is not affected and hyphenation is permitted after the underscore.
+For example, "compound\_fracture" hyphenates as com- pound_- frac- ture.
+If you prefer the underscore to break without a hyphen (but still with 
+the same rules for explicit hyphen-breaks) then use the [nohyphen]
+package option.
+
+A simple _  acts just like \_ in text mode, but makes a subscript in 
+math mode: activation_energy $E_a$
+
+Both forms use an underscore character if the font encoding contains
+one (e.g., "\usepackage[T1]{fontenc}" or typewriter fonts in any encoding),
+but they use a rule if the there is no proper character.
+
+Deficiencies:
+~~~~~~~~~~~~~
+The skips and penalties ruin any kerning with the underscore character
+(when a character is used).  However, there doesn't seem to be much, if
+any, such kerning in the ec fonts, and there is never any kerning with
+a rule.
+
+You must avoid "_" in file names and in cite or ref tags, or you must use 
+the babel package, with its active-character controls, or you must give 
+the [strings] option, which attempts to redefine several commands (and 
+may not work perfectly).  Even without the [strings] option or babel, you 
+can use occasional underscores like: "\include{file\string_name}".
+
+Option: [strings]
+~~~~~~~~~~~~~~~~~
+The default operation is quite simple and needs no customization; but
+you must avoid using "_" in any place where LaTeX uses an argument as
+a string of characters for some control function or as a name.  These
+include the tags for \cite and \ref, file names for \input, \include,
+and \includegraphics, environment names, counter names, and placement
+parameters (like "[t]").  The problem with these contexts is that they
+are `moving arguments' but LaTeX does not `switch on' the \protect
+mechanism for them.
+
+If you need to use the underscore character in these places, the package
+option [strings] is provided to redefine commands taking a string argument
+so that the argument is protected (with \protect -> \string).  The list
+of commands is given in "\UnderscoreCommands", with "\do" before each,
+covering \cite, \ref, \input, and their variants.  Not included are many
+commands regarding font names, everything with counter names, environment
+names, page styles, and versions of \ref and \cite defined by external
+packages (e.g. \vref and \citeyear).
+
+You can add to the list of supported commands by defining \UnderscoreCommands
+before loading this package; e.g.
+
+   \usepackage{chicago}
+   \newcommand{\UnderscoreCommands}{%   (\cite already done)
+     \do\citeNP \do\citeA \do\citeANP \do\citeN \do\shortcite
+     \do\shortciteNP \do\shortciteA \do\shortciteANP \do\shortciteN
+     \do\citeyear \do\citeyearNP
+   }
+   \usepackage[strings]{underscore}
+
+Not all commands can be supported this way!  Only commands that take a
+string argument *first* can be protected.  One optional argument before
+the string argument is also permitted, as exemplified by \cite: both
+\cite{tags} and \cite[text]{tags} are allowed.  A command like
+\@addtoreset which takes two counter names as arguments could not
+be protected by adding it to \UnderscoreCommands.
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! When you use the [strings] option, you must load this package !!
+!! last (or nearly last).                                        !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+There are two reasons: 1) The redefinitions done for protection must come
+after other packages define their customized versions of those commands.
+2) The [strings] option requires the _ character to be activated immediately
+in order for the cite and ref tags to be read properly from the .aux file
+as plain strings, and this catcode setting might disrupt other packages.
+
+The babel package implements a protection mechanism for many commands,
+and will be a complete fix for most documents without the [strings] option.
+Many add-on packages are compatible with babel, so they will get the
+strings protection also.  However, there are several commands that are 
+not covered by babel, but can easily be supported by the [strings] and 
+\UnderscoreCommands mechanism.  Beware that using both [strings] and babel 
+may lead to conflicts, but does appear to work (load babel last).
+
+Implementation Notes:
+~~~~~~~~~~~~~~~~~~~~~
+The first setting of "_" to be an active character is performed in a local
+group so as to not interfere with other packages.  The catcode setting
+is repeated with \AtBeginDocument so the definition is in effect for the
+text.  However, the catcode setting is repeated immediately when the
+[strings] option is detected.
+
+The definition of the active "_" is essentially:
+       \ifmmode \sb \else \BreakableUnderscore \fi
+where "\sb" retains the normal subscript meaning of "_" and where
+"\BreakableUnderscore" is essentially "\_".  The rest of the definition
+handles the "\protect"ion without causing \relax to be inserted before
+the character.
+
+\BreakableUnderscore uses "\nobreak\hskip\z at skip" to separate the
+underscore from surrounding words, thus allowing TeX to hyphenate them,
+but preventing free breaks around the underscore. Next, it checks the
+current font family, and uses the underscore character from tt fonts or
+otherwise \textunderscore (which is a character or rule depending on
+the font encoding).  After the underscore, it inserts a discretionary
+hyphenation point as "\usc at dischyph", which is usually just "\-"
+except that it still works in the tabbing environment, although it
+will give "\discretionary{}{}{}" under the [nohyphen] option.  After
+that, another piece of non-breaking interword glue is inserted. 
+Ordinarily, the comparison "\ifx\f at family\ttdefault" will always fail 
+because \ttdefault is `long' where \f at family is not (boooo hisss), but 
+\ttdefault is redefined to be non-long by "\AtBeginDocument".
+
+The "\_" command is then defined to use "\BreakableUnderscore".
+
+If the [strings] option is not given, then that is all!
+
+Under the [strings] option, the list of special commands is processed to:
+- retain the original command as \US_command (\US_ref)
+- redefine the command as \US at prot\US_command for ordinary commands
+  (\ref -> \US at prot\US_ref) or as \US at protopt\US_command when an optional
+  argument is possible (\bibitem -> \US at protopt\US_bibitem).
+- self-protecting commands (\cite) retain their self-protection.
+Diagnosing the state of the pre-existing command is done by painful
+contortions involving \meaning.
+
+\US at prot and \US at protopt read the argument, process it with \protect
+enabled, then invoke the saved \US_command.
+
+Modifications:
+~~~~~~~~~~~~~~
+12-Oct-2001  Babel (safe at actives) compatibility and [nohyphen] option.
+
+Test file integrity:  ASCII 32-57, 58-126:  !"#$%&'()*+,-./0123456789
+:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Added: sandbox/trunk/pdb/Doc/html/icons/blank.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/blank.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/contents.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/contents.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/index.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/index.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/modules.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/modules.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/next.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/next.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/previous.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/previous.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/pyfav.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/pyfav.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/up.gif
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/icons/up.png
==============================================================================
Binary file. No diff available.

Added: sandbox/trunk/pdb/Doc/html/stdabout.dat
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/html/stdabout.dat	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,45 @@
+<-- -*- HTML -*->
+<p> This document was generated using the <a
+    href="http://saftsack.fs.uni-bayreuth.de/;SPMtilde;latex2ht/">
+    <strong>LaTeX</strong>2<tt>HTML</tt></a> translator.
+</p>
+
+<p> <a
+    href="http://saftsack.fs.uni-bayreuth.de/;SPMtilde;latex2ht/">
+    <strong>LaTeX</strong>2<tt>HTML</tt></a> is Copyright &copy;
+  1993, 1994, 1995, 1996, 1997, <a
+    href="http://cbl.leeds.ac.uk/nikos/personal.html">Nikos
+    Drakos</a>, Computer Based Learning Unit, University of
+  Leeds, and Copyright &copy; 1997, 1998, <a
+    href="http://www.maths.mq.edu.au/;SPMtilde;ross/">Ross
+    Moore</a>, Mathematics Department, Macquarie University,
+  Sydney.
+</p>
+
+<p> The application of <a
+    href="http://saftsack.fs.uni-bayreuth.de/;SPMtilde;latex2ht/">
+    <strong>LaTeX</strong>2<tt>HTML</tt></a> to the Python
+  documentation has been heavily tailored by Fred L. Drake,
+  Jr.  Original navigation icons were contributed by Christopher
+  Petrilli.
+</p>
+
+<hr>
+
+<h2>Comments and Questions</h2>
+
+<p> General comments and questions regarding this document should
+  be sent by email to <a
+href="mailto:mattjfleming at googlemail.com">mattjfleming at googlemail.com</a>.
+
+<p>
+  If you are able to provide suggested text, either to replace
+  existing incorrect or unclear material, or additional text to
+  supplement what's already available, we'd appreciate the
+  contribution.  There's no need to worry about text markup; our
+  documentation team will gladly take care of that.
+</p>
+
+<p> For any of these channels, please be sure not to send HTML email.
+  Thanks.
+</p>

Added: sandbox/trunk/pdb/Doc/html/style.css
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/html/style.css	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,243 @@
+/*
+ * The first part of this is the standard CSS generated by LaTeX2HTML,
+ * with the "empty" declarations removed.
+ */
+
+/* Century Schoolbook font is very similar to Computer Modern Math: cmmi */
+.math                   { font-family: "Century Schoolbook", serif; }
+.math i                 { font-family: "Century Schoolbook", serif;
+                          font-weight: bold }
+.boldmath               { font-family: "Century Schoolbook", serif;
+                          font-weight: bold }
+
+/*
+ * Implement both fixed-size and relative sizes.
+ *
+ * I think these can be safely removed, as it doesn't appear that
+ * LaTeX2HTML ever generates these, even though these are carried
+ * over from the LaTeX2HTML stylesheet.
+ */
+small.xtiny             { font-size : xx-small; }
+small.tiny              { font-size : x-small; }
+small.scriptsize        { font-size : smaller; }
+small.footnotesize      { font-size : small; }
+big.xlarge              { font-size : large; }
+big.xxlarge             { font-size : x-large; }
+big.huge                { font-size : larger; }
+big.xhuge               { font-size : xx-large; }
+
+/*
+ * Document-specific styles come next;
+ * these are added for the Python documentation.
+ *
+ * Note that the size specifications for the H* elements are because
+ * Netscape on Solaris otherwise doesn't get it right; they all end up
+ * the normal text size.
+ */
+
+body                    { color: #000000;
+                          background-color: #ffffff; }
+
+a:link:active           { color: #ff0000; }
+a:link:hover            { background-color: #bbeeff; }
+a:visited:hover         { background-color: #bbeeff; }
+a:visited               { color: #551a8b; }
+a:link                  { color: #0000bb; }
+
+h1, h2, h3, h4, h5, h6  { font-family: avantgarde, sans-serif;
+                          font-weight: bold; }
+h1                      { font-size: 180%; }
+h2                      { font-size: 150%; }
+h3, h4                  { font-size: 120%; }
+
+/* These are section titles used in navigation links, so make sure we
+ * match the section header font here, even it not the weight.
+ */
+.sectref                { font-family: avantgarde, sans-serif; }
+/* And the label before the titles in navigation: */
+.navlabel               { font-size: 85%; }
+
+
+/* LaTeX2HTML insists on inserting <br> elements into headers which
+ * are marked with \label.  This little bit of CSS magic ensures that
+ * these elements don't cause spurious whitespace to be added.
+ */
+h1>br, h2>br, h3>br,
+h4>br, h5>br, h6>br     { display: none; }
+
+code, tt                { font-family: "lucida typewriter", lucidatypewriter,
+                                       monospace; }
+var                     { font-family: times, serif;
+                          font-style: italic;
+                          font-weight: normal; }
+
+.Unix                   { font-variant: small-caps; }
+
+.typelabel              { font-family: lucida, sans-serif; }
+
+.navigation td          { background-color: #99ccff;
+                          font-weight: bold;
+                          font-family: avantgarde, sans-serif;
+                          font-size: 110%; }
+
+div.warning             { background-color: #fffaf0;
+                          border: thin solid black;
+                          padding: 1em;
+                          margin-left: 2em;
+                          margin-right: 2em; }
+
+div.warning .label      { font-family: sans-serif;
+                          font-size: 110%;
+                          margin-right: 0.5em; }
+
+div.note                { background-color: #fffaf0;
+                          border: thin solid black;
+                          padding: 1em;
+                          margin-left: 2em;
+                          margin-right: 2em; }
+
+div.note .label         { margin-right: 0.5em;
+                          font-family: sans-serif; }
+
+address                 { font-size: 80%; }
+.release-info           { font-style: italic;
+                          font-size: 80%; }
+
+.titlegraphic           { vertical-align: top; }
+
+.verbatim pre           { color: #00008b;
+                          font-family: "lucida typewriter", lucidatypewriter,
+                                       monospace;
+                          font-size: 90%; }
+.verbatim               { margin-left: 2em; }
+.verbatim .footer       { padding: 0.05in;
+                          font-size: 85%;
+                          background-color: #99ccff;
+                          margin-right: 0.5in; }
+
+.grammar                { background-color: #99ccff;
+                          margin-right: 0.5in;
+                          padding: 0.05in; }
+.grammar-footer         { padding: 0.05in;
+                          font-size: 85%; }
+.grammartoken           { font-family: "lucida typewriter", lucidatypewriter,
+                                       monospace; }
+
+.productions                  { background-color: #bbeeff; }
+.productions a:active         { color: #ff0000; }
+.productions a:link:hover     { background-color: #99ccff; }
+.productions a:visited:hover  { background-color: #99ccff; }
+.productions a:visited        { color: #551a8b; }
+.productions a:link           { color: #0000bb; }
+.productions table            { vertical-align: baseline;
+                                empty-cells: show; }
+.productions > table td,
+.productions > table th       { padding: 2px; }
+.productions > table td:first-child,
+.productions > table td:last-child {
+                                font-family: "lucida typewriter",
+                                             lucidatypewriter,
+                                             monospace;
+                                }
+/* same as the second selector above, but expressed differently for Opera */
+.productions > table td:first-child + td + td {
+                                font-family: "lucida typewriter",
+                                             lucidatypewriter,
+                                             monospace;
+                                vertical-align: baseline;
+                                }
+.productions > table td:first-child + td {
+                                padding-left: 1em;
+                                padding-right: 1em;
+                                }
+.productions > table tr       { vertical-align: baseline; }
+
+.email                  { font-family: avantgarde, sans-serif; }
+.mailheader             { font-family: avantgarde, sans-serif; }
+.mimetype               { font-family: avantgarde, sans-serif; }
+.newsgroup              { font-family: avantgarde, sans-serif; }
+.url                    { font-family: avantgarde, sans-serif; }
+.file                   { font-family: avantgarde, sans-serif; }
+.guilabel               { font-family: avantgarde, sans-serif; }
+
+.realtable              { border-collapse: collapse;
+                          border-color: black;
+                          border-style: solid;
+                          border-width: 0px 0px 2px 0px;
+                          empty-cells: show;
+                          margin-left: auto;
+                          margin-right: auto;
+                          padding-left: 0.4em;
+                          padding-right: 0.4em;
+                          }
+.realtable tbody        { vertical-align: baseline; }
+.realtable tfoot        { display: table-footer-group; }
+.realtable thead        { background-color: #99ccff;
+                          border-width: 0px 0px 2px 1px;
+                          display: table-header-group;
+                          font-family: avantgarde, sans-serif;
+                          font-weight: bold;
+                          vertical-align: baseline;
+                          }
+.realtable thead :first-child {
+                          border-width: 0px 0px 2px 0px;
+                          }
+.realtable thead th     { border-width: 0px 0px 2px 1px }
+.realtable td,
+.realtable th           { border-color: black;
+                          border-style: solid;
+                          border-width: 0px 0px 1px 1px;
+                          padding-left: 0.4em;
+                          padding-right: 0.4em;
+                          }
+.realtable td:first-child,
+.realtable th:first-child {
+                          border-left-width: 0px;
+                          vertical-align: baseline;
+                          }
+.center                 { text-align: center; }
+.left                   { text-align: left; }
+.right                  { text-align: right; }
+
+.refcount-info          { font-style: italic; }
+.refcount-info .value   { font-weight: bold;
+                          color: #006600; }
+
+/*
+ * Some decoration for the "See also:" blocks, in part inspired by some of
+ * the styling on Lars Marius Garshol's XSA pages.
+ * (The blue in the navigation bars is #99CCFF.)
+ */
+.seealso                { background-color: #fffaf0;
+                          border: thin solid black;
+                          padding: 0pt 1em 4pt 1em; }
+
+.seealso > .heading     { font-size: 110%;
+                          font-weight: bold; }
+
+/*
+ * Class 'availability' is used for module availability statements at
+ * the top of modules.
+ */
+.availability .platform { font-weight: bold; }
+
+
+/*
+ * Additional styles for the distutils package.
+ */
+.du-command             { font-family: monospace; }
+.du-option              { font-family: avantgarde, sans-serif; }
+.du-filevar             { font-family: avantgarde, sans-serif;
+                          font-style: italic; }
+.du-xxx:before          { content: "** ";
+                          font-weight: bold; }
+.du-xxx:after           { content: " **";
+                          font-weight: bold; }
+
+
+/*
+ * Some specialization for printed output.
+ */
+ at media print {
+  .online-navigation    { display: none; }
+  }

Added: sandbox/trunk/pdb/Doc/info/Makefile
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/info/Makefile	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,44 @@
+# Generate the Python "info" documentation.
+
+TOPDIR=..
+TOOLSDIR=$(TOPDIR)/tools
+HTMLDIR=$(TOPDIR)/html
+
+# The emacs binary used to build the info docs. GNU Emacs 21 is required.
+EMACS=emacs
+
+MKINFO=$(TOOLSDIR)/mkinfo
+SCRIPTS=$(TOOLSDIR)/checkargs.pm $(TOOLSDIR)/mkinfo $(TOOLSDIR)/py2texi.el
+
+# set VERSION to code the VERSION number into the info file name
+# allowing installation of more than one set of python info docs
+# into the same directory
+VERSION=
+
+all:	check-emacs-version \
+	lib
+#	doc inst
+
+lib:	python$(VERSION)-lib.info
+
+whatsnew:	$(WHATSNEW)
+$(WHATSNEW):	python$(VERSION)-$(WHATSNEW).info
+
+check-emacs-version:
+	@v="`$(EMACS) --version 2>&1 | egrep '^(GNU |X)Emacs [12]*'`"; \
+	if `echo "$$v" | grep '^GNU Emacs 21' >/dev/null 2>&1`; then \
+	  echo "Using $(EMACS) to build the info docs"; \
+	else \
+	  echo "GNU Emacs 21 is required to build the info docs"; \
+	  echo "Found $$v"; \
+	  false; \
+	fi
+
+python$(VERSION)-lib.info:	../lib/lib.tex $(SCRIPTS)
+	EMACS=$(EMACS) $(MKINFO) $< $*.texi $@
+
+clean:
+	rm -f *.texi~ *.texi
+
+clobber: clean
+	rm -f *.texi python*-*.info python*-*.info-[0-9]*

Added: sandbox/trunk/pdb/Doc/lib/Makefile
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/lib/Makefile	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,7 @@
+#=============================================================
+# $Id: Makefile,v 1.1 2006/01/28 10:50:36 rockyb Exp $
+#=============================================================
+# Whatever it is you want to do, it should be handled by the 
+# by the main (parent) Makefile. So reissue make from there.
+all %:
+	$(MAKE) -C .. $@

Added: sandbox/trunk/pdb/Doc/lib/lib-ds.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/lib/lib-ds.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,54 @@
+\documentclass{manual}
+
+% NOTE: this file controls which chapters/sections of the library
+% manual are actually printed.  It is easy to customize your manual
+% by commenting out sections that you're not interested in.
+
+\title{Python Library Reference for the Improved Python Debugger}
+
+\input{boilerplate}
+
+\makeindex                      % tell \index to actually write the
+                                % .idx file
+\makemodindex                   % ... and the module index as well.
+
+ 
+\begin{document}
+
+\maketitle
+
+\ifhtml
+\chapter*{Front Matter\label{front}}
+\fi
+
+\input{copyright}
+
+\begin{abstract}
+
+\noindent
+Python is an extensible, interpreted, object-oriented programming
+language.  It supports a wide range of applications, from simple text
+processing scripts to interactive Web browsers.
+
+We describe here only the Improved Python Debugger. The rest of the The
+\ulink{\module{Python Reference Manual}}
+{http://docs.python.org/lib/lib.html} should be consulted for other
+standard Python modules including the original \ulink{\module{Python
+Debugger}}{http://docs.python.org/lib/module-pdb.html} (\tt{pdb.py}).
+
+\end{abstract}
+
+\tableofcontents
+
+                                % Chapter title:
+
+% =============
+% DEVELOPMENT TOOLS
+% =============
+%                                % Software development support
+
+\renewcommand{\baselinestretch}{3.0}\normalsize
+\input{libmpdb}                  % The Python Debugger
+
+
+\end{document}

Added: sandbox/trunk/pdb/Doc/lib/lib.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/lib/lib.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,57 @@
+\documentclass{manual}
+
+% NOTE: this file controls which chapters/sections of the library
+% manual are actually printed.  It is easy to customize your manual
+% by commenting out sections that you're not interested in.
+
+\title{Python Library Reference for The Improved Python Debugger}
+
+\input{boilerplate}
+
+\makeindex                      % tell \index to actually write the
+                                % .idx file
+\makemodindex                   % ... and the module index as well.
+
+ 
+\begin{document}
+
+\maketitle
+
+\ifhtml
+\chapter*{Front Matter\label{front}}
+\fi
+
+\input{copyright}
+
+\begin{abstract}
+
+\noindent
+Python is an extensible, interpreted, object-oriented programming
+language.  It supports a wide range of applications, from simple text
+processing scripts to interactive Web browsers.
+
+We describe here only the Improved Python Debugger. The rest of the The
+\ulink{\module{Python Reference Manual}}
+{http://docs.python.org/lib/lib.html} should be consulted for other
+standard Python modules including the original \ulink{\module{Python
+Debugger}}{http://docs.python.org/lib/module-pdb.html} (\tt{pdb.py}).
+
+\end{abstract}
+
+\tableofcontents
+
+                                % Chapter title:
+
+% =============
+% DEVELOPMENT TOOLS
+% =============
+%                                % Software development support
+
+\input{libmpdb}                  % The Python Debugger
+
+%begin{latexonly}
+\renewcommand{\indexname}{Index}
+%end{latexonly}
+\input{lib.ind}                 % Index
+
+\end{document}

Added: sandbox/trunk/pdb/Doc/lib/libmpdb.tex
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/lib/libmpdb.tex	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,81 @@
+\chapter{The Improved Python Debugger \label{chapter-mpdb}}
+
+\declaremodule{}{mpdb}			% not standard, in Python
+
+\platform{Unix, Windows}
+
+
+\moduleauthor{Matt Fleming}{mattjfleming at googlemail.com}
+
+\sectionauthor{Matt Fleming}{mattjfleming at googlemail.com}
+
+
+
+% Leave at least one blank line after this, to simplify ad-hoc tools
+% that are sometimes used to massage these files.
+\modulesynopsis{An Improved Python Debugger}
+
+
+This module is a Goolge Summer Of Code project undertaken in the summer of 
+2006 by Matt Fleming.
+The \module{mpdb} module defines operations for debugging programs remotely,
+debugging threaded programs and debugging separate processes. It builds on the
+work done by Rocky Bernstein in his Extended Python Debugger (\module{Pydb}), which 
+in turn, builds upon the Python Debugger that is part of the Python 
+Standard Library. Rocky also kindly agreed to mentor this project.
+
+
+
+The \module{mpdb} module defines the following functions:
+
+
+\begin{funcdesc}{pdbserver}{address\optional{, mpdb}}
+Setup a pdbserver at \var{address} that will allows debuggers to
+connect to this debugging session. \var{address} should be of the form
+ \code{'protocol procotol-specific-address'}. For example, to use TCP at host
+'myhost' and port '8765', \var{address} would be \code{'tcp myhost:8765'}.
+To connect to a serial device \var{address} might be \code{'serial /dev/ttyC0'}.
+The optional argument \var{mpdb} is an \class{MPdb} instance to use
+for this pdbserver. If \var{mpdb} is ommitted, a new \class{MPdb} instance
+is created.
+\end{funcdesc}
+
+\begin{funcdesc}{target}{address}
+Connect to a pdbserver at \var{address}. \var{address} should use the same
+format as \function{pdbserver}.
+\end{funcdesc}
+
+\begin{excdesc}{Exit}
+Exception raised when the debugger is going to immediately exit.
+\end{excdesc}
+
+\section{MPdb Class}
+\label{mpdb-class}
+
+MPdb objects have the following methods:
+
+\begin{methoddesc}[mpdb]{remote_onecmd}{self, line}
+This method is used by an \class{MPdb} instance that is connected
+to a remote machine. Instead of the debugger instance interpreting commands,
+all commands are sent directly to the remote machine where they are 
+interpreted, executed and the results are sent back to the client.
+\end{methoddesc}
+
+\begin{methoddesc}[mpdb]{do_pdbserver}{self, addr}
+Setup a pdbserver at \var{addr} and wait for incoming connections. \var{addr}
+must be string containing a protocol to use and a protocol-specific address.
+\end{methoddesc}
+
+\section{Thread Debugging}
+\label{thread-debug}
+This section provides information on Python's thread debugging facilities and
+how \module{mpdb} makes use of them.
+
+\section{Remote Debugging}
+This section describes how \module{mpdb} handles debugging remotely.
+\label{remote-debug}
+
+\section{External Process Debugging}
+This section describes how \module{mpdb} debugs processes that are external
+to the process in which \module{mpdb} is being run.
+\label{proc-debug}
\ No newline at end of file

Added: sandbox/trunk/pdb/Doc/perl/SynopsisTable.pm
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/perl/SynopsisTable.pm	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,95 @@
+package SynopsisTable;
+
+sub new{
+    return bless {names=>'', info=>{}, file=>''};
+}
+
+sub declare{
+    my($self,$name,$key,$type) = @_;
+    if ($self->{names}) {
+        $self->{names} .= ",$name";
+    }
+    else {
+        $self->{names} .= "$name";
+    }
+    $self->{info}{$name} = "$key,$type,";
+}
+
+# The 'file' attribute is used to store the filename of the node in which
+# the table will be presented; this assumes that each table will be presented
+# only once, which works for the current use of this object.
+
+sub set_file{
+    my($self, $filename) = @_;
+    $self->{file} = "$filename";
+}
+
+sub get_file{
+    my $self = shift;
+    return $self->{file};
+}
+
+sub set_synopsis{
+    my($self,$name,$synopsis) = @_;
+    my($key,$type,$unused) = split ',', $self->{info}{$name}, 3;
+    $self->{info}{$name} = "$key,$type,$synopsis";
+}
+
+sub get{
+    my($self,$name) = @_;
+    return split /,/, $self->{info}{$name}, 3;
+}
+
+sub show{
+    my $self = shift;
+    my $name;
+    print "names: ", $self->{names}, "\n\n";
+    foreach $name (split /,/, $self->{names}) {
+        my($key,$type,$synopsis) = $self->get($name);
+        print "$name($key) is $type: $synopsis\n";
+    }
+}
+
+sub tohtml{
+    my $self = shift;
+    my $oddrow = 1;
+    my $data = "<table class='synopsistable' valign='baseline'>\n";
+    my $name;
+    foreach $name (split /,/, $self->{names}) {
+        my($key,$type,$synopsis) = $self->get($name);
+        my $link = "<a href='module-$key.html'>";
+        $synopsis =~ s/<tex2html_percent_mark>/%/g;
+        $synopsis =~ s/<tex2html_ampersand_mark>/\&amp;/g;
+        $data .= ('  <tr'
+                  . ($oddrow ? " class='oddrow'>\n      " : '>')
+                  . "<td><b><tt class='module'>$link$name</a></tt></b></td>\n"
+                  . "      <td>\&nbsp;</td>\n"
+                  . "      <td class='synopsis'>$synopsis</td></tr>\n");
+        $oddrow = !$oddrow;
+    }
+    $data .= "</table>\n";
+    $data;
+}
+
+
+package testSynopsisTable;
+
+sub test{
+    # this little test is mostly to debug the stuff above, since this is
+    # my first Perl "object".
+    my $st = SynopsisTable->new();
+    $st->declare("sample", "sample", "standard");
+    $st->set_synopsis("sample", "This is a little synopsis....");
+    $st->declare("copy_reg", "copyreg", "standard");
+    $st->set_synopsis("copy_reg", "pickle support stuff");
+    $st->show();
+
+    print "\n\n";
+
+    my $st2 = SynopsisTable->new();
+    $st2->declare("st2module", "st2module", "built-in");
+    $st2->set_synopsis("st2module", "silly little synopsis");
+    $st2->show();
+}
+
+1;      # This must be the last line -- Perl is bogus!

Added: sandbox/trunk/pdb/Doc/perl/l2hinit.perl
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/perl/l2hinit.perl	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,784 @@
+# LaTeX2HTML support base for use with Python documentation.
+
+package main;
+
+use L2hos;
+
+$HTML_VERSION = 4.0;
+
+$MAX_LINK_DEPTH = 2;
+$ADDRESS = '';
+
+$NO_FOOTNODE = 1;
+$NUMBERED_FOOTNOTES = 1;
+
+# Python documentation uses section numbers to support references to match
+# in the printed and online versions.
+#
+$SHOW_SECTION_NUMBERS = 1;
+
+$ICONSERVER = '.';
+$IMAGE_TYPE = 'gif';
+
+# Control where the navigation bars should show up:
+$TOP_NAVIGATION = 1;
+$BOTTOM_NAVIGATION = 1;
+$AUTO_NAVIGATION = 0;
+
+$BODYTEXT = '';
+$CHILDLINE = "\n<p><br /></p><hr class='online-navigation' />\n";
+$VERBOSITY = 0;
+
+# default # of columns for the indexes
+$INDEX_COLUMNS = 2;
+$MODULE_INDEX_COLUMNS = 4;
+
+$HAVE_MODULE_INDEX = 0;
+$HAVE_GENERAL_INDEX = 0;
+$HAVE_TABLE_OF_CONTENTS = 0;
+
+$AESOP_META_TYPE = 'information';
+
+
+# A little painful, but lets us clean up the top level directory a little,
+# and not be tied to the current directory (as far as I can tell).  Testing
+# an existing definition of $mydir is needed since it cannot be computed when
+# run under mkhowto with recent versions of LaTeX2HTML, since this file is
+# not read directly by LaTeX2HTML any more.  mkhowto is required to prepend
+# the required definition at the top of the actual input file.
+#
+if (!defined $mydir) {
+    use Cwd;
+    use File::Basename;
+    ($myname, $mydir, $myext) = fileparse(__FILE__, '\..*');
+    chop $mydir;                        # remove trailing '/'
+    $mydir = getcwd() . "$dd$mydir"
+        unless $mydir =~ s|^/|/|;
+}
+$LATEX2HTMLSTYLES = "$mydir$envkey$LATEX2HTMLSTYLES";
+push (@INC, $mydir);
+
+($myrootname, $myrootdir, $myext) = fileparse($mydir, '\..*');
+chop $myrootdir;
+
+
+# Hackish way to get the appropriate paper-*/ directory into $TEXINPUTS;
+# pass in the paper size (a4 or letter) as the environment variable PAPER
+# to add the right directory.  If not given, the current directory is
+# added instead for use with HOWTO processing.
+#
+if (defined $ENV{'PAPER'}) {
+    $mytexinputs = "$myrootdir${dd}paper-$ENV{'PAPER'}$envkey";
+}
+else {
+    $mytexinputs = getcwd() . $envkey;
+}
+$mytexinputs .= "$myrootdir${dd}texinputs";
+
+
+# Change this variable to change the text added in "About this document...";
+# this should be an absolute pathname to get it right.
+#
+$ABOUT_FILE = "$myrootdir${dd}html${dd}stdabout.dat";
+
+
+sub custom_driver_hook {
+    #
+    # This adds the directory of the main input file to $TEXINPUTS; it
+    # seems to be sufficiently general that it should be fine for HOWTO
+    # processing.
+    #
+    # XXX This still isn't quite right; we should actually be inserting
+    # $mytexinputs just before any empty entry in TEXINPUTS is one
+    # exists instead of just concatenating the pieces like we do here.
+    #
+    my $file = $_[0];
+    my($jobname, $dir, $ext) = fileparse($file, '\..*');
+    $dir = L2hos->Make_directory_absolute($dir);
+    $dir =~ s/$dd$//;
+    $TEXINPUTS = "$dir$envkey$mytexinputs";
+    # Push everything into $TEXINPUTS since LaTeX2HTML doesn't pick
+    # this up on its own; we clear $ENV{'TEXINPUTS'} so the value set
+    # for this by the main LaTeX2HTML script doesn't contain duplicate
+    # directories.
+    if ($ENV{'TEXINPUTS'}) {
+        $TEXINPUTS .= "$envkey$ENV{'TEXINPUTS'}";
+        $ENV{'TEXINPUTS'} = undef;
+    }
+    print "\nSetting \$TEXINPUTS to $TEXINPUTS\n";
+}
+
+
+# $CUSTOM_BUTTONS is only used for the module index link.
+$CUSTOM_BUTTONS = '';
+
+sub make_nav_sectref($$$) {
+    my($label, $linktype, $title) = @_;
+    if ($title) {
+        if ($title =~ /\<[aA] /) {
+            $title =~ s/\<[aA] /<a class="sectref" rel="$linktype" /;
+            $title =~ s/ HREF=/ href=/;
+        }
+        else {
+            $title = "<span class=\"sectref\">$title</span>";
+        }
+        return "<b class=\"navlabel\">$label:</b>\n$title\n";
+    }
+    return '';
+}
+
+ at my_icon_tags = ();
+$my_icon_tags{'next'} = 'Next Page';
+$my_icon_tags{'next_page'} = 'Next Page';
+$my_icon_tags{'previous'} = 'Previous Page';
+$my_icon_tags{'previous_page'} = 'Previous Page';
+$my_icon_tags{'up'} = 'Up One Level';
+$my_icon_tags{'contents'} = 'Contents';
+$my_icon_tags{'index'} = 'Index';
+$my_icon_tags{'modules'} = 'Module Index';
+
+ at my_icon_names = ();
+$my_icon_names{'previous_page'} = 'previous';
+$my_icon_names{'next_page'} = 'next';
+
+sub get_my_icon($) {
+    my $name = $_[0];
+    my $text = $my_icon_tags{$name};
+    if ($my_icon_names{$name}) {
+        $name = $my_icon_names{$name};
+    }
+    if ($text eq '') {
+        $name = 'blank';
+    }
+    my $iconserver = ($ICONSERVER eq '.') ? '' : "$ICONSERVER/";
+    return "<img src='$iconserver$name.$IMAGE_TYPE'\n  border='0'"
+           . " height='32'  alt='$text' width='32' />";
+}
+
+sub unlinkify($) {
+    my $text = "$_[0]";
+    $text =~ s|</[aA]>||;
+    $text =~ s|<a\s+[^>]*>||i;
+    return $text;
+}
+
+sub use_icon($$$) {
+    my($rel,$str,$title) = @_;
+    if ($str) {
+        my $s = "$str";
+        if ($s =~ /\<tex2html_([a-z_]+)_visible_mark\>/) {
+            my $r = get_my_icon($1);
+            $s =~ s/\<tex2html_[a-z_]+_visible_mark\>/$r/;
+        }
+        $s =~ s/<[aA] /<a rel="$rel" title="$title"\n  /;
+        $s =~ s/ HREF=/ href=/;
+        return $s;
+    }
+    else {
+        return get_my_icon('blank');
+    }
+}
+
+sub make_nav_panel() {
+    my $s;
+    # new iconic         rel         iconic     page title
+    my $next     = use_icon('next',     $NEXT,     unlinkify($NEXT_TITLE));
+    my $up       = use_icon('parent',   $UP,       unlinkify($UP_TITLE));
+    my $previous = use_icon('prev',     $PREVIOUS, unlinkify($PREVIOUS_TITLE));
+    my $contents = use_icon('contents', $CONTENTS, 'Table of Contents');
+    my $index    = use_icon('index',    $INDEX,    'Index');
+    if (!$CUSTOM_BUTTONS) {
+        $CUSTOM_BUTTONS = get_my_icon('blank');
+    }
+    $s = ('<table align="center" width="100%" cellpadding="0" cellspacing="2">'
+          . "\n<tr>"
+          # left-hand side
+          . "\n<td class='online-navigation'>$previous</td>"
+          . "\n<td class='online-navigation'>$up</td>"
+          . "\n<td class='online-navigation'>$next</td>"
+          # title box
+          . "\n<td align=\"center\" width=\"100%\">$t_title</td>"
+          # right-hand side
+          . "\n<td class='online-navigation'>$contents</td>"
+          # module index
+          . "\n<td class='online-navigation'>$CUSTOM_BUTTONS</td>"
+          . "\n<td class='online-navigation'>$index</td>"
+          . "\n</tr></table>\n"
+          # textual navigation
+          . "<div class='online-navigation'>\n"
+          . make_nav_sectref("Previous", "prev", $PREVIOUS_TITLE)
+          . make_nav_sectref("Up", "parent", $UP_TITLE)
+          . make_nav_sectref("Next", "next", $NEXT_TITLE)
+          . "</div>\n"
+          );
+    # remove these; they are unnecessary and cause errors from validation
+    $s =~ s/ NAME="tex2html\d+"\n */ /g;
+    return $s;
+}
+
+sub add_child_links {
+    my $toc = add_real_child_links(@_);
+    $toc =~ s|\s*</[aA]>|</a>|g;
+    $toc =~ s/ NAME=\"tex2html\d+\"\s*href=/ href=/gi;
+    $toc =~ s|</UL>(\s*<BR( /)?>)?|</ul>|gi;
+    if ($toc =~ / NAME=["']CHILD_LINKS["']/) {
+        return "<div class='online-navigation'>\n$toc</div>\n";
+    }
+    return $toc;
+}
+
+sub get_version_text() {
+    if ($PACKAGE_VERSION ne '' && $t_date) {
+        return ("<span class=\"release-info\">"
+                . "Release $PACKAGE_VERSION$RELEASE_INFO,"
+                . " documentation updated on $t_date.</span>");
+    }
+    if ($PACKAGE_VERSION ne '') {
+        return ("<span class=\"release-info\">"
+                . "Release $PACKAGE_VERSION$RELEASE_INFO.</span>");
+    }
+    if ($t_date) {
+        return ("<span class=\"release-info\">Documentation released on "
+                . "$t_date.</span>");
+    }
+    return '';
+}
+
+
+sub top_navigation_panel() {
+    return "\n<div id='top-navigation-panel' xml:id='top-navigation-panel'>\n"
+           . make_nav_panel()
+           . "<hr /></div>\n";
+}
+
+sub bot_navigation_panel() {
+    return "\n<div class='online-navigation'>\n"
+           . "<p></p><hr />\n"
+           . make_nav_panel()
+           . "</div>\n"
+           . "<hr />\n"
+           . get_version_text()
+           . "\n";
+}
+
+sub add_link {
+    # Returns a pair (iconic link, textual link)
+    my($icon, $current_file, @link) = @_;
+    my($dummy, $file, $title) = split($delim,
+                                      $section_info{join(' ', at link)});
+    if ($icon =~ /\<tex2html_([_a-z]+)_visible_mark\>/) {
+        my $r = get_my_icon($1);
+        $icon =~ s/\<tex2html_[_a-z]+_visible_mark\>/$r/;
+    }
+    if ($title && ($file ne $current_file)) {
+        $title = purify($title);
+        $title = get_first_words($title, $WORDS_IN_NAVIGATION_PANEL_TITLES);
+        return (make_href($file, $icon), make_href($file, "$title"))
+        }
+    elsif ($icon eq get_my_icon('up') && $EXTERNAL_UP_LINK) {
+        return (make_href($EXTERNAL_UP_LINK, $icon),
+                make_href($EXTERNAL_UP_LINK, "$EXTERNAL_UP_TITLE"))
+        }
+    elsif ($icon eq get_my_icon('previous')
+           && $EXTERNAL_PREV_LINK && $EXTERNAL_PREV_TITLE) {
+        return (make_href($EXTERNAL_PREV_LINK, $icon),
+                make_href($EXTERNAL_PREV_LINK, "$EXTERNAL_PREV_TITLE"))
+        }
+    elsif ($icon eq get_my_icon('next')
+           && $EXTERNAL_DOWN_LINK && $EXTERNAL_DOWN_TITLE) {
+        return (make_href($EXTERNAL_DOWN_LINK, $icon),
+                make_href($EXTERNAL_DOWN_LINK, "$EXTERNAL_DOWN_TITLE"))
+        }
+    return (&inactive_img($icon), "");
+}
+
+sub add_special_link($$$) {
+    my($icon, $file, $current_file) = @_;
+    if ($icon =~ /\<tex2html_([_a-z]+)_visible_mark\>/) {
+        my $r = get_my_icon($1);
+        $icon =~ s/\<tex2html_[_a-z]+_visible_mark\>/$r/;
+    }
+    return (($file && ($file ne $current_file))
+            ? make_href($file, $icon)
+            : undef)
+}
+
+# The img_tag() function seems only to be called with the parameter
+# 'anchor_invisible_mark', which we want to turn into ''.  Since
+# replace_icon_marks() is the only interesting caller, and all it really
+# does is call img_tag(), we can just define the hook alternative to be
+# a no-op instead.
+#
+sub replace_icons_hook {}
+
+sub do_cmd_arabic {
+    # get rid of that nasty <SPAN CLASS="arabic">...</SPAN>
+    my($ctr, $val, $id, $text) = &read_counter_value($_[0]);
+    return ($val ? farabic($val) : "0") . $text;
+}
+
+
+sub gen_index_id($$) {
+    # this is used to ensure common index key generation and a stable sort
+    my($str, $extra) = @_;
+    sprintf('%s###%s%010d', $str, $extra, ++$global{'max_id'});
+}
+
+sub insert_index($$$$$) {
+    my($mark, $datafile, $columns, $letters, $prefix) = @_;
+    my $prog = "$myrootdir/tools/buildindex.py";
+    my $index;
+    if ($letters) {
+        $index = `$prog --columns $columns --letters $datafile`;
+    }
+    else {
+        $index = `$prog --columns $columns $datafile`;
+    }
+    if (!s/$mark/$prefix$index/) {
+        print "\nCould not locate index mark: $mark";
+    }
+}
+
+sub add_idx() {
+    print "\nBuilding HTML for the index ...";
+    close(IDXFILE);
+    insert_index($idx_mark, 'index.dat', $INDEX_COLUMNS, 1, '');
+}
+
+
+$idx_module_mark = '<tex2html_idx_module_mark>';
+$idx_module_title = 'Module Index';
+
+sub add_module_idx() {
+    print "\nBuilding HTML for the module index ...";
+    my $key;
+    my $first = 1;
+    my $prevplat = '';
+    my $allthesame = 1;
+    my $prefix = '';
+    foreach $key (keys %Modules) {
+        $key =~ s/<tt>([a-zA-Z0-9._]*)<\/tt>/$1/;
+        my $plat = "$ModulePlatforms{$key}";
+        $plat = ''
+          if ($plat eq $IGNORE_PLATFORM_ANNOTATION);
+        if (!$first) {
+            $allthesame = 0
+              if ($prevplat ne $plat);
+        }
+        else { $first = 0; }
+        $prevplat = $plat;
+    }
+    open(MODIDXFILE, '>modindex.dat') || die "\n$!\n";
+    foreach $key (keys %Modules) {
+        # dump the line in the data file; just use a dummy seqno field
+        my $nkey = $1;
+        my $moditem = "$Modules{$key}";
+        my $plat = '';
+        $key =~ s/<tt>([a-zA-Z0-9._]*)<\/tt>/$1/;
+        if ($ModulePlatforms{$key} && !$allthesame) {
+            $plat = (" <em>(<span class=\"platform\">$ModulePlatforms{$key}"
+                     . '</span>)</em>');
+        }
+        print MODIDXFILE $moditem . $IDXFILE_FIELD_SEP
+              . "<tt class=\"module\">$key</tt>$plat###\n";
+    }
+    close(MODIDXFILE);
+
+    if ($GLOBAL_MODULE_INDEX) {
+        $prefix = <<MODULE_INDEX_PREFIX;
+
+<p> This index only lists modules documented in this manual.
+  The <em class="citetitle"><a href="$GLOBAL_MODULE_INDEX">Global Module
+     Index</a></em> lists all modules that are documented in this set
+  of manuals.</p>
+MODULE_INDEX_PREFIX
+    }
+    if (!$allthesame) {
+        $prefix .= <<PLAT_DISCUSS;
+
+<p> Some module names are followed by an annotation indicating what
+platform they are available on.</p>
+
+PLAT_DISCUSS
+    }
+    insert_index($idx_module_mark, 'modindex.dat', $MODULE_INDEX_COLUMNS, 0,
+                 $prefix);
+}
+
+# replace both indexes as needed:
+sub add_idx_hook {
+    add_idx() if (/$idx_mark/);
+    process_python_state();
+    if ($MODULE_INDEX_FILE) {
+        local ($_);
+        open(MYFILE, "<$MODULE_INDEX_FILE");
+        sysread(MYFILE, $_, 1024*1024);
+        close(MYFILE);
+        add_module_idx();
+        open(MYFILE,">$MODULE_INDEX_FILE");
+        print MYFILE $_;
+        close(MYFILE);
+    }
+}
+
+
+# In addition to the standard stuff, add label to allow named node files and
+# support suppression of the page complete (for HTML Help use).
+$MY_CONTENTS_PAGE = '';
+sub do_cmd_tableofcontents {
+    local($_) = @_;
+    $TITLE = $toc_title;
+    $tocfile = $CURRENT_FILE;
+    my($closures, $reopens) = preserve_open_tags();
+    anchor_label('contents', $CURRENT_FILE, $_);        # this is added
+    $MY_CONTENTS_PAGE = "$CURRENT_FILE";
+    join('', "\\tableofchildlinks[off]", $closures
+         , make_section_heading($toc_title, 'h2'), $toc_mark
+         , $reopens, $_);
+}
+# In addition to the standard stuff, add label to allow named node files.
+sub do_cmd_listoffigures {
+    local($_) = @_;
+    $TITLE = $lof_title;
+    $loffile = $CURRENT_FILE;
+    my($closures, $reopens) = preserve_open_tags();
+    anchor_label('lof', $CURRENT_FILE, $_);             # this is added
+    join('', "<br />\n", $closures
+         , make_section_heading($lof_title, 'h2'), $lof_mark
+         , $reopens, $_);
+}
+# In addition to the standard stuff, add label to allow named node files.
+sub do_cmd_listoftables {
+    local($_) = @_;
+    $TITLE = $lot_title;
+    $lotfile = $CURRENT_FILE;
+    my($closures, $reopens) = preserve_open_tags();
+    anchor_label('lot', $CURRENT_FILE, $_);             # this is added
+    join('', "<br />\n", $closures
+         , make_section_heading($lot_title, 'h2'), $lot_mark
+         , $reopens, $_);
+}
+# In addition to the standard stuff, add label to allow named node files.
+sub do_cmd_textohtmlinfopage {
+    local($_) = @_;
+    if ($INFO) {                                        #
+        anchor_label("about",$CURRENT_FILE,$_);         # this is added
+    }                                                   #
+    my $the_version = '';                               # and the rest is
+    if ($t_date) {                                      # mostly ours
+        $the_version = ",\n$t_date";
+        if ($PACKAGE_VERSION) {
+            $the_version .= ", Release $PACKAGE_VERSION$RELEASE_INFO";
+        }
+    }
+    my $about;
+    open(ABOUT, "<$ABOUT_FILE") || die "\n$!\n";
+    sysread(ABOUT, $about, 1024*1024);
+    close(ABOUT);
+    $_ = (($INFO == 1)
+          ? join('',
+                 $close_all,
+                 "<strong>$t_title</strong>$the_version\n",
+                 $about,
+                 $open_all, $_)
+          : join('', $close_all, $INFO,"\n", $open_all, $_));
+    $_;
+}
+
+$GENERAL_INDEX_FILE = '';
+$MODULE_INDEX_FILE = '';
+
+# $idx_mark will be replaced with the real index at the end
+sub do_cmd_textohtmlindex {
+    local($_) = @_;
+    $TITLE = $idx_title;
+    $idxfile = $CURRENT_FILE;
+    $GENERAL_INDEX_FILE = "$CURRENT_FILE";
+    if (%index_labels) { make_index_labels(); }
+    if (($SHORT_INDEX) && (%index_segment)) { make_preindex(); }
+    else { $preindex = ''; }
+    my $heading = make_section_heading($idx_title, 'h2') . $idx_mark;
+    my($pre, $post) = minimize_open_tags($heading);
+    anchor_label('genindex',$CURRENT_FILE,$_);          # this is added
+    return "<br />\n" . $pre . $_;
+}
+
+# $idx_module_mark will be replaced with the real index at the end
+sub do_cmd_textohtmlmoduleindex {
+    local($_) = @_;
+    $TITLE = $idx_module_title;
+    anchor_label('modindex', $CURRENT_FILE, $_);
+    $MODULE_INDEX_FILE = "$CURRENT_FILE";
+    $_ = ('<p></p>' . make_section_heading($idx_module_title, 'h2')
+          . $idx_module_mark . $_);
+    return $_;
+}
+
+# The bibliography and the index should be treated as separate
+# sections in their own HTML files. The \bibliography{} command acts
+# as a sectioning command that has the desired effect. But when the
+# bibliography is constructed manually using the thebibliography
+# environment, or when using the theindex environment it is not
+# possible to use the normal sectioning mechanism. This subroutine
+# inserts a \bibliography{} or a dummy \textohtmlindex command just
+# before the appropriate environments to force sectioning.
+
+# XXX   This *assumes* that if there are two {theindex} environments,
+#       the first is the module index and the second is the standard
+#       index.  This is sufficient for the current Python documentation,
+#       but that's about it.
+
+sub add_bbl_and_idx_dummy_commands {
+    my $id = $global{'max_id'};
+
+    if (/[\\]tableofcontents/) {
+        $HAVE_TABLE_OF_CONTENTS = 1;
+    }
+    s/([\\]begin\s*$O\d+$C\s*thebibliography)/$bbl_cnt++; $1/eg;
+    s/([\\]begin\s*$O\d+$C\s*thebibliography)/$id++; "\\bibliography$O$id$C$O$id$C $1"/geo;
+    my(@parts) = split(/\\begin\s*$O\d+$C\s*theindex/);
+    if (scalar(@parts) == 3) {
+        # Be careful to re-write the string in place, since $_ is *not*
+        # returned explicity;  *** nasty side-effect dependency! ***
+        print "\nadd_bbl_and_idx_dummy_commands ==> adding general index";
+        print "\nadd_bbl_and_idx_dummy_commands ==> adding module index";
+        my $rx = "([\\\\]begin\\s*$O\\d+$C\\s*theindex[\\s\\S]*)"
+          . "([\\\\]begin\\s*$O\\d+$C\\s*theindex)";
+        s/$rx/\\textohtmlmoduleindex $1 \\textohtmlindex $2/o;
+        # Add a button to the navigation areas:
+        $CUSTOM_BUTTONS .= ('<a href="modindex.html" title="Module Index">'
+                            . get_my_icon('modules')
+                            . '</a>');
+        $HAVE_MODULE_INDEX = 1;
+        $HAVE_GENERAL_INDEX = 1;
+    }
+    elsif (scalar(@parts) == 2) {
+        print "\nadd_bbl_and_idx_dummy_commands ==> adding general index";
+        my $rx = "([\\\\]begin\\s*$O\\d+$C\\s*theindex)";
+        s/$rx/\\textohtmlindex $1/o;
+        $HAVE_GENERAL_INDEX = 1;
+    }
+    elsif (scalar(@parts) == 1) {
+        print "\nadd_bbl_and_idx_dummy_commands ==> no index found";
+        $CUSTOM_BUTTONS .= get_my_icon('blank');
+        $global{'max_id'} = $id; # not sure why....
+        s/([\\]begin\s*$O\d+$C\s*theindex)/\\textohtmlindex $1/o;
+            s/[\\]printindex/\\textohtmlindex /o;
+    }
+    else {
+        die "\n\nBad number of index environments!\n\n";
+    }
+    #----------------------------------------------------------------------
+    lib_add_bbl_and_idx_dummy_commands()
+        if defined(&lib_add_bbl_and_idx_dummy_commands);
+}
+
+# The bibliographic references, the appendices, the lists of figures
+# and tables etc. must appear in the contents table at the same level
+# as the outermost sectioning command. This subroutine finds what is
+# the outermost level and sets the above to the same level;
+
+sub set_depth_levels {
+    # Sets $outermost_level
+    my $level;
+    #RRM:  do not alter user-set value for  $MAX_SPLIT_DEPTH
+    foreach $level ("part", "chapter", "section", "subsection",
+                    "subsubsection", "paragraph") {
+        last if (($outermost_level) = /\\($level)$delimiter_rx/);
+    }
+    $level = ($outermost_level ? $section_commands{$outermost_level} :
+              do {$outermost_level = 'section'; 3;});
+
+    #RRM:  but calculate value for $MAX_SPLIT_DEPTH when a $REL_DEPTH was given
+    if ($REL_DEPTH && $MAX_SPLIT_DEPTH) {
+        $MAX_SPLIT_DEPTH = $level + $MAX_SPLIT_DEPTH;
+    } elsif (!($MAX_SPLIT_DEPTH)) { $MAX_SPLIT_DEPTH = 1 };
+
+    %unnumbered_section_commands = ('tableofcontents' => $level,
+                                    'listoffigures' => $level,
+                                    'listoftables' => $level,
+                                    'bibliography' => $level,
+                                    'textohtmlindex' => $level,
+                                    'textohtmlmoduleindex' => $level);
+    $section_headings{'textohtmlmoduleindex'} = 'h1';
+
+    %section_commands = (%unnumbered_section_commands,
+                         %section_commands);
+
+    make_sections_rx();
+}
+
+
+# This changes the markup used for {verbatim} environments, and is the
+# best way I've found that ensures the <dl> goes on the outside of the
+# <pre>...</pre>.
+#
+# Note that this *must* be done in the init file, not the python.perl
+# style support file.  The %declarations must be set before
+# initialize() is called in the main LaTeX2HTML script (which happens
+# before style files are loaded).
+#
+%declarations = ('preform' => '<div class="verbatim"><pre></pre></div>',
+                 %declarations);
+
+
+# This is a modified version of what's provided by LaTeX2HTML; see the
+# comment on the middle stanza for an explanation of why we keep our
+# own version.
+#
+# This routine must be called once on the text only,
+# else it will "eat up" sensitive constructs.
+sub text_cleanup {
+    # MRO: replaced $* with /m
+    s/(\s*\n){3,}/\n\n/gom;	# Replace consecutive blank lines with one
+    s/<(\/?)P>\s*(\w)/<$1P>\n$2/gom;      # clean up paragraph starts and ends
+    s/$O\d+$C//go;		# Get rid of bracket id's
+    s/$OP\d+$CP//go;		# Get rid of processed bracket id's
+    s/(<!)?--?(>)?/(length($1) || length($2)) ? "$1--$2" : "-"/ge;
+    # Spacing commands
+    s/\\( |$)/ /go;
+    #JKR: There should be no more comments in the source now.
+    #s/([^\\]?)%/$1/go;        # Remove the comment character
+    # Cannot treat \, as a command because , is a delimiter ...
+    s/\\,/ /go;
+    # Replace tilde's with non-breaking spaces
+    s/ *~/&nbsp;/g;
+
+    # This is why we have this copy of this routine; the following
+    # isn't so desirable as the author/maintainers of LaTeX2HTML seem
+    # to think.  It's not commented out in the main script, so we have
+    # to override the whole thing.  In particular, we don't want empty
+    # table cells to disappear.
+
+    ### DANGEROUS ?? ###
+    # remove redundant (not <P></P>) empty tags, incl. with attributes
+    #s/\n?<([^PD >][^>]*)>\s*<\/\1>//g;
+    #s/\n?<([^PD >][^>]*)>\s*<\/\1>//g;
+    # remove redundant empty tags (not </P><P> or <TD> or <TH>)
+    #s/<\/(TT|[^PTH][A-Z]+)><\1>//g;
+    #s/<([^PD ]+)(\s[^>]*)?>\n*<\/\1>//g;
+
+    #JCL(jcl-hex)
+    # Replace ^^ special chars (according to p.47 of the TeX book)
+    # Useful when coming from the .aux file (german umlauts, etc.)
+    s/\^\^([^0-9a-f])/chr((64+ord($1))&127)/ge;
+    s/\^\^([0-9a-f][0-9a-f])/chr(hex($1))/ge;
+}
+
+# This is used to map the link rel attributes LaTeX2HTML uses to those
+# currently recommended by the W3C.
+sub custom_REL_hook {
+    my($rel,$junk) = @_;
+    return 'parent' if $rel eq 'up';
+    return 'prev' if $rel eq 'previous';
+    return $rel;
+}
+
+# This is added to get rid of the long comment that follows the
+# doctype declaration; MSIE5 on NT4 SP4 barfs on it and drops the
+# content of the page.
+$MY_PARTIAL_HEADER = '';
+sub make_head_and_body($$) {
+    my($title, $body) = @_;
+    $body = " $body" unless ($body eq '');
+    my $DTDcomment = '';
+    my($version, $isolanguage) = ($HTML_VERSION, 'EN');
+    my %isolanguages = (  'english',  'EN'   , 'USenglish', 'EN.US'
+                        , 'original', 'EN'   , 'german'   , 'DE'
+                        , 'austrian', 'DE.AT', 'french'   , 'FR'
+                        , 'spanish',  'ES');
+    $isolanguage = $isolanguages{$default_language};
+    $isolanguage = 'EN' unless $isolanguage;
+    $title = &purify($title,1);
+    eval("\$title = ". $default_title ) unless ($title);
+
+    # allow user-modification of the <title> tag; thanks Dan Young
+    if (defined &custom_TITLE_hook) {
+        $title = &custom_TITLE_hook($title, $toc_sec_title);
+    }
+
+    if ($DOCTYPE =~ /\/\/[\w\.]+\s*$/) { # language spec included
+        $DTDcomment = "<!DOCTYPE html PUBLIC \"$DOCTYPE\">\n";
+    } else {
+        $DTDcomment = "<!DOCTYPE html PUBLIC \"$DOCTYPE//"
+            . ($ISO_LANGUAGE ? $ISO_LANGUAGE : $isolanguage) . "\">\n";
+    }
+    if ($MY_PARTIAL_HEADER eq '') {
+        my $favicon = '';
+        if ($FAVORITES_ICON) {
+            my($myname, $mydir, $myext) = fileparse($FAVORITES_ICON, '\..*');
+            my $favtype = '';
+            if ($myext eq '.gif' || $myext eq '.png') {
+                $myext =~ s/^[.]//;
+                $favtype = " type=\"image/$myext\"";
+            }
+            $favicon = (
+                "\n<link rel=\"SHORTCUT ICON\" href=\"$FAVORITES_ICON\""
+                . "$favtype />");
+        }
+        $STYLESHEET = $FILE.".css" unless $STYLESHEET;
+        $MY_PARTIAL_HEADER = join('',
+            ($DOCTYPE ? $DTDcomment : ''),
+            "<html>\n<head>",
+            ($BASE ? "\n<base href=\"$BASE\" />" : ''),
+            "\n<link rel=\"STYLESHEET\" href=\"$STYLESHEET\" type='text/css'",
+            " />",
+            $favicon,
+            ($EXTERNAL_UP_LINK
+             ? ("\n<link rel='start' href='" . $EXTERNAL_UP_LINK
+                . ($EXTERNAL_UP_TITLE ?
+                   "' title='$EXTERNAL_UP_TITLE' />" : "' />"))
+             : ''),
+            "\n<link rel=\"first\" href=\"$FILE.html\"",
+            ($t_title ? " title='$t_title'" : ''),
+            ' />',
+            ($HAVE_TABLE_OF_CONTENTS
+             ? ("\n<link rel='contents' href='$MY_CONTENTS_PAGE'"
+                . ' title="Contents" />')
+             : ''),
+            ($HAVE_GENERAL_INDEX
+             ? ("\n<link rel='index' href='$GENERAL_INDEX_FILE'"
+                . " title='Index' />")
+             : ''),
+            # disable for now -- Mozilla doesn't do well with multiple indexes
+            # ($HAVE_MODULE_INDEX
+            #  ? ("<link rel="index" href='$MODULE_INDEX_FILE'"
+            #     . " title='Module Index' />\n")
+            #  : ''),
+            ($INFO
+             # XXX We can do this with the Python tools since the About...
+             # page always gets copied to about.html, even when we use the
+             # generated node###.html page names.  Won't work with the
+             # rest of the Python doc tools.
+             ? ("\n<link rel='last' href='about.html'"
+                . " title='About this document...' />"
+                . "\n<link rel='help' href='about.html'"
+                . " title='About this document...' />")
+             : ''),
+            $more_links_mark,
+            "\n",
+            ($CHARSET && $HTML_VERSION ge "2.1"
+             ? ('<meta http-equiv="Content-Type" content="text/html; '
+                . "charset=$CHARSET\" />\n")
+             : ''),
+            ($AESOP_META_TYPE
+             ? "<meta name='aesop' content='$AESOP_META_TYPE' />\n" : ''));
+    }
+    if (!$charset && $CHARSET) {
+        $charset = $CHARSET;
+        $charset =~ s/_/\-/go;
+    }
+    join('',
+         $MY_PARTIAL_HEADER,
+         "<title>", $title, "</title>\n</head>\n<body$body>");
+}
+
+sub replace_morelinks {
+    $more_links =~ s/ REL=/ rel=/g;
+    $more_links =~ s/ HREF=/ href=/g;
+    $more_links =~ s/<LINK /<link /g;
+    $more_links =~ s/">/" \/>/g;
+    $_ =~ s/$more_links_mark/$more_links/e;
+}
+
+1;      # This must be the last line

Added: sandbox/trunk/pdb/Doc/perl/manual.perl
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/perl/manual.perl	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,15 @@
+# -*- perl -*-
+#
+# This implements the Python manual class.  All it really needs to do it
+# load the "python" style.  The style code is not moved into the class code
+# at this time, since we expect additional document class to be developed
+# for the Python documentation in the future.  Appropriate relocations will
+# be made at that time.
+
+package main;
+
+do_require_package("report");
+do_require_package("alltt");
+do_require_package("python");
+
+1;				# sheesh....

Added: sandbox/trunk/pdb/Doc/perl/python.perl
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/perl/python.perl	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,2173 @@
+# python.perl by Fred L. Drake, Jr. <fdrake at acm.org>            -*- perl -*-
+#
+# Heavily based on Guido van Rossum's myformat.perl (now obsolete).
+#
+# Extension to LaTeX2HTML for documents using myformat.sty.
+# Subroutines of the form do_cmd_<name> here define translations
+# for LaTeX commands \<name> defined in the corresponding .sty file.
+
+package main;
+
+use warnings;
+use File::Basename;
+
+
+sub next_argument{
+    my $param;
+    $param = missing_braces()
+      unless ((s/$next_pair_pr_rx/$param=$2;''/eo)
+              ||(s/$next_pair_rx/$param=$2;''/eo));
+    return $param;
+}
+
+sub next_optional_argument{
+    my($param, $rx) = ('', "^\\s*(\\[([^]]*)\\])?");
+    s/$rx/$param=$2;''/eo;
+    return $param;
+}
+
+sub make_icon_filename($){
+    my($myname, $mydir, $myext) = fileparse($_[0], '\..*');
+    chop $mydir;
+    if ($mydir eq '.') {
+        $mydir = $ICONSERVER;
+    }
+    $myext = ".$IMAGE_TYPE"
+      unless $myext;
+    return "$mydir$dd$myname$myext";
+}
+
+sub get_link_icon($){
+    my $url = $_[0];
+    if ($OFF_SITE_LINK_ICON && ($url =~ /^[-a-zA-Z0-9.]+:/)) {
+        # absolute URL; assume it points off-site
+        my $icon = make_icon_filename($OFF_SITE_LINK_ICON);
+        return (" <img src=\"$icon\"\n"
+                . '  border="0" class="offsitelink"'
+                . ($OFF_SITE_LINK_ICON_HEIGHT
+                   ? " height=\"$OFF_SITE_LINK_ICON_HEIGHT\""
+                   : '')
+                . ($OFF_SITE_LINK_ICON_WIDTH
+                   ? " width=\"$OFF_SITE_LINK_ICON_WIDTH\""
+                   : '')
+                . " alt=\"[off-site link]\"\n"
+                . "  />");
+    }
+    return '';
+}
+
+# This is a fairly simple hack; it supports \let when it is used to create
+# (or redefine) a macro to exactly be some other macro: \let\newname=\oldname.
+# Many possible uses of \let aren't supported or aren't supported correctly.
+#
+sub do_cmd_let{
+    local($_) = @_;
+    my $matched = 0;
+    s/[\\]([a-zA-Z]+)\s*(=\s*)?[\\]([a-zA-Z]*)/$matched=1; ''/e;
+    if ($matched) {
+        my($new, $old) = ($1, $3);
+        eval "sub do_cmd_$new { do_cmd_$old" . '(@_); }';
+        print "\ndefining handler for \\$new using \\$old\n";
+    }
+    else {
+        s/[\\]([a-zA-Z]+)\s*(=\s*)?([^\\])/$matched=1; ''/es;
+        if ($matched) {
+            my($new, $char) = ($1, $3);
+            eval "sub do_cmd_$new { \"\\$char\" . \$_[0]; }";
+            print "\ndefining handler for \\$new to insert '$char'\n";
+        }
+        else {
+            write_warnings("Could not interpret \\let construct...");
+        }
+    }
+    return $_;
+}
+
+
+# the older version of LaTeX2HTML we use doesn't support this, but we use it:
+
+sub do_cmd_textasciitilde{ '&#126;' . $_[0]; }
+sub do_cmd_textasciicircum{ '^' . $_[0]; }
+sub do_cmd_textbar{ '|' . $_[0]; }
+sub do_cmd_texteuro { '&#8364;' . $_[0]; }
+sub do_cmd_textgreater{ '&gt;' . $_[0]; }
+sub do_cmd_textless{ '&lt;' . $_[0]; }
+sub do_cmd_textunderscore{ '_' . $_[0]; }
+sub do_cmd_infinity{ '&infin;' . $_[0]; }
+sub do_cmd_plusminus{ '&plusmn;' . $_[0]; }
+sub do_cmd_guilabel{
+    return use_wrappers($_[0]. '<span class="guilabel">', '</span>'); }
+sub do_cmd_menuselection{
+    return use_wrappers($_[0], '<span class="guilabel">', '</span>'); }
+sub do_cmd_sub{
+    return '</span> &gt; <span class="guilabel">' . $_[0]; }
+
+
+# words typeset in a special way (not in HTML though)
+
+sub do_cmd_ABC{ 'ABC' . $_[0]; }
+sub do_cmd_UNIX{ '<span class="Unix">Unix</span>' . $_[0]; }
+sub do_cmd_LaTeX{ '<span class="LaTeX">LaTeX</span>' . $_[0]; }
+sub do_cmd_TeX{ '<span class="TeX">TeX</span>' . $_[0]; }
+sub do_cmd_ASCII{ 'ASCII' . $_[0]; }
+sub do_cmd_POSIX{ 'POSIX' . $_[0]; }
+sub do_cmd_C{ 'C' . $_[0]; }
+sub do_cmd_Cpp{ 'C++' . $_[0]; }
+sub do_cmd_EOF{ 'EOF' . $_[0]; }
+sub do_cmd_NULL{ '<tt class="constant">NULL</tt>' . $_[0]; }
+
+sub do_cmd_e{ '&#92;' . $_[0]; }
+
+$DEVELOPER_ADDRESS = '';
+$SHORT_VERSION = '';
+$RELEASE_INFO = '';
+$PACKAGE_VERSION = '';
+
+sub do_cmd_version{ $PACKAGE_VERSION . $_[0]; }
+sub do_cmd_shortversion{ $SHORT_VERSION . $_[0]; }
+sub do_cmd_release{
+    local($_) = @_;
+    $PACKAGE_VERSION = next_argument();
+    return $_;
+}
+
+sub do_cmd_setreleaseinfo{
+    local($_) = @_;
+    $RELEASE_INFO = next_argument();
+    return $_;
+}
+
+sub do_cmd_setshortversion{
+    local($_) = @_;
+    $SHORT_VERSION = next_argument();
+    return $_;
+}
+
+sub do_cmd_authoraddress{
+    local($_) = @_;
+    $DEVELOPER_ADDRESS = next_argument();
+    return $_;
+}
+
+sub do_cmd_hackscore{
+    local($_) = @_;
+    next_argument();
+    return '_' . $_;
+}
+
+# Helper used in many places that arbitrary code-like text appears:
+
+sub codetext($){
+    my $text = "$_[0]";
+    # Make sure that "---" is not converted to "--" later when
+    # LaTeX2HTML tries converting em-dashes based on the conventional
+    # TeX font ligatures:
+    $text =~ s/--/-\&#45;/go;
+    return $text;
+}
+
+sub use_wrappers($$$){
+    local($_,$before,$after) = @_;
+    my $stuff = next_argument();
+    return $before . $stuff . $after . $_;
+}
+
+sub use_code_wrappers($$$){
+    local($_,$before,$after) = @_;
+    my $stuff = codetext(next_argument());
+    return $before . $stuff . $after . $_;
+}
+
+$IN_DESC_HANDLER = 0;
+sub do_cmd_optional{
+    if ($IN_DESC_HANDLER) {
+        return use_wrappers($_[0], "</var><big>\[</big><var>",
+                            "</var><big>\]</big><var>");
+    }
+    else {
+        return use_wrappers($_[0], "<big>\[</big>", "<big>\]</big>");
+    }
+}
+
+# Logical formatting (some based on texinfo), needs to be converted to
+# minimalist HTML.  The "minimalist" is primarily to reduce the size of
+# output files for users that read them over the network rather than
+# from local repositories.
+
+sub do_cmd_pytype{ return $_[0]; }
+sub do_cmd_makevar{
+    return use_wrappers($_[0], '<span class="makevar">', '</span>'); }
+sub do_cmd_code{
+    return use_code_wrappers($_[0], '<code>', '</code>'); }
+sub do_cmd_module{
+    return use_wrappers($_[0], '<tt class="module">', '</tt>'); }
+sub do_cmd_keyword{
+    return use_wrappers($_[0], '<tt class="keyword">', '</tt>'); }
+sub do_cmd_exception{
+    return use_wrappers($_[0], '<tt class="exception">', '</tt>'); }
+sub do_cmd_class{
+    return use_wrappers($_[0], '<tt class="class">', '</tt>'); }
+sub do_cmd_function{
+    return use_wrappers($_[0], '<tt class="function">', '</tt>'); }
+sub do_cmd_constant{
+    return use_wrappers($_[0], '<tt class="constant">', '</tt>'); }
+sub do_cmd_member{
+    return use_wrappers($_[0], '<tt class="member">', '</tt>'); }
+sub do_cmd_method{
+    return use_wrappers($_[0], '<tt class="method">', '</tt>'); }
+sub do_cmd_cfunction{
+    return use_wrappers($_[0], '<tt class="cfunction">', '</tt>'); }
+sub do_cmd_cdata{
+    return use_wrappers($_[0], '<tt class="cdata">', '</tt>'); }
+sub do_cmd_ctype{
+    return use_wrappers($_[0], '<tt class="ctype">', '</tt>'); }
+sub do_cmd_regexp{
+    return use_code_wrappers($_[0], '<tt class="regexp">', '</tt>'); }
+sub do_cmd_character{
+    return use_code_wrappers($_[0], '"<tt class="character">', '</tt>"'); }
+sub do_cmd_program{
+    return use_wrappers($_[0], '<b class="program">', '</b>'); }
+sub do_cmd_programopt{
+    return use_wrappers($_[0], '<b class="programopt">', '</b>'); }
+sub do_cmd_longprogramopt{
+    # note that the --- will be later converted to -- by LaTeX2HTML
+    return use_wrappers($_[0], '<b class="programopt">---', '</b>'); }
+sub do_cmd_email{
+    return use_wrappers($_[0], '<span class="email">', '</span>'); }
+sub do_cmd_mailheader{
+    return use_wrappers($_[0], '<span class="mailheader">', ':</span>'); }
+sub do_cmd_mimetype{
+    return use_wrappers($_[0], '<span class="mimetype">', '</span>'); }
+sub do_cmd_var{
+    return use_wrappers($_[0], "<var>", "</var>"); }
+sub do_cmd_dfn{
+    return use_wrappers($_[0], '<i class="dfn">', '</i>'); }
+sub do_cmd_emph{
+    return use_wrappers($_[0], '<em>', '</em>'); }
+sub do_cmd_file{
+    return use_wrappers($_[0], '<span class="file">', '</span>'); }
+sub do_cmd_filenq{
+    return do_cmd_file($_[0]); }
+sub do_cmd_samp{
+    return use_code_wrappers($_[0], '"<tt class="samp">', '</tt>"'); }
+sub do_cmd_kbd{
+    return use_wrappers($_[0], '<kbd>', '</kbd>'); }
+sub do_cmd_strong{
+    return use_wrappers($_[0], '<strong>', '</strong>'); }
+sub do_cmd_textbf{
+    return use_wrappers($_[0], '<b>', '</b>'); }
+sub do_cmd_textit{
+    return use_wrappers($_[0], '<i>', '</i>'); }
+# This can be changed/overridden for translations:
+%NoticeNames = ('note' => 'Note:',
+                'warning' => 'Warning:',
+                );
+
+sub do_cmd_note{
+    my $label = $NoticeNames{'note'};
+    return use_wrappers(
+        $_[0],
+        "<span class=\"note\"><b class=\"label\">$label</b>\n",
+        '</span>'); }
+sub do_cmd_warning{
+    my $label = $NoticeNames{'warning'};
+    return use_wrappers(
+        $_[0],
+        "<span class=\"warning\"><b class=\"label\">$label</b>\n",
+        '</span>'); }
+
+sub do_env_notice{
+    local($_) = @_;
+    my $notice = next_optional_argument();
+    if (!$notice) {
+        $notice = 'note';
+    }
+    my $label = $NoticeNames{$notice};
+    return ("<div class=\"$notice\"><b class=\"label\">$label</b>\n"
+            . $_
+            . '</div>');
+}
+
+sub do_cmd_moreargs{
+    return '...' . $_[0]; }
+sub do_cmd_unspecified{
+    return '...' . $_[0]; }
+
+
+sub do_cmd_refmodule{
+    # Insert the right magic to jump to the module definition.
+    local($_) = @_;
+    my $key = next_optional_argument();
+    my $module = next_argument();
+    $key = $module
+        unless $key;
+    return "<tt class=\"module\"><a href=\"module-$key.html\">$module</a></tt>"
+      . $_;
+}
+
+sub do_cmd_newsgroup{
+    local($_) = @_;
+    my $newsgroup = next_argument();
+    my $icon = get_link_icon("news:$newsgroup");
+    my $stuff = ("<a class=\"newsgroup\" href=\"news:$newsgroup\">"
+                 . "$newsgroup$icon</a>");
+    return $stuff . $_;
+}
+
+sub do_cmd_envvar{
+    local($_) = @_;
+    my $envvar = next_argument();
+    my($name, $aname, $ahref) = new_link_info();
+    # The <tt> here is really to keep buildindex.py from making
+    # the variable name case-insensitive.
+    add_index_entry("environment variables!$envvar@<tt>$envvar</tt>",
+                    $ahref);
+    add_index_entry("$envvar (environment variable)", $ahref);
+    $aname =~ s/<a/<a class="envvar"/;
+    return "$aname$envvar</a>" . $_;
+}
+
+sub do_cmd_url{
+    # use the URL as both text and hyperlink
+    local($_) = @_;
+    my $url = next_argument();
+    my $icon = get_link_icon($url);
+    $url =~ s/~/&#126;/g;
+    return "<a class=\"url\" href=\"$url\">$url$icon</a>" . $_;
+}
+
+sub do_cmd_manpage{
+    # two parameters:  \manpage{name}{section}
+    local($_) = @_;
+    my $page = next_argument();
+    my $section = next_argument();
+    return "<span class=\"manpage\"><i>$page</i>($section)</span>" . $_;
+}
+
+$PEP_FORMAT = "http://www.python.org/peps/pep-%04d.html";
+#$RFC_FORMAT = "http://www.ietf.org/rfc/rfc%04d.txt";
+$RFC_FORMAT = "http://www.faqs.org/rfcs/rfc%d.html";
+
+sub get_rfc_url($$){
+    my($rfcnum, $format) = @_;
+    return sprintf($format, $rfcnum);
+}
+
+sub do_cmd_pep{
+    local($_) = @_;
+    my $rfcnumber = next_argument();
+    my $id = "rfcref-" . ++$global{'max_id'};
+    my $href = get_rfc_url($rfcnumber, $PEP_FORMAT);
+    my $icon = get_link_icon($href);
+    # Save the reference
+    my $nstr = gen_index_id("Python Enhancement Proposals!PEP $rfcnumber", '');
+    $index{$nstr} .= make_half_href("$CURRENT_FILE#$id");
+    return ("<a class=\"rfc\" id='$id' xml:id='$id'\n"
+            . "href=\"$href\">PEP $rfcnumber$icon</a>" . $_);
+}
+
+sub do_cmd_rfc{
+    local($_) = @_;
+    my $rfcnumber = next_argument();
+    my $id = "rfcref-" . ++$global{'max_id'};
+    my $href = get_rfc_url($rfcnumber, $RFC_FORMAT);
+    my $icon = get_link_icon($href);
+    # Save the reference
+    my $nstr = gen_index_id("RFC!RFC $rfcnumber", '');
+    $index{$nstr} .= make_half_href("$CURRENT_FILE#$id");
+    return ("<a class=\"rfc\" id='$id' xml:id='$id'\nhref=\"$href\">"
+            . "RFC $rfcnumber$icon</a>" . $_);
+}
+
+sub do_cmd_ulink{
+    local($_) = @_;
+    my $text = next_argument();
+    my $url = next_argument();
+    return "<a class=\"ulink\" href=\"$url\"\n  >$text</a>" . $_;
+}
+
+sub do_cmd_citetitle{
+    local($_) = @_;
+    my $url = next_optional_argument();
+    my $title = next_argument();
+    my $icon = get_link_icon($url);
+    my $repl = '';
+    if ($url) {
+        my $titletext = strip_html_markup("$title");
+        $repl = ("<em class=\"citetitle\"><a\n"
+                 . " href=\"$url\"\n"
+                 . " title=\"$titletext\"\n"
+                 . " >$title$icon</a></em>");
+    }
+    else {
+        $repl = "<em class=\"citetitle\"\n >$title</em>";
+    }
+    return $repl . $_;
+}
+
+sub do_cmd_deprecated{
+    # two parameters:  \deprecated{version}{whattodo}
+    local($_) = @_;
+    my $release = next_argument();
+    my $reason = next_argument();
+    return ('<div class="versionnote">'
+            . "<b>Deprecated since release $release.</b>"
+            . "\n$reason</div><p></p>"
+            . $_);
+}
+
+sub versionnote($$){
+    # one or two parameters:  \versionnote[explanation]{version}
+    my $type = $_[0];
+    local $_ = $_[1];
+    my $explanation = next_optional_argument();
+    my $release = next_argument();
+    my $text = "$type in version $release.";
+    if ($explanation) {
+        $text = "$type in version $release:\n$explanation.";
+    }
+    return "\n<span class=\"versionnote\">$text</span>\n" . $_;
+}
+
+sub do_cmd_versionadded{
+    return versionnote('New', $_[0]);
+}
+
+sub do_cmd_versionchanged{
+    return versionnote('Changed', $_[0]);
+}
+
+#
+# These function handle platform dependency tracking.
+#
+sub do_cmd_platform{
+    local($_) = @_;
+    my $platform = next_argument();
+    $ModulePlatforms{"<tt class=\"module\">$THIS_MODULE</tt>"} = $platform;
+    $platform = "Macintosh"
+      if $platform eq 'Mac';
+    return "\n<p class=\"availability\">Availability: <span"
+      . "\n class=\"platform\">$platform</span>.</p>\n" . $_;
+}
+
+$IGNORE_PLATFORM_ANNOTATION = '';
+sub do_cmd_ignorePlatformAnnotation{
+    local($_) = @_;
+    $IGNORE_PLATFORM_ANNOTATION = next_argument();
+    return $_;
+}
+
+
+# index commands
+
+$INDEX_SUBITEM = "";
+
+sub get_indexsubitem(){
+    return $INDEX_SUBITEM ? " $INDEX_SUBITEM" : '';
+}
+
+sub do_cmd_setindexsubitem{
+    local($_) = @_;
+    $INDEX_SUBITEM = next_argument();
+    return $_;
+}
+
+sub do_cmd_withsubitem{
+    # We can't really do the right thing, because LaTeX2HTML doesn't
+    # do things in the right order, but we need to at least strip this stuff
+    # out, and leave anything that the second argument expanded out to.
+    #
+    local($_) = @_;
+    my $oldsubitem = $INDEX_SUBITEM;
+    $INDEX_SUBITEM = next_argument();
+    my $stuff = next_argument();
+    my $br_id = ++$globals{'max_id'};
+    my $marker = "$O$br_id$C";
+    $stuff =~ s/^\s+//;
+    return
+      $stuff
+      . "\\setindexsubitem$marker$oldsubitem$marker"
+      . $_;
+}
+
+# This is the prologue macro which is required to start writing the
+# mod\jobname.idx file; we can just ignore it.  (Defining this suppresses
+# a warning that \makemodindex is unknown.)
+#
+sub do_cmd_makemodindex{ return $_[0]; }
+
+# We're in the document subdirectory when this happens!
+#
+open(IDXFILE, '>index.dat') || die "\n$!\n";
+open(INTLABELS, '>intlabels.pl') || die "\n$!\n";
+print INTLABELS "%internal_labels = ();\n";
+print INTLABELS "1;             # hack in case there are no entries\n\n";
+
+# Using \0 for this is bad because we can't use common tools to work with the
+# resulting files.  Things like grep can be useful with this stuff!
+#
+$IDXFILE_FIELD_SEP = "\1";
+
+sub write_idxfile($$){
+    my($ahref, $str) = @_;
+    print IDXFILE $ahref, $IDXFILE_FIELD_SEP, $str, "\n";
+}
+
+
+sub gen_link($$){
+    my($node, $target) = @_;
+    print INTLABELS "\$internal_labels{\"$target\"} = \"/$node\";\n";
+    return "<a href=\"$node#$target\">";
+}
+
+sub add_index_entry($$){
+    # add an entry to the index structures; ignore the return value
+    my($str, $ahref) = @_;
+    $str = gen_index_id($str, '');
+    $index{$str} .= $ahref;
+    write_idxfile($ahref, $str);
+}
+
+sub new_link_name_info(){
+    my $name = "l2h-" . ++$globals{'max_id'};
+    my $aname = "<a id='$name' xml:id='$name'>";
+    my $ahref = gen_link($CURRENT_FILE, $name);
+    return ($name, $ahref);
+}
+
+sub new_link_info(){
+    my($name, $ahref) = new_link_name_info();
+    my $aname = "<a id='$name' xml:id='$name'>";
+    return ($name, $aname, $ahref);
+}
+
+$IndexMacroPattern = '';
+sub define_indexing_macro(@){
+    my $count = @_;
+    my $i = 0;
+    for (; $i < $count; ++$i) {
+        my $name = $_[$i];
+        my $cmd = "idx_cmd_$name";
+        die "\nNo function $cmd() defined!\n"
+          if (!defined &$cmd);
+        eval ("sub do_cmd_$name { return process_index_macros("
+              . "\$_[0], '$name'); }");
+        if (length($IndexMacroPattern) == 0) {
+            $IndexMacroPattern = "$name";
+        }
+        else {
+            $IndexMacroPattern .= "|$name";
+        }
+    }
+}
+
+$DEBUG_INDEXING = 0;
+sub process_index_macros($$){
+    local($_) = @_;
+    my $cmdname = $_[1];        # This is what triggered us in the first place;
+                                # we know it's real, so just process it.
+    my($name, $aname, $ahref) = new_link_info();
+    my $cmd = "idx_cmd_$cmdname";
+    print "\nIndexing: \\$cmdname"
+      if $DEBUG_INDEXING;
+    &$cmd($ahref);              # modifies $_ and adds index entries
+    while (/^[\s\n]*\\($IndexMacroPattern)</) {
+        $cmdname = "$1";
+        print " \\$cmdname"
+          if $DEBUG_INDEXING;
+        $cmd = "idx_cmd_$cmdname";
+        if (!defined &$cmd) {
+            last;
+        }
+        else {
+            s/^[\s\n]*\\$cmdname//;
+            &$cmd($ahref);
+        }
+    }
+# XXX I don't remember why I added this to begin with.
+#     if (/^[ \t\r\n]/) {
+#         $_ = substr($_, 1);
+#     }
+    return "$aname$anchor_invisible_mark</a>" . $_;
+}
+
+define_indexing_macro('index');
+sub idx_cmd_index($){
+    my $str = next_argument();
+    add_index_entry("$str", $_[0]);
+}
+
+define_indexing_macro('kwindex');
+sub idx_cmd_kwindex($){
+    my $str = next_argument();
+    add_index_entry("<tt>$str</tt>!keyword", $_[0]);
+    add_index_entry("keyword!<tt>$str</tt>", $_[0]);
+}
+
+define_indexing_macro('indexii');
+sub idx_cmd_indexii($){
+    my $str1 = next_argument();
+    my $str2 = next_argument();
+    add_index_entry("$str1!$str2", $_[0]);
+    add_index_entry("$str2!$str1", $_[0]);
+}
+
+define_indexing_macro('indexiii');
+sub idx_cmd_indexiii($){
+    my $str1 = next_argument();
+    my $str2 = next_argument();
+    my $str3 = next_argument();
+    add_index_entry("$str1!$str2 $str3", $_[0]);
+    add_index_entry("$str2!$str3, $str1", $_[0]);
+    add_index_entry("$str3!$str1 $str2", $_[0]);
+}
+
+define_indexing_macro('indexiv');
+sub idx_cmd_indexiv($){
+    my $str1 = next_argument();
+    my $str2 = next_argument();
+    my $str3 = next_argument();
+    my $str4 = next_argument();
+    add_index_entry("$str1!$str2 $str3 $str4", $_[0]);
+    add_index_entry("$str2!$str3 $str4, $str1", $_[0]);
+    add_index_entry("$str3!$str4, $str1 $str2", $_[0]);
+    add_index_entry("$str4!$str1 $str2 $str3", $_[0]);
+}
+
+define_indexing_macro('ttindex');
+sub idx_cmd_ttindex($){
+    my $str = codetext(next_argument());
+    my $entry = $str . get_indexsubitem();
+    add_index_entry($entry, $_[0]);
+}
+
+sub my_typed_index_helper($$){
+    my($word, $ahref) = @_;
+    my $str = next_argument();
+    add_index_entry("$str $word", $ahref);
+    add_index_entry("$word!$str", $ahref);
+}
+
+define_indexing_macro('stindex', 'opindex', 'exindex', 'obindex');
+sub idx_cmd_stindex($){ my_typed_index_helper('statement', $_[0]); }
+sub idx_cmd_opindex($){ my_typed_index_helper('operator', $_[0]); }
+sub idx_cmd_exindex($){ my_typed_index_helper('exception', $_[0]); }
+sub idx_cmd_obindex($){ my_typed_index_helper('object', $_[0]); }
+
+define_indexing_macro('bifuncindex');
+sub idx_cmd_bifuncindex($){
+    my $str = next_argument();
+    add_index_entry("<tt class=\"function\">$str()</tt> (built-in function)",
+                    $_[0]);
+}
+
+
+sub make_mod_index_entry($$){
+    my($str, $define) = @_;
+    my($name, $aname, $ahref) = new_link_info();
+    # equivalent of add_index_entry() using $define instead of ''
+    $ahref =~ s/\#[-_a-zA-Z0-9]*\"/\"/
+      if ($define eq 'DEF');
+    $str = gen_index_id($str, $define);
+    $index{$str} .= $ahref;
+    write_idxfile($ahref, $str);
+
+    if ($define eq 'DEF') {
+        # add to the module index
+        $str =~ /(<tt.*<\/tt>)/;
+        my $nstr = $1;
+        $Modules{$nstr} .= $ahref;
+    }
+    return "$aname$anchor_invisible_mark2</a>";
+}
+
+
+$THIS_MODULE = '';
+$THIS_CLASS = '';
+
+sub define_module($$){
+    my($word, $name) = @_;
+    my $section_tag = join('', @curr_sec_id);
+    if ($word ne "built-in" && $word ne "extension"
+        && $word ne "standard" && $word ne "") {
+        write_warnings("Bad module type '$word'"
+                       . " for \\declaremodule (module $name)");
+        $word = "";
+    }
+    $word = "$word " if $word;
+    $THIS_MODULE = "$name";
+    $INDEX_SUBITEM = "(in module $name)";
+    print "[$name]";
+    return make_mod_index_entry(
+        "<tt class=\"module\">$name</tt> (${word}module)", 'DEF');
+}
+
+sub my_module_index_helper($$){
+    local($word, $_) = @_;
+    my $name = next_argument();
+    return define_module($word, $name) . $_;
+}
+
+sub do_cmd_modindex{ return my_module_index_helper('', $_[0]); }
+sub do_cmd_bimodindex{ return my_module_index_helper('built-in', $_[0]); }
+sub do_cmd_exmodindex{ return my_module_index_helper('extension', $_[0]); }
+sub do_cmd_stmodindex{ return my_module_index_helper('standard', $_[0]); }
+#     local($_) = @_;
+#     my $name = next_argument();
+#     return define_module('standard', $name) . $_;
+# }
+
+sub ref_module_index_helper($$){
+    my($word, $ahref) = @_;
+    my $str = next_argument();
+    $word = "$word " if $word;
+    $str = "<tt class=\"module\">$str</tt> (${word}module)";
+    # can't use add_index_entry() since the 2nd arg to gen_index_id() is used;
+    # just inline it all here
+    $str = gen_index_id($str, 'REF');
+    $index{$str} .= $ahref;
+    write_idxfile($ahref, $str);
+}
+
+# these should be adjusted a bit....
+define_indexing_macro('refmodindex', 'refbimodindex',
+                      'refexmodindex', 'refstmodindex');
+sub idx_cmd_refmodindex($){
+    return ref_module_index_helper('', $_[0]); }
+sub idx_cmd_refbimodindex($){
+    return ref_module_index_helper('built-in', $_[0]); }
+sub idx_cmd_refexmodindex($){
+    return ref_module_index_helper('extension', $_[0]);}
+sub idx_cmd_refstmodindex($){
+    return ref_module_index_helper('standard', $_[0]); }
+
+sub do_cmd_nodename{ return do_cmd_label($_[0]); }
+
+sub init_myformat(){
+    # This depends on the override of text_cleanup() in l2hinit.perl;
+    # if that function cleans out empty tags, the first three of these
+    # variables must be set to comments.
+    #
+    # Thanks to Dave Kuhlman for figuring why some named anchors were
+    # being lost.
+    $anchor_invisible_mark = '';
+    $anchor_invisible_mark2 = '';
+    $anchor_mark = '';
+    $icons{'anchor_mark'} = '';
+}
+init_myformat();
+
+# Create an index entry, but include the string in the target anchor
+# instead of the dummy filler.
+#
+sub make_str_index_entry($){
+    my $str = $_[0];
+    my($name, $ahref) = new_link_name_info();
+    add_index_entry($str, $ahref);
+    if ($str =~ /^<[a-z]+\b/) {
+        my $s = "$str";
+        $s =~ s/^<([a-z]+)\b/<$1 id='$name' xml:id='$name'/;
+        return $s;
+    }
+    else {
+        return "<a id='$name' xml:id='$name'>$str</a>";
+    }
+}
+
+
+%TokenToTargetMapping = ();     # language:token -> link target
+%DefinedGrammars = ();          # language -> full grammar text
+%BackpatchGrammarFiles = ();    # file -> 1 (hash of files to fixup)
+
+sub do_cmd_token{
+    local($_) = @_;
+    my $token = next_argument();
+    my $target = $TokenToTargetMapping{"$CURRENT_GRAMMAR:$token"};
+    if ($token eq $CURRENT_TOKEN || $CURRENT_GRAMMAR eq '*') {
+        # recursive definition or display-only productionlist
+        return "$token";
+    }
+    if ($target eq '') {
+        $target = "<pyGrammarToken><$CURRENT_GRAMMAR><$token>";
+        if (! $BackpatchGrammarFiles{"$CURRENT_FILE"}) {
+            print "Adding '$CURRENT_FILE' to back-patch list.\n";
+        }
+        $BackpatchGrammarFiles{"$CURRENT_FILE"} = 1;
+    }
+    return "<a class='grammartoken' href=\"$target\">$token</a>" . $_;
+}
+
+sub do_cmd_grammartoken{
+    return do_cmd_token(@_);
+}
+
+sub do_env_productionlist{
+    local($_) = @_;
+    my $lang = next_optional_argument();
+    my $filename = "grammar-$lang.txt";
+    if ($lang eq '') {
+        $filename = 'grammar.txt';
+    }
+    local($CURRENT_GRAMMAR) = $lang;
+    $DefinedGrammars{$lang} .= $_;
+    return ("<dl><dd class=\"grammar\">\n"
+            . "<div class=\"productions\">\n"
+            . "<table>\n"
+            . translate_commands(translate_environments($_))
+            . "</table>\n"
+            . "</div>\n"
+            . (($lang eq '*')
+               ? ''
+               : ("<a class=\"grammar-footer\"\n"
+                  . "  href=\"$filename\" type=\"text/plain\"\n"
+                  . "  >Download entire grammar as text.</a>\n"))
+            . "</dd></dl>");
+}
+
+sub do_cmd_production{
+    local($_) = @_;
+    my $token = next_argument();
+    my $defn = next_argument();
+    my $lang = $CURRENT_GRAMMAR;
+    local($CURRENT_TOKEN) = $token;
+    if ($lang eq '*') {
+        return ("<tr>\n"
+                . "    <td>$token</td>\n"
+                . "    <td>::=</td>\n"
+                . "    <td>"
+                . translate_commands($defn)
+                . "</td></tr>"
+                . $_);
+    }
+    my $target;
+    if ($lang eq '') {
+        $target = "$CURRENT_FILE\#tok-$token";
+    }
+    else {
+        $target = "$CURRENT_FILE\#tok-$lang-$token";
+    }
+    $TokenToTargetMapping{"$CURRENT_GRAMMAR:$token"} = $target;
+    return ("<tr>\n"
+            . "    <td><a id='tok-$token' xml:id='tok-$token'>"
+            . "$token</a></td>\n"
+            . "    <td>::=</td>\n"
+            . "    <td>"
+            . translate_commands($defn)
+            . "</td></tr>"
+            . $_);
+}
+
+sub do_cmd_productioncont{
+    local($_) = @_;
+    my $defn = next_argument();
+    $defn =~ s/^( +)/'&nbsp;' x length $1/e;
+    return ("<tr>\n"
+            . "    <td></td>\n"
+            . "    <td></td>\n"
+            . "    <td><code>"
+            . translate_commands($defn)
+            . "</code></td></tr>"
+            . $_);
+}
+
+sub process_grammar_files(){
+    my $lang;
+    my $filename;
+    local($_);
+    print "process_grammar_files()\n";
+    foreach $lang (keys %DefinedGrammars) {
+        $filename = "grammar-$lang.txt";
+        if ($lang eq '*') {
+            next;
+        }
+        if ($lang eq '') {
+            $filename = 'grammar.txt';
+        }
+        open(GRAMMAR, ">$filename") || die "\n$!\n";
+        print GRAMMAR strip_grammar_markup($DefinedGrammars{$lang});
+        close(GRAMMAR);
+        print "Wrote grammar file $filename\n";
+    }
+    my $PATTERN = '<pyGrammarToken><([^>]*)><([^>]*)>';
+    foreach $filename (keys %BackpatchGrammarFiles) {
+        print "\nBack-patching grammar links in $filename\n";
+        my $buffer;
+        open(GRAMMAR, "<$filename") || die "\n$!\n";
+        # read all of the file into the buffer
+        sysread(GRAMMAR, $buffer, 1024*1024);
+        close(GRAMMAR);
+        while ($buffer =~ /$PATTERN/) {
+            my($lang, $token) = ($1, $2);
+            my $target = $TokenToTargetMapping{"$lang:$token"};
+            my $source = "<pyGrammarToken><$lang><$token>";
+            $buffer =~ s/$source/$target/g;
+        }
+        open(GRAMMAR, ">$filename") || die "\n$!\n";
+        print GRAMMAR $buffer;
+        close(GRAMMAR);
+    }
+}
+
+sub strip_grammar_markup($){
+    local($_) = @_;
+    s/\\productioncont/              /g;
+    s/\\production(<<\d+>>)(.+)\1/\n$2 ::= /g;
+    s/\\token(<<\d+>>)(.+)\1/$2/g;
+    s/\\e([^a-zA-Z])/\\$1/g;
+    s/<<\d+>>//g;
+    s/;SPMgt;/>/g;
+    s/;SPMlt;/</g;
+    s/;SPMquot;/\"/g;
+    return $_;
+}
+
+
+$REFCOUNTS_LOADED = 0;
+
+sub load_refcounts(){
+    $REFCOUNTS_LOADED = 1;
+
+    my($myname, $mydir, $myext) = fileparse(__FILE__, '\..*');
+    chop $mydir;                        # remove trailing '/'
+    ($myname, $mydir, $myext) = fileparse($mydir, '\..*');
+    chop $mydir;                        # remove trailing '/'
+    $mydir = getcwd() . "$dd$mydir"
+      unless $mydir =~ s|^/|/|;
+    local $_;
+    my $filename = "$mydir${dd}api${dd}refcounts.dat";
+    open(REFCOUNT_FILE, "<$filename") || die "\n$!\n";
+    print "[loading API refcount data]";
+    while (<REFCOUNT_FILE>) {
+        if (/([a-zA-Z0-9_]+):PyObject\*:([a-zA-Z0-9_]*):(0|[-+]1|null):(.*)$/) {
+            my($func, $param, $count, $comment) = ($1, $2, $3, $4);
+            #print "\n$func($param) --> $count";
+            $REFCOUNTS{"$func:$param"} = $count;
+        }
+    }
+}
+
+sub get_refcount($$){
+    my($func, $param) = @_;
+    load_refcounts()
+        unless $REFCOUNTS_LOADED;
+    return $REFCOUNTS{"$func:$param"};
+}
+
+
+$TLSTART = '<span class="typelabel">';
+$TLEND   = '</span>&nbsp;';
+
+sub cfuncline_helper($$$){
+    my($type, $name, $args) = @_;
+    my $idx = make_str_index_entry(
+        "<tt class=\"cfunction\">$name()</tt>" . get_indexsubitem());
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)//;           # ???? - why both of these?
+    $args =~ s/(\s|\*)([a-z_][a-z_0-9]*),/$1<var>$2<\/var>,/g;
+    $args =~ s/(\s|\*)([a-z_][a-z_0-9]*)$/$1<var>$2<\/var>/s;
+    return ('<table cellpadding="0" cellspacing="0"><tr valign="baseline">'
+            . "<td><nobr>$type\&nbsp;<b>$idx</b>(</nobr></td>"
+            . "<td>$args)</td>"
+            . '</tr></table>');
+}
+sub do_cmd_cfuncline{
+    local($_) = @_;
+    my $type = next_argument();
+    my $name = next_argument();
+    my $args = next_argument();
+    my $siginfo = cfuncline_helper($type, $name, $args);
+    return "<dt>$siginfo\n<dd>" . $_;
+}
+sub do_env_cfuncdesc{
+    local($_) = @_;
+    my $type = next_argument();
+    my $name = next_argument();
+    my $args = next_argument();
+    my $siginfo = cfuncline_helper($type, $name, $args);
+    my $result_rc = get_refcount($name, '');
+    my $rcinfo = '';
+    if ($result_rc eq '+1') {
+        $rcinfo = 'New reference';
+    }
+    elsif ($result_rc eq '0') {
+        $rcinfo = 'Borrowed reference';
+    }
+    elsif ($result_rc eq 'null') {
+        $rcinfo = 'Always <tt class="constant">NULL</tt>';
+    }
+    if ($rcinfo ne '') {
+        $rcinfo = (  "\n<div class=\"refcount-info\">"
+                   . "\n  <span class=\"label\">Return value:</span>"
+                   . "\n  <span class=\"value\">$rcinfo.</span>"
+                   . "\n</div>");
+    }
+    return "<dl><dt>$siginfo</dt>\n<dd>"
+           . $rcinfo
+           . $_
+           . '</dd></dl>';
+}
+
+sub do_cmd_cmemberline{
+    local($_) = @_;
+    my $container = next_argument();
+    my $type = next_argument();
+    my $name = next_argument();
+    my $idx = make_str_index_entry("<tt class=\"cmember\">$name</tt>"
+                                   . " ($container member)");
+    $idx =~ s/ \(.*\)//;
+    return "<dt>$type <b>$idx</b></dt>\n<dd>"
+           . $_;
+}
+sub do_env_cmemberdesc{
+    local($_) = @_;
+    my $container = next_argument();
+    my $type = next_argument();
+    my $name = next_argument();
+    my $idx = make_str_index_entry("<tt class=\"cmember\">$name</tt>"
+                                   . " ($container member)");
+    $idx =~ s/ \(.*\)//;
+    return "<dl><dt>$type <b>$idx</b></dt>\n<dd>"
+           . $_
+           . '</dl>';
+}
+
+sub do_env_csimplemacrodesc{
+    local($_) = @_;
+    my $name = next_argument();
+    my $idx = make_str_index_entry("<tt class=\"macro\">$name</tt>");
+    return "<dl><dt><b>$idx</b></dt>\n<dd>"
+           . $_
+           . '</dl>'
+}
+
+sub do_env_ctypedesc{
+    local($_) = @_;
+    my $index_name = next_optional_argument();
+    my $type_name = next_argument();
+    $index_name = $type_name
+      unless $index_name;
+    my($name, $aname, $ahref) = new_link_info();
+    add_index_entry("<tt class=\"ctype\">$index_name</tt> (C type)", $ahref);
+    return "<dl><dt><b><tt class=\"ctype\">$aname$type_name</a></tt></b></dt>"
+           . "\n<dd>"
+           . $_
+           . '</dl>'
+}
+
+sub do_env_cvardesc{
+    local($_) = @_;
+    my $var_type = next_argument();
+    my $var_name = next_argument();
+    my $idx = make_str_index_entry("<tt class=\"cdata\">$var_name</tt>"
+                                   . get_indexsubitem());
+    $idx =~ s/ \(.*\)//;
+    return "<dl><dt>$var_type <b>$idx</b></dt>\n"
+           . '<dd>'
+           . $_
+           . '</dd></dl>';
+}
+
+sub convert_args($){
+    local($IN_DESC_HANDLER) = 1;
+    local($_) = @_;
+    return translate_commands($_);
+}
+
+sub funcline_helper($$$){
+    my($first, $idxitem, $arglist) = @_;
+    return (($first ? '<dl>' : '')
+            . '<dt><table cellpadding="0" cellspacing="0"><tr valign="baseline">'
+            . "\n  <td><nobr><b>$idxitem</b>(</nobr></td>"
+            . "\n  <td><var>$arglist</var>)</td></tr></table></dt>\n<dd>");
+}
+
+sub do_env_funcdesc{
+    local($_) = @_;
+    my $function_name = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $idx = make_str_index_entry("<tt class=\"function\">$function_name()"
+                                   . '</tt>'
+                                   . get_indexsubitem());
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)<\/tt>/<\/tt>/;
+    return funcline_helper(1, $idx, $arg_list) . $_ . '</dl>';
+}
+
+sub do_env_funcdescni{
+    local($_) = @_;
+    my $function_name = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $prefix = "<tt class=\"function\">$function_name</tt>";
+    return funcline_helper(1, $prefix, $arg_list) . $_ . '</dl>';
+}
+
+sub do_cmd_funcline{
+    local($_) = @_;
+    my $function_name = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $prefix = "<tt class=\"function\">$function_name()</tt>";
+    my $idx = make_str_index_entry($prefix . get_indexsubitem());
+    $prefix =~ s/\(\)//;
+
+    return funcline_helper(0, $prefix, $arg_list) . $_;
+}
+
+sub do_cmd_funclineni{
+    local($_) = @_;
+    my $function_name = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $prefix = "<tt class=\"function\">$function_name</tt>";
+
+    return funcline_helper(0, $prefix, $arg_list) . $_;
+}
+
+# Change this flag to index the opcode entries.  I don't think it's very
+# useful to index them, since they're only presented to describe the dis
+# module.
+#
+$INDEX_OPCODES = 0;
+
+sub do_env_opcodedesc{
+    local($_) = @_;
+    my $opcode_name = next_argument();
+    my $arg_list = next_argument();
+    my $idx;
+    if ($INDEX_OPCODES) {
+        $idx = make_str_index_entry("<tt class=\"opcode\">$opcode_name</tt>"
+                                    . ' (byte code instruction)');
+        $idx =~ s/ \(byte code instruction\)//;
+    }
+    else {
+        $idx = "<tt class=\"opcode\">$opcode_name</tt>";
+    }
+    my $stuff = "<dl><dt><b>$idx</b>";
+    if ($arg_list) {
+        $stuff .= "&nbsp;&nbsp;&nbsp;&nbsp;<var>$arg_list</var>";
+    }
+    return $stuff . "</dt>\n<dd>" . $_ . '</dt></dl>';
+}
+
+sub do_env_datadesc{
+    local($_) = @_;
+    my $dataname = next_argument();
+    my $idx = make_str_index_entry("<tt>$dataname</tt>" . get_indexsubitem());
+    $idx =~ s/ \(.*\)//;
+    return "<dl><dt><b>$idx</b></dt>\n<dd>"
+           . $_
+           . '</dd></dl>';
+}
+
+sub do_env_datadescni{
+    local($_) = @_;
+    my $idx = next_argument();
+    if (! $STRING_INDEX_TT) {
+        $idx = "<tt>$idx</tt>";
+    }
+    return "<dl><dt><b>$idx</b></dt>\n<dd>" . $_ . '</dd></dl>';
+}
+
+sub do_cmd_dataline{
+    local($_) = @_;
+    my $data_name = next_argument();
+    my $idx = make_str_index_entry("<tt>$data_name</tt>" . get_indexsubitem());
+    $idx =~ s/ \(.*\)//;
+    return "<dt><b>$idx</b></dt><dd>" . $_;
+}
+
+sub do_cmd_datalineni{
+    local($_) = @_;
+    my $data_name = next_argument();
+    return "<dt><b><tt>$data_name</tt></b></dt><dd>" . $_;
+}
+
+sub do_env_excdesc{
+    local($_) = @_;
+    my $excname = next_argument();
+    my $idx = make_str_index_entry("<tt class=\"exception\">$excname</tt>");
+    return ("<dl><dt><b>${TLSTART}exception$TLEND$idx</b></dt>"
+            . "\n<dd>"
+            . $_
+            . '</dd></dl>');
+}
+
+sub do_env_fulllineitems{ return do_env_itemize(@_); }
+
+
+sub handle_classlike_descriptor($$){
+    local($_, $what) = @_;
+    $THIS_CLASS = next_argument();
+    my $arg_list = convert_args(next_argument());
+    $idx = make_str_index_entry(
+        "<tt class=\"$what\">$THIS_CLASS</tt> ($what in $THIS_MODULE)" );
+    $idx =~ s/ \(.*\)//;
+    my $prefix = "$TLSTART$what$TLEND$idx";
+    return funcline_helper(1, $prefix, $arg_list) . $_ . '</dl>';
+}
+
+sub do_env_classdesc{
+    return handle_classlike_descriptor($_[0], "class");
+}
+
+sub do_env_classdescstar{
+    local($_) = @_;
+    $THIS_CLASS = next_argument();
+    $idx = make_str_index_entry(
+        "<tt class=\"class\">$THIS_CLASS</tt> (class in $THIS_MODULE)");
+    $idx =~ s/ \(.*\)//;
+    my $prefix = "${TLSTART}class$TLEND$idx";
+    # Can't use funcline_helper() since there is no args list.
+    return "<dl><dt><b>$prefix</b>\n<dd>" . $_ . '</dl>';
+}
+
+sub do_env_excclassdesc{
+    return handle_classlike_descriptor($_[0], "exception");
+}
+
+
+sub do_env_methoddesc{
+    local($_) = @_;
+    my $class_name = next_optional_argument();
+    $class_name = $THIS_CLASS
+        unless $class_name;
+    my $method = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $extra = '';
+    if ($class_name) {
+        $extra = " ($class_name method)";
+    }
+    my $idx = make_str_index_entry(
+        "<tt class=\"method\">$method()</tt>$extra");
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)//;
+    return funcline_helper(1, $idx, $arg_list) . $_ . '</dl>';
+}
+
+
+sub do_cmd_methodline{
+    local($_) = @_;
+    my $class_name = next_optional_argument();
+    $class_name = $THIS_CLASS
+        unless $class_name;
+    my $method = next_argument();
+    my $arg_list = convert_args(next_argument());
+    my $extra = '';
+    if ($class_name) {
+        $extra = " ($class_name method)";
+    }
+    my $idx = make_str_index_entry(
+        "<tt class=\"method\">$method()</tt>$extra");
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)//;
+    return funcline_helper(0, $idx, $arg_list) . $_;
+}
+
+
+sub do_cmd_methodlineni{
+    local($_) = @_;
+    next_optional_argument();
+    my $method = next_argument();
+    my $arg_list = convert_args(next_argument());
+    return funcline_helper(0, $method, $arg_list) . $_;
+}
+
+sub do_env_methoddescni{
+    local($_) = @_;
+    next_optional_argument();
+    my $method = next_argument();
+    my $arg_list = convert_args(next_argument());
+    return funcline_helper(1, $method, $arg_list) . $_ . '</dl>';
+}
+
+
+sub do_env_memberdesc{
+    local($_) = @_;
+    my $class = next_optional_argument();
+    my $member = next_argument();
+    $class = $THIS_CLASS
+        unless $class;
+    my $extra = '';
+    $extra = " ($class attribute)"
+        if ($class ne '');
+    my $idx = make_str_index_entry("<tt class=\"member\">$member</tt>$extra");
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)//;
+    return "<dl><dt><b>$idx</b></dt>\n<dd>" . $_ . '</dl>';
+}
+
+
+sub do_cmd_memberline{
+    local($_) = @_;
+    my $class = next_optional_argument();
+    my $member = next_argument();
+    $class = $THIS_CLASS
+        unless $class;
+    my $extra = '';
+    $extra = " ($class attribute)"
+        if ($class ne '');
+    my $idx = make_str_index_entry("<tt class=\"member\">$member</tt>$extra");
+    $idx =~ s/ \(.*\)//;
+    $idx =~ s/\(\)//;
+    return "<dt><b>$idx</b></dt><dd>" . $_;
+}
+
+
+sub do_env_memberdescni{
+    local($_) = @_;
+    next_optional_argument();
+    my $member = next_argument();
+    return "<dl><dt><b><tt class=\"member\">$member</tt></b></dt>\n<dd>"
+           . $_
+           . '</dd></dl>';
+}
+
+
+sub do_cmd_memberlineni{
+    local($_) = @_;
+    next_optional_argument();
+    my $member = next_argument();
+    return "<dt><b><tt class=\"member\">$member</tt></b></dt>\n<dd>" . $_;
+}
+
+
+# For tables, we include a class on every cell to allow the CSS to set
+# the text-align property; this is because support for styling columns
+# via the <col> element appears nearly non-existant on even the latest
+# browsers (Mozilla 1.7 is stable at the time of this writing).
+# Hopefully this can be improved as browsers evolve.
+
+ at col_aligns = ('<td>', '<td>', '<td>', '<td>', '<td>');
+
+%FontConversions = ('cdata' => 'tt class="cdata"',
+                    'character' => 'tt class="character"',
+                    'class' => 'tt class="class"',
+                    'command' => 'code',
+                    'constant' => 'tt class="constant"',
+                    'exception' => 'tt class="exception"',
+                    'file' => 'tt class="file"',
+                    'filenq' => 'tt class="file"',
+                    'kbd' => 'kbd',
+                    'member' => 'tt class="member"',
+                    'programopt' => 'b',
+                    'textrm' => '',
+                    );
+
+sub fix_font($){
+    # do a little magic on a font name to get the right behavior in the first
+    # column of the output table
+    my $font = $_[0];
+    if (defined $FontConversions{$font}) {
+        $font = $FontConversions{$font};
+    }
+    return $font;
+}
+
+sub figure_column_alignment($){
+    my $a = $_[0];
+    if (!defined $a) {
+        return '';
+    }
+    my $mark = substr($a, 0, 1);
+    my $r = '';
+    if ($mark eq 'c')
+      { $r = ' class="center"'; }
+    elsif ($mark eq 'r')
+      { $r = ' class="right" '; }
+    elsif ($mark eq 'l')
+      { $r = ' class="left"  '; }
+    elsif ($mark eq 'p')
+      { $r = ' class="left"  '; }
+    return $r;
+}
+
+sub setup_column_alignments($){
+    local($_) = @_;
+    my($s1, $s2, $s3, $s4, $s5) = split(/[|]/,$_);
+    my $a1 = figure_column_alignment($s1);
+    my $a2 = figure_column_alignment($s2);
+    my $a3 = figure_column_alignment($s3);
+    my $a4 = figure_column_alignment($s4);
+    my $a5 = figure_column_alignment($s5);
+    $col_aligns[0] = "<td$a1 valign=\"baseline\">";
+    $col_aligns[1] = "<td$a2>";
+    $col_aligns[2] = "<td$a3>";
+    $col_aligns[3] = "<td$a4>";
+    $col_aligns[4] = "<td$a5>";
+    # return the aligned header start tags
+    return ("<th$a1>", "<th$a2>", "<th$a3>", "<th$a4>", "<th$a5>");
+}
+
+sub get_table_col1_fonts(){
+    my $font = $globals{'lineifont'};
+    my($sfont, $efont) = ('', '');
+    if ($font) {
+        $sfont = "<$font>";
+        $efont = "</$font>";
+        $efont =~ s/ .*>/>/;
+    }
+    return ($sfont, $efont);
+}
+
+sub do_env_tableii{
+    local($_) = @_;
+    my $arg = next_argument();
+    my($th1, $th2, $th3, $th4, $th5) = setup_column_alignments($arg);
+    my $font = fix_font(next_argument());
+    my $h1 = next_argument();
+    my $h2 = next_argument();
+    s/[\s\n]+//;
+    $globals{'lineifont'} = $font;
+    my $a1 = $col_aligns[0];
+    my $a2 = $col_aligns[1];
+    s/\\lineii</\\lineii[$a1|$a2]</g;
+    return '<div class="center"><table class="realtable">'
+           . "\n  <thead>"
+           . "\n    <tr>"
+           . "\n      $th1$h1</th>"
+           . "\n      $th2$h2</th>"
+           . "\n      </tr>"
+           . "\n    </thead>"
+           . "\n  <tbody>"
+           . $_
+           . "\n    </tbody>"
+           . "\n</table></div>";
+}
+
+sub do_env_longtableii{
+    return do_env_tableii(@_);
+}
+
+sub do_cmd_lineii{
+    local($_) = @_;
+    my $aligns = next_optional_argument();
+    my $c1 = next_argument();
+    my $c2 = next_argument();
+    s/[\s\n]+//;
+    my($sfont, $efont) = get_table_col1_fonts();
+    my($c1align, $c2align) = split('\|', $aligns);
+    return "\n    <tr>$c1align$sfont$c1$efont</td>\n"
+           . "        $c2align$c2</td></tr>"
+           . $_;
+}
+
+sub do_env_tableiii{
+    local($_) = @_;
+    my $arg = next_argument();
+    my($th1, $th2, $th3, $th4, $th5) = setup_column_alignments($arg);
+    my $font = fix_font(next_argument());
+    my $h1 = next_argument();
+    my $h2 = next_argument();
+    my $h3 = next_argument();
+    s/[\s\n]+//;
+    $globals{'lineifont'} = $font;
+    my $a1 = $col_aligns[0];
+    my $a2 = $col_aligns[1];
+    my $a3 = $col_aligns[2];
+    s/\\lineiii</\\lineiii[$a1|$a2|$a3]</g;
+    return '<div class="center"><table class="realtable">'
+           . "\n  <thead>"
+           . "\n    <tr>"
+           . "\n      $th1$h1</th>"
+           . "\n      $th2$h2</th>"
+           . "\n      $th3$h3</th>"
+           . "\n      </tr>"
+           . "\n    </thead>"
+           . "\n  <tbody>"
+           . $_
+           . "\n    </tbody>"
+           . "\n</table></div>";
+}
+
+sub do_env_longtableiii{
+    return do_env_tableiii(@_);
+}
+
+sub do_cmd_lineiii{
+    local($_) = @_;
+    my $aligns = next_optional_argument();
+    my $c1 = next_argument();
+    my $c2 = next_argument();
+    my $c3 = next_argument();
+    s/[\s\n]+//;
+    my($sfont, $efont) = get_table_col1_fonts();
+    my($c1align, $c2align, $c3align) = split('\|', $aligns);
+    return "\n    <tr>$c1align$sfont$c1$efont</td>\n"
+           . "        $c2align$c2</td>\n"
+           . "        $c3align$c3</td></tr>"
+           . $_;
+}
+
+sub do_env_tableiv{
+    local($_) = @_;
+    my $arg = next_argument();
+    my($th1, $th2, $th3, $th4, $th5) = setup_column_alignments($arg);
+    my $font = fix_font(next_argument());
+    my $h1 = next_argument();
+    my $h2 = next_argument();
+    my $h3 = next_argument();
+    my $h4 = next_argument();
+    s/[\s\n]+//;
+    $globals{'lineifont'} = $font;
+    my $a1 = $col_aligns[0];
+    my $a2 = $col_aligns[1];
+    my $a3 = $col_aligns[2];
+    my $a4 = $col_aligns[3];
+    s/\\lineiv</\\lineiv[$a1|$a2|$a3|$a4]</g;
+    return '<div class="center"><table class="realtable">'
+           . "\n  <thead>"
+           . "\n    <tr>"
+           . "\n      $th1$h1</th>"
+           . "\n      $th2$h2</th>"
+           . "\n      $th3$h3</th>"
+           . "\n      $th4$h4</th>"
+           . "\n      </tr>"
+           . "\n    </thead>"
+           . "\n  <tbody>"
+           . $_
+           . "\n    </tbody>"
+           . "\n</table></div>";
+}
+
+sub do_env_longtableiv{
+    return do_env_tableiv(@_);
+}
+
+sub do_cmd_lineiv{
+    local($_) = @_;
+    my $aligns = next_optional_argument();
+    my $c1 = next_argument();
+    my $c2 = next_argument();
+    my $c3 = next_argument();
+    my $c4 = next_argument();
+    s/[\s\n]+//;
+    my($sfont, $efont) = get_table_col1_fonts();
+    my($c1align, $c2align, $c3align, $c4align) = split('\|', $aligns);
+    return "\n    <tr>$c1align$sfont$c1$efont</td>\n"
+           . "        $c2align$c2</td>\n"
+           . "        $c3align$c3</td>\n"
+           . "        $c4align$c4</td></tr>"
+           . $_;
+}
+
+sub do_env_tablev{
+    local($_) = @_;
+    my $arg = next_argument();
+    my($th1, $th2, $th3, $th4, $th5) = setup_column_alignments($arg);
+    my $font = fix_font(next_argument());
+    my $h1 = next_argument();
+    my $h2 = next_argument();
+    my $h3 = next_argument();
+    my $h4 = next_argument();
+    my $h5 = next_argument();
+    s/[\s\n]+//;
+    $globals{'lineifont'} = $font;
+    my $a1 = $col_aligns[0];
+    my $a2 = $col_aligns[1];
+    my $a3 = $col_aligns[2];
+    my $a4 = $col_aligns[3];
+    my $a5 = $col_aligns[4];
+    s/\\linev</\\linev[$a1|$a2|$a3|$a4|$a5]</g;
+    return '<div class="center"><table class="realtable">'
+           . "\n  <thead>"
+           . "\n    <tr>"
+           . "\n      $th1$h1</th>"
+           . "\n      $th2$h2</th>"
+           . "\n      $th3$h3</th>"
+           . "\n      $th4$h4</th>"
+           . "\n      $th5$h5</th>"
+           . "\n      </tr>"
+           . "\n    </thead>"
+           . "\n  <tbody>"
+           . $_
+           . "\n    </tbody>"
+           . "\n</table></div>";
+}
+
+sub do_env_longtablev{
+    return do_env_tablev(@_);
+}
+
+sub do_cmd_linev{
+    local($_) = @_;
+    my $aligns = next_optional_argument();
+    my $c1 = next_argument();
+    my $c2 = next_argument();
+    my $c3 = next_argument();
+    my $c4 = next_argument();
+    my $c5 = next_argument();
+    s/[\s\n]+//;
+    my($sfont, $efont) = get_table_col1_fonts();
+    my($c1align, $c2align, $c3align, $c4align, $c5align) = split('\|',$aligns);
+    return "\n    <tr>$c1align$sfont$c1$efont</td>\n"
+           . "        $c2align$c2</td>\n"
+           . "        $c3align$c3</td>\n"
+           . "        $c4align$c4</td>\n"
+           . "        $c5align$c5</td></tr>"
+           . $_;
+}
+
+
+# These can be used to control the title page appearance;
+# they need a little bit of documentation.
+#
+# If $TITLE_PAGE_GRAPHIC is set, it should be the name of a file in the
+# $ICONSERVER directory, or include path information (other than "./").  The
+# default image type will be assumed if an extension is not provided.
+#
+# If specified, the "title page" will contain two colums: one containing the
+# title/author/etc., and the other containing the graphic.  Use the other
+# four variables listed here to control specific details of the layout; all
+# are optional.
+#
+# $TITLE_PAGE_GRAPHIC = "my-company-logo";
+# $TITLE_PAGE_GRAPHIC_COLWIDTH = "30%";
+# $TITLE_PAGE_GRAPHIC_WIDTH = 150;
+# $TITLE_PAGE_GRAPHIC_HEIGHT = 150;
+# $TITLE_PAGE_GRAPHIC_ON_RIGHT = 0;
+
+sub make_my_titlepage(){
+    my $the_title = "";
+    if ($t_title) {
+        $the_title .= "\n<h1>$t_title</h1>";
+    }
+    else {
+        write_warnings("\nThis document has no title.");
+    }
+    if ($t_author) {
+        if ($t_authorURL) {
+            my $href = translate_commands($t_authorURL);
+            $href = make_named_href('author', $href,
+                                    "<b><font size=\"+2\">$t_author"
+                                    . '</font></b>');
+            $the_title .= "\n<p>$href</p>";
+        }
+        else {
+            $the_title .= ("\n<p><b><font size=\"+2\">$t_author"
+                           . '</font></b></p>');
+        }
+    }
+    else {
+        write_warnings("\nThere is no author for this document.");
+    }
+    if ($t_institute) {
+        $the_title .= "\n<p>$t_institute</p>";
+    }
+    if ($DEVELOPER_ADDRESS) {
+        $the_title .= "\n<p>$DEVELOPER_ADDRESS</p>";
+    }
+    if ($t_affil) {
+        $the_title .= "\n<p><i>$t_affil</i></p>";
+    }
+    if ($t_date) {
+        $the_title .= "\n<p>";
+        if ($PACKAGE_VERSION) {
+            $the_title .= ('<strong>Release '
+                           . "$PACKAGE_VERSION$RELEASE_INFO</strong><br />\n");
+        }
+        $the_title .= "<strong>$t_date</strong></p>"
+    }
+    if ($t_address) {
+        $the_title .= "\n<p>$t_address</p>";
+    }
+    else {
+        $the_title .= "\n<p></p>";
+    }
+    if ($t_email) {
+        $the_title .= "\n<p>$t_email</p>";
+    }
+    return $the_title;
+}
+
+sub make_my_titlegraphic(){
+    my $filename = make_icon_filename($TITLE_PAGE_GRAPHIC);
+    my $graphic = "<td class=\"titlegraphic\"";
+    $graphic .= " width=\"$TITLE_PAGE_GRAPHIC_COLWIDTH\""
+      if ($TITLE_PAGE_GRAPHIC_COLWIDTH);
+    $graphic .= "><img";
+    $graphic .= " width=\"$TITLE_PAGE_GRAPHIC_WIDTH\""
+      if ($TITLE_PAGE_GRAPHIC_WIDTH);
+    $graphic .= " height=\"$TITLE_PAGE_GRAPHIC_HEIGHT\""
+      if ($TITLE_PAGE_GRAPHIC_HEIGHT);
+    $graphic .= "\n  src=\"$filename\" /></td>\n";
+    return $graphic;
+}
+
+sub do_cmd_maketitle{
+    local($_) = @_;
+    my $the_title = "\n";
+    if ($EXTERNAL_UP_LINK) {
+        # This generates a <link> element in the wrong place (the
+        # body), but I don't see any other way to get this generated
+        # at all.  Browsers like Mozilla, that support navigation
+        # links, can make use of this.
+        $the_title .= ("<link rel='up' href='$EXTERNAL_UP_LINK'"
+                       . ($EXTERNAL_UP_TITLE
+                          ? " title='$EXTERNAL_UP_TITLE'" : '')
+                       . " />\n");
+    }
+    $the_title .= '<div class="titlepage">';
+    if ($TITLE_PAGE_GRAPHIC) {
+        if ($TITLE_PAGE_GRAPHIC_ON_RIGHT) {
+            $the_title .= ("\n<table border=\"0\" width=\"100%\">"
+                           . "<tr align=\"right\">\n<td>"
+                           . make_my_titlepage()
+                           . "</td>\n"
+                           . make_my_titlegraphic()
+                           . "</tr>\n</table>");
+        }
+        else {
+            $the_title .= ("\n<table border=\"0\" width=\"100%\"><tr>\n"
+                           . make_my_titlegraphic()
+                           . "<td>"
+                           . make_my_titlepage()
+                           . "</td></tr>\n</table>");
+        }
+    }
+    else {
+        $the_title .= ("\n<div class='center'>"
+                       . make_my_titlepage()
+                       . "\n</div>");
+    }
+    $the_title .= "\n</div>";
+    return $the_title . $_;
+}
+
+
+#
+#  Module synopsis support
+#
+
+require SynopsisTable;
+
+sub get_chapter_id(){
+    my $id = do_cmd_thechapter('');
+    $id =~ s/<SPAN CLASS="arabic">(\d+)<\/SPAN>/$1/;
+    $id =~ s/\.//;
+    return $id;
+}
+
+# 'chapter' => 'SynopsisTable instance'
+%ModuleSynopses = ();
+
+sub get_synopsis_table($){
+    my $chap = $_[0];
+    my $key;
+    foreach $key (keys %ModuleSynopses) {
+        if ($key eq $chap) {
+            return $ModuleSynopses{$chap};
+        }
+    }
+    my $st = SynopsisTable->new();
+    $ModuleSynopses{$chap} = $st;
+    return $st;
+}
+
+sub do_cmd_moduleauthor{
+    local($_) = @_;
+    next_argument();
+    next_argument();
+    return $_;
+}
+
+sub do_cmd_sectionauthor{
+    local($_) = @_;
+    next_argument();
+    next_argument();
+    return $_;
+}
+
+sub do_cmd_declaremodule{
+    local($_) = @_;
+    my $key = next_optional_argument();
+    my $type = next_argument();
+    my $name = next_argument();
+    my $st = get_synopsis_table(get_chapter_id());
+    #
+    $key = $name unless $key;
+    $type = 'built-in' if $type eq 'builtin';
+    $st->declare($name, $key, $type);
+    define_module($type, $name);
+    return anchor_label("module-$key",$CURRENT_FILE,$_)
+}
+
+sub do_cmd_modulesynopsis{
+    local($_) = @_;
+    my $st = get_synopsis_table(get_chapter_id());
+    $st->set_synopsis($THIS_MODULE, translate_commands(next_argument()));
+    return $_;
+}
+
+sub do_cmd_localmoduletable{
+    local($_) = @_;
+    my $chap = get_chapter_id();
+    my $st = get_synopsis_table($chap);
+    $st->set_file("$CURRENT_FILE");
+    return "<tex2html-localmoduletable><$chap>\\tableofchildlinks[off]" . $_;
+}
+
+sub process_all_localmoduletables(){
+    my $key;
+    foreach $key (keys %ModuleSynopses) {
+        my $st = $ModuleSynopses{$key};
+        my $file = $st->get_file();
+        if ($file) {
+            process_localmoduletables_in_file($file);
+        }
+        else {
+            print "\nsynopsis table $key has no file association\n";
+        }
+    }
+}
+
+sub process_localmoduletables_in_file($){
+    my $file = $_[0];
+    open(MYFILE, "<$file");
+    local($_);
+    sysread(MYFILE, $_, 1024*1024);
+    close(MYFILE);
+    # need to get contents of file in $_
+    while (/<tex2html-localmoduletable><(\d+)>/) {
+        my $match = $&;
+        my $chap = $1;
+        my $st = get_synopsis_table($chap);
+        my $data = $st->tohtml();
+        s/$match/$data/;
+    }
+    open(MYFILE,">$file");
+    print MYFILE $_;
+    close(MYFILE);
+}
+sub process_python_state(){
+    process_all_localmoduletables();
+    process_grammar_files();
+}
+
+
+#
+#  "See also:" -- references placed at the end of a \section
+#
+
+sub do_env_seealso{
+    return ("<div class=\"seealso\">\n  "
+            . "<p class=\"heading\">See Also:</p>\n"
+            . $_[0]
+            . '</div>');
+}
+
+sub do_env_seealsostar{
+    return ("<div class=\"seealso-simple\">\n  "
+            . $_[0]
+            . '</div>');
+}
+
+sub do_cmd_seemodule{
+    # Insert the right magic to jump to the module definition.  This should
+    # work most of the time, at least for repeat builds....
+    local($_) = @_;
+    my $key = next_optional_argument();
+    my $module = next_argument();
+    my $text = next_argument();
+    my $period = '.';
+    $key = $module
+        unless $key;
+    if ($text =~ /\.$/) {
+        $period = '';
+    }
+    return ('<dl compact="compact" class="seemodule">'
+            . "\n    <dt>Module <b><tt class=\"module\">"
+            . "<a href=\"module-$key.html\">$module</a></tt>:</b>"
+            . "\n    <dd>$text$period\n  </dl>"
+            . $_);
+}
+
+sub strip_html_markup($){
+    my $str = $_[0];
+    my $s = "$str";
+    $s =~ s/<[a-zA-Z0-9]+(\s+[a-zA-Z0-9]+(\s*=\s*(\'[^\']*\'|\"[^\"]*\"|[a-zA-Z0-9]+))?)*\s*>//g;
+    $s =~ s/<\/[a-zA-Z0-9]+>//g;
+    return $s;
+}
+
+sub handle_rfclike_reference($$$){
+    local($_, $what, $format) = @_;
+    my $rfcnum = next_argument();
+    my $title = next_argument();
+    my $text = next_argument();
+    my $url = get_rfc_url($rfcnum, $format);
+    my $icon = get_link_icon($url);
+    my $attrtitle = strip_html_markup($title);
+    return '<dl compact="compact" class="seerfc">'
+      . "\n    <dt><a href=\"$url\""
+      . "\n        title=\"$attrtitle\""
+      . "\n        >$what $rfcnum, <em>$title</em>$icon</a>"
+      . "\n    <dd>$text\n  </dl>"
+      . $_;
+}
+
+sub do_cmd_seepep{
+    return handle_rfclike_reference($_[0], "PEP", $PEP_FORMAT);
+}
+
+sub do_cmd_seerfc{
+    # XXX Would be nice to add links to the text/plain and PDF versions.
+    return handle_rfclike_reference($_[0], "RFC", $RFC_FORMAT);
+}
+
+sub do_cmd_seetitle{
+    local($_) = @_;
+    my $url = next_optional_argument();
+    my $title = next_argument();
+    my $text = next_argument();
+    if ($url) {
+        my $icon = get_link_icon($url);
+        return '<dl compact="compact" class="seetitle">'
+          . "\n    <dt><em class=\"citetitle\"><a href=\"$url\""
+          . "\n        >$title$icon</a></em></dt>"
+          . "\n    <dd>$text</dd>\n  </dl>"
+          . $_;
+    }
+    return '<dl compact="compact" class="seetitle">'
+      . "\n    <dt><em class=\"citetitle\""
+      . "\n        >$title</em></dt>"
+      . "\n    <dd>$text</dd>\n  </dl>"
+      . $_;
+}
+
+sub do_cmd_seelink{
+    local($_) = @_;
+    my $url = next_argument();
+    my $linktext = next_argument();
+    my $text = next_argument();
+    my $icon = get_link_icon($url);
+    return '<dl compact="compact" class="seeurl">'
+      . "\n    <dt><a href='$url'"
+      . "\n        >$linktext$icon</a></dt>"
+      . "\n    <dd>$text</dd>\n  </dl>"
+      . $_;
+}
+
+sub do_cmd_seeurl{
+    local($_) = @_;
+    my $url = next_argument();
+    my $text = next_argument();
+    my $icon = get_link_icon($url);
+    return '<dl compact="compact" class="seeurl">'
+      . "\n    <dt><a href=\"$url\""
+      . "\n        class=\"url\">$url$icon</a></dt>"
+      . "\n    <dd>$text</dd>\n  </dl>"
+      . $_;
+}
+
+sub do_cmd_seetext{
+    local($_) = @_;
+    my $content = next_argument();
+    return '<div class="seetext"><p>' . $content . '</p></div>' . $_;
+}
+
+
+#
+#  Definition list support.
+#
+
+sub do_env_definitions{
+    return '<dl class="definitions">' . $_[0] . "</dl>\n";
+}
+
+sub do_cmd_term{
+    local($_) = @_;
+    my $term = next_argument();
+    my($name, $aname, $ahref) = new_link_info();
+    # could easily add an index entry here...
+    return "<dt><b>$aname" . $term . "</a></b></dt>\n<dd>" . $_;
+}
+
+
+# Commands listed here have process-order dependencies; these often
+# are related to indexing operations.
+# XXX Not sure why funclineni, methodlineni, and samp are here.
+#
+process_commands_wrap_deferred(<<_RAW_ARG_DEFERRED_CMDS_);
+declaremodule # [] # {} # {}
+funcline # {} # {}
+funclineni # {} # {}
+memberline # [] # {}
+methodline # [] # {} # {}
+methodlineni # [] # {} # {}
+modulesynopsis # {}
+bifuncindex # {}
+exindex # {}
+indexii # {} # {}
+indexiii # {} # {} # {}
+indexiv # {} # {} # {} # {}
+kwindex # {}
+obindex # {}
+opindex # {}
+stindex # {}
+platform # {}
+samp # {}
+setindexsubitem # {}
+withsubitem # {} # {}
+_RAW_ARG_DEFERRED_CMDS_
+
+
+$alltt_start = '<div class="verbatim"><pre>';
+$alltt_end = '</pre></div>';
+
+sub do_env_alltt{
+    local ($_) = @_;
+    local($closures,$reopens, at open_block_tags);
+
+    # get the tag-strings for all open tags
+    local(@keep_open_tags) = @$open_tags_R;
+    ($closures,$reopens) = &preserve_open_tags() if (@$open_tags_R);
+
+    # get the tags for text-level tags only
+    $open_tags_R = [ @keep_open_tags ];
+    local($local_closures, $local_reopens);
+    ($local_closures, $local_reopens, at open_block_tags)
+      = &preserve_open_block_tags
+        if (@$open_tags_R);
+
+    $open_tags_R = [ @open_block_tags ];
+
+    do {
+        local($open_tags_R) = [ @open_block_tags ];
+        local(@save_open_tags) = ();
+
+        local($cnt) = ++$global{'max_id'};
+        $_ = join('',"$O$cnt$C\\tt$O", ++$global{'max_id'}, $C
+                , $_ , $O, $global{'max_id'}, "$C$O$cnt$C");
+
+        $_ = &translate_environments($_);
+        $_ = &translate_commands($_) if (/\\/);
+
+        # remove spurious <BR> someone sticks in; not sure where they
+        # actually come from
+        # XXX the replacement space is there to accomodate something
+        # broken that inserts a space in front of the first line of
+        # the environment
+        s/<BR>/ /gi;
+
+        $_ = join('', $closures, $alltt_start, $local_reopens
+                , $_
+                , &balance_tags() #, $local_closures
+                , $alltt_end, $reopens);
+        undef $open_tags_R; undef @save_open_tags;
+    };
+    $open_tags_R = [ @keep_open_tags ];
+    return codetext($_);
+}
+
+# List of all filenames produced by do_cmd_verbatiminput()
+%VerbatimFiles = ();
+ at VerbatimOutputs = ();
+
+sub get_verbatim_output_name($){
+    my $file = $_[0];
+    #
+    # Re-write the source filename to always use a .txt extension
+    # so that Web servers will present it as text/plain.  This is
+    # needed since there is no other even moderately reliable way
+    # to get the right Content-Type header on text files for
+    # servers which we can't configure (like python.org mirrors).
+    #
+    if (defined $VerbatimFiles{$file}) {
+        # We've seen this one before; re-use the same output file.
+        return $VerbatimFiles{$file};
+    }
+    my($srcname, $srcdir, $srcext) = fileparse($file, '\..*');
+    $filename = "$srcname.txt";
+    #
+    # We need to determine if our default filename is already
+    # being used, and find a new one it it is.  If the name is in
+    # used, this algorithm will first attempt to include the
+    # source extension as part of the name, and if that is also in
+    # use (if the same file is included multiple times, or if
+    # another source file has that as the base name), a counter is
+    # used instead.
+    #
+    my $found = 1;
+  FIND:
+    while ($found) {
+        foreach $fn (@VerbatimOutputs) {
+            if ($fn eq $filename) {
+                if ($found == 1) {
+                    $srcext =~ s/^[.]//;  # Remove '.' from extension
+                    $filename = "$srcname-$srcext.txt";
+                }
+                else {
+                    $filename = "$srcname-$found.txt";
+                }
+                ++$found;
+                next FIND;
+            }
+        }
+        $found = 0;
+    }
+    push @VerbatimOutputs, $filename;
+    $VerbatimFiles{$file} = $filename;
+    return $filename;
+}
+
+sub do_cmd_verbatiminput{
+    local($_) = @_;
+    my $fname = next_argument();
+    my $file;
+    my $found = 0;
+    my $texpath;
+    # Search TEXINPUTS for the input file, the way we're supposed to:
+    foreach $texpath (split /$envkey/, $TEXINPUTS) {
+        $file = "$texpath$dd$fname";
+        last if ($found = (-f $file));
+    }
+    my $filename = '';
+    my $text;
+    if ($found) {
+        open(MYFILE, "<$file") || die "\n$!\n";
+        read(MYFILE, $text, 1024*1024);
+        close(MYFILE);
+        $filename = get_verbatim_output_name($file);
+        # Now that we have a filename, write it out.
+        open(MYFILE, ">$filename");
+        print MYFILE $text;
+        close(MYFILE);
+        #
+        # These rewrites convert the raw text to something that will
+        # be properly visible as HTML and also will pass through the
+        # vagaries of conversion through LaTeX2HTML.  The order in
+        # which the specific rewrites are performed is significant.
+        #
+        $text =~ s/\&/\&amp;/g;
+        # These need to happen before the normal < and > re-writes,
+        # since we need to avoid LaTeX2HTML's attempt to perform
+        # ligature processing without regard to context (since it
+        # doesn't have font information).
+        $text =~ s/--/-&\#45;/g;
+        $text =~ s/<</\&lt;\&\#60;/g;
+        $text =~ s/>>/\&gt;\&\#62;/g;
+        # Just normal re-writes...
+        $text =~ s/</\&lt;/g;
+        $text =~ s/>/\&gt;/g;
+        # These last isn't needed for the HTML, but is needed to get
+        # past LaTeX2HTML processing TeX macros.  We use &#92; instead
+        # of &sol; since many browsers don't support that.
+        $text =~ s/\\/\&\#92;/g;
+    }
+    else {
+        return '<b>Could not locate requested file <i>$fname</i>!</b>\n';
+    }
+    my $note = 'Download as text.';
+    if ($file ne $filename) {
+        $note = ('Download as text (original file name: <span class="file">'
+                 . $fname
+                 . '</span>).');
+    }
+    return ("<div class=\"verbatim\">\n<pre>"
+            . $text
+            . "</pre>\n<div class=\"footer\">\n"
+            . "<a href=\"$filename\" type=\"text/plain\""
+            . ">$note</a>"
+            . "\n</div></div>"
+            . $_);
+}
+
+1;                              # This must be the last line

Added: sandbox/trunk/pdb/Doc/texinputs/fncychap.sty
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/fncychap.sty	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,433 @@
+%%% Derived from the original fncychap.sty,
+%%% but changed ``TWELV'' to ``TWELVE''.
+
+%%% Copyright   Ulf A. Lindgren
+%%%             Department of Applied Electronics
+%%%             Chalmers University of Technology
+%%%             S-412 96 Gothenburg, Sweden
+%%%             E-mail lindgren at ae.chalmers.se
+%%%
+%%% Note        Permission is granted to modify this file under
+%%%             the condition that it is saved using another
+%%%             file and package name.
+%%%
+%%% Revision    1.1
+%%%
+%%%             Jan. 8th Modified package name base date option
+%%%             Jan. 22th Modified FmN and FmTi for error in book.cls
+%%%                  \MakeUppercase{#}->{\MakeUppercase#}
+%%%             Apr. 6th Modified Lenny option to prevent undesired 
+%%%                  skip of line.
+%%%             Nov. 8th Fixed \@chapapp for AMS
+%%%             Feb. 11th Fixed appendix problem related to Bjarne
+%%% Last modified    Feb. 11th 1998
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesPackage{fncychap}
+             [1997/04/06 v1.11
+                 LaTeX package (Revised chapters)]
+
+%%%% DEFINITION OF Chapapp variables
+\newcommand{\CNV}{\huge\bfseries}
+\newcommand{\ChNameVar}[1]{\renewcommand{\CNV}{#1}}
+
+
+%%%% DEFINITION OF TheChapter variables
+\newcommand{\CNoV}{\huge\bfseries}
+\newcommand{\ChNumVar}[1]{\renewcommand{\CNoV}{#1}}
+
+\newif\ifUCN
+\UCNfalse
+\newif\ifLCN
+\LCNfalse
+\def\ChNameLowerCase{\LCNtrue\UCNfalse}
+\def\ChNameUpperCase{\UCNtrue\LCNfalse}
+\def\ChNameAsIs{\UCNfalse\LCNfalse}
+
+%%%%% Fix for AMSBook 971008
+
+\@ifundefined{@chapapp}{\let\@chapapp\chaptername}{}
+
+
+%%%%% Fix for Bjarne and appendix 980211
+
+\newif\ifinapp
+\inappfalse
+\renewcommand\appendix{\par
+  \setcounter{chapter}{0}%
+  \setcounter{section}{0}%
+  \inapptrue%
+  \renewcommand\@chapapp{\appendixname}%
+  \renewcommand\thechapter{\@Alph\c at chapter}}
+
+%%%%%
+
+\newcommand{\FmN}[1]{%
+\ifUCN
+   {\MakeUppercase#1}\LCNfalse
+\else
+   \ifLCN
+      {\MakeLowercase#1}\UCNfalse
+   \else #1
+   \fi
+\fi}
+
+
+%%%% DEFINITION OF Title variables
+\newcommand{\CTV}{\Huge\bfseries}
+\newcommand{\ChTitleVar}[1]{\renewcommand{\CTV}{#1}}
+
+%%%% DEFINITION OF the basic rule width
+\newlength{\RW}
+\setlength{\RW}{1pt}
+\newcommand{\ChRuleWidth}[1]{\setlength{\RW}{#1}}
+
+\newif\ifUCT
+\UCTfalse
+\newif\ifLCT
+\LCTfalse
+\def\ChTitleLowerCase{\LCTtrue\UCTfalse}
+\def\ChTitleUpperCase{\UCTtrue\LCTfalse}
+\def\ChTitleAsIs{\UCTfalse\LCTfalse}
+\newcommand{\FmTi}[1]{%
+\ifUCT
+
+   {\MakeUppercase#1}\LCTfalse
+\else
+   \ifLCT
+      {\MakeLowercase#1}\UCTfalse
+   \else #1
+   \fi
+\fi}
+
+
+
+\newlength{\mylen}
+\newlength{\myhi}
+\newlength{\px}
+\newlength{\py}
+\newlength{\pyy}
+\newlength{\pxx}
+
+
+\def\mghrulefill#1{\leavevmode\leaders\hrule\@height #1\hfill\kern\z@}
+
+\newcommand{\DOCH}{%
+  \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+  \par\nobreak
+  \vskip 20\p@
+  }
+\newcommand{\DOTI}[1]{%
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@
+    }
+\newcommand{\DOTIS}[1]{%
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@
+    }
+
+%%%%%% SONNY DEF
+
+\DeclareOption{Sonny}{%
+  \ChNameVar{\Large\sf}
+  \ChNumVar{\Huge}
+  \ChTitleVar{\Large\sf}
+  \ChRuleWidth{0.5pt}
+  \ChNameUpperCase
+  \renewcommand{\DOCH}{%
+    \raggedleft
+    \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+    \par\nobreak
+    \vskip 40\p@}
+  \renewcommand{\DOTI}[1]{%
+    \CTV\raggedleft\mghrulefill{\RW}\par\nobreak
+    \vskip 5\p@
+    \CTV\FmTi{#1}\par\nobreak
+    \mghrulefill{\RW}\par\nobreak
+    \vskip 40\p@}
+  \renewcommand{\DOTIS}[1]{%
+    \CTV\raggedleft\mghrulefill{\RW}\par\nobreak
+    \vskip 5\p@
+    \CTV\FmTi{#1}\par\nobreak
+    \mghrulefill{\RW}\par\nobreak
+    \vskip 40\p@}
+}
+
+%%%%%% LENNY DEF
+
+\DeclareOption{Lenny}{%
+
+  \ChNameVar{\fontsize{14}{16}\usefont{OT1}{phv}{m}{n}\selectfont}
+  \ChNumVar{\fontsize{60}{62}\usefont{OT1}{ptm}{m}{n}\selectfont}
+  \ChTitleVar{\Huge\bfseries\rm}
+  \ChRuleWidth{1pt}
+  \renewcommand{\DOCH}{%
+    \settowidth{\px}{\CNV\FmN{\@chapapp}}
+    \addtolength{\px}{2pt}
+    \settoheight{\py}{\CNV\FmN{\@chapapp}}
+    \addtolength{\py}{1pt}
+
+    \settowidth{\mylen}{\CNV\FmN{\@chapapp}\space\CNoV\thechapter}
+    \addtolength{\mylen}{1pt}
+    \settowidth{\pxx}{\CNoV\thechapter}
+    \addtolength{\pxx}{-1pt}
+
+    \settoheight{\pyy}{\CNoV\thechapter}
+    \addtolength{\pyy}{-2pt}
+    \setlength{\myhi}{\pyy}
+    \addtolength{\myhi}{-1\py}
+    \par
+    \parbox[b]{\textwidth}{%
+    \rule[\py]{\RW}{\myhi}%
+    \hskip -\RW%
+    \rule[\pyy]{\px}{\RW}%
+    \hskip -\px%
+    \raggedright%
+    \CNV\FmN{\@chapapp}\space\CNoV\thechapter%
+    \hskip1pt%
+    \mghrulefill{\RW}%
+    \rule{\RW}{\pyy}\par\nobreak%
+    \vskip -\baselineskip%
+    \vskip -\pyy%
+    \hskip \mylen%
+    \mghrulefill{\RW}\par\nobreak%
+    \vskip \pyy}%
+    \vskip 20\p@}
+ 
+
+  \renewcommand{\DOTI}[1]{%
+    \raggedright
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@}
+
+  \renewcommand{\DOTIS}[1]{%
+    \raggedright
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@}
+ }
+
+
+%%%%%%% GLENN DEF
+
+
+\DeclareOption{Glenn}{%
+  \ChNameVar{\bfseries\Large\sf}
+  \ChNumVar{\Huge}
+  \ChTitleVar{\bfseries\Large\rm}
+  \ChRuleWidth{1pt}
+  \ChNameUpperCase
+  \ChTitleUpperCase
+  \renewcommand{\DOCH}{%
+    \settoheight{\myhi}{\CTV\FmTi{Test}}
+    \setlength{\py}{\baselineskip}
+    \addtolength{\py}{\RW}
+    \addtolength{\py}{\myhi}
+    \setlength{\pyy}{\py}
+    \addtolength{\pyy}{-1\RW}
+     
+    \raggedright
+    \CNV\FmN{\@chapapp}\space\CNoV\thechapter
+    \hskip 3pt\mghrulefill{\RW}\rule[-1\pyy]{2\RW}{\py}\par\nobreak}
+
+  \renewcommand{\DOTI}[1]{%
+    \addtolength{\pyy}{-4pt}
+    \settoheight{\myhi}{\CTV\FmTi{#1}}
+    \addtolength{\myhi}{\py}
+    \addtolength{\myhi}{-1\RW}
+    \vskip -1\pyy
+    \rule{2\RW}{\myhi}\mghrulefill{\RW}\hskip 2pt
+    \raggedleft\CTV\FmTi{#1}\par\nobreak
+    \vskip 80\p@}
+
+  \renewcommand{\DOTIS}[1]{%
+    \setlength{\py}{10pt}
+    \setlength{\pyy}{\py}
+    \addtolength{\pyy}{\RW}
+    \setlength{\myhi}{\baselineskip}
+    \addtolength{\myhi}{\pyy}
+    \mghrulefill{\RW}\rule[-1\py]{2\RW}{\pyy}\par\nobreak
+%    \addtolength{}{}
+\vskip -1\baselineskip
+    \rule{2\RW}{\myhi}\mghrulefill{\RW}\hskip 2pt
+    \raggedleft\CTV\FmTi{#1}\par\nobreak
+    \vskip 60\p@}
+  }
+
+%%%%%%% CONNY DEF
+
+\DeclareOption{Conny}{%
+  \ChNameUpperCase
+  \ChTitleUpperCase  
+  \ChNameVar{\centering\Huge\rm\bfseries}
+  \ChNumVar{\Huge}
+  \ChTitleVar{\centering\Huge\rm}
+  \ChRuleWidth{2pt}
+
+  \renewcommand{\DOCH}{%
+    \mghrulefill{3\RW}\par\nobreak
+    \vskip -0.5\baselineskip
+    \mghrulefill{\RW}\par\nobreak
+    \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+    \par\nobreak
+    \vskip -0.5\baselineskip
+   }
+  \renewcommand{\DOTI}[1]{%
+    \mghrulefill{\RW}\par\nobreak
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 60\p@
+    }
+  \renewcommand{\DOTIS}[1]{%
+    \mghrulefill{\RW}\par\nobreak
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 60\p@
+    }
+  }
+
+%%%%%%% REJNE DEF
+
+\DeclareOption{Rejne}{%
+
+  \ChNameUpperCase
+  \ChTitleUpperCase  
+  \ChNameVar{\centering\Large\rm}
+  \ChNumVar{\Huge}
+  \ChTitleVar{\centering\Huge\rm}
+  \ChRuleWidth{1pt}
+  \renewcommand{\DOCH}{%
+    \settoheight{\py}{\CNoV\thechapter}
+    \addtolength{\py}{-1pt}
+    \CNV\FmN{\@chapapp}\par\nobreak
+    \vskip 20\p@
+    \setlength{\myhi}{2\baselineskip}
+    \setlength{\px}{\myhi}
+    \addtolength{\px}{-1\RW}
+    \rule[-1\px]{\RW}{\myhi}\mghrulefill{\RW}\hskip
+    10pt\raisebox{-0.5\py}{\CNoV\thechapter}\hskip
+10pt\mghrulefill{\RW}\rule[-1\px]{\RW}{\myhi}\par\nobreak
+     \vskip -1\p@
+    }
+  \renewcommand{\DOTI}[1]{%
+    \setlength{\mylen}{\textwidth}
+    \addtolength{\mylen}{-2\RW}
+    {\vrule width\RW}\parbox{\mylen}{\CTV\FmTi{#1}}{\vrule
+width\RW}\par\nobreak
+    \vskip
+-1pt\rule{\RW}{2\baselineskip}\mghrulefill{\RW}\rule{\RW}{2\baselineskip}
+    \vskip 60\p@
+    }
+  \renewcommand{\DOTIS}[1]{%
+    \setlength{\py}{\fboxrule}
+    \setlength{\fboxrule}{\RW}
+    \setlength{\mylen}{\textwidth}
+    \addtolength{\mylen}{-2\RW}
+    \fbox{\parbox{\mylen}{\vskip
+2\baselineskip\CTV\FmTi{#1}\par\nobreak\vskip \baselineskip}} 
+    \setlength{\fboxrule}{\py}
+    \vskip 60\p@
+    }
+  }
+
+
+%%%%%%% BJARNE DEF
+
+\DeclareOption{Bjarne}{%
+  \ChNameUpperCase
+  \ChTitleUpperCase  
+  \ChNameVar{\raggedleft\normalsize\rm}
+  \ChNumVar{\raggedleft \bfseries\Large}
+  \ChTitleVar{\raggedleft \Large\rm}
+  \ChRuleWidth{1pt}
+
+
+%% Note thechapter -> c at chapter fix appendix bug
+
+  \newcounter{AlphaCnt}
+  \newcounter{AlphaDecCnt}
+  \newcommand{\AlphaNo}{%
+    \ifcase\number\theAlphaCnt
+      \ifnum\c at chapter=0
+        ZERO\else{}\fi
+    \or ONE\or TWO\or THREE\or FOUR\or FIVE
+    \or SIX\or SEVEN\or EIGHT\or NINE\or TEN
+    \or ELEVEN\or TWELVE\or THIRTEEN\or FOURTEEN\or FIFTEEN
+    \or SIXTEEN\or SEVENTEEN\or EIGHTEEN\or NINETEEN\fi
+}
+
+  \newcommand{\AlphaDecNo}{%
+    \setcounter{AlphaDecCnt}{0}
+    \@whilenum\number\theAlphaCnt>0\do
+      {\addtocounter{AlphaCnt}{-10}
+       \addtocounter{AlphaDecCnt}{1}}
+     \ifnum\number\theAlphaCnt=0
+     \else
+       \addtocounter{AlphaDecCnt}{-1}
+       \addtocounter{AlphaCnt}{10}
+     \fi
+     
+     
+    \ifcase\number\theAlphaDecCnt\or TEN\or TWENTY\or THIRTY\or
+    FORTY\or FIFTY\or SIXTY\or SEVENTY\or EIGHTY\or NINETY\fi
+    }
+  \newcommand{\TheAlphaChapter}{%
+    
+    \ifinapp 
+      \thechapter
+    \else
+      \setcounter{AlphaCnt}{\c at chapter}
+      \ifnum\c at chapter<20
+        \AlphaNo
+      \else
+        \AlphaDecNo\AlphaNo
+      \fi
+    \fi
+    }  
+  \renewcommand{\DOCH}{%
+    \mghrulefill{\RW}\par\nobreak
+    \CNV\FmN{\@chapapp}\par\nobreak 
+    \CNoV\TheAlphaChapter\par\nobreak
+    \vskip -1\baselineskip\vskip 5pt\mghrulefill{\RW}\par\nobreak
+    \vskip 20\p@
+    }
+  \renewcommand{\DOTI}[1]{%
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@
+    }
+  \renewcommand{\DOTIS}[1]{%
+    \CTV\FmTi{#1}\par\nobreak
+    \vskip 40\p@
+    }
+}
+
+\DeclareOption*{%
+  \PackageWarning{fancychapter}{unknown style option}
+  }
+
+\ProcessOptions* \relax
+
+\def\@makechapterhead#1{%
+  \vspace*{50\p@}%
+  {\parindent \z@ \raggedright \normalfont
+    \ifnum \c at secnumdepth >\m at ne
+      \DOCH
+    \fi
+    \interlinepenalty\@M
+    \DOTI{#1}
+  }}
+\def\@schapter#1{\if at twocolumn
+                   \@topnewpage[\@makeschapterhead{#1}]%
+                 \else
+                   \@makeschapterhead{#1}%
+                   \@afterheading
+                 \fi}
+\def\@makeschapterhead#1{%
+  \vspace*{50\p@}%
+  {\parindent \z@ \raggedright
+    \normalfont
+    \interlinepenalty\@M
+    \DOTIS{#1}
+    \vskip 40\p@
+  }}
+
+\endinput
+
+

Added: sandbox/trunk/pdb/Doc/texinputs/manual.cls
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/manual.cls	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,155 @@
+%
+% manual.cls for the Python documentation
+%
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesClass{manual}
+             [1998/03/03 Document class (Python manual)]
+
+\RequirePackage{pypaper}
+\RequirePackage{fancybox}
+
+% Change the options here to get a different set of basic options, but only
+% if you have to.  Paper and font size should be adjusted in pypaper.sty.
+%
+\LoadClass[\py at paper,\py at ptsize,twoside,openright]{report}
+
+\setcounter{secnumdepth}{2}
+
+% Optional packages:
+%
+% If processing of these documents fails at your TeX installation,
+% these may be commented out (independently) to make things work.
+% These are both supplied with the current version of the teTeX
+% distribution.
+%
+% The "fancyhdr" package makes nicer page footers reasonable to
+% implement, and is used to put the chapter and section information in 
+% the footers.
+%
+\RequirePackage{fancyhdr}\typeout{Using fancier footers than usual.}
+
+
+% Required packages:
+%
+% The "fncychap" package is used to get the nice chapter headers.  The
+% .sty file is distributed with Python, so you should not need to disable
+% it.  You'd also end up with a mixed page style; uglier than stock LaTeX!
+%
+\RequirePackage[Bjarne]{fncychap}\typeout{Using fancy chapter headings.}
+% Do horizontal rules it this way to match:
+\newcommand{\py at doHorizontalRule}{\mghrulefill{\RW}}
+%
+%
+% This gives us all the Python-specific markup that we really want.
+% This should come last.  Do not change this.
+%
+\RequirePackage{python}
+
+% support for module synopsis sections:
+\newcommand{\py at ModSynopsisFilename}{\jobname\thechapter.syn}
+\let\py at OldChapter=\chapter
+\renewcommand{\chapter}{
+  \py at ProcessModSynopsis
+  \py at closeModSynopsisFile
+  \py at OldChapter
+}
+
+
+% Change the title page to look a bit better, and fit in with the
+% fncychap ``Bjarne'' style a bit better.
+%
+\renewcommand{\maketitle}{%
+  \begin{titlepage}%
+    \let\footnotesize\small
+    \let\footnoterule\relax
+    \py at doHorizontalRule%
+    \ifpdf
+      \begingroup
+      % This \def is required to deal with multi-line authors; it
+      % changes \\ to ', ' (comma-space), making it pass muster for
+      % generating document info in the PDF file.
+      \def\\{, }
+      \pdfinfo{
+        /Author (\@author)
+        /Title (\@title)
+      }
+      \endgroup
+    \fi
+    \begin{flushright}%
+      {\rm\Huge\py at HeaderFamily \@title \par}%
+      {\em\LARGE\py at HeaderFamily \py at release\releaseinfo \par}
+      \vfill
+      {\LARGE\py at HeaderFamily \@author \par}
+      \vfill\vfill
+      {\large
+       \@date \par
+       \vfill
+       \py at authoraddress \par
+      }%
+    \end{flushright}%\par
+    \@thanks
+  \end{titlepage}%
+  \setcounter{footnote}{0}%
+  \let\thanks\relax\let\maketitle\relax
+  \gdef\@thanks{}\gdef\@author{}\gdef\@title{}
+}
+
+
+% Catch the end of the {abstract} environment, but here make sure the
+% abstract is followed by a blank page if the 'openright' option is used.
+%
+\let\py at OldEndAbstract=\endabstract
+\renewcommand{\endabstract}{
+  \if at openright
+    \ifodd\value{page}
+      \typeout{Adding blank page after the abstract.}
+      \vfil\pagebreak
+    \fi
+  \fi
+  \py at OldEndAbstract
+}
+
+% This wraps the \tableofcontents macro with all the magic to get the
+% spacing right and have the right number of pages if the 'openright'
+% option has been used.  This eliminates a fair amount of crud in the
+% individual document files.
+%
+\let\py at OldTableofcontents=\tableofcontents
+\renewcommand{\tableofcontents}{%
+  \setcounter{page}{1}%
+  \pagebreak%
+  \pagestyle{plain}%
+  {%
+    \parskip = 0mm%
+    \py at OldTableofcontents%
+    \if at openright%
+      \ifodd\value{page}%
+        \typeout{Adding blank page after the table of contents.}%
+        \pagebreak\hspace{0pt}%
+      \fi%
+    \fi%
+    \cleardoublepage%
+  }%
+  \pagenumbering{arabic}%
+  \@ifundefined{fancyhf}{}{\pagestyle{normal}}%
+  \py at doing@page at targetstrue%
+}
+% This is needed to get the width of the section # area wide enough in the
+% library reference.  Doing it here keeps it the same for all the manuals.
+%
+\renewcommand*\l at section{\@dottedtocline{1}{1.5em}{2.6em}}
+\renewcommand*\l at subsection{\@dottedtocline{2}{4.1em}{3.5em}}
+\setcounter{tocdepth}{1}
+
+
+% Fix the theindex environment to add an entry to the Table of
+% Contents; this is much nicer than just having to jump to the end of
+% the book and flip around, especially with multiple indexes.
+%
+\let\py at OldTheindex=\theindex
+\renewcommand{\theindex}{
+  \cleardoublepage
+  \py at OldTheindex
+  \addcontentsline{toc}{chapter}{\indexname}
+}

Added: sandbox/trunk/pdb/Doc/texinputs/pypaper.sty
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/pypaper.sty	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,18 @@
+%
+%  Change this to say a4paper instead of letterpaper if you want A4.  These
+%  are the latex defaults.
+%
+\newcommand{\py at paper}{letterpaper}
+\newcommand{\py at ptsize}{10pt}
+
+%  These set up the fonts for the documents.
+%
+%  The "times" package makes the default font the PostScript Times
+%  font, which makes for smaller PostScript and a font that more people 
+%  like.
+%
+%  The "avant" package causes the AvantGarde font to be used for
+%  sans-serif text, instead of the uglier Helvetica set up by the "times"
+%  package.
+%
+\RequirePackage{times}\typeout{Using Times instead of Computer Modern.}

Added: sandbox/trunk/pdb/Doc/texinputs/python.ist
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/python.ist	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,11 @@
+line_max 100
+headings_flag 1
+heading_prefix "  \\bigletter "
+
+preamble "\\begin{theindex}
+\\def\\bigletter#1{{\\Large\\sffamily#1}\\nopagebreak\\vspace{1mm}}
+
+"
+
+symhead_positive "{Symbols}"
+numhead_positive "{Numbers}"

Added: sandbox/trunk/pdb/Doc/texinputs/python.sty
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/python.sty	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,1309 @@
+%
+% python.sty for the Python docummentation  [works only with Latex2e]
+%
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesPackage{python}
+             [1998/01/11 LaTeX package (Python markup)]
+
+\RequirePackage{longtable}
+\RequirePackage{underscore}
+
+% Uncomment these two lines to ignore the paper size and make the page 
+% size more like a typical published manual.
+%\renewcommand{\paperheight}{9in}
+%\renewcommand{\paperwidth}{8.5in}   % typical squarish manual
+%\renewcommand{\paperwidth}{7in}     % O'Reilly ``Programmming Python''
+
+% These packages can be used to add marginal annotations which indicate
+% index entries and labels; useful for reviewing this messy documentation!
+%
+%\RequirePackage{showkeys}
+%\RequirePackage{showidx}
+
+% If we ever want to indent paragraphs, this needs to be changed.
+% This is used inside the macros defined here instead of coding
+% \noindent directly.
+\let\py at parindent=\noindent
+
+% for PDF output, use maximal compression & a lot of other stuff
+% (test for PDF recommended by Tanmoy Bhattacharya <tanmoy at qcd.lanl.gov>)
+%
+\newif\ifpy at doing@page at targets
+\py at doing@page at targetsfalse
+
+\newif\ifpdf\pdffalse
+\ifx\pdfoutput\undefined\else\ifcase\pdfoutput
+\else
+  \pdftrue
+  \input{pdfcolor}
+  \let\py at LinkColor=\NavyBlue
+  \let\py at NormalColor=\Black
+  \pdfcompresslevel=9
+  \pdfpagewidth=\paperwidth    % page width of PDF output
+  \pdfpageheight=\paperheight  % page height of PDF output
+  %
+  % Pad the number with '0' to 3 digits wide so no page name is a prefix
+  % of any other.
+  %
+  \newcommand{\py at targetno}[1]{\ifnum#1<100 0\fi\ifnum#1<10 0\fi#1}
+  \newcommand{\py at pageno}{\py at targetno\thepage}
+  %
+  % This definition allows the entries in the page-view of the ToC to be
+  % active links.  Some work, some don't.
+  %
+  \let\py at OldContentsline=\contentsline
+  %
+  % Backward compatibility hack: pdfTeX 0.13 defined \pdfannotlink,
+  % but it changed to \pdfstartlink in 0.14.  This let's us use either
+  % version and still get useful behavior.
+  %
+  \@ifundefined{pdfstartlink}{
+    \let\pdfstartlink=\pdfannotlink
+  }{}
+  %
+  % The \py at parindent here is a hack -- we're forcing pdfTeX into
+  % horizontal mode since \pdfstartlink requires that.
+  \def\py at pdfstartlink{%
+    \ifvmode\py at parindent\fi%
+    \pdfstartlink%
+  }
+  %
+  % Macro that takes two args: the name to link to and the content of
+  % the link.  This takes care of the PDF magic, getting the colors
+  % the same for each link, and avoids having lots of garbage all over 
+  % this style file.
+  \newcommand{\py at linkToName}[2]{%
+    \py at pdfstartlink attr{/Border [0 0 0]} goto name{#1}%
+      \py at LinkColor#2\py at NormalColor%
+    \pdfendlink%
+  }
+  % Compute the padded page number separately since we end up with a pair of
+  % \relax tokens; this gets the right string computed and works.
+  \renewcommand{\contentsline}[3]{%
+    \def\my at pageno{\py at targetno{#3}}%
+    \py at OldContentsline{#1}{\py at linkToName{page\my at pageno}{#2}}{#3}%
+  }
+  \AtEndDocument{
+    \def\_{\string_}
+    \InputIfFileExists{\jobname.bkm}{\pdfcatalog{/PageMode /UseOutlines}}{}
+  }
+  \newcommand{\py at target}[1]{%
+    \ifpy at doing@page at targets%
+      {\pdfdest name{#1} xyz}%
+    \fi%
+  }
+  \let\py at OldLabel=\label
+  \renewcommand{\label}[1]{%
+    \py at OldLabel{#1}%
+    \py at target{label-#1}%
+  }
+  % This stuff adds a page# destination to every PDF page, where # is three
+  % digits wide, padded with leading zeros.  This doesn't really help with
+  % the frontmatter, but does fine with the body.
+  %
+  % This is *heavily* based on the hyperref package.
+  %
+  \def\@begindvi{%
+    \unvbox \@begindvibox
+    \@hyperfixhead
+  }
+  \def\@hyperfixhead{%
+   \let\H at old@thehead\@thehead
+       \global\def\@foo{\py at target{page\py at pageno}}%
+     \expandafter\ifx\expandafter\@empty\H at old@thehead
+       \def\H at old@thehead{\hfil}\fi
+    \def\@thehead{\@foo\relax\H at old@thehead}%
+  }
+\fi\fi
+
+% Increase printable page size (copied from fullpage.sty)
+\topmargin 0pt
+\advance \topmargin by -\headheight
+\advance \topmargin by -\headsep
+
+% attempt to work a little better for A4 users
+\textheight \paperheight
+\advance\textheight by -2in
+
+\oddsidemargin 0pt
+\evensidemargin 0pt
+%\evensidemargin -.25in  % for ``manual size'' documents
+\marginparwidth 0.5in
+
+\textwidth \paperwidth
+\advance\textwidth by -2in
+
+
+% Style parameters and macros used by most documents here
+\raggedbottom
+\sloppy
+\parindent = 0mm
+\parskip = 2mm
+\hbadness = 5000                % don't print trivial gripes
+
+\pagestyle{empty}               % start this way; change for
+\pagenumbering{roman}           % ToC & chapters
+
+% Use this to set the font family for headers and other decor:
+\newcommand{\py at HeaderFamily}{\sffamily}
+
+% Set up abstract ways to get the normal and smaller font sizes that
+% work even in footnote context.
+\newif\ifpy at infootnote \py at infootnotefalse
+\let\py at oldmakefntext\@makefntext
+\def\@makefntext#1{%
+  \bgroup%
+    \py at infootnotetrue
+    \py at oldmakefntext{#1}%
+  \egroup%
+}
+\def\py at defaultsize{%
+  \ifpy at infootnote\footnotesize\else\normalsize\fi%
+}
+\def\py at smallsize{%
+  \ifpy at infootnote\scriptsize\else\small\fi%
+}
+
+% Redefine the 'normal' header/footer style when using "fancyhdr" package:
+\@ifundefined{fancyhf}{}{
+  % Use \pagestyle{normal} as the primary pagestyle for text.
+  \fancypagestyle{normal}{
+    \fancyhf{}
+    \fancyfoot[LE,RO]{{\py at HeaderFamily\thepage}}
+    \fancyfoot[LO]{{\py at HeaderFamily\nouppercase{\rightmark}}}
+    \fancyfoot[RE]{{\py at HeaderFamily\nouppercase{\leftmark}}}
+    \renewcommand{\headrulewidth}{0pt}
+    \renewcommand{\footrulewidth}{0.4pt}
+  }
+  % Update the plain style so we get the page number & footer line,
+  % but not a chapter or section title.  This is to keep the first
+  % page of a chapter and the blank page between chapters `clean.'
+  \fancypagestyle{plain}{
+    \fancyhf{}
+    \fancyfoot[LE,RO]{{\py at HeaderFamily\thepage}}
+    \renewcommand{\headrulewidth}{0pt}
+    \renewcommand{\footrulewidth}{0.4pt}
+  }
+  % Redefine \cleardoublepage so that the blank page between chapters
+  % gets the plain style and not the fancy style.  This is described
+  % in the documentation for the fancyhdr package by Piet von Oostrum.
+  \@ifundefined{chapter}{}{
+    \renewcommand{\cleardoublepage}{
+      \clearpage\if at openright \ifodd\c at page\else
+      \hbox{}
+      \thispagestyle{plain}
+      \newpage
+      \if at twocolumn\hbox{}\newpage\fi\fi\fi
+    }
+  }
+}
+
+% This sets up the {verbatim} environment to be indented and a minipage,
+% and to have all the other mostly nice properties that we want for
+% code samples.
+
+\let\py at OldVerbatim=\verbatim
+\let\py at OldEndVerbatim=\endverbatim
+\RequirePackage{verbatim}
+\let\py at OldVerbatimInput=\verbatiminput
+
+% Variable used by begin code command
+\newlength{\py at codewidth}
+
+\renewcommand{\verbatim}{%
+  \setlength{\parindent}{1cm}%
+  % Calculate the text width for the minipage:
+  \setlength{\py at codewidth}{\linewidth}%
+  \addtolength{\py at codewidth}{-\parindent}%
+  %
+  \par\indent%
+  \begin{minipage}[t]{\py at codewidth}%
+    \small%
+    \py at OldVerbatim%
+}
+\renewcommand{\endverbatim}{%
+    \py at OldEndVerbatim%
+  \end{minipage}%
+}
+\renewcommand{\verbatiminput}[1]{%
+  {\setlength{\parindent}{1cm}%
+   % Calculate the text width for the minipage:
+   \setlength{\py at codewidth}{\linewidth}%
+   \addtolength{\py at codewidth}{-\parindent}%
+   %
+   \small%
+   \begin{list}{}{\setlength{\leftmargin}{1cm}}
+     \item%
+     \py at OldVerbatimInput{#1}%
+   \end{list}
+  }%
+}
+
+% This does a similar thing for the {alltt} environment:
+\RequirePackage{alltt}
+\let\py at OldAllTT=\alltt
+\let\py at OldEndAllTT=\endalltt
+
+\renewcommand{\alltt}{%
+  \setlength{\parindent}{1cm}%
+  % Calculate the text width for the minipage:
+  \setlength{\py at codewidth}{\linewidth}%
+  \addtolength{\py at codewidth}{-\parindent}%
+  \let\e=\textbackslash%
+  %
+  \par\indent%
+  \begin{minipage}[t]{\py at codewidth}%
+    \small%
+    \py at OldAllTT%
+}
+\renewcommand{\endalltt}{%
+    \py at OldEndAllTT%
+  \end{minipage}%
+}
+
+
+\newcommand{\py at modulebadkey}{{--just-some-junk--}}
+
+
+%%  Lots of index-entry generation support.
+
+% Command to wrap around stuff that refers to function / module /
+% attribute names  in the index.  Default behavior: like \code{}.  To
+% just keep the index entries in the roman font, uncomment the second
+% definition; it matches O'Reilly style more.
+%
+\newcommand{\py at idxcode}[1]{\texttt{#1}}
+%\renewcommand{\py at idxcode}[1]{#1}
+
+% Command to generate two index entries (using subentries)
+\newcommand{\indexii}[2]{\index{#1!#2}\index{#2!#1}}
+
+% And three entries (using only one level of subentries)
+\newcommand{\indexiii}[3]{\index{#1!#2 #3}\index{#2!#3, #1}\index{#3!#1 #2}}
+
+% And four (again, using only one level of subentries)
+\newcommand{\indexiv}[4]{
+\index{#1!#2 #3 #4}
+\index{#2!#3 #4, #1}
+\index{#3!#4, #1 #2}
+\index{#4!#1 #2 #3}
+}
+
+% Command to generate a reference to a function, statement, keyword,
+% operator.
+\newcommand{\kwindex}[1]{\indexii{keyword}{#1@{\py at idxcode{#1}}}}
+\newcommand{\stindex}[1]{\indexii{statement}{#1@{\py at idxcode{#1}}}}
+\newcommand{\opindex}[1]{\indexii{operator}{#1@{\py at idxcode{#1}}}}
+\newcommand{\exindex}[1]{\indexii{exception}{#1@{\py at idxcode{#1}}}}
+\newcommand{\obindex}[1]{\indexii{object}{#1}}
+\newcommand{\bifuncindex}[1]{%
+  \index{#1@{\py at idxcode{#1()}} (built-in function)}}
+
+% Add an index entry for a module
+\newcommand{\py at refmodule}[2]{\index{#1@{\py at idxcode{#1}} (#2module)}}
+\newcommand{\refmodindex}[1]{\py at refmodule{#1}{}}
+\newcommand{\refbimodindex}[1]{\py at refmodule{#1}{built-in }}
+\newcommand{\refexmodindex}[1]{\py at refmodule{#1}{extension }}
+\newcommand{\refstmodindex}[1]{\py at refmodule{#1}{standard }}
+
+% Refer to a module's documentation using a hyperlink of the module's
+% name, at least if we're building PDF:
+\ifpdf
+  \newcommand{\refmodule}[2][\py at modulebadkey]{%
+    \ifx\py at modulebadkey#1\def\py at modulekey{#2}\else\def\py at modulekey{#1}\fi%
+    \py at linkToName{label-module-\py at modulekey}{\module{#2}}%
+  }
+\else
+  \newcommand{\refmodule}[2][\py at modulebadkey]{\module{#2}}
+\fi
+
+% support for the module index
+\newif\ifpy at UseModuleIndex
+\py at UseModuleIndexfalse
+
+\newcommand{\makemodindex}{
+  \newwrite\modindexfile
+  \openout\modindexfile=mod\jobname.idx
+  \py at UseModuleIndextrue
+}
+
+% Add the defining entry for a module
+\newcommand{\py at modindex}[2]{%
+  \renewcommand{\py at thismodule}{#1}
+  \setindexsubitem{(in module #1)}%
+  \index{#1@{\py at idxcode{#1}} (#2module)|textbf}%
+  \ifpy at UseModuleIndex%
+    \@ifundefined{py at modplat@\py at thismodulekey}{
+      \write\modindexfile{\protect\indexentry{#1@{\texttt{#1}}}{\thepage}}%
+    }{\write\modindexfile{\protect\indexentry{#1@{\texttt{#1} %
+        \emph{(\py at platformof[\py at thismodulekey]{})}}}{\thepage}}%
+    }
+  \fi%
+}
+
+% *** XXX *** THE NEXT FOUR MACROS ARE NOW OBSOLETE !!! ***
+
+% built-in & Python modules in the main distribution
+\newcommand{\bimodindex}[1]{\py at modindex{#1}{built-in }%
+  \typeout{*** MACRO bimodindex IS OBSOLETE -- USE declaremodule INSTEAD!}}
+\newcommand{\stmodindex}[1]{\py at modindex{#1}{standard }%
+  \typeout{*** MACRO stmodindex IS OBSOLETE -- USE declaremodule INSTEAD!}}
+
+% Python & extension modules outside the main distribution
+\newcommand{\modindex}[1]{\py at modindex{#1}{}%
+  \typeout{*** MACRO modindex IS OBSOLETE -- USE declaremodule INSTEAD!}}
+\newcommand{\exmodindex}[1]{\py at modindex{#1}{extension }%
+  \typeout{*** MACRO exmodindex IS OBSOLETE -- USE declaremodule INSTEAD!}}
+
+% Additional string for an index entry
+\newif\ifpy at usingsubitem\py at usingsubitemfalse
+\newcommand{\py at indexsubitem}{}
+\newcommand{\setindexsubitem}[1]{\renewcommand{\py at indexsubitem}{ #1}%
+                                 \py at usingsubitemtrue}
+\newcommand{\ttindex}[1]{%
+  \ifpy at usingsubitem
+    \index{#1@{\py at idxcode{#1}}\py at indexsubitem}%
+  \else%
+    \index{#1@{\py at idxcode{#1}}}%
+  \fi%
+}
+\newcommand{\withsubitem}[2]{%
+  \begingroup%
+    \def\ttindex##1{\index{##1@{\py at idxcode{##1}} #1}}%
+    #2%
+  \endgroup%
+}
+
+
+% Module synopsis processing -----------------------------------------------
+%
+\newcommand{\py at thisclass}{}
+\newcommand{\py at thismodule}{}
+\newcommand{\py at thismodulekey}{}
+\newcommand{\py at thismoduletype}{}
+
+\newcommand{\py at standardIndexModule}[1]{\py at modindex{#1}{standard }}
+\newcommand{\py at builtinIndexModule}[1]{\py at modindex{#1}{built-in }}
+\newcommand{\py at extensionIndexModule}[1]{\py at modindex{#1}{extension }}
+\newcommand{\py at IndexModule}[1]{\py at modindex{#1}{}}
+
+\newif\ifpy at HaveModSynopsis       \py at HaveModSynopsisfalse
+\newif\ifpy at ModSynopsisFileIsOpen \py at ModSynopsisFileIsOpenfalse
+\newif\ifpy at HaveModPlatform       \py at HaveModPlatformfalse
+
+% \declaremodule[key]{type}{name}
+\newcommand{\declaremodule}[3][\py at modulebadkey]{
+  \py at openModSynopsisFile
+  \renewcommand{\py at thismoduletype}{#2}
+  \ifx\py at modulebadkey#1
+    \renewcommand{\py at thismodulekey}{#3}
+  \else
+    \renewcommand{\py at thismodulekey}{#1}
+  \fi
+  \@ifundefined{py@#2IndexModule}{%
+    \typeout{*** MACRO declaremodule called with unknown module type: `#2'}
+    \py at IndexModule{#3}%
+  }{%
+    \csname py@#2IndexModule\endcsname{#3}%
+  }
+  \label{module-\py at thismodulekey}
+}
+\newif\ifpy at ModPlatformFileIsOpen \py at ModPlatformFileIsOpenfalse
+\newcommand{\py at ModPlatformFilename}{\jobname.pla}
+\newcommand{\platform}[1]{
+  \ifpy at ModPlatformFileIsOpen\else
+    \newwrite\py at ModPlatformFile
+    \openout\py at ModPlatformFile=\py at ModPlatformFilename
+    \py at ModPlatformFileIsOpentrue
+  \fi
+}
+\InputIfFileExists{\jobname.pla}{}{}
+\newcommand{\py at platformof}[2][\py at modulebadkey]{%
+  \ifx\py at modulebadkey#1 \def\py at key{#2}%
+  \else \def\py at key{#1}%
+  \fi%
+  \csname py at modplat@\py at key\endcsname%
+}
+\newcommand{\ignorePlatformAnnotation}[1]{}
+
+% \moduleauthor{name}{email}
+\newcommand{\moduleauthor}[2]{}
+
+% \sectionauthor{name}{email}
+\newcommand{\sectionauthor}[2]{}
+
+
+\newcommand{\py at defsynopsis}{Module has no synopsis.}
+\newcommand{\py at modulesynopsis}{\py at defsynopsis}
+\newcommand{\modulesynopsis}[1]{
+  \py at HaveModSynopsistrue
+  \renewcommand{\py at modulesynopsis}{#1}
+}
+
+% define the file
+\newwrite\py at ModSynopsisFile
+
+% hacked from \addtocontents from latex.ltx:
+\long\def\py at writeModSynopsisFile#1{%
+  \protected at write\py at ModSynopsisFile%
+      {\let\label\@gobble \let\index\@gobble \let\glossary\@gobble}%
+      {\string#1}%
+}
+\newcommand{\py at closeModSynopsisFile}{
+  \ifpy at ModSynopsisFileIsOpen
+    \closeout\py at ModSynopsisFile
+    \py at ModSynopsisFileIsOpenfalse
+  \fi
+}
+\newcommand{\py at openModSynopsisFile}{
+  \ifpy at ModSynopsisFileIsOpen\else
+    \openout\py at ModSynopsisFile=\py at ModSynopsisFilename
+    \py at ModSynopsisFileIsOpentrue
+  \fi
+}
+
+\newcommand{\py at ProcessModSynopsis}{
+  \ifpy at HaveModSynopsis
+    \py at writeModSynopsisFile{\modulesynopsis%
+      {\py at thismodulekey}{\py at thismodule}%
+      {\py at thismoduletype}{\py at modulesynopsis}}%
+    \py at HaveModSynopsisfalse
+  \fi
+  \renewcommand{\py at modulesynopsis}{\py at defsynopsis}
+}
+\AtEndDocument{\py at ProcessModSynopsis\py at closeModSynopsisFile}
+
+
+\long\def\py at writeModPlatformFile#1{%
+  \protected at write\py at ModPlatformFile%
+    {\let\label\@gobble \let\index\@gobble \let\glossary\@gobble}%
+    {\string#1}%
+}
+
+
+\newcommand{\localmoduletable}{
+  \IfFileExists{\py at ModSynopsisFilename}{
+    \begin{synopsistable}
+      \input{\py at ModSynopsisFilename}
+    \end{synopsistable}
+  }{}
+}
+
+\ifpdf
+  \newcommand{\py at ModSynopsisSummary}[4]{%
+    \py at linkToName{label-module-#1}{\bfcode{#2}} & #4\\
+  }
+\else
+  \newcommand{\py at ModSynopsisSummary}[4]{\bfcode{#2} & #4\\}
+\fi
+\newenvironment{synopsistable}{
+  % key, name, type, synopsis
+  \let\modulesynopsis=\py at ModSynopsisSummary
+  \begin{tabular}{ll}
+}{
+  \end{tabular}
+}
+%
+% --------------------------------------------------------------------------
+
+
+\newcommand{\py at reset}{
+  \py at usingsubitemfalse
+  \py at ProcessModSynopsis
+  \renewcommand{\py at thisclass}{}
+  \renewcommand{\py at thismodule}{}
+  \renewcommand{\py at thismodulekey}{}
+  \renewcommand{\py at thismoduletype}{}
+}
+
+% Augment the sectioning commands used to get our own font family in place,
+% and reset some internal data items:
+\renewcommand{\section}{\py at reset%
+                        \@startsection{section}{1}{\z@}%
+                                    {-3.5ex \@plus -1ex \@minus -.2ex}%
+                                    {2.3ex \@plus.2ex}%
+                                    {\reset at font\Large\py at HeaderFamily}}
+\renewcommand{\subsection}{\@startsection{subsection}{2}{\z@}%
+                                    {-3.25ex\@plus -1ex \@minus -.2ex}%
+                                    {1.5ex \@plus .2ex}%
+                                    {\reset at font\large\py at HeaderFamily}}
+\renewcommand{\subsubsection}{\@startsection{subsubsection}{3}{\z@}%
+                                    {-3.25ex\@plus -1ex \@minus -.2ex}%
+                                    {1.5ex \@plus .2ex}%
+                                    {\reset at font\normalsize\py at HeaderFamily}}
+\renewcommand{\paragraph}{\@startsection{paragraph}{4}{\z@}%
+                                    {3.25ex \@plus1ex \@minus.2ex}%
+                                    {-1em}%
+                                    {\reset at font\normalsize\py at HeaderFamily}}
+\renewcommand{\subparagraph}{\@startsection{subparagraph}{5}{\parindent}%
+                                    {3.25ex \@plus1ex \@minus .2ex}%
+                                    {-1em}%
+                                    {\reset at font\normalsize\py at HeaderFamily}}
+
+
+% Now for a lot of semantically-loaded environments that do a ton of magical
+% things to get the right formatting and index entries for the stuff in
+% Python modules and C API.
+
+
+% {fulllineitems} is used in one place in libregex.tex, but is really for
+% internal use in this file.
+%
+\newcommand{\py at itemnewline}[1]{%
+  \@tempdima\linewidth%
+  \advance\@tempdima \leftmargin\makebox[\@tempdima][l]{#1}%
+}
+
+\newenvironment{fulllineitems}{
+  \begin{list}{}{\labelwidth \leftmargin \labelsep 0pt
+                 \rightmargin 0pt \topsep -\parskip \partopsep \parskip
+                 \itemsep -\parsep
+                 \let\makelabel=\py at itemnewline}
+}{\end{list}}
+
+% \optional is mostly for use in the arguments parameters to the various
+% {*desc} environments defined below, but may be used elsewhere.  Known to
+% be used in the debugger chapter.
+%
+% Typical usage:
+%
+%     \begin{funcdesc}{myfunc}{reqparm\optional{, optparm}}
+%                                    ^^^       ^^^
+%                          No space here       No space here
+%
+% When a function has multiple optional parameters, \optional should be
+% nested, not chained.  This is right:
+%
+%     \begin{funcdesc}{myfunc}{\optional{parm1\optional{, parm2}}}
+%
+\let\py at badkey=\@undefined
+
+\newcommand{\optional}[1]{%
+  {\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}}
+
+% This can be used when a function or method accepts an varying number 
+% of arguments, such as by using the *args syntax in the parameter list.
+\newcommand{\py at moreargs}{...}
+
+% This can be used when you don't want to document the parameters to a 
+% function or method, but simply state that it's an alias for
+% something else.
+\newcommand{\py at unspecified}{...}
+
+
+\newlength{\py at argswidth}
+\newcommand{\py at sigparams}[1]{%
+  \parbox[t]{\py at argswidth}{\py at varvars{#1}\code{)}}}
+\newcommand{\py at sigline}[2]{%
+  \settowidth{\py at argswidth}{#1\code{(}}%
+  \addtolength{\py at argswidth}{-2\py at argswidth}%
+  \addtolength{\py at argswidth}{\textwidth}%
+  \item[#1\code{(}\py at sigparams{#2}]}
+
+% C functions ------------------------------------------------------------
+% \begin{cfuncdesc}[refcount]{type}{name}{arglist}
+% Note that the [refcount] slot should only be filled in by
+% tools/anno-api.py; it pulls the value from the refcounts database.
+\newcommand{\cfuncline}[3]{
+  \py at sigline{\code{#1 \bfcode{#2}}}{#3}%
+  \index{#2@{\py at idxcode{#2()}}}
+}
+\newenvironment{cfuncdesc}[4][\py at badkey]{
+  \begin{fulllineitems}
+    \cfuncline{#2}{#3}{#4}
+    \ifx#1\@undefined\else%
+      \emph{Return value: \textbf{#1}.}\\
+    \fi
+}{\end{fulllineitems}}
+
+% C variables ------------------------------------------------------------
+% \begin{cvardesc}{type}{name}
+\newenvironment{cvardesc}[2]{
+  \begin{fulllineitems}
+    \item[\code{#1 \bfcode{#2}}\index{#2@{\py at idxcode{#2}}}]
+}{\end{fulllineitems}}
+
+% C data types -----------------------------------------------------------
+% \begin{ctypedesc}[index name]{typedef name}
+\newenvironment{ctypedesc}[2][\py at badkey]{
+  \begin{fulllineitems}
+    \item[\bfcode{#2}%
+    \ifx#1\@undefined%
+      \index{#2@{\py at idxcode{#2}} (C type)}
+    \else%
+      \index{#2@{\py at idxcode{#1}} (C type)}
+    \fi]
+}{\end{fulllineitems}}
+
+% C type fields ----------------------------------------------------------
+% \begin{cmemberdesc}{container type}{ctype}{membername}
+\newcommand{\cmemberline}[3]{
+  \item[\code{#2 \bfcode{#3}}]
+  \index{#3@{\py at idxcode{#3}} (#1 member)}
+}
+\newenvironment{cmemberdesc}[3]{
+  \begin{fulllineitems}
+    \cmemberline{#1}{#2}{#3}
+}{\end{fulllineitems}}
+
+% Funky macros -----------------------------------------------------------
+% \begin{csimplemacrodesc}{name}
+% -- "simple" because it has no args; NOT for constant definitions!
+\newenvironment{csimplemacrodesc}[1]{
+  \begin{fulllineitems}
+    \item[\bfcode{#1}\index{#1@{\py at idxcode{#1}} (macro)}]
+}{\end{fulllineitems}}
+
+% simple functions (not methods) -----------------------------------------
+% \begin{funcdesc}{name}{args}
+\newcommand{\funcline}[2]{%
+  \funclineni{#1}{#2}%
+  \index{#1@{\py at idxcode{#1()}} (in module \py at thismodule)}}
+\newenvironment{funcdesc}[2]{
+  \begin{fulllineitems}
+    \funcline{#1}{#2}
+}{\end{fulllineitems}}
+
+% similar to {funcdesc}, but doesn't add to the index
+\newcommand{\funclineni}[2]{%
+  \py at sigline{\bfcode{#1}}{#2}}
+\newenvironment{funcdescni}[2]{
+  \begin{fulllineitems}
+    \funclineni{#1}{#2}
+}{\end{fulllineitems}}
+
+% classes ----------------------------------------------------------------
+% \begin{classdesc}{name}{constructor args}
+\newenvironment{classdesc}[2]{
+  % Using \renewcommand doesn't work for this, for unknown reasons:
+  \global\def\py at thisclass{#1}
+  \begin{fulllineitems}
+    \py at sigline{\strong{class }\bfcode{#1}}{#2}%
+    \index{#1@{\py at idxcode{#1}} (class in \py at thismodule)}
+}{\end{fulllineitems}}
+
+% \begin{classdesc*}{name}
+\newenvironment{classdesc*}[1]{
+  % Using \renewcommand doesn't work for this, for unknown reasons:
+  \global\def\py at thisclass{#1}
+  \begin{fulllineitems}
+    \item[\strong{class }\code{\bfcode{#1}}%
+      \index{#1@{\py at idxcode{#1}} (class in \py at thismodule)}]
+}{\end{fulllineitems}}
+
+% \begin{excclassdesc}{name}{constructor args}
+% but indexes as an exception
+\newenvironment{excclassdesc}[2]{
+  % Using \renewcommand doesn't work for this, for unknown reasons:
+  \global\def\py at thisclass{#1}
+  \begin{fulllineitems}
+    \py at sigline{\strong{exception }\bfcode{#1}}{#2}%
+    \index{#1@{\py at idxcode{#1}} (exception in \py at thismodule)}
+}{\end{fulllineitems}}
+
+% There is no corresponding {excclassdesc*} environment.  To describe
+% a class exception without parameters, use the {excdesc} environment.
+
+
+\let\py at classbadkey=\@undefined
+
+% object method ----------------------------------------------------------
+% \begin{methoddesc}[classname]{methodname}{args}
+\newcommand{\methodline}[3][\@undefined]{
+  \methodlineni{#2}{#3}
+  \ifx#1\@undefined
+    \index{#2@{\py at idxcode{#2()}} (\py at thisclass\ method)}
+  \else
+    \index{#2@{\py at idxcode{#2()}} (#1 method)}
+  \fi
+}
+\newenvironment{methoddesc}[3][\@undefined]{
+  \begin{fulllineitems}
+    \ifx#1\@undefined
+      \methodline{#2}{#3}
+    \else
+      \def\py at thisclass{#1}
+      \methodline{#2}{#3}
+    \fi
+}{\end{fulllineitems}}
+
+% similar to {methoddesc}, but doesn't add to the index
+% (never actually uses the optional argument)
+\newcommand{\methodlineni}[3][\py at classbadkey]{%
+  \py at sigline{\bfcode{#2}}{#3}}
+\newenvironment{methoddescni}[3][\py at classbadkey]{
+  \begin{fulllineitems}
+    \methodlineni{#2}{#3}
+}{\end{fulllineitems}}
+
+% object data attribute --------------------------------------------------
+% \begin{memberdesc}[classname]{membername}
+\newcommand{\memberline}[2][\py at classbadkey]{%
+  \ifx#1\@undefined
+    \memberlineni{#2}
+    \index{#2@{\py at idxcode{#2}} (\py at thisclass\ attribute)}
+  \else
+    \memberlineni{#2}
+    \index{#2@{\py at idxcode{#2}} (#1 attribute)}
+  \fi
+}
+\newenvironment{memberdesc}[2][\py at classbadkey]{
+  \begin{fulllineitems}
+    \ifx#1\@undefined
+      \memberline{#2}
+    \else
+      \def\py at thisclass{#1}
+      \memberline{#2}
+    \fi
+}{\end{fulllineitems}}
+
+% similar to {memberdesc}, but doesn't add to the index
+% (never actually uses the optional argument)
+\newcommand{\memberlineni}[2][\py at classbadkey]{\item[\bfcode{#2}]}
+\newenvironment{memberdescni}[2][\py at classbadkey]{
+  \begin{fulllineitems}
+    \memberlineni{#2}
+}{\end{fulllineitems}}
+
+% For exceptions: --------------------------------------------------------
+% \begin{excdesc}{name}
+%  -- for constructor information, use excclassdesc instead
+\newenvironment{excdesc}[1]{
+  \begin{fulllineitems}
+    \item[\strong{exception }\bfcode{#1}%
+          \index{#1@{\py at idxcode{#1}} (exception in \py at thismodule)}]
+}{\end{fulllineitems}}
+
+% Module data or constants: ----------------------------------------------
+% \begin{datadesc}{name}
+\newcommand{\dataline}[1]{%
+  \datalineni{#1}\index{#1@{\py at idxcode{#1}} (data in \py at thismodule)}}
+\newenvironment{datadesc}[1]{
+  \begin{fulllineitems}
+    \dataline{#1}
+}{\end{fulllineitems}}
+
+% similar to {datadesc}, but doesn't add to the index
+\newcommand{\datalineni}[1]{\item[\bfcode{#1}]\nopagebreak}
+\newenvironment{datadescni}[1]{
+  \begin{fulllineitems}
+    \datalineni{#1}
+}{\end{fulllineitems}}
+
+% bytecode instruction ---------------------------------------------------
+% \begin{opcodedesc}{name}{var}
+% -- {var} may be {}
+\newenvironment{opcodedesc}[2]{
+  \begin{fulllineitems}
+    \item[\bfcode{#1}\quad\var{#2}]
+}{\end{fulllineitems}}
+
+
+\newcommand{\nodename}[1]{\label{#1}}
+
+% For these commands, use \command{} to get the typography right, not 
+% {\command}.  This works better with the texinfo translation.
+\newcommand{\ABC}{{\sc abc}}
+\newcommand{\UNIX}{{\sc Unix}}
+\newcommand{\POSIX}{POSIX}
+\newcommand{\ASCII}{{\sc ascii}}
+\newcommand{\Cpp}{C\protect\raisebox{.18ex}{++}}
+\newcommand{\C}{C}
+\newcommand{\EOF}{{\sc eof}}
+\newcommand{\NULL}{\constant{NULL}}
+\newcommand{\infinity}{\ensuremath{\infty}}
+\newcommand{\plusminus}{\ensuremath{\pm}}
+
+% \guilabel{Start}
+\newcommand{\guilabel}[1]{\textsf{#1}}
+% \menuselection{Start \sub Programs \sub Python}
+\newcommand{\menuselection}[1]{\guilabel{{\def\sub{ \ensuremath{>} }#1}}}
+
+% Also for consistency: spell Python "Python", not "python"!
+
+% code is the most difficult one...
+\newcommand{\code}[1]{\textrm{\@vobeyspaces\@noligs\def\{{\char`\{}\def\}{\char`\}}\def\~{\char`\~}\def\^{\char`\^}\def\e{\char`\\}\def\${\char`\$}\def\#{\char`\#}\def\&{\char`\&}\def\%{\char`\%}%
+\texttt{#1}}}
+
+\newcommand{\bfcode}[1]{\code{\bfseries#1}} % bold-faced code font
+\newcommand{\csimplemacro}[1]{\code{#1}}
+\newcommand{\kbd}[1]{\code{#1}}
+\newcommand{\samp}[1]{`\code{#1}'}
+\newcommand{\var}[1]{%
+  \ifmmode%
+    \hbox{\py at defaultsize\textrm{\textit{#1\/}}}%
+  \else%
+    \py at defaultsize\textrm{\textit{#1\/}}%
+  \fi%
+}
+\renewcommand{\emph}[1]{{\em #1}}
+\newcommand{\dfn}[1]{\emph{#1}}
+\newcommand{\strong}[1]{{\bf #1}}
+% let's experiment with a new font:
+\newcommand{\file}[1]{`\filenq{#1}'}
+\newcommand{\filenq}[1]{{\py at smallsize\textsf{\let\e=\textbackslash#1}}}
+
+% Use this def/redef approach for \url{} since hyperref defined this already,
+% but only if we actually used hyperref:
+\ifpdf
+  \newcommand{\url}[1]{{%
+    \py at pdfstartlink attr{/Border [0 0 0]} user{/S /URI /URI (#1)}%
+    \py at LinkColor%                              color of the link text
+    \py at smallsize\sf #1%
+    \py at NormalColor%                    Turn it back off; these are declarative
+    \pdfendlink}%                       and don't appear bound to the current
+  }%                                    formatting "box".
+\else
+  \newcommand{\url}[1]{\mbox{\py at smallsize\textsf{#1}}}
+\fi
+\newcommand{\email}[1]{{\py at smallsize\textsf{#1}}}
+\newcommand{\newsgroup}[1]{{\py at smallsize\textsf{#1}}}
+
+\newcommand{\py at varvars}[1]{{%
+  {\let\unspecified=\py at unspecified%
+   \let\moreargs=\py at moreargs%
+   \var{#1}}}}
+
+% I'd really like to get rid of this!
+\newif\iftexi\texifalse
+
+% This is used to get l2h to put the copyright and abstract on
+% a separate HTML page.
+\newif\ifhtml\htmlfalse
+
+
+% These should be used for all references to identifiers which are
+% used to refer to instances of specific language constructs.  See the
+% names for specific semantic assignments.
+%
+% For now, don't do anything really fancy with them; just use them as
+% logical markup.  This might change in the future.
+%
+\newcommand{\module}[1]{\texttt{#1}}
+\newcommand{\keyword}[1]{\texttt{#1}}
+\newcommand{\exception}[1]{\texttt{#1}}
+\newcommand{\class}[1]{\texttt{#1}}
+\newcommand{\function}[1]{\texttt{#1}}
+\newcommand{\member}[1]{\texttt{#1}}
+\newcommand{\method}[1]{\texttt{#1}}
+
+\newcommand{\pytype}[1]{#1}             % built-in Python type
+
+\newcommand{\cfunction}[1]{\texttt{#1}}
+\newcommand{\ctype}[1]{\texttt{#1}}     % C struct or typedef name
+\newcommand{\cdata}[1]{\texttt{#1}}     % C variable, typically global
+
+\newcommand{\mailheader}[1]{{\py at smallsize\textsf{#1:}}}
+\newcommand{\mimetype}[1]{{\py at smallsize\textsf{#1}}}
+% The \! is a "negative thin space" in math mode.
+\newcommand{\regexp}[1]{%
+  {\tiny$^{^\lceil}\!\!$%
+   {\py at defaultsize\code{#1}}%
+   $\!\rfloor\!$%
+  }}
+\newcommand{\envvar}[1]{%
+  #1%
+  \index{#1}%
+  \index{environment variables!{#1}}%
+}
+\newcommand{\makevar}[1]{#1}            % variable in a Makefile
+\newcommand{\character}[1]{\samp{#1}}
+
+% constants defined in Python modules or C headers, not language constants:
+\newcommand{\constant}[1]{\code{#1}}    % manifest constant, not syntactic
+
+\newcommand{\manpage}[2]{{\emph{#1}(#2)}}
+\newcommand{\pep}[1]{PEP #1\index{Python Enhancement Proposals!PEP #1}}
+\newcommand{\rfc}[1]{RFC #1\index{RFC!RFC #1}}
+\newcommand{\program}[1]{\strong{#1}}
+\newcommand{\programopt}[1]{\strong{#1}}
+% Note that \longprogramopt provides the '--'!
+\newcommand{\longprogramopt}[1]{\strong{-{}-#1}}
+
+% \ulink{link text}{URL}
+\ifpdf
+  \newcommand{\ulink}[2]{{%
+    % For PDF, we *should* only generate a link when the URL is absolute.
+    \py at pdfstartlink attr{/Border [0 0 0]} user{/S /URI /URI (#2)}%
+    \py at LinkColor%                              color of the link text
+    #1%
+    \py at NormalColor%                    Turn it back off; these are declarative
+    \pdfendlink}%                       and don't appear bound to the current
+  }%                                    formatting "box".
+\else
+  \newcommand{\ulink}[2]{#1}
+\fi
+
+% cited titles:  \citetitle{Title of Work}
+%       online:  \citetitle[url-to-resource]{Title of Work}
+\ifpdf
+  \newcommand{\citetitle}[2][\py at modulebadkey]{%
+    \ifx\py at modulebadkey#1\emph{#2}\else\ulink{\emph{#2}}{#1}\fi%
+  }
+\else
+  \newcommand{\citetitle}[2][URL]{\emph{#2}}
+\fi
+
+
+
+% This version is being checked in for the historical record; it shows
+% how I've managed to get some aspects of this to work.  It will not
+% be used in practice, so a subsequent revision will change things
+% again.  This version has problems, but shows how to do something
+% that proved more tedious than I'd expected, so I don't want to lose
+% the example completely.
+%
+\newcommand{\grammartoken}[1]{\texttt{#1}}
+\newenvironment{productionlist}[1][\py at badkey]{
+  \def\optional##1{{\Large[}##1{\Large]}}
+  \def\production##1##2{\code{##1}&::=&\code{##2}\\}
+  \def\productioncont##1{& &\code{##1}\\}
+  \def\token##1{##1}
+  \let\grammartoken=\token
+  \parindent=2em
+  \indent
+  \begin{tabular}{lcl}
+}{%
+  \end{tabular}
+}
+
+\newlength{\py at noticelength}
+
+\newcommand{\py at heavybox}{
+  \setlength{\fboxrule}{2pt}
+  \setlength{\fboxsep}{7pt}
+  \setlength{\py at noticelength}{\linewidth}
+  \addtolength{\py at noticelength}{-2\fboxsep}
+  \addtolength{\py at noticelength}{-2\fboxrule}
+  \setlength{\shadowsize}{3pt}
+  \Sbox
+  \minipage{\py at noticelength}
+}
+\newcommand{\py at endheavybox}{
+  \endminipage
+  \endSbox
+  \fbox{\TheSbox}
+}
+
+% a 'note' is as plain as it gets:
+\newcommand{\py at noticelabel@note}{Note:}
+\newcommand{\py at noticestart@note}{}
+\newcommand{\py at noticeend@note}{}
+
+% a 'warning' gets more visible distinction:
+\newcommand{\py at noticelabel@warning}{Warning:}
+\newcommand{\py at noticestart@warning}{\py at heavybox}
+\newcommand{\py at noticeend@warning}{\py at endheavybox}
+
+\newenvironment{notice}[1][note]{
+  \def\py at noticetype{#1}
+  \csname py at noticestart@#1\endcsname
+  \par\strong{\csname py at noticelabel@#1\endcsname}
+}{\csname py at noticeend@\py at noticetype\endcsname}
+\newcommand{\note}[1]{\strong{\py at noticelabel@note} #1}
+\newcommand{\warning}[1]{\strong{\py at noticelabel@warning} #1}
+
+% Deprecation stuff.
+% Should be extended to allow an index / list of deprecated stuff.  But
+% there's a lot of stuff that needs to be done to make that automatable.
+%
+% First parameter is the release number that deprecates the feature, the
+% second is the action the should be taken by users of the feature.
+%
+% Example:
+%  \deprecated{1.5.1}{Use \method{frobnicate()} instead.}
+%
+\newcommand{\deprecated}[2]{%
+  \strong{Deprecated since release #1.}  #2\par}
+
+% New stuff.
+% This should be used to mark things which have been added to the
+% development tree but that aren't in the release, but are documented.
+% This allows release of documentation that already includes updated
+% descriptions.  Place at end of descriptor environment.
+%
+% Example:
+%  \versionadded{1.5.2}
+%  \versionchanged[short explanation]{2.0}
+%
+\newcommand{\versionadded}[2][\py at badkey]{%
+  \ifx#1\@undefined%
+    {  New in version #2.  }%
+  \else%
+    {  New in version #2:\ #1.  }%
+  \fi%
+}
+\newcommand{\versionchanged}[2][\py at badkey]{%
+  \ifx#1\@undefined%
+    {  Changed in version #2.  }%
+  \else%
+    {  Changed in version #2:\ #1.  }%
+  \fi%
+}
+
+
+% Tables.
+%
+\newenvironment{tableii}[4]{%
+  \begin{center}%
+    \def\lineii##1##2{\csname#2\endcsname{##1}&##2\\}%
+    \begin{tabular}{#1}\strong{#3}&\strong{#4} \\* \hline%
+}{%
+    \end{tabular}%
+  \end{center}%
+}
+
+\newenvironment{longtableii}[4]{%
+  \begin{center}%
+    \def\lineii##1##2{\csname#2\endcsname{##1}&##2\\}%
+    \begin{longtable}[c]{#1}\strong{#3}&\strong{#4} \\* \hline\endhead%
+}{%
+    \end{longtable}%
+  \end{center}%
+}
+
+\newenvironment{tableiii}[5]{%
+  \begin{center}%
+    \def\lineiii##1##2##3{\csname#2\endcsname{##1}&##2&##3\\}%
+    \begin{tabular}{#1}\strong{#3}&\strong{#4}&\strong{#5} \\%
+      \hline%
+}{%
+    \end{tabular}%
+  \end{center}%
+}
+
+\newenvironment{longtableiii}[5]{%
+  \begin{center}%
+    \def\lineiii##1##2##3{\csname#2\endcsname{##1}&##2&##3\\}%
+    \begin{longtable}[c]{#1}\strong{#3}&\strong{#4}&\strong{#5} \\%
+      \hline\endhead%
+}{%
+    \end{longtable}%
+  \end{center}%
+}
+
+\newenvironment{tableiv}[6]{%
+  \begin{center}%
+    \def\lineiv##1##2##3##4{\csname#2\endcsname{##1}&##2&##3&##4\\}%
+    \begin{tabular}{#1}\strong{#3}&\strong{#4}&\strong{#5}&\strong{#6} \\%
+      \hline%
+}{%
+    \end{tabular}%
+  \end{center}%
+}
+
+\newenvironment{longtableiv}[6]{%
+  \begin{center}%
+    \def\lineiv##1##2##3##4{\csname#2\endcsname{##1}&##2&##3&##4\\}%
+    \begin{longtable}[c]{#1}\strong{#3}&\strong{#4}&\strong{#5}&\strong{#6}%
+      \\%
+      \hline\endhead%
+}{%
+    \end{longtable}%
+  \end{center}%
+}
+
+\newenvironment{tablev}[7]{%
+  \begin{center}%
+    \def\linev##1##2##3##4##5{\csname#2\endcsname{##1}&##2&##3&##4&##5\\}%
+    \begin{tabular}{#1}\strong{#3}&\strong{#4}&\strong{#5}&\strong{#6}&\strong{#7} \\%
+      \hline%
+}{%
+    \end{tabular}%
+  \end{center}%
+}
+
+\newenvironment{longtablev}[7]{%
+  \begin{center}%
+    \def\linev##1##2##3##4##5{\csname#2\endcsname{##1}&##2&##3&##4&##5\\}%
+    \begin{longtable}[c]{#1}\strong{#3}&\strong{#4}&\strong{#5}&\strong{#6}&\strong{#7}%
+      \\%
+      \hline\endhead%
+}{%
+    \end{longtable}%
+  \end{center}%
+}
+
+% XXX Don't think we can use this yet, though it cleans up some
+% tedious markup.  There's no equivalent for the HTML transform yet,
+% and that needs to exist.  I don't know how to write it.
+%
+% This should really have something that makes it easier to bind a
+% table's ``Notes'' column and an associated tablenotes environment,
+% and generates the right magic for getting the numbers right in the
+% table.
+%
+% So this is quite incomplete.
+%
+\newcounter{py at tablenotescounter}
+\newenvironment{tablenotes}{%
+  \noindent Notes:
+  \par
+  \setcounter{py at tablenotescounter}{0}
+  \begin{list}{(\arabic{py at tablenotescounter})}%
+              {\usecounter{py at tablenotescounter}}
+}{\end{list}}
+
+
+% Cross-referencing (AMK, new impl. FLD)
+% Sample usage:
+%  \begin{seealso}
+%    \seemodule{rand}{Uniform random number generator.}; % Module xref
+%    \seetext{\emph{Encyclopedia Britannica}}.           % Ref to a book
+% 
+%    % A funky case: module name contains '_'; have to supply an optional key
+%    \seemodule[copyreg]{copy_reg}{Interface constructor registration for
+%                                  \module{pickle}.}
+%  \end{seealso}
+%
+% Note that the last parameter for \seemodule and \seetext should be complete
+% sentences and be terminated with the proper punctuation.
+
+\ifpdf
+  \newcommand{\py at seemodule}[3][\py at modulebadkey]{%
+    \par%
+    \ifx\py at modulebadkey#1\def\py at modulekey{#2}\else\def\py at modulekey{#1}\fi%
+    \begin{fulllineitems}
+      \item[\py at linkToName{label-module-\py at modulekey}{Module \module{#2}}
+            (section \ref{module-\py at modulekey}):]
+      #3
+    \end{fulllineitems}
+  }
+\else
+  \newcommand{\py at seemodule}[3][\py at modulebadkey]{%
+    \par%
+    \ifx\py at modulebadkey#1\def\py at modulekey{#2}\else\def\py at modulekey{#1}\fi%
+    \begin{fulllineitems}
+      \item[Module \module{#2} (section \ref{module-\py at modulekey}):]
+      #3
+    \end{fulllineitems}
+  }
+\fi
+
+% \seelink{url}{link text}{why it's interesting}
+\newcommand{\py at seelink}[3]{%
+  \par
+  \begin{fulllineitems}
+    \item[\ulink{#2}{#1}]
+    #3
+  \end{fulllineitems}
+}
+% \seetitle[url]{title}{why it's interesting}
+\newcommand{\py at seetitle}[3][\py at modulebadkey]{%
+  \par
+  \begin{fulllineitems}
+    \item[\citetitle{#2}]
+    \ifx\py at modulebadkey#1\else
+      \item[{\small{(\url{#1})}}]
+    \fi
+    #3
+  \end{fulllineitems}
+}
+% \seepep{number}{title}{why it's interesting}
+\newcommand{\py at seepep}[3]{%
+  \par%
+  \begin{fulllineitems}
+    \item[\pep{#1}, ``\emph{#2}'']
+    #3
+  \end{fulllineitems}
+}
+% \seerfc{number}{title}{why it's interesting}
+\newcommand{\py at seerfc}[3]{%
+  \par%
+  \begin{fulllineitems}
+    \item[\rfc{#1}, ``\emph{#2}'']
+    #3
+  \end{fulllineitems}
+}
+% \seeurl{url}{why it's interesting}
+\newcommand{\py at seeurl}[2]{%
+  \par%
+  \begin{fulllineitems}
+    \item[\url{#1}]
+    #2
+  \end{fulllineitems}
+}
+
+\newenvironment{seealso*}{
+  \par
+  \def\seetext##1{\par{##1}}
+  \let\seemodule=\py at seemodule
+  \let\seepep=\py at seepep
+  \let\seerfc=\py at seerfc
+  \let\seetitle=\py at seetitle
+  \let\seeurl=\py at seeurl
+  \let\seelink=\py at seelink
+}{\par}
+\newenvironment{seealso}{
+  \par
+  \strong{See Also:}
+  \par
+  \def\seetext##1{\par{##1}}
+  \let\seemodule=\py at seemodule
+  \let\seepep=\py at seepep
+  \let\seerfc=\py at seerfc
+  \let\seetitle=\py at seetitle
+  \let\seeurl=\py at seeurl
+  \let\seelink=\py at seelink
+}{\par}
+
+% Allow the Python release number to be specified independently of the
+% \date{}.  This allows the date to reflect the document's date and
+% release to specify the Python release that is documented.
+%
+\newcommand{\py at release}{}
+\newcommand{\version}{}
+\newcommand{\shortversion}{}
+\newcommand{\releaseinfo}{}
+\newcommand{\releasename}{Release}
+\newcommand{\release}[1]{%
+  \renewcommand{\py at release}{\releasename\space\version}%
+  \renewcommand{\version}{#1}}
+\newcommand{\setshortversion}[1]{%
+  \renewcommand{\shortversion}{#1}}
+\newcommand{\setreleaseinfo}[1]{%
+  \renewcommand{\releaseinfo}{#1}}
+
+% Allow specification of the author's address separately from the
+% author's name.  This can be used to format them differently, which
+% is a good thing.
+%
+\newcommand{\py at authoraddress}{}
+\newcommand{\authoraddress}[1]{\renewcommand{\py at authoraddress}{#1}}
+\let\developersaddress=\authoraddress
+\let\developer=\author
+\let\developers=\author
+
+% This sets up the fancy chapter headings that make the documents look
+% at least a little better than the usual LaTeX output.
+%
+\@ifundefined{ChTitleVar}{}{
+  \ChNameVar{\raggedleft\normalsize\py at HeaderFamily}
+  \ChNumVar{\raggedleft \bfseries\Large\py at HeaderFamily}
+  \ChTitleVar{\raggedleft \rm\Huge\py at HeaderFamily}
+  % This creates chapter heads without the leading \vspace*{}:
+  \def\@makechapterhead#1{%
+    {\parindent \z@ \raggedright \normalfont
+      \ifnum \c at secnumdepth >\m at ne
+        \DOCH
+      \fi
+      \interlinepenalty\@M
+      \DOTI{#1}
+    }
+  }
+}
+
+
+% Definition lists; requested by AMK for HOWTO documents.  Probably useful
+% elsewhere as well, so keep in in the general style support.
+%
+\newenvironment{definitions}{%
+  \begin{description}%
+  \def\term##1{\item[##1]\mbox{}\\*[0mm]}
+}{%
+  \end{description}%
+}
+
+% Tell TeX about pathological hyphenation cases:
+\hyphenation{Base-HTTP-Re-quest-Hand-ler}

Added: sandbox/trunk/pdb/Doc/texinputs/underscore.sty
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/texinputs/underscore.sty	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,232 @@
+% underscore.sty     12-Oct-2001   Donald Arseneau   asnd at triumf.ca
+% Make the "_" character print as "\textunderscore" in text.
+% Copyright 1998,2001 Donald Arseneau;  Distribute freely if unchanged.
+% Instructions follow after the definitions.
+
+\ProvidesPackage{underscore}[2001/10/12]
+
+\begingroup
+ \catcode`\_=\active
+ \gdef_{% \relax % No relax gives a small vulnerability in alignments
+   \ifx\if at safe@actives\iftrue % must be outermost test!
+      \string_%
+   \else
+      \ifx\protect\@typeset at protect
+         \ifmmode \sb \else \BreakableUnderscore \fi
+      \else
+         \ifx\protect\@unexpandable at protect \noexpand_%
+         \else \protect_%
+      \fi\fi
+    \fi}
+\endgroup
+
+% At begin: set catcode; fix \long \ttdefault so I can use it in comparisons; 
+\AtBeginDocument{%
+  {\immediate\write\@auxout{\catcode\number\string`\_ \string\active}}%
+  \catcode\string`\_\string=\active
+  \edef\ttdefault{\ttdefault}%
+}
+
+\newcommand{\BreakableUnderscore}{\leavevmode\nobreak\hskip\z at skip
+ \ifx\f at family\ttdefault \string_\else \textunderscore\fi
+ \usc at dischyph\nobreak\hskip\z at skip}
+
+\DeclareRobustCommand{\_}{%
+  \ifmmode \nfss at text{\textunderscore}\else \BreakableUnderscore \fi}
+
+\let\usc at dischyph\@dischyph
+\DeclareOption{nohyphen}{\def\usc at dischyph{\discretionary{}{}{}}}
+\DeclareOption{strings}{\catcode`\_=\active}
+
+\ProcessOptions
+\ifnum\catcode`\_=\active\else \endinput \fi
+
+%%%%%%%%   Redefine commands that use character strings   %%%%%%%%
+
+\@ifundefined{UnderscoreCommands}{\let\UnderscoreCommands\@empty}{}
+\expandafter\def\expandafter\UnderscoreCommands\expandafter{%
+  \UnderscoreCommands
+  \do\include \do\includeonly
+  \do\@input \do\@iinput \do\InputIfFileExists
+  \do\ref \do\pageref \do\newlabel
+  \do\bibitem \do\@bibitem \do\cite \do\nocite \do\bibcite
+}
+
+% Macro to redefine a macro to pre-process its string argument
+% with \protect -> \string.
+\def\do#1{% Avoid double processing if user includes command twice!
+ \@ifundefined{US\string_\expandafter\@gobble\string#1}{%
+   \edef\@tempb{\meaning#1}% Check if macro is just a protection shell...
+   \def\@tempc{\protect}%
+   \edef\@tempc{\meaning\@tempc\string#1\space\space}%
+   \ifx\@tempb\@tempc % just a shell: hook into the protected inner command
+     \expandafter\do
+       \csname \expandafter\@gobble\string#1 \expandafter\endcsname
+   \else % Check if macro takes an optional argument
+     \def\@tempc{\@ifnextchar[}%
+     \edef\@tempa{\def\noexpand\@tempa####1\meaning\@tempc}%
+     \@tempa##2##3\@tempa{##2\relax}%
+     \edef\@tempb{\meaning#1\meaning\@tempc}%
+     \edef\@tempc{\noexpand\@tempd \csname
+        US\string_\expandafter\@gobble\string#1\endcsname}%
+     \if \expandafter\@tempa\@tempb \relax 12\@tempa % then no optional arg
+       \@tempc #1\US at prot
+     \else  % There is optional arg
+       \@tempc #1\US at protopt
+     \fi
+   \fi
+ }{}}
+
+\def\@tempd#1#2#3{\let#1#2\def#2{#3#1}}
+
+\def\US at prot#1#2{\let\@@protect\protect \let\protect\string
+  \edef\US at temp##1{##1{#2}}\restore at protect\US at temp#1}
+\def\US at protopt#1{\@ifnextchar[{\US at protarg#1}{\US at prot#1}}
+\def\US at protarg #1[#2]{\US at prot{{#1[#2]}}}
+
+\UnderscoreCommands
+\let\do\relax \let\@tempd\relax  % un-do
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+\endinput
+
+underscore.sty    12-Oct-2001  Donald Arseneau
+
+Features:
+~~~~~~~~~
+\_ prints an underscore so that the hyphenation of constituent words
+is not affected and hyphenation is permitted after the underscore.
+For example, "compound\_fracture" hyphenates as com- pound_- frac- ture.
+If you prefer the underscore to break without a hyphen (but still with 
+the same rules for explicit hyphen-breaks) then use the [nohyphen]
+package option.
+
+A simple _  acts just like \_ in text mode, but makes a subscript in 
+math mode: activation_energy $E_a$
+
+Both forms use an underscore character if the font encoding contains
+one (e.g., "\usepackage[T1]{fontenc}" or typewriter fonts in any encoding),
+but they use a rule if the there is no proper character.
+
+Deficiencies:
+~~~~~~~~~~~~~
+The skips and penalties ruin any kerning with the underscore character
+(when a character is used).  However, there doesn't seem to be much, if
+any, such kerning in the ec fonts, and there is never any kerning with
+a rule.
+
+You must avoid "_" in file names and in cite or ref tags, or you must use 
+the babel package, with its active-character controls, or you must give 
+the [strings] option, which attempts to redefine several commands (and 
+may not work perfectly).  Even without the [strings] option or babel, you 
+can use occasional underscores like: "\include{file\string_name}".
+
+Option: [strings]
+~~~~~~~~~~~~~~~~~
+The default operation is quite simple and needs no customization; but
+you must avoid using "_" in any place where LaTeX uses an argument as
+a string of characters for some control function or as a name.  These
+include the tags for \cite and \ref, file names for \input, \include,
+and \includegraphics, environment names, counter names, and placement
+parameters (like "[t]").  The problem with these contexts is that they
+are `moving arguments' but LaTeX does not `switch on' the \protect
+mechanism for them.
+
+If you need to use the underscore character in these places, the package
+option [strings] is provided to redefine commands taking a string argument
+so that the argument is protected (with \protect -> \string).  The list
+of commands is given in "\UnderscoreCommands", with "\do" before each,
+covering \cite, \ref, \input, and their variants.  Not included are many
+commands regarding font names, everything with counter names, environment
+names, page styles, and versions of \ref and \cite defined by external
+packages (e.g. \vref and \citeyear).
+
+You can add to the list of supported commands by defining \UnderscoreCommands
+before loading this package; e.g.
+
+   \usepackage{chicago}
+   \newcommand{\UnderscoreCommands}{%   (\cite already done)
+     \do\citeNP \do\citeA \do\citeANP \do\citeN \do\shortcite
+     \do\shortciteNP \do\shortciteA \do\shortciteANP \do\shortciteN
+     \do\citeyear \do\citeyearNP
+   }
+   \usepackage[strings]{underscore}
+
+Not all commands can be supported this way!  Only commands that take a
+string argument *first* can be protected.  One optional argument before
+the string argument is also permitted, as exemplified by \cite: both
+\cite{tags} and \cite[text]{tags} are allowed.  A command like
+\@addtoreset which takes two counter names as arguments could not
+be protected by adding it to \UnderscoreCommands.
+
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+!! When you use the [strings] option, you must load this package !!
+!! last (or nearly last).                                        !!
+!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+There are two reasons: 1) The redefinitions done for protection must come
+after other packages define their customized versions of those commands.
+2) The [strings] option requires the _ character to be activated immediately
+in order for the cite and ref tags to be read properly from the .aux file
+as plain strings, and this catcode setting might disrupt other packages.
+
+The babel package implements a protection mechanism for many commands,
+and will be a complete fix for most documents without the [strings] option.
+Many add-on packages are compatible with babel, so they will get the
+strings protection also.  However, there are several commands that are 
+not covered by babel, but can easily be supported by the [strings] and 
+\UnderscoreCommands mechanism.  Beware that using both [strings] and babel 
+may lead to conflicts, but does appear to work (load babel last).
+
+Implementation Notes:
+~~~~~~~~~~~~~~~~~~~~~
+The first setting of "_" to be an active character is performed in a local
+group so as to not interfere with other packages.  The catcode setting
+is repeated with \AtBeginDocument so the definition is in effect for the
+text.  However, the catcode setting is repeated immediately when the
+[strings] option is detected.
+
+The definition of the active "_" is essentially:
+       \ifmmode \sb \else \BreakableUnderscore \fi
+where "\sb" retains the normal subscript meaning of "_" and where
+"\BreakableUnderscore" is essentially "\_".  The rest of the definition
+handles the "\protect"ion without causing \relax to be inserted before
+the character.
+
+\BreakableUnderscore uses "\nobreak\hskip\z at skip" to separate the
+underscore from surrounding words, thus allowing TeX to hyphenate them,
+but preventing free breaks around the underscore. Next, it checks the
+current font family, and uses the underscore character from tt fonts or
+otherwise \textunderscore (which is a character or rule depending on
+the font encoding).  After the underscore, it inserts a discretionary
+hyphenation point as "\usc at dischyph", which is usually just "\-"
+except that it still works in the tabbing environment, although it
+will give "\discretionary{}{}{}" under the [nohyphen] option.  After
+that, another piece of non-breaking interword glue is inserted. 
+Ordinarily, the comparison "\ifx\f at family\ttdefault" will always fail 
+because \ttdefault is `long' where \f at family is not (boooo hisss), but 
+\ttdefault is redefined to be non-long by "\AtBeginDocument".
+
+The "\_" command is then defined to use "\BreakableUnderscore".
+
+If the [strings] option is not given, then that is all!
+
+Under the [strings] option, the list of special commands is processed to:
+- retain the original command as \US_command (\US_ref)
+- redefine the command as \US at prot\US_command for ordinary commands
+  (\ref -> \US at prot\US_ref) or as \US at protopt\US_command when an optional
+  argument is possible (\bibitem -> \US at protopt\US_bibitem).
+- self-protecting commands (\cite) retain their self-protection.
+Diagnosing the state of the pre-existing command is done by painful
+contortions involving \meaning.
+
+\US at prot and \US at protopt read the argument, process it with \protect
+enabled, then invoke the saved \US_command.
+
+Modifications:
+~~~~~~~~~~~~~~
+12-Oct-2001  Babel (safe at actives) compatibility and [nohyphen] option.
+
+Test file integrity:  ASCII 32-57, 58-126:  !"#$%&'()*+,-./0123456789
+:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Added: sandbox/trunk/pdb/Doc/tools/buildindex.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/buildindex.py	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,388 @@
+#! /usr/bin/env python
+
+__version__ = '$Revision: 1.1 $'
+
+import os.path
+import re
+import string
+import sys
+
+from xml.sax.saxutils import quoteattr
+
+
+bang_join = "!".join
+null_join = "".join
+
+REPLACEMENTS = [
+    # Hackish way to deal with macros replaced with simple text
+    (re.compile(r"\\ABC\b"), "ABC"),
+    (re.compile(r"\\ASCII\b"), "ASCII"),
+    (re.compile(r"\\Cpp\b"), "C++"),
+    (re.compile(r"\\EOF\b"), "EOF"),
+    (re.compile(r"\\NULL\b"), "NULL"),
+    (re.compile(r"\\POSIX\b"), "POSIX"),
+    (re.compile(r"\\UNIX\b"), "Unix"),
+    # deal with turds left over from LaTeX2HTML
+    (re.compile(r"<#\d+#>"), ""),
+    ]
+
+class Node:
+    continuation = 0
+
+    def __init__(self, link, str, seqno):
+        self.links = [link]
+        self.seqno = seqno
+        for pattern, replacement in REPLACEMENTS:
+            str = pattern.sub(replacement, str)
+        # build up the text
+        self.text = split_entry_text(str)
+        self.key = split_entry_key(str)
+
+    def __cmp__(self, other):
+        """Comparison operator includes sequence number, for use with
+        list.sort()."""
+        return self.cmp_entry(other) or cmp(self.seqno, other.seqno)
+
+    def cmp_entry(self, other):
+        """Comparison 'operator' that ignores sequence number."""
+        c = 0
+        for i in range(min(len(self.key), len(other.key))):
+            c = (cmp_part(self.key[i], other.key[i])
+                 or cmp_part(self.text[i], other.text[i]))
+            if c:
+                break
+        return c or cmp(self.key, other.key) or cmp(self.text, other.text)
+
+    def __repr__(self):
+        return "<Node for %s (%s)>" % (bang_join(self.text), self.seqno)
+
+    def __str__(self):
+        return bang_join(self.key)
+
+    def dump(self):
+        return "%s\1%s###%s\n" \
+               % ("\1".join(self.links),
+                  bang_join(self.text),
+                  self.seqno)
+
+
+def cmp_part(s1, s2):
+    result = cmp(s1, s2)
+    if result == 0:
+        return 0
+    l1 = s1.lower()
+    l2 = s2.lower()
+    minlen = min(len(s1), len(s2))
+    if len(s1) < len(s2) and l1 == l2[:len(s1)]:
+        result = -1
+    elif len(s2) < len(s1) and l2 == l1[:len(s2)]:
+        result = 1
+    else:
+        result = cmp(l1, l2) or cmp(s1, s2)
+    return result
+
+
+def split_entry(str, which):
+    stuff = []
+    parts = str.split('!')
+    parts = [part.split('@') for part in parts]
+    for entry in parts:
+        if len(entry) != 1:
+            key = entry[which]
+        else:
+            key = entry[0]
+        stuff.append(key)
+    return stuff
+
+
+_rmtt = re.compile(r"""(.*)<tt(?: class=['"][a-z0-9]+["'])?>(.*)</tt>(.*)$""",
+                   re.IGNORECASE)
+_rmparens = re.compile(r"\(\)")
+
+def split_entry_key(str):
+    parts = split_entry(str, 1)
+    for i in range(len(parts)):
+        m = _rmtt.match(parts[i])
+        if m:
+            parts[i] = null_join(m.group(1, 2, 3))
+        else:
+            parts[i] = parts[i].lower()
+        # remove '()' from the key:
+        parts[i] = _rmparens.sub('', parts[i])
+    return map(trim_ignored_letters, parts)
+
+
+def split_entry_text(str):
+    if '<' in str:
+        m = _rmtt.match(str)
+        if m:
+            str = null_join(m.group(1, 2, 3))
+    return split_entry(str, 1)
+
+
+def load(fp):
+    nodes = []
+    rx = re.compile("(.*)\1(.*)###(.*)$")
+    while 1:
+        line = fp.readline()
+        if not line:
+            break
+        m = rx.match(line)
+        if m:
+            link, str, seqno = m.group(1, 2, 3)
+            nodes.append(Node(link, str, seqno))
+    return nodes
+
+
+def trim_ignored_letters(s):
+    # ignore $ to keep environment variables with the
+    # leading letter from the name
+    if s.startswith("$"):
+        return s[1:].lower()
+    else:
+        return s.lower()
+
+def get_first_letter(s):
+    if s.startswith("<tex2html_percent_mark>"):
+        return "%"
+    else:
+        return trim_ignored_letters(s)[0]
+
+
+def split_letters(nodes):
+    letter_groups = []
+    if nodes:
+        group = []
+        append = group.append
+        letter = get_first_letter(nodes[0].text[0])
+        letter_groups.append((letter, group))
+        for node in nodes:
+            nletter = get_first_letter(node.text[0])
+            if letter != nletter:
+                letter = nletter
+                group = []
+                letter_groups.append((letter, group))
+                append = group.append
+            append(node)
+    return letter_groups
+
+
+def group_symbols(groups):
+    entries = []
+    ident_letters = string.ascii_letters + "_"
+    while groups[0][0] not in ident_letters:
+        entries += groups[0][1]
+        del groups[0]
+    if entries:
+        groups.insert(0, ("Symbols", entries))
+
+
+# need a function to separate the nodes into columns...
+def split_columns(nodes, columns=1):
+    if columns <= 1:
+        return [nodes]
+    # This is a rough height; we may have to increase to avoid breaks before
+    # a subitem.
+    colheight = int(len(nodes) / columns)
+    numlong = int(len(nodes) % columns)
+    if numlong:
+        colheight = colheight + 1
+    else:
+        numlong = columns
+    cols = []
+    for i in range(numlong):
+        start = i * colheight
+        end = start + colheight
+        cols.append(nodes[start:end])
+    del nodes[:end]
+    colheight = colheight - 1
+    try:
+        numshort = int(len(nodes) / colheight)
+    except ZeroDivisionError:
+        cols = cols + (columns - len(cols)) * [[]]
+    else:
+        for i in range(numshort):
+            start = i * colheight
+            end = start + colheight
+            cols.append(nodes[start:end])
+    #
+    # If items continue across columns, make sure they are marked
+    # as continuations so the user knows to look at the previous column.
+    #
+    for i in range(len(cols) - 1):
+        try:
+            prev = cols[i][-1]
+            next = cols[i + 1][0]
+        except IndexError:
+            return cols
+        else:
+            n = min(len(prev.key), len(next.key))
+            for j in range(n):
+                if prev.key[j] != next.key[j]:
+                    break
+                next.continuation = j + 1
+    return cols
+
+
+DL_LEVEL_INDENT = "  "
+
+def format_column(nodes):
+    strings = ["<dl compact='compact'>"]
+    append = strings.append
+    level = 0
+    previous = []
+    for node in nodes:
+        current = node.text
+        count = 0
+        for i in range(min(len(current), len(previous))):
+            if previous[i] != current[i]:
+                break
+            count = i + 1
+        if count > level:
+            append("<dl compact='compact'>" * (count - level) + "\n")
+            level = count
+        elif level > count:
+            append("\n")
+            append(level * DL_LEVEL_INDENT)
+            append("</dl>" * (level - count))
+            level = count
+        # else: level == count
+        for i in range(count, len(current) - 1):
+            term = node.text[i]
+            level = level + 1
+            if node.continuation > i:
+                extra = " (continued)"
+            else:
+                extra = ""
+            append("\n<dt>%s%s\n<dd>\n%s<dl compact='compact'>"
+                   % (term, extra, level * DL_LEVEL_INDENT))
+        append("\n%s<dt>%s%s</a>"
+               % (level * DL_LEVEL_INDENT, node.links[0], node.text[-1]))
+        for link in node.links[1:]:
+            append(",\n%s    %s[Link]</a>" % (level * DL_LEVEL_INDENT, link))
+        previous = current
+    append("\n")
+    append("</dl>" * (level + 1))
+    return null_join(strings)
+
+
+def format_nodes(nodes, columns=1):
+    strings = []
+    append = strings.append
+    if columns > 1:
+        colnos = range(columns)
+        colheight = int(len(nodes) / columns)
+        if len(nodes) % columns:
+            colheight = colheight + 1
+        colwidth = int(100 / columns)
+        append('<table width="100%"><tr valign="top">')
+        for col in split_columns(nodes, columns):
+            append('<td width="%d%%">\n' % colwidth)
+            append(format_column(col))
+            append("\n</td>")
+        append("\n</tr></table>")
+    else:
+        append(format_column(nodes))
+    return null_join(strings)
+
+
+def format_letter(letter):
+    if letter == '.':
+        lettername = ". (dot)"
+    elif letter == '_':
+        lettername = "_ (underscore)"
+    else:
+        lettername = letter.capitalize()
+    return "\n<hr />\n<h2 id=%s>%s</h2>\n\n" \
+           % (quoteattr("letter-" + letter), lettername)
+
+
+def format_html_letters(nodes, columns, group_symbol_nodes):
+    letter_groups = split_letters(nodes)
+    if group_symbol_nodes:
+        group_symbols(letter_groups)
+    items = []
+    for letter, nodes in letter_groups:
+        s = "<b><a href=\"#letter-%s\">%s</a></b>" % (letter, letter)
+        items.append(s)
+    s = ["<hr /><center>\n%s</center>\n" % " |\n".join(items)]
+    for letter, nodes in letter_groups:
+        s.append(format_letter(letter))
+        s.append(format_nodes(nodes, columns))
+    return null_join(s)
+
+def format_html(nodes, columns):
+    return format_nodes(nodes, columns)
+
+
+def collapse(nodes):
+    """Collapse sequences of nodes with matching keys into a single node.
+    Destructive."""
+    if len(nodes) < 2:
+        return
+    prev = nodes[0]
+    i = 1
+    while i < len(nodes):
+        node = nodes[i]
+        if not node.cmp_entry(prev):
+            prev.links.append(node.links[0])
+            del nodes[i]
+        else:
+            i = i + 1
+            prev = node
+
+
+def dump(nodes, fp):
+    for node in nodes:
+        fp.write(node.dump())
+
+
+def process_nodes(nodes, columns, letters=0, group_symbol_nodes=0):
+    nodes.sort()
+    collapse(nodes)
+    if letters:
+        return format_html_letters(nodes, columns, group_symbol_nodes)
+    else:
+        return format_html(nodes, columns)
+
+
+def main():
+    import getopt
+    ifn = "-"
+    ofn = "-"
+    columns = 1
+    letters = 0
+    group_symbol_nodes = 1
+    opts, args = getopt.getopt(sys.argv[1:], "c:lo:",
+                               ["columns=", "dont-group-symbols",
+                                "group-symbols", "letters", "output="])
+    for opt, val in opts:
+        if opt in ("-o", "--output"):
+            ofn = val
+        elif opt in ("-c", "--columns"):
+            columns = int(val, 10)
+        elif opt in ("-l", "--letters"):
+            letters = 1
+        elif opt == "--group-symbols":
+            group_symbol_nodes = 1
+        elif opt == "--dont-group-symbols":
+            group_symbol_nodes = 0
+    if not args:
+        args = [ifn]
+    nodes = []
+    for fn in args:
+        nodes = nodes + load(open(fn))
+    num_nodes = len(nodes)
+    html = process_nodes(nodes, columns, letters, group_symbol_nodes)
+    program = os.path.basename(sys.argv[0])
+    if ofn == "-":
+        sys.stdout.write(html)
+        sys.stderr.write("\n%s: %d index nodes" % (program, num_nodes))
+    else:
+        open(ofn, "w").write(html)
+        print
+        print "%s: %d index nodes" % (program, num_nodes)
+
+
+if __name__ == "__main__":
+    main()

Added: sandbox/trunk/pdb/Doc/tools/checkargs.pm
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/checkargs.pm	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,112 @@
+#! /usr/bin/perl
+
+package checkargs;
+require 5.004;			# uses "for my $var"
+require Exporter;
+ at ISA = qw(Exporter);
+ at EXPORT = qw(check_args check_args_range check_args_at_least);
+use strict;
+use Carp;
+
+=head1 NAME
+
+checkargs -- Provide rudimentary argument checking for perl5 functions
+
+=head1 SYNOPSIS
+
+  check_args(cArgsExpected, @_)
+  check_args_range(cArgsMin, cArgsMax, @_)
+  check_args_at_least(cArgsMin, @_)
+where "@_" should be supplied literally.
+
+=head1 DESCRIPTION
+
+As the first line of user-written subroutine foo, do one of the following:
+
+  my ($arg1, $arg2) = check_args(2, @_);
+  my ($arg1, @rest) = check_args_range(1, 4, @_);
+  my ($arg1, @rest) = check_args_at_least(1, @_);
+  my @args = check_args_at_least(0, @_);
+
+These functions may also be called for side effect (put a call to one
+of the functions near the beginning of the subroutine), but using the
+argument checkers to set the argument list is the recommended usage.
+
+The number of arguments and their definedness are checked; if the wrong
+number are received, the program exits with an error message.
+
+=head1 AUTHOR
+
+Michael D. Ernst <F<mernst at cs.washington.edu>>
+
+=cut
+
+## Need to check that use of caller(1) really gives desired results.
+## Need to give input chunk information.
+## Is this obviated by Perl 5.003's declarations?  Not entirely, I think.
+
+sub check_args ( $@ )
+{
+  my ($num_formals, @args) = @_;
+  my ($pack, $file_arg, $line_arg, $subname, $hasargs, $wantarr) = caller(1);
+  if (@_ < 1) { croak "check_args needs at least 7 args, got ", scalar(@_), ": @_\n "; }
+  if ((!wantarray) && ($num_formals != 0))
+    { croak "check_args called in scalar context"; }
+  # Can't use croak below here: it would only go out to caller, not its caller
+  my $num_actuals = @args;
+  if ($num_actuals != $num_formals)
+    { die "$file_arg:$line_arg: function $subname expected $num_formals argument",
+      (($num_formals == 1) ? "" : "s"),
+      ", got $num_actuals",
+      (($num_actuals == 0) ? "" : ": @args"),
+      "\n"; }
+  for my $index (0..$#args)
+    { if (!defined($args[$index]))
+	{ die "$file_arg:$line_arg: function $subname undefined argument ", $index+1, ": @args[0..$index-1]\n"; } }
+  return @args;
+}
+
+sub check_args_range ( $$@ )
+{
+  my ($min_formals, $max_formals, @args) = @_;
+  my ($pack, $file_arg, $line_arg, $subname, $hasargs, $wantarr) = caller(1);
+  if (@_ < 2) { croak "check_args_range needs at least 8 args, got ", scalar(@_), ": @_"; }
+  if ((!wantarray) && ($max_formals != 0) && ($min_formals !=0) )
+    { croak "check_args_range called in scalar context"; }
+  # Can't use croak below here: it would only go out to caller, not its caller
+  my $num_actuals = @args;
+  if (($num_actuals < $min_formals) || ($num_actuals > $max_formals))
+    { die "$file_arg:$line_arg: function $subname expected $min_formals-$max_formals arguments, got $num_actuals",
+      ($num_actuals == 0) ? "" : ": @args", "\n"; }
+  for my $index (0..$#args)
+    { if (!defined($args[$index]))
+	{ die "$file_arg:$line_arg: function $subname undefined argument ", $index+1, ": @args[0..$index-1]\n"; } }
+  return @args;
+}
+
+sub check_args_at_least ( $@ )
+{
+  my ($min_formals, @args) = @_;
+  my ($pack, $file_arg, $line_arg, $subname, $hasargs, $wantarr) = caller(1);
+  # Don't do this, because we want every sub to start with a call to check_args*
+  # if ($min_formals == 0)
+  #   { die "Isn't it pointless to check for at least zero args to $subname?\n"; }
+  if (scalar(@_) < 1)
+    { croak "check_args_at_least needs at least 1 arg, got ", scalar(@_), ": @_"; }
+  if ((!wantarray) && ($min_formals != 0))
+    { croak "check_args_at_least called in scalar context"; }
+  # Can't use croak below here: it would only go out to caller, not its caller
+  my $num_actuals = @args;
+  if ($num_actuals < $min_formals)
+    { die "$file_arg:$line_arg: function $subname expected at least $min_formals argument",
+      ($min_formals == 1) ? "" : "s",
+      ", got $num_actuals",
+      ($num_actuals == 0) ? "" : ": @args", "\n"; }
+  for my $index (0..$#args)
+    { if (!defined($args[$index]))
+	{ warn "$file_arg:$line_arg: function $subname undefined argument ", $index+1, ": @args[0..$index-1]\n"; last; } }
+  return @args;
+}
+
+1;				# successful import
+__END__

Added: sandbox/trunk/pdb/Doc/tools/getversioninfo
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/getversioninfo	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,63 @@
+#! /usr/bin/env python
+
+import os
+import re
+import sys
+
+try:
+    __file__
+except NameError:
+    __file__ = sys.argv[0]
+
+tools = os.path.dirname(os.path.abspath(__file__))
+Doc = os.path.dirname(tools)
+src = os.path.dirname(Doc)
+patchlevel_h = os.path.join(Doc, "tools", "patchlevel.h")
+
+# This won't pick out all #defines, but it will pick up the ones we
+# care about.
+rx = re.compile(r"\s*#define\s+([a-zA-Z][a-zA-Z_0-9]*)\s+([a-zA-Z_0-9]+)")
+
+d = {}
+f = open(patchlevel_h)
+for line in f:
+    m = rx.match(line)
+    if m is not None:
+        name, value = m.group(1, 2)
+        d[name] = value
+f.close()
+
+release = "%s.%s" % (d["PY_MAJOR_VERSION"], d["PY_MINOR_VERSION"])
+micro = int(d["PY_MICRO_VERSION"])
+shortversion = release
+if micro != 0:
+    release += "." + str(micro)
+level = d["PY_RELEASE_LEVEL"]
+
+releaseinfo = "mpdb"
+
+def write_file(name, text):
+    """Write text to a file if the file doesn't exist or if text
+    differs from any existing content."""
+    if os.path.exists(name):
+        f = open(name, "r")
+        s = f.read()
+        f.close()
+        if s == text:
+            return
+    f = open(name, "w")
+    f.write(text)
+    f.close()
+
+patchlevel_tex = os.path.join(Doc, "commontex", "patchlevel.tex")
+
+write_file(patchlevel_tex,
+           "%% This file is generated by ../tools/getversioninfo;\n"
+           "%% do not edit manually.\n"
+           "\n"
+           "\\release{%s}\n"
+           "\\setreleaseinfo{%s}\n"
+           "\\setshortversion{%s}\n"
+           % (release, releaseinfo, shortversion))
+
+print release + releaseinfo

Added: sandbox/trunk/pdb/Doc/tools/indfix.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/indfix.py	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,100 @@
+#! /usr/bin/env python
+
+"""Combine similar index entries into an entry and subentries.
+
+For example:
+
+    \item {foobar} (in module flotz), 23
+    \item {foobar} (in module whackit), 4323
+
+becomes
+
+    \item {foobar}
+      \subitem in module flotz, 23
+      \subitem in module whackit, 4323
+
+Note that an item which matches the format of a collapsable item but which
+isn't part of a group of similar items is not modified.
+"""
+__version__ = '$Revision: 1.1 $'
+
+import re
+import StringIO
+import sys
+
+
+def cmp_entries(e1, e2):
+    return cmp(e1[1].lower(), e2[1].lower()) or cmp(e1, e2)
+
+
+def dump_entries(write, entries):
+    if len(entries) == 1:
+        write("  \\item %s (%s)%s\n" % entries[0])
+        return
+    write("  \item %s\n" % entries[0][0])
+    # now sort these in a case insensitive manner:
+    if len(entries) > 0:
+        entries.sort(cmp_entries)
+    for xxx, subitem, pages in entries:
+        write("    \subitem %s%s\n" % (subitem, pages))
+
+
+breakable_re = re.compile(
+    r"  \\item (.*) [(](.*)[)]((?:(?:, \d+)|(?:, \\[a-z]*\{\d+\}))+)")
+
+
+def process(ifn, ofn=None):
+    if ifn == "-":
+        ifp = sys.stdin
+    else:
+        ifp = open(ifn)
+    if ofn is None:
+        ofn = ifn
+    ofp = StringIO.StringIO()
+    entries = []
+    match = breakable_re.match
+    write = ofp.write
+    while 1:
+        line = ifp.readline()
+        if not line:
+            break
+        m = match(line)
+        if m:
+            entry = m.group(1, 2, 3)
+            if entries and entries[-1][0] != entry[0]:
+                dump_entries(write, entries)
+                entries = []
+            entries.append(entry)
+        elif entries:
+            dump_entries(write, entries)
+            entries = []
+            write(line)
+        else:
+            write(line)
+    del write
+    del match
+    ifp.close()
+    data = ofp.getvalue()
+    ofp.close()
+    if ofn == "-":
+        ofp = sys.stdout
+    else:
+        ofp = open(ofn, "w")
+    ofp.write(data)
+    ofp.close()
+
+
+def main():
+    import getopt
+    outfile = None
+    opts, args = getopt.getopt(sys.argv[1:], "o:")
+    for opt, val in opts:
+        if opt in ("-o", "--output"):
+            outfile = val
+    filename = args[0]
+    outfile = outfile or filename
+    process(filename, outfile)
+
+
+if __name__ == "__main__":
+    main()

Added: sandbox/trunk/pdb/Doc/tools/mkhowto
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/mkhowto	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,659 @@
+#! /usr/bin/env python
+#  -*- Python -*-
+"""usage: %(program)s [options...] file ...
+
+Options specifying formats to build:
+    --html		HyperText Markup Language (default)
+    --pdf		Portable Document Format
+    --ps		PostScript
+    --dvi		'DeVice Indepentent' format from TeX
+    --text		ASCII text (requires lynx)
+
+    More than one output format may be specified, or --all.
+
+HTML options:
+    --address, -a	Specify an address for page footers.
+    --dir		Specify the directory for HTML output.
+    --link		Specify the number of levels to include on each page.
+    --split, -s		Specify a section level for page splitting, default: %(max_split_depth)s.
+    --iconserver, -i	Specify location of icons (default: ./).
+    --image-type	Specify the image type to use in HTML output;
+                        values: gif, png (default).
+    --numeric           Don't rename the HTML files; just keep node#.html for
+                        the filenames.
+    --style             Specify the CSS file to use for the output (filename,
+                        not a URL).
+    --up-link           URL to a parent document.
+    --up-title          Title of a parent document.
+    --favicon           Icon to display in the browsers location bar.
+
+Other options:
+    --a4		Format for A4 paper.
+    --letter		Format for US letter paper (the default).
+    --help, -H		Show this text.
+    --logging, -l	Log stdout and stderr to a file (*.how).
+    --debugging, -D	Echo commands as they are executed.
+    --keep, -k		Keep temporary files around.
+    --quiet, -q		Do not print command output to stdout.
+			(stderr is also lost,  sorry; see *.how for errors)
+"""
+
+import getopt
+import glob
+import os
+import re
+import shutil
+import sys
+
+
+MYDIR = os.path.abspath(sys.path[0])
+TOPDIR = os.path.dirname(MYDIR)
+
+ISTFILE = os.path.join(TOPDIR, "texinputs", "python.ist")
+NODE2LABEL_SCRIPT = os.path.join(MYDIR, "node2label.pl")
+L2H_INIT_FILE = os.path.join(TOPDIR, "perl", "l2hinit.perl")
+
+BIBTEX_BINARY = "bibtex"
+DVIPS_BINARY = "dvips"
+LATEX_BINARY = "latex"
+LATEX2HTML_BINARY = "latex2html"
+LYNX_BINARY = "lynx"
+MAKEINDEX_BINARY = "makeindex"
+PDFLATEX_BINARY = "pdflatex"
+PERL_BINARY = "perl"
+PYTHON_BINARY = "python"
+
+
+def usage(options, file):
+    print >>file, __doc__ % options
+
+def error(options, message, err=2):
+    print >>sys.stderr, message
+    print >>sys.stderr
+    usage(options, sys.stderr)
+    sys.exit(2)
+
+
+class Options:
+    program = os.path.basename(sys.argv[0])
+    #
+    address = ''
+    builddir = None
+    debugging = 0
+    discard_temps = 1
+    have_temps = 0
+    icon_server = "."
+    image_type = "png"
+    logging = 0
+    max_link_depth = 3
+    max_split_depth = 6
+    paper = "letter"
+    quiet = 0
+    runs = 0
+    numeric = 0
+    global_module_index = None
+    style_file = os.path.join(TOPDIR, "html", "style.css")
+    about_file = os.path.join(TOPDIR, "html", "about.dat")
+    up_link = None
+    up_title = None
+    favicon = None
+    #
+    # 'dvips_safe' is a weird option.  It is used mostly to make
+    # LaTeX2HTML not try to be too smart about protecting the user
+    # from a bad version of dvips -- some versions would core dump if
+    # the path to the source DVI contained a dot, and it's appearantly
+    # difficult to determine if the version available has that bug.
+    # This option gets set when PostScript output is requested
+    # (because we're going to run dvips regardless, and we'll either
+    # know it succeeds before LaTeX2HTML is run, or we'll have
+    # detected the failure and bailed), or the user asserts that it's
+    # safe from the command line.
+    #
+    # So, why does LaTeX2HTML think it appropriate to protect the user
+    # from a dvips that's only potentially going to core dump?  Only
+    # because they want to avoid doing a lot of work just to have to
+    # bail later with no useful intermediates.  Unfortunately, they
+    # bail *before* they know whether dvips will be needed at all.
+    # I've gone around the bush a few times with the LaTeX2HTML
+    # developers over whether this is appropriate behavior, and they
+    # don't seem interested in changing their position.
+    #
+    dvips_safe = 0
+    #
+    DEFAULT_FORMATS = ("html",)
+    ALL_FORMATS = ("dvi", "html", "pdf", "ps", "text")
+
+    def __init__(self):
+        self.formats = []
+        self.l2h_init_files = []
+
+    def __getitem__(self, key):
+        # This is used when formatting the usage message.
+        try:
+            return getattr(self, key)
+        except AttributeError:
+            raise KeyError, key
+
+    def parse(self, args):
+        opts, args = getopt.getopt(args, "Hi:a:s:lDkqr:",
+                                   ["all", "postscript", "help", "iconserver=",
+                                    "address=", "a4", "letter", "l2h-init=",
+                                    "link=", "split=", "logging", "debugging",
+                                    "keep", "quiet", "runs=", "image-type=",
+                                    "about=", "numeric", "style=", "paper=",
+                                    "up-link=", "up-title=", "dir=",
+                                    "global-module-index=", "dvips-safe",
+                                    "favicon="]
+                                   + list(self.ALL_FORMATS))
+        for opt, arg in opts:
+            if opt == "--all":
+                self.formats = list(self.ALL_FORMATS)
+                self.dvips_safe = "ps" in self.formats
+            elif opt in ("-H", "--help"):
+                usage(self, sys.stdout)
+                sys.exit()
+            elif opt == "--iconserver":
+                self.icon_server = arg
+            elif opt in ("-a", "--address"):
+                self.address = arg
+            elif opt == "--a4":
+                self.paper = "a4"
+            elif opt == "--letter":
+                self.paper = "letter"
+            elif opt == "--link":
+                self.max_link_depth = int(arg)
+            elif opt in ("-s", "--split"):
+                self.max_split_depth = int(arg)
+            elif opt in ("-l", "--logging"):
+                self.logging = self.logging + 1
+            elif opt in ("-D", "--debugging"):
+                self.debugging = self.debugging + 1
+            elif opt in ("-k", "--keep"):
+                self.discard_temps = 0
+            elif opt in ("-q", "--quiet"):
+                self.quiet = 1
+            elif opt in ("-r", "--runs"):
+                self.runs = int(arg)
+            elif opt == "--image-type":
+                self.image_type = arg
+            elif opt == "--about":
+                # always make this absolute:
+                self.about_file = os.path.normpath(
+                    os.path.abspath(arg))
+            elif opt == "--numeric":
+                self.numeric = 1
+            elif opt == "--style":
+                self.style_file = os.path.abspath(arg)
+            elif opt == "--l2h-init":
+                self.l2h_init_files.append(os.path.abspath(arg))
+            elif opt == "--favicon":
+                self.favicon = arg
+            elif opt == "--up-link":
+                self.up_link = arg
+            elif opt == "--up-title":
+                self.up_title = arg
+            elif opt == "--global-module-index":
+                self.global_module_index = arg
+            elif opt == "--dir":
+                if os.sep == "\\":
+                    arg = re.sub("/", "\\\\", arg)
+                self.builddir = os.path.expanduser(arg)
+            elif opt == "--paper":
+                self.paper = arg
+            elif opt == "--dvips-safe":
+                self.dvips_safe = 1
+            #
+            # Format specifiers:
+            #
+            elif opt[2:] in self.ALL_FORMATS:
+                self.add_format(opt[2:])
+            elif opt == "--postscript":
+                # synonym for --ps
+                self.add_format("ps")
+        self.initialize()
+        #
+        # return the args to allow the caller access:
+        #
+        return args
+
+    def add_format(self, format):
+        """Add a format to the formats list if not present."""
+        if not format in self.formats:
+            if format == "ps":
+                # assume this is safe since we're going to run it anyway
+                self.dvips_safe = 1
+            self.formats.append(format)
+
+    def initialize(self):
+        """Complete initialization.  This is needed if parse() isn't used."""
+        # add the default format if no formats were specified:
+        if not self.formats:
+            self.formats = self.DEFAULT_FORMATS
+        # determine the base set of texinputs directories:
+        texinputs = os.environ.get("TEXINPUTS", "").split(os.pathsep)
+        if not texinputs:
+            texinputs = ['']
+        mydirs = [os.path.join(TOPDIR, "paper-" + self.paper),
+                  os.path.join(TOPDIR, "texinputs"),
+                  ]
+        if '' in texinputs:
+            i = texinputs.index('')
+            texinputs[i:i] = mydirs
+        else:
+            texinputs += mydirs
+        self.base_texinputs = texinputs
+        if self.builddir:
+            self.builddir = os.path.abspath(self.builddir)
+
+
+class Job:
+    latex_runs = 0
+
+    def __init__(self, options, path):
+        self.options = options
+        self.doctype = get_doctype(path)
+        self.filedir, self.doc = split_pathname(path)
+        self.builddir = os.path.abspath(options.builddir or self.doc)
+        if ("html" in options.formats or "text" in options.formats):
+            if not os.path.exists(self.builddir):
+                os.mkdir(self.builddir)
+            self.log_filename = os.path.join(self.builddir, self.doc + ".how")
+        else:
+            self.log_filename = os.path.abspath(self.doc + ".how")
+        if os.path.exists(self.log_filename):
+            os.unlink(self.log_filename)
+        l2hconf = self.doc + ".l2h"
+        if os.path.exists(l2hconf):
+            if os.path.exists(l2hconf + "~"):
+                os.unlink(l2hconf + "~")
+            os.rename(l2hconf, l2hconf + "~")
+        self.l2h_aux_init_file = self.doc + ".l2h"
+        self.write_l2h_aux_init_file()
+
+    def build(self):
+        self.setup_texinputs()
+        formats = self.options.formats
+        if "dvi" in formats or "ps" in formats:
+            self.build_dvi()
+        if "pdf" in formats:
+            self.build_pdf()
+        if "ps" in formats:
+            self.build_ps()
+        if "html" in formats:
+            self.require_temps()
+            self.build_html(self.builddir)
+            if self.options.icon_server == ".":
+                pattern = os.path.join(TOPDIR, "html", "icons",
+                                       "*." + self.options.image_type)
+                imgs = glob.glob(pattern)
+                if not imgs:
+                    self.warning(
+                        "Could not locate support images of type %s."
+                        % `self.options.image_type`)
+                for fn in imgs:
+                    new_fn = os.path.join(self.builddir, os.path.basename(fn))
+                    shutil.copyfile(fn, new_fn)
+        if "text" in formats:
+            self.require_temps()
+            tempdir = self.doc
+            need_html = "html" not in formats
+            if self.options.max_split_depth != 1:
+                fp = open(self.l2h_aux_init_file, "a")
+                fp.write("# re-hack this file for --text:\n")
+                l2hoption(fp, "MAX_SPLIT_DEPTH", "1")
+                fp.write("1;\n")
+                fp.close()
+                tempdir = self.doc + "-temp-html"
+                need_html = 1
+            if need_html:
+                self.build_html(tempdir, max_split_depth=1)
+            self.build_text(tempdir)
+        if self.options.discard_temps:
+            self.cleanup()
+
+    def setup_texinputs(self):
+        texinputs = [self.filedir] + self.options.base_texinputs
+        os.environ["TEXINPUTS"] = os.pathsep.join(texinputs)
+        self.message("TEXINPUTS=" + os.environ["TEXINPUTS"])
+
+    def build_aux(self, binary=None):
+        if binary is None:
+            binary = LATEX_BINARY
+        new_index(   "%s.ind" % self.doc, "genindex")
+        new_index("mod%s.ind" % self.doc, "modindex")
+        self.run("%s %s" % (binary, self.doc))
+        self.use_bibtex = check_for_bibtex(self.doc + ".aux")
+        self.latex_runs = 1
+
+    def build_dvi(self):
+        self.use_latex(LATEX_BINARY)
+
+    def build_pdf(self):
+        self.use_latex(PDFLATEX_BINARY)
+
+    def use_latex(self, binary):
+        self.require_temps(binary=binary)
+        if self.latex_runs < 2:
+            if os.path.isfile("mod%s.idx" % self.doc):
+                self.run("%s mod%s.idx" % (MAKEINDEX_BINARY, self.doc))
+            use_indfix = 0
+            if os.path.isfile(self.doc + ".idx"):
+                use_indfix = 1
+                # call to Doc/tools/fix_hack omitted; doesn't appear necessary
+                self.run("%s %s.idx" % (MAKEINDEX_BINARY, self.doc))
+                import indfix
+                indfix.process(self.doc + ".ind")
+            if self.use_bibtex:
+                self.run("%s %s" % (BIBTEX_BINARY, self.doc))
+            self.process_synopsis_files()
+            self.run("%s %s" % (binary, self.doc))
+            self.latex_runs = self.latex_runs + 1
+            if os.path.isfile("mod%s.idx" % self.doc):
+                self.run("%s -s %s mod%s.idx"
+                         % (MAKEINDEX_BINARY, ISTFILE, self.doc))
+            if use_indfix:
+                self.run("%s -s %s %s.idx"
+                         % (MAKEINDEX_BINARY, ISTFILE, self.doc))
+                indfix.process(self.doc + ".ind")
+            self.process_synopsis_files()
+        #
+        # and now finish it off:
+        #
+        if os.path.isfile(self.doc + ".toc") and binary == PDFLATEX_BINARY:
+            import toc2bkm
+            if self.doctype == "manual":
+                bigpart = "chapter"
+            else:
+                bigpart = "section"
+            toc2bkm.process(self.doc + ".toc", self.doc + ".bkm", bigpart)
+        if self.use_bibtex:
+            self.run("%s %s" % (BIBTEX_BINARY, self.doc))
+        self.run("%s %s" % (binary, self.doc))
+        self.latex_runs = self.latex_runs + 1
+
+    def process_synopsis_files(self):
+        synopsis_files = glob.glob(self.doc + "*.syn")
+        for path in synopsis_files:
+            uniqify_module_table(path)
+
+    def build_ps(self):
+        self.run("%s -N0 -o %s.ps %s" % (DVIPS_BINARY, self.doc, self.doc))
+
+    def build_html(self, builddir, max_split_depth=None):
+        if max_split_depth is None:
+            max_split_depth = self.options.max_split_depth
+        texfile = None
+        for p in os.environ["TEXINPUTS"].split(os.pathsep):
+            fn = os.path.join(p, self.doc + ".tex")
+            if os.path.isfile(fn):
+                texfile = fn
+                break
+        if not texfile:
+            self.warning("Could not locate %s.tex; aborting." % self.doc)
+            sys.exit(1)
+        # remove leading ./ (or equiv.); might avoid problems w/ dvips
+        if texfile[:2] == os.curdir + os.sep:
+            texfile = texfile[2:]
+        # build the command line and run LaTeX2HTML:
+        if not os.path.isdir(builddir):
+            os.mkdir(builddir)
+        else:
+            for fname in glob.glob(os.path.join(builddir, "*.html")):
+                os.unlink(fname)
+        args = [LATEX2HTML_BINARY,
+                "-init_file", self.l2h_aux_init_file,
+                "-dir", builddir,
+                texfile
+                ]
+        self.run(" ".join(args))     # XXX need quoting!
+        # ... postprocess
+        shutil.copyfile(self.options.style_file,
+                        os.path.join(builddir, self.doc + ".css"))
+        shutil.copyfile(os.path.join(builddir, self.doc + ".html"),
+                        os.path.join(builddir, "index.html"))
+        if max_split_depth != 1:
+            label_file = os.path.join(builddir, "labels.pl")
+            fp = open(label_file)
+            about_node = None
+            target = " = q/about/;\n"
+            x = len(target)
+            while 1:
+                line = fp.readline()
+                if not line:
+                    break
+                if line[-x:] == target:
+                    line = fp.readline()
+                    m = re.search(r"\|(node\d+\.[a-z]+)\|", line)
+                    about_node = m.group(1)
+                    shutil.copyfile(os.path.join(builddir, about_node),
+                                    os.path.join(builddir, "about.html"))
+                    break
+            if not self.options.numeric:
+                pwd = os.getcwd()
+                try:
+                    os.chdir(builddir)
+                    self.run("%s %s *.html" % (PERL_BINARY, NODE2LABEL_SCRIPT))
+                finally:
+                    os.chdir(pwd)
+        # These files need to be cleaned up here since builddir there
+        # can be more than one, so we clean each of them.
+        if self.options.discard_temps:
+            for fn in ("images.tex", "images.log", "images.aux"):
+                safe_unlink(os.path.join(builddir, fn))
+
+    def build_text(self, tempdir=None):
+        if tempdir is None:
+            tempdir = self.doc
+        indexfile = os.path.join(tempdir, "index.html")
+        self.run("%s -nolist -dump %s >%s.txt"
+                 % (LYNX_BINARY, indexfile, self.doc))
+
+    def require_temps(self, binary=None):
+        if not self.latex_runs:
+            self.build_aux(binary=binary)
+
+    def write_l2h_aux_init_file(self):
+        options = self.options
+        fp = open(self.l2h_aux_init_file, "w")
+        d = string_to_perl(os.path.dirname(L2H_INIT_FILE))
+        fp.write("package main;\n"
+                 "push (@INC, '%s');\n"
+                 "$mydir = '%s';\n"
+                 % (d, d))
+        fp.write(open(L2H_INIT_FILE).read())
+        for filename in options.l2h_init_files:
+            fp.write("\n# initialization code incorporated from:\n# ")
+            fp.write(filename)
+            fp.write("\n")
+            fp.write(open(filename).read())
+        fp.write("\n"
+                 "# auxillary init file for latex2html\n"
+                 "# generated by mkhowto\n"
+                 "$NO_AUTO_LINK = 1;\n"
+                 )
+        l2hoption(fp, "ABOUT_FILE", options.about_file)
+        l2hoption(fp, "ICONSERVER", options.icon_server)
+        l2hoption(fp, "IMAGE_TYPE", options.image_type)
+        l2hoption(fp, "ADDRESS", options.address)
+        l2hoption(fp, "MAX_LINK_DEPTH", options.max_link_depth)
+        l2hoption(fp, "MAX_SPLIT_DEPTH", options.max_split_depth)
+        l2hoption(fp, "EXTERNAL_UP_LINK", options.up_link)
+        l2hoption(fp, "EXTERNAL_UP_TITLE", options.up_title)
+        l2hoption(fp, "FAVORITES_ICON", options.favicon)
+        l2hoption(fp, "GLOBAL_MODULE_INDEX", options.global_module_index)
+        l2hoption(fp, "DVIPS_SAFE", options.dvips_safe)
+        fp.write("1;\n")
+        fp.close()
+
+    def cleanup(self):
+        self.__have_temps = 0
+        for pattern in ("%s.aux", "%s.log", "%s.out", "%s.toc", "%s.bkm",
+                        "%s.idx", "%s.ilg", "%s.ind", "%s.pla",
+                        "%s.bbl", "%s.blg",
+                        "mod%s.idx", "mod%s.ind", "mod%s.ilg",
+                        ):
+            safe_unlink(pattern % self.doc)
+        map(safe_unlink, glob.glob(self.doc + "*.syn"))
+        for spec in ("IMG*", "*.pl", "WARNINGS", "index.dat", "modindex.dat"):
+            pattern = os.path.join(self.doc, spec)
+            map(safe_unlink, glob.glob(pattern))
+        if "dvi" not in self.options.formats:
+            safe_unlink(self.doc + ".dvi")
+        if os.path.isdir(self.doc + "-temp-html"):
+            shutil.rmtree(self.doc + "-temp-html", ignore_errors=1)
+        if not self.options.logging:
+            os.unlink(self.log_filename)
+        if not self.options.debugging:
+            os.unlink(self.l2h_aux_init_file)
+
+    def run(self, command):
+        self.message(command)
+        if sys.platform.startswith("win"):
+            rc = os.system(command)
+        else:
+            rc = os.system("(%s) </dev/null >>%s 2>&1"
+                           % (command, self.log_filename))
+        if rc:
+            self.warning(
+                "Session transcript and error messages are in %s."
+                % self.log_filename)
+            result = 1
+            if hasattr(os, "WIFEXITED"):
+                if os.WIFEXITED(rc):
+                    result = os.WEXITSTATUS(rc)
+                    self.warning("Exited with status %s." % result)
+                else:
+                    self.warning("Killed by signal %s." % os.WSTOPSIG(rc))
+            else:
+                self.warning("Return code: %s" % rc)
+            sys.stderr.write("The relevant lines from the transcript are:\n")
+            sys.stderr.write("-" * 72 + "\n")
+            sys.stderr.writelines(get_run_transcript(self.log_filename))
+            sys.exit(result)
+
+    def message(self, msg):
+        msg = "+++ " + msg
+        if not self.options.quiet:
+            print msg
+        self.log(msg + "\n")
+
+    def warning(self, msg):
+        msg = "*** %s\n" % msg
+        sys.stderr.write(msg)
+        self.log(msg)
+
+    def log(self, msg):
+        fp = open(self.log_filename, "a")
+        fp.write(msg)
+        fp.close()
+
+
+def get_run_transcript(filename):
+    """Return lines from the transcript file for the most recent run() call."""
+    fp = open(filename)
+    lines = fp.readlines()
+    fp.close()
+    lines.reverse()
+    L = []
+    for line in lines:
+        L.append(line)
+        if line[:4] == "+++ ":
+            break
+    L.reverse()
+    return L
+
+
+def safe_unlink(path):
+    """Unlink a file without raising an error if it doesn't exist."""
+    try:
+        os.unlink(path)
+    except os.error:
+        pass
+
+
+def split_pathname(path):
+    path = os.path.abspath(path)
+    dirname, basename = os.path.split(path)
+    if basename[-4:] == ".tex":
+        basename = basename[:-4]
+    return dirname, basename
+
+
+_doctype_rx = re.compile(r"\\documentclass(?:\[[^]]*\])?{([a-zA-Z]*)}")
+def get_doctype(path):
+    fp = open(path)
+    doctype = None
+    while 1:
+        line = fp.readline()
+        if not line:
+            break
+        m = _doctype_rx.match(line)
+        if m:
+            doctype = m.group(1)
+            break
+    fp.close()
+    return doctype
+
+
+def main():
+    options = Options()
+    try:
+        args = options.parse(sys.argv[1:])
+    except getopt.error, msg:
+        error(options, msg)
+    if not args:
+        # attempt to locate single .tex file in current directory:
+        args = glob.glob("*.tex")
+        if not args:
+            error(options, "No file to process.")
+        if len(args) > 1:
+            error(options, "Could not deduce which files should be processed.")
+    #
+    # parameters are processed, let's go!
+    #
+    for path in args:
+        Job(options, path).build()
+
+
+def l2hoption(fp, option, value):
+    if value:
+        fp.write('$%s = "%s";\n' % (option, string_to_perl(str(value))))
+
+
+_to_perl = {}
+for c in map(chr, range(1, 256)):
+    _to_perl[c] = c
+_to_perl["@"] = "\\@"
+_to_perl["$"] = "\\$"
+_to_perl['"'] = '\\"'
+
+def string_to_perl(s):
+    return ''.join(map(_to_perl.get, s))
+
+
+def check_for_bibtex(filename):
+    fp = open(filename)
+    pos = fp.read().find(r"\bibdata{")
+    fp.close()
+    return pos >= 0
+
+def uniqify_module_table(filename):
+    lines = open(filename).readlines()
+    if len(lines) > 1:
+        if lines[-1] == lines[-2]:
+            del lines[-1]
+    open(filename, "w").writelines(lines)
+
+
+def new_index(filename, label="genindex"):
+    fp = open(filename, "w")
+    fp.write(r"""\
+\begin{theindex}
+\label{%s}
+\end{theindex}
+""" % label)
+    fp.close()
+
+
+if __name__ == "__main__":
+    main()

Added: sandbox/trunk/pdb/Doc/tools/mkinfo
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/mkinfo	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,65 @@
+#! /bin/sh
+#  -*- Ksh -*-
+
+#  Script to drive the HTML-info conversion process.
+#  Pass in upto three parameters:
+#  - the name of the main tex file
+#  - the name of the output file in texi format (optional)
+#  - the name of the output file in info format (optional)
+#
+#  Written by Fred L. Drake, Jr. <fdrake at acm.org>
+
+EMACS=${EMACS:-emacs}
+MAKEINFO=${MAKEINFO:-makeinfo}
+
+
+# Normalize file name since something called by html2texi.pl seems to
+# screw up with relative path names.
+FILENAME="$1"
+DOCDIR=`dirname "$FILENAME"`
+DOCFILE=`basename "$FILENAME"`
+DOCNAME=`basename "$FILENAME" .tex`
+if [ $# -gt 1 ]; then
+    TEXINAME="$2"
+else
+    TEXINAME="python-$DOCNAME.texi"
+fi
+if [ $# -gt 2 ]; then
+    INFONAME="$3"
+else
+    INFONAME="python-$DOCNAME.info"
+fi
+
+# Now build the real directory names, and locate our support stuff:
+WORKDIR=`pwd`
+cd `dirname $0`
+TOOLSDIR=`pwd`
+cd $DOCDIR
+DOCDIR=`pwd`
+cd $WORKDIR
+
+COMMONDIR="`dirname $DOCDIR`/commontex"
+
+
+run() {
+    # show what we're doing, like make does:
+    echo "$*"
+    "$@" || exit $?
+}
+
+
+# generate the Texinfo file:
+
+run $EMACS -batch -q --no-site-file -l $TOOLSDIR/py2texi.el \
+    --eval "(setq py2texi-dirs '(\"$DOCDIR\" \"$COMMONDIR\" \"../texinputs\"))" \
+    --eval "(setq py2texi-texi-file-name \"$TEXINAME\")" \
+    --eval "(setq py2texi-info-file-name \"$INFONAME\")" \
+    --eval "(py2texi \"$DOCDIR/$DOCFILE\")" \
+    -f kill-emacs
+echo Done
+
+
+# generate the .info files:
+
+run $MAKEINFO --footnote-style end --fill-column 72 \
+	      --paragraph-indent 0 --output=$INFONAME $TEXINAME

Added: sandbox/trunk/pdb/Doc/tools/node2label.pl
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/node2label.pl	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,71 @@
+#! /usr/bin/env perl
+
+# On Cygwin, we actually have to generate a temporary file when doing
+# the inplace edit, or we'll get permission errors.  Not sure who's
+# bug this is, except that it isn't ours.  To deal with this, we
+# generate backups during the edit phase and remove them at the end.
+#
+use English;
+$INPLACE_EDIT = '.bak';
+
+# read the labels, then reverse the mappings
+require "labels.pl";
+
+%nodes = ();
+my $key;
+# sort so that we get a consistent assignment for nodes with multiple labels 
+foreach $label (sort keys %external_labels) {
+  #
+  # If the label can't be used as a filename on non-Unix platforms,
+  # skip it.  Such labels may be used internally within the documentation,
+  # but will never be used for filename generation.
+  #
+  if ($label =~ /^([-.a-zA-Z0-9]+)$/) {
+    $key = $external_labels{$label};
+    $key =~ s|^/||;
+    $nodes{$key} = $label;
+  }
+}
+
+# This adds the "internal" labels added for indexing.  These labels will not
+# be used for file names.
+require "intlabels.pl";
+foreach $label (keys %internal_labels) {
+  $key = $internal_labels{$label};
+  $key =~ s|^/||;
+  if (defined($nodes{$key})) {
+    $nodes{$label} = $nodes{$key};
+  }
+}
+
+# collect labels that have been used
+%newnames = ();
+
+while (<>) {
+  # don't want to do one s/// per line per node
+  # so look for lines with hrefs, then do s/// on nodes present
+  if (/(HREF|href)=[\"\']node\d+\.html[\#\"\']/) {
+    @parts = split(/(HREF|href)\=[\"\']/);
+    shift @parts;
+    for $node (@parts) {
+      $node =~ s/[\#\"\'].*$//g;
+      chomp($node);
+      if (defined($nodes{$node})) {
+	$label = $nodes{$node};
+	if (s/(HREF|href)=([\"\'])$node([\#\"\'])/href=$2$label.html$3/g) {
+	  s/(HREF|href)=([\"\'])$label.html/href=$2$label.html/g;
+	  $newnames{$node} = "$label.html";
+	}
+      }
+    }
+  }
+  print;
+}
+
+foreach $oldname (keys %newnames) {
+  rename($oldname, $newnames{$oldname});
+}
+
+foreach $filename (glob('*.bak')) {
+  unlink($filename);
+}

Added: sandbox/trunk/pdb/Doc/tools/patchlevel.h
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/patchlevel.h	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,40 @@
+
+/* Newfangled version identification scheme.
+
+   This scheme was added in Python 1.5.2b2; before that time, only PATCHLEVEL
+   was available.  To test for presence of the scheme, test for
+   defined(PY_MAJOR_VERSION).
+
+   When the major or minor version changes, the VERSION variable in
+   configure.in must also be changed.
+
+   There is also (independent) API version information in modsupport.h.
+*/
+
+/* Values for PY_RELEASE_LEVEL */
+#define PY_RELEASE_LEVEL_ALPHA	0xA
+#define PY_RELEASE_LEVEL_BETA	0xB
+#define PY_RELEASE_LEVEL_GAMMA	0xC     /* For release candidates */
+#define PY_RELEASE_LEVEL_FINAL	0xF	/* Serial should be 0 here */
+					/* Higher for patch releases */
+
+/* Version parsed out into numeric values */
+#define PY_MAJOR_VERSION	2
+#define PY_MINOR_VERSION	4
+#define PY_MICRO_VERSION	2
+#define PY_RELEASE_LEVEL	PY_RELEASE_LEVEL_ALPHA
+#define PY_RELEASE_SERIAL	0
+
+/* Version as a string */
+#define PY_VERSION		"2.4.3mpdb"
+
+/* Subversion Revision number of this file (not of the repository) */
+#define PY_PATCHLEVEL_REVISION  "$Revision: 1.1 $"
+
+/* Version as a single 4-byte hex number, e.g. 0x010502B2 == 1.5.2b2.
+   Use this for numeric comparisons, e.g. #if PY_VERSION_HEX >= ... */
+#define PY_VERSION_HEX ((PY_MAJOR_VERSION << 24) | \
+			(PY_MINOR_VERSION << 16) | \
+			(PY_MICRO_VERSION <<  8) | \
+			(PY_RELEASE_LEVEL <<  4) | \
+			(PY_RELEASE_SERIAL << 0))

Added: sandbox/trunk/pdb/Doc/tools/py2texi.el
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/py2texi.el	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,951 @@
+;;; py2texi.el -- Conversion of Python LaTeX documentation to Texinfo
+
+;; Copyright (C) 1998, 1999, 2001, 2002 Milan Zamazal
+
+;; Author: Milan Zamazal <pdm at zamazal.org>
+;; Version: $Id: py2texi.el,v 1.1 2006/01/30 11:54:58 rockyb Exp $
+;; Keywords: python
+
+;; COPYRIGHT NOTICE
+;;
+;; This program is free software; you can redistribute it and/or modify it
+;; under the terms of the GNU General Public License as published by the Free
+;; Software Foundation; either version 2, or (at your option) any later
+;; version.
+;;
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+;; or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+;; for more details.
+;;
+;; You can find the GNU General Public License at
+;; http://www.gnu.org/copyleft/gpl.html
+;; or you can write to the Free Software Foundation, Inc., 59 Temple Place,
+;; Suite 330, Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+
+;; This is a Q&D hack for conversion of Python manuals to on-line help format.
+;; I desperately needed usable online documenta for Python, so I wrote this.
+;; The result code is ugly and need not contain complete information from
+;; Python manuals.  I apologize for my ignorance, especially ignorance to
+;; python.sty.  Improvements of this convertor are welcomed.
+
+;; How to use it:
+;; Load this file and apply `M-x py2texi'.  You will be asked for name of a
+;; file to be converted.
+
+;; Where to find it:
+;; New versions of this code might be found at
+;; http://www.zamazal.org/software/python/py2texi/ .
+
+;;; Code:
+
+
+(require 'texinfo)
+(eval-when-compile
+  (require 'cl))
+
+
+(defvar py2texi-python-version "2.2"
+  "What to substitute for the \\version macro.")
+
+(defvar py2texi-python-short-version
+  (progn
+    (string-match "[0-9]+\\.[0-9]+" py2texi-python-version)
+    (match-string 0 py2texi-python-version))
+  "Short version number, usually set by the LaTeX commands.")
+
+(defvar py2texi-texi-file-name nil
+  "If non-nil, that string is used as the name of the Texinfo file.
+Otherwise a generated Texinfo file name is used.")
+
+(defvar py2texi-info-file-name nil
+  "If non-nil, that string is used as the name of the Info file.
+Otherwise a generated Info file name is used.")
+
+(defvar py2texi-stop-on-problems nil
+  "*If non-nil, stop when you encouter soft problem.")
+
+(defconst py2texi-environments
+  '(("abstract" 0 "@quotation" "@end quotation\n")
+    ("center" 0 "" "")
+    ("cfuncdesc" 3
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1 \\2(\\3)\n at findex \\2\n")
+     "@end table\n")
+    ("cmemberdesc" 3
+     "\n at table @code\n at item \\2 \\3\n"
+     "@end table\n")
+    ("classdesc" 2
+     (progn (setq obindex t)
+	    "\n at table @code\n at item \\1(\\2)\n at obindex \\1\n")
+     "@end table\n")
+    ("classdesc*" 1
+     (progn (setq obindex t)
+	    "\n at table @code\n at item \\1\n at obindex \\1\n")
+     "@end table\n")
+    ("comment" 0 "\n at ignore\n" "\n at end ignore\n")
+    ("csimplemacrodesc" 1
+     (progn (setq cindex t)
+	    "\n at table @code\n at item \\1\n at cindex \\1\n")
+     "@end table\n")     
+    ("ctypedesc" 1
+     (progn (setq cindex t)
+	    "\n at table @code\n at item \\1\n at cindex \\1\n")
+     "@end table\n")
+    ("cvardesc" 2
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1 \\2\n at findex \\2\n")
+     "@end table\n")
+    ("datadesc" 1
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1\n at findex \\1\n")
+     "@end table\n")
+    ("datadescni" 1 "\n at table @code\n at item \\1\n" "@end table\n")
+    ("definitions" 0 "@table @dfn" "@end table\n")
+    ("description" 0 "@table @samp" "@end table\n")
+    ("displaymath" 0 "" "")
+    ("document" 0
+     (concat "@defcodeindex mo\n"
+	     "@defcodeindex ob\n"
+	     "@titlepage\n"
+	     (format "@title " title "\n")
+	     (format "@author " author "\n")
+	     "@page\n"
+	     author-address
+	     "@end titlepage\n"
+	     "@node Top, , , (dir)\n")
+     (concat "@indices\n"
+	     "@contents\n"
+	     "@bye\n"))
+    ("enumerate" 0 "@enumerate" "@end enumerate")
+    ("envdesc" 2 (concat "\n at table @code"
+                         "\n at item @backslash{}begin@{\\1@}\\2")
+     "@end table\n")
+    ("excdesc" 1
+     (progn (setq obindex t)
+	    "\n at table @code\n at item \\1\n at obindex \\1\n")
+     "@end table\n")
+    ("excclassdesc" 2
+     (progn (setq obindex t)
+	    "\n at table @code\n at item \\1(\\2)\n at obindex \\1\n")
+     "@end table\n")
+    ("flushleft" 0 "" "")
+    ("fulllineitems" 0 "\n at table @code\n" "@end table\n")
+    ("funcdesc" 2
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1(\\2)\n at findex \\1\n")
+     "@end table\n")
+    ("funcdescni" 2 "\n at table @code\n at item \\1(\\2)\n" "@end table\n")
+    ("itemize" 0 "@itemize @bullet" "@end itemize\n")
+    ("list" 2 "\n at table @code\n" "@end table\n")
+    ("longtableii" 4 (concat "@multitable @columnfractions .5 .5\n"
+			     "@item \\3 @tab \\4\n"
+			     "@item ------- @tab ------ \n")
+     "@end multitable\n")
+    ("longtableiii" 5 (concat "@multitable @columnfractions .33 .33 .33\n"
+			      "@item \\3 @tab \\4 @tab \\5\n"
+			      "@item ------- @tab ------ @tab ------\n")
+     "@end multitable\n")
+    ("macrodesc" 2 (concat "\n at table @code"
+                           "\n at item \\1@{\\2@}")
+     "@end table\n")
+    ("memberdesc" 1
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1\n at findex \\1\n")
+     "@end table\n")
+    ("memberdescni" 1 "\n at table @code\n at item \\1\n" "@end table\n")
+    ("methoddesc" 2
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1(\\2)\n at findex \\1\n")
+     "@end table\n")
+    ("methoddescni" 2 "\n at table @code\n at item \\1(\\2)\n" "@end table\n")
+    ("notice" 0 "@emph{Notice:} " "")
+    ("opcodedesc" 2
+     (progn (setq findex t)
+	    "\n at table @code\n at item \\1 \\2\n at findex \\1\n")
+     "@end table\n")
+    ("productionlist" 0 "\n at table @code\n" "@end table\n")
+    ("quotation" 0 "@quotation" "@end quotation")
+    ("seealso" 0 "See also:\n at table @emph\n" "@end table\n")
+    ("seealso*" 0 "@table @emph\n" "@end table\n")
+    ("sloppypar" 0 "" "")
+    ("small" 0 "" "")
+    ("tableii" 4 (concat "@multitable @columnfractions .5 .5\n"
+			 "@item \\3 @tab \\4\n"
+			 "@item ------- @tab ------ \n")
+     "@end multitable\n")
+    ("tableiii" 5 (concat "@multitable @columnfractions .33 .33 .33\n"
+			 "@item \\3 @tab \\4 @tab \\5\n"
+			 "@item ------- @tab ------ @tab ------\n")
+     "@end multitable\n")
+    ("tableiv" 6 (concat
+		  "@multitable @columnfractions .25 .25 .25 .25\n"
+		  "@item \\3 @tab \\4 @tab \\5 @tab \\6\n"
+		  "@item ------- @tab ------- @tab ------- @tab -------\n")
+     "@end multitable\n")
+    ("tablev" 7 (concat
+		 "@multitable @columnfractions .20 .20 .20 .20 .20\n"
+		 "@item \\3 @tab \\4 @tab \\5 @tab \\6 @tab \\7\n"
+		 "@item ------- @tab ------- @tab ------- @tab ------- @tab -------\n")
+     "@end multitable\n")
+    ("alltt" 0 "@example" "@end example")
+    )
+  "Associative list defining substitutions for environments.
+Each list item is of the form (ENVIRONMENT ARGNUM BEGIN END) where:
+- ENVIRONMENT is LaTeX environment name
+- ARGNUM is number of (required) macro arguments
+- BEGIN is substitution for \begin{ENVIRONMENT}
+- END is substitution for \end{ENVIRONMENT}
+Both BEGIN and END are evaled.  Moreover, you can reference arguments through
+\N regular expression notation in strings of BEGIN.")
+
+(defconst py2texi-commands
+  '(("AA" 0 "@AA{}")
+    ("aa" 0 "@aa{}")
+    ("ABC" 0 "ABC")
+    ("appendix" 0 (progn (setq appendix t) ""))
+    ("ASCII" 0 "ASCII")
+    ("author" 1 (progn (setq author (match-string 1 string)) ""))
+    ("authoraddress" 1
+     (progn (setq author-address (match-string 1 string)) ""))
+    ("b" 1 "@w{\\1}")
+    ("backslash" 0 "@backslash{}")
+    ("bf" 0 "@destroy")
+    ("bifuncindex" 1 (progn (setq findex t) "@findex{\\1}"))
+    ("C" 0 "C")
+    ("c" 0 "@,")
+    ("catcode" 0 "")
+    ("cdata" 1 "@code{\\1}")
+    ("centerline" 1 "@center \\1")
+    ("cfuncline" 3 "@itemx \\1 \\2(\\3)\n at findex \\2")
+    ("cfunction" 1 "@code{\\1}")
+    ("chapter" 1 (format "@node \\1\n@%s \\1\n"
+			 (if appendix "appendix" "chapter")))
+    ("chapter*" 1 "@node \\1\n at unnumbered \\1\n")
+    ("character" 1 "@samp{\\1}")
+    ("citetitle" 1 "@ref{Top,,,\\1}")
+    ("class" 1 "@code{\\1}")
+    ("cmemberline" 3 "@itemx \\2 \\3\n")
+    ("code" 1 "@code{\\1}")
+    ("command" 1 "@command{\\1}")
+    ("constant" 1 "@code{\\1}")
+    ("copyright" 1 "@copyright{}")
+    ("Cpp" 0 "C++")
+    ("csimplemacro" 1 "@code{\\1}")
+    ("ctype" 1 "@code{\\1}")
+    ("dataline" 1 (progn (setq findex t) "@item \\1\n at findex \\1\n"))
+    ("date" 1 "\\1")
+    ("declaremodule" 2 (progn (setq cindex t) "@label{\\2}@cindex{\\2}"))
+    ("deprecated" 2 "@emph{This is deprecated in Python \\1.  \\2}\n\n")
+    ("dfn" 1 "@dfn{\\1}")
+    ("documentclass" 1 py2texi-magic)
+    ("e" 0 "@backslash{}")
+    ("else" 0 (concat "@end ifinfo\n@" (setq last-if "iftex")))
+    ("env" 1 "@code{\\1}")
+    ("EOF" 0 "@code{EOF}")
+    ("email" 1 "@email{\\1}")
+    ("emph" 1 "@emph{\\1}")
+    ("envvar" 1 "@env{\\1}")
+    ("exception" 1 "@code{\\1}")
+    ("exindex" 1 (progn (setq obindex t) "@obindex{\\1}"))
+    ("fi" 0 (concat "@end " last-if))
+    ("file" 1 "@file{\\1}")
+    ("filenq" 1 "@file{\\1}")
+    ("filevar" 1 "@file{@var{\\1}}")
+    ("footnote" 1 "@footnote{\\1}")
+    ("frac" 0 "")
+    ("funcline" 2 (progn (setq findex t) "@item \\1 \\2\n at findex \\1"))
+    ("funclineni" 2 "@item \\1 \\2")
+    ("function" 1 "@code{\\1}")
+    ("grammartoken" 1 "@code{\\1}")
+    ("guilabel" 1 "@strong{\\1}")
+    ("hline" 0 "")
+    ("ifhtml" 0 (concat "@" (setq last-if "ifinfo")))
+    ("iftexi" 0 (concat "@" (setq last-if "ifinfo")))
+    ("index" 1 (progn (setq cindex t) "@cindex{\\1}"))
+    ("indexii" 2 (progn (setq cindex t) "@cindex{\\1 \\2}"))
+    ("indexiii" 3 (progn (setq cindex t) "@cindex{\\1 \\2 \\3}"))
+    ("indexiv" 3 (progn (setq cindex t) "@cindex{\\1 \\2 \\3 \\4}"))
+    ("infinity" 0 "@emph{infinity}")
+    ("it" 0 "@destroy")
+    ("kbd" 1 "@key{\\1}")
+    ("keyword" 1 "@code{\\1}")
+    ("kwindex" 1 (progn (setq cindex t) "@cindex{\\1}"))
+    ("label" 1 "@label{\\1}")
+    ("Large" 0 "")
+    ("LaTeX" 0 "La at TeX{}")
+    ("large" 0 "")
+    ("ldots" 0 "@dots{}")
+    ("leftline" 1 "\\1")
+    ("leq" 0 "<=")
+    ("lineii" 2 "@item \\1 @tab \\2")
+    ("lineiii" 3 "@item \\1 @tab \\2 @tab \\3")
+    ("lineiv" 4 "@item \\1 @tab \\2 @tab \\3 @tab \\4")
+    ("linev" 5 "@item \\1 @tab \\2 @tab \\3 @tab \\4 @tab \\5")
+    ("localmoduletable" 0 "")
+    ("longprogramopt" 1 "@option{--\\1}")
+    ("macro" 1 "@code{@backslash{}\\1}")
+    ("mailheader" 1 "@code{\\1}")
+    ("makeindex" 0 "")
+    ("makemodindex" 0 "")
+    ("maketitle" 0 (concat "@top " title "\n"))
+    ("makevar" 1 "@code{\\1}")
+    ("manpage" 2 "@samp{\\1(\\2)}")
+    ("mbox" 1 "@w{\\1}")
+    ("member" 1 "@code{\\1}")
+    ("memberline" 1 "@item \\1\n at findex \\1\n")
+    ("menuselection" 1 "@samp{\\1}")
+    ("method" 1 "@code{\\1}")
+    ("methodline" 2 (progn (setq moindex t) "@item \\1(\\2)\n at moindex \\1\n"))
+    ("methodlineni" 2 "@item \\1(\\2)\n")
+    ("mimetype" 1 "@samp{\\1}")
+    ("module" 1 "@samp{\\1}")
+    ("moduleauthor" 2 "")
+    ("modulesynopsis" 1 "\\1")
+    ("moreargs" 0 "@dots{}")
+    ("n" 0 "@backslash{}n")
+    ("newcommand" 2 "")
+    ("newsgroup" 1 "@samp{\\1}")
+    ("nodename" 1
+     (save-excursion
+       (save-match-data
+	 (re-search-backward "^@node "))
+       (delete-region (point) (save-excursion (end-of-line) (point)))
+       (insert "@node " (match-string 1 string))
+       ""))
+    ("noindent" 0 "@noindent ")
+    ("note" 1 "@emph{Note:} \\1")
+    ("NULL" 0 "@code{NULL}")
+    ("obindex" 1 (progn (setq obindex t) "@obindex{\\1}"))
+    ("opindex" 1 (progn (setq cindex t) "@cindex{\\1}"))
+    ("option" 1 "@option{\\1}")
+    ("optional" 1 "[\\1]")
+    ("pep" 1 (progn (setq cindex t) "PEP@ \\1 at cindex PEP \\1\n"))
+    ("pi" 0 "pi")
+    ("platform" 1 "")
+    ("plusminus" 0 "+-")
+    ("POSIX" 0 "POSIX")
+    ("production" 2 "@item \\1 \\2")
+    ("productioncont" 1 "@item @w{} \\1")
+    ("program" 1 "@command{\\1}")
+    ("programopt" 1 "@option{\\1}")
+    ("protect" 0 "")
+    ("pytype" 1 "@code{\\1}")
+    ("ref" 1 "@ref{\\1}")
+    ("refbimodindex" 1 (progn (setq moindex t) "@moindex{\\1}"))
+    ("refmodindex" 1 (progn (setq moindex t) "@moindex{\\1}"))
+    ("refmodule" 1 "@samp{\\1}")
+    ("refstmodindex" 1 (progn (setq moindex t) "@moindex{\\1}"))
+    ("regexp" 1 "\"\\1\"")
+    ("release" 1
+     (progn (setq py2texi-python-version (match-string 1 string)) ""))
+    ("renewcommand" 2 "")
+    ("rfc" 1 (progn (setq cindex t) "RFC@ \\1 at cindex RFC \\1\n"))
+    ("rm" 0 "@destroy")
+    ("samp" 1 "@samp{\\1}")
+    ("section" 1 (let ((str (match-string 1 string)))
+		   (save-match-data
+		     (if (string-match "\\(.*\\)[ \t\n]*---[ \t\n]*\\(.*\\)"
+				       str)
+			 (format
+			  "@node %s\n at section %s\n"
+			  (py2texi-backslash-quote (match-string 1 str))
+			  (py2texi-backslash-quote (match-string 2 str)))
+		       "@node \\1\n at section \\1\n"))))
+    ("sectionauthor" 2 "")
+    ("seelink" 3 "\n at table @url\n at item @strong{\\1}\n(\\2)\n\\3\n at end table\n")
+    ("seemodule" 2 "@ref{\\1} \\2")
+    ("seepep" 3 "\n at table @strong\n at item PEP\\1 \\2\n\\3\n at end table\n")
+    ("seerfc" 3 "\n at table @strong\n at item RFC\\1 \\2\n\\3\n at end table\n")
+    ("seetext" 1 "\\1")
+    ("seetitle" 1 "@cite{\\1}")
+    ("seeurl" 2 "\n at table @url\n at item \\1\n\\2\n at end table\n")
+    ("setindexsubitem" 1 (progn (setq cindex t) "@cindex \\1"))
+    ("setreleaseinfo" 1 (progn (setq py2texi-releaseinfo "")))
+    ("setshortversion" 1
+     (progn (setq py2texi-python-short-version (match-string 1 string)) ""))
+    ("shortversion" 0 py2texi-python-short-version)
+    ("sqrt" 0 "")
+    ("stindex" 1 (progn (setq cindex t) "@cindex{\\1}"))
+    ("stmodindex" 1 (progn (setq moindex t) "@moindex{\\1}"))
+    ("strong" 1 "@strong{\\1}")
+    ("sub" 0 "/")
+    ("subsection" 1 "@node \\1\n at subsection \\1\n")
+    ("subsubsection" 1 "@node \\1\n at subsubsection \\1\n")
+    ("sum" 0 "")
+    ("tableofcontents" 0 "")
+    ("term" 1 "@item \\1")
+    ("TeX" 0 "@TeX{}")
+    ("textasciitilde" 0 "~")
+    ("textasciicircum" 0 "^")
+    ("textbackslash" 0 "@backslash{}")
+    ("textbar" 0 "|")
+    ; Some common versions of Texinfo don't support @euro yet:
+    ; ("texteuro" 0 "@euro{}")
+    ; Unfortunately, this alternate spelling doesn't actually apply to
+    ; the usage found in Python Tutorial, which actually requires a
+    ; Euro symbol to make sense, so this is commented out as well.
+    ; ("texteuro" 0 "Euro ")
+    ("textgreater" 0 ">")
+    ("textit" 1 "@i{\\1}")
+    ("textless" 0 "<")
+    ("textrm" 1 "\\1")
+    ("texttt" 1 "@code{\\1}")
+    ("textunderscore" 0 "_")
+    ("title" 1 (progn (setq title (match-string 1 string)) "@settitle \\1"))
+    ("today" 0 "@today{}")
+    ("token" 1 "@code{\\1}")
+    ("tt" 0 "@destroy")
+    ("ttindex" 1 (progn (setq cindex t) "@cindex{\\1}"))
+    ("u" 0 "@backslash{}u")
+    ("ulink" 2 "\\1")
+    ("UNIX" 0 "UNIX")
+    ("unspecified" 0 "@dots{}")
+    ("url" 1 "@url{\\1}")
+    ("usepackage" 1 "")
+    ("var" 1 "@var{\\1}")
+    ("verbatiminput" 1 "@code{\\1}")
+    ("version" 0 py2texi-python-version)
+    ("versionadded" 1 "@emph{Added in Python version \\1}")
+    ("versionchanged" 1 "@emph{Changed in Python version \\1}")
+    ("vskip" 1 "")
+    ("vspace" 1 "")
+    ("warning" 1 "@emph{\\1}")
+    ("withsubitem" 2 "\\2")
+    ("XXX" 1 "@strong{\\1}"))
+  "Associative list of command substitutions.
+Each list item is of the form (COMMAND ARGNUM SUBSTITUTION) where:
+- COMMAND is LaTeX command name
+- ARGNUM is number of (required) command arguments
+- SUBSTITUTION substitution for the command.  It is evaled and you can
+  reference command arguments through the \\N regexp notation in strings.")
+
+(defvar py2texi-magic "@documentclass\n"
+  "\"Magic\" string for auxiliary insertion at the beginning of document.")
+
+(defvar py2texi-dirs '("./" "../texinputs/")
+  "Where to search LaTeX input files.")
+
+(defvar py2texi-buffer "*py2texi*"
+  "The name of a buffer where Texinfo is generated.")
+
+(defconst py2texi-xemacs (string-match "^XEmacs" (emacs-version))
+  "Running under XEmacs?")
+
+
+(defmacro py2texi-search (regexp &rest body)
+  `(progn
+     (goto-char (point-min))
+     (while (re-search-forward ,regexp nil t)
+       , at body)))
+
+(defmacro py2texi-search-safe (regexp &rest body)
+  `(py2texi-search ,regexp
+    (unless (py2texi-protected)
+      , at body)))
+
+
+(defun py2texi-message (message)
+  "Report message and stop if `py2texi-stop-on-problems' is non-nil."
+  (if py2texi-stop-on-problems
+      (error message)
+    (message message)))
+
+
+(defun py2texi-backslash-quote (string)
+  "Double backslahes in STRING."
+  (let ((i 0))
+    (save-match-data
+      (while (setq i (string-match "\\\\" string i))
+	(setq string (replace-match "\\\\\\\\" t nil string))
+	(setq i (+ i 2))))
+    string))
+
+
+(defun py2texi (file)
+  "Convert Python LaTeX documentation FILE to Texinfo."
+  (interactive "fFile to convert: ")
+  (switch-to-buffer (get-buffer-create py2texi-buffer))
+  (erase-buffer)
+  (insert-file file)
+  (let ((case-fold-search nil)
+	(title "")
+	(author "")
+	(author-address "")
+	(appendix nil)
+	(findex nil)
+	(obindex nil)
+	(cindex nil)
+	(moindex nil)
+	last-if)
+    (py2texi-process-verbatims)
+    (py2texi-process-comments)
+    (py2texi-process-includes)
+    (py2texi-process-funnyas)
+    (py2texi-process-environments)
+    (py2texi-process-commands)
+    (py2texi-fix-indentation)
+    (py2texi-fix-nodes)
+    (py2texi-fix-references)
+    (py2texi-fix-indices)
+    (py2texi-process-simple-commands)
+    (py2texi-fix-fonts)
+    (py2texi-fix-braces)
+    (py2texi-fix-backslashes)
+    (py2texi-destroy-empties)
+    (py2texi-fix-newlines)
+    (py2texi-adjust-level))
+  (let* ((texi-file-name (or py2texi-texi-file-name
+			     (py2texi-texi-file-name file)))
+	 (info-file-name (or py2texi-info-file-name
+			     (py2texi-info-file-name texi-file-name))))
+    (goto-char (point-min))
+    (when (looking-at py2texi-magic)
+      (delete-region (point) (progn (beginning-of-line 2) (point)))
+      (insert "\\input texinfo @c -*-texinfo-*-\n")
+      (insert "@setfilename " info-file-name))
+    (when (re-search-forward "@chapter" nil t)
+      (texinfo-all-menus-update t))
+    (goto-char (point-min))
+    (write-file texi-file-name)
+    (message (format "You can apply `makeinfo %s' now." texi-file-name))))
+
+
+(defun py2texi-texi-file-name (filename)
+  "Generate name of Texinfo file from original file name FILENAME."
+  (concat filename
+	  (if (string-match "\\.tex$" filename) "i" ".texi")))
+
+
+(defun py2texi-info-file-name (filename)
+  "Generate name of info file from original file name FILENAME."
+  (setq filename (expand-file-name filename))
+  (let ((directory (file-name-directory filename))
+	(basename (file-name-nondirectory filename)))
+    (concat directory "python-"
+	    (substring basename 0 (- (length basename) 4)) "info")))
+
+
+(defun py2texi-process-verbatims ()
+  "Process and protect verbatim environments."
+  (let (delimiter
+	beg
+	end)
+    (py2texi-search-safe "\\\\begin{\\(verbatim\\|displaymath\\)}"
+      (replace-match "@example")
+      (setq beg (copy-marker (point) nil))
+      (re-search-forward "\\\\end{\\(verbatim\\|displaymath\\)}")
+      (setq end (copy-marker (match-beginning 0) nil))
+      (replace-match "@end example")
+      (py2texi-texinfo-escape beg end)
+      (put-text-property (- beg (length "@example"))
+			 (+ end (length "@end example"))
+			 'py2texi-protected t))
+    (py2texi-search-safe "\\\\verb\\([^a-z]\\)"
+      (setq delimiter (match-string 1))
+      (replace-match "@code{")
+      (setq beg (copy-marker (point) nil))
+      (re-search-forward (regexp-quote delimiter))
+      (setq end (copy-marker (match-beginning 0) nil))
+      (replace-match "}")
+      (put-text-property (- beg (length "@code{")) (+ end (length "}"))
+			 'py2texi-protected t)
+      (py2texi-texinfo-escape beg end))))
+
+
+(defun py2texi-process-comments ()
+  "Remove comments."
+  (let (point)
+    (py2texi-search-safe "%"
+      (setq point (point))
+      (when (save-excursion
+	      (re-search-backward "\\(^\\|[^\\]\\(\\\\\\\\\\)*\\)%\\=" nil t))
+	(delete-region (1- point)
+		       (save-excursion (beginning-of-line 2) (point)))))))
+
+
+(defun py2texi-process-includes ()
+  "Include LaTeX input files.
+Do not include .ind files."
+  (let ((path (file-name-directory file))
+	filename
+	dirs
+	includefile)
+    (py2texi-search-safe "\\\\input{\\([^}]+\\)}"
+      (setq filename (match-string 1))
+      (unless (save-match-data (string-match "\\.tex$" filename))
+	(setq filename (concat filename ".tex")))
+      (setq includefile (save-match-data
+			  (string-match "\\.ind\\.tex$" filename)))
+      (setq dirs py2texi-dirs)
+      (while (and (not includefile) dirs)
+	(setq includefile
+              (concat (file-name-as-directory (car dirs)) filename))
+        (if (not (file-name-absolute-p includefile))
+            (setq includefile
+                  (concat (file-name-as-directory path) includefile)))
+	(unless (file-exists-p includefile)
+          (setq includefile nil)
+	  (setq dirs (cdr dirs))))
+      (if includefile
+	  (save-restriction
+	    (narrow-to-region (match-beginning 0) (match-end 0))
+	    (delete-region (point-min) (point-max))
+	    (when (stringp includefile)
+	      (insert-file-contents includefile)
+	      (goto-char (point-min))
+	      (insert "\n")
+	      (py2texi-process-verbatims)
+	      (py2texi-process-comments)
+	      (py2texi-process-includes)))
+	(replace-match (format "\\\\emph{Included file %s}" filename))
+	(py2texi-message (format "Input file %s not found" filename))))))
+
+
+(defun py2texi-process-funnyas ()
+  "Convert @s."
+  (py2texi-search-safe "@"
+    (replace-match "@@")))
+
+
+(defun py2texi-process-environments ()
+  "Process LaTeX environments."
+  (let ((stack ())
+	kind
+	environment
+	parameter
+	arguments
+	n
+	string
+	description)
+    (py2texi-search-safe (concat "\\\\\\(begin\\|end\\|item\\)"
+				 "\\({\\([^}]*\\)}\\|[[]\\([^]]*\\)[]]\\|\\)")
+      (setq kind (match-string 1)
+	    environment (match-string 3)
+	    parameter (match-string 4))
+      (replace-match "")
+      (cond
+       ((string= kind "begin")
+	(setq description (assoc environment py2texi-environments))
+	(if description
+	    (progn
+	      (setq n (cadr description))
+	      (setq description (cddr description))
+	      (setq string (py2texi-tex-arguments n))
+	      (string-match (py2texi-regexp n) string)
+				      ; incorrect but sufficient
+	      (insert (replace-match (eval (car description))
+				     t nil string))
+	      (setq stack (cons (cadr description) stack)))
+	  (py2texi-message (format "Unknown environment: %s" environment))
+	  (setq stack (cons "" stack))))
+       ((string= kind "end")
+	(insert (eval (car stack)))
+	(setq stack (cdr stack)))
+       ((string= kind "item")
+	(insert "\n at item " (or parameter "") "\n"))))
+    (when stack
+      (py2texi-message (format "Unclosed environment: %s" (car stack))))))
+
+
+(defun py2texi-process-commands ()
+  "Process LaTeX commands."
+  (let (done
+	command
+	command-info
+	string
+	n)
+    (while (not done)
+      (setq done t)
+      (py2texi-search-safe "\\\\\\([a-zA-Z*]+\\)\\(\\[[^]]*\\]\\)?"
+	(setq command (match-string 1))
+	(setq command-info (assoc command py2texi-commands))
+	(if command-info
+	    (progn
+	      (setq done nil)
+	      (replace-match "")
+	      (setq command-info (cdr command-info))
+	      (setq n (car command-info))
+	      (setq string (py2texi-tex-arguments n))
+	      (string-match (py2texi-regexp n) string)
+				      ; incorrect but sufficient
+	      (insert (replace-match (eval (cadr command-info))
+				     t nil string)))
+	  (py2texi-message (format "Unknown command: %s (not processed)"
+				   command)))))))
+
+
+(defun py2texi-argument-pattern (count)
+  (let ((filler "\\(?:[^{}]\\|\\\\{\\|\\\\}\\)*"))
+    (if (<= count 0)
+	filler
+      (concat filler "\\(?:{"
+	      (py2texi-argument-pattern (1- count))
+	      "}" filler "\\)*" filler))))
+(defconst py2texi-tex-argument
+  (concat
+   "{\\("
+   (py2texi-argument-pattern 10)	;really at least 10!
+   "\\)}[ \t%@c\n]*")
+  "Regexp describing LaTeX command argument including argument separators.")
+
+
+(defun py2texi-regexp (n)
+  "Make regexp matching N LaTeX command arguments."
+  (if (= n 0)
+      ""
+    (let ((regexp "^[^{]*"))
+      (while (> n 0)
+	(setq regexp (concat regexp py2texi-tex-argument))
+	(setq n (1- n)))
+      regexp)))
+
+
+(defun py2texi-tex-arguments (n)
+  "Remove N LaTeX command arguments and return them as a string."
+  (let ((point (point))
+	(i 0)
+	result
+	match)
+    (if (= n 0)
+	(progn
+	  (when (re-search-forward "\\=\\({}\\| *\\)" nil t)
+	    (replace-match ""))
+	  "")
+      (while (> n 0)
+	(unless (re-search-forward
+		 "\\(\\=\\|[^\\\\]\\)\\(\\\\\\\\\\)*\\([{}]\\)" nil t)
+	  (debug))
+	(if (string= (match-string 3) "{")
+	    (setq i (1+ i))
+	  (setq i (1- i))
+	  (when (<= i 0)
+	    (setq n (1- n)))))
+      (setq result (buffer-substring-no-properties point (point)))
+      (while (string-match "\n[ \t]*" result)
+	(setq result (replace-match " " t nil result)))
+      (delete-region point (point))
+      result)))
+
+
+(defun py2texi-process-simple-commands ()
+  "Replace single character LaTeX commands."
+  (let (char)
+    (py2texi-search-safe "\\\\\\([^a-z]\\)"
+      (setq char (match-string 1))
+      (replace-match (format "%s%s"
+			     (if (or (string= char "{")
+				     (string= char "}")
+				     (string= char " "))
+				 "@"
+			       "")
+			     (if (string= char "\\")
+				 "\\\\"
+			       char))))))
+
+
+(defun py2texi-fix-indentation ()
+  "Remove white space at the beginning of lines."
+  (py2texi-search-safe "^[ \t]+"
+    (replace-match "")))
+
+
+(defun py2texi-fix-nodes ()
+  "Remove unwanted characters from nodes and make nodes unique."
+  (let ((nodes (make-hash-table :test 'equal))
+	id
+	counter
+	string
+	label
+	index)
+    (py2texi-search "^@node +\\(.*\\)$"
+      (setq string (match-string 1))
+      (if py2texi-xemacs
+	  (replace-match "@node " t)
+	(replace-match "" t nil nil 1))
+      (while (string-match "@label{[^}]*}" string)
+	(setq label (match-string 0 string))
+	(setq string (replace-match "" t nil string)))
+      (while (string-match "@..?index{[^}]*}" string)
+	(setq index (match-string 0 string))
+	(setq string (replace-match "" t nil string)))
+      (while (string-match "@[a-zA-Z]+\\|[{}():]\\|``\\|''" string)
+	(setq string (replace-match "" t nil string)))
+      (while (string-match " -- " string)
+	(setq string (replace-match " - " t nil string)))
+      (while (string-match "\\." string)
+	(setq string (replace-match "" t nil string)))
+      (when (string-match " +$" string)
+	(setq string (replace-match "" t nil string)))
+      (when (string-match "^\\(Built-in\\|Standard\\) Module \\|The " string)
+	(setq string (replace-match "" t nil string)))
+      (string-match "^[^,]+" string)
+      (setq id (match-string 0 string))
+      (setq counter (gethash id nodes))
+      (if counter
+	  (progn
+	    (setq counter (1+ counter))
+	    (setq string (replace-match (format "\\& %d" counter)
+					t nil string)))
+	(setq counter 1))
+      (setf (gethash id nodes) counter)
+      (insert string)
+      (beginning-of-line 3)
+      (when label
+	(insert label "\n"))
+      (when index
+	(insert index "\n")))))
+
+
+(defun py2texi-fix-references ()
+  "Process labels and make references to point to appropriate nodes."
+  (let ((labels ())
+	node)
+    (py2texi-search-safe "@label{\\([^}]*\\)}"
+      (setq node (save-excursion
+		   (save-match-data
+		     (and (re-search-backward "@node +\\([^,\n]+\\)" nil t)
+			  (match-string 1)))))
+      (when node
+	(setq labels (cons (cons (match-string 1) node) labels)))
+      (replace-match ""))
+    (py2texi-search-safe "@ref{\\([^}]*\\)}"
+      (setq node (assoc (match-string 1) labels))
+      (replace-match "")
+      (when node
+	(insert (format "@ref{%s}" (cdr node)))))))
+
+
+(defun py2texi-fix-indices ()
+  "Remove unwanted characters from @*index commands and create final indices."
+  (py2texi-search-safe "@..?index\\>[^\n]*\\(\\)\n"
+    (replace-match "" t nil nil 1))
+  (py2texi-search-safe "@..?index\\>[^\n]*\\(\\)"
+    (replace-match "\n" t nil nil 1))
+  (py2texi-search-safe "@..?index\\({\\)\\([^}]+\\)\\(}+\\)"
+    (replace-match " " t nil nil 1)
+    (replace-match "" t nil nil 3)
+    (let ((string (match-string 2)))
+      (save-match-data
+	(while (string-match "@[a-z]+{" string)
+	  (setq string (replace-match "" nil nil string)))
+	(while (string-match "{" string)
+	  (setq string (replace-match "" nil nil string))))
+      (replace-match string t t nil 2)))
+  (py2texi-search-safe "@..?index\\>.*\\([{}]\\|@[a-z]*\\)"
+    (replace-match "" t nil nil 1)
+    (goto-char (match-beginning 0)))
+  (py2texi-search-safe "[^\n]\\(\\)@..?index\\>"
+    (replace-match "\n" t nil nil 1))
+  (goto-char (point-max))
+  (re-search-backward "@indices")
+  (replace-match "")
+  (insert (if moindex
+	      (concat "@node Module Index\n"
+		      "@unnumbered Module Index\n"
+		      "@printindex mo\n")
+	    "")
+	  (if obindex
+	      (concat "@node Class-Exception-Object Index\n"
+		      "@unnumbered Class, Exception, and Object Index\n"
+		      "@printindex ob\n")
+	    "")
+	  (if findex
+	      (concat "@node Function-Method-Variable Index\n"
+		      "@unnumbered Function, Method, and Variable Index\n"
+		      "@printindex fn\n")
+	    "")
+	  (if cindex
+	      (concat "@node Miscellaneous Index\n"
+		      "@unnumbered Miscellaneous Index\n"
+		      "@printindex cp\n")
+	    "")))
+
+
+(defun py2texi-fix-backslashes ()
+  "Make backslashes from auxiliary commands."
+  (py2texi-search-safe "@backslash{}"
+    (replace-match "\\\\")))
+
+
+(defun py2texi-fix-fonts ()
+  "Remove garbage after unstructured font commands."
+  (let (string)
+    (py2texi-search-safe "@destroy"
+      (replace-match "")
+      (when (eq (preceding-char) ?{)
+	(forward-char -1)
+	(setq string (py2texi-tex-arguments 1))
+	(insert (substring string 1 (1- (length string))))))))
+
+
+(defun py2texi-fix-braces ()
+  "Escape braces for Texinfo."
+  (let (string)
+    (py2texi-search "{"
+       (unless (or (py2texi-protected)
+		   (save-excursion
+		     (re-search-backward
+		      "@\\([a-zA-Z]*\\|multitable.*\\){\\=" nil t)))
+	 (forward-char -1)
+	 (setq string (py2texi-tex-arguments 1))
+	 (insert "@" (substring string 0 (1- (length string))) "@}")))))
+
+
+(defun py2texi-fix-newlines ()
+  "Remove extra newlines."
+  (py2texi-search "\n\n\n+"
+    (replace-match "\n\n"))
+  (py2texi-search-safe "@item.*\n\n"
+    (delete-backward-char 1))
+  (py2texi-search "@end example"
+    (unless (looking-at "\n\n")
+      (insert "\n"))))
+
+
+(defun py2texi-destroy-empties ()
+  "Remove all comments.
+This avoids some makeinfo errors."
+  (py2texi-search "@c\\>"
+    (unless (eq (py2texi-protected) t)
+      (delete-region (- (point) 2) (save-excursion (end-of-line) (point)))
+      (cond
+       ((looking-at "\n\n")
+	(delete-char 1))
+       ((save-excursion (re-search-backward "^[ \t]*\\=" nil t))
+	(delete-region (save-excursion (beginning-of-line) (point))
+		       (1+ (point))))))))
+
+
+(defun py2texi-adjust-level ()
+  "Increase heading level to @chapter, if needed.
+This is only needed for distutils, so it has a very simple form only."
+  (goto-char (point-min))
+  (unless (re-search-forward "@chapter\\>" nil t)
+    (py2texi-search-safe "@section\\>"
+      (replace-match "@chapter" t))
+    (py2texi-search-safe "@\\(sub\\)\\(sub\\)?section\\>"
+      (replace-match "" nil nil nil 1))))
+
+
+(defun py2texi-texinfo-escape (beg end)
+  "Escape Texinfo special characters in region."
+  (save-excursion
+    (goto-char beg)
+    (while (re-search-forward "[@{}]" end t)
+      (replace-match "@\\&"))))
+
+
+(defun py2texi-protected ()
+  "Return protection status of the point before current point."
+  (get-text-property (1- (point)) 'py2texi-protected))
+
+
+;;; Announce
+
+(provide 'py2texi)
+
+
+;;; py2texi.el ends here

Added: sandbox/trunk/pdb/Doc/tools/toc2bkm.py
==============================================================================
--- (empty file)
+++ sandbox/trunk/pdb/Doc/tools/toc2bkm.py	Wed Jul  5 14:19:15 2006
@@ -0,0 +1,143 @@
+#! /usr/bin/env python
+
+"""Convert a LaTeX .toc file to some PDFTeX magic to create that neat outline.
+
+The output file has an extension of '.bkm' instead of '.out', since hyperref
+already uses that extension.
+"""
+
+import getopt
+import os
+import re
+import string
+import sys
+
+
+# Ench item in an entry is a tuple of:
+#
+#   Section #,  Title String,  Page #,  List of Sub-entries
+#
+# The return value of parse_toc() is such a tuple.
+
+cline_re = r"""^
+\\contentsline\ \{([a-z]*)}             # type of section in $1
+\{(?:\\numberline\ \{([0-9.A-Z]+)})?     # section number
+(.*)}                                   # title string
+\{(\d+)}$"""                            # page number
+
+cline_rx = re.compile(cline_re, re.VERBOSE)
+
+OUTER_TO_INNER = -1
+
+_transition_map = {
+    ('chapter', 'section'): OUTER_TO_INNER,
+    ('section', 'subsection'): OUTER_TO_INNER,
+    ('subsection', 'subsubsection'): OUTER_TO_INNER,
+    ('subsubsection', 'subsection'): 1,
+    ('subsection', 'section'): 1,
+    ('section', 'chapter'): 1,
+    ('subsection', 'chapter'): 2,
+    ('subsubsection', 'section'): 2,
+    ('subsubsection', 'chapter'): 3,
+    }
+
+INCLUDED_LEVELS = ("chapter", "section", "subsection", "subsubsection")
+
+
+def parse_toc(fp, bigpart=None):
+    toc = top = []
+    stack = [toc]
+    level = bigpart or 'chapter'
+    lineno = 0
+    while 1:
+        line = fp.readline()
+        if not line:
+            break
+        lineno = lineno + 1
+        m = cline_rx.match(line)
+        if m:
+            stype, snum, title, pageno = m.group(1, 2, 3, 4)
+            title = clean_title(title)
+            entry = (stype, snum, title, int(pageno), [])
+            if stype == level:
+                toc.append(entry)
+            else:
+                if stype not in INCLUDED_LEVELS:
+                    # we don't want paragraphs & subparagraphs
+                    continue
+                direction = _transition_map[(level, stype)]
+                if direction == OUTER_TO_INNER:
+                    toc = toc[-1][-1]
+                    stack.insert(0, toc)
+                    toc.append(entry)
+                else:
+                    for i in range(direction):
+                        del stack[0]
+                        toc = stack[0]
+                    toc.append(entry)
+                level = stype
+        else:
+            sys.stderr.write("l.%s: " + line)
+    return top
+
+
+hackscore_rx = re.compile(r"\\hackscore\s*{[^}]*}")
+raisebox_rx = re.compile(r"\\raisebox\s*{[^}]*}")
+title_rx = re.compile(r"\\([a-zA-Z])+\s+")
+title_trans = string.maketrans("", "")
+
+def clean_title(title):
+    title = raisebox_rx.sub("", title)
+    title = hackscore_rx.sub(r"\\_", title)
+    pos = 0
+    while 1:
+        m = title_rx.search(title, pos)
+        if m:
+            start = m.start()
+            if title[start:start+15] != "\\textunderscore":
+                title = title[:start] + title[m.end():]
+            pos = start + 1
+        else:
+            break
+    title = title.translate(title_trans, "{}")
+    return title
+
+
+def write_toc(toc, fp):
+    for entry in toc:
+        write_toc_entry(entry, fp, 0)
+
+def write_toc_entry(entry, fp, layer):
+    stype, snum, title, pageno, toc = entry
+    s = "\\pdfoutline goto name{page%03d}" % pageno
+    if toc:
+        s = "%s count -%d" % (s, len(toc))
+    if snum:
+        title = "%s %s" % (snum, title)
+    s = "%s {%s}\n" % (s, title)
+    fp.write(s)
+    for entry in toc:
+        write_toc_entry(entry, fp, layer + 1)
+
+
+def process(ifn, ofn, bigpart=None):
+    toc = parse_toc(open(ifn), bigpart)
+    write_toc(toc, open(ofn, "w"))
+
+
+def main():
+    bigpart = None
+    opts, args = getopt.getopt(sys.argv[1:], "c:")
+    if opts:
+        bigpart = opts[0][1]
+    if not args:
+        usage()
+        sys.exit(2)
+    for filename in args:
+        base, ext = os.path.splitext(filename)
+        ext = ext or ".toc"
+        process(base + ext, base + ".bkm", bigpart)
+
+
+if __name__ == "__main__":
+    main()


More information about the Python-checkins mailing list