home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pydoc.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-11-11  |  88.5 KB  |  2,544 lines

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