Commits

Anonymous committed a83b45a

Move python stuff from prog-modes to python-modes.

  • Participants

Comments (0)

Files changed (10)

+_pkg.el
+auto-autoloads.el
+custom-load.el
+package-info
+pdepends.mk
+2002-09-18  Ville Skyttä  <ville.skytta@xemacs.org>
+
+	* Package created, moved pydoc and python-mode from the
+	prog-modes package here.
+
+# Makefile for Python modes lisp code
+
+# This file is part of XEmacs.
+
+# XEmacs is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by the
+# Free Software Foundation; either version 2, or (at your option) any
+# later version.
+
+# XEmacs is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# for more details.
+
+# You should have received a copy of the GNU General Public License
+# along with XEmacs; see the file COPYING.  If not, write to
+# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+
+VERSION = 0.99
+AUTHOR_VERSION =
+MAINTAINER = XEmacs Development Team <xemacs-beta@xemacs.org>
+PACKAGE = python-modes
+PKG_TYPE = single-file
+REQUIRES = xemacs-base mail-lib
+CATEGORY = standard
+
+ELCS = pydoc.elc python-mode.elc
+
+EXTRA_SOURCES = pydoc-el-README pydoc_lisp.py
+
+include ../../XEmacs.rules
+
+GENERATED += custom-load.elc
+
+all:: $(ELCS) auto-autoloads.elc custom-load.elc
+
+srckit: srckit-std
+
+binkit: binkit-common
+(python-modes
+  (standards-version 1.1
+   version VERSION
+   author-version AUTHOR_VERSION
+   date DATE
+   build-date BUILD_DATE
+   maintainer MAINTAINER
+   distribution xemacs
+   priority low
+   category CATEGORY
+   dump nil
+   description "Python support."
+   filename FILENAME
+   md5sum MD5SUM
+   size SIZE
+   provides (pydoc python-mode)
+   requires (REQUIRES)
+   type regular
+))
+# SUMMARY:      README for pydoc.el emacs interface to Python pydoc.
+#
+# AUTHOR:       Bob Weiner
+# ORG:          Deepware
+#
+# ORIG-DATE:    23-Apr-01 at 00:03:37
+# LAST-MOD:     23-Apr-01 at 00:16:15 by Bob Weiner
+#
+# Copyright (C) 2001  Bob Weiner
+# Licensed under the Python license version 2.0 or higher.
+#
+# DESCRIPTION:  
+
+pydoc.el is an Emacs/XEmacs/InfoDock interface to the Python pydoc system.
+It provides convenient integration with powerful programming editors,
+speeding both Python learning and day-to-day access of reference
+documentation while programming.
+
+For installation information, see the DESCRIPTION section in "pydoc.el".
+
+----
+
+pydoc.el adds one new global key binding, {C-c M-h} (pydoc-commands) which
+displays a menu of commands for interacting with pydoc.  It is global so
+you may examine Python documentation whenever needed, regardless of whether
+you have a Python code buffer on screen.
+
+The following commands are available, each invoked by typing the first
+character of the command name when prompted with the menu.
+
+A)propos <term>    - list modules/packages with <term> in their first line doc strings
+H)elp <term>       - display doc for name <term> or string literal '<term>'
+K)eyword <keyword> - with completion, display doc for a Python <keyword>
+M)odule <name>     - with completion, display doc for a Python module <name>
+P)ackage <name>    - with completion, display doc for a Python package <name>
+T)opic <topic>     - with completion, display Python reference doc for <topic>
+X)ref <term>       - with completion, display doc for a pydoc cross-reference
+                     within a Python reference manual section
+
+?   - show the above help
+C-g - abort from menu
+
+# DESCRIP-END.
+
+;; LCD-ENTRY:    pydoc.el|Bob Weiner|bob@deepware.com|Interface to pydoc Python documentation viewer|Date|04/23/2001|01.02|www.deepware.com/pub/python
+;;
+;; FILE:         pydoc.el
+;; SUMMARY:      Interface to pydoc Python documentation viewer
+;; USAGE:        Autoloaded XEmacs Lisp Library, use {C-c M-h} to invoke
+;; KEYWORDS:     help, languages, oop, tools
+;;
+;; AUTHOR:       Bob Weiner
+;; ORG:          Deepware
+;; E-MAIL:       bob@deepware.com
+;;
+;; ORIG-DATE:    18-Apr-01 at 19:11:27
+;; LAST-MOD:     23-Apr-01 at 23:59:46 by Bob Weiner
+;;
+;; Copyright (C) 2001  Bob Weiner
+;; Licensed under the Python license version 2.0 or higher.
+;;
+;; This file is part of InfoDock, available from:
+;;   www.sourceforge.net/projects/infodock
+;;
+;; DESCRIPTION:
+;;
+;;   Globally adds key binding {C-c M-h} (pydoc-commands) which
+;;   displays a menu of commands for interacting with the pydoc Python
+;;   documentation viewer library.  See the documentation of
+;;   `pydoc-menu-help' for details on each available command.
+;;
+;;   NOTE: You *must* install the following for pydoc.el to work:
+;;
+;;     python-mode.el 4.1.1 or higher as your Python editing mode (included
+;;     in the pydoc.el distribution)
+;;
+;;     pydoc_lisp.py in your Python site-packages directory (unless
+;;       these functions are already integrated into pydoc.py)
+;;
+;;     set the environment variable PYTHONDOCS to the root directory
+;;       of your Python html documentation tree, for example:
+;;       export PYTHONDOCS=$HOME/Python-2.1/Doc/html/
+;;     and then startup your editor (otherwise, the environment variable
+;;     setting won't be inherited by the editor and some commands will not
+;;     work).
+;;
+;;   Install and byte-compile pydoc.el in one of your load-path directories
+;;   and then either set it to autoload or do a (require 'pydoc) in your
+;;   editor initialization file.  Then invoke it via the menu key binding.
+;;
+;; DESCRIP-END.
+
+;;; ************************************************************************
+;;; Other required Elisp libraries
+;;; ************************************************************************
+
+(require 'python-mode)
+
+;; Ensure that the user has a python-mode version which supports pydoc.el.
+(if (string-lessp py-version "$Revision$")
+    (error "(pydoc): you must upgrade from python-mode.el %s to 4.1.1 (or higher)"
+	   (if (string-match "[0-9.]+" py-version)
+	       (match-string 0 py-version) py-version)))
+
+(provide 'pydoc)
+
+;;; ************************************************************************
+;;; Public variables
+;;; ************************************************************************
+
+(defvar pydoc-version "01.01"
+  "Release version of the Emacs Lisp interface to pydoc.")
+
+;; Provide easy access to (pydoc-commands) everywhere since the user may want
+;; to reference Python doc when in a Python help buffer, a documentation file,
+;; etc.  Use {C-c M-h} instead of {C-c C-h} for this next binding since
+;; {C-c C-h} is an important key in InfoDock's outline-minor-mode which is
+;; often used under python-mode, so this avoids conflicts.
+
+;;;###autoload
+(global-set-key "\C-c\M-h" 'pydoc-commands)
+
+(defvar pydoc-buffer-prefix "Py: "
+  "Prefix string attached to all pydoc display buffers.")
+
+(defvar pydoc-xrefs-prefix "^Related help topics:"
+  "Prefix regexp output before comma separated pydoc help section names.")
+
+;;; ************************************************************************
+;;; Private variables
+;;; ************************************************************************
+
+(defvar pydoc-cmd-alist
+  '(("A)propos"         . pydoc-apropos)
+    ("H)elp"            . pydoc-help)
+    ("K)eyword"         . pydoc-keywords)
+    ("M)odule"          . pydoc-modules)
+    ("P)ackage"         . pydoc-packages)
+    ("T)opic"           . pydoc-topics)
+    ("X)ref"            . pydoc-xrefs))
+  "Association list of (HELP-CMD-PROMPT . CMD) elements for pydoc commands.")
+
+(defvar pydoc-alist nil
+  "Association list of (list-name . alist) elements used to build prompt completion tables.")
+
+(defvar pydoc-menu-mode-map nil
+  "Keymap containing pydoc-menu commands.")
+
+(defvar pydoc-menu-special-keys '(?\C-g ?? ?\C-i ?\C-j ?\C-m ?\ ))
+
+(if pydoc-menu-mode-map
+    nil
+  (setq pydoc-menu-mode-map (make-keymap))
+  (suppress-keymap pydoc-menu-mode-map)
+  (define-key pydoc-menu-mode-map
+    (car (where-is-internal 'keyboard-quit)) 'pydoc-menu-enter)
+  (mapcar #'(lambda (key)
+	      (define-key pydoc-menu-mode-map (char-to-string key) 'pydoc-menu-enter))
+	  pydoc-menu-special-keys)
+  (let ((i 33))
+    (while (<= i 127)
+      (define-key pydoc-menu-mode-map (char-to-string i) 'pydoc-menu-enter)
+      (setq i (1+ i)))))
+
+;;; ************************************************************************
+;;; Commands
+;;; ************************************************************************
+
+;;;###autoload
+(defun pydoc-commands (&optional init-flag)
+  "Display a menu of commands for interacting with the pydoc Python documentation viewer library.
+With optional prefix arg INIT-FLAG, reinitializes the pydoc completion
+tables which includes the list of available Python modules.
+See the documentation for `pydoc-menu-help' for a description of the
+available commands."
+  (interactive "P")
+  (if (or init-flag (null pydoc-alist))
+      (pydoc-initialize))
+  (call-interactively (pydoc-select-command)))
+
+;;;###autoload
+(defun pydoc-apropos (&optional argument)
+  "Call the Python module apropos function with optional ARGUMENT and display the output.
+ARGUMENT defaults to an identifier near point.
+The apropos function finds matches for ARGUMENT within the first line of
+module or package doc strings."
+  (interactive)
+  (if (not argument)
+      (setq argument (pydoc-read-argument "Python module/package apropos: ")))
+  (pydoc-call "apropos" (format "'%s'" argument) (concat "apropos " argument)))
+
+;;;###autoload
+(defun pydoc-help (&optional argument)
+  "Call the Python help function with optional ARGUMENT and display the output.
+ARGUMENT defaults to an identifier near point.
+ARGUMENT is resolved as a name in any present Python namespace; use
+single 'quotes' to send ARGUMENT as a Python literal string."
+  (interactive)
+  (if (not argument)
+      (setq argument (pydoc-read-argument "Python help (name or 'string'): ")))
+  (pydoc-call "help" argument argument))
+
+;;;###autoload
+(defun pydoc-keywords (argument)
+  "Prompt with completion for a Python keyword ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python keyword help (RET for all): "
+		       (cdr (assoc "keywords" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "keywords"))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-modules (argument)
+  "Prompt with completion for a Python module/package ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python module/package help (RET for all): "
+		       (cdr (assoc "modules" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "modules"))
+  (if (string-match "\\`Pkg-" argument)
+      (setq argument (substring argument (match-end 0))))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-packages (argument)
+  "Prompt with completion for a Python package ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python package help (RET for all): "
+		       (delq nil
+			     (mapcar
+			      #'(lambda (entry)
+				  (if (string-match "\\`Pkg-" entry)
+				      (list (substring entry (match-end 0)))))
+			      (mapcar 'car (cdr (assoc "modules" pydoc-alist)))))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "modules"))
+  (if (string-match "\\`Pkg-" argument)
+      (setq argument (substring argument (match-end 0))))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-topics (argument)
+  "Prompt with completion for a Python topic ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python topic help (RET for all): "
+		       (cdr (assoc "topics" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "topics")
+    (setq argument (upcase argument)))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-xrefs ()
+  "Display xref at point or prompt user with completion and display chosen xref.
+Xrefs are terms which follow the `pydoc-xrefs-prefix' regular expression."
+  (interactive)
+  (cond ((save-excursion
+	   (beginning-of-line)
+	   (looking-at pydoc-xrefs-prefix))
+	 ;; On an xref line
+	 (if (>= (point) (match-end 0))
+	     ;; After prefix, within an xref
+	     (pydoc-display-xref)
+	   ;; Prompt for with completion and display xref
+	   (pydoc-display-xref
+	    (save-excursion
+	      (goto-char (match-end 0))
+	      (pydoc-choose-xref "Display xref: ")))))
+
+	;; Move to last xref line if any in buffer
+	((pydoc-xrefs-p)
+	 ;; Prompt for with completion and display xref
+	 (pydoc-display-xref
+	  (save-excursion
+	    (goto-char (match-end 0))
+	    (pydoc-choose-xref "Display xref: "))))
+
+	(t (error "(pydoc): No cross-references in this buffer"))))
+
+;;; ************************************************************************
+;;; Public functions
+;;; ************************************************************************
+
+(defun pydoc-call (func-name argument buf-name-suffix)
+  "Call the pydoc function FUNC-NAME with ARGUMENT (a string) and display in Py: BUF-NAME-SUFFIX."
+  (let ((wind-config (current-window-configuration))
+	(output-buf-name
+	 (py-execute-string
+	  (format
+	   "if not vars().has_key('%s'):\n    from pydoc import %s\n\n%s(%s)\n"
+	   func-name func-name func-name argument)))
+	(async-process (pydoc-async-output-p))
+	input-buf-name)
+    (setq input-buf-name (if async-process
+			     (buffer-name (process-buffer async-process))
+			   " *Python Command*"))
+    (if (buffer-live-p (get-buffer input-buf-name))
+	(bury-buffer input-buf-name))
+
+    ;; current vintages of python-mode.el (4.6 at least)
+    ;; no longer return a buffer [name].  We get t from the
+    ;; final kill-buffer instead.  If we see t we use try to
+    ;; guess a good buffer name.
+    (if (eq output-buf-name t)
+	(setq output-buf-name (if async-process
+				  (buffer-name (process-buffer async-process))
+				"*Python Output*")))
+
+    (if (or (null output-buf-name)
+	    ;; In earlier versions of python-mode.el, py-execute-string does
+	    ;; not return a buffer name.
+	    (not (stringp output-buf-name))
+	    (not (buffer-live-p (get-buffer output-buf-name)))
+	    (and async-process (not (pydoc-wait-for-output input-buf-name 10.0))))
+	(message "(\"%s(%s)\" finished with no output)" func-name argument)
+      (set-window-configuration wind-config)
+      (bury-buffer output-buf-name)
+      (set-buffer output-buf-name)
+      (goto-char (point-max)) ;; User may have moved point elsewhere.
+      (let ((output-end 
+	     ;; Skip any trailing Python prompt
+	     (save-excursion (beginning-of-line) (point)))
+	    (output-start (pydoc-output-start))
+	    (display-buf))
+	(if (save-excursion
+	      (goto-char (point-max))
+	      (forward-line -1)
+	      (looking-at "^NameError:"))
+	    (progn (switch-to-buffer (car (buffer-list)))
+		   (error "(pydoc): %s(%s) failed to find any matching term"
+			  func-name argument))
+	  (setq display-buf (get-buffer-create
+			     (concat pydoc-buffer-prefix buf-name-suffix)))
+	  (set-buffer display-buf)
+	  (toggle-read-only 0)
+	  (erase-buffer)
+	  (insert-buffer-substring output-buf-name output-start output-end)
+	  (goto-char (point-min))
+	  (set-buffer-modified-p nil)
+	  (message "")
+	  (help-mode)
+	  (pydoc-kill-async-output output-buf-name async-process)
+	  (pop-to-buffer display-buf))))))
+
+(defun pydoc-display-apropos-entry ()
+  "Detect module/package names in pydoc apropos buffer entries and display their code.
+Each module/package name must be at the beginning of the line
+and must be followed by a space, dash and then another space."
+  (interactive)
+  (if (string-match (concat "\\`" (regexp-quote pydoc-buffer-prefix)
+			    "apropos ")
+		    (buffer-name))
+      (save-excursion
+	(beginning-of-line)
+	(if (looking-at "\\([^][-(){}<>'`\"/*+&^%$#@!=|?,~ \t\n\r]+\\) - ")
+	    (let* ((entry (buffer-substring
+			   (match-beginning 1) (match-end 1)))
+		   (path (pydoc-pathname entry)))
+	      (if (and path (file-exists-p path))
+		  (find-file-other-window path)))))))
+
+(defun pydoc-pathname (module-identifier)
+  "Return the filename or package directory where MODULE-IDENTIFIER is defined, else nil."
+  (setq module-identifier
+	(replace-in-string module-identifier "\\."
+			   (char-to-string directory-sep-char) t))
+  (or (locate-file module-identifier (pydoc-paths-list) ".py:.pyc:.pyo:.pyd")
+      ;; May be a package directory
+      (locate-data-directory module-identifier (pydoc-paths-list))))
+
+;;; ************************************************************************
+;;; Private functions
+;;; ************************************************************************
+
+(defun pydoc-commands-dialog-box (dialog-box)
+  "Prompt user with DIALOG-BOX and return selected value.
+Assumes caller has checked that `dialog-box' function exists."
+  (let ((echo-keystrokes 0)
+	event-obj
+	event)	 
+    ;; Add cmd-help and cancel buttons to dialog box.
+    (setq dialog-box (append dialog-box
+			     (list nil '["Cmd-Help" (pydoc-menu-help) t]
+				   '["Cancel" 'keyboard-quit t])))
+    (popup-dialog-box dialog-box)
+    (catch 'pydoc-done
+      (while t
+	(setq event (next-command-event event)
+	      event-obj (event-object event))
+	(cond ((and (menu-event-p event)
+		    (memq event-obj '(abort menu-no-selection-hook)))
+	       (signal 'quit nil))
+	      ((button-release-event-p event) ;; don't beep twice
+	       nil)
+	      ((menu-event-p event)
+	       (throw 'pydoc-done (eval event-obj)))
+	      (t
+	       (beep)
+	       (message "Please answer the dialog box.")))))))
+
+(defun pydoc-default-argument ()
+  "Return a default identifier argument near point."
+  (require 'etags)
+  ;; Include periods as symbol constituents but remove any trailing period.
+  (let* ((period-syntax (char-to-string (char-syntax ?\.)))
+	 (default (unwind-protect
+		      (progn
+			(modify-syntax-entry ?\. "_")
+			(find-tag-default))
+		    (modify-syntax-entry ?\. period-syntax))))
+    (if (and (stringp default) (string-match "\\.+\\'" default))
+	(setq default (substring default 0 (match-beginning 0))))
+    default))
+
+(defun pydoc-initialize()
+  (message "Please wait a moment while the Python help system is initialized...")
+  (let (output-buf)
+    (save-window-excursion
+      ;; Start a Python interpreter if not already running.
+      (py-shell)
+      (pydoc-wait-for-output (current-buffer) 3.0)
+      (setq output-buf
+	    (py-execute-string
+	     "if not vars().has_key('pydoc_lisp'):
+    import pydoc_lisp
+
+pydoc_lisp.pydoc_output_lisp()
+"))
+      ;; current vintages of python-mode.el (4.6 at least)
+      ;; no longer return a buffer [name].  We get t from the
+      ;; final kill-buffer instead.  If we see t we use the
+      ;; python shell's buffer.
+      (if (eq output-buf t)
+	  (setq output-buf 
+		(buffer-name (process-buffer (pydoc-async-output-p)))))
+
+      (setq pydoc-alist (pydoc-lisp-read-result output-buf)))
+    (if (member pydoc-alist '(nil None Traceback))
+	(progn 
+	  (setq pydoc-alist nil)
+	  (pop-to-buffer output-buf)
+	  (error "(pydoc): Initialization failed, Python did not output Lisp lists"))
+      (pydoc-kill-async-output output-buf (pydoc-async-output-p))
+      ;; Normalize Python search paths and make a regular list, not an alist
+      (let ((paths (assoc "paths" pydoc-alist)))
+	(setcdr paths (mapcar 'file-name-as-directory
+			      (mapcar 'car (cdr paths)))))
+      (message ""))))
+
+(defun pydoc-lisp-read-result (result-buf)
+  "Read and return the most recent python output in RESULT-BUF as a Lisp expression.
+If a timeout occurs before the expression is read, then return nil."
+  (save-excursion
+    (if (pydoc-wait-for-output result-buf 5.0)
+	(progn (goto-char (pydoc-output-start))
+	       (read (current-buffer)))
+      nil)))
+
+(defun pydoc-output-start ()
+  "Return the character position start of the most recent Python output."
+  (save-excursion
+    ;; Skip any trailing Python prompt
+    (forward-line 0) ;; to bol
+    (if (re-search-backward "^>>> " nil t)
+	(if (not (zerop (forward-line 1)))
+	    (goto-char (point-max)))
+      (goto-char (point-min)))
+    (point)))
+
+(defun pydoc-read-argument (prompt)
+  "Read and return a string argument using PROMPT."
+  (let* ((default (pydoc-default-argument))
+	 (argument
+	  (read-string
+	   (if default
+	       (format "%s(default %s) " prompt default)
+	     prompt))))
+    (if (member argument '(nil ""))
+	default
+      argument)))
+
+(defun pydoc-select-command ()
+  "Interactively select and return a pydoc command to run."
+  (let ((cmd-prompt)
+	(cmd)
+	;; Use dialog box if last user event involved the mouse.
+	(use-dialog-box (and (fboundp 'popup-dialog-box)
+			     (fboundp 'button-press-event-p)
+			     (or (button-press-event-p last-command-event)
+				 (button-release-event-p last-command-event)
+				 (menu-event-p last-command-event)))))
+    ;; Create a prompt numbering each command available.
+    (setq cmd-prompt
+	  (if use-dialog-box
+	      (mapcar
+	       #'(lambda (name-and-cmd)
+		   (vector (car name-and-cmd)
+			   (list 'quote (cdr name-and-cmd))
+			   't))
+	       pydoc-cmd-alist)
+	    (concat
+	     "Pydoc>  "
+	     (mapconcat 'identity (mapcar 'car pydoc-cmd-alist) "  ")
+	     ": ")))
+    ;; Prompt user.
+    (if use-dialog-box
+	(setq cmd (pydoc-commands-dialog-box
+		   (cons "Choose pydoc command (or choose Cmd-Help for help on commands): " cmd-prompt)))
+      ;; Otherwise, prompt in the minibuffer.
+      (let ((item-keys (mapcar #'(lambda (item) (aref item 0))
+			       (mapcar 'car pydoc-cmd-alist)))
+	    key)
+	(while (and (not (memq (setq key (upcase
+					  (string-to-char
+					   (read-from-minibuffer
+					    "" cmd-prompt pydoc-menu-mode-map))))
+			       item-keys))
+		    (not (memq key pydoc-menu-special-keys)))
+	  (beep)
+	  (discard-input))
+	(if (eq key ?\C-g)
+	    ;; abort
+	    (keyboard-quit))
+	(if (memq key pydoc-menu-special-keys)
+	    (setq cmd (pydoc-menu-help))
+	  (setq cmd (cdr (nth (- (length pydoc-cmd-alist)
+				 (length (memq key item-keys)))
+			      pydoc-cmd-alist))))))
+    cmd))
+
+;;; Asynchronous handling
+(defun pydoc-async-output-p ()
+  "Return the running asynchronous process for Python code evaluation or nil if none."
+  (let ((proc (and (stringp py-which-bufname)
+		   (get-process py-which-bufname))))
+    (and proc (eq (process-status proc) 'run) proc)))
+
+(defun pydoc-kill-async-output (output-buf async-process)
+  (if async-process
+      (progn
+	(set-buffer output-buf)
+	;; Remove output so it doesn't clog up the interpreter buffer.
+	(comint-kill-output))))
+
+(defun pydoc-wait-for-output (buffer timeout)
+  "Move to BUFFER and wait a maximum of TIMEOUT seconds or until Python command execution ends.
+Python command execution ends when Python returns a top-level prompt.
+Return t if waited less than TIMEOUT time (and thus received full output)."
+  (set-buffer buffer)
+  (goto-char (point-max)) ;; User may have moved point elsewhere.
+  (let ((time-waited 0.0)
+	(wait-time 0.1))
+    (while (and (< time-waited timeout)
+		(not (save-excursion
+		       (forward-line 0) ;; to bol
+		       (looking-at ">>> \\'"))))
+      (sleep-for wait-time)
+      (setq time-waited (+ time-waited wait-time)))
+    (< time-waited timeout)))
+
+
+;;; Cmd menu handling
+(defun pydoc-menu-enter (&optional char-str)
+  "Uses CHAR-STR or last input character as minibuffer argument."
+  (interactive)
+  (let ((input (or char-str (aref (recent-keys) (1- (length (recent-keys))))))
+	(case-fold-search t))
+    (cond
+     ;; GNU Emacs 19 or above
+     ((and (not (string-match "XEmacs" emacs-version))
+	   ;; Version 19 and above.
+	   (string-lessp "19" emacs-version))
+      (and (not (integerp input))
+	   (eventp input)
+	   (setq input (event-basic-type input))))
+     ((string-match "XEmacs" emacs-version)
+      (if (eventp input)
+	  (setq input (event-to-character input)))))
+    (erase-buffer)
+    (insert input))
+  (exit-minibuffer))
+
+(defun pydoc-menu-help ()
+  "Type one of the following characters:
+
+a   - A)propos <term>    - list modules/packages with <term> in their first line doc strings
+h   - H)elp <term>       - display doc for name <term> or string literal '<term>'
+k   - K)eyword <keyword> - with completion, display doc for a Python <keyword>
+m   - M)odule <name>     - with completion, display doc for a Python module <name>
+p   - P)ackage <name>    - with completion, display doc for a Python package <name>
+t   - T)opic <topic>     - with completion, display Python reference doc for <topic>
+x   - X)ref <term>       - with completion, display doc for a pydoc cross-reference
+
+?   - show this help
+C-g - abort from menu"
+  (interactive)
+  (save-window-excursion
+    (switch-to-buffer "*Help*")
+    (setq buffer-read-only nil)
+    (erase-buffer)
+    (insert (documentation 'pydoc-menu-help))
+    (goto-char (point-min))
+    (pydoc-select-command)))
+
+;;; Pathname handling
+(defun pydoc-paths-list ()
+  (cdr (assoc "paths" pydoc-alist)))
+
+
+;;; Xref handling
+(defun pydoc-choose-xref (prompt &optional xrefs-alist)
+  (or xrefs-alist (setq xrefs-alist (pydoc-xrefs-alist)))
+  (if (null xrefs-alist)
+      (error "(pydoc): No cross-references in this buffer")
+    (let ((completion-ignore-case t)
+	  (default (pydoc-default-argument))
+	  (result))
+      (if (not (assoc default xrefs-alist))
+	  (setq default nil))
+      (while (not result)
+	(setq result (completing-read
+		      (if default
+			  (format "%s(default %s) " prompt default)
+			prompt)
+		      xrefs-alist nil t))
+	(if (string-equal result "")
+	    (if default
+		(setq result default)
+	      (beep)
+	      (setq result nil))))
+      result)))
+
+(defun pydoc-delete-space (string)
+  "Delete any leading and trailing space from STRING and return the STRING."
+  (if (string-match "\\`[ \t\n\r\f]+" string)
+      (setq string (substring string (match-end 0))))
+  (if (string-match "[ \t\n\r\f]+\\'" string)
+      (setq string (substring string 0 (match-beginning 0))))
+  string)
+
+(defun pydoc-display-xref (&optional xref)
+  "Displays optional XREF (or prompts for and then displays it).
+Signals an error when there are no xrefs within the current buffer."
+  (interactive)
+  (if (member xref '(nil ""))
+      ;; Triggers an error if there are no xrefs.
+      (setq xref (pydoc-choose-xref "Display xref: ")))
+  (let ((case-fold-search nil))
+    (if (string-match "\\`[0-9A-Z_]+\\'" xref)
+	;; all uppercase, so is a topic
+	(pydoc-topics xref)
+      ;; assume is a module
+      (pydoc-modules xref))))
+
+(defun pydoc-xrefs-alist ()
+  ;; Assumes all xrefs are on a single line following point.
+  (mapcar #'(lambda (str) (list (pydoc-delete-space str)))
+	  (split-string (buffer-substring
+			 (point) (save-excursion (end-of-line) (point)))
+			",")))
+
+(defun pydoc-xrefs-p ()
+  "Return t if current buffer contains xrefs or nil otherwise.
+A call to \(match-end 0) returns the end of the xrefs-prefix."
+  (save-excursion
+    (goto-char (point-max))
+    (re-search-backward pydoc-xrefs-prefix nil t)))
+
+

pydoc.el.upstream

+;; LCD-ENTRY:    pydoc.el|Bob Weiner|bob@deepware.com|Interface to pydoc Python documentation viewer|Date|04/23/2001|01.02|www.deepware.com/pub/python
+;;
+;; FILE:         pydoc.el
+;; SUMMARY:      Interface to pydoc Python documentation viewer
+;; USAGE:        Autoloaded XEmacs Lisp Library, use {C-c M-h} to invoke
+;; KEYWORDS:     help, languages, oop, tools
+;;
+;; AUTHOR:       Bob Weiner
+;; ORG:          Deepware
+;; E-MAIL:       bob@deepware.com
+;;
+;; ORIG-DATE:    18-Apr-01 at 19:11:27
+;; LAST-MOD:     23-Apr-01 at 23:59:46 by Bob Weiner
+;;
+;; Copyright (C) 2001  Bob Weiner
+;; Licensed under the Python license version 2.0 or higher.
+;;
+;; This file is part of InfoDock, available from:
+;;   www.sourceforge.net/projects/infodock
+;;
+;; DESCRIPTION:
+;;
+;;   Globally adds key binding {C-c M-h} (pydoc-commands) which
+;;   displays a menu of commands for interacting with the pydoc Python
+;;   documentation viewer library.  See the documentation of
+;;   `pydoc-menu-help' for details on each available command.
+;;
+;;   NOTE: You *must* install the following for pydoc.el to work:
+;;
+;;     python-mode.el 4.1.1 or higher as your Python editing mode (included
+;;     in the pydoc.el distribution)
+;;
+;;     pydoc_lisp.py in your Python site-packages directory (unless
+;;       these functions are already integrated into pydoc.py)
+;;
+;;     set the environment variable PYTHONDOCS to the root directory
+;;       of your Python html documentation tree, for example:
+;;       export PYTHONDOCS=$HOME/Python-2.1/Doc/html/
+;;     and then startup your editor (otherwise, the environment variable
+;;     setting won't be inherited by the editor and some commands will not
+;;     work).
+;;
+;;   Install and byte-compile pydoc.el in one of your load-path directories
+;;   and then either set it to autoload or do a (require 'pydoc) in your
+;;   editor initialization file.  Then invoke it via the menu key binding.
+;;
+;; DESCRIP-END.
+
+;;; ************************************************************************
+;;; Other required Elisp libraries
+;;; ************************************************************************
+
+(require 'python-mode)
+
+;; Ensure that the user has a python-mode version which supports pydoc.el.
+(if (string-lessp py-version "$Revision$")
+    (error "(pydoc): you must upgrade from python-mode.el %s to 4.1.1 (or higher)"
+	   (if (string-match "[0-9.]+" py-version)
+	       (match-string 0 py-version) py-version)))
+
+(provide 'pydoc)
+
+;;; ************************************************************************
+;;; Public variables
+;;; ************************************************************************
+
+(defvar pydoc-version "01.01"
+  "Release version of the Emacs Lisp interface to pydoc.")
+
+;; Provide easy access to (pydoc-commands) everywhere since the user may want
+;; to reference Python doc when in a Python help buffer, a documentation file,
+;; etc.  Use {C-c M-h} instead of {C-c C-h} for this next binding since
+;; {C-c C-h} is an important key in InfoDock's outline-minor-mode which is
+;; often used under python-mode, so this avoids conflicts.
+
+;;;###autoload
+(global-set-key "\C-c\M-h" 'pydoc-commands)
+
+(defvar pydoc-buffer-prefix "Py: "
+  "Prefix string attached to all pydoc display buffers.")
+
+(defvar pydoc-xrefs-prefix "^Related help topics:"
+  "Prefix regexp output before comma separated pydoc help section names.")
+
+;;; ************************************************************************
+;;; Private variables
+;;; ************************************************************************
+
+(defvar pydoc-cmd-alist
+  '(("A)propos"         . pydoc-apropos)
+    ("H)elp"            . pydoc-help)
+    ("K)eyword"         . pydoc-keywords)
+    ("M)odule"          . pydoc-modules)
+    ("P)ackage"         . pydoc-packages)
+    ("T)opic"           . pydoc-topics)
+    ("X)ref"            . pydoc-xrefs))
+  "Association list of (HELP-CMD-PROMPT . CMD) elements for pydoc commands.")
+
+(defvar pydoc-alist nil
+  "Association list of (list-name . alist) elements used to build prompt completion tables.")
+
+(defvar pydoc-menu-mode-map nil
+  "Keymap containing pydoc-menu commands.")
+
+(defvar pydoc-menu-special-keys '(?\C-g ?? ?\C-i ?\C-j ?\C-m ?\ ))
+
+(if pydoc-menu-mode-map
+    nil
+  (setq pydoc-menu-mode-map (make-keymap))
+  (suppress-keymap pydoc-menu-mode-map)
+  (define-key pydoc-menu-mode-map
+    (car (where-is-internal 'keyboard-quit)) 'pydoc-menu-enter)
+  (mapcar #'(lambda (key)
+	      (define-key pydoc-menu-mode-map (char-to-string key) 'pydoc-menu-enter))
+	  pydoc-menu-special-keys)
+  (let ((i 33))
+    (while (<= i 127)
+      (define-key pydoc-menu-mode-map (char-to-string i) 'pydoc-menu-enter)
+      (setq i (1+ i)))))
+
+;;; ************************************************************************
+;;; Commands
+;;; ************************************************************************
+
+;;;###autoload
+(defun pydoc-commands (&optional init-flag)
+  "Display a menu of commands for interacting with the pydoc Python documentation viewer library.
+With optional prefix arg INIT-FLAG, reinitializes the pydoc completion
+tables which includes the list of available Python modules.
+See the documentation for `pydoc-menu-help' for a description of the
+available commands."
+  (interactive "P")
+  (if (or init-flag (null pydoc-alist))
+      (pydoc-initialize))
+  (call-interactively (pydoc-select-command)))
+
+;;;###autoload
+(defun pydoc-apropos (&optional argument)
+  "Call the Python module apropos function with optional ARGUMENT and display the output.
+ARGUMENT defaults to an identifier near point.
+The apropos function finds matches for ARGUMENT within the first line of
+module or package doc strings."
+  (interactive)
+  (if (not argument)
+      (setq argument (pydoc-read-argument "Python module/package apropos: ")))
+  (pydoc-call "apropos" (format "'%s'" argument) (concat "apropos " argument)))
+
+;;;###autoload
+(defun pydoc-help (&optional argument)
+  "Call the Python help function with optional ARGUMENT and display the output.
+ARGUMENT defaults to an identifier near point.
+ARGUMENT is resolved as a name in any present Python namespace; use
+single 'quotes' to send ARGUMENT as a Python literal string."
+  (interactive)
+  (if (not argument)
+      (setq argument (pydoc-read-argument "Python help (name or 'string'): ")))
+  (pydoc-call "help" argument argument))
+
+;;;###autoload
+(defun pydoc-keywords (argument)
+  "Prompt with completion for a Python keyword ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python keyword help (RET for all): "
+		       (cdr (assoc "keywords" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "keywords"))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-modules (argument)
+  "Prompt with completion for a Python module/package ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python module/package help (RET for all): "
+		       (cdr (assoc "modules" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "modules"))
+  (if (string-match "\\`Pkg-" argument)
+      (setq argument (substring argument (match-end 0))))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-packages (argument)
+  "Prompt with completion for a Python package ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python package help (RET for all): "
+		       (delq nil
+			     (mapcar
+			      #'(lambda (entry)
+				  (if (string-match "\\`Pkg-" entry)
+				      (list (substring entry (match-end 0)))))
+			      (mapcar 'car (cdr (assoc "modules" pydoc-alist)))))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "modules"))
+  (if (string-match "\\`Pkg-" argument)
+      (setq argument (substring argument (match-end 0))))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-topics (argument)
+  "Prompt with completion for a Python topic ARGUMENT and display its documentation."
+  (interactive
+   (list
+    (let ((completion-ignore-case t))
+      (completing-read "Python topic help (RET for all): "
+		       (cdr (assoc "topics" pydoc-alist))
+		       nil t))))
+  (if (member argument '(nil ""))
+      (setq argument "topics")
+    (setq argument (upcase argument)))
+  (pydoc-call "help" (format "'%s'" argument) argument))
+
+;;;###autoload
+(defun pydoc-xrefs ()
+  "Display xref at point or prompt user with completion and display chosen xref.
+Xrefs are terms which follow the `pydoc-xrefs-prefix' regular expression."
+  (interactive)
+  (cond ((save-excursion
+	   (beginning-of-line)
+	   (looking-at pydoc-xrefs-prefix))
+	 ;; On an xref line
+	 (if (>= (point) (match-end 0))
+	     ;; After prefix, within an xref
+	     (pydoc-display-xref)
+	   ;; Prompt for with completion and display xref
+	   (pydoc-display-xref
+	    (save-excursion
+	      (goto-char (match-end 0))
+	      (pydoc-choose-xref "Display xref: ")))))
+
+	;; Move to last xref line if any in buffer
+	((pydoc-xrefs-p)
+	 ;; Prompt for with completion and display xref
+	 (pydoc-display-xref
+	  (save-excursion
+	    (goto-char (match-end 0))
+	    (pydoc-choose-xref "Display xref: "))))
+
+	(t (error "(pydoc): No cross-references in this buffer"))))
+
+;;; ************************************************************************
+;;; Public functions
+;;; ************************************************************************
+
+(defun pydoc-call (func-name argument buf-name-suffix)
+  "Call the pydoc function FUNC-NAME with ARGUMENT (a string) and display in Py: BUF-NAME-SUFFIX."
+  (let ((wind-config (current-window-configuration))
+	(output-buf-name
+	 (py-execute-string
+	  (format
+	   "if not vars().has_key('%s'):\n    from pydoc import %s\n\n%s(%s)\n"
+	   func-name func-name func-name argument)))
+	(async-process (pydoc-async-output-p))
+	input-buf-name)
+    (setq input-buf-name (if async-process
+			     (buffer-name (process-buffer async-process))
+			   " *Python Command*"))
+    (if (buffer-live-p (get-buffer input-buf-name))
+	(bury-buffer input-buf-name))
+    (if (or (null output-buf-name)
+	    ;; In earlier versions of python-mode.el, py-execute-string does
+	    ;; not return a buffer name.
+	    (not (stringp output-buf-name))
+	    (not (buffer-live-p (get-buffer output-buf-name)))
+	    (and async-process (not (pydoc-wait-for-output input-buf-name 10.0))))
+	(message "(\"%s(%s)\" finished with no output)" func-name argument)
+      (set-window-configuration wind-config)
+      (bury-buffer output-buf-name)
+      (set-buffer output-buf-name)
+      (goto-char (point-max)) ;; User may have moved point elsewhere.
+      (let ((output-end 
+	     ;; Skip any trailing Python prompt
+	     (save-excursion (beginning-of-line) (point)))
+	    (output-start (pydoc-output-start))
+	    (display-buf))
+	(if (save-excursion
+	      (goto-char (point-max))
+	      (forward-line -1)
+	      (looking-at "^NameError:"))
+	    (progn (switch-to-buffer (car (buffer-list)))
+		   (error "(pydoc): %s(%s) failed to find any matching term"
+			  func-name argument))
+	  (setq display-buf (get-buffer-create
+			     (concat pydoc-buffer-prefix buf-name-suffix)))
+	  (set-buffer display-buf)
+	  (toggle-read-only 0)
+	  (erase-buffer)
+	  (insert-buffer-substring output-buf-name output-start output-end)
+	  (goto-char (point-min))
+	  (set-buffer-modified-p nil)
+	  (message "")
+	  (help-mode)
+	  (pydoc-kill-async-output output-buf-name async-process)
+	  (pop-to-buffer display-buf))))))
+
+(defun pydoc-display-apropos-entry ()
+  "Detect module/package names in pydoc apropos buffer entries and display their code.
+Each module/package name must be at the beginning of the line
+and must be followed by a space, dash and then another space."
+  (interactive)
+  (if (string-match (concat "\\`" (regexp-quote pydoc-buffer-prefix)
+			    "apropos ")
+		    (buffer-name))
+      (save-excursion
+	(beginning-of-line)
+	(if (looking-at "\\([^][-(){}<>'`\"/*+&^%$#@!=|?,~ \t\n\r]+\\) - ")
+	    (let* ((entry (buffer-substring
+			   (match-beginning 1) (match-end 1)))
+		   (path (pydoc-pathname entry)))
+	      (if (and path (file-exists-p path))
+		  (find-file-other-window path)))))))
+
+(defun pydoc-pathname (module-identifier)
+  "Return the filename or package directory where MODULE-IDENTIFIER is defined, else nil."
+  (setq module-identifier
+	(replace-in-string module-identifier "\\."
+			   (char-to-string directory-sep-char) t))
+  (or (locate-file module-identifier (pydoc-paths-list) ".py:.pyc:.pyo:.pyd")
+      ;; May be a package directory
+      (locate-data-directory module-identifier (pydoc-paths-list))))
+
+;;; ************************************************************************
+;;; Private functions
+;;; ************************************************************************
+
+(defun pydoc-commands-dialog-box (dialog-box)
+  "Prompt user with DIALOG-BOX and return selected value.
+Assumes caller has checked that `dialog-box' function exists."
+  (let ((echo-keystrokes 0)
+	event-obj
+	event)	 
+    ;; Add cmd-help and cancel buttons to dialog box.
+    (setq dialog-box (append dialog-box
+			     (list nil '["Cmd-Help" (pydoc-menu-help) t]
+				   '["Cancel" 'keyboard-quit t])))
+    (popup-dialog-box dialog-box)
+    (catch 'pydoc-done
+      (while t
+	(setq event (next-command-event event)
+	      event-obj (event-object event))
+	(cond ((and (menu-event-p event)
+		    (memq event-obj '(abort menu-no-selection-hook)))
+	       (signal 'quit nil))
+	      ((button-release-event-p event) ;; don't beep twice
+	       nil)
+	      ((menu-event-p event)
+	       (throw 'pydoc-done (eval event-obj)))
+	      (t
+	       (beep)
+	       (message "Please answer the dialog box.")))))))
+
+(defun pydoc-default-argument ()
+  "Return a default identifier argument near point."
+  (require 'etags)
+  ;; Include periods as symbol constituents but remove any trailing period.
+  (let* ((period-syntax (char-to-string (char-syntax ?\.)))
+	 (default (unwind-protect
+		      (progn
+			(modify-syntax-entry ?\. "_")
+			(find-tag-default))
+		    (modify-syntax-entry ?\. period-syntax))))
+    (if (and (stringp default) (string-match "\\.+\\'" default))
+	(setq default (substring default 0 (match-beginning 0))))
+    default))
+
+(defun pydoc-initialize()
+  (message "Please wait a moment while the Python help system is initialized...")
+  (let (output-buf)
+    (save-window-excursion
+      ;; Start a Python interpreter if not already running.
+      (py-shell)
+      (pydoc-wait-for-output (current-buffer) 3.0)
+      (setq output-buf
+	    (py-execute-string
+	     "if not vars().has_key('pydoc_lisp'):
+    import pydoc_lisp
+
+pydoc_lisp.pydoc_output_lisp()
+"))
+      (setq pydoc-alist (pydoc-lisp-read-result output-buf)))
+    (if (member pydoc-alist '(nil None Traceback))
+	(progn 
+	  (setq pydoc-alist nil)
+	  (pop-to-buffer output-buf)
+	  (error "(pydoc): Initialization failed, Python did not output Lisp lists"))
+      (pydoc-kill-async-output output-buf (pydoc-async-output-p))
+      ;; Normalize Python search paths and make a regular list, not an alist
+      (let ((paths (assoc "paths" pydoc-alist)))
+	(setcdr paths (mapcar 'file-name-as-directory
+			      (mapcar 'car (cdr paths)))))
+      (message ""))))
+
+(defun pydoc-lisp-read-result (result-buf)
+  "Read and return the most recent python output in RESULT-BUF as a Lisp expression.
+If a timeout occurs before the expression is read, then return nil."
+  (save-excursion
+    (if (pydoc-wait-for-output result-buf 5.0)
+	(progn (goto-char (pydoc-output-start))
+	       (read (current-buffer)))
+      nil)))
+
+(defun pydoc-output-start ()
+  "Return the character position start of the most recent Python output."
+  (save-excursion
+    ;; Skip any trailing Python prompt
+    (forward-line 0) ;; to bol
+    (if (re-search-backward "^>>> " nil t)
+	(if (not (zerop (forward-line 1)))
+	    (goto-char (point-max)))
+      (goto-char (point-min)))
+    (point)))
+
+(defun pydoc-read-argument (prompt)
+  "Read and return a string argument using PROMPT."
+  (let* ((default (pydoc-default-argument))
+	 (argument
+	  (read-string
+	   (if default
+	       (format "%s(default %s) " prompt default)
+	     prompt))))
+    (if (member argument '(nil ""))
+	default
+      argument)))
+
+(defun pydoc-select-command ()
+  "Interactively select and return a pydoc command to run."
+  (let ((cmd-prompt)
+	(cmd)
+	;; Use dialog box if last user event involved the mouse.
+	(use-dialog-box (and (fboundp 'popup-dialog-box)
+			     (fboundp 'button-press-event-p)
+			     (or (button-press-event-p last-command-event)
+				 (button-release-event-p last-command-event)
+				 (menu-event-p last-command-event)))))
+    ;; Create a prompt numbering each command available.
+    (setq cmd-prompt
+	  (if use-dialog-box
+	      (mapcar
+	       #'(lambda (name-and-cmd)
+		   (vector (car name-and-cmd)
+			   (list 'quote (cdr name-and-cmd))
+			   't))
+	       pydoc-cmd-alist)
+	    (concat
+	     "Pydoc>  "
+	     (mapconcat 'identity (mapcar 'car pydoc-cmd-alist) "  ")
+	     ": ")))
+    ;; Prompt user.
+    (if use-dialog-box
+	(setq cmd (pydoc-commands-dialog-box
+		   (cons "Choose pydoc command (or choose Cmd-Help for help on commands): " cmd-prompt)))
+      ;; Otherwise, prompt in the minibuffer.
+      (let ((item-keys (mapcar #'(lambda (item) (aref item 0))
+			       (mapcar 'car pydoc-cmd-alist)))
+	    key)
+	(while (and (not (memq (setq key (upcase
+					  (string-to-char
+					   (read-from-minibuffer
+					    "" cmd-prompt pydoc-menu-mode-map))))
+			       item-keys))
+		    (not (memq key pydoc-menu-special-keys)))
+	  (beep)
+	  (discard-input))
+	(if (eq key ?\C-g)
+	    ;; abort
+	    (keyboard-quit))
+	(if (memq key pydoc-menu-special-keys)
+	    (setq cmd (pydoc-menu-help))
+	  (setq cmd (cdr (nth (- (length pydoc-cmd-alist)
+				 (length (memq key item-keys)))
+			      pydoc-cmd-alist))))))
+    cmd))
+
+;;; Asynchronous handling
+(defun pydoc-async-output-p ()
+  "Return the running asynchronous process for Python code evaluation or nil if none."
+  (let ((proc (and (stringp py-which-bufname)
+		   (get-process py-which-bufname))))
+    (and proc (eq (process-status proc) 'run) proc)))
+
+(defun pydoc-kill-async-output (output-buf async-process)
+  (if async-process
+      (progn
+	(set-buffer output-buf)
+	;; Remove output so it doesn't clog up the interpreter buffer.
+	(comint-kill-output))))
+
+(defun pydoc-wait-for-output (buffer timeout)
+  "Move to BUFFER and wait a maximum of TIMEOUT seconds or until Python command execution ends.
+Python command execution ends when Python returns a top-level prompt.
+Return t if waited less than TIMEOUT time (and thus received full output)."
+  (set-buffer buffer)
+  (goto-char (point-max)) ;; User may have moved point elsewhere.
+  (let ((time-waited 0.0)
+	(wait-time 0.1))
+    (while (and (< time-waited timeout)
+		(not (save-excursion
+		       (forward-line 0) ;; to bol
+		       (looking-at ">>> \\'"))))
+      (sleep-for wait-time)
+      (setq time-waited (+ time-waited wait-time)))
+    (< time-waited timeout)))
+
+
+;;; Cmd menu handling
+(defun pydoc-menu-enter (&optional char-str)
+  "Uses CHAR-STR or last input character as minibuffer argument."
+  (interactive)
+  (let ((input (or char-str (aref (recent-keys) (1- (length (recent-keys))))))
+	(case-fold-search t))
+    (cond
+     ;; GNU Emacs 19 or above
+     ((and (not (string-match "XEmacs" emacs-version))
+	   ;; Version 19 and above.
+	   (string-lessp "19" emacs-version))
+      (and (not (integerp input))
+	   (eventp input)
+	   (setq input (event-basic-type input))))
+     ((string-match "XEmacs" emacs-version)
+      (if (eventp input)
+	  (setq input (event-to-character input)))))
+    (erase-buffer)
+    (insert input))
+  (exit-minibuffer))
+
+(defun pydoc-menu-help ()
+  "Type one of the following characters:
+
+a   - A)propos <term>    - list modules/packages with <term> in their first line doc strings
+h   - H)elp <term>       - display doc for name <term> or string literal '<term>'
+k   - K)eyword <keyword> - with completion, display doc for a Python <keyword>
+m   - M)odule <name>     - with completion, display doc for a Python module <name>
+p   - P)ackage <name>    - with completion, display doc for a Python package <name>
+t   - T)opic <topic>     - with completion, display Python reference doc for <topic>
+x   - X)ref <term>       - with completion, display doc for a pydoc cross-reference
+
+?   - show this help
+C-g - abort from menu"
+  (interactive)
+  (save-window-excursion
+    (switch-to-buffer "*Help*")
+    (setq buffer-read-only nil)
+    (erase-buffer)
+    (insert (documentation 'pydoc-menu-help))
+    (goto-char (point-min))
+    (pydoc-select-command)))
+
+;;; Pathname handling
+(defun pydoc-paths-list ()
+  (cdr (assoc "paths" pydoc-alist)))
+
+
+;;; Xref handling
+(defun pydoc-choose-xref (prompt &optional xrefs-alist)
+  (or xrefs-alist (setq xrefs-alist (pydoc-xrefs-alist)))
+  (if (null xrefs-alist)
+      (error "(pydoc): No cross-references in this buffer")
+    (let ((completion-ignore-case t)
+	  (default (pydoc-default-argument))
+	  (result))
+      (if (not (assoc default xrefs-alist))
+	  (setq default nil))
+      (while (not result)
+	(setq result (completing-read
+		      (if default
+			  (format "%s(default %s) " prompt default)
+			prompt)
+		      xrefs-alist nil t))
+	(if (string-equal result "")
+	    (if default
+		(setq result default)
+	      (beep)
+	      (setq result nil))))
+      result)))
+
+(defun pydoc-delete-space (string)
+  "Delete any leading and trailing space from STRING and return the STRING."
+  (if (string-match "\\`[ \t\n\r\f]+" string)
+      (setq string (substring string (match-end 0))))
+  (if (string-match "[ \t\n\r\f]+\\'" string)
+      (setq string (substring string 0 (match-beginning 0))))
+  string)
+
+(defun pydoc-display-xref (&optional xref)
+  "Displays optional XREF (or prompts for and then displays it).
+Signals an error when there are no xrefs within the current buffer."
+  (interactive)
+  (if (member xref '(nil ""))
+      ;; Triggers an error if there are no xrefs.
+      (setq xref (pydoc-choose-xref "Display xref: ")))
+  (let ((case-fold-search nil))
+    (if (string-match "\\`[0-9A-Z_]+\\'" xref)
+	;; all uppercase, so is a topic
+	(pydoc-topics xref)
+      ;; assume is a module
+      (pydoc-modules xref))))
+
+(defun pydoc-xrefs-alist ()
+  ;; Assumes all xrefs are on a single line following point.
+  (mapcar #'(lambda (str) (list (pydoc-delete-space str)))
+	  (split-string (buffer-substring
+			 (point) (save-excursion (end-of-line) (point)))
+			",")))
+
+(defun pydoc-xrefs-p ()
+  "Return t if current buffer contains xrefs or nil otherwise.
+A call to \(match-end 0) returns the end of the xrefs-prefix."
+  (save-excursion
+    (goto-char (point-max))
+    (re-search-backward pydoc-xrefs-prefix nil t)))
+
+
+#!/usr/bin/env python
+# -*- Mode: Python; tab-width: 4 -*-
+#
+# SUMMARY:      Produces Lisp lists of Python paths, pydoc keywords, modules and help topics.
+# USAGE:        l = Pydoc_Lisp()
+# KEYWORDS:     doc, emacs, lisp, pydoc
+#
+# AUTHOR:       Bob Weiner
+# ORG:          Deepware
+#
+# ORIG-DATE:    18-Apr-01 at 12:08:46
+# LAST-MOD:     22-Apr-01 at 11:03:03 by Bob Weiner
+#
+# COPYRIGHT:    Copyright (C) 2001  Bob Weiner
+#   Available for use and distribution under the terms of the Python license 2.0 or greater.
+#
+# DESCRIPTION:  
+"""
+Produces Lisp lists of Python paths, pydoc keywords, modules and help topics.
+See the doc for class Pydoc_Lisp for details.  This provides the interface from
+pydoc to the Emacs Lisp pydoc commands.
+"""
+# DESCRIP-END.
+
+## ------------------------------------------------------------------------
+## Required modules
+## ------------------------------------------------------------------------
+
+from string import find, join
+import pydoc
+import sys
+
+## ------------------------------------------------------------------------
+## Globals
+## ------------------------------------------------------------------------
+
+global pydoc_lisp_alist
+
+def pydoc_output_lisp():
+    try:
+        if isinstance(pydoc_lisp_alist, Pydoc_Lisp):
+            # Reinitialize the lists
+            pydoc_lisp_alist.__init__()
+        else:
+            pydoc_lisp_alist = Pydoc_Lisp()
+    except NameError:
+        pydoc_lisp_alist = Pydoc_Lisp()
+
+
+## ------------------------------------------------------------------------
+## Classes
+## ------------------------------------------------------------------------
+
+# This is defined as a class so that it may be easily added to pydoc.py
+# rather than keeping it in this separate module.
+class Pydoc_Lisp:
+    """
+    Produces Lisp lists of Python paths, pydoc keywords, modules and help topics.
+    Results are stored in the class variables: keywords, modules, topics
+    and alist, the latter being an association list containing each of the former
+    three values.  An instance prints as the value of `alist'.  Call self.__init__()
+    if there is a need to reset the value of the module list.
+    """
+
+    ## Class variables
+    keywords = modules = paths = topics = alist = None
+
+    def __init__(self):
+        Pydoc_Lisp.keywords = self._dict_to_lisp_list(pydoc.Helper.keywords)
+        Pydoc_Lisp.modules = self._get_modules_lisp()
+        Pydoc_Lisp.paths = self._get_paths_lisp()
+        Pydoc_Lisp.topics = self._dict_to_lisp_list(pydoc.Helper.topics)
+        Pydoc_Lisp.alist = '(("keywords" . %s)\n ("modules" . %s)\n ("paths" . %s)\n ("topics" . %s))' \
+                           % (Pydoc_Lisp.keywords, Pydoc_Lisp.modules, \
+                              Pydoc_Lisp.paths, Pydoc_Lisp.topics)
+        # Print the alist so the Lisp reader can evaluate it.
+        print Pydoc_Lisp.alist
+
+    def __str__(self):
+        return Pydoc_Lisp.alist
+
+    def _dict_to_lisp_list(self, dict):
+        keys = dict.keys()
+        keys.sort()
+        return '(("%s"))\n' % join(keys, '") ("')
+
+    def _get_modules_lisp(self):
+        "Return a Lisp list of available Python module and package names."
+        module_dict = {}
+
+        def callback(path, modname, desc, module_dict=module_dict):
+            if modname and modname[-9:] == '.__init__':
+                modname = 'Pkg-' + modname[:-9]
+            if find(modname, '.') < 0:
+                module_dict[modname] = 1
+
+        pydoc.ModuleScanner().run(callback)
+        return self._dict_to_lisp_list(module_dict)
+
+    def _get_paths_lisp(self):
+        paths = sys.path[:]
+        try:
+            paths[paths.index('')] = '.'
+        except ValueError:
+            pass
+        return '(("%s"))\n' % join(paths, '") ("')
+
+## ------------------------------------------------------------------------
+## Program execution
+## ------------------------------------------------------------------------
+
+if __name__ == '__main__':
+    l = Pydoc_Lisp()
+;;; python-mode.el --- Major mode for editing Python programs
+
+;; Copyright (C) 1992,1993,1994  Tim Peters
+
+;; Author: 1995-2001 Barry A. Warsaw
+;;         1992-1994 Tim Peters
+;; Maintainer: python-mode@python.org
+;; Created:    Feb 1992
+;; Keywords:   python languages oop
+
+(defconst py-version "4.6"
+  "`python-mode' version number.")
+
+;; This software is provided as-is, without express or implied
+;; warranty.  Permission to use, copy, modify, distribute or sell this
+;; software, without fee, for any purpose and by any individual or
+;; organization, is hereby granted, provided that the above copyright
+;; notice and this paragraph appear in all copies.
+
+;;; Commentary:
+
+;; This is a major mode for editing Python programs.  It was developed
+;; by Tim Peters after an original idea by Michael A. Guravage.  Tim
+;; subsequently left the net; in 1995, Barry Warsaw inherited the mode
+;; and is the current maintainer.  Tim's now back but disavows all
+;; responsibility for the mode.  Smart Tim :-)
+
+;; pdbtrack support contributed by Ken Manheimer, April 2001.
+
+;; This version of python-mode.el has only been tested with XEmacs
+;; 21.1.14 and Emacs 20.7 as these are the latest versions of these
+;; Emacsen as of this writing (11-Apr-2001).  I have no intent to test
+;; it with earlier Emacsen, but I will accept patches if they are
+;; small and reasonable.  Please use the SourceForge Python project to
+;; submit bugs or patches:
+;;
+;;     http://sourceforge.net/projects/python
+
+;; FOR MORE INFORMATION:
+
+;; There is some information on python-mode.el at
+
+;;     http://www.python.org/emacs/python-mode/
+;;
+;; but this link is fairly out of date, due to the current difficulty
+;; in updating that site. It does contain links to other packages that
+;; you might find useful, such as pdb interfaces, OO-Browser links,
+;; etc.  Eventually, we'll be able to update it much more easily.
+
+;; BUG REPORTING:
+
+;; As mentioned above, please use the SourceForge Python project for
+;; submitting bug reports or patches.  The old recommendation, to use
+;; C-c C-b will still work, but those reports have a higher chance of
+;; getting buried in my mailbox.  Please include a complete, but
+;; concise code sample and a recipe for reproducing the bug.  Send
+;; suggestions and other comments to python-mode@python.org.
+
+;; When in a Python mode buffer, do a C-h m for more help.  It's
+;; doubtful that a texinfo manual would be very useful, but if you
+;; want to contribute one, I'll certainly accept it!
+
+;;; Code:
+
+(require 'comint)
+(require 'custom)
+(require 'cl)
+
+
+;; user definable variables
+;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
+
+(defgroup python nil
+  "Support for the Python programming language, <http://www.python.org/>"
+  :group 'languages
+  :prefix "py-")
+
+(defcustom py-python-command "python"
+  "*Shell command used to start Python interpreter."
+  :type 'string
+  :group 'python)
+
+(defcustom py-jpython-command "jpython"
+  "*Shell command used to start the JPython interpreter."
+  :type 'string
+  :group 'python
+  :tag "JPython Command")
+
+(defcustom py-default-interpreter 'cpython
+  "*Which Python interpreter is used by default.
+The value for this variable can be either `cpython' or `jpython'.
+
+When the value is `cpython', the variables `py-python-command' and
+`py-python-command-args' are consulted to determine the interpreter
+and arguments to use.
+
+When the value is `jpython', the variables `py-jpython-command' and
+`py-jpython-command-args' are consulted to determine the interpreter
+and arguments to use.
+
+Note that this variable is consulted only the first time that a Python
+mode buffer is visited during an Emacs session.  After that, use
+\\[py-toggle-shells] to change the interpreter shell."
+  :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
+		 (const :tag "JPython" jpython))
+  :group 'python)
+
+(defcustom py-python-command-args '("-i")
+  "*List of string arguments to be used when starting a Python shell."
+  :type '(repeat string)
+  :group 'python)
+
+(defcustom py-jpython-command-args '("-i")
+  "*List of string arguments to be used when starting a JPython shell."
+  :type '(repeat string)
+  :group 'python
+  :tag "JPython Command Args")
+
+(defcustom py-indent-offset 4
+  "*Amount of offset per level of indentation.
+`\\[py-guess-indent-offset]' can usually guess a good value when
+you're editing someone else's Python code."
+  :type 'integer
+  :group 'python)
+
+(defcustom py-continuation-offset 4
+  "*Additional amount of offset to give for some continuation lines.
+Continuation lines are those that immediately follow a backslash
+terminated line.  Only those continuation lines for a block opening
+statement are given this extra offset."
+  :type 'integer
+  :group 'python)
+
+(defcustom py-smart-indentation t
+  "*Should `python-mode' try to automagically set some indentation variables?
+When this variable is non-nil, two things happen when a buffer is set
+to `python-mode':
+
+    1. `py-indent-offset' is guessed from existing code in the buffer.
+       Only guessed values between 2 and 8 are considered.  If a valid
+       guess can't be made (perhaps because you are visiting a new
+       file), then the value in `py-indent-offset' is used.
+
+    2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
+       equal `tab-width' (`indent-tabs-mode' is never turned on by
+       Python mode).  This means that for newly written code, tabs are
+       only inserted in indentation if one tab is one indentation
+       level, otherwise only spaces are used.
+
+Note that both these settings occur *after* `python-mode-hook' is run,
+so if you want to defeat the automagic configuration, you must also
+set `py-smart-indentation' to nil in your `python-mode-hook'."
+  :type 'boolean
+  :group 'python)
+
+(defcustom py-align-multiline-strings-p t
+  "*Flag describing how multi-line triple quoted strings are aligned.
+When this flag is non-nil, continuation lines are lined up under the
+preceding line's indentation.  When this flag is nil, continuation
+lines are aligned to column zero."
+  :type '(choice (const :tag "Align under preceding line" t)
+		 (const :tag "Align to column zero" nil))
+  :group 'python)
+
+(defcustom py-block-comment-prefix "##"
+  "*String used by \\[comment-region] to comment out a block of code.
+This should follow the convention for non-indenting comment lines so
+that the indentation commands won't get confused (i.e., the string
+should be of the form `#x...' where `x' is not a blank or a tab, and
+`...' is arbitrary).  However, this string should not end in whitespace."
+  :type 'string
+  :group 'python)
+
+(defcustom py-honor-comment-indentation t
+  "*Controls how comment lines influence subsequent indentation.
+
+When nil, all comment lines are skipped for indentation purposes, and
+if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
+
+When t, lines that begin with a single `#' are a hint to subsequent
+line indentation.  If the previous line is such a comment line (as
+opposed to one that starts with `py-block-comment-prefix'), then its
+indentation is used as a hint for this line's indentation.  Lines that
+begin with `py-block-comment-prefix' are ignored for indentation
+purposes.
+
+When not nil or t, comment lines that begin with a `#' are used as
+indentation hints, unless the comment character is in column zero."
+  :type '(choice
+	  (const :tag "Skip all comment lines (fast)" nil)
+	  (const :tag "Single # `sets' indentation for next line" t)
+	  (const :tag "Single # `sets' indentation except at column zero"
+		 other)
+	  )
+  :group 'python)
+
+(defcustom py-temp-directory
+  (let ((ok '(lambda (x)
+	       (and x
+		    (setq x (expand-file-name x)) ; always true
+		    (file-directory-p x)
+		    (file-writable-p x)
+		    x))))
+    (or (funcall ok (getenv "TMPDIR"))
+	(funcall ok "/usr/tmp")
+	(funcall ok "/tmp")
+	(funcall ok  ".")
+	(error
+	 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
+  "*Directory used for temp files created by a *Python* process.
+By default, the first directory from this list that exists and that you
+can write into:  the value (if any) of the environment variable TMPDIR,
+/usr/tmp, /tmp, or the current directory."
+  :type 'string
+  :group 'python)
+
+(defcustom py-beep-if-tab-change t
+  "*Ring the bell if `tab-width' is changed.
+If a comment of the form
+
+  \t# vi:set tabsize=<number>:
+
+is found before the first code line when the file is entered, and the
+current value of (the general Emacs variable) `tab-width' does not
+equal <number>, `tab-width' is set to <number>, a message saying so is
+displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
+the Emacs bell is also rung as a warning."
+  :type 'boolean
+  :group 'python)
+
+(defcustom py-jump-on-exception t
+  "*Jump to innermost exception frame in *Python Output* buffer.
+When this variable is non-nil and an exception occurs when running
+Python code synchronously in a subprocess, jump immediately to the
+source code of the innermost traceback frame."
+  :type 'boolean
+  :group 'python)
+
+(defcustom py-ask-about-save t
+  "If not nil, ask about which buffers to save before executing some code.
+Otherwise, all modified buffers are saved without asking."
+  :type 'boolean
+  :group 'python)
+
+(defcustom py-backspace-function 'backward-delete-char-untabify
+  "*Function called by `py-electric-backspace' when deleting backwards."
+  :type 'function
+  :group 'python)
+
+(defcustom py-delete-function 'delete-char
+  "*Function called by `py-electric-delete' when deleting forwards."
+  :type 'function
+  :group 'python)
+
+(defcustom py-imenu-show-method-args-p nil 
+  "*Controls echoing of arguments of functions & methods in the Imenu buffer.
+When non-nil, arguments are printed."
+  :type 'boolean
+  :group 'python)
+(make-variable-buffer-local 'py-indent-offset)
+
+(defcustom py-pdbtrack-do-tracking-p t
+  "*Controls whether the pdbtrack feature is enabled or not.
+When non-nil, pdbtrack is enabled in all comint-based buffers,
+e.g. shell buffers and the *Python* buffer.  When using pdb to debug a
+Python program, pdbtrack notices the pdb prompt and displays the
+source file and line that the program is stopped at, much the same way
+as gud-mode does for debugging C programs with gdb."
+  :type 'boolean
+  :group 'python)
+(make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
+
+(defcustom py-pdbtrack-minor-mode-string " PDB"
+  "*String to use in the minor mode list when pdbtrack is enabled."
+  :type 'string
+  :group 'python)
+
+;; Not customizable
+(defvar py-master-file nil
+  "If non-nil, execute the named file instead of the buffer's file.
+The intent is to allow you to set this variable in the file's local
+variable section, e.g.:
+
+    # Local Variables:
+    # py-master-file: \"master.py\"
+    # End:
+
+so that typing \\[py-execute-buffer] in that buffer executes the named
+master file instead of the buffer's file.  If the file name has a
+relative path, the value of variable `default-directory' for the
+buffer is prepended to come up with a file name.")
+(make-variable-buffer-local 'py-master-file)
+
+
+
+;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
+
+(defconst py-emacs-features
+  (let (features)
+   features)
+  "A list of features extant in the Emacs you are using.
+There are many flavors of Emacs out there, with different levels of
+support for features needed by `python-mode'.")
+
+(defvar python-font-lock-keywords
+  (let ((kw1 (mapconcat 'identity
+			'("and"      "assert"   "break"   "class"
+			  "continue" "def"      "del"     "elif"
+			  "else"     "except"   "exec"    "for"
+			  "from"     "global"   "if"      "import"
+			  "in"       "is"       "lambda"  "not"
+			  "or"       "pass"     "print"   "raise"
+			  "return"   "while"    "yield"
+			  )
+			"\\|"))
+	(kw2 (mapconcat 'identity
+			'("else:" "except:" "finally:" "try:")
+			"\\|"))
+	)
+    (list
+     ;; keywords
+     (cons (concat "\\b\\(" kw1 "\\)\\b[ \n\t(]") 1)
+     ;; block introducing keywords with immediately following colons.
+     ;; Yes "except" is in both lists.
+     (cons (concat "\\b\\(" kw2 "\\)[ \n\t(]") 1)
+     ;; `as' but only in "import foo as bar"
+     '("[ \t]*\\(\\bfrom\\b.*\\)?\\bimport\\b.*\\b\\(as\\)\\b" . 2)
+     ;; classes
+     '("\\bclass[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
+       1 font-lock-type-face)
+     ;; functions
+     '("\\bdef[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
+       1 font-lock-function-name-face)
+     ))
+  "Additional expressions to highlight in Python mode.")
+(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
+
+;; have to bind py-file-queue before installing the kill-emacs-hook
+(defvar py-file-queue nil
+  "Queue of Python temp files awaiting execution.
+Currently-active file is at the head of the list.")
+
+(defvar py-pdbtrack-is-tracking-p nil)
+
+
+
+;; Constants
+
+(defconst py-stringlit-re
+  (concat
+   ;; These fail if backslash-quote ends the string (not worth
+   ;; fixing?).  They precede the short versions so that the first two
+   ;; quotes don't look like an empty short string.
+   ;;
+   ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
+   ;; with potential embedded single quotes
+   "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
+   "\\|"
+   ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
+   ;; with potential embedded double quotes
+   "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
+   "\\|"
+   "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'"	; single-quoted
+   "\\|"				; or
+   "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\""	; double-quoted
+   )
+  "Regular expression matching a Python string literal.")
+
+(defconst py-continued-re
+  ;; This is tricky because a trailing backslash does not mean
+  ;; continuation if it's in a comment
+  (concat
+   "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
+   "\\\\$")
+  "Regular expression matching Python backslash continuation lines.")
+  
+(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
+  "Regular expression matching a blank or comment line.")
+
+(defconst py-outdent-re
+  (concat "\\(" (mapconcat 'identity
+			   '("else:"
+			     "except\\(\\s +.*\\)?:"
+			     "finally:"
+			     "elif\\s +.*:")
+			   "\\|")
+	  "\\)")
+  "Regular expression matching statements to be dedented one level.")
+  
+(defconst py-block-closing-keywords-re
+  "\\(return\\|raise\\|break\\|continue\\|pass\\)"
+  "Regular expression matching keywords which typically close a block.")
+
+(defconst py-no-outdent-re
+  (concat
+   "\\("
+   (mapconcat 'identity
+	      (list "try:"
+		    "except\\(\\s +.*\\)?:"
+		    "while\\s +.*:"
+		    "for\\s +.*:"
+		    "if\\s +.*:"
+		    "elif\\s +.*:"
+		    (concat py-block-closing-keywords-re "[ \t\n]")
+		    )
+	      "\\|")
+	  "\\)")
+  "Regular expression matching lines not to dedent after.")
+
+(defconst py-defun-start-re
+  "^\\([ \t]*\\)def[ \t]+\\([a-zA-Z_0-9]+\\)\\|\\(^[a-zA-Z_0-9]+\\)[ \t]*="
+  ;; If you change this, you probably have to change py-current-defun
+  ;; as well.  This is only used by py-current-defun to find the name
+  ;; for add-log.el.
+  "Regular expression matching a function, method, or variable assignment.")
+
+(defconst py-class-start-re "^class[ \t]*\\([a-zA-Z_0-9]+\\)"
+  ;; If you change this, you probably have to change py-current-defun
+  ;; as well.  This is only used by py-current-defun to find the name
+  ;; for add-log.el.
+  "Regular expression for finding a class name.")
+
+(defconst py-traceback-line-re
+  "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
+  "Regular expression that describes tracebacks.")
+
+;; pdbtrack contants
+(defconst py-pdbtrack-stack-entry-regexp
+  "> \\([^(]+\\)(\\([0-9]+\\))[?a-zA-Z0-9_]+()"
+  "Regular expression pdbtrack uses to find a stack trace entry.")
+
+(defconst py-pdbtrack-input-prompt "\n[(<]?pdb[>)]? "
+  "Regular expression pdbtrack uses to recognize a pdb prompt.")
+
+(defconst py-pdbtrack-track-range 10000
+  "Max number of characters from end of buffer to search for stack entry.")
+
+
+
+;; Major mode boilerplate
+
+;; define a mode-specific abbrev table for those who use such things
+(defvar python-mode-abbrev-table nil
+  "Abbrev table in use in `python-mode' buffers.")
+(define-abbrev-table 'python-mode-abbrev-table nil)
+
+(defvar python-mode-hook nil
+  "*Hook called by `python-mode'.")
+
+;; In previous version of python-mode.el, the hook was incorrectly
+;; called py-mode-hook, and was not defvar'd.  Deprecate its use.
+(and (fboundp 'make-obsolete-variable)
+     (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
+
+(defvar py-mode-map ()
+  "Keymap used in `python-mode' buffers.")
+(if py-mode-map
+    nil
+  (setq py-mode-map (make-sparse-keymap))
+  ;; electric keys
+  (define-key py-mode-map ":" 'py-electric-colon)
+  ;; indentation level modifiers
+  (define-key py-mode-map "\C-c\C-l"  'py-shift-region-left)
+  (define-key py-mode-map "\C-c\C-r"  'py-shift-region-right)
+  (define-key py-mode-map "\C-c<"     'py-shift-region-left)
+  (define-key py-mode-map "\C-c>"     'py-shift-region-right)
+  ;; subprocess commands
+  (define-key py-mode-map "\C-c\C-c"  'py-execute-buffer)
+  (define-key py-mode-map "\C-c\C-m"  'py-execute-import-or-reload)
+  (define-key py-mode-map "\C-c\C-s"  'py-execute-string)
+  (define-key py-mode-map "\C-c|"     'py-execute-region)
+  (define-key py-mode-map "\e\C-x"    'py-execute-def-or-class)
+  (define-key py-mode-map "\C-c!"     'py-shell)
+  (define-key py-mode-map "\C-c\C-t"  'py-toggle-shells)
+  ;; Caution!  Enter here at your own risk.  We are trying to support
+  ;; several behaviors and it gets disgusting. :-( This logic ripped
+  ;; largely from CC Mode.
+  ;;
+  ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
+  ;; backwards deletion behavior to DEL, which both Delete and
+  ;; Backspace get translated to.  There's no way to separate this
+  ;; behavior in a clean way, so deal with it!  Besides, it's been
+  ;; this way since the dawn of time.
+  (if (not (boundp 'delete-key-deletes-forward))
+      (define-key py-mode-map "\177" 'py-electric-backspace)
+    ;; However, XEmacs 20 actually achieved enlightenment.  It is
+    ;; possible to sanely define both backward and forward deletion
+    ;; behavior under X separately (TTYs are forever beyond hope, but
+    ;; who cares?  XEmacs 20 does the right thing with these too).
+    (define-key py-mode-map [delete]    'py-electric-delete)
+    (define-key py-mode-map [backspace] 'py-electric-backspace))
+  ;; Separate M-BS from C-M-h.  The former should remain
+  ;; backward-kill-word.
+  (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
+  (define-key py-mode-map "\C-c\C-k"  'py-mark-block)
+  ;; Miscellaneous
+  (define-key py-mode-map "\C-c:"     'py-guess-indent-offset)
+  (define-key py-mode-map "\C-c\t"    'py-indent-region)
+  (define-key py-mode-map "\C-c\C-d"  'py-pdbtrack-toggle-stack-tracking)
+  (define-key py-mode-map "\C-c\C-n"  'py-next-statement)
+  (define-key py-mode-map "\C-c\C-p"  'py-previous-statement)
+  (define-key py-mode-map "\C-c\C-u"  'py-goto-block-up)
+  (define-key py-mode-map "\C-c#"     'py-comment-region)
+  (define-key py-mode-map "\C-c?"     'py-describe-mode)
+  (define-key py-mode-map "\C-c\C-hm" 'py-describe-mode)
+  (define-key py-mode-map "\e\C-a"    'py-beginning-of-def-or-class)
+  (define-key py-mode-map "\e\C-e"    'py-end-of-def-or-class)
+  (define-key py-mode-map "\C-c-"     'py-up-exception)
+  (define-key py-mode-map "\C-c="     'py-down-exception)
+  ;; stuff that is `standard' but doesn't interface well with
+  ;; python-mode, which forces us to rebind to special commands
+  (define-key py-mode-map "\C-xnd"    'py-narrow-to-defun)
+  ;; information
+  (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
+  (define-key py-mode-map "\C-c\C-v" 'py-version)
+  ;; shadow global bindings for newline-and-indent w/ the py- version.
+  ;; BAW - this is extremely bad form, but I'm not going to change it
+  ;; for now.
+  (mapcar #'(lambda (key)
+	      (define-key py-mode-map key 'py-newline-and-indent))
+	  (where-is-internal 'newline-and-indent))
+  ;; Force RET to be py-newline-and-indent even if it didn't get
+  ;; mapped by the above code.  motivation: Emacs' default binding for
+  ;; RET is `newline' and C-j is `newline-and-indent'.  Most Pythoneers
+  ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
+  ;; dislike this are probably knowledgeable enough to do a rebind.
+  ;; However, we do *not* change C-j since many Emacsers have already
+  ;; swapped RET and C-j and they don't want C-j bound to `newline' to 
+  ;; change.
+  (define-key py-mode-map "\C-m" 'py-newline-and-indent)
+  )
+
+(defvar py-mode-output-map nil
+  "Keymap used in *Python Output* buffers.")
+(if py-mode-output-map
+    nil
+  (setq py-mode-output-map (make-sparse-keymap))
+  (define-key py-mode-output-map [button2]  'py-mouseto-exception)
+  (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
+  ;; TBD: Disable all self-inserting keys.  This is bogus, we should
+  ;; really implement this as *Python Output* buffer being read-only
+  (mapcar #' (lambda (key)
+	       (define-key py-mode-output-map key
+		 #'(lambda () (interactive) (beep))))
+	     (where-is-internal 'self-insert-command))
+  )
+
+(defvar py-shell-map nil
+  "Keymap used in *Python* shell buffers.")
+(if py-shell-map
+    nil
+  (setq py-shell-map (copy-keymap comint-mode-map))
+  (define-key py-shell-map [tab]   'tab-to-tab-stop)
+  (define-key py-shell-map "\C-c-" 'py-up-exception)
+  (define-key py-shell-map "\C-c=" 'py-down-exception)
+  )
+
+(defvar py-mode-syntax-table nil
+  "Syntax table used in `python-mode' buffers.")
+(if py-mode-syntax-table
+    nil
+  (setq py-mode-syntax-table (make-syntax-table))
+  (modify-syntax-entry ?\( "()" py-mode-syntax-table)
+  (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
+  (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
+  (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
+  (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
+  (modify-syntax-entry ?\} "){" py-mode-syntax-table)
+  ;; Add operator symbols misassigned in the std table
+  (modify-syntax-entry ?\$ "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\% "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\& "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\* "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\+ "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\- "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\/ "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\< "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\= "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\> "."  py-mode-syntax-table)
+  (modify-syntax-entry ?\| "."  py-mode-syntax-table)
+  ;; For historical reasons, underscore is word class instead of
+  ;; symbol class.  GNU conventions say it should be symbol class, but
+  ;; there's a natural conflict between what major mode authors want
+  ;; and what users expect from `forward-word' and `backward-word'.
+  ;; Guido and I have hashed this out and have decided to keep
+  ;; underscore in word class.  If you're tempted to change it, try
+  ;; binding M-f and M-b to py-forward-into-nomenclature and
+  ;; py-backward-into-nomenclature instead.  This doesn't help in all
+  ;; situations where you'd want the different behavior
+  ;; (e.g. backward-kill-word).
+  (modify-syntax-entry ?\_ "w"  py-mode-syntax-table)
+  ;; Both single quote and double quote are string delimiters
+  (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
+  (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
+  ;; backquote is open and close paren
+  (modify-syntax-entry ?\` "$"  py-mode-syntax-table)
+  ;; comment delimiters
+  (modify-syntax-entry ?\# "<"  py-mode-syntax-table)
+  (modify-syntax-entry ?\n ">"  py-mode-syntax-table)
+  )
+
+
+
+;; Utilities
+
+(defmacro py-safe (&rest body)
+  "Safely execute BODY, return nil if an error occurred."
+  (` (condition-case nil
+	 (progn (,@ body))
+       (error nil))))
+
+(defsubst py-keep-region-active ()
+  "Keep the region active in XEmacs."
+  ;; Ignore byte-compiler warnings you might see.  Also note that
+  ;; FSF's Emacs 19 does it differently; its policy doesn't require us
+  ;; to take explicit action.
+  (and (boundp 'zmacs-region-stays)
+       (setq zmacs-region-stays t)))
+
+(defsubst py-point (position)
+  "Returns the value of point at certain commonly referenced POSITIONs.
+POSITION can be one of the following symbols:
+
+  bol  -- beginning of line
+  eol  -- end of line
+  bod  -- beginning of def or class
+  eod  -- end of def or class
+  bob  -- beginning of buffer
+  eob  -- end of buffer
+  boi  -- back to indentation
+  bos  -- beginning of statement
+
+This function does not modify point or mark."
+  (let ((here (point)))
+    (cond
+     ((eq position 'bol) (beginning-of-line))
+     ((eq position 'eol) (end-of-line))
+     ((eq position 'bod) (py-beginning-of-def-or-class))
+     ((eq position 'eod) (py-end-of-def-or-class))
+     ;; Kind of funny, I know, but useful for py-up-exception.
+     ((eq position 'bob) (beginning-of-buffer))
+     ((eq position 'eob) (end-of-buffer))
+     ((eq position 'boi) (back-to-indentation))
+     ((eq position 'bos) (py-goto-initial-line))
+     (t (error "Unknown buffer position requested: %s" position))
+     )
+    (prog1
+	(point)
+      (goto-char here))))
+
+(defsubst py-highlight-line (from to file line)
+  (cond
+   ((fboundp 'make-extent)
+    ;; XEmacs
+    (let ((e (make-extent from to)))
+      (set-extent-property e 'mouse-face 'highlight)
+      (set-extent-property e 'py-exc-info (cons file line))
+      (set-extent-property e 'keymap py-mode-output-map)))
+   (t
+    ;; Emacs -- Please port this!
+    )
+   ))
+
+(defun py-in-literal (&optional lim)
+  "Return non-nil if point is in a Python literal (a comment or string).
+Optional argument LIM indicates the beginning of the containing form,
+i.e. the limit on how far back to scan."
+  ;; This is the version used for non-XEmacs, which has a nicer
+  ;; interface.
+  ;;
+  ;; WARNING: Watch out for infinite recursion.
+  (let* ((lim (or lim (py-point 'bod)))
+	 (state (parse-partial-sexp lim (point))))
+    (cond
+     ((nth 3 state) 'string)
+     ((nth 4 state) 'comment)
+     (t nil))))
+
+;; XEmacs has a built-in function that should make this much quicker.
+;; In this case, lim is ignored
+(defun py-fast-in-literal (&optional lim)
+  "Fast version of `py-in-literal', used only by XEmacs.
+Optional LIM is ignored."
+  ;; don't have to worry about context == 'block-comment
+  (buffer-syntactic-context))
+
+(if (fboundp 'buffer-syntactic-context)
+    (defalias 'py-in-literal 'py-fast-in-literal))
+
+
+
+;; Menu definitions, only relevent if you have the ea