PageRenderTime 60ms CodeModel.GetById 15ms app.highlight 25ms RepoModel.GetById 1ms app.codeStats 1ms

/Misc/python-mode.el

http://unladen-swallow.googlecode.com/
Lisp | 3906 lines | 2964 code | 439 blank | 503 comment | 144 complexity | e71c5f8da53b08ae3d6d303719f41172 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1;;; python-mode.el --- Major mode for editing Python programs
   2
   3;; Copyright (C) 1992,1993,1994  Tim Peters
   4
   5;; Author: 2003-2007 http://sf.net/projects/python-mode
   6;;         1995-2002 Barry A. Warsaw
   7;;         1992-1994 Tim Peters
   8;; Maintainer: python-mode@python.org
   9;; Created:    Feb 1992
  10;; Keywords:   python languages oop
  11
  12(defconst py-version "$Revision: 60587 $"
  13  "`python-mode' version number.")
  14
  15;; This software is provided as-is, without express or implied
  16;; warranty.  Permission to use, copy, modify, distribute or sell this
  17;; software, without fee, for any purpose and by any individual or
  18;; organization, is hereby granted, provided that the above copyright
  19;; notice and this paragraph appear in all copies.
  20
  21;;; Commentary:
  22
  23;; This is a major mode for editing Python programs.  It was developed by Tim
  24;; Peters after an original idea by Michael A. Guravage.  Tim subsequently
  25;; left the net and in 1995, Barry Warsaw inherited the mode.  Tim's now back
  26;; but disavows all responsibility for the mode.  In fact, we suspect he
  27;; doesn't even use Emacs any more.  In 2003, python-mode.el was moved to its
  28;; own SourceForge project apart from the Python project, and now is
  29;; maintained by the volunteers at the python-mode@python.org mailing list.
  30
  31;; pdbtrack support contributed by Ken Manheimer, April 2001.  Skip Montanaro
  32;; has also contributed significantly to python-mode's development.
  33
  34;; Please use the SourceForge Python project to submit bugs or
  35;; patches:
  36;;
  37;;     http://sourceforge.net/projects/python
  38
  39;; INSTALLATION:
  40
  41;; To install, just drop this file into a directory on your load-path and
  42;; byte-compile it.  To set up Emacs to automatically edit files ending in
  43;; ".py" using python-mode add the following to your ~/.emacs file (GNU
  44;; Emacs) or ~/.xemacs/init.el file (XEmacs):
  45;;    (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist))
  46;;    (setq interpreter-mode-alist (cons '("python" . python-mode)
  47;;                                       interpreter-mode-alist))
  48;;    (autoload 'python-mode "python-mode" "Python editing mode." t)
  49;;
  50;; In XEmacs syntax highlighting should be enabled automatically.  In GNU
  51;; Emacs you may have to add these lines to your ~/.emacs file:
  52;;    (global-font-lock-mode t)
  53;;    (setq font-lock-maximum-decoration t)
  54
  55;; FOR MORE INFORMATION:
  56
  57;; There is some information on python-mode.el at
  58
  59;;     http://www.python.org/emacs/python-mode/
  60;;
  61;; It does contain links to other packages that you might find useful,
  62;; such as pdb interfaces, OO-Browser links, etc.
  63
  64;; BUG REPORTING:
  65
  66;; As mentioned above, please use the SourceForge Python project for
  67;; submitting bug reports or patches.  The old recommendation, to use
  68;; C-c C-b will still work, but those reports have a higher chance of
  69;; getting buried in my mailbox.  Please include a complete, but
  70;; concise code sample and a recipe for reproducing the bug.  Send
  71;; suggestions and other comments to python-mode@python.org.
  72
  73;; When in a Python mode buffer, do a C-h m for more help.  It's
  74;; doubtful that a texinfo manual would be very useful, but if you
  75;; want to contribute one, I'll certainly accept it!
  76
  77;;; Code:
  78
  79(require 'comint)
  80(require 'custom)
  81(require 'cl)
  82(require 'compile)
  83(require 'ansi-color)
  84
  85
  86;; user definable variables
  87;; vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
  88
  89(defgroup python nil
  90  "Support for the Python programming language, <http://www.python.org/>"
  91  :group 'languages
  92  :prefix "py-")
  93
  94(defcustom py-tab-always-indent t
  95  "*Non-nil means TAB in Python mode should always reindent the current line,
  96regardless of where in the line point is when the TAB command is used."
  97  :type 'boolean
  98  :group 'python)
  99
 100(defcustom py-python-command "python"
 101  "*Shell command used to start Python interpreter."
 102  :type 'string
 103  :group 'python)
 104
 105(make-obsolete-variable 'py-jpython-command 'py-jython-command)
 106(defcustom py-jython-command "jython"
 107  "*Shell command used to start the Jython interpreter."
 108  :type 'string
 109  :group 'python
 110  :tag "Jython Command")
 111
 112(defcustom py-default-interpreter 'cpython
 113  "*Which Python interpreter is used by default.
 114The value for this variable can be either `cpython' or `jython'.
 115
 116When the value is `cpython', the variables `py-python-command' and
 117`py-python-command-args' are consulted to determine the interpreter
 118and arguments to use.
 119
 120When the value is `jython', the variables `py-jython-command' and
 121`py-jython-command-args' are consulted to determine the interpreter
 122and arguments to use.
 123
 124Note that this variable is consulted only the first time that a Python
 125mode buffer is visited during an Emacs session.  After that, use
 126\\[py-toggle-shells] to change the interpreter shell."
 127  :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
 128		 (const :tag "Jython" jython))
 129  :group 'python)
 130
 131(defcustom py-python-command-args '("-i")
 132  "*List of string arguments to be used when starting a Python shell."
 133  :type '(repeat string)
 134  :group 'python)
 135
 136(make-obsolete-variable 'py-jpython-command-args 'py-jython-command-args)
 137(defcustom py-jython-command-args '("-i")
 138  "*List of string arguments to be used when starting a Jython shell."
 139  :type '(repeat string)
 140  :group 'python
 141  :tag "Jython Command Args")
 142
 143(defcustom py-indent-offset 4
 144  "*Amount of offset per level of indentation.
 145`\\[py-guess-indent-offset]' can usually guess a good value when
 146you're editing someone else's Python code."
 147  :type 'integer
 148  :group 'python)
 149
 150(defcustom py-continuation-offset 4
 151  "*Additional amount of offset to give for some continuation lines.
 152Continuation lines are those that immediately follow a backslash
 153terminated line.  Only those continuation lines for a block opening
 154statement are given this extra offset."
 155  :type 'integer
 156  :group 'python)
 157
 158(defcustom py-smart-indentation t
 159  "*Should `python-mode' try to automagically set some indentation variables?
 160When this variable is non-nil, two things happen when a buffer is set
 161to `python-mode':
 162
 163    1. `py-indent-offset' is guessed from existing code in the buffer.
 164       Only guessed values between 2 and 8 are considered.  If a valid
 165       guess can't be made (perhaps because you are visiting a new
 166       file), then the value in `py-indent-offset' is used.
 167
 168    2. `indent-tabs-mode' is turned off if `py-indent-offset' does not
 169       equal `tab-width' (`indent-tabs-mode' is never turned on by
 170       Python mode).  This means that for newly written code, tabs are
 171       only inserted in indentation if one tab is one indentation
 172       level, otherwise only spaces are used.
 173
 174Note that both these settings occur *after* `python-mode-hook' is run,
 175so if you want to defeat the automagic configuration, you must also
 176set `py-smart-indentation' to nil in your `python-mode-hook'."
 177  :type 'boolean
 178  :group 'python)
 179
 180(defcustom py-align-multiline-strings-p t
 181  "*Flag describing how multi-line triple quoted strings are aligned.
 182When this flag is non-nil, continuation lines are lined up under the
 183preceding line's indentation.  When this flag is nil, continuation
 184lines are aligned to column zero."
 185  :type '(choice (const :tag "Align under preceding line" t)
 186		 (const :tag "Align to column zero" nil))
 187  :group 'python)
 188
 189(defcustom py-block-comment-prefix "##"
 190  "*String used by \\[comment-region] to comment out a block of code.
 191This should follow the convention for non-indenting comment lines so
 192that the indentation commands won't get confused (i.e., the string
 193should be of the form `#x...' where `x' is not a blank or a tab, and
 194`...' is arbitrary).  However, this string should not end in whitespace."
 195  :type 'string
 196  :group 'python)
 197
 198(defcustom py-honor-comment-indentation t
 199  "*Controls how comment lines influence subsequent indentation.
 200
 201When nil, all comment lines are skipped for indentation purposes, and
 202if possible, a faster algorithm is used (i.e. X/Emacs 19 and beyond).
 203
 204When t, lines that begin with a single `#' are a hint to subsequent
 205line indentation.  If the previous line is such a comment line (as
 206opposed to one that starts with `py-block-comment-prefix'), then its
 207indentation is used as a hint for this line's indentation.  Lines that
 208begin with `py-block-comment-prefix' are ignored for indentation
 209purposes.
 210
 211When not nil or t, comment lines that begin with a single `#' are used
 212as indentation hints, unless the comment character is in column zero."
 213  :type '(choice
 214	  (const :tag "Skip all comment lines (fast)" nil)
 215	  (const :tag "Single # `sets' indentation for next line" t)
 216	  (const :tag "Single # `sets' indentation except at column zero"
 217		 other)
 218	  )
 219  :group 'python)
 220
 221(defcustom py-temp-directory
 222  (let ((ok '(lambda (x)
 223	       (and x
 224		    (setq x (expand-file-name x)) ; always true
 225		    (file-directory-p x)
 226		    (file-writable-p x)
 227		    x))))
 228    (or (funcall ok (getenv "TMPDIR"))
 229	(funcall ok "/usr/tmp")
 230	(funcall ok "/tmp")
 231	(funcall ok "/var/tmp")
 232	(funcall ok  ".")
 233	(error
 234	 "Couldn't find a usable temp directory -- set `py-temp-directory'")))
 235  "*Directory used for temporary files created by a *Python* process.
 236By default, the first directory from this list that exists and that you
 237can write into: the value (if any) of the environment variable TMPDIR,
 238/usr/tmp, /tmp, /var/tmp, or the current directory."
 239  :type 'string
 240  :group 'python)
 241
 242(defcustom py-beep-if-tab-change t
 243  "*Ring the bell if `tab-width' is changed.
 244If a comment of the form
 245
 246  \t# vi:set tabsize=<number>:
 247
 248is found before the first code line when the file is entered, and the
 249current value of (the general Emacs variable) `tab-width' does not
 250equal <number>, `tab-width' is set to <number>, a message saying so is
 251displayed in the echo area, and if `py-beep-if-tab-change' is non-nil
 252the Emacs bell is also rung as a warning."
 253  :type 'boolean
 254  :group 'python)
 255
 256(defcustom py-jump-on-exception t
 257  "*Jump to innermost exception frame in *Python Output* buffer.
 258When this variable is non-nil and an exception occurs when running
 259Python code synchronously in a subprocess, jump immediately to the
 260source code of the innermost traceback frame."
 261  :type 'boolean
 262  :group 'python)
 263
 264(defcustom py-ask-about-save t
 265  "If not nil, ask about which buffers to save before executing some code.
 266Otherwise, all modified buffers are saved without asking."
 267  :type 'boolean
 268  :group 'python)
 269
 270(defcustom py-backspace-function 'backward-delete-char-untabify
 271  "*Function called by `py-electric-backspace' when deleting backwards."
 272  :type 'function
 273  :group 'python)
 274
 275(defcustom py-delete-function 'delete-char
 276  "*Function called by `py-electric-delete' when deleting forwards."
 277  :type 'function
 278  :group 'python)
 279
 280(defcustom py-imenu-show-method-args-p nil
 281  "*Controls echoing of arguments of functions & methods in the Imenu buffer.
 282When non-nil, arguments are printed."
 283  :type 'boolean
 284  :group 'python)
 285(make-variable-buffer-local 'py-indent-offset)
 286
 287(defcustom py-pdbtrack-do-tracking-p t
 288  "*Controls whether the pdbtrack feature is enabled or not.
 289When non-nil, pdbtrack is enabled in all comint-based buffers,
 290e.g. shell buffers and the *Python* buffer.  When using pdb to debug a
 291Python program, pdbtrack notices the pdb prompt and displays the
 292source file and line that the program is stopped at, much the same way
 293as gud-mode does for debugging C programs with gdb."
 294  :type 'boolean
 295  :group 'python)
 296(make-variable-buffer-local 'py-pdbtrack-do-tracking-p)
 297
 298(defcustom py-pdbtrack-minor-mode-string " PDB"
 299  "*String to use in the minor mode list when pdbtrack is enabled."
 300  :type 'string
 301  :group 'python)
 302
 303(defcustom py-import-check-point-max
 304  20000
 305  "Maximum number of characters to search for a Java-ish import statement.
 306When `python-mode' tries to calculate the shell to use (either a
 307CPython or a Jython shell), it looks at the so-called `shebang' line
 308-- i.e. #! line.  If that's not available, it looks at some of the
 309file heading imports to see if they look Java-like."
 310  :type 'integer
 311  :group 'python
 312  )
 313
 314(make-obsolete-variable 'py-jpython-packages 'py-jython-packages)
 315(defcustom py-jython-packages
 316  '("java" "javax" "org" "com")
 317  "Imported packages that imply `jython-mode'."
 318  :type '(repeat string)
 319  :group 'python)
 320
 321;; Not customizable
 322(defvar py-master-file nil
 323  "If non-nil, execute the named file instead of the buffer's file.
 324The intent is to allow you to set this variable in the file's local
 325variable section, e.g.:
 326
 327    # Local Variables:
 328    # py-master-file: \"master.py\"
 329    # End:
 330
 331so that typing \\[py-execute-buffer] in that buffer executes the named
 332master file instead of the buffer's file.  If the file name has a
 333relative path, the value of variable `default-directory' for the
 334buffer is prepended to come up with a file name.")
 335(make-variable-buffer-local 'py-master-file)
 336
 337(defcustom py-pychecker-command "pychecker"
 338  "*Shell command used to run Pychecker."
 339  :type 'string
 340  :group 'python
 341  :tag "Pychecker Command")
 342
 343(defcustom py-pychecker-command-args '("--stdlib")
 344  "*List of string arguments to be passed to pychecker."
 345  :type '(repeat string)
 346  :group 'python
 347  :tag "Pychecker Command Args")
 348
 349(defvar py-shell-alist
 350  '(("jython" . 'jython)
 351    ("python" . 'cpython))
 352  "*Alist of interpreters and python shells. Used by `py-choose-shell'
 353to select the appropriate python interpreter mode for a file.")
 354
 355(defcustom py-shell-input-prompt-1-regexp "^>>> "
 356  "*A regular expression to match the input prompt of the shell."
 357  :type 'string
 358  :group 'python)
 359
 360(defcustom py-shell-input-prompt-2-regexp "^[.][.][.] "
 361  "*A regular expression to match the input prompt of the shell after the
 362  first line of input."
 363  :type 'string
 364  :group 'python)
 365
 366(defcustom py-shell-switch-buffers-on-execute t
 367  "*Controls switching to the Python buffer where commands are
 368  executed.  When non-nil the buffer switches to the Python buffer, if
 369  not no switching occurs."
 370  :type 'boolean
 371  :group 'python)
 372
 373
 374;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 375;; NO USER DEFINABLE VARIABLES BEYOND THIS POINT
 376
 377(defvar py-line-number-offset 0
 378  "When an exception occurs as a result of py-execute-region, a
 379subsequent py-up-exception needs the line number where the region
 380started, in order to jump to the correct file line.  This variable is
 381set in py-execute-region and used in py-jump-to-exception.")
 382
 383(defconst py-emacs-features
 384  (let (features)
 385   features)
 386  "A list of features extant in the Emacs you are using.
 387There are many flavors of Emacs out there, with different levels of
 388support for features needed by `python-mode'.")
 389
 390;; Face for None, True, False, self, and Ellipsis
 391(defvar py-pseudo-keyword-face 'py-pseudo-keyword-face
 392  "Face for pseudo keywords in Python mode, like self, True, False, Ellipsis.")
 393(make-face 'py-pseudo-keyword-face)
 394
 395;; PEP 318 decorators
 396(defvar py-decorators-face 'py-decorators-face
 397  "Face method decorators.")
 398(make-face 'py-decorators-face)
 399
 400;; Face for builtins
 401(defvar py-builtins-face 'py-builtins-face
 402  "Face for builtins like TypeError, object, open, and exec.")
 403(make-face 'py-builtins-face)
 404
 405;; XXX, TODO, and FIXME comments and such
 406(defvar py-XXX-tag-face 'py-XXX-tag-face
 407  "Face for XXX, TODO, and FIXME tags")
 408(make-face 'py-XXX-tag-face)
 409
 410(defun py-font-lock-mode-hook ()
 411  (or (face-differs-from-default-p 'py-pseudo-keyword-face)
 412      (copy-face 'font-lock-keyword-face 'py-pseudo-keyword-face))
 413  (or (face-differs-from-default-p 'py-builtins-face)
 414      (copy-face 'font-lock-keyword-face 'py-builtins-face))
 415  (or (face-differs-from-default-p 'py-decorators-face)
 416      (copy-face 'py-pseudo-keyword-face 'py-decorators-face))
 417  (or (face-differs-from-default-p 'py-XXX-tag-face)
 418      (copy-face 'font-lock-comment-face 'py-XXX-tag-face))
 419  )
 420(add-hook 'font-lock-mode-hook 'py-font-lock-mode-hook)
 421
 422(defvar python-font-lock-keywords
 423  (let ((kw1 (mapconcat 'identity
 424			'("and"      "assert"   "break"   "class"
 425			  "continue" "def"      "del"     "elif"
 426			  "else"     "except"   "exec"    "for"
 427			  "from"     "global"   "if"      "import"
 428			  "in"       "is"       "lambda"  "not"
 429			  "or"       "pass"     "print"   "raise"
 430			  "return"   "while"    "with"    "yield"
 431			  )
 432			"\\|"))
 433	(kw2 (mapconcat 'identity
 434			'("else:" "except:" "finally:" "try:")
 435			"\\|"))
 436	(kw3 (mapconcat 'identity
 437			;; Don't include True, False, None, or
 438			;; Ellipsis in this list, since they are
 439			;; already defined as pseudo keywords.
 440			'("__debug__"
 441			  "__import__" "__name__" "abs" "apply" "basestring"
 442			  "bool" "buffer" "callable" "chr" "classmethod"
 443			  "cmp" "coerce" "compile" "complex" "copyright"
 444			  "delattr" "dict" "dir" "divmod"
 445			  "enumerate" "eval" "execfile" "exit" "file"
 446			  "filter" "float" "getattr" "globals" "hasattr"
 447			  "hash" "hex" "id" "input" "int" "intern"
 448			  "isinstance" "issubclass" "iter" "len" "license"
 449			  "list" "locals" "long" "map" "max" "min" "object"
 450			  "oct" "open" "ord" "pow" "property" "range"
 451			  "raw_input" "reduce" "reload" "repr" "round"
 452			  "setattr" "slice" "staticmethod" "str" "sum"
 453			  "super" "tuple" "type" "unichr" "unicode" "vars"
 454			  "xrange" "zip")
 455			"\\|"))
 456	(kw4 (mapconcat 'identity
 457			;; Exceptions and warnings
 458			'("ArithmeticError" "AssertionError"
 459			  "AttributeError" "DeprecationWarning" "EOFError"
 460			  "EnvironmentError" "Exception"
 461			  "FloatingPointError" "FutureWarning" "IOError"
 462			  "ImportError" "IndentationError" "IndexError"
 463			  "KeyError" "KeyboardInterrupt" "LookupError"
 464			  "MemoryError" "NameError" "NotImplemented"
 465			  "NotImplementedError" "OSError" "OverflowError"
 466			  "OverflowWarning" "PendingDeprecationWarning"
 467			  "ReferenceError" "RuntimeError" "RuntimeWarning"
 468			  "StandardError" "StopIteration" "SyntaxError"
 469			  "SyntaxWarning" "SystemError" "SystemExit"
 470			  "TabError" "TypeError" "UnboundLocalError"
 471			  "UnicodeDecodeError" "UnicodeEncodeError"
 472			  "UnicodeError" "UnicodeTranslateError"
 473			  "UserWarning" "ValueError" "Warning"
 474			  "ZeroDivisionError")
 475			"\\|"))
 476	)
 477    (list
 478     '("^[ \t]*\\(@.+\\)" 1 'py-decorators-face)
 479     ;; keywords
 480     (cons (concat "\\<\\(" kw1 "\\)\\>[ \n\t(]") 1)
 481     ;; builtins when they don't appear as object attributes
 482     (list (concat "\\([^. \t]\\|^\\)[ \t]*\\<\\(" kw3 "\\)\\>[ \n\t(]") 2
 483	   'py-builtins-face)
 484     ;; block introducing keywords with immediately following colons.
 485     ;; Yes "except" is in both lists.
 486     (cons (concat "\\<\\(" kw2 "\\)[ \n\t(]") 1)
 487     ;; Exceptions
 488     (list (concat "\\<\\(" kw4 "\\)[ \n\t:,(]") 1 'py-builtins-face)
 489     ;; `as' but only in "import foo as bar" or "with foo as bar"
 490     '("[ \t]*\\(\\<from\\>.*\\)?\\<import\\>.*\\<\\(as\\)\\>" . 2)
 491     '("[ \t]*\\<with\\>.*\\<\\(as\\)\\>" . 1)
 492     ;; classes
 493     '("\\<class[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)" 1 font-lock-type-face)
 494     ;; functions
 495     '("\\<def[ \t]+\\([a-zA-Z_]+[a-zA-Z0-9_]*\\)"
 496       1 font-lock-function-name-face)
 497     ;; pseudo-keywords
 498     '("\\<\\(self\\|None\\|True\\|False\\|Ellipsis\\)\\>"
 499       1 py-pseudo-keyword-face)
 500     ;; XXX, TODO, and FIXME tags
 501     '("XXX\\|TODO\\|FIXME" 0 py-XXX-tag-face t)
 502     ))
 503  "Additional expressions to highlight in Python mode.")
 504(put 'python-mode 'font-lock-defaults '(python-font-lock-keywords))
 505
 506;; have to bind py-file-queue before installing the kill-emacs-hook
 507(defvar py-file-queue nil
 508  "Queue of Python temp files awaiting execution.
 509Currently-active file is at the head of the list.")
 510
 511(defvar py-pdbtrack-is-tracking-p nil)
 512
 513(defvar py-pychecker-history nil)
 514
 515
 516
 517;; Constants
 518
 519(defconst py-stringlit-re
 520  (concat
 521   ;; These fail if backslash-quote ends the string (not worth
 522   ;; fixing?).  They precede the short versions so that the first two
 523   ;; quotes don't look like an empty short string.
 524   ;;
 525   ;; (maybe raw), long single quoted triple quoted strings (SQTQ),
 526   ;; with potential embedded single quotes
 527   "[rR]?'''[^']*\\(\\('[^']\\|''[^']\\)[^']*\\)*'''"
 528   "\\|"
 529   ;; (maybe raw), long double quoted triple quoted strings (DQTQ),
 530   ;; with potential embedded double quotes
 531   "[rR]?\"\"\"[^\"]*\\(\\(\"[^\"]\\|\"\"[^\"]\\)[^\"]*\\)*\"\"\""
 532   "\\|"
 533   "[rR]?'\\([^'\n\\]\\|\\\\.\\)*'"	; single-quoted
 534   "\\|"				; or
 535   "[rR]?\"\\([^\"\n\\]\\|\\\\.\\)*\""	; double-quoted
 536   )
 537  "Regular expression matching a Python string literal.")
 538
 539(defconst py-continued-re
 540  ;; This is tricky because a trailing backslash does not mean
 541  ;; continuation if it's in a comment
 542  (concat
 543   "\\(" "[^#'\"\n\\]" "\\|" py-stringlit-re "\\)*"
 544   "\\\\$")
 545  "Regular expression matching Python backslash continuation lines.")
 546
 547(defconst py-blank-or-comment-re "[ \t]*\\($\\|#\\)"
 548  "Regular expression matching a blank or comment line.")
 549
 550(defconst py-outdent-re
 551  (concat "\\(" (mapconcat 'identity
 552			   '("else:"
 553			     "except\\(\\s +.*\\)?:"
 554			     "finally:"
 555			     "elif\\s +.*:")
 556			   "\\|")
 557	  "\\)")
 558  "Regular expression matching statements to be dedented one level.")
 559
 560(defconst py-block-closing-keywords-re
 561  "\\(return\\|raise\\|break\\|continue\\|pass\\)"
 562  "Regular expression matching keywords which typically close a block.")
 563
 564(defconst py-no-outdent-re
 565  (concat
 566   "\\("
 567   (mapconcat 'identity
 568	      (list "try:"
 569		    "except\\(\\s +.*\\)?:"
 570		    "while\\s +.*:"
 571		    "for\\s +.*:"
 572		    "if\\s +.*:"
 573		    "elif\\s +.*:"
 574		    (concat py-block-closing-keywords-re "[ \t\n]")
 575		    )
 576	      "\\|")
 577	  "\\)")
 578  "Regular expression matching lines not to dedent after.")
 579
 580(defvar py-traceback-line-re
 581  "[ \t]+File \"\\([^\"]+\\)\", line \\([0-9]+\\)"
 582  "Regular expression that describes tracebacks.")
 583
 584;; pdbtrack constants
 585(defconst py-pdbtrack-stack-entry-regexp
 586;  "^> \\([^(]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
 587  "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_]+\\)()"
 588  "Regular expression pdbtrack uses to find a stack trace entry.")
 589
 590(defconst py-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
 591  "Regular expression pdbtrack uses to recognize a pdb prompt.")
 592
 593(defconst py-pdbtrack-track-range 10000
 594  "Max number of characters from end of buffer to search for stack entry.")
 595
 596
 597
 598;; Major mode boilerplate
 599
 600;; define a mode-specific abbrev table for those who use such things
 601(defvar python-mode-abbrev-table nil
 602  "Abbrev table in use in `python-mode' buffers.")
 603(define-abbrev-table 'python-mode-abbrev-table nil)
 604
 605(defvar python-mode-hook nil
 606  "*Hook called by `python-mode'.")
 607
 608(make-obsolete-variable 'jpython-mode-hook 'jython-mode-hook)
 609(defvar jython-mode-hook nil
 610  "*Hook called by `jython-mode'. `jython-mode' also calls
 611`python-mode-hook'.")
 612
 613(defvar py-shell-hook nil
 614  "*Hook called by `py-shell'.")
 615
 616;; In previous version of python-mode.el, the hook was incorrectly
 617;; called py-mode-hook, and was not defvar'd.  Deprecate its use.
 618(and (fboundp 'make-obsolete-variable)
 619     (make-obsolete-variable 'py-mode-hook 'python-mode-hook))
 620
 621(defvar py-mode-map ()
 622  "Keymap used in `python-mode' buffers.")
 623(if py-mode-map
 624    nil
 625  (setq py-mode-map (make-sparse-keymap))
 626  ;; electric keys
 627  (define-key py-mode-map ":" 'py-electric-colon)
 628  ;; indentation level modifiers
 629  (define-key py-mode-map "\C-c\C-l"  'py-shift-region-left)
 630  (define-key py-mode-map "\C-c\C-r"  'py-shift-region-right)
 631  (define-key py-mode-map "\C-c<"     'py-shift-region-left)
 632  (define-key py-mode-map "\C-c>"     'py-shift-region-right)
 633  ;; subprocess commands
 634  (define-key py-mode-map "\C-c\C-c"  'py-execute-buffer)
 635  (define-key py-mode-map "\C-c\C-m"  'py-execute-import-or-reload)
 636  (define-key py-mode-map "\C-c\C-s"  'py-execute-string)
 637  (define-key py-mode-map "\C-c|"     'py-execute-region)
 638  (define-key py-mode-map "\e\C-x"    'py-execute-def-or-class)
 639  (define-key py-mode-map "\C-c!"     'py-shell)
 640  (define-key py-mode-map "\C-c\C-t"  'py-toggle-shells)
 641  ;; Caution!  Enter here at your own risk.  We are trying to support
 642  ;; several behaviors and it gets disgusting. :-( This logic ripped
 643  ;; largely from CC Mode.
 644  ;;
 645  ;; In XEmacs 19, Emacs 19, and Emacs 20, we use this to bind
 646  ;; backwards deletion behavior to DEL, which both Delete and
 647  ;; Backspace get translated to.  There's no way to separate this
 648  ;; behavior in a clean way, so deal with it!  Besides, it's been
 649  ;; this way since the dawn of time.
 650  (if (not (boundp 'delete-key-deletes-forward))
 651      (define-key py-mode-map "\177" 'py-electric-backspace)
 652    ;; However, XEmacs 20 actually achieved enlightenment.  It is
 653    ;; possible to sanely define both backward and forward deletion
 654    ;; behavior under X separately (TTYs are forever beyond hope, but
 655    ;; who cares?  XEmacs 20 does the right thing with these too).
 656    (define-key py-mode-map [delete]    'py-electric-delete)
 657    (define-key py-mode-map [backspace] 'py-electric-backspace))
 658  ;; Separate M-BS from C-M-h.  The former should remain
 659  ;; backward-kill-word.
 660  (define-key py-mode-map [(control meta h)] 'py-mark-def-or-class)
 661  (define-key py-mode-map "\C-c\C-k"  'py-mark-block)
 662  ;; Miscellaneous
 663  (define-key py-mode-map "\C-c:"     'py-guess-indent-offset)
 664  (define-key py-mode-map "\C-c\t"    'py-indent-region)
 665  (define-key py-mode-map "\C-c\C-d"  'py-pdbtrack-toggle-stack-tracking)
 666  (define-key py-mode-map "\C-c\C-n"  'py-next-statement)
 667  (define-key py-mode-map "\C-c\C-p"  'py-previous-statement)
 668  (define-key py-mode-map "\C-c\C-u"  'py-goto-block-up)
 669  (define-key py-mode-map "\C-c#"     'py-comment-region)
 670  (define-key py-mode-map "\C-c?"     'py-describe-mode)
 671  (define-key py-mode-map "\C-c\C-h"  'py-help-at-point)
 672  (define-key py-mode-map "\e\C-a"    'py-beginning-of-def-or-class)
 673  (define-key py-mode-map "\e\C-e"    'py-end-of-def-or-class)
 674  (define-key py-mode-map "\C-c-"     'py-up-exception)
 675  (define-key py-mode-map "\C-c="     'py-down-exception)
 676  ;; stuff that is `standard' but doesn't interface well with
 677  ;; python-mode, which forces us to rebind to special commands
 678  (define-key py-mode-map "\C-xnd"    'py-narrow-to-defun)
 679  ;; information
 680  (define-key py-mode-map "\C-c\C-b" 'py-submit-bug-report)
 681  (define-key py-mode-map "\C-c\C-v" 'py-version)
 682  (define-key py-mode-map "\C-c\C-w" 'py-pychecker-run)
 683  ;; shadow global bindings for newline-and-indent w/ the py- version.
 684  ;; BAW - this is extremely bad form, but I'm not going to change it
 685  ;; for now.
 686  (mapcar #'(lambda (key)
 687	      (define-key py-mode-map key 'py-newline-and-indent))
 688	  (where-is-internal 'newline-and-indent))
 689  ;; Force RET to be py-newline-and-indent even if it didn't get
 690  ;; mapped by the above code.  motivation: Emacs' default binding for
 691  ;; RET is `newline' and C-j is `newline-and-indent'.  Most Pythoneers
 692  ;; expect RET to do a `py-newline-and-indent' and any Emacsers who
 693  ;; dislike this are probably knowledgeable enough to do a rebind.
 694  ;; However, we do *not* change C-j since many Emacsers have already
 695  ;; swapped RET and C-j and they don't want C-j bound to `newline' to
 696  ;; change.
 697  (define-key py-mode-map "\C-m" 'py-newline-and-indent)
 698  )
 699
 700(defvar py-mode-output-map nil
 701  "Keymap used in *Python Output* buffers.")
 702(if py-mode-output-map
 703    nil
 704  (setq py-mode-output-map (make-sparse-keymap))
 705  (define-key py-mode-output-map [button2]  'py-mouseto-exception)
 706  (define-key py-mode-output-map "\C-c\C-c" 'py-goto-exception)
 707  ;; TBD: Disable all self-inserting keys.  This is bogus, we should
 708  ;; really implement this as *Python Output* buffer being read-only
 709  (mapcar #' (lambda (key)
 710	       (define-key py-mode-output-map key
 711		 #'(lambda () (interactive) (beep))))
 712	     (where-is-internal 'self-insert-command))
 713  )
 714
 715(defvar py-shell-map nil
 716  "Keymap used in *Python* shell buffers.")
 717(if py-shell-map
 718    nil
 719  (setq py-shell-map (copy-keymap comint-mode-map))
 720  (define-key py-shell-map [tab]   'tab-to-tab-stop)
 721  (define-key py-shell-map "\C-c-" 'py-up-exception)
 722  (define-key py-shell-map "\C-c=" 'py-down-exception)
 723  )
 724
 725(defvar py-mode-syntax-table nil
 726  "Syntax table used in `python-mode' buffers.")
 727(when (not py-mode-syntax-table)
 728  (setq py-mode-syntax-table (make-syntax-table))
 729  (modify-syntax-entry ?\( "()" py-mode-syntax-table)
 730  (modify-syntax-entry ?\) ")(" py-mode-syntax-table)
 731  (modify-syntax-entry ?\[ "(]" py-mode-syntax-table)
 732  (modify-syntax-entry ?\] ")[" py-mode-syntax-table)
 733  (modify-syntax-entry ?\{ "(}" py-mode-syntax-table)
 734  (modify-syntax-entry ?\} "){" py-mode-syntax-table)
 735  ;; Add operator symbols misassigned in the std table
 736  (modify-syntax-entry ?\$ "."  py-mode-syntax-table)
 737  (modify-syntax-entry ?\% "."  py-mode-syntax-table)
 738  (modify-syntax-entry ?\& "."  py-mode-syntax-table)
 739  (modify-syntax-entry ?\* "."  py-mode-syntax-table)
 740  (modify-syntax-entry ?\+ "."  py-mode-syntax-table)
 741  (modify-syntax-entry ?\- "."  py-mode-syntax-table)
 742  (modify-syntax-entry ?\/ "."  py-mode-syntax-table)
 743  (modify-syntax-entry ?\< "."  py-mode-syntax-table)
 744  (modify-syntax-entry ?\= "."  py-mode-syntax-table)
 745  (modify-syntax-entry ?\> "."  py-mode-syntax-table)
 746  (modify-syntax-entry ?\| "."  py-mode-syntax-table)
 747  ;; For historical reasons, underscore is word class instead of
 748  ;; symbol class.  GNU conventions say it should be symbol class, but
 749  ;; there's a natural conflict between what major mode authors want
 750  ;; and what users expect from `forward-word' and `backward-word'.
 751  ;; Guido and I have hashed this out and have decided to keep
 752  ;; underscore in word class.  If you're tempted to change it, try
 753  ;; binding M-f and M-b to py-forward-into-nomenclature and
 754  ;; py-backward-into-nomenclature instead.  This doesn't help in all
 755  ;; situations where you'd want the different behavior
 756  ;; (e.g. backward-kill-word).
 757  (modify-syntax-entry ?\_ "w"  py-mode-syntax-table)
 758  ;; Both single quote and double quote are string delimiters
 759  (modify-syntax-entry ?\' "\"" py-mode-syntax-table)
 760  (modify-syntax-entry ?\" "\"" py-mode-syntax-table)
 761  ;; backquote is open and close paren
 762  (modify-syntax-entry ?\` "$"  py-mode-syntax-table)
 763  ;; comment delimiters
 764  (modify-syntax-entry ?\# "<"  py-mode-syntax-table)
 765  (modify-syntax-entry ?\n ">"  py-mode-syntax-table)
 766  )
 767
 768;; An auxiliary syntax table which places underscore and dot in the
 769;; symbol class for simplicity
 770(defvar py-dotted-expression-syntax-table nil
 771  "Syntax table used to identify Python dotted expressions.")
 772(when (not py-dotted-expression-syntax-table)
 773  (setq py-dotted-expression-syntax-table
 774	(copy-syntax-table py-mode-syntax-table))
 775  (modify-syntax-entry ?_ "_" py-dotted-expression-syntax-table)
 776  (modify-syntax-entry ?. "_" py-dotted-expression-syntax-table))
 777
 778
 779
 780;; Utilities
 781(defmacro py-safe (&rest body)
 782  "Safely execute BODY, return nil if an error occurred."
 783  (` (condition-case nil
 784	 (progn (,@ body))
 785       (error nil))))
 786
 787(defsubst py-keep-region-active ()
 788  "Keep the region active in XEmacs."
 789  ;; Ignore byte-compiler warnings you might see.  Also note that
 790  ;; FSF's Emacs 19 does it differently; its policy doesn't require us
 791  ;; to take explicit action.
 792  (and (boundp 'zmacs-region-stays)
 793       (setq zmacs-region-stays t)))
 794
 795(defsubst py-point (position)
 796  "Returns the value of point at certain commonly referenced POSITIONs.
 797POSITION can be one of the following symbols:
 798
 799  bol  -- beginning of line
 800  eol  -- end of line
 801  bod  -- beginning of def or class
 802  eod  -- end of def or class
 803  bob  -- beginning of buffer
 804  eob  -- end of buffer
 805  boi  -- back to indentation
 806  bos  -- beginning of statement
 807
 808This function does not modify point or mark."
 809  (let ((here (point)))
 810    (cond
 811     ((eq position 'bol) (beginning-of-line))
 812     ((eq position 'eol) (end-of-line))
 813     ((eq position 'bod) (py-beginning-of-def-or-class 'either))
 814     ((eq position 'eod) (py-end-of-def-or-class 'either))
 815     ;; Kind of funny, I know, but useful for py-up-exception.
 816     ((eq position 'bob) (beginning-of-buffer))
 817     ((eq position 'eob) (end-of-buffer))
 818     ((eq position 'boi) (back-to-indentation))
 819     ((eq position 'bos) (py-goto-initial-line))
 820     (t (error "Unknown buffer position requested: %s" position))
 821     )
 822    (prog1
 823	(point)
 824      (goto-char here))))
 825
 826(defsubst py-highlight-line (from to file line)
 827  (cond
 828   ((fboundp 'make-extent)
 829    ;; XEmacs
 830    (let ((e (make-extent from to)))
 831      (set-extent-property e 'mouse-face 'highlight)
 832      (set-extent-property e 'py-exc-info (cons file line))
 833      (set-extent-property e 'keymap py-mode-output-map)))
 834   (t
 835    ;; Emacs -- Please port this!
 836    )
 837   ))
 838
 839(defun py-in-literal (&optional lim)
 840  "Return non-nil if point is in a Python literal (a comment or string).
 841Optional argument LIM indicates the beginning of the containing form,
 842i.e. the limit on how far back to scan."
 843  ;; This is the version used for non-XEmacs, which has a nicer
 844  ;; interface.
 845  ;;
 846  ;; WARNING: Watch out for infinite recursion.
 847  (let* ((lim (or lim (py-point 'bod)))
 848	 (state (parse-partial-sexp lim (point))))
 849    (cond
 850     ((nth 3 state) 'string)
 851     ((nth 4 state) 'comment)
 852     (t nil))))
 853
 854;; XEmacs has a built-in function that should make this much quicker.
 855;; In this case, lim is ignored
 856(defun py-fast-in-literal (&optional lim)
 857  "Fast version of `py-in-literal', used only by XEmacs.
 858Optional LIM is ignored."
 859  ;; don't have to worry about context == 'block-comment
 860  (buffer-syntactic-context))
 861
 862(if (fboundp 'buffer-syntactic-context)
 863    (defalias 'py-in-literal 'py-fast-in-literal))
 864
 865
 866
 867;; Menu definitions, only relevent if you have the easymenu.el package
 868;; (standard in the latest Emacs 19 and XEmacs 19 distributions).
 869(defvar py-menu nil
 870  "Menu for Python Mode.
 871This menu will get created automatically if you have the `easymenu'
 872package.  Note that the latest X/Emacs releases contain this package.")
 873
 874(and (py-safe (require 'easymenu) t)
 875     (easy-menu-define
 876      py-menu py-mode-map "Python Mode menu"
 877      '("Python"
 878	["Comment Out Region"   py-comment-region  (mark)]
 879	["Uncomment Region"     (py-comment-region (point) (mark) '(4)) (mark)]
 880	"-"
 881	["Mark current block"   py-mark-block t]
 882	["Mark current def"     py-mark-def-or-class t]
 883	["Mark current class"   (py-mark-def-or-class t) t]
 884	"-"
 885	["Shift region left"    py-shift-region-left (mark)]
 886	["Shift region right"   py-shift-region-right (mark)]
 887	"-"
 888	["Import/reload file"   py-execute-import-or-reload t]
 889	["Execute buffer"       py-execute-buffer t]
 890	["Execute region"       py-execute-region (mark)]
 891	["Execute def or class" py-execute-def-or-class (mark)]
 892	["Execute string"       py-execute-string t]
 893	["Start interpreter..." py-shell t]
 894	"-"
 895	["Go to start of block" py-goto-block-up t]
 896	["Go to start of class" (py-beginning-of-def-or-class t) t]
 897	["Move to end of class" (py-end-of-def-or-class t) t]
 898	["Move to start of def" py-beginning-of-def-or-class t]
 899	["Move to end of def"   py-end-of-def-or-class t]
 900	"-"
 901	["Describe mode"        py-describe-mode t]
 902	)))
 903
 904
 905
 906;; Imenu definitions
 907(defvar py-imenu-class-regexp
 908  (concat				; <<classes>>
 909   "\\("				;
 910   "^[ \t]*"				; newline and maybe whitespace
 911   "\\(class[ \t]+[a-zA-Z0-9_]+\\)"	; class name
 912					; possibly multiple superclasses
 913   "\\([ \t]*\\((\\([a-zA-Z0-9_,. \t\n]\\)*)\\)?\\)"
 914   "[ \t]*:"				; and the final :
 915   "\\)"				; >>classes<<
 916   )
 917  "Regexp for Python classes for use with the Imenu package."
 918  )
 919
 920(defvar py-imenu-method-regexp
 921  (concat                               ; <<methods and functions>>
 922   "\\("                                ;
 923   "^[ \t]*"                            ; new line and maybe whitespace
 924   "\\(def[ \t]+"                       ; function definitions start with def
 925   "\\([a-zA-Z0-9_]+\\)"                ;   name is here
 926					;   function arguments...
 927;;   "[ \t]*(\\([-+/a-zA-Z0-9_=,\* \t\n.()\"'#]*\\))"
 928   "[ \t]*(\\([^:#]*\\))"
 929   "\\)"                                ; end of def
 930   "[ \t]*:"                            ; and then the :
 931   "\\)"                                ; >>methods and functions<<
 932   )
 933  "Regexp for Python methods/functions for use with the Imenu package."
 934  )
 935
 936(defvar py-imenu-method-no-arg-parens '(2 8)
 937  "Indices into groups of the Python regexp for use with Imenu.
 938
 939Using these values will result in smaller Imenu lists, as arguments to
 940functions are not listed.
 941
 942See the variable `py-imenu-show-method-args-p' for more
 943information.")
 944
 945(defvar py-imenu-method-arg-parens '(2 7)
 946  "Indices into groups of the Python regexp for use with imenu.
 947Using these values will result in large Imenu lists, as arguments to
 948functions are listed.
 949
 950See the variable `py-imenu-show-method-args-p' for more
 951information.")
 952
 953;; Note that in this format, this variable can still be used with the
 954;; imenu--generic-function. Otherwise, there is no real reason to have
 955;; it.
 956(defvar py-imenu-generic-expression
 957  (cons
 958   (concat
 959    py-imenu-class-regexp
 960    "\\|"				; or...
 961    py-imenu-method-regexp
 962    )
 963   py-imenu-method-no-arg-parens)
 964  "Generic Python expression which may be used directly with Imenu.
 965Used by setting the variable `imenu-generic-expression' to this value.
 966Also, see the function \\[py-imenu-create-index] for a better
 967alternative for finding the index.")
 968
 969;; These next two variables are used when searching for the Python
 970;; class/definitions. Just saving some time in accessing the
 971;; generic-python-expression, really.
 972(defvar py-imenu-generic-regexp nil)
 973(defvar py-imenu-generic-parens nil)
 974
 975
 976(defun py-imenu-create-index-function ()
 977  "Python interface function for the Imenu package.
 978Finds all Python classes and functions/methods. Calls function
 979\\[py-imenu-create-index-engine].  See that function for the details
 980of how this works."
 981  (setq py-imenu-generic-regexp (car py-imenu-generic-expression)
 982	py-imenu-generic-parens (if py-imenu-show-method-args-p
 983				    py-imenu-method-arg-parens
 984				  py-imenu-method-no-arg-parens))
 985  (goto-char (point-min))
 986  ;; Warning: When the buffer has no classes or functions, this will
 987  ;; return nil, which seems proper according to the Imenu API, but
 988  ;; causes an error in the XEmacs port of Imenu.  Sigh.
 989  (py-imenu-create-index-engine nil))
 990
 991(defun py-imenu-create-index-engine (&optional start-indent)
 992  "Function for finding Imenu definitions in Python.
 993
 994Finds all definitions (classes, methods, or functions) in a Python
 995file for the Imenu package.
 996
 997Returns a possibly nested alist of the form
 998
 999	(INDEX-NAME . INDEX-POSITION)
1000
1001The second element of the alist may be an alist, producing a nested
1002list as in
1003
1004	(INDEX-NAME . INDEX-ALIST)
1005
1006This function should not be called directly, as it calls itself
1007recursively and requires some setup.  Rather this is the engine for
1008the function \\[py-imenu-create-index-function].
1009
1010It works recursively by looking for all definitions at the current
1011indention level.  When it finds one, it adds it to the alist.  If it
1012finds a definition at a greater indentation level, it removes the
1013previous definition from the alist. In its place it adds all
1014definitions found at the next indentation level.  When it finds a
1015definition that is less indented then the current level, it returns
1016the alist it has created thus far.
1017
1018The optional argument START-INDENT indicates the starting indentation
1019at which to continue looking for Python classes, methods, or
1020functions.  If this is not supplied, the function uses the indentation
1021of the first definition found."
1022  (let (index-alist
1023	sub-method-alist
1024	looking-p
1025	def-name prev-name
1026	cur-indent def-pos
1027	(class-paren (first  py-imenu-generic-parens))
1028	(def-paren   (second py-imenu-generic-parens)))
1029    (setq looking-p
1030	  (re-search-forward py-imenu-generic-regexp (point-max) t))
1031    (while looking-p
1032      (save-excursion
1033	;; used to set def-name to this value but generic-extract-name
1034	;; is new to imenu-1.14. this way it still works with
1035	;; imenu-1.11
1036	;;(imenu--generic-extract-name py-imenu-generic-parens))
1037	(let ((cur-paren (if (match-beginning class-paren)
1038			     class-paren def-paren)))
1039	  (setq def-name
1040		(buffer-substring-no-properties (match-beginning cur-paren)
1041						(match-end cur-paren))))
1042	(save-match-data
1043	  (py-beginning-of-def-or-class 'either))
1044	(beginning-of-line)
1045	(setq cur-indent (current-indentation)))
1046      ;; HACK: want to go to the next correct definition location.  We
1047      ;; explicitly list them here but it would be better to have them
1048      ;; in a list.
1049      (setq def-pos
1050	    (or (match-beginning class-paren)
1051		(match-beginning def-paren)))
1052      ;; if we don't have a starting indent level, take this one
1053      (or start-indent
1054	  (setq start-indent cur-indent))
1055      ;; if we don't have class name yet, take this one
1056      (or prev-name
1057	  (setq prev-name def-name))
1058      ;; what level is the next definition on?  must be same, deeper
1059      ;; or shallower indentation
1060      (cond
1061       ;; Skip code in comments and strings
1062       ((py-in-literal))
1063       ;; at the same indent level, add it to the list...
1064       ((= start-indent cur-indent)
1065	(push (cons def-name def-pos) index-alist))
1066       ;; deeper indented expression, recurse
1067       ((< start-indent cur-indent)
1068	;; the point is currently on the expression we're supposed to
1069	;; start on, so go back to the last expression. The recursive
1070	;; call will find this place again and add it to the correct
1071	;; list
1072	(re-search-backward py-imenu-generic-regexp (point-min) 'move)
1073	(setq sub-method-alist (py-imenu-create-index-engine cur-indent))
1074	(if sub-method-alist
1075	    ;; we put the last element on the index-alist on the start
1076	    ;; of the submethod alist so the user can still get to it.
1077	    (let ((save-elmt (pop index-alist)))
1078	      (push (cons prev-name
1079			  (cons save-elmt sub-method-alist))
1080		    index-alist))))
1081       ;; found less indented expression, we're done.
1082       (t
1083	(setq looking-p nil)
1084	(re-search-backward py-imenu-generic-regexp (point-min) t)))
1085      ;; end-cond
1086      (setq prev-name def-name)
1087      (and looking-p
1088	   (setq looking-p
1089		 (re-search-forward py-imenu-generic-regexp
1090				    (point-max) 'move))))
1091    (nreverse index-alist)))
1092
1093
1094
1095(defun py-choose-shell-by-shebang ()
1096  "Choose CPython or Jython mode by looking at #! on the first line.
1097Returns the appropriate mode function.
1098Used by `py-choose-shell', and similar to but distinct from
1099`set-auto-mode', though it uses `auto-mode-interpreter-regexp' (if available)."
1100  ;; look for an interpreter specified in the first line
1101  ;; similar to set-auto-mode (files.el)
1102  (let* ((re (if (boundp 'auto-mode-interpreter-regexp)
1103		 auto-mode-interpreter-regexp
1104	       ;; stolen from Emacs 21.2
1105	       "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)"))
1106	 (interpreter (save-excursion
1107			(goto-char (point-min))
1108			(if (looking-at re)
1109			    (match-string 2)
1110			  "")))
1111	 elt)
1112    ;; Map interpreter name to a mode.
1113    (setq elt (assoc (file-name-nondirectory interpreter)
1114		     py-shell-alist))
1115    (and elt (caddr elt))))
1116
1117
1118
1119(defun py-choose-shell-by-import ()
1120  "Choose CPython or Jython mode based imports.
1121If a file imports any packages in `py-jython-packages', within
1122`py-import-check-point-max' characters from the start of the file,
1123return `jython', otherwise return nil."
1124  (let (mode)
1125    (save-excursion
1126      (goto-char (point-min))
1127      (while (and (not mode)
1128		  (search-forward-regexp
1129		   "^\\(\\(from\\)\\|\\(import\\)\\) \\([^ \t\n.]+\\)"
1130		   py-import-check-point-max t))
1131	(setq mode (and (member (match-string 4) py-jython-packages)
1132			'jython
1133			))))
1134    mode))
1135
1136
1137(defun py-choose-shell ()
1138  "Choose CPython or Jython mode. Returns the appropriate mode function.
1139This does the following:
1140 - look for an interpreter with `py-choose-shell-by-shebang'
1141 - examine imports using `py-choose-shell-by-import'
1142 - default to the variable `py-default-interpreter'"
1143  (interactive)
1144  (or (py-choose-shell-by-shebang)
1145      (py-choose-shell-by-import)
1146      py-default-interpreter
1147;      'cpython ;; don't use to py-default-interpreter, because default
1148;               ;; is only way to choose CPython
1149      ))
1150
1151
1152;;;###autoload
1153(defun python-mode ()
1154  "Major mode for editing Python files.
1155To submit a problem report, enter `\\[py-submit-bug-report]' from a
1156`python-mode' buffer.  Do `\\[py-describe-mode]' for detailed
1157documentation.  To see what version of `python-mode' you are running,
1158enter `\\[py-version]'.
1159
1160This mode knows about Python indentation, tokens, comments and
1161continuation lines.  Paragraphs are separated by blank lines only.
1162
1163COMMANDS
1164\\{py-mode-map}
1165VARIABLES
1166
1167py-indent-offset\t\tindentation increment
1168py-block-comment-prefix\t\tcomment string used by `comment-region'
1169py-python-command\t\tshell command to invoke Python interpreter
1170py-temp-directory\t\tdirectory used for temp files (if needed)
1171py-beep-if-tab-change\t\tring the bell if `tab-width' is changed"
1172  (interactive)
1173  ;; set up local variables
1174  (kill-all-local-variables)
1175  (make-local-variable 'font-lock-defaults)
1176  (make-local-variable 'paragraph-separate)
1177  (make-local-variable 'paragraph-start)
1178  (make-local-variable 'require-final-newline)
1179  (make-local-variable 'comment-start)
1180  (make-local-variable 'comment-end)
1181  (make-local-variable 'comment-start-skip)
1182  (make-local-variable 'comment-column)
1183  (make-local-variable 'comment-indent-function)
1184  (make-local-variable 'indent-region-function)
1185  (make-local-variable 'indent-line-function)
1186  (make-local-variable 'add-log-current-defun-function)
1187  (make-local-variable 'fill-paragraph-function)
1188  ;;
1189  (set-syntax-table py-mode-syntax-table)
1190  (setq major-mode              'python-mode
1191	mode-name               "Python"
1192	local-abbrev-table      python-mode-abbrev-table
1193	font-lock-defaults      '(python-font-lock-keywords)
1194	paragraph-separate      "^[ \t]*$"
1195	paragraph-start         "^[ \t]*$"
1196	require-final-newline   t
1197	comment-start           "# "
1198	comment-end             ""
1199	comment-start-skip      "# *"
1200	comment-column          40
1201	comment-indent-function 'py-comment-indent-function
1202	indent-region-function  'py-indent-region
1203	indent-line-function    'py-indent-line
1204	;; tell add-log.el how to find the current function/method/variable
1205	add-log-current-defun-function 'py-current-defun
1206
1207	fill-paragraph-function 'py-fill-paragraph
1208	)
1209  (use-local-map py-mode-map)
1210  ;; add the menu
1211  (if py-menu
1212      (easy-menu-add py-menu))
1213  ;; Emacs 19 requires this
1214  (if (boundp 'comment-multi-line)
1215      (setq comment-multi-line nil))
1216  ;; Install Imenu if available
1217  (when (py-safe (require 'imenu))
1218    (setq imenu-create-index-function #'py-imenu-create-index-function)
1219    (setq imenu-generic-expression py-imenu-generic-expression)
1220    (if (fboundp 'imenu-add-to-menubar)
1221	(imenu-add-to-menubar (format "%s-%s" "IM" mode-name)))
1222    )
1223  ;; Run the mode hook.  Note that py-mode-hook is deprecated.
1224  (if python-mode-hook
1225      (run-hooks 'python-mode-hook)
1226    (run-hooks 'py-mode-hook))
1227  ;; Now do the automagical guessing
1228  (if py-smart-indentation
1229    (let ((offset py-indent-offset))
1230      ;; It's okay if this fails to guess a good value
1231      (if (and (py-safe (py-guess-indent-offset))
1232	       (<= py-indent-offset 8)
1233	       (>= py-indent-offset 2))
1234	  (setq offset py-indent-offset))
1235      (setq py-indent-offset offset)
1236      ;; Only turn indent-tabs-mode off if tab-width !=
1237      ;; py-indent-offset.  Never turn it on, because the user must
1238      ;; have explicitly turned it off.
1239      (if (/= tab-width py-indent-offset)
1240	  (setq indent-tabs-mode nil))
1241      ))
1242  ;; Set the default shell if not already set
1243  (when (null py-which-shell)
1244    (py-toggle-shells (py-choose-shell))))
1245
1246
1247(make-obsolete 'jpython-mode 'jython-mode)
1248(defun jython-mode ()
1249  "Major mode for editing Jython/Jython files.
1250This is a simple wrapper around `python-mode'.
1251It runs `jython-mode-hook' then calls `python-mode.'
1252It is added to `interpreter-mode-alist' and `py-choose-shell'.
1253"
1254  (interactive)
1255  (python-mode)
1256  (py-toggle-shells 'jython)
1257  (when jython-mode-hook
1258      (run-hooks 'jython-mode-hook)))
1259
1260
1261;; It's handy to add recognition of Python files to the
1262;; interpreter-mode-alist and to auto-mode-alist.  With the former, we
1263;; can specify different `derived-modes' based on the #! line, but
1264;; with the latter, we can't.  So we just won't add them if they're
1265;; already added.
1266;;;###autoload
1267(let ((modes '(("jython" . jython-mode)
1268	       ("python" . python-mode))))
1269  (while modes
1270    (when (not (assoc (car modes) interpreter-mode-alist))
1271      (push (car modes) interpreter-mode-alist))
1272    (setq modes (cdr modes))))
1273;;;###autoload
1274(when (not (or (rassq 'python-mode auto-mode-alist)
1275	       (rassq 'jython-mode auto-mode-alist)))
1276  (push '("\\.py$" . python-mode) auto-mode-alist))
1277
1278
1279
1280;; electric characters
1281(defun py-outdent-p ()
1282  "Returns non-nil if the current line should dedent one level."
1283  (save-excursion
1284    (and (progn (back-to-indentation)
1285		(looking-at py-outdent-re))
1286	 ;; short circuit infloop on illegal construct
1287	 (not (bobp))
1288	 (progn (forward-line -1)
1289		(py-goto-initial-line)
1290		(back-to-indentation)
1291		(while (or (looking-at py-blank-or-comment-re)
1292			   (bobp))
1293		  (backward-to-indentation 1))
1294		(not (looking-at py-no-outdent-re)))
1295	 )))
1296
1297(defun py-electric-colon (arg)
1298  "Insert a colon.
1299In certain cases the line is dedented appropriately.  If a numeric
1300argument ARG is provided, that many colons are inserted
1301non-electrically.  Electric behavior is inhibited inside a string or
1302comment."
1303  (interactive "*P")
1304  (self-insert-command (prefix-numeric-value arg))
1305  ;; are we in a string or comment?
1306  (if (save-excursion
1307	(let ((pps (parse-partial-sexp (save-excursion
1308					 (py-beginning-of-def-or-class)
1309					 (point))
1310				       (point))))
1311	  (not (or (nth 3 pps) (nth 4 pps)))))
1312      (save-excursion
1313	(let ((here (point))
1314	      (outdent 0)
1315	      (indent (py-compute-indentation t)))
1316	  (if (and (not arg)
1317		   (py-outdent-p)
1318		   (= indent (save-excursion
1319			       (py-next-statement -1)
1320			       (py-compute-indentation t)))
1321		   )
1322	      (setq outdent py-indent-offset))
1323	  ;; Don't indent, only dedent.  This assumes that any lines
1324	  ;; that are already dedented relative to
1325	  ;; py-compute-indentation were put there on …

Large files files are truncated, but you can click here to view the full file