source file: /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/pydoc.py
file stats: 1441 lines, 141 executed: 9.8% covered
   1. #!/usr/bin/env python
   2. # -*- coding: Latin-1 -*-
   3. """Generate Python documentation in HTML or text for interactive use.
   4. 
   5. In the Python interpreter, do "from pydoc import help" to provide online
   6. help.  Calling help(thing) on a Python object documents the object.
   7. 
   8. Or, at the shell command line outside of Python:
   9. 
  10. Run "pydoc <name>" to show documentation on something.  <name> may be
  11. the name of a function, module, package, or a dotted reference to a
  12. class or function within a module or module in a package.  If the
  13. argument contains a path segment delimiter (e.g. slash on Unix,
  14. backslash on Windows) it is treated as the path to a Python source file.
  15. 
  16. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  17. of all available modules.
  18. 
  19. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  20. local machine to generate documentation web pages.
  21. 
  22. For platforms without a command line, "pydoc -g" starts the HTTP server
  23. and also pops up a little window for controlling it.
  24. 
  25. Run "pydoc -w <name>" to write out the HTML documentation for a module
  26. to a file named "<name>.html".
  27. """
  28. 
  29. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  30. __date__ = "26 February 2001"
  31. __version__ = "$Revision: 1.86.8.3 $"
  32. __credits__ = """Guido van Rossum, for an excellent programming language.
  33. Tommy Burnette, the original creator of manpy.
  34. Paul Prescod, for all his work on onlinehelp.
  35. Richard Chamberlain, for the first implementation of textdoc.
  36. 
  37. Mynd you, møøse bites Kan be pretty nasti..."""
  38. 
  39. # Known bugs that can't be fixed here:
  40. #   - imp.load_module() cannot be prevented from clobbering existing
  41. #     loaded modules, so calling synopsis() on a binary module file
  42. #     changes the contents of any existing module with the same name.
  43. #   - If the __file__ attribute on a module is a relative path and
  44. #     the current directory is changed with os.chdir(), an incorrect
  45. #     path will be displayed.
  46. 
  47. import sys, imp, os, re, types, inspect, __builtin__
  48. from repr import Repr
  49. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  50. 
  51. # --------------------------------------------------------- common routines
  52. 
  53. def pathdirs():
  54.     """Convert sys.path into a list of absolute, existing, unique paths."""
  55.     dirs = []
  56.     normdirs = []
  57.     for dir in sys.path:
  58.         dir = os.path.abspath(dir or '.')
  59.         normdir = os.path.normcase(dir)
  60.         if normdir not in normdirs and os.path.isdir(dir):
  61.             dirs.append(dir)
  62.             normdirs.append(normdir)
  63.     return dirs
  64. 
  65. def getdoc(object):
  66.     """Get the doc string or comments for an object."""
  67.     result = inspect.getdoc(object) or inspect.getcomments(object)
  68.     return result and re.sub('^ *\n', '', rstrip(result)) or ''
  69. 
  70. def splitdoc(doc):
  71.     """Split a doc string into a synopsis line (if any) and the rest."""
  72.     lines = split(strip(doc), '\n')
  73.     if len(lines) == 1:
  74.         return lines[0], ''
  75.     elif len(lines) >= 2 and not rstrip(lines[1]):
  76.         return lines[0], join(lines[2:], '\n')
  77.     return '', join(lines, '\n')
  78. 
  79. def classname(object, modname):
  80.     """Get a class name and qualify it with a module name if necessary."""
  81.     name = object.__name__
  82.     if object.__module__ != modname:
  83.         name = object.__module__ + '.' + name
  84.     return name
  85. 
  86. def isdata(object):
  87.     """Check if an object is of a type that probably means it's data."""
  88.     return not (inspect.ismodule(object) or inspect.isclass(object) or
  89.                 inspect.isroutine(object) or inspect.isframe(object) or
  90.                 inspect.istraceback(object) or inspect.iscode(object))
  91. 
  92. def replace(text, *pairs):
  93.     """Do a series of global replacements on a string."""
  94.     while pairs:
  95.         text = join(split(text, pairs[0]), pairs[1])
  96.         pairs = pairs[2:]
  97.     return text
  98. 
  99. def cram(text, maxlen):
 100.     """Omit part of a string if needed to make it fit in a maximum length."""
 101.     if len(text) > maxlen:
 102.         pre = max(0, (maxlen-3)//2)
 103.         post = max(0, maxlen-3-pre)
 104.         return text[:pre] + '...' + text[len(text)-post:]
 105.     return text
 106. 
 107. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,}(>+)$', re.IGNORECASE)
 108. def stripid(text):
 109.     """Remove the hexadecimal id from a Python object representation."""
 110.     # The behaviour of %p is implementation-dependent in terms of case.
 111.     if _re_stripid.search(repr(Exception)):
 112.         return _re_stripid.sub(r'\1', text)
 113.     return text
 114. 
 115. def _is_some_method(object):
 116.     return inspect.ismethod(object) or inspect.ismethoddescriptor(object)
 117. 
 118. def allmethods(cl):
 119.     methods = {}
 120.     for key, value in inspect.getmembers(cl, _is_some_method):
 121.         methods[key] = 1
 122.     for base in cl.__bases__:
 123.         methods.update(allmethods(base)) # all your base are belong to us
 124.     for key in methods.keys():
 125.         methods[key] = getattr(cl, key)
 126.     return methods
 127. 
 128. def _split_list(s, predicate):
 129.     """Split sequence s via predicate, and return pair ([true], [false]).
 130. 
 131.     The return value is a 2-tuple of lists,
 132.         ([x for x in s if predicate(x)],
 133.          [x for x in s if not predicate(x)])
 134.     """
 135. 
 136.     yes = []
 137.     no = []
 138.     for x in s:
 139.         if predicate(x):
 140.             yes.append(x)
 141.         else:
 142.             no.append(x)
 143.     return yes, no
 144. 
 145. def visiblename(name):
 146.     """Decide whether to show documentation on a variable."""
 147.     # Certain special names are redundant.
 148.     if name in ['__builtins__', '__doc__', '__file__', '__path__',
 149.                 '__module__', '__name__']: return 0
 150.     # Private names are hidden, but special names are displayed.
 151.     if name.startswith('__') and name.endswith('__'): return 1
 152.     return not name.startswith('_')
 153. 
 154. # ----------------------------------------------------- module manipulation
 155. 
 156. def ispackage(path):
 157.     """Guess whether a path refers to a package directory."""
 158.     if os.path.isdir(path):
 159.         for ext in ['.py', '.pyc', '.pyo']:
 160.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
 161.                 return True
 162.     return False
 163. 
 164. def synopsis(filename, cache={}):
 165.     """Get the one-line summary out of a module file."""
 166.     mtime = os.stat(filename).st_mtime
 167.     lastupdate, result = cache.get(filename, (0, None))
 168.     if lastupdate < mtime:
 169.         info = inspect.getmoduleinfo(filename)
 170.         file = open(filename)
 171.         if info and 'b' in info[2]: # binary modules have to be imported
 172.             try: module = imp.load_module('__temp__', file, filename, info[1:])
 173.             except: return None
 174.             result = split(module.__doc__ or '', '\n')[0]
 175.             del sys.modules['__temp__']
 176.         else: # text modules can be directly examined
 177.             line = file.readline()
 178.             while line[:1] == '#' or not strip(line):
 179.                 line = file.readline()
 180.                 if not line: break
 181.             line = strip(line)
 182.             if line[:4] == 'r"""': line = line[1:]
 183.             if line[:3] == '"""':
 184.                 line = line[3:]
 185.                 if line[-1:] == '\\': line = line[:-1]
 186.                 while not strip(line):
 187.                     line = file.readline()
 188.                     if not line: break
 189.                 result = strip(split(line, '"""')[0])
 190.             else: result = None
 191.         file.close()
 192.         cache[filename] = (mtime, result)
 193.     return result
 194. 
 195. class ErrorDuringImport(Exception):
 196.     """Errors that occurred while trying to import something to document it."""
 197.     def __init__(self, filename, (exc, value, tb)):
 198.         self.filename = filename
 199.         self.exc = exc
 200.         self.value = value
 201.         self.tb = tb
 202. 
 203.     def __str__(self):
 204.         exc = self.exc
 205.         if type(exc) is types.ClassType:
 206.             exc = exc.__name__
 207.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
 208. 
 209. def importfile(path):
 210.     """Import a Python source file or compiled file given its path."""
 211.     magic = imp.get_magic()
 212.     file = open(path, 'r')
 213.     if file.read(len(magic)) == magic:
 214.         kind = imp.PY_COMPILED
 215.     else:
 216.         kind = imp.PY_SOURCE
 217.     file.close()
 218.     filename = os.path.basename(path)
 219.     name, ext = os.path.splitext(filename)
 220.     file = open(path, 'r')
 221.     try:
 222.         module = imp.load_module(name, file, path, (ext, 'r', kind))
 223.     except:
 224.         raise ErrorDuringImport(path, sys.exc_info())
 225.     file.close()
 226.     return module
 227. 
 228. def safeimport(path, forceload=0, cache={}):
 229.     """Import a module; handle errors; return None if the module isn't found.
 230. 
 231.     If the module *is* found but an exception occurs, it's wrapped in an
 232.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
 233.     package path is specified, the module at the end of the path is returned,
 234.     not the package at the beginning.  If the optional 'forceload' argument
 235.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
 236.     if forceload and path in sys.modules:
 237.         # This is the only way to be sure.  Checking the mtime of the file
 238.         # isn't good enough (e.g. what if the module contains a class that
 239.         # inherits from another module that has changed?).
 240.         if path not in sys.builtin_module_names:
 241.             # Python never loads a dynamic extension a second time from the
 242.             # same path, even if the file is changed or missing.  Deleting
 243.             # the entry in sys.modules doesn't help for dynamic extensions,
 244.             # so we're not even going to try to keep them up to date.
 245.             info = inspect.getmoduleinfo(sys.modules[path].__file__)
 246.             if info[3] != imp.C_EXTENSION:
 247.                 cache[path] = sys.modules[path] # prevent module from clearing
 248.                 del sys.modules[path]
 249.     try:
 250.         module = __import__(path)
 251.     except:
 252.         # Did the error occur before or after the module was found?
 253.         (exc, value, tb) = info = sys.exc_info()
 254.         if path in sys.modules:
 255.             # An error occured while executing the imported module.
 256.             raise ErrorDuringImport(sys.modules[path].__file__, info)
 257.         elif exc is SyntaxError:
 258.             # A SyntaxError occurred before we could execute the module.
 259.             raise ErrorDuringImport(value.filename, info)
 260.         elif exc is ImportError and \
 261.              split(lower(str(value)))[:2] == ['no', 'module']:
 262.             # The module was not found.
 263.             return None
 264.         else:
 265.             # Some other error occurred during the importing process.
 266.             raise ErrorDuringImport(path, sys.exc_info())
 267.     for part in split(path, '.')[1:]:
 268.         try: module = getattr(module, part)
 269.         except AttributeError: return None
 270.     return module
 271. 
 272. # ---------------------------------------------------- formatter base class
 273. 
 274. class Doc:
 275.     def document(self, object, name=None, *args):
 276.         """Generate documentation for an object."""
 277.         args = (object, name) + args
 278.         # 'try' clause is to attempt to handle the possibility that inspect
 279.         # identifies something in a way that pydoc itself has issues handling;
 280.         # think 'super' and how it is a descriptor (which raises the exception
 281.         # by lacking a __name__ attribute) and an instance.
 282.         try:
 283.             if inspect.ismodule(object): return self.docmodule(*args)
 284.             if inspect.isclass(object): return self.docclass(*args)
 285.             if inspect.isroutine(object): return self.docroutine(*args)
 286.         except AttributeError:
 287.             pass
 288.         return self.docother(*args)
 289. 
 290.     def fail(self, object, name=None, *args):
 291.         """Raise an exception for unimplemented types."""
 292.         message = "don't know how to document object%s of type %s" % (
 293.             name and ' ' + repr(name), type(object).__name__)
 294.         raise TypeError, message
 295. 
 296.     docmodule = docclass = docroutine = docother = fail
 297. 
 298. # -------------------------------------------- HTML documentation generator
 299. 
 300. class HTMLRepr(Repr):
 301.     """Class for safely making an HTML representation of a Python object."""
 302.     def __init__(self):
 303.         Repr.__init__(self)
 304.         self.maxlist = self.maxtuple = 20
 305.         self.maxdict = 10
 306.         self.maxstring = self.maxother = 100
 307. 
 308.     def escape(self, text):
 309.         return replace(text, '&', '&amp;', '<', '&lt;', '>', '&gt;')
 310. 
 311.     def repr(self, object):
 312.         return Repr.repr(self, object)
 313. 
 314.     def repr1(self, x, level):
 315.         if hasattr(type(x), '__name__'):
 316.             methodname = 'repr_' + join(split(type(x).__name__), '_')
 317.             if hasattr(self, methodname):
 318.                 return getattr(self, methodname)(x, level)
 319.         return self.escape(cram(stripid(repr(x)), self.maxother))
 320. 
 321.     def repr_string(self, x, level):
 322.         test = cram(x, self.maxstring)
 323.         testrepr = repr(test)
 324.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
 325.             # Backslashes are only literal in the string and are never
 326.             # needed to make any special characters, so show a raw string.
 327.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
 328.         return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
 329.                       r'<font color="#c040c0">\1</font>',
 330.                       self.escape(testrepr))
 331. 
 332.     repr_str = repr_string
 333. 
 334.     def repr_instance(self, x, level):
 335.         try:
 336.             return self.escape(cram(stripid(repr(x)), self.maxstring))
 337.         except:
 338.             return self.escape('<%s instance>' % x.__class__.__name__)
 339. 
 340.     repr_unicode = repr_string
 341. 
 342. class HTMLDoc(Doc):
 343.     """Formatter class for HTML documentation."""
 344. 
 345.     # ------------------------------------------- HTML formatting utilities
 346. 
 347.     _repr_instance = HTMLRepr()
 348.     repr = _repr_instance.repr
 349.     escape = _repr_instance.escape
 350. 
 351.     def page(self, title, contents):
 352.         """Format an HTML page."""
 353.         return '''
 354. <!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
 355. <html><head><title>Python: %s</title>
 356. </head><body bgcolor="#f0f0f8">
 357. %s
 358. </body></html>''' % (title, contents)
 359. 
 360.     def heading(self, title, fgcol, bgcol, extras=''):
 361.         """Format a page heading."""
 362.         return '''
 363. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
 364. <tr bgcolor="%s">
 365. <td valign=bottom>&nbsp;<br>
 366. <font color="%s" face="helvetica, arial">&nbsp;<br>%s</font></td
 367. ><td align=right valign=bottom
 368. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
 369.     ''' % (bgcol, fgcol, title, fgcol, extras or '&nbsp;')
 370. 
 371.     def section(self, title, fgcol, bgcol, contents, width=6,
 372.                 prelude='', marginalia=None, gap='&nbsp;'):
 373.         """Format a section with a heading."""
 374.         if marginalia is None:
 375.             marginalia = '<tt>' + '&nbsp;' * width + '</tt>'
 376.         result = '''<p>
 377. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
 378. <tr bgcolor="%s">
 379. <td colspan=3 valign=bottom>&nbsp;<br>
 380. <font color="%s" face="helvetica, arial">%s</font></td></tr>
 381.     ''' % (bgcol, fgcol, title)
 382.         if prelude:
 383.             result = result + '''
 384. <tr bgcolor="%s"><td rowspan=2>%s</td>
 385. <td colspan=2>%s</td></tr>
 386. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
 387.         else:
 388.             result = result + '''
 389. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
 390. 
 391.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
 392. 
 393.     def bigsection(self, title, *args):
 394.         """Format a section with a big heading."""
 395.         title = '<big><strong>%s</strong></big>' % title
 396.         return self.section(title, *args)
 397. 
 398.     def preformat(self, text):
 399.         """Format literal preformatted text."""
 400.         text = self.escape(expandtabs(text))
 401.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
 402.                              ' ', '&nbsp;', '\n', '<br>\n')
 403. 
 404.     def multicolumn(self, list, format, cols=4):
 405.         """Format a list of items into a multi-column list."""
 406.         result = ''
 407.         rows = (len(list)+cols-1)/cols
 408.         for col in range(cols):
 409.             result = result + '<td width="%d%%" valign=top>' % (100/cols)
 410.             for i in range(rows*col, rows*col+rows):
 411.                 if i < len(list):
 412.                     result = result + format(list[i]) + '<br>\n'
 413.             result = result + '</td>'
 414.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
 415. 
 416.     def grey(self, text): return '<font color="#909090">%s</font>' % text
 417. 
 418.     def namelink(self, name, *dicts):
 419.         """Make a link for an identifier, given name-to-URL mappings."""
 420.         for dict in dicts:
 421.             if name in dict:
 422.                 return '<a href="%s">%s</a>' % (dict[name], name)
 423.         return name
 424. 
 425.     def classlink(self, object, modname):
 426.         """Make a link for a class."""
 427.         name, module = object.__name__, sys.modules.get(object.__module__)
 428.         if hasattr(module, name) and getattr(module, name) is object:
 429.             return '<a href="%s.html#%s">%s</a>' % (
 430.                 module.__name__, name, classname(object, modname))
 431.         return classname(object, modname)
 432. 
 433.     def modulelink(self, object):
 434.         """Make a link for a module."""
 435.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
 436. 
 437.     def modpkglink(self, (name, path, ispackage, shadowed)):
 438.         """Make a link for a module or package to display in an index."""
 439.         if shadowed:
 440.             return self.grey(name)
 441.         if path:
 442.             url = '%s.%s.html' % (path, name)
 443.         else:
 444.             url = '%s.html' % name
 445.         if ispackage:
 446.             text = '<strong>%s</strong>&nbsp;(package)' % name
 447.         else:
 448.             text = name
 449.         return '<a href="%s">%s</a>' % (url, text)
 450. 
 451.     def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
 452.         """Mark up some plain text, given a context of symbols to look for.
 453.         Each context dictionary maps object names to anchor names."""
 454.         escape = escape or self.escape
 455.         results = []
 456.         here = 0
 457.         pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
 458.                                 r'RFC[- ]?(\d+)|'
 459.                                 r'PEP[- ]?(\d+)|'
 460.                                 r'(self\.)?(\w+))')
 461.         while True:
 462.             match = pattern.search(text, here)
 463.             if not match: break
 464.             start, end = match.span()
 465.             results.append(escape(text[here:start]))
 466. 
 467.             all, scheme, rfc, pep, selfdot, name = match.groups()
 468.             if scheme:
 469.                 url = escape(all).replace('"', '&quot;')
 470.                 results.append('<a href="%s">%s</a>' % (url, url))
 471.             elif rfc:
 472.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
 473.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
 474.             elif pep:
 475.                 url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
 476.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
 477.             elif text[end:end+1] == '(':
 478.                 results.append(self.namelink(name, methods, funcs, classes))
 479.             elif selfdot:
 480.                 results.append('self.<strong>%s</strong>' % name)
 481.             else:
 482.                 results.append(self.namelink(name, classes))
 483.             here = end
 484.         results.append(escape(text[here:]))
 485.         return join(results, '')
 486. 
 487.     # ---------------------------------------------- type-specific routines
 488. 
 489.     def formattree(self, tree, modname, parent=None):
 490.         """Produce HTML for a class tree as given by inspect.getclasstree()."""
 491.         result = ''
 492.         for entry in tree:
 493.             if type(entry) is type(()):
 494.                 c, bases = entry
 495.                 result = result + '<dt><font face="helvetica, arial">'
 496.                 result = result + self.classlink(c, modname)
 497.                 if bases and bases != (parent,):
 498.                     parents = []
 499.                     for base in bases:
 500.                         parents.append(self.classlink(base, modname))
 501.                     result = result + '(' + join(parents, ', ') + ')'
 502.                 result = result + '\n</font></dt>'
 503.             elif type(entry) is type([]):
 504.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(
 505.                     entry, modname, c)
 506.         return '<dl>\n%s</dl>\n' % result
 507. 
 508.     def docmodule(self, object, name=None, mod=None, *ignored):
 509.         """Produce HTML documentation for a module object."""
 510.         name = object.__name__ # ignore the passed-in name
 511.         parts = split(name, '.')
 512.         links = []
 513.         for i in range(len(parts)-1):
 514.             links.append(
 515.                 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
 516.                 (join(parts[:i+1], '.'), parts[i]))
 517.         linkedname = join(links + parts[-1:], '.')
 518.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
 519.         try:
 520.             path = inspect.getabsfile(object)
 521.             url = path
 522.             if sys.platform == 'win32':
 523.                 import nturl2path
 524.                 url = nturl2path.pathname2url(path)
 525.             filelink = '<a href="file:%s">%s</a>' % (url, path)
 526.         except TypeError:
 527.             filelink = '(built-in)'
 528.         info = []
 529.         if hasattr(object, '__version__'):
 530.             version = str(object.__version__)
 531.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
 532.                 version = strip(version[11:-1])
 533.             info.append('version %s' % self.escape(version))
 534.         if hasattr(object, '__date__'):
 535.             info.append(self.escape(str(object.__date__)))
 536.         if info:
 537.             head = head + ' (%s)' % join(info, ', ')
 538.         result = self.heading(
 539.             head, '#ffffff', '#7799ee', '<a href=".">index</a><br>' + filelink)
 540. 
 541.         modules = inspect.getmembers(object, inspect.ismodule)
 542. 
 543.         classes, cdict = [], {}
 544.         for key, value in inspect.getmembers(object, inspect.isclass):
 545.             if (inspect.getmodule(value) or object) is object:
 546.                 if visiblename(key):
 547.                     classes.append((key, value))
 548.                     cdict[key] = cdict[value] = '#' + key
 549.         for key, value in classes:
 550.             for base in value.__bases__:
 551.                 key, modname = base.__name__, base.__module__
 552.                 module = sys.modules.get(modname)
 553.                 if modname != name and module and hasattr(module, key):
 554.                     if getattr(module, key) is base:
 555.                         if not key in cdict:
 556.                             cdict[key] = cdict[base] = modname + '.html#' + key
 557.         funcs, fdict = [], {}
 558.         for key, value in inspect.getmembers(object, inspect.isroutine):
 559.             if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
 560.                 if visiblename(key):
 561.                     funcs.append((key, value))
 562.                     fdict[key] = '#-' + key
 563.                     if inspect.isfunction(value): fdict[value] = fdict[key]
 564.         data = []
 565.         for key, value in inspect.getmembers(object, isdata):
 566.             if visiblename(key):
 567.                 data.append((key, value))
 568. 
 569.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
 570.         doc = doc and '<tt>%s</tt>' % doc
 571.         result = result + '<p>%s</p>\n' % doc
 572. 
 573.         if hasattr(object, '__path__'):
 574.             modpkgs = []
 575.             modnames = []
 576.             for file in os.listdir(object.__path__[0]):
 577.                 path = os.path.join(object.__path__[0], file)
 578.                 modname = inspect.getmodulename(file)
 579.                 if modname != '__init__':
 580.                     if modname and modname not in modnames:
 581.                         modpkgs.append((modname, name, 0, 0))
 582.                         modnames.append(modname)
 583.                     elif ispackage(path):
 584.                         modpkgs.append((file, name, 1, 0))
 585.             modpkgs.sort()
 586.             contents = self.multicolumn(modpkgs, self.modpkglink)
 587.             result = result + self.bigsection(
 588.                 'Package Contents', '#ffffff', '#aa55cc', contents)
 589.         elif modules:
 590.             contents = self.multicolumn(
 591.                 modules, lambda (key, value), s=self: s.modulelink(value))
 592.             result = result + self.bigsection(
 593.                 'Modules', '#fffff', '#aa55cc', contents)
 594. 
 595.         if classes:
 596.             classlist = map(lambda (key, value): value, classes)
 597.             contents = [
 598.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
 599.             for key, value in classes:
 600.                 contents.append(self.document(value, key, name, fdict, cdict))
 601.             result = result + self.bigsection(
 602.                 'Classes', '#ffffff', '#ee77aa', join(contents))
 603.         if funcs:
 604.             contents = []
 605.             for key, value in funcs:
 606.                 contents.append(self.document(value, key, name, fdict, cdict))
 607.             result = result + self.bigsection(
 608.                 'Functions', '#ffffff', '#eeaa77', join(contents))
 609.         if data:
 610.             contents = []
 611.             for key, value in data:
 612.                 contents.append(self.document(value, key))
 613.             result = result + self.bigsection(
 614.                 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
 615.         if hasattr(object, '__author__'):
 616.             contents = self.markup(str(object.__author__), self.preformat)
 617.             result = result + self.bigsection(
 618.                 'Author', '#ffffff', '#7799ee', contents)
 619.         if hasattr(object, '__credits__'):
 620.             contents = self.markup(str(object.__credits__), self.preformat)
 621.             result = result + self.bigsection(
 622.                 'Credits', '#ffffff', '#7799ee', contents)
 623. 
 624.         return result
 625. 
 626.     def docclass(self, object, name=None, mod=None, funcs={}, classes={},
 627.                  *ignored):
 628.         """Produce HTML documentation for a class object."""
 629.         realname = object.__name__
 630.         name = name or realname
 631.         bases = object.__bases__
 632. 
 633.         contents = []
 634.         push = contents.append
 635. 
 636.         # Cute little class to pump out a horizontal rule between sections.
 637.         class HorizontalRule:
 638.             def __init__(self):
 639.                 self.needone = 0
 640.             def maybe(self):
 641.                 if self.needone:
 642.                     push('<hr>\n')
 643.                 self.needone = 1
 644.         hr = HorizontalRule()
 645. 
 646.         # List the mro, if non-trivial.
 647.         mro = list(inspect.getmro(object))
 648.         if len(mro) > 2:
 649.             hr.maybe()
 650.             push('<dl><dt>Method resolution order:</dt>\n')
 651.             for base in mro:
 652.                 push('<dd>%s</dd>\n' % self.classlink(base,
 653.                                                       object.__module__))
 654.             push('</dl>\n')
 655. 
 656.         def spill(msg, attrs, predicate):
 657.             ok, attrs = _split_list(attrs, predicate)
 658.             if ok:
 659.                 hr.maybe()
 660.                 push(msg)
 661.                 for name, kind, homecls, value in ok:
 662.                     push(self.document(getattr(object, name), name, mod,
 663.                                        funcs, classes, mdict, object))
 664.                     push('\n')
 665.             return attrs
 666. 
 667.         def spillproperties(msg, attrs, predicate):
 668.             ok, attrs = _split_list(attrs, predicate)
 669.             if ok:
 670.                 hr.maybe()
 671.                 push(msg)
 672.                 for name, kind, homecls, value in ok:
 673.                     push('<dl><dt><strong>%s</strong></dt>\n' % name)
 674.                     if value.__doc__ is not None:
 675.                         doc = self.markup(value.__doc__, self.preformat,
 676.                                           funcs, classes, mdict)
 677.                         push('<dd><tt>%s</tt></dd>\n' % doc)
 678.                     for attr, tag in [('fget', '<em>get</em>'),
 679.                                       ('fset', '<em>set</em>'),
 680.                                       ('fdel', '<em>delete</em>')]:
 681.                         func = getattr(value, attr)
 682.                         if func is not None:
 683.                             base = self.document(func, tag, mod,
 684.                                                  funcs, classes, mdict, object)
 685.                             push('<dd>%s</dd>\n' % base)
 686.                     push('</dl>\n')
 687.             return attrs
 688. 
 689.         def spilldata(msg, attrs, predicate):
 690.             ok, attrs = _split_list(attrs, predicate)
 691.             if ok:
 692.                 hr.maybe()
 693.                 push(msg)
 694.                 for name, kind, homecls, value in ok:
 695.                     base = self.docother(getattr(object, name), name, mod)
 696.                     if callable(value) or inspect.isdatadescriptor(value):
 697.                         doc = getattr(value, "__doc__", None)
 698.                     else:
 699.                         doc = None
 700.                     if doc is None:
 701.                         push('<dl><dt>%s</dl>\n' % base)
 702.                     else:
 703.                         doc = self.markup(getdoc(value), self.preformat,
 704.                                           funcs, classes, mdict)
 705.                         doc = '<dd><tt>%s</tt>' % doc
 706.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
 707.                     push('\n')
 708.             return attrs
 709. 
 710.         attrs = filter(lambda (name, kind, cls, value): visiblename(name),
 711.                        inspect.classify_class_attrs(object))
 712.         mdict = {}
 713.         for key, kind, homecls, value in attrs:
 714.             mdict[key] = anchor = '#' + name + '-' + key
 715.             value = getattr(object, key)
 716.             try:
 717.                 # The value may not be hashable (e.g., a data attr with
 718.                 # a dict or list value).
 719.                 mdict[value] = anchor
 720.             except TypeError:
 721.                 pass
 722. 
 723.         while attrs:
 724.             if mro:
 725.                 thisclass = mro.pop(0)
 726.             else:
 727.                 thisclass = attrs[0][2]
 728.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
 729. 
 730.             if thisclass is __builtin__.object:
 731.                 attrs = inherited
 732.                 continue
 733.             elif thisclass is object:
 734.                 tag = 'defined here'
 735.             else:
 736.                 tag = 'inherited from %s' % self.classlink(thisclass,
 737.                                                            object.__module__)
 738.             tag += ':<br>\n'
 739. 
 740.             # Sort attrs by name.
 741.             attrs.sort(lambda t1, t2: cmp(t1[0], t2[0]))
 742. 
 743.             # Pump out the attrs, segregated by kind.
 744.             attrs = spill('Methods %s' % tag, attrs,
 745.                           lambda t: t[1] == 'method')
 746.             attrs = spill('Class methods %s' % tag, attrs,
 747.                           lambda t: t[1] == 'class method')
 748.             attrs = spill('Static methods %s' % tag, attrs,
 749.                           lambda t: t[1] == 'static method')
 750.             attrs = spillproperties('Properties %s' % tag, attrs,
 751.                                     lambda t: t[1] == 'property')
 752.             attrs = spilldata('Data and other attributes %s' % tag, attrs,
 753.                               lambda t: t[1] == 'data')
 754.             assert attrs == []
 755.             attrs = inherited
 756. 
 757.         contents = ''.join(contents)
 758. 
 759.         if name == realname:
 760.             title = '<a name="%s">class <strong>%s</strong></a>' % (
 761.                 name, realname)
 762.         else:
 763.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
 764.                 name, name, realname)
 765.         if bases:
 766.             parents = []
 767.             for base in bases:
 768.                 parents.append(self.classlink(base, object.__module__))
 769.             title = title + '(%s)' % join(parents, ', ')
 770.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
 771.         doc = doc and '<tt>%s<br>&nbsp;</tt>' % doc
 772. 
 773.         return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
 774. 
 775.     def formatvalue(self, object):
 776.         """Format an argument default value as text."""
 777.         return self.grey('=' + self.repr(object))
 778. 
 779.     def docroutine(self, object, name=None, mod=None,
 780.                    funcs={}, classes={}, methods={}, cl=None):
 781.         """Produce HTML documentation for a function or method object."""
 782.         realname = object.__name__
 783.         name = name or realname
 784.         anchor = (cl and cl.__name__ or '') + '-' + name
 785.         note = ''
 786.         skipdocs = 0
 787.         if inspect.ismethod(object):
 788.             imclass = object.im_class
 789.             if cl:
 790.                 if imclass is not cl:
 791.                     note = ' from ' + self.classlink(imclass, mod)
 792.             else:
 793.                 if object.im_self:
 794.                     note = ' method of %s instance' % self.classlink(
 795.                         object.im_self.__class__, mod)
 796.                 else:
 797.                     note = ' unbound %s method' % self.classlink(imclass,mod)
 798.             object = object.im_func
 799. 
 800.         if name == realname:
 801.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
 802.         else:
 803.             if (cl and realname in cl.__dict__ and
 804.                 cl.__dict__[realname] is object):
 805.                 reallink = '<a href="#%s">%s</a>' % (
 806.                     cl.__name__ + '-' + realname, realname)
 807.                 skipdocs = 1
 808.             else:
 809.                 reallink = realname
 810.             title = '<a name="%s"><strong>%s</strong></a> = %s' % (
 811.                 anchor, name, reallink)
 812.         if inspect.isfunction(object):
 813.             args, varargs, varkw, defaults = inspect.getargspec(object)
 814.             argspec = inspect.formatargspec(
 815.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
 816.             if realname == '<lambda>':
 817.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
 818.                 argspec = argspec[1:-1] # remove parentheses
 819.         else:
 820.             argspec = '(...)'
 821. 
 822.         decl = title + argspec + (note and self.grey(
 823.                '<font face="helvetica, arial">%s</font>' % note))
 824. 
 825.         if skipdocs:
 826.             return '<dl><dt>%s</dt></dl>\n' % decl
 827.         else:
 828.             doc = self.markup(
 829.                 getdoc(object), self.preformat, funcs, classes, methods)
 830.             doc = doc and '<dd><tt>%s</tt></dd>' % doc
 831.             return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
 832. 
 833.     def docother(self, object, name=None, mod=None, *ignored):
 834.         """Produce HTML documentation for a data object."""
 835.         lhs = name and '<strong>%s</strong> = ' % name or ''
 836.         return lhs + self.repr(object)
 837. 
 838.     def index(self, dir, shadowed=None):
 839.         """Generate an HTML index for a directory of modules."""
 840.         modpkgs = []
 841.         if shadowed is None: shadowed = {}
 842.         seen = {}
 843.         files = os.listdir(dir)
 844. 
 845.         def found(name, ispackage,
 846.                   modpkgs=modpkgs, shadowed=shadowed, seen=seen):
 847.             if name not in seen:
 848.                 modpkgs.append((name, '', ispackage, name in shadowed))
 849.                 seen[name] = 1
 850.                 shadowed[name] = 1
 851. 
 852.         # Package spam/__init__.py takes precedence over module spam.py.
 853.         for file in files:
 854.             path = os.path.join(dir, file)
 855.             if ispackage(path): found(file, 1)
 856.         for file in files:
 857.             path = os.path.join(dir, file)
 858.             if os.path.isfile(path):
 859.                 modname = inspect.getmodulename(file)
 860.                 if modname: found(modname, 0)
 861. 
 862.         modpkgs.sort()
 863.         contents = self.multicolumn(modpkgs, self.modpkglink)
 864.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
 865. 
 866. # -------------------------------------------- text documentation generator
 867. 
 868. class TextRepr(Repr):
 869.     """Class for safely making a text representation of a Python object."""
 870.     def __init__(self):
 871.         Repr.__init__(self)
 872.         self.maxlist = self.maxtuple = 20
 873.         self.maxdict = 10
 874.         self.maxstring = self.maxother = 100
 875. 
 876.     def repr1(self, x, level):
 877.         if hasattr(type(x), '__name__'):
 878.             methodname = 'repr_' + join(split(type(x).__name__), '_')
 879.             if hasattr(self, methodname):
 880.                 return getattr(self, methodname)(x, level)
 881.         return cram(stripid(repr(x)), self.maxother)
 882. 
 883.     def repr_string(self, x, level):
 884.         test = cram(x, self.maxstring)
 885.         testrepr = repr(test)
 886.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
 887.             # Backslashes are only literal in the string and are never
 888.             # needed to make any special characters, so show a raw string.
 889.             return 'r' + testrepr[0] + test + testrepr[0]
 890.         return testrepr
 891. 
 892.     repr_str = repr_string
 893. 
 894.     def repr_instance(self, x, level):
 895.         try:
 896.             return cram(stripid(repr(x)), self.maxstring)
 897.         except:
 898.             return '<%s instance>' % x.__class__.__name__
 899. 
 900. class TextDoc(Doc):
 901.     """Formatter class for text documentation."""
 902. 
 903.     # ------------------------------------------- text formatting utilities
 904. 
 905.     _repr_instance = TextRepr()
 906.     repr = _repr_instance.repr
 907. 
 908.     def bold(self, text):
 909.         """Format a string in bold by overstriking."""
 910.         return join(map(lambda ch: ch + '\b' + ch, text), '')
 911. 
 912.     def indent(self, text, prefix='    '):
 913.         """Indent text by prepending a given prefix to each line."""
 914.         if not text: return ''
 915.         lines = split(text, '\n')
 916.         lines = map(lambda line, prefix=prefix: prefix + line, lines)
 917.         if lines: lines[-1] = rstrip(lines[-1])
 918.         return join(lines, '\n')
 919. 
 920.     def section(self, title, contents):
 921.         """Format a section with a given heading."""
 922.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
 923. 
 924.     # ---------------------------------------------- type-specific routines
 925. 
 926.     def formattree(self, tree, modname, parent=None, prefix=''):
 927.         """Render in text a class tree as returned by inspect.getclasstree()."""
 928.         result = ''
 929.         for entry in tree:
 930.             if type(entry) is type(()):
 931.                 c, bases = entry
 932.                 result = result + prefix + classname(c, modname)
 933.                 if bases and bases != (parent,):
 934.                     parents = map(lambda c, m=modname: classname(c, m), bases)
 935.                     result = result + '(%s)' % join(parents, ', ')
 936.                 result = result + '\n'
 937.             elif type(entry) is type([]):
 938.                 result = result + self.formattree(
 939.                     entry, modname, c, prefix + '    ')
 940.         return result
 941. 
 942.     def docmodule(self, object, name=None, mod=None):
 943.         """Produce text documentation for a given module object."""
 944.         name = object.__name__ # ignore the passed-in name
 945.         synop, desc = splitdoc(getdoc(object))
 946.         result = self.section('NAME', name + (synop and ' - ' + synop))
 947. 
 948.         try:
 949.             file = inspect.getabsfile(object)
 950.         except TypeError:
 951.             file = '(built-in)'
 952.         result = result + self.section('FILE', file)
 953.         if desc:
 954.             result = result + self.section('DESCRIPTION', desc)
 955. 
 956.         classes = []
 957.         for key, value in inspect.getmembers(object, inspect.isclass):
 958.             if (inspect.getmodule(value) or object) is object:
 959.                 if visiblename(key):
 960.                     classes.append((key, value))
 961.         funcs = []
 962.         for key, value in inspect.getmembers(object, inspect.isroutine):
 963.             if inspect.isbuiltin(value) or inspect.getmodule(value) is object:
 964.                 if visiblename(key):
 965.                     funcs.append((key, value))
 966.         data = []
 967.         for key, value in inspect.getmembers(object, isdata):
 968.             if visiblename(key):
 969.                 data.append((key, value))
 970. 
 971.         if hasattr(object, '__path__'):
 972.             modpkgs = []
 973.             for file in os.listdir(object.__path__[0]):
 974.                 path = os.path.join(object.__path__[0], file)
 975.                 modname = inspect.getmodulename(file)
 976.                 if modname != '__init__':
 977.                     if modname and modname not in modpkgs:
 978.                         modpkgs.append(modname)
 979.                     elif ispackage(path):
 980.                         modpkgs.append(file + ' (package)')
 981.             modpkgs.sort()
 982.             result = result + self.section(
 983.                 'PACKAGE CONTENTS', join(modpkgs, '\n'))
 984. 
 985.         if classes:
 986.             classlist = map(lambda (key, value): value, classes)
 987.             contents = [self.formattree(
 988.                 inspect.getclasstree(classlist, 1), name)]
 989.             for key, value in classes:
 990.                 contents.append(self.document(value, key, name))
 991.             result = result + self.section('CLASSES', join(contents, '\n'))
 992. 
 993.         if funcs:
 994.             contents = []
 995.             for key, value in funcs:
 996.                 contents.append(self.document(value, key, name))
 997.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
 998. 
 999.         if data:
1000.             contents = []
1001.             for key, value in data:
1002.                 contents.append(self.docother(value, key, name, 70))
1003.             result = result + self.section('DATA', join(contents, '\n'))
1004. 
1005.         if hasattr(object, '__version__'):
1006.             version = str(object.__version__)
1007.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
1008.                 version = strip(version[11:-1])
1009.             result = result + self.section('VERSION', version)
1010.         if hasattr(object, '__date__'):
1011.             result = result + self.section('DATE', str(object.__date__))
1012.         if hasattr(object, '__author__'):
1013.             result = result + self.section('AUTHOR', str(object.__author__))
1014.         if hasattr(object, '__credits__'):
1015.             result = result + self.section('CREDITS', str(object.__credits__))
1016.         return result
1017. 
1018.     def docclass(self, object, name=None, mod=None):
1019.         """Produce text documentation for a given class object."""
1020.         realname = object.__name__
1021.         name = name or realname
1022.         bases = object.__bases__
1023. 
1024.         def makename(c, m=object.__module__):
1025.             return classname(c, m)
1026. 
1027.         if name == realname:
1028.             title = 'class ' + self.bold(realname)
1029.         else:
1030.             title = self.bold(name) + ' = class ' + realname
1031.         if bases:
1032.             parents = map(makename, bases)
1033.             title = title + '(%s)' % join(parents, ', ')
1034. 
1035.         doc = getdoc(object)
1036.         contents = doc and [doc + '\n'] or []
1037.         push = contents.append
1038. 
1039.         # List the mro, if non-trivial.
1040.         mro = list(inspect.getmro(object))
1041.         if len(mro) > 2:
1042.             push("Method resolution order:")
1043.             for base in mro:
1044.                 push('    ' + makename(base))
1045.             push('')
1046. 
1047.         # Cute little class to pump out a horizontal rule between sections.
1048.         class HorizontalRule:
1049.             def __init__(self):
1050.                 self.needone = 0
1051.             def maybe(self):
1052.                 if self.needone:
1053.                     push('-' * 70)
1054.                 self.needone = 1
1055.         hr = HorizontalRule()
1056. 
1057.         def spill(msg, attrs, predicate):
1058.             ok, attrs = _split_list(attrs, predicate)
1059.             if ok:
1060.                 hr.maybe()
1061.                 push(msg)
1062.                 for name, kind, homecls, value in ok:
1063.                     push(self.document(getattr(object, name),
1064.                                        name, mod, object))
1065.             return attrs
1066. 
1067.         def spillproperties(msg, attrs, predicate):
1068.             ok, attrs = _split_list(attrs, predicate)
1069.             if ok:
1070.                 hr.maybe()
1071.                 push(msg)
1072.                 for name, kind, homecls, value in ok:
1073.                     push(name)
1074.                     need_blank_after_doc = 0
1075.                     doc = getdoc(value) or ''
1076.                     if doc:
1077.                         push(self.indent(doc))
1078.                         need_blank_after_doc = 1
1079.                     for attr, tag in [('fget', '<get>'),
1080.                                       ('fset', '<set>'),
1081.                                       ('fdel', '<delete>')]:
1082.                         func = getattr(value, attr)
1083.                         if func is not None:
1084.                             if need_blank_after_doc:
1085.                                 push('')
1086.                                 need_blank_after_doc = 0
1087.                             base = self.document(func, tag, mod)
1088.                             push(self.indent(base))
1089.             return attrs
1090. 
1091.         def spilldata(msg, attrs, predicate):
1092.             ok, attrs = _split_list(attrs, predicate)
1093.             if ok:
1094.                 hr.maybe()
1095.                 push(msg)
1096.                 for name, kind, homecls, value in ok:
1097.                     if callable(value) or inspect.isdatadescriptor(value):
1098.                         doc = getattr(value, "__doc__", None)
1099.                     else:
1100.                         doc = None
1101.                     push(self.docother(getattr(object, name),
1102.                                        name, mod, 70, doc) + '\n')
1103.             return attrs
1104. 
1105.         attrs = filter(lambda (name, kind, cls, value): visiblename(name),
1106.                        inspect.classify_class_attrs(object))
1107.         while attrs:
1108.             if mro:
1109.                 thisclass = mro.pop(0)
1110.             else:
1111.                 thisclass = attrs[0][2]
1112.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
1113. 
1114.             if thisclass is __builtin__.object:
1115.                 attrs = inherited
1116.                 continue
1117.             elif thisclass is object:
1118.                 tag = "defined here"
1119.             else:
1120.                 tag = "inherited from %s" % classname(thisclass,
1121.                                                       object.__module__)
1122.             filter(lambda t: not t[0].startswith('_'), attrs)
1123. 
1124.             # Sort attrs by name.
1125.             attrs.sort()
1126. 
1127.             # Pump out the attrs, segregated by kind.
1128.             attrs = spill("Methods %s:\n" % tag, attrs,
1129.                           lambda t: t[1] == 'method')
1130.             attrs = spill("Class methods %s:\n" % tag, attrs,
1131.                           lambda t: t[1] == 'class method')
1132.             attrs = spill("Static methods %s:\n" % tag, attrs,
1133.                           lambda t: t[1] == 'static method')
1134.             attrs = spillproperties("Properties %s:\n" % tag, attrs,
1135.                                     lambda t: t[1] == 'property')
1136.             attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
1137.                               lambda t: t[1] == 'data')
1138.             assert attrs == []
1139.             attrs = inherited
1140. 
1141.         contents = '\n'.join(contents)
1142.         if not contents:
1143.             return title + '\n'
1144.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
1145. 
1146.     def formatvalue(self, object):
1147.         """Format an argument default value as text."""
1148.         return '=' + self.repr(object)
1149. 
1150.     def docroutine(self, object, name=None, mod=None, cl=None):
1151.         """Produce text documentation for a function or method object."""
1152.         realname = object.__name__
1153.         name = name or realname
1154.         note = ''
1155.         skipdocs = 0
1156.         if inspect.ismethod(object):
1157.             imclass = object.im_class
1158.             if cl:
1159.                 if imclass is not cl:
1160.                     note = ' from ' + classname(imclass, mod)
1161.             else:
1162.                 if object.im_self:
1163.                     note = ' method of %s instance' % classname(
1164.                         object.im_self.__class__, mod)
1165.                 else:
1166.                     note = ' unbound %s method' % classname(imclass,mod)
1167.             object = object.im_func
1168. 
1169.         if name == realname:
1170.             title = self.bold(realname)
1171.         else:
1172.             if (cl and realname in cl.__dict__ and
1173.                 cl.__dict__[realname] is object):
1174.                 skipdocs = 1
1175.             title = self.bold(name) + ' = ' + realname
1176.         if inspect.isfunction(object):
1177.             args, varargs, varkw, defaults = inspect.getargspec(object)
1178.             argspec = inspect.formatargspec(
1179.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
1180.             if realname == '<lambda>':
1181.                 title = 'lambda'
1182.                 argspec = argspec[1:-1] # remove parentheses
1183.         else:
1184.             argspec = '(...)'
1185.         decl = title + argspec + note
1186. 
1187.         if skipdocs:
1188.             return decl + '\n'
1189.         else:
1190.             doc = getdoc(object) or ''
1191.             return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
1192. 
1193.     def docother(self, object, name=None, mod=None, maxlen=None, doc=None):
1194.         """Produce text documentation for a data object."""
1195.         repr = self.repr(object)
1196.         if maxlen:
1197.             line = (name and name + ' = ' or '') + repr
1198.             chop = maxlen - len(line)
1199.             if chop < 0: repr = repr[:chop] + '...'
1200.         line = (name and self.bold(name) + ' = ' or '') + repr
1201.         if doc is not None:
1202.             line += '\n' + self.indent(str(doc))
1203.         return line
1204. 
1205. # --------------------------------------------------------- user interfaces
1206. 
1207. def pager(text):
1208.     """The first time this is called, determine what kind of pager to use."""
1209.     global pager
1210.     pager = getpager()
1211.     pager(text)
1212. 
1213. def getpager():
1214.     """Decide what method to use for paging through text."""
1215.     if type(sys.stdout) is not types.FileType:
1216.         return plainpager
1217.     if not sys.stdin.isatty() or not sys.stdout.isatty():
1218.         return plainpager
1219.     if os.environ.get('TERM') in ['dumb', 'emacs']:
1220.         return plainpager
1221.     if 'PAGER' in os.environ:
1222.         if sys.platform == 'win32': # pipes completely broken in Windows
1223.             return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
1224.         elif os.environ.get('TERM') in ['dumb', 'emacs']:
1225.             return lambda text: pipepager(plain(text), os.environ['PAGER'])
1226.         else:
1227.             return lambda text: pipepager(text, os.environ['PAGER'])
1228.     if sys.platform == 'win32' or sys.platform.startswith('os2'):
1229.         return lambda text: tempfilepager(plain(text), 'more <')
1230.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
1231.         return lambda text: pipepager(text, 'less')
1232. 
1233.     import tempfile
1234.     (fd, filename) = tempfile.mkstemp()
1235.     os.close(fd)
1236.     try:
1237.         if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
1238.             return lambda text: pipepager(text, 'more')
1239.         else:
1240.             return ttypager
1241.     finally:
1242.         os.unlink(filename)
1243. 
1244. def plain(text):
1245.     """Remove boldface formatting from text."""
1246.     return re.sub('.\b', '', text)
1247. 
1248. def pipepager(text, cmd):
1249.     """Page through text by feeding it to another program."""
1250.     pipe = os.popen(cmd, 'w')
1251.     try:
1252.         pipe.write(text)
1253.         pipe.close()
1254.     except IOError:
1255.         pass # Ignore broken pipes caused by quitting the pager program.
1256. 
1257. def tempfilepager(text, cmd):
1258.     """Page through text by invoking a program on a temporary file."""
1259.     import tempfile
1260.     filename = tempfile.mktemp()
1261.     file = open(filename, 'w')
1262.     file.write(text)
1263.     file.close()
1264.     try:
1265.         os.system(cmd + ' ' + filename)
1266.     finally:
1267.         os.unlink(filename)
1268. 
1269. def ttypager(text):
1270.     """Page through text on a text terminal."""
1271.     lines = split(plain(text), '\n')
1272.     try:
1273.         import tty
1274.         fd = sys.stdin.fileno()
1275.         old = tty.tcgetattr(fd)
1276.         tty.setcbreak(fd)
1277.         getchar = lambda: sys.stdin.read(1)
1278.     except (ImportError, AttributeError):
1279.         tty = None
1280.         getchar = lambda: sys.stdin.readline()[:-1][:1]
1281. 
1282.     try:
1283.         r = inc = os.environ.get('LINES', 25) - 1
1284.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
1285.         while lines[r:]:
1286.             sys.stdout.write('-- more --')
1287.             sys.stdout.flush()
1288.             c = getchar()
1289. 
1290.             if c in ['q', 'Q']:
1291.                 sys.stdout.write('\r          \r')
1292.                 break
1293.             elif c in ['\r', '\n']:
1294.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
1295.                 r = r + 1
1296.                 continue
1297.             if c in ['b', 'B', '\x1b']:
1298.                 r = r - inc - inc
1299.                 if r < 0: r = 0
1300.             sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
1301.             r = r + inc
1302. 
1303.     finally:
1304.         if tty:
1305.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
1306. 
1307. def plainpager(text):
1308.     """Simply print unformatted text.  This is the ultimate fallback."""
1309.     sys.stdout.write(plain(text))
1310. 
1311. def describe(thing):
1312.     """Produce a short description of the given thing."""
1313.     if inspect.ismodule(thing):
1314.         if thing.__name__ in sys.builtin_module_names:
1315.             return 'built-in module ' + thing.__name__
1316.         if hasattr(thing, '__path__'):
1317.             return 'package ' + thing.__name__
1318.         else:
1319.             return 'module ' + thing.__name__
1320.     if inspect.isbuiltin(thing):
1321.         return 'built-in function ' + thing.__name__
1322.     if inspect.isclass(thing):
1323.         return 'class ' + thing.__name__
1324.     if inspect.isfunction(thing):
1325.         return 'function ' + thing.__name__
1326.     if inspect.ismethod(thing):
1327.         return 'method ' + thing.__name__
1328.     if type(thing) is types.InstanceType:
1329.         return 'instance of ' + thing.__class__.__name__
1330.     return type(thing).__name__
1331. 
1332. def locate(path, forceload=0):
1333.     """Locate an object by name or dotted path, importing as necessary."""
1334.     parts = [part for part in split(path, '.') if part]
1335.     module, n = None, 0
1336.     while n < len(parts):
1337.         nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
1338.         if nextmodule: module, n = nextmodule, n + 1
1339.         else: break
1340.     if module:
1341.         object = module
1342.         for part in parts[n:]:
1343.             try: object = getattr(object, part)
1344.             except AttributeError: return None
1345.         return object
1346.     else:
1347.         if hasattr(__builtin__, path):
1348.             return getattr(__builtin__, path)
1349. 
1350. # --------------------------------------- interactive interpreter interface
1351. 
1352. text = TextDoc()
1353. html = HTMLDoc()
1354. 
1355. def resolve(thing, forceload=0):
1356.     """Given an object or a path to an object, get the object and its name."""
1357.     if isinstance(thing, str):
1358.         object = locate(thing, forceload)
1359.         if not object:
1360.             raise ImportError, 'no Python documentation found for %r' % thing
1361.         return object, thing
1362.     else:
1363.         return thing, getattr(thing, '__name__', None)
1364. 
1365. def doc(thing, title='Python Library Documentation: %s', forceload=0):
1366.     """Display text documentation, given an object or a path to an object."""
1367.     try:
1368.         object, name = resolve(thing, forceload)
1369.         desc = describe(object)
1370.         module = inspect.getmodule(object)
1371.         if name and '.' in name:
1372.             desc += ' in ' + name[:name.rfind('.')]
1373.         elif module and module is not object:
1374.             desc += ' in module ' + module.__name__
1375.         pager(title % desc + '\n\n' + text.document(object, name))
1376.     except (ImportError, ErrorDuringImport), value:
1377.         print value
1378. 
1379. def writedoc(thing, forceload=0):
1380.     """Write HTML documentation to a file in the current directory."""
1381.     try:
1382.         object, name = resolve(thing, forceload)
1383.         page = html.page(describe(object), html.document(object, name))
1384.         file = open(name + '.html', 'w')
1385.         file.write(page)
1386.         file.close()
1387.         print 'wrote', name + '.html'
1388.     except (ImportError, ErrorDuringImport), value:
1389.         print value
1390. 
1391. def writedocs(dir, pkgpath='', done=None):
1392.     """Write out HTML documentation for all modules in a directory tree."""
1393.     if done is None: done = {}
1394.     for file in os.listdir(dir):
1395.         path = os.path.join(dir, file)
1396.         if ispackage(path):
1397.             writedocs(path, pkgpath + file + '.', done)
1398.         elif os.path.isfile(path):
1399.             modname = inspect.getmodulename(path)
1400.             if modname:
1401.                 if modname == '__init__':
1402.                     modname = pkgpath[:-1] # remove trailing period
1403.                 else:
1404.                     modname = pkgpath + modname
1405.                 if modname not in done:
1406.                     done[modname] = 1
1407.                     writedoc(modname)
1408. 
1409. class Helper:
1410.     keywords = {
1411.         'and': 'BOOLEAN',
1412.         'assert': ('ref/assert', ''),
1413.         'break': ('ref/break', 'while for'),
1414.         'class': ('ref/class', 'CLASSES SPECIALMETHODS'),
1415.         'continue': ('ref/continue', 'while for'),
1416.         'def': ('ref/function', ''),
1417.         'del': ('ref/del', 'BASICMETHODS'),
1418.         'elif': 'if',
1419.         'else': ('ref/if', 'while for'),
1420.         'except': 'try',
1421.         'exec': ('ref/exec', ''),
1422.         'finally': 'try',
1423.         'for': ('ref/for', 'break continue while'),
1424.         'from': 'import',
1425.         'global': ('ref/global', 'NAMESPACES'),
1426.         'if': ('ref/if', 'TRUTHVALUE'),
1427.         'import': ('ref/import', 'MODULES'),
1428.         'in': ('ref/comparisons', 'SEQUENCEMETHODS2'),
1429.         'is': 'COMPARISON',
1430.         'lambda': ('ref/lambdas', 'FUNCTIONS'),
1431.         'not': 'BOOLEAN',
1432.         'or': 'BOOLEAN',
1433.         'pass': ('ref/pass', ''),
1434.         'print': ('ref/print', ''),
1435.         'raise': ('ref/raise', 'EXCEPTIONS'),
1436.         'return': ('ref/return', 'FUNCTIONS'),
1437.         'try': ('ref/try', 'EXCEPTIONS'),
1438.         'while': ('ref/while', 'break continue if TRUTHVALUE'),
1439.         'yield': ('ref/yield', ''),
1440.     }
1441. 
1442.     topics = {
1443.         'TYPES': ('ref/types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS FUNCTIONS CLASSES MODULES FILES inspect'),
1444.         'STRINGS': ('ref/strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING TYPES'),
1445.         'STRINGMETHODS': ('lib/string-methods', 'STRINGS FORMATTING'),
1446.         'FORMATTING': ('lib/typesseq-strings', 'OPERATORS'),
1447.         'UNICODE': ('ref/strings', 'encodings unicode SEQUENCES STRINGMETHODS FORMATTING TYPES'),
1448.         'NUMBERS': ('ref/numbers', 'INTEGER FLOAT COMPLEX TYPES'),
1449.         'INTEGER': ('ref/integers', 'int range'),
1450.         'FLOAT': ('ref/floating', 'float math'),
1451.         'COMPLEX': ('ref/imaginary', 'complex cmath'),
1452.         'SEQUENCES': ('lib/typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
1453.         'MAPPINGS': 'DICTIONARIES',
1454.         'FUNCTIONS': ('lib/typesfunctions', 'def TYPES'),
1455.         'METHODS': ('lib/typesmethods', 'class def CLASSES TYPES'),
1456.         'CODEOBJECTS': ('lib/bltin-code-objects', 'compile FUNCTIONS TYPES'),
1457.         'TYPEOBJECTS': ('lib/bltin-type-objects', 'types TYPES'),
1458.         'FRAMEOBJECTS': 'TYPES',
1459.         'TRACEBACKS': 'TYPES',
1460.         'NONE': ('lib/bltin-null-object', ''),
1461.         'ELLIPSIS': ('lib/bltin-ellipsis-object', 'SLICINGS'),
1462.         'FILES': ('lib/bltin-file-objects', ''),
1463.         'SPECIALATTRIBUTES': ('lib/specialattrs', ''),
1464.         'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'),
1465.         'MODULES': ('lib/typesmodules', 'import'),
1466.         'PACKAGES': 'import',
1467.         'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'),
1468.         'OPERATORS': 'EXPRESSIONS',
1469.         'PRECEDENCE': 'EXPRESSIONS',
1470.         'OBJECTS': ('ref/objects', 'TYPES'),
1471.         'SPECIALMETHODS': ('ref/specialnames', 'BASICMETHODS ATTRIBUTEMETHODS CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
1472.         'BASICMETHODS': ('ref/customization', 'cmp hash repr str SPECIALMETHODS'),
1473.         'ATTRIBUTEMETHODS': ('ref/attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
1474.         'CALLABLEMETHODS': ('ref/callable-types', 'CALLS SPECIALMETHODS'),
1475.         'SEQUENCEMETHODS1': ('ref/sequence-types', 'SEQUENCES SEQUENCEMETHODS2 SPECIALMETHODS'),
1476.         'SEQUENCEMETHODS2': ('ref/sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 SPECIALMETHODS'),
1477.         'MAPPINGMETHODS': ('ref/sequence-types', 'MAPPINGS SPECIALMETHODS'),
1478.         'NUMBERMETHODS': ('ref/numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT SPECIALMETHODS'),
1479.         'EXECUTION': ('ref/execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
1480.         'NAMESPACES': ('ref/naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
1481.         'DYNAMICFEATURES': ('ref/dynamic-features', ''),
1482.         'SCOPING': 'NAMESPACES',
1483.         'FRAMES': 'NAMESPACES',
1484.         'EXCEPTIONS': ('ref/exceptions', 'try except finally raise'),
1485.         'COERCIONS': ('ref/coercion-rules','CONVERSIONS'),
1486.         'CONVERSIONS': ('ref/conversions', 'COERCIONS'),
1487.         'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'),
1488.         'SPECIALIDENTIFIERS': ('ref/id-classes', ''),
1489.         'PRIVATENAMES': ('ref/atom-identifiers', ''),
1490.         'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
1491.         'TUPLES': 'SEQUENCES',
1492.         'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'),
1493.         'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'),
1494.         'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'),
1495.         'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'),
1496.         'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'),
1497.         'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'),
1498.         'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'),
1499.         'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'),
1500.         'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'),
1501.         'CALLS': ('ref/calls', 'EXPRESSIONS'),
1502.         'POWER': ('ref/power', 'EXPRESSIONS'),
1503.         'UNARY': ('ref/unary', 'EXPRESSIONS'),
1504.         'BINARY': ('ref/binary', 'EXPRESSIONS'),
1505.         'SHIFTING': ('ref/shifting', 'EXPRESSIONS'),
1506.         'BITWISE': ('ref/bitwise', 'EXPRESSIONS'),
1507.         'COMPARISON': ('ref/comparisons', 'EXPRESSIONS BASICMETHODS'),
1508.         'BOOLEAN': ('ref/Booleans', 'EXPRESSIONS TRUTHVALUE'),
1509.         'ASSERTION': 'assert',
1510.         'ASSIGNMENT': ('ref/assignment', 'AUGMENTEDASSIGNMENT'),
1511.         'AUGMENTEDASSIGNMENT': ('ref/augassign', 'NUMBERMETHODS'),
1512.         'DELETION': 'del',
1513.         'PRINTING': 'print',
1514.         'RETURNING': 'return',
1515.         'IMPORTING': 'import',
1516.         'CONDITIONAL': 'if',
1517.         'LOOPING': ('ref/compound', 'for while break continue'),
1518.         'TRUTHVALUE': ('lib/truth', 'if while and or not BASICMETHODS'),
1519.         'DEBUGGING': ('lib/module-pdb', 'pdb'),
1520.     }
1521. 
1522.     def __init__(self, input, output):
1523.         self.input = input
1524.         self.output = output
1525.         self.docdir = None
1526.         execdir = os.path.dirname(sys.executable)
1527.         homedir = os.environ.get('PYTHONHOME')
1528.         for dir in [os.environ.get('PYTHONDOCS'),
1529.                     homedir and os.path.join(homedir, 'doc'),
1530.                     os.path.join(execdir, 'doc'),
1531.                     '/usr/doc/python-docs-' + split(sys.version)[0],
1532.                     '/usr/doc/python-' + split(sys.version)[0],
1533.                     '/usr/doc/python-docs-' + sys.version[:3],
1534.                     '/usr/doc/python-' + sys.version[:3],
1535.                     os.path.join(sys.prefix, 'Resources/English.lproj/Documentation')]:
1536.             if dir and os.path.isdir(os.path.join(dir, 'lib')):
1537.                 self.docdir = dir
1538. 
1539.     def __repr__(self):
1540.         if inspect.stack()[1][3] == '?':
1541.             self()
1542.             return ''
1543.         return '<pydoc.Helper instance>'
1544. 
1545.     def __call__(self, request=None):
1546.         if request is not None:
1547.             self.help(request)
1548.         else:
1549.             self.intro()
1550.             self.interact()
1551.             self.output.write('''
1552. You are now leaving help and returning to the Python interpreter.
1553. If you want to ask for help on a particular object directly from the
1554. interpreter, you can type "help(object)".  Executing "help('string')"
1555. has the same effect as typing a particular string at the help> prompt.
1556. ''')
1557. 
1558.     def interact(self):
1559.         self.output.write('\n')
1560.         while True:
1561.             self.output.write('help> ')
1562.             self.output.flush()
1563.             try:
1564.                 request = self.input.readline()
1565.                 if not request: break
1566.             except KeyboardInterrupt: break
1567.             request = strip(replace(request, '"', '', "'", ''))
1568.             if lower(request) in ['q', 'quit']: break
1569.             self.help(request)
1570. 
1571.     def help(self, request):
1572.         if type(request) is type(''):
1573.             if request == 'help': self.intro()
1574.             elif request == 'keywords': self.listkeywords()
1575.             elif request == 'topics': self.listtopics()
1576.             elif request == 'modules': self.listmodules()
1577.             elif request[:8] == 'modules ':
1578.                 self.listmodules(split(request)[1])
1579.             elif request in self.keywords: self.showtopic(request)
1580.             elif request in self.topics: self.showtopic(request)
1581.             elif request: doc(request, 'Help on %s:')
1582.         elif isinstance(request, Helper): self()
1583.         else: doc(request, 'Help on %s:')
1584.         self.output.write('\n')
1585. 
1586.     def intro(self):
1587.         self.output.write('''
1588. Welcome to Python %s!  This is the online help utility.
1589. 
1590. If this is your first time using Python, you should definitely check out
1591. the tutorial on the Internet at http://www.python.org/doc/tut/.
1592. 
1593. Enter the name of any module, keyword, or topic to get help on writing
1594. Python programs and using Python modules.  To quit this help utility and
1595. return to the interpreter, just type "quit".
1596. 
1597. To get a list of available modules, keywords, or topics, type "modules",
1598. "keywords", or "topics".  Each module also comes with a one-line summary
1599. of what it does; to list the modules whose summaries contain a given word
1600. such as "spam", type "modules spam".
1601. ''' % sys.version[:3])
1602. 
1603.     def list(self, items, columns=4, width=80):
1604.         items = items[:]
1605.         items.sort()
1606.         colw = width / columns
1607.         rows = (len(items) + columns - 1) / columns
1608.         for row in range(rows):
1609.             for col in range(columns):
1610.                 i = col * rows + row
1611.                 if i < len(items):
1612.                     self.output.write(items[i])
1613.                     if col < columns - 1:
1614.                         self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
1615.             self.output.write('\n')
1616. 
1617.     def listkeywords(self):
1618.         self.output.write('''
1619. Here is a list of the Python keywords.  Enter any keyword to get more help.
1620. 
1621. ''')
1622.         self.list(self.keywords.keys())
1623. 
1624.     def listtopics(self):
1625.         self.output.write('''
1626. Here is a list of available topics.  Enter any topic name to get more help.
1627. 
1628. ''')
1629.         self.list(self.topics.keys())
1630. 
1631.     def showtopic(self, topic):
1632.         if not self.docdir:
1633.             self.output.write('''
1634. Sorry, topic and keyword documentation is not available because the Python
1635. HTML documentation files could not be found.  If you have installed them,
1636. please set the environment variable PYTHONDOCS to indicate their location.
1637. ''')
1638.             return
1639.         target = self.topics.get(topic, self.keywords.get(topic))
1640.         if not target:
1641.             self.output.write('no documentation found for %s\n' % repr(topic))
1642.             return
1643.         if type(target) is type(''):
1644.             return self.showtopic(target)
1645. 
1646.         filename, xrefs = target
1647.         filename = self.docdir + '/' + filename + '.html'
1648.         try:
1649.             file = open(filename)
1650.         except:
1651.             self.output.write('could not read docs from %s\n' % filename)
1652.             return
1653. 
1654.         divpat = re.compile('<div[^>]*navigat.*?</div.*?>', re.I | re.S)
1655.         addrpat = re.compile('<address.*?>.*?</address.*?>', re.I | re.S)
1656.         document = re.sub(addrpat, '', re.sub(divpat, '', file.read()))
1657.         file.close()
1658. 
1659.         import htmllib, formatter, StringIO
1660.         buffer = StringIO.StringIO()
1661.         parser = htmllib.HTMLParser(
1662.             formatter.AbstractFormatter(formatter.DumbWriter(buffer)))
1663.         parser.start_table = parser.do_p
1664.         parser.end_table = lambda parser=parser: parser.do_p({})
1665.         parser.start_tr = parser.do_br
1666.         parser.start_td = parser.start_th = lambda a, b=buffer: b.write('\t')
1667.         parser.feed(document)
1668.         buffer = replace(buffer.getvalue(), '\xa0', ' ', '\n', '\n  ')
1669.         pager('  ' + strip(buffer) + '\n')
1670.         if xrefs:
1671.             buffer = StringIO.StringIO()
1672.             formatter.DumbWriter(buffer).send_flowing_data(
1673.                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
1674.             self.output.write('\n%s\n' % buffer.getvalue())
1675. 
1676.     def listmodules(self, key=''):
1677.         if key:
1678.             self.output.write('''
1679. Here is a list of matching modules.  Enter any module name to get more help.
1680. 
1681. ''')
1682.             apropos(key)
1683.         else:
1684.             self.output.write('''
1685. Please wait a moment while I gather a list of all available modules...
1686. 
1687. ''')
1688.             modules = {}
1689.             def callback(path, modname, desc, modules=modules):
1690.                 if modname and modname[-9:] == '.__init__':
1691.                     modname = modname[:-9] + ' (package)'
1692.                 if find(modname, '.') < 0:
1693.                     modules[modname] = 1
1694.             ModuleScanner().run(callback)
1695.             self.list(modules.keys())
1696.             self.output.write('''
1697. Enter any module name to get more help.  Or, type "modules spam" to search
1698. for modules whose descriptions contain the word "spam".
1699. ''')
1700. 
1701. help = Helper(sys.stdin, sys.stdout)
1702. 
1703. class Scanner:
1704.     """A generic tree iterator."""
1705.     def __init__(self, roots, children, descendp):
1706.         self.roots = roots[:]
1707.         self.state = []
1708.         self.children = children
1709.         self.descendp = descendp
1710. 
1711.     def next(self):
1712.         if not self.state:
1713.             if not self.roots:
1714.                 return None
1715.             root = self.roots.pop(0)
1716.             self.state = [(root, self.children(root))]
1717.         node, children = self.state[-1]
1718.         if not children:
1719.             self.state.pop()
1720.             return self.next()
1721.         child = children.pop(0)
1722.         if self.descendp(child):
1723.             self.state.append((child, self.children(child)))
1724.         return child
1725. 
1726. class ModuleScanner(Scanner):
1727.     """An interruptible scanner that searches module synopses."""
1728.     def __init__(self):
1729.         roots = map(lambda dir: (dir, ''), pathdirs())
1730.         Scanner.__init__(self, roots, self.submodules, self.isnewpackage)
1731.         self.inodes = map(lambda (dir, pkg): os.stat(dir).st_ino, roots)
1732. 
1733.     def submodules(self, (dir, package)):
1734.         children = []
1735.         for file in os.listdir(dir):
1736.             path = os.path.join(dir, file)
1737.             if ispackage(path):
1738.                 children.append((path, package + (package and '.') + file))
1739.             else:
1740.                 children.append((path, package))
1741.         children.sort() # so that spam.py comes before spam.pyc or spam.pyo
1742.         return children
1743. 
1744.     def isnewpackage(self, (dir, package)):
1745.         inode = os.path.exists(dir) and os.stat(dir).st_ino
1746.         if not (os.path.islink(dir) and inode in self.inodes):
1747.             self.inodes.append(inode) # detect circular symbolic links
1748.             return ispackage(dir)
1749.         return False
1750. 
1751.     def run(self, callback, key=None, completer=None):
1752.         if key: key = lower(key)
1753.         self.quit = False
1754.         seen = {}
1755. 
1756.         for modname in sys.builtin_module_names:
1757.             if modname != '__main__':
1758.                 seen[modname] = 1
1759.                 if key is None:
1760.                     callback(None, modname, '')
1761.                 else:
1762.                     desc = split(__import__(modname).__doc__ or '', '\n')[0]
1763.                     if find(lower(modname + ' - ' + desc), key) >= 0:
1764.                         callback(None, modname, desc)
1765. 
1766.         while not self.quit:
1767.             node = self.next()
1768.             if not node: break
1769.             path, package = node
1770.             modname = inspect.getmodulename(path)
1771.             if os.path.isfile(path) and modname:
1772.                 modname = package + (package and '.') + modname
1773.                 if not modname in seen:
1774.                     seen[modname] = 1 # if we see spam.py, skip spam.pyc
1775.                     if key is None:
1776.                         callback(path, modname, '')
1777.                     else:
1778.                         desc = synopsis(path) or ''
1779.                         if find(lower(modname + ' - ' + desc), key) >= 0:
1780.                             callback(path, modname, desc)
1781.         if completer: completer()
1782. 
1783. def apropos(key):
1784.     """Print all the one-line module summaries that contain a substring."""
1785.     def callback(path, modname, desc):
1786.         if modname[-9:] == '.__init__':
1787.             modname = modname[:-9] + ' (package)'
1788.         print modname, desc and '- ' + desc
1789.     try: import warnings
1790.     except ImportError: pass
1791.     else: warnings.filterwarnings('ignore') # ignore problems during import
1792.     ModuleScanner().run(callback, key)
1793. 
1794. # --------------------------------------------------- web browser interface
1795. 
1796. def serve(port, callback=None, completer=None):
1797.     import BaseHTTPServer, mimetools, select
1798. 
1799.     # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
1800.     class Message(mimetools.Message):
1801.         def __init__(self, fp, seekable=1):
1802.             Message = self.__class__
1803.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
1804.             self.encodingheader = self.getheader('content-transfer-encoding')
1805.             self.typeheader = self.getheader('content-type')
1806.             self.parsetype()
1807.             self.parseplist()
1808. 
1809.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1810.         def send_document(self, title, contents):
1811.             try:
1812.                 self.send_response(200)
1813.                 self.send_header('Content-Type', 'text/html')
1814.                 self.end_headers()
1815.                 self.wfile.write(html.page(title, contents))
1816.             except IOError: pass
1817. 
1818.         def do_GET(self):
1819.             path = self.path
1820.             if path[-5:] == '.html': path = path[:-5]
1821.             if path[:1] == '/': path = path[1:]
1822.             if path and path != '.':
1823.                 try:
1824.                     obj = locate(path, forceload=1)
1825.                 except ErrorDuringImport, value:
1826.                     self.send_document(path, html.escape(str(value)))
1827.                     return
1828.                 if obj:
1829.                     self.send_document(describe(obj), html.document(obj, path))
1830.                 else:
1831.                     self.send_document(path,
1832. 'no Python documentation found for %s' % repr(path))
1833.             else:
1834.                 heading = html.heading(
1835. '<big><big><strong>Python: Index of Modules</strong></big></big>',
1836. '#ffffff', '#7799ee')
1837.                 def bltinlink(name):
1838.                     return '<a href="%s.html">%s</a>' % (name, name)
1839.                 names = filter(lambda x: x != '__main__',
1840.                                sys.builtin_module_names)
1841.                 contents = html.multicolumn(names, bltinlink)
1842.                 indices = ['<p>' + html.bigsection(
1843.                     'Built-in Modules', '#ffffff', '#ee77aa', contents)]
1844. 
1845.                 seen = {}
1846.                 for dir in pathdirs():
1847.                     indices.append(html.index(dir, seen))
1848.                 contents = heading + join(indices) + '''<p align=right>
1849. <font color="#909090" face="helvetica, arial"><strong>
1850. pydoc</strong> by Ka-Ping Yee &lt;ping@lfw.org&gt;</font>'''
1851.                 self.send_document('Index of Modules', contents)
1852. 
1853.         def log_message(self, *args): pass
1854. 
1855.     class DocServer(BaseHTTPServer.HTTPServer):
1856.         def __init__(self, port, callback):
1857.             host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
1858.             self.address = ('', port)
1859.             self.url = 'http://%s:%d/' % (host, port)
1860.             self.callback = callback
1861.             self.base.__init__(self, self.address, self.handler)
1862. 
1863.         def serve_until_quit(self):
1864.             import select
1865.             self.quit = False
1866.             while not self.quit:
1867.                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
1868.                 if rd: self.handle_request()
1869. 
1870.         def server_activate(self):
1871.             self.base.server_activate(self)
1872.             if self.callback: self.callback(self)
1873. 
1874.     DocServer.base = BaseHTTPServer.HTTPServer
1875.     DocServer.handler = DocHandler
1876.     DocHandler.MessageClass = Message
1877.     try:
1878.         try:
1879.             DocServer(port, callback).serve_until_quit()
1880.         except (KeyboardInterrupt, select.error):
1881.             pass
1882.     finally:
1883.         if completer: completer()
1884. 
1885. # ----------------------------------------------------- graphical interface
1886. 
1887. def gui():
1888.     """Graphical interface (starts web server and pops up a control window)."""
1889.     class GUI:
1890.         def __init__(self, window, port=7464):
1891.             self.window = window
1892.             self.server = None
1893.             self.scanner = None
1894. 
1895.             import Tkinter
1896.             self.server_frm = Tkinter.Frame(window)
1897.             self.title_lbl = Tkinter.Label(self.server_frm,
1898.                 text='Starting server...\n ')
1899.             self.open_btn = Tkinter.Button(self.server_frm,
1900.                 text='open browser', command=self.open, state='disabled')
1901.             self.quit_btn = Tkinter.Button(self.server_frm,
1902.                 text='quit serving', command=self.quit, state='disabled')
1903. 
1904.             self.search_frm = Tkinter.Frame(window)
1905.             self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
1906.             self.search_ent = Tkinter.Entry(self.search_frm)
1907.             self.search_ent.bind('<Return>', self.search)
1908.             self.stop_btn = Tkinter.Button(self.search_frm,
1909.                 text='stop', pady=0, command=self.stop, state='disabled')
1910.             if sys.platform == 'win32':
1911.                 # Trying to hide and show this button crashes under Windows.
1912.                 self.stop_btn.pack(side='right')
1913. 
1914.             self.window.title('pydoc')
1915.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
1916.             self.title_lbl.pack(side='top', fill='x')
1917.             self.open_btn.pack(side='left', fill='x', expand=1)
1918.             self.quit_btn.pack(side='right', fill='x', expand=1)
1919.             self.server_frm.pack(side='top', fill='x')
1920. 
1921.             self.search_lbl.pack(side='left')
1922.             self.search_ent.pack(side='right', fill='x', expand=1)
1923.             self.search_frm.pack(side='top', fill='x')
1924.             self.search_ent.focus_set()
1925. 
1926.             font = ('helvetica', sys.platform == 'win32' and 8 or 10)
1927.             self.result_lst = Tkinter.Listbox(window, font=font, height=6)
1928.             self.result_lst.bind('<Button-1>', self.select)
1929.             self.result_lst.bind('<Double-Button-1>', self.goto)
1930.             self.result_scr = Tkinter.Scrollbar(window,
1931.                 orient='vertical', command=self.result_lst.yview)
1932.             self.result_lst.config(yscrollcommand=self.result_scr.set)
1933. 
1934.             self.result_frm = Tkinter.Frame(window)
1935.             self.goto_btn = Tkinter.Button(self.result_frm,
1936.                 text='go to selected', command=self.goto)
1937.             self.hide_btn = Tkinter.Button(self.result_frm,
1938.                 text='hide results', command=self.hide)
1939.             self.goto_btn.pack(side='left', fill='x', expand=1)
1940.             self.hide_btn.pack(side='right', fill='x', expand=1)
1941. 
1942.             self.window.update()
1943.             self.minwidth = self.window.winfo_width()
1944.             self.minheight = self.window.winfo_height()
1945.             self.bigminheight = (self.server_frm.winfo_reqheight() +
1946.                                  self.search_frm.winfo_reqheight() +
1947.                                  self.result_lst.winfo_reqheight() +
1948.                                  self.result_frm.winfo_reqheight())
1949.             self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
1950.             self.expanded = 0
1951.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
1952.             self.window.wm_minsize(self.minwidth, self.minheight)
1953.             self.window.tk.willdispatch()
1954. 
1955.             import threading
1956.             threading.Thread(
1957.                 target=serve, args=(port, self.ready, self.quit)).start()
1958. 
1959.         def ready(self, server):
1960.             self.server = server
1961.             self.title_lbl.config(
1962.                 text='Python documentation server at\n' + server.url)
1963.             self.open_btn.config(state='normal')
1964.             self.quit_btn.config(state='normal')
1965. 
1966.         def open(self, event=None, url=None):
1967.             url = url or self.server.url
1968.             try:
1969.                 import webbrowser
1970.                 webbrowser.open(url)
1971.             except ImportError: # pre-webbrowser.py compatibility
1972.                 if sys.platform == 'win32':
1973.                     os.system('start "%s"' % url)
1974.                 elif sys.platform == 'mac':
1975.                     try: import ic
1976.                     except ImportError: pass
1977.                     else: ic.launchurl(url)
1978.                 else:
1979.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
1980.                     if rc: os.system('netscape "%s" &' % url)
1981. 
1982.         def quit(self, event=None):
1983.             if self.server:
1984.                 self.server.quit = 1
1985.             self.window.quit()
1986. 
1987.         def search(self, event=None):
1988.             key = self.search_ent.get()
1989.             self.stop_btn.pack(side='right')
1990.             self.stop_btn.config(state='normal')
1991.             self.search_lbl.config(text='Searching for "%s"...' % key)
1992.             self.search_ent.forget()
1993.             self.search_lbl.pack(side='left')
1994.             self.result_lst.delete(0, 'end')
1995.             self.goto_btn.config(state='disabled')
1996.             self.expand()
1997. 
1998.             import threading
1999.             if self.scanner:
2000.                 self.scanner.quit = 1
2001.             self.scanner = ModuleScanner()
2002.             threading.Thread(target=self.scanner.run,
2003.                              args=(self.update, key, self.done)).start()
2004. 
2005.         def update(self, path, modname, desc):
2006.             if modname[-9:] == '.__init__':
2007.                 modname = modname[:-9] + ' (package)'
2008.             self.result_lst.insert('end',
2009.                 modname + ' - ' + (desc or '(no description)'))
2010. 
2011.         def stop(self, event=None):
2012.             if self.scanner:
2013.                 self.scanner.quit = 1
2014.                 self.scanner = None
2015. 
2016.         def done(self):
2017.             self.scanner = None
2018.             self.search_lbl.config(text='Search for')
2019.             self.search_lbl.pack(side='left')
2020.             self.search_ent.pack(side='right', fill='x', expand=1)
2021.             if sys.platform != 'win32': self.stop_btn.forget()
2022.             self.stop_btn.config(state='disabled')
2023. 
2024.         def select(self, event=None):
2025.             self.goto_btn.config(state='normal')
2026. 
2027.         def goto(self, event=None):
2028.             selection = self.result_lst.curselection()
2029.             if selection:
2030.                 modname = split(self.result_lst.get(selection[0]))[0]
2031.                 self.open(url=self.server.url + modname + '.html')
2032. 
2033.         def collapse(self):
2034.             if not self.expanded: return
2035.             self.result_frm.forget()
2036.             self.result_scr.forget()
2037.             self.result_lst.forget()
2038.             self.bigwidth = self.window.winfo_width()
2039.             self.bigheight = self.window.winfo_height()
2040.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
2041.             self.window.wm_minsize(self.minwidth, self.minheight)
2042.             self.expanded = 0
2043. 
2044.         def expand(self):
2045.             if self.expanded: return
2046.             self.result_frm.pack(side='bottom', fill='x')
2047.             self.result_scr.pack(side='right', fill='y')
2048.             self.result_lst.pack(side='top', fill='both', expand=1)
2049.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
2050.             self.window.wm_minsize(self.minwidth, self.bigminheight)
2051.             self.expanded = 1
2052. 
2053.         def hide(self, event=None):
2054.             self.stop()
2055.             self.collapse()
2056. 
2057.     import Tkinter
2058.     try:
2059.         root = Tkinter.Tk()
2060.         # Tk will crash if pythonw.exe has an XP .manifest
2061.         # file and the root has is not destroyed explicitly.
2062.         # If the problem is ever fixed in Tk, the explicit
2063.         # destroy can go.
2064.         try:
2065.             gui = GUI(root)
2066.             root.mainloop()
2067.         finally:
2068.             root.destroy()
2069.     except KeyboardInterrupt:
2070.         pass
2071. 
2072. # -------------------------------------------------- command-line interface
2073. 
2074. def ispath(x):
2075.     return isinstance(x, str) and find(x, os.sep) >= 0
2076. 
2077. def cli():
2078.     """Command-line interface (looks at sys.argv to decide what to do)."""
2079.     import getopt
2080.     class BadUsage: pass
2081. 
2082.     # Scripts don't get the current directory in their path by default.
2083.     scriptdir = os.path.dirname(sys.argv[0])
2084.     if scriptdir in sys.path:
2085.         sys.path.remove(scriptdir)
2086.     sys.path.insert(0, '.')
2087. 
2088.     try:
2089.         opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
2090.         writing = 0
2091. 
2092.         for opt, val in opts:
2093.             if opt == '-g':
2094.                 gui()
2095.                 return
2096.             if opt == '-k':
2097.                 apropos(val)
2098.                 return
2099.             if opt == '-p':
2100.                 try:
2101.                     port = int(val)
2102.                 except ValueError:
2103.                     raise BadUsage
2104.                 def ready(server):
2105.                     print 'pydoc server ready at %s' % server.url
2106.                 def stopped():
2107.                     print 'pydoc server stopped'
2108.                 serve(port, ready, stopped)
2109.                 return
2110.             if opt == '-w':
2111.                 writing = 1
2112. 
2113.         if not args: raise BadUsage
2114.         for arg in args:
2115.             if ispath(arg) and not os.path.exists(arg):
2116.                 print 'file %r does not exist' % arg
2117.                 break
2118.             try:
2119.                 if ispath(arg) and os.path.isfile(arg):
2120.                     arg = importfile(arg)
2121.                 if writing:
2122.                     if ispath(arg) and os.path.isdir(arg):
2123.                         writedocs(arg)
2124.                     else:
2125.                         writedoc(arg)
2126.                 else:
2127.                     help.help(arg)
2128.             except ErrorDuringImport, value:
2129.                 print value
2130. 
2131.     except (getopt.error, BadUsage):
2132.         cmd = os.path.basename(sys.argv[0])
2133.         print """pydoc - the Python documentation tool
2134. 
2135. %s <name> ...
2136.     Show text documentation on something.  <name> may be the name of a
2137.     Python keyword, topic, function, module, or package, or a dotted
2138.     reference to a class or function within a module or module in a
2139.     package.  If <name> contains a '%s', it is used as the path to a
2140.     Python source file to document. If name is 'keywords', 'topics',
2141.     or 'modules', a listing of these things is displayed.
2142. 
2143. %s -k <keyword>
2144.     Search for a keyword in the synopsis lines of all available modules.
2145. 
2146. %s -p <port>
2147.     Start an HTTP server on the given port on the local machine.
2148. 
2149. %s -g
2150.     Pop up a graphical interface for finding and serving documentation.
2151. 
2152. %s -w <name> ...
2153.     Write out the HTML documentation for a module to a file in the current
2154.     directory.  If <name> contains a '%s', it is treated as a filename; if
2155.     it names a directory, documentation is written for all the contents.
2156. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
2157. 
2158. if __name__ == '__main__': cli()