Derive from prog-mode, use derived-mode-p, and fix up various
[emacs.git] / lisp / progmodes / python.el
blob2428ecb7555684d112f8472ee2eeeee0bdd13768
1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
6 ;; Author: Dave Love <fx@gnu.org>
7 ;; Maintainer: FSF
8 ;; Created: Nov 2003
9 ;; Keywords: languages
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;;; Commentary:
28 ;; Major mode for editing Python, with support for inferior processes.
30 ;; There is another Python mode, python-mode.el:
31 ;; http://launchpad.net/python-mode
32 ;; used by XEmacs, and originally maintained with Python.
33 ;; That isn't covered by an FSF copyright assignment (?), unlike this
34 ;; code, and seems not to be well-maintained for Emacs (though I've
35 ;; submitted fixes). This mode is rather simpler and is better in
36 ;; other ways. In particular, using the syntax functions with text
37 ;; properties maintained by font-lock makes it more correct with
38 ;; arbitrary string and comment contents.
40 ;; This doesn't implement all the facilities of python-mode.el. Some
41 ;; just need doing, e.g. catching exceptions in the inferior Python
42 ;; buffer (but see M-x pdb for debugging). [Actually, the use of
43 ;; `compilation-shell-minor-mode' now is probably enough for that.]
44 ;; Others don't seem appropriate. For instance,
45 ;; `forward-into-nomenclature' should be done separately, since it's
46 ;; not specific to Python, and I've installed a minor mode to do the
47 ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
48 ;; feature, `subword-mode' which is intended to have a similar
49 ;; effect, but actually only affects word-oriented keybindings.]
51 ;; Other things seem more natural or canonical here, e.g. the
52 ;; {beginning,end}-of-defun implementation dealing with nested
53 ;; definitions, and the inferior mode following `cmuscheme'. (The
54 ;; inferior mode can find the source of errors from
55 ;; `python-send-region' & al via `compilation-shell-minor-mode'.)
56 ;; There is (limited) symbol completion using lookup in Python and
57 ;; Eldoc support also using the inferior process. Successive TABs
58 ;; cycle between possible indentations for the line.
60 ;; Even where it has similar facilities, this mode is incompatible
61 ;; with python-mode.el in some respects. For instance, various key
62 ;; bindings are changed to obey Emacs conventions.
64 ;; TODO: See various Fixmes below.
66 ;; Fixme: This doesn't support (the nascent) Python 3 .
68 ;;; Code:
70 (require 'comint)
72 (eval-when-compile
73 (require 'compile)
74 (require 'hippie-exp))
76 (autoload 'comint-mode "comint")
78 (defgroup python nil
79 "Silly walks in the Python language."
80 :group 'languages
81 :version "22.1"
82 :link '(emacs-commentary-link "python"))
84 ;;;###autoload
85 (add-to-list 'interpreter-mode-alist (cons (purecopy "jython") 'jython-mode))
86 ;;;###autoload
87 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
88 ;;;###autoload
89 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
90 (add-to-list 'same-window-buffer-names (purecopy "*Python*"))
92 ;;;; Font lock
94 (defvar python-font-lock-keywords
95 `(,(rx symbol-start
96 ;; From v 2.7 reference, § keywords.
97 ;; def and class dealt with separately below
98 (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
99 "except" "exec" "finally" "for" "from" "global" "if"
100 "import" "in" "is" "lambda" "not" "or" "pass" "print"
101 "raise" "return" "try" "while" "with" "yield"
102 ;; Not real keywords, but close enough to be fontified as such
103 "self" "True" "False")
104 symbol-end)
105 (,(rx symbol-start "None" symbol-end) ; see § Keywords in 2.7 manual
106 . font-lock-constant-face)
107 ;; Definitions
108 (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
109 (1 font-lock-keyword-face) (2 font-lock-type-face))
110 (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
111 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
112 ;; Top-level assignments are worth highlighting.
113 (,(rx line-start (group (1+ (or word ?_))) (0+ space)
114 (opt (or "+" "-" "*" "**" "/" "//" "&" "%" "|" "^" "<<" ">>")) "=")
115 (1 font-lock-variable-name-face))
116 ;; Decorators.
117 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
118 (0+ "." (1+ (or word ?_)))))
119 (1 font-lock-type-face))
120 ;; Built-ins. (The next three blocks are from
121 ;; `__builtin__.__dict__.keys()' in Python 2.7) These patterns
122 ;; are debateable, but they at least help to spot possible
123 ;; shadowing of builtins.
124 (,(rx symbol-start (or
125 ;; exceptions
126 "ArithmeticError" "AssertionError" "AttributeError"
127 "BaseException" "DeprecationWarning" "EOFError"
128 "EnvironmentError" "Exception" "FloatingPointError"
129 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
130 "ImportWarning" "IndentationError" "IndexError" "KeyError"
131 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
132 "NotImplemented" "NotImplementedError" "OSError"
133 "OverflowError" "PendingDeprecationWarning" "ReferenceError"
134 "RuntimeError" "RuntimeWarning" "StandardError"
135 "StopIteration" "SyntaxError" "SyntaxWarning" "SystemError"
136 "SystemExit" "TabError" "TypeError" "UnboundLocalError"
137 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
138 "UnicodeTranslateError" "UnicodeWarning" "UserWarning"
139 "ValueError" "Warning" "ZeroDivisionError"
140 ;; Python 2.7
141 "BufferError" "BytesWarning" "WindowsError") symbol-end)
142 . font-lock-type-face)
143 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
144 (group (or
145 ;; callable built-ins, fontified when not appearing as
146 ;; object attributes
147 "abs" "all" "any" "apply" "basestring" "bool" "buffer" "callable"
148 "chr" "classmethod" "cmp" "coerce" "compile" "complex"
149 "copyright" "credits" "delattr" "dict" "dir" "divmod"
150 "enumerate" "eval" "execfile" "exit" "file" "filter" "float"
151 "frozenset" "getattr" "globals" "hasattr" "hash" "help"
152 "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
153 "iter" "len" "license" "list" "locals" "long" "map" "max"
154 "min" "object" "oct" "open" "ord" "pow" "property" "quit"
155 "range" "raw_input" "reduce" "reload" "repr" "reversed"
156 "round" "set" "setattr" "slice" "sorted" "staticmethod"
157 "str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars"
158 "xrange" "zip"
159 ;; Python 2.7.
160 "bin" "bytearray" "bytes" "format" "memoryview" "next" "print"
161 )) symbol-end)
162 (1 font-lock-builtin-face))
163 (,(rx symbol-start (or
164 ;; other built-ins
165 "True" "False" "None" "Ellipsis"
166 "_" "__debug__" "__doc__" "__import__" "__name__" "__package__")
167 symbol-end)
168 . font-lock-builtin-face)))
170 (defconst python-syntax-propertize-function
171 ;; Make outer chars of matching triple-quote sequences into generic
172 ;; string delimiters. Fixme: Is there a better way?
173 ;; First avoid a sequence preceded by an odd number of backslashes.
174 (syntax-propertize-rules
175 (;; ¡Backrefs don't work in syntax-propertize-rules!
176 (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
177 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
178 (3 (ignore (python-quote-syntax))))
179 ;; This doesn't really help.
180 ;;((rx (and ?\\ (group ?\n))) (1 " "))
183 (defun python-quote-syntax ()
184 "Put `syntax-table' property correctly on triple quote.
185 Used for syntactic keywords. N is the match number (1, 2 or 3)."
186 ;; Given a triple quote, we have to check the context to know
187 ;; whether this is an opening or closing triple or whether it's
188 ;; quoted anyhow, and should be ignored. (For that we need to do
189 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
190 ;; to use it here despite initial worries.) We also have to sort
191 ;; out a possible prefix -- well, we don't _have_ to, but I think it
192 ;; should be treated as part of the string.
194 ;; Test cases:
195 ;; ur"""ar""" x='"' # """
196 ;; x = ''' """ ' a
197 ;; '''
198 ;; x '"""' x """ \"""" x
199 (save-excursion
200 (goto-char (match-beginning 0))
201 (let ((syntax (save-match-data (syntax-ppss))))
202 (cond
203 ((eq t (nth 3 syntax)) ; after unclosed fence
204 ;; Consider property for the last char if in a fenced string.
205 (goto-char (nth 8 syntax)) ; fence position
206 (skip-chars-forward "uUrR") ; skip any prefix
207 ;; Is it a matching sequence?
208 (if (eq (char-after) (char-after (match-beginning 2)))
209 (put-text-property (match-beginning 3) (match-end 3)
210 'syntax-table (string-to-syntax "|"))))
211 ((match-end 1)
212 ;; Consider property for initial char, accounting for prefixes.
213 (put-text-property (match-beginning 1) (match-end 1)
214 'syntax-table (string-to-syntax "|")))
216 ;; Consider property for initial char, accounting for prefixes.
217 (put-text-property (match-beginning 2) (match-end 2)
218 'syntax-table (string-to-syntax "|"))))
221 ;; This isn't currently in `font-lock-defaults' as probably not worth
222 ;; it -- we basically only mess with a few normally-symbol characters.
224 ;; (defun python-font-lock-syntactic-face-function (state)
225 ;; "`font-lock-syntactic-face-function' for Python mode.
226 ;; Returns the string or comment face as usual, with side effect of putting
227 ;; a `syntax-table' property on the inside of the string or comment which is
228 ;; the standard syntax table."
229 ;; (if (nth 3 state)
230 ;; (save-excursion
231 ;; (goto-char (nth 8 state))
232 ;; (condition-case nil
233 ;; (forward-sexp)
234 ;; (error nil))
235 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
236 ;; 'syntax-table (standard-syntax-table))
237 ;; 'font-lock-string-face)
238 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
239 ;; 'syntax-table (standard-syntax-table))
240 ;; 'font-lock-comment-face))
242 ;;;; Keymap and syntax
244 (defvar python-mode-map
245 (let ((map (make-sparse-keymap)))
246 ;; Mostly taken from python-mode.el.
247 (define-key map ":" 'python-electric-colon)
248 (define-key map "\177" 'python-backspace)
249 (define-key map "\C-c<" 'python-shift-left)
250 (define-key map "\C-c>" 'python-shift-right)
251 (define-key map "\C-c\C-k" 'python-mark-block)
252 (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking)
253 (define-key map "\C-c\C-n" 'python-next-statement)
254 (define-key map "\C-c\C-p" 'python-previous-statement)
255 (define-key map "\C-c\C-u" 'python-beginning-of-block)
256 (define-key map "\C-c\C-f" 'python-describe-symbol)
257 (define-key map "\C-c\C-w" 'python-check)
258 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
259 (define-key map "\C-c\C-s" 'python-send-string)
260 (define-key map [?\C-\M-x] 'python-send-defun)
261 (define-key map "\C-c\C-r" 'python-send-region)
262 (define-key map "\C-c\M-r" 'python-send-region-and-go)
263 (define-key map "\C-c\C-c" 'python-send-buffer)
264 (define-key map "\C-c\C-z" 'python-switch-to-python)
265 (define-key map "\C-c\C-m" 'python-load-file)
266 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
267 (substitute-key-definition 'complete-symbol 'completion-at-point
268 map global-map)
269 (define-key map "\C-c\C-i" 'python-find-imports)
270 (define-key map "\C-c\C-t" 'python-expand-template)
271 (easy-menu-define python-menu map "Python Mode menu"
272 `("Python"
273 :help "Python-specific Features"
274 ["Shift region left" python-shift-left :active mark-active
275 :help "Shift by a single indentation step"]
276 ["Shift region right" python-shift-right :active mark-active
277 :help "Shift by a single indentation step"]
279 ["Mark block" python-mark-block
280 :help "Mark innermost block around point"]
281 ["Mark def/class" mark-defun
282 :help "Mark innermost definition around point"]
284 ["Start of block" python-beginning-of-block
285 :help "Go to start of innermost definition around point"]
286 ["End of block" python-end-of-block
287 :help "Go to end of innermost definition around point"]
288 ["Start of def/class" beginning-of-defun
289 :help "Go to start of innermost definition around point"]
290 ["End of def/class" end-of-defun
291 :help "Go to end of innermost definition around point"]
293 ("Templates..."
294 :help "Expand templates for compound statements"
295 :filter (lambda (&rest junk)
296 (abbrev-table-menu python-mode-abbrev-table)))
298 ["Start interpreter" python-shell
299 :help "Run `inferior' Python in separate buffer"]
300 ["Import/reload file" python-load-file
301 :help "Load into inferior Python session"]
302 ["Eval buffer" python-send-buffer
303 :help "Evaluate buffer en bloc in inferior Python session"]
304 ["Eval region" python-send-region :active mark-active
305 :help "Evaluate region en bloc in inferior Python session"]
306 ["Eval def/class" python-send-defun
307 :help "Evaluate current definition in inferior Python session"]
308 ["Switch to interpreter" python-switch-to-python
309 :help "Switch to inferior Python buffer"]
310 ["Set default process" python-set-proc
311 :help "Make buffer's inferior process the default"
312 :active (buffer-live-p python-buffer)]
313 ["Check file" python-check :help "Run pychecker"]
314 ["Debugger" pdb :help "Run pdb under GUD"]
316 ["Help on symbol" python-describe-symbol
317 :help "Use pydoc on symbol at point"]
318 ["Complete symbol" completion-at-point
319 :help "Complete (qualified) symbol before point"]
320 ["Find function" python-find-function
321 :help "Try to find source definition of function at point"]
322 ["Update imports" python-find-imports
323 :help "Update list of top-level imports for completion"]))
324 map))
325 ;; Fixme: add toolbar stuff for useful things like symbol help, send
326 ;; region, at least. (Shouldn't be specific to Python, obviously.)
327 ;; eric has items including: (un)indent, (un)comment, restart script,
328 ;; run script, debug script; also things for profiling, unit testing.
330 (defvar python-shell-map
331 (let ((map (copy-keymap comint-mode-map)))
332 (define-key map [tab] 'tab-to-tab-stop)
333 (define-key map "\C-c-" 'py-up-exception)
334 (define-key map "\C-c=" 'py-down-exception)
335 map)
336 "Keymap used in *Python* shell buffers.")
338 (defvar python-mode-syntax-table
339 (let ((table (make-syntax-table)))
340 ;; Give punctuation syntax to ASCII that normally has symbol
341 ;; syntax or has word syntax and isn't a letter.
342 (let ((symbol (string-to-syntax "_"))
343 (sst (standard-syntax-table)))
344 (dotimes (i 128)
345 (unless (= i ?_)
346 (if (equal symbol (aref sst i))
347 (modify-syntax-entry i "." table)))))
348 (modify-syntax-entry ?$ "." table)
349 (modify-syntax-entry ?% "." table)
350 ;; exceptions
351 (modify-syntax-entry ?# "<" table)
352 (modify-syntax-entry ?\n ">" table)
353 (modify-syntax-entry ?' "\"" table)
354 (modify-syntax-entry ?` "$" table)
355 table))
357 ;;;; Utility stuff
359 (defsubst python-in-string/comment ()
360 "Return non-nil if point is in a Python literal (a comment or string)."
361 ;; We don't need to save the match data.
362 (nth 8 (syntax-ppss)))
364 (defconst python-space-backslash-table
365 (let ((table (copy-syntax-table python-mode-syntax-table)))
366 (modify-syntax-entry ?\\ " " table)
367 table)
368 "`python-mode-syntax-table' with backslash given whitespace syntax.")
370 (defun python-skip-comments/blanks (&optional backward)
371 "Skip comments and blank lines.
372 BACKWARD non-nil means go backwards, otherwise go forwards.
373 Backslash is treated as whitespace so that continued blank lines
374 are skipped. Doesn't move out of comments -- should be outside
375 or at end of line."
376 (let ((arg (if backward
377 ;; If we're in a comment (including on the trailing
378 ;; newline), forward-comment doesn't move backwards out
379 ;; of it. Don't set the syntax table round this bit!
380 (let ((syntax (syntax-ppss)))
381 (if (nth 4 syntax)
382 (goto-char (nth 8 syntax)))
383 (- (point-max)))
384 (point-max))))
385 (with-syntax-table python-space-backslash-table
386 (forward-comment arg))))
388 (defun python-backslash-continuation-line-p ()
389 "Non-nil if preceding line ends with backslash that is not in a comment."
390 (and (eq ?\\ (char-before (line-end-position 0)))
391 (not (syntax-ppss-context (syntax-ppss)))))
393 (defun python-continuation-line-p ()
394 "Return non-nil if current line continues a previous one.
395 The criteria are that the previous line ends in a backslash outside
396 comments and strings, or that point is within brackets/parens."
397 (or (python-backslash-continuation-line-p)
398 (let ((depth (syntax-ppss-depth
399 (save-excursion ; syntax-ppss with arg changes point
400 (syntax-ppss (line-beginning-position))))))
401 (or (> depth 0)
402 (if (< depth 0) ; Unbalanced brackets -- act locally
403 (save-excursion
404 (condition-case ()
405 (progn (backward-up-list) t) ; actually within brackets
406 (error nil))))))))
408 (defun python-comment-line-p ()
409 "Return non-nil if and only if current line has only a comment."
410 (save-excursion
411 (end-of-line)
412 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
413 (back-to-indentation)
414 (looking-at (rx (or (syntax comment-start) line-end))))))
416 (defun python-blank-line-p ()
417 "Return non-nil if and only if current line is blank."
418 (save-excursion
419 (beginning-of-line)
420 (looking-at "\\s-*$")))
422 (defun python-beginning-of-string ()
423 "Go to beginning of string around point.
424 Do nothing if not in string."
425 (let ((state (syntax-ppss)))
426 (when (eq 'string (syntax-ppss-context state))
427 (goto-char (nth 8 state)))))
429 (defun python-open-block-statement-p (&optional bos)
430 "Return non-nil if statement at point opens a block.
431 BOS non-nil means point is known to be at beginning of statement."
432 (save-excursion
433 (unless bos (python-beginning-of-statement))
434 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
435 "class" "try" "except" "finally" "with")
436 symbol-end)))))
438 (defun python-close-block-statement-p (&optional bos)
439 "Return non-nil if current line is a statement closing a block.
440 BOS non-nil means point is at beginning of statement.
441 The criteria are that the line isn't a comment or in string and
442 starts with keyword `raise', `break', `continue' or `pass'."
443 (save-excursion
444 (unless bos (python-beginning-of-statement))
445 (back-to-indentation)
446 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
447 symbol-end))))
449 (defun python-outdent-p ()
450 "Return non-nil if current line should outdent a level."
451 (save-excursion
452 (back-to-indentation)
453 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
454 symbol-end)))
455 (not (python-in-string/comment))
456 ;; Ensure there's a previous statement and move to it.
457 (zerop (python-previous-statement))
458 (not (python-close-block-statement-p t))
459 ;; Fixme: check this
460 (not (python-open-block-statement-p)))))
462 ;;;; Indentation.
464 (defcustom python-indent 4
465 "Number of columns for a unit of indentation in Python mode.
466 See also `\\[python-guess-indent]'"
467 :group 'python
468 :type 'integer)
469 (put 'python-indent 'safe-local-variable 'integerp)
471 (defcustom python-guess-indent t
472 "Non-nil means Python mode guesses `python-indent' for the buffer."
473 :type 'boolean
474 :group 'python)
476 (defcustom python-indent-string-contents t
477 "Non-nil means indent contents of multi-line strings together.
478 This means indent them the same as the preceding non-blank line.
479 Otherwise preserve their indentation.
481 This only applies to `doc' strings, i.e. those that form statements;
482 the indentation is preserved in others."
483 :type '(choice (const :tag "Align with preceding" t)
484 (const :tag "Preserve indentation" nil))
485 :group 'python)
487 (defcustom python-honour-comment-indentation nil
488 "Non-nil means indent relative to preceding comment line.
489 Only do this for comments where the leading comment character is
490 followed by space. This doesn't apply to comment lines, which
491 are always indented in lines with preceding comments."
492 :type 'boolean
493 :group 'python)
495 (defcustom python-continuation-offset 4
496 "Number of columns of additional indentation for continuation lines.
497 Continuation lines follow a backslash-terminated line starting a
498 statement."
499 :group 'python
500 :type 'integer)
503 (defcustom python-default-interpreter 'cpython
504 "*Which Python interpreter is used by default.
505 The value for this variable can be either `cpython' or `jpython'.
507 When the value is `cpython', the variables `python-python-command' and
508 `python-python-command-args' are consulted to determine the interpreter
509 and arguments to use.
511 When the value is `jpython', the variables `python-jpython-command' and
512 `python-jpython-command-args' are consulted to determine the interpreter
513 and arguments to use.
515 Note that this variable is consulted only the first time that a Python
516 mode buffer is visited during an Emacs session. After that, use
517 \\[python-toggle-shells] to change the interpreter shell."
518 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
519 (const :tag "JPython" jpython))
520 :group 'python)
522 (defcustom python-python-command-args '("-i")
523 "*List of string arguments to be used when starting a Python shell."
524 :type '(repeat string)
525 :group 'python)
527 (defcustom python-jython-command-args '("-i")
528 "*List of string arguments to be used when starting a Jython shell."
529 :type '(repeat string)
530 :group 'python
531 :tag "JPython Command Args")
533 ;; for toggling between CPython and JPython
534 (defvar python-which-shell nil)
535 (defvar python-which-args python-python-command-args)
536 (defvar python-which-bufname "Python")
537 (make-variable-buffer-local 'python-which-shell)
538 (make-variable-buffer-local 'python-which-args)
539 (make-variable-buffer-local 'python-which-bufname)
541 (defcustom python-pdbtrack-do-tracking-p t
542 "*Controls whether the pdbtrack feature is enabled or not.
544 When non-nil, pdbtrack is enabled in all comint-based buffers,
545 e.g. shell interaction buffers and the *Python* buffer.
547 When using pdb to debug a Python program, pdbtrack notices the
548 pdb prompt and presents the line in the source file where the
549 program is stopped in a pop-up buffer. It's similar to what
550 gud-mode does for debugging C programs with gdb, but without
551 having to restart the program."
552 :type 'boolean
553 :group 'python)
554 (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
556 (defcustom python-pdbtrack-minor-mode-string " PDB"
557 "*Minor-mode sign to be displayed when pdbtrack is active."
558 :type 'string
559 :group 'python)
561 ;; Add a designator to the minor mode strings
562 (or (assq 'python-pdbtrack-is-tracking-p minor-mode-alist)
563 (push '(python-pdbtrack-is-tracking-p python-pdbtrack-minor-mode-string)
564 minor-mode-alist))
566 ;; Bind python-file-queue before installing the kill-emacs-hook.
567 (defvar python-file-queue nil
568 "Queue of Python temp files awaiting execution.
569 Currently-active file is at the head of the list.")
571 (defcustom python-shell-prompt-alist
572 '(("ipython" . "^In \\[[0-9]+\\]: *")
573 (t . "^>>> "))
574 "Alist of Python input prompts.
575 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
576 the value of `python-python-command' for the python process and
577 REGEXP is a regular expression matching the Python prompt.
578 PROGRAM can also be t, which specifies the default when no other
579 element matches `python-python-command'."
580 :type 'string
581 :group 'python
582 :version "24.1")
584 (defcustom python-shell-continuation-prompt-alist
585 '(("ipython" . "^ [.][.][.]+: *")
586 (t . "^[.][.][.] "))
587 "Alist of Python continued-line prompts.
588 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
589 the value of `python-python-command' for the python process and
590 REGEXP is a regular expression matching the Python prompt for
591 continued lines.
592 PROGRAM can also be t, which specifies the default when no other
593 element matches `python-python-command'."
594 :type 'string
595 :group 'python
596 :version "24.1")
598 (defvar python-pdbtrack-is-tracking-p nil)
600 (defconst python-pdbtrack-stack-entry-regexp
601 "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
602 "Regular expression pdbtrack uses to find a stack trace entry.")
604 (defconst python-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
605 "Regular expression pdbtrack uses to recognize a pdb prompt.")
607 (defconst python-pdbtrack-track-range 10000
608 "Max number of characters from end of buffer to search for stack entry.")
610 (defun python-guess-indent ()
611 "Guess step for indentation of current buffer.
612 Set `python-indent' locally to the value guessed."
613 (interactive)
614 (save-excursion
615 (save-restriction
616 (widen)
617 (goto-char (point-min))
618 (let (done indent)
619 (while (and (not done) (not (eobp)))
620 (when (and (re-search-forward (rx ?: (0+ space)
621 (or (syntax comment-start)
622 line-end))
623 nil 'move)
624 (python-open-block-statement-p))
625 (save-excursion
626 (python-beginning-of-statement)
627 (let ((initial (current-indentation)))
628 (if (zerop (python-next-statement))
629 (setq indent (- (current-indentation) initial)))
630 (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
631 (setq done t))))))
632 (when done
633 (when (/= indent (default-value 'python-indent))
634 (set (make-local-variable 'python-indent) indent)
635 (unless (= tab-width python-indent)
636 (setq indent-tabs-mode nil)))
637 indent)))))
639 ;; Alist of possible indentations and start of statement they would
640 ;; close. Used in indentation cycling (below).
641 (defvar python-indent-list nil
642 "Internal use.")
643 ;; Length of the above
644 (defvar python-indent-list-length nil
645 "Internal use.")
646 ;; Current index into the alist.
647 (defvar python-indent-index nil
648 "Internal use.")
650 (defun python-calculate-indentation ()
651 "Calculate Python indentation for line at point."
652 (setq python-indent-list nil
653 python-indent-list-length 1)
654 (save-excursion
655 (beginning-of-line)
656 (let ((syntax (syntax-ppss))
657 start)
658 (cond
659 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
660 (if (not python-indent-string-contents)
661 (current-indentation)
662 ;; Only respect `python-indent-string-contents' in doc
663 ;; strings (defined as those which form statements).
664 (if (not (save-excursion
665 (python-beginning-of-statement)
666 (looking-at (rx (or (syntax string-delimiter)
667 (syntax string-quote))))))
668 (current-indentation)
669 ;; Find indentation of preceding non-blank line within string.
670 (setq start (nth 8 syntax))
671 (forward-line -1)
672 (while (and (< start (point)) (looking-at "\\s-*$"))
673 (forward-line -1))
674 (current-indentation))))
675 ((python-continuation-line-p) ; after backslash, or bracketed
676 (let ((point (point))
677 (open-start (cadr syntax))
678 (backslash (python-backslash-continuation-line-p))
679 (colon (eq ?: (char-before (1- (line-beginning-position))))))
680 (if open-start
681 ;; Inside bracketed expression.
682 (progn
683 (goto-char (1+ open-start))
684 ;; Look for first item in list (preceding point) and
685 ;; align with it, if found.
686 (if (with-syntax-table python-space-backslash-table
687 (let ((parse-sexp-ignore-comments t))
688 (condition-case ()
689 (progn (forward-sexp)
690 (backward-sexp)
691 (< (point) point))
692 (error nil))))
693 ;; Extra level if we're backslash-continued or
694 ;; following a key.
695 (if (or backslash colon)
696 (+ python-indent (current-column))
697 (current-column))
698 ;; Otherwise indent relative to statement start, one
699 ;; level per bracketing level.
700 (goto-char (1+ open-start))
701 (python-beginning-of-statement)
702 (+ (current-indentation) (* (car syntax) python-indent))))
703 ;; Otherwise backslash-continued.
704 (forward-line -1)
705 (if (python-continuation-line-p)
706 ;; We're past first continuation line. Align with
707 ;; previous line.
708 (current-indentation)
709 ;; First continuation line. Indent one step, with an
710 ;; extra one if statement opens a block.
711 (python-beginning-of-statement)
712 (+ (current-indentation) python-continuation-offset
713 (if (python-open-block-statement-p t)
714 python-indent
715 0))))))
716 ((bobp) 0)
717 ;; Fixme: Like python-mode.el; not convinced by this.
718 ((looking-at (rx (0+ space) (syntax comment-start)
719 (not (any " \t\n")))) ; non-indentable comment
720 (current-indentation))
721 ((and python-honour-comment-indentation
722 ;; Back over whitespace, newlines, non-indentable comments.
723 (catch 'done
724 (while (cond ((bobp) nil)
725 ((not (forward-comment -1))
726 nil) ; not at comment start
727 ;; Now at start of comment -- trailing one?
728 ((/= (current-column) (current-indentation))
729 nil)
730 ;; Indentable comment, like python-mode.el?
731 ((and (looking-at (rx (syntax comment-start)
732 (or space line-end)))
733 (/= 0 (current-column)))
734 (throw 'done (current-column)))
735 ;; Else skip it (loop).
736 (t))))))
738 (python-indentation-levels)
739 ;; Prefer to indent comments with an immediately-following
740 ;; statement, e.g.
741 ;; ...
742 ;; # ...
743 ;; def ...
744 (when (and (> python-indent-list-length 1)
745 (python-comment-line-p))
746 (forward-line)
747 (unless (python-comment-line-p)
748 (let ((elt (assq (current-indentation) python-indent-list)))
749 (setq python-indent-list
750 (nconc (delete elt python-indent-list)
751 (list elt))))))
752 (caar (last python-indent-list)))))))
754 ;;;; Cycling through the possible indentations with successive TABs.
756 ;; These don't need to be buffer-local since they're only relevant
757 ;; during a cycle.
759 (defun python-initial-text ()
760 "Text of line following indentation and ignoring any trailing comment."
761 (save-excursion
762 (buffer-substring (progn
763 (back-to-indentation)
764 (point))
765 (progn
766 (end-of-line)
767 (forward-comment -1)
768 (point)))))
770 (defconst python-block-pairs
771 '(("else" "if" "elif" "while" "for" "try" "except")
772 ("elif" "if" "elif")
773 ("except" "try" "except")
774 ("finally" "else" "try" "except"))
775 "Alist of keyword matches.
776 The car of an element is a keyword introducing a statement which
777 can close a block opened by a keyword in the cdr.")
779 (defun python-first-word ()
780 "Return first word (actually symbol) on the line."
781 (save-excursion
782 (back-to-indentation)
783 (current-word t)))
785 (defun python-indentation-levels ()
786 "Return a list of possible indentations for this line.
787 It is assumed not to be a continuation line or in a multi-line string.
788 Includes the default indentation and those which would close all
789 enclosing blocks. Elements of the list are actually pairs:
790 \(INDENTATION . TEXT), where TEXT is the initial text of the
791 corresponding block opening (or nil)."
792 (save-excursion
793 (let ((initial "")
794 levels indent)
795 ;; Only one possibility immediately following a block open
796 ;; statement, assuming it doesn't have a `suite' on the same line.
797 (cond
798 ((save-excursion (and (python-previous-statement)
799 (python-open-block-statement-p t)
800 (setq indent (current-indentation))
801 ;; Check we don't have something like:
802 ;; if ...: ...
803 (if (progn (python-end-of-statement)
804 (python-skip-comments/blanks t)
805 (eq ?: (char-before)))
806 (setq indent (+ python-indent indent)))))
807 (push (cons indent initial) levels))
808 ;; Only one possibility for comment line immediately following
809 ;; another.
810 ((save-excursion
811 (when (python-comment-line-p)
812 (forward-line -1)
813 (if (python-comment-line-p)
814 (push (cons (current-indentation) initial) levels)))))
815 ;; Fixme: Maybe have a case here which indents (only) first
816 ;; line after a lambda.
818 (let ((start (car (assoc (python-first-word) python-block-pairs))))
819 (python-previous-statement)
820 ;; Is this a valid indentation for the line of interest?
821 (unless (or (if start ; potentially only outdentable
822 ;; Check for things like:
823 ;; if ...: ...
824 ;; else ...:
825 ;; where the second line need not be outdented.
826 (not (member (python-first-word)
827 (cdr (assoc start
828 python-block-pairs)))))
829 ;; Not sensible to indent to the same level as
830 ;; previous `return' &c.
831 (python-close-block-statement-p))
832 (push (cons (current-indentation) (python-initial-text))
833 levels))
834 (while (python-beginning-of-block)
835 (when (or (not start)
836 (member (python-first-word)
837 (cdr (assoc start python-block-pairs))))
838 (push (cons (current-indentation) (python-initial-text))
839 levels))))))
840 (prog1 (or levels (setq levels '((0 . ""))))
841 (setq python-indent-list levels
842 python-indent-list-length (length python-indent-list))))))
844 ;; This is basically what `python-indent-line' would be if we didn't
845 ;; do the cycling.
846 (defun python-indent-line-1 (&optional leave)
847 "Subroutine of `python-indent-line'.
848 Does non-repeated indentation. LEAVE non-nil means leave
849 indentation if it is valid, i.e. one of the positions returned by
850 `python-calculate-indentation'."
851 (let ((target (python-calculate-indentation))
852 (pos (- (point-max) (point))))
853 (if (or (= target (current-indentation))
854 ;; Maybe keep a valid indentation.
855 (and leave python-indent-list
856 (assq (current-indentation) python-indent-list)))
857 (if (< (current-column) (current-indentation))
858 (back-to-indentation))
859 (beginning-of-line)
860 (delete-horizontal-space)
861 (indent-to target)
862 (if (> (- (point-max) pos) (point))
863 (goto-char (- (point-max) pos))))))
865 (defun python-indent-line ()
866 "Indent current line as Python code.
867 When invoked via `indent-for-tab-command', cycle through possible
868 indentations for current line. The cycle is broken by a command
869 different from `indent-for-tab-command', i.e. successive TABs do
870 the cycling."
871 (interactive)
872 (if (and (eq this-command 'indent-for-tab-command)
873 (eq last-command this-command))
874 (if (= 1 python-indent-list-length)
875 (message "Sole indentation")
876 (progn (setq python-indent-index
877 (% (1+ python-indent-index) python-indent-list-length))
878 (beginning-of-line)
879 (delete-horizontal-space)
880 (indent-to (car (nth python-indent-index python-indent-list)))
881 (if (python-block-end-p)
882 (let ((text (cdr (nth python-indent-index
883 python-indent-list))))
884 (if text
885 (message "Closes: %s" text))))))
886 (python-indent-line-1)
887 (setq python-indent-index (1- python-indent-list-length))))
889 (defun python-indent-region (start end)
890 "`indent-region-function' for Python.
891 Leaves validly-indented lines alone, i.e. doesn't indent to
892 another valid position."
893 (save-excursion
894 (goto-char end)
895 (setq end (point-marker))
896 (goto-char start)
897 (or (bolp) (forward-line 1))
898 (while (< (point) end)
899 (or (and (bolp) (eolp))
900 (python-indent-line-1 t))
901 (forward-line 1))
902 (move-marker end nil)))
904 (defun python-block-end-p ()
905 "Non-nil if this is a line in a statement closing a block,
906 or a blank line indented to where it would close a block."
907 (and (not (python-comment-line-p))
908 (or (python-close-block-statement-p t)
909 (< (current-indentation)
910 (save-excursion
911 (python-previous-statement)
912 (current-indentation))))))
914 ;;;; Movement.
916 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
917 ;; block, statement, depending on context.
919 (defun python-beginning-of-defun ()
920 "`beginning-of-defun-function' for Python.
921 Finds beginning of innermost nested class or method definition.
922 Returns the name of the definition found at the end, or nil if
923 reached start of buffer."
924 (let ((ci (current-indentation))
925 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
926 (group (1+ (or word (syntax symbol))))))
927 found lep) ;; def-line
928 (if (python-comment-line-p)
929 (setq ci most-positive-fixnum))
930 (while (and (not (bobp)) (not found))
931 ;; Treat bol at beginning of function as outside function so
932 ;; that successive C-M-a makes progress backwards.
933 ;;(setq def-line (looking-at def-re))
934 (unless (bolp) (end-of-line))
935 (setq lep (line-end-position))
936 (if (and (re-search-backward def-re nil 'move)
937 ;; Must be less indented or matching top level, or
938 ;; equally indented if we started on a definition line.
939 (let ((in (current-indentation)))
940 (or (and (zerop ci) (zerop in))
941 (= lep (line-end-position)) ; on initial line
942 ;; Not sure why it was like this -- fails in case of
943 ;; last internal function followed by first
944 ;; non-def statement of the main body.
945 ;; (and def-line (= in ci))
946 (= in ci)
947 (< in ci)))
948 (not (python-in-string/comment)))
949 (setq found t)))
950 found))
952 (defun python-end-of-defun ()
953 "`end-of-defun-function' for Python.
954 Finds end of innermost nested class or method definition."
955 (let ((orig (point))
956 (pattern (rx line-start (0+ space) (or "def" "class") space)))
957 ;; Go to start of current block and check whether it's at top
958 ;; level. If it is, and not a block start, look forward for
959 ;; definition statement.
960 (when (python-comment-line-p)
961 (end-of-line)
962 (forward-comment most-positive-fixnum))
963 (if (not (python-open-block-statement-p))
964 (python-beginning-of-block))
965 (if (zerop (current-indentation))
966 (unless (python-open-block-statement-p)
967 (while (and (re-search-forward pattern nil 'move)
968 (python-in-string/comment))) ; just loop
969 (unless (eobp)
970 (beginning-of-line)))
971 ;; Don't move before top-level statement that would end defun.
972 (end-of-line)
973 (python-beginning-of-defun))
974 ;; If we got to the start of buffer, look forward for
975 ;; definition statement.
976 (if (and (bobp) (not (looking-at "def\\|class")))
977 (while (and (not (eobp))
978 (re-search-forward pattern nil 'move)
979 (python-in-string/comment)))) ; just loop
980 ;; We're at a definition statement (or end-of-buffer).
981 (unless (eobp)
982 (python-end-of-block)
983 ;; Count trailing space in defun (but not trailing comments).
984 (skip-syntax-forward " >")
985 (unless (eobp) ; e.g. missing final newline
986 (beginning-of-line)))
987 ;; Catch pathological cases like this, where the beginning-of-defun
988 ;; skips to a definition we're not in:
989 ;; if ...:
990 ;; ...
991 ;; else:
992 ;; ... # point here
993 ;; ...
994 ;; def ...
995 (if (< (point) orig)
996 (goto-char (point-max)))))
998 (defun python-beginning-of-statement ()
999 "Go to start of current statement.
1000 Accounts for continuation lines, multi-line strings, and
1001 multi-line bracketed expressions."
1002 (beginning-of-line)
1003 (python-beginning-of-string)
1004 (let (point)
1005 (while (and (python-continuation-line-p)
1006 (if point
1007 (< (point) point)
1009 (beginning-of-line)
1010 (if (python-backslash-continuation-line-p)
1011 (progn
1012 (forward-line -1)
1013 (while (python-backslash-continuation-line-p)
1014 (forward-line -1)))
1015 (python-beginning-of-string)
1016 (python-skip-out))
1017 (setq point (point))))
1018 (back-to-indentation))
1020 (defun python-skip-out (&optional forward syntax)
1021 "Skip out of any nested brackets.
1022 Skip forward if FORWARD is non-nil, else backward.
1023 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
1024 Return non-nil if and only if skipping was done."
1025 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
1026 (forward (if forward -1 1)))
1027 (unless (zerop depth)
1028 (if (> depth 0)
1029 ;; Skip forward out of nested brackets.
1030 (condition-case () ; beware invalid syntax
1031 (progn (backward-up-list (* forward depth)) t)
1032 (error nil))
1033 ;; Invalid syntax (too many closed brackets).
1034 ;; Skip out of as many as possible.
1035 (let (done)
1036 (while (condition-case ()
1037 (progn (backward-up-list forward)
1038 (setq done t))
1039 (error nil)))
1040 done)))))
1042 (defun python-end-of-statement ()
1043 "Go to the end of the current statement and return point.
1044 Usually this is the start of the next line, but if this is a
1045 multi-line statement we need to skip over the continuation lines.
1046 On a comment line, go to end of line."
1047 (end-of-line)
1048 (while (let (comment)
1049 ;; Move past any enclosing strings and sexps, or stop if
1050 ;; we're in a comment.
1051 (while (let ((s (syntax-ppss)))
1052 (cond ((eq 'comment (syntax-ppss-context s))
1053 (setq comment t)
1054 nil)
1055 ((eq 'string (syntax-ppss-context s))
1056 ;; Go to start of string and skip it.
1057 (let ((pos (point)))
1058 (goto-char (nth 8 s))
1059 (condition-case () ; beware invalid syntax
1060 (progn (forward-sexp) t)
1061 ;; If there's a mismatched string, make sure
1062 ;; we still overall move *forward*.
1063 (error (goto-char pos) (end-of-line)))))
1064 ((python-skip-out t s))))
1065 (end-of-line))
1066 (unless comment
1067 (eq ?\\ (char-before)))) ; Line continued?
1068 (end-of-line 2)) ; Try next line.
1069 (point))
1071 (defun python-previous-statement (&optional count)
1072 "Go to start of previous statement.
1073 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
1074 Return count of statements left to move."
1075 (interactive "p")
1076 (unless count (setq count 1))
1077 (if (< count 0)
1078 (python-next-statement (- count))
1079 (python-beginning-of-statement)
1080 (while (and (> count 0) (not (bobp)))
1081 (python-skip-comments/blanks t)
1082 (python-beginning-of-statement)
1083 (unless (bobp) (setq count (1- count))))
1084 count))
1086 (defun python-next-statement (&optional count)
1087 "Go to start of next statement.
1088 With argument COUNT, do it COUNT times. Stop at end of buffer.
1089 Return count of statements left to move."
1090 (interactive "p")
1091 (unless count (setq count 1))
1092 (if (< count 0)
1093 (python-previous-statement (- count))
1094 (beginning-of-line)
1095 (let (bogus)
1096 (while (and (> count 0) (not (eobp)) (not bogus))
1097 (python-end-of-statement)
1098 (python-skip-comments/blanks)
1099 (if (eq 'string (syntax-ppss-context (syntax-ppss)))
1100 (setq bogus t)
1101 (unless (eobp)
1102 (setq count (1- count))))))
1103 count))
1105 (defun python-beginning-of-block (&optional arg)
1106 "Go to start of current block.
1107 With numeric arg, do it that many times. If ARG is negative, call
1108 `python-end-of-block' instead.
1109 If point is on the first line of a block, use its outer block.
1110 If current statement is in column zero, don't move and return nil.
1111 Otherwise return non-nil."
1112 (interactive "p")
1113 (unless arg (setq arg 1))
1114 (cond
1115 ((zerop arg))
1116 ((< arg 0) (python-end-of-block (- arg)))
1118 (let ((point (point)))
1119 (if (or (python-comment-line-p)
1120 (python-blank-line-p))
1121 (python-skip-comments/blanks t))
1122 (python-beginning-of-statement)
1123 (let ((ci (current-indentation)))
1124 (if (zerop ci)
1125 (not (goto-char point)) ; return nil
1126 ;; Look upwards for less indented statement.
1127 (if (catch 'done
1128 ;;; This is slower than the below.
1129 ;;; (while (zerop (python-previous-statement))
1130 ;;; (when (and (< (current-indentation) ci)
1131 ;;; (python-open-block-statement-p t))
1132 ;;; (beginning-of-line)
1133 ;;; (throw 'done t)))
1134 (while (and (zerop (forward-line -1)))
1135 (when (and (< (current-indentation) ci)
1136 (not (python-comment-line-p))
1137 ;; Move to beginning to save effort in case
1138 ;; this is in string.
1139 (progn (python-beginning-of-statement) t)
1140 (python-open-block-statement-p t))
1141 (beginning-of-line)
1142 (throw 'done t)))
1143 (not (goto-char point))) ; Failed -- return nil
1144 (python-beginning-of-block (1- arg)))))))))
1146 (defun python-end-of-block (&optional arg)
1147 "Go to end of current block.
1148 With numeric arg, do it that many times. If ARG is negative,
1149 call `python-beginning-of-block' instead.
1150 If current statement is in column zero and doesn't open a block,
1151 don't move and return nil. Otherwise return t."
1152 (interactive "p")
1153 (unless arg (setq arg 1))
1154 (if (< arg 0)
1155 (python-beginning-of-block (- arg))
1156 (while (and (> arg 0)
1157 (let* ((point (point))
1158 (_ (if (python-comment-line-p)
1159 (python-skip-comments/blanks t)))
1160 (ci (current-indentation))
1161 (open (python-open-block-statement-p)))
1162 (if (and (zerop ci) (not open))
1163 (not (goto-char point))
1164 (catch 'done
1165 (while (zerop (python-next-statement))
1166 (when (or (and open (<= (current-indentation) ci))
1167 (< (current-indentation) ci))
1168 (python-skip-comments/blanks t)
1169 (beginning-of-line 2)
1170 (throw 'done t)))))))
1171 (setq arg (1- arg)))
1172 (zerop arg)))
1174 (defvar python-which-func-length-limit 40
1175 "Non-strict length limit for `python-which-func' output.")
1177 (defun python-which-func ()
1178 (let ((function-name (python-current-defun python-which-func-length-limit)))
1179 (set-text-properties 0 (length function-name) nil function-name)
1180 function-name))
1183 ;;;; Imenu.
1185 ;; For possibily speeding this up, here's the top of the ELP profile
1186 ;; for rescanning pydoc.py (2.2k lines, 90kb):
1187 ;; Function Name Call Count Elapsed Time Average Time
1188 ;; ==================================== ========== ============= ============
1189 ;; python-imenu-create-index 156 2.430906 0.0155827307
1190 ;; python-end-of-defun 155 1.2718260000 0.0082053290
1191 ;; python-end-of-block 155 1.1898689999 0.0076765741
1192 ;; python-next-statement 2970 1.024717 0.0003450225
1193 ;; python-end-of-statement 2970 0.4332190000 0.0001458649
1194 ;; python-beginning-of-defun 265 0.0918479999 0.0003465962
1195 ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05
1197 (defvar python-recursing)
1198 (defun python-imenu-create-index ()
1199 "`imenu-create-index-function' for Python.
1201 Makes nested Imenu menus from nested `class' and `def' statements.
1202 The nested menus are headed by an item referencing the outer
1203 definition; it has a space prepended to the name so that it sorts
1204 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1205 precede it)."
1206 (unless (boundp 'python-recursing) ; dynamically bound below
1207 ;; Normal call from Imenu.
1208 (goto-char (point-min))
1209 ;; Without this, we can get an infloop if the buffer isn't all
1210 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1211 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1212 ;; what's going on, but it must be something to do with timers in
1213 ;; font-lock.
1214 ;; This can't be right, especially not when jit-lock is not used. --Stef
1215 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1216 ;; (font-lock-fontify-region (point-min) (point-max)))
1218 (let (index-alist) ; accumulated value to return
1219 (while (re-search-forward
1220 (rx line-start (0+ space) ; leading space
1221 (or (group "def") (group "class")) ; type
1222 (1+ space) (group (1+ (or word ?_)))) ; name
1223 nil t)
1224 (unless (python-in-string/comment)
1225 (let ((pos (match-beginning 0))
1226 (name (match-string-no-properties 3)))
1227 (if (match-beginning 2) ; def or class?
1228 (setq name (concat "class " name)))
1229 (save-restriction
1230 (narrow-to-defun)
1231 (let* ((python-recursing t)
1232 (sublist (python-imenu-create-index)))
1233 (if sublist
1234 (progn (push (cons (concat " " name) pos) sublist)
1235 (push (cons name sublist) index-alist))
1236 (push (cons name pos) index-alist)))))))
1237 (unless (boundp 'python-recursing)
1238 ;; Look for module variables.
1239 (let (vars)
1240 (goto-char (point-min))
1241 (while (re-search-forward
1242 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1243 nil t)
1244 (unless (python-in-string/comment)
1245 (push (cons (match-string 1) (match-beginning 1))
1246 vars)))
1247 (setq index-alist (nreverse index-alist))
1248 (if vars
1249 (push (cons "Module variables"
1250 (nreverse vars))
1251 index-alist))))
1252 index-alist))
1254 ;;;; `Electric' commands.
1256 (defun python-electric-colon (arg)
1257 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1258 With numeric ARG, just insert that many colons. With \\[universal-argument],
1259 just insert a single colon."
1260 (interactive "*P")
1261 (self-insert-command (if (not (integerp arg)) 1 arg))
1262 (and (not arg)
1263 (eolp)
1264 (python-outdent-p)
1265 (not (python-in-string/comment))
1266 (> (current-indentation) (python-calculate-indentation))
1267 (python-indent-line))) ; OK, do it
1268 (put 'python-electric-colon 'delete-selection t)
1270 (defun python-backspace (arg)
1271 "Maybe delete a level of indentation on the current line.
1272 Do so if point is at the end of the line's indentation outside
1273 strings and comments.
1274 Otherwise just call `backward-delete-char-untabify'.
1275 Repeat ARG times."
1276 (interactive "*p")
1277 (if (or (/= (current-indentation) (current-column))
1278 (bolp)
1279 (python-continuation-line-p)
1280 (python-in-string/comment))
1281 (backward-delete-char-untabify arg)
1282 ;; Look for the largest valid indentation which is smaller than
1283 ;; the current indentation.
1284 (let ((indent 0)
1285 (ci (current-indentation))
1286 (indents (python-indentation-levels))
1287 initial)
1288 (dolist (x indents)
1289 (if (< (car x) ci)
1290 (setq indent (max indent (car x)))))
1291 (setq initial (cdr (assq indent indents)))
1292 (if (> (length initial) 0)
1293 (message "Closes %s" initial))
1294 (delete-horizontal-space)
1295 (indent-to indent))))
1296 (put 'python-backspace 'delete-selection 'supersede)
1298 ;;;; pychecker
1300 (defcustom python-check-command "pychecker --stdlib"
1301 "Command used to check a Python file."
1302 :type 'string
1303 :group 'python)
1305 (defvar python-saved-check-command nil
1306 "Internal use.")
1308 ;; After `sgml-validate-command'.
1309 (defun python-check (command)
1310 "Check a Python file (default current buffer's file).
1311 Runs COMMAND, a shell command, as if by `compile'.
1312 See `python-check-command' for the default."
1313 (interactive
1314 (list (read-string "Checker command: "
1315 (or python-saved-check-command
1316 (concat python-check-command " "
1317 (let ((name (buffer-file-name)))
1318 (if name
1319 (file-name-nondirectory name))))))))
1320 (set (make-local-variable 'python-saved-check-command) command)
1321 (require 'compile) ;To define compilation-* variables.
1322 (save-some-buffers (not compilation-ask-about-save) nil)
1323 (let ((compilation-error-regexp-alist
1324 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1325 compilation-error-regexp-alist)))
1326 (compilation-start command)))
1328 ;;;; Inferior mode stuff (following cmuscheme).
1330 (defcustom python-python-command "python"
1331 "Shell command to run Python interpreter.
1332 Any arguments can't contain whitespace."
1333 :group 'python
1334 :type 'string)
1336 (defcustom python-jython-command "jython"
1337 "Shell command to run Jython interpreter.
1338 Any arguments can't contain whitespace."
1339 :group 'python
1340 :type 'string)
1342 (defvar python-command python-python-command
1343 "Actual command used to run Python.
1344 May be `python-python-command' or `python-jython-command', possibly
1345 modified by the user. Additional arguments are added when the command
1346 is used by `run-python' et al.")
1348 (defvar python-buffer nil
1349 "*The current Python process buffer.
1351 Commands that send text from source buffers to Python processes have
1352 to choose a process to send to. This is determined by buffer-local
1353 value of `python-buffer'. If its value in the current buffer,
1354 i.e. both any local value and the default one, is nil, `run-python'
1355 and commands that send to the Python process will start a new process.
1357 Whenever \\[run-python] starts a new process, it resets the default
1358 value of `python-buffer' to be the new process's buffer and sets the
1359 buffer-local value similarly if the current buffer is in Python mode
1360 or Inferior Python mode, so that source buffer stays associated with a
1361 specific sub-process.
1363 Use \\[python-set-proc] to set the default value from a buffer with a
1364 local value.")
1365 (make-variable-buffer-local 'python-buffer)
1367 (defconst python-compilation-regexp-alist
1368 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1369 ;; The first already is (for CAML), but the second isn't. Anyhow,
1370 ;; these are specific to the inferior buffer. -- fx
1371 `((,(rx line-start (1+ (any " \t")) "File \""
1372 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1373 "\", line " (group (1+ digit)))
1374 1 2)
1375 (,(rx " in file " (group (1+ not-newline)) " on line "
1376 (group (1+ digit)))
1377 1 2)
1378 ;; pdb stack trace
1379 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1380 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1381 1 2))
1382 "`compilation-error-regexp-alist' for inferior Python.")
1384 (defvar inferior-python-mode-map
1385 (let ((map (make-sparse-keymap)))
1386 ;; This will inherit from comint-mode-map.
1387 (define-key map "\C-c\C-l" 'python-load-file)
1388 (define-key map "\C-c\C-v" 'python-check)
1389 ;; Note that we _can_ still use these commands which send to the
1390 ;; Python process even at the prompt iff we have a normal prompt,
1391 ;; i.e. '>>> ' and not '... '. See the comment before
1392 ;; python-send-region. Fixme: uncomment these if we address that.
1394 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1395 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1396 map))
1398 (defvar inferior-python-mode-syntax-table
1399 (let ((st (make-syntax-table python-mode-syntax-table)))
1400 ;; Don't get confused by apostrophes in the process's output (e.g. if
1401 ;; you execute "help(os)").
1402 (modify-syntax-entry ?\' "." st)
1403 ;; Maybe we should do the same for double quotes?
1404 ;; (modify-syntax-entry ?\" "." st)
1405 st))
1407 ;; Autoloaded.
1408 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1410 (defvar python--prompt-regexp nil)
1412 (defun python--set-prompt-regexp ()
1413 (let ((prompt (cdr-safe (or (assoc python-python-command
1414 python-shell-prompt-alist)
1415 (assq t python-shell-prompt-alist))))
1416 (cprompt (cdr-safe (or (assoc python-python-command
1417 python-shell-continuation-prompt-alist)
1418 (assq t python-shell-continuation-prompt-alist)))))
1419 (set (make-local-variable 'comint-prompt-regexp)
1420 (concat "\\("
1421 (mapconcat 'identity
1422 (delq nil (list prompt cprompt "^([Pp]db) "))
1423 "\\|")
1424 "\\)"))
1425 (set (make-local-variable 'python--prompt-regexp) prompt)))
1427 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1428 ;; not sure how much: at least some keybindings, like C-c C-f;
1429 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1430 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1431 "Major mode for interacting with an inferior Python process.
1432 A Python process can be started with \\[run-python].
1434 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1435 that order.
1437 You can send text to the inferior Python process from other buffers
1438 containing Python source.
1439 * \\[python-switch-to-python] switches the current buffer to the Python
1440 process buffer.
1441 * \\[python-send-region] sends the current region to the Python process.
1442 * \\[python-send-region-and-go] switches to the Python process buffer
1443 after sending the text.
1444 For running multiple processes in multiple buffers, see `run-python' and
1445 `python-buffer'.
1447 \\{inferior-python-mode-map}"
1448 :group 'python
1449 (require 'ansi-color) ; for ipython
1450 (setq mode-line-process '(":%s"))
1451 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1452 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1453 nil t)
1454 (python--set-prompt-regexp)
1455 (set (make-local-variable 'compilation-error-regexp-alist)
1456 python-compilation-regexp-alist)
1457 (compilation-shell-minor-mode 1))
1459 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1460 "Input matching this regexp is not saved on the history list.
1461 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1462 :type 'regexp
1463 :group 'python)
1465 (defcustom python-remove-cwd-from-path t
1466 "Whether to allow loading of Python modules from the current directory.
1467 If this is non-nil, Emacs removes '' from sys.path when starting
1468 an inferior Python process. This is the default, for security
1469 reasons, as it is easy for the Python process to be started
1470 without the user's realization (e.g. to perform completion)."
1471 :type 'boolean
1472 :group 'python
1473 :version "23.3")
1475 (defun python-input-filter (str)
1476 "`comint-input-filter' function for inferior Python.
1477 Don't save anything for STR matching `inferior-python-filter-regexp'."
1478 (not (string-match inferior-python-filter-regexp str)))
1480 ;; Fixme: Loses with quoted whitespace.
1481 (defun python-args-to-list (string)
1482 (let ((where (string-match "[ \t]" string)))
1483 (cond ((null where) (list string))
1484 ((not (= where 0))
1485 (cons (substring string 0 where)
1486 (python-args-to-list (substring string (+ 1 where)))))
1487 (t (let ((pos (string-match "[^ \t]" string)))
1488 (if pos (python-args-to-list (substring string pos))))))))
1490 (defvar python-preoutput-result nil
1491 "Data from last `_emacs_out' line seen by the preoutput filter.")
1493 (defvar python-preoutput-continuation nil
1494 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1496 (defvar python-preoutput-leftover nil)
1497 (defvar python-preoutput-skip-next-prompt nil)
1499 ;; Using this stops us getting lines in the buffer like
1500 ;; >>> ... ... >>>
1501 ;; Also look for (and delete) an `_emacs_ok' string and call
1502 ;; `python-preoutput-continuation' if we get it.
1503 (defun python-preoutput-filter (s)
1504 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1505 (when python-preoutput-leftover
1506 (setq s (concat python-preoutput-leftover s))
1507 (setq python-preoutput-leftover nil))
1508 (let ((start 0)
1509 (res ""))
1510 ;; First process whole lines.
1511 (while (string-match "\n" s start)
1512 (let ((line (substring s start (setq start (match-end 0)))))
1513 ;; Skip prompt if needed.
1514 (when (and python-preoutput-skip-next-prompt
1515 (string-match comint-prompt-regexp line))
1516 (setq python-preoutput-skip-next-prompt nil)
1517 (setq line (substring line (match-end 0))))
1518 ;; Recognize special _emacs_out lines.
1519 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1520 (local-variable-p 'python-preoutput-result))
1521 (progn
1522 (setq python-preoutput-result (match-string 1 line))
1523 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1524 (setq res (concat res line)))))
1525 ;; Then process the remaining partial line.
1526 (unless (zerop start) (setq s (substring s start)))
1527 (cond ((and (string-match comint-prompt-regexp s)
1528 ;; Drop this prompt if it follows an _emacs_out...
1529 (or python-preoutput-skip-next-prompt
1530 ;; ... or if it's not gonna be inserted at BOL.
1531 ;; Maybe we could be more selective here.
1532 (if (zerop (length res))
1533 (not (bolp))
1534 (string-match ".\\'" res))))
1535 ;; The need for this seems to be system-dependent:
1536 ;; What is this all about, exactly? --Stef
1537 ;; (if (and (eq ?. (aref s 0)))
1538 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1539 (setq python-preoutput-skip-next-prompt nil)
1540 res)
1541 ((let ((end (min (length "_emacs_out ") (length s))))
1542 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1543 ;; The leftover string is a prefix of _emacs_out so we don't know
1544 ;; yet whether it's an _emacs_out or something else: wait until we
1545 ;; get more output so we can resolve this ambiguity.
1546 (set (make-local-variable 'python-preoutput-leftover) s)
1547 res)
1548 (t (concat res s)))))
1550 (autoload 'comint-check-proc "comint")
1552 (defvar python-version-checked nil)
1553 (defun python-check-version (cmd)
1554 "Check that CMD runs a suitable version of Python."
1555 ;; Fixme: Check on Jython.
1556 (unless (or python-version-checked
1557 (equal 0 (string-match (regexp-quote python-python-command)
1558 cmd)))
1559 (unless (shell-command-to-string cmd)
1560 (error "Can't run Python command `%s'" cmd))
1561 (let* ((res (shell-command-to-string
1562 (concat cmd
1563 " -c \"from sys import version_info;\
1564 print version_info >= (2, 2) and version_info < (3, 0)\""))))
1565 (unless (string-match "True" res)
1566 (error "Only Python versions >= 2.2 and < 3.0 are supported")))
1567 (setq python-version-checked t)))
1569 ;;;###autoload
1570 (defun run-python (&optional cmd noshow new)
1571 "Run an inferior Python process, input and output via buffer *Python*.
1572 CMD is the Python command to run. NOSHOW non-nil means don't
1573 show the buffer automatically.
1575 Interactively, a prefix arg means to prompt for the initial
1576 Python command line (default is `python-command').
1578 A new process is started if one isn't running attached to
1579 `python-buffer', or if called from Lisp with non-nil arg NEW.
1580 Otherwise, if a process is already running in `python-buffer',
1581 switch to that buffer.
1583 This command runs the hook `inferior-python-mode-hook' after
1584 running `comint-mode-hook'. Type \\[describe-mode] in the
1585 process buffer for a list of commands.
1587 By default, Emacs inhibits the loading of Python modules from the
1588 current working directory, for security reasons. To disable this
1589 behavior, change `python-remove-cwd-from-path' to nil."
1590 (interactive (if current-prefix-arg
1591 (list (read-string "Run Python: " python-command) nil t)
1592 (list python-command)))
1593 (require 'ansi-color) ; for ipython
1594 (unless cmd (setq cmd python-command))
1595 (python-check-version cmd)
1596 (setq python-command cmd)
1597 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1598 ;; (not a name) in Python buffers from which `run-python' &c is
1599 ;; invoked. Would support multiple processes better.
1600 (when (or new (not (comint-check-proc python-buffer)))
1601 (with-current-buffer
1602 (let* ((cmdlist
1603 (append (python-args-to-list cmd) '("-i")
1604 (if python-remove-cwd-from-path
1605 '("-c" "import sys; sys.path.remove('')"))))
1606 (path (getenv "PYTHONPATH"))
1607 (process-environment ; to import emacs.py
1608 (cons (concat "PYTHONPATH="
1609 (if path (concat path path-separator))
1610 data-directory)
1611 process-environment))
1612 ;; If we use a pipe, unicode characters are not printed
1613 ;; correctly (Bug#5794) and IPython does not work at
1614 ;; all (Bug#5390).
1615 (process-connection-type t))
1616 (apply 'make-comint-in-buffer "Python"
1617 (generate-new-buffer "*Python*")
1618 (car cmdlist) nil (cdr cmdlist)))
1619 (setq-default python-buffer (current-buffer))
1620 (setq python-buffer (current-buffer))
1621 (accept-process-output (get-buffer-process python-buffer) 5)
1622 (inferior-python-mode)
1623 ;; Load function definitions we need.
1624 ;; Before the preoutput function was used, this was done via -c in
1625 ;; cmdlist, but that loses the banner and doesn't run the startup
1626 ;; file. The code might be inline here, but there's enough that it
1627 ;; seems worth putting in a separate file, and it's probably cleaner
1628 ;; to put it in a module.
1629 ;; Ensure we're at a prompt before doing anything else.
1630 (python-send-string "import emacs")
1631 ;; The following line was meant to ensure that we're at a prompt
1632 ;; before doing anything else. However, this can cause Emacs to
1633 ;; hang waiting for a response, if that Python function fails
1634 ;; (i.e. raises an exception).
1635 ;; (python-send-receive "print '_emacs_out ()'")
1637 (if (derived-mode-p 'python-mode)
1638 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1639 ;; Without this, help output goes into the inferior python buffer if
1640 ;; the process isn't already running.
1641 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1642 (unless noshow (pop-to-buffer python-buffer t)))
1644 (defun python-send-command (command)
1645 "Like `python-send-string' but resets `compilation-shell-minor-mode'."
1646 (when (python-check-comint-prompt)
1647 (with-current-buffer (process-buffer (python-proc))
1648 (goto-char (point-max))
1649 (compilation-forget-errors)
1650 (python-send-string command)
1651 (setq compilation-last-buffer (current-buffer)))))
1653 (defun python-send-region (start end)
1654 "Send the region to the inferior Python process."
1655 ;; The region is evaluated from a temporary file. This avoids
1656 ;; problems with blank lines, which have different semantics
1657 ;; interactively and in files. It also saves the inferior process
1658 ;; buffer filling up with interpreter prompts. We need a Python
1659 ;; function to remove the temporary file when it has been evaluated
1660 ;; (though we could probably do it in Lisp with a Comint output
1661 ;; filter). This function also catches exceptions and truncates
1662 ;; tracebacks not to mention the frame of the function itself.
1664 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1665 ;; the reference to the temporary file to the source.
1667 ;; Fixme: Write a `coding' header to the temp file if the region is
1668 ;; non-ASCII.
1669 (interactive "r")
1670 (let* ((f (make-temp-file "py"))
1671 (command
1672 ;; IPython puts the FakeModule module into __main__ so
1673 ;; emacs.eexecfile becomes useless.
1674 (if (string-match "^ipython" python-command)
1675 (format "execfile %S" f)
1676 (format "emacs.eexecfile(%S)" f)))
1677 (orig-start (copy-marker start)))
1678 (when (save-excursion
1679 (goto-char start)
1680 (/= 0 (current-indentation))) ; need dummy block
1681 (save-excursion
1682 (goto-char orig-start)
1683 ;; Wrong if we had indented code at buffer start.
1684 (set-marker orig-start (line-beginning-position 0)))
1685 (write-region "if True:\n" nil f nil 'nomsg))
1686 (write-region start end f t 'nomsg)
1687 (python-send-command command)
1688 (with-current-buffer (process-buffer (python-proc))
1689 ;; Tell compile.el to redirect error locations in file `f' to
1690 ;; positions past marker `orig-start'. It has to be done *after*
1691 ;; `python-send-command''s call to `compilation-forget-errors'.
1692 (compilation-fake-loc orig-start f))))
1694 (defun python-send-string (string)
1695 "Evaluate STRING in inferior Python process."
1696 (interactive "sPython command: ")
1697 (comint-send-string (python-proc) string)
1698 (unless (string-match "\n\\'" string)
1699 ;; Make sure the text is properly LF-terminated.
1700 (comint-send-string (python-proc) "\n"))
1701 (when (string-match "\n[ \t].*\n?\\'" string)
1702 ;; If the string contains a final indented line, add a second newline so
1703 ;; as to make sure we terminate the multiline instruction.
1704 (comint-send-string (python-proc) "\n")))
1706 (defun python-send-buffer ()
1707 "Send the current buffer to the inferior Python process."
1708 (interactive)
1709 (python-send-region (point-min) (point-max)))
1711 ;; Fixme: Try to define the function or class within the relevant
1712 ;; module, not just at top level.
1713 (defun python-send-defun ()
1714 "Send the current defun (class or method) to the inferior Python process."
1715 (interactive)
1716 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1717 (progn (end-of-defun) (point)))))
1719 (defun python-switch-to-python (eob-p)
1720 "Switch to the Python process buffer, maybe starting new process.
1721 With prefix arg, position cursor at end of buffer."
1722 (interactive "P")
1723 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1724 (when eob-p
1725 (push-mark)
1726 (goto-char (point-max))))
1728 (defun python-send-region-and-go (start end)
1729 "Send the region to the inferior Python process.
1730 Then switch to the process buffer."
1731 (interactive "r")
1732 (python-send-region start end)
1733 (python-switch-to-python t))
1735 (defcustom python-source-modes '(python-mode jython-mode)
1736 "Used to determine if a buffer contains Python source code.
1737 If a file is loaded into a buffer that is in one of these major modes,
1738 it is considered Python source by `python-load-file', which uses the
1739 value to determine defaults."
1740 :type '(repeat function)
1741 :group 'python)
1743 (defvar python-prev-dir/file nil
1744 "Caches (directory . file) pair used in the last `python-load-file' command.
1745 Used for determining the default in the next one.")
1747 (autoload 'comint-get-source "comint")
1749 (defun python-load-file (file-name)
1750 "Load a Python file FILE-NAME into the inferior Python process.
1751 If the file has extension `.py' import or reload it as a module.
1752 Treating it as a module keeps the global namespace clean, provides
1753 function location information for debugging, and supports users of
1754 module-qualified names."
1755 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1756 python-source-modes
1757 t)) ; because execfile needs exact name
1758 (comint-check-source file-name) ; Check to see if buffer needs saving.
1759 (setq python-prev-dir/file (cons (file-name-directory file-name)
1760 (file-name-nondirectory file-name)))
1761 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1762 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1763 (python-send-command
1764 (if (string-match "\\.py\\'" file-name)
1765 (let ((module (file-name-sans-extension
1766 (file-name-nondirectory file-name))))
1767 (format "emacs.eimport(%S,%S)"
1768 module (file-name-directory file-name)))
1769 (format "execfile(%S)" file-name)))
1770 (message "%s loaded" file-name)))
1772 (defun python-proc ()
1773 "Return the current Python process.
1774 See variable `python-buffer'. Starts a new process if necessary."
1775 ;; Fixme: Maybe should look for another active process if there
1776 ;; isn't one for `python-buffer'.
1777 (unless (comint-check-proc python-buffer)
1778 (run-python nil t))
1779 (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
1780 (current-buffer)
1781 python-buffer)))
1783 (defun python-set-proc ()
1784 "Set the default value of `python-buffer' to correspond to this buffer.
1785 If the current buffer has a local value of `python-buffer', set the
1786 default (global) value to that. The associated Python process is
1787 the one that gets input from \\[python-send-region] et al when used
1788 in a buffer that doesn't have a local value of `python-buffer'."
1789 (interactive)
1790 (if (local-variable-p 'python-buffer)
1791 (setq-default python-buffer python-buffer)
1792 (error "No local value of `python-buffer'")))
1794 ;;;; Context-sensitive help.
1796 (defconst python-dotty-syntax-table
1797 (let ((table (make-syntax-table)))
1798 (set-char-table-parent table python-mode-syntax-table)
1799 (modify-syntax-entry ?. "_" table)
1800 table)
1801 "Syntax table giving `.' symbol syntax.
1802 Otherwise inherits from `python-mode-syntax-table'.")
1804 (defvar view-return-to-alist)
1805 (eval-when-compile (autoload 'help-buffer "help-fns"))
1807 (defvar python-imports) ; forward declaration
1809 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1810 ;; bound to C-h S? [Probably not, since info-look may work in cases
1811 ;; where this doesn't.]
1812 (defun python-describe-symbol (symbol)
1813 "Get help on SYMBOL using `help'.
1814 Interactively, prompt for symbol.
1816 Symbol may be anything recognized by the interpreter's `help'
1817 command -- e.g. `CALLS' -- not just variables in scope in the
1818 interpreter. This only works for Python version 2.2 or newer
1819 since earlier interpreters don't support `help'.
1821 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1822 will."
1823 ;; Note that we do this in the inferior process, not a separate one, to
1824 ;; ensure the environment is appropriate.
1825 (interactive
1826 (let ((symbol (with-syntax-table python-dotty-syntax-table
1827 (current-word)))
1828 (enable-recursive-minibuffers t))
1829 (list (read-string (if symbol
1830 (format "Describe symbol (default %s): " symbol)
1831 "Describe symbol: ")
1832 nil nil symbol))))
1833 (if (equal symbol "") (error "No symbol"))
1834 ;; Ensure we have a suitable help buffer.
1835 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1836 ;; allow C-c C-f in help buffer.
1837 (let ((temp-buffer-show-hook ; avoid xref stuff
1838 (lambda ()
1839 (toggle-read-only 1)
1840 (setq view-return-to-alist
1841 (list (cons (selected-window) help-return-method))))))
1842 (with-output-to-temp-buffer (help-buffer)
1843 (with-current-buffer standard-output
1844 ;; Fixme: Is this actually useful?
1845 (help-setup-xref (list 'python-describe-symbol symbol)
1846 (called-interactively-p 'interactive))
1847 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1848 (help-print-return-message))))
1849 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1850 symbol python-imports)
1851 "*Help*" (python-proc) nil nil))
1853 (add-to-list 'debug-ignored-errors "^No symbol")
1855 (defun python-send-receive (string)
1856 "Send STRING to inferior Python (if any) and return result.
1857 The result is what follows `_emacs_out' in the output.
1858 This is a no-op if `python-check-comint-prompt' returns nil."
1859 (python-send-string string)
1860 (let ((proc (python-proc)))
1861 (with-current-buffer (process-buffer proc)
1862 (when (python-check-comint-prompt proc)
1863 (set (make-local-variable 'python-preoutput-result) nil)
1864 (while (progn
1865 (accept-process-output proc 5)
1866 (null python-preoutput-result)))
1867 (prog1 python-preoutput-result
1868 (kill-local-variable 'python-preoutput-result))))))
1870 (defun python-check-comint-prompt (&optional proc)
1871 "Return non-nil if and only if there's a normal prompt in the inferior buffer.
1872 If there isn't, it's probably not appropriate to send input to return Eldoc
1873 information etc. If PROC is non-nil, check the buffer for that process."
1874 (with-current-buffer (process-buffer (or proc (python-proc)))
1875 (save-excursion
1876 (save-match-data
1877 (re-search-backward (concat python--prompt-regexp " *\\=")
1878 nil t)))))
1880 ;; Fixme: Is there anything reasonable we can do with random methods?
1881 ;; (Currently only works with functions.)
1882 (defun python-eldoc-function ()
1883 "`eldoc-documentation-function' for Python.
1884 Only works when point is in a function name, not its arg list, for
1885 instance. Assumes an inferior Python is running."
1886 (let ((symbol (with-syntax-table python-dotty-syntax-table
1887 (current-word))))
1888 ;; This is run from timers, so inhibit-quit tends to be set.
1889 (with-local-quit
1890 ;; First try the symbol we're on.
1891 (or (and symbol
1892 (python-send-receive (format "emacs.eargs(%S, %s)"
1893 symbol python-imports)))
1894 ;; Try moving to symbol before enclosing parens.
1895 (let ((s (syntax-ppss)))
1896 (unless (zerop (car s))
1897 (when (eq ?\( (char-after (nth 1 s)))
1898 (save-excursion
1899 (goto-char (nth 1 s))
1900 (skip-syntax-backward "-")
1901 (let ((point (point)))
1902 (skip-chars-backward "a-zA-Z._")
1903 (if (< (point) point)
1904 (python-send-receive
1905 (format "emacs.eargs(%S, %s)"
1906 (buffer-substring-no-properties (point) point)
1907 python-imports))))))))))))
1909 ;;;; Info-look functionality.
1911 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1913 (defun python-after-info-look ()
1914 "Set up info-look for Python.
1915 Used with `eval-after-load'."
1916 (let* ((version (let ((s (shell-command-to-string (concat python-command
1917 " -V"))))
1918 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1919 (match-string 1 s)))
1920 ;; Whether info files have a Python version suffix, e.g. in Debian.
1921 (versioned
1922 (with-temp-buffer
1923 (with-no-warnings (Info-mode))
1924 (condition-case ()
1925 ;; Don't use `info' because it would pop-up a *info* buffer.
1926 (with-no-warnings
1927 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1928 version))
1930 (error nil)))))
1931 (info-lookup-maybe-add-help
1932 :mode 'python-mode
1933 :regexp "[[:alnum:]_]+"
1934 :doc-spec
1935 ;; Fixme: Can this reasonably be made specific to indices with
1936 ;; different rules? Is the order of indices optimal?
1937 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1938 ;; instance.)
1939 (if versioned
1940 ;; The empty prefix just gets us highlighted terms.
1941 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1942 (,(concat "(python" version "-ref)Module Index" nil ""))
1943 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1944 nil ""))
1945 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1946 nil ""))
1947 (,(concat "(python" version "-lib)Module Index" nil ""))
1948 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1949 nil ""))
1950 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1951 nil ""))
1952 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1953 '(("(python-ref)Miscellaneous Index" nil "")
1954 ("(python-ref)Module Index" nil "")
1955 ("(python-ref)Function-Method-Variable Index" nil "")
1956 ("(python-ref)Class-Exception-Object Index" nil "")
1957 ("(python-lib)Module Index" nil "")
1958 ("(python-lib)Class-Exception-Object Index" nil "")
1959 ("(python-lib)Function-Method-Variable Index" nil "")
1960 ("(python-lib)Miscellaneous Index" nil ""))))))
1961 (eval-after-load "info-look" '(python-after-info-look))
1963 ;;;; Miscellany.
1965 (defcustom python-jython-packages '("java" "javax" "org" "com")
1966 "Packages implying `jython-mode'.
1967 If these are imported near the beginning of the buffer, `python-mode'
1968 actually punts to `jython-mode'."
1969 :type '(repeat string)
1970 :group 'python)
1972 ;; Called from `python-mode', this causes a recursive call of the
1973 ;; mode. See logic there to break out of the recursion.
1974 (defun python-maybe-jython ()
1975 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1976 The criterion is either a match for `jython-mode' via
1977 `interpreter-mode-alist' or an import of a module from the list
1978 `python-jython-packages'."
1979 ;; The logic is taken from python-mode.el.
1980 (save-excursion
1981 (save-restriction
1982 (widen)
1983 (goto-char (point-min))
1984 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1985 (match-string 2))))
1986 (if (and interpreter (eq 'jython-mode
1987 (cdr (assoc (file-name-nondirectory
1988 interpreter)
1989 interpreter-mode-alist))))
1990 (jython-mode)
1991 (if (catch 'done
1992 (while (re-search-forward
1993 (rx line-start (or "import" "from") (1+ space)
1994 (group (1+ (not (any " \t\n.")))))
1995 (+ (point-min) 10000) ; Probably not worth customizing.
1997 (if (member (match-string 1) python-jython-packages)
1998 (throw 'done t))))
1999 (jython-mode)))))))
2001 (defun python-fill-paragraph (&optional justify)
2002 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2003 If any of the current line is in or at the end of a multi-line string,
2004 fill the string or the paragraph of it that point is in, preserving
2005 the string's indentation."
2006 (interactive "P")
2007 (or (fill-comment-paragraph justify)
2008 (save-excursion
2009 (end-of-line)
2010 (let* ((syntax (syntax-ppss))
2011 (orig (point))
2012 start end)
2013 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
2014 (let (fill-paragraph-function)
2015 (fill-paragraph justify)))
2016 ;; The `paragraph-start' and `paragraph-separate'
2017 ;; variables don't allow us to delimit the last
2018 ;; paragraph in a multi-line string properly, so narrow
2019 ;; to the string and then fill around (the end of) the
2020 ;; current line.
2021 ((eq t (nth 3 syntax)) ; in fenced string
2022 (goto-char (nth 8 syntax)) ; string start
2023 (setq start (line-beginning-position))
2024 (setq end (condition-case () ; for unbalanced quotes
2025 (progn (forward-sexp)
2026 (- (point) 3))
2027 (error (point-max)))))
2028 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
2029 (forward-char)
2030 (setq end (point))
2031 (condition-case ()
2032 (progn (backward-sexp)
2033 (setq start (line-beginning-position)))
2034 (error nil))))
2035 (when end
2036 (save-restriction
2037 (narrow-to-region start end)
2038 (goto-char orig)
2039 ;; Avoid losing leading and trailing newlines in doc
2040 ;; strings written like:
2041 ;; """
2042 ;; ...
2043 ;; """
2044 (let ((paragraph-separate
2045 ;; Note that the string could be part of an
2046 ;; expression, so it can have preceding and
2047 ;; trailing non-whitespace.
2048 (concat
2049 (rx (or
2050 ;; Opening triple quote without following text.
2051 (and (* nonl)
2052 (group (syntax string-delimiter))
2053 (repeat 2 (backref 1))
2054 ;; Fixme: Not sure about including
2055 ;; trailing whitespace.
2056 (* (any " \t"))
2057 eol)
2058 ;; Closing trailing quote without preceding text.
2059 (and (group (any ?\" ?')) (backref 2)
2060 (syntax string-delimiter))))
2061 "\\(?:" paragraph-separate "\\)"))
2062 fill-paragraph-function)
2063 (fill-paragraph justify))))))) t)
2065 (defun python-shift-left (start end &optional count)
2066 "Shift lines in region COUNT (the prefix arg) columns to the left.
2067 COUNT defaults to `python-indent'. If region isn't active, just shift
2068 current line. The region shifted includes the lines in which START and
2069 END lie. It is an error if any lines in the region are indented less than
2070 COUNT columns."
2071 (interactive
2072 (if mark-active
2073 (list (region-beginning) (region-end) current-prefix-arg)
2074 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2075 (if count
2076 (setq count (prefix-numeric-value count))
2077 (setq count python-indent))
2078 (when (> count 0)
2079 (save-excursion
2080 (goto-char start)
2081 (while (< (point) end)
2082 (if (and (< (current-indentation) count)
2083 (not (looking-at "[ \t]*$")))
2084 (error "Can't shift all lines enough"))
2085 (forward-line))
2086 (indent-rigidly start end (- count)))))
2088 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
2090 (defun python-shift-right (start end &optional count)
2091 "Shift lines in region COUNT (the prefix arg) columns to the right.
2092 COUNT defaults to `python-indent'. If region isn't active, just shift
2093 current line. The region shifted includes the lines in which START and
2094 END lie."
2095 (interactive
2096 (if mark-active
2097 (list (region-beginning) (region-end) current-prefix-arg)
2098 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2099 (if count
2100 (setq count (prefix-numeric-value count))
2101 (setq count python-indent))
2102 (indent-rigidly start end count))
2104 (defun python-outline-level ()
2105 "`outline-level' function for Python mode.
2106 The level is the number of `python-indent' steps of indentation
2107 of current line."
2108 (1+ (/ (current-indentation) python-indent)))
2110 ;; Fixme: Consider top-level assignments, imports, &c.
2111 (defun python-current-defun (&optional length-limit)
2112 "`add-log-current-defun-function' for Python."
2113 (save-excursion
2114 ;; Move up the tree of nested `class' and `def' blocks until we
2115 ;; get to zero indentation, accumulating the defined names.
2116 (let ((accum)
2117 (length -1))
2118 (catch 'done
2119 (while (or (null length-limit)
2120 (null (cdr accum))
2121 (< length length-limit))
2122 (let ((started-from (point)))
2123 (python-beginning-of-block)
2124 (end-of-line)
2125 (beginning-of-defun)
2126 (when (= (point) started-from)
2127 (throw 'done nil)))
2128 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
2129 (group (1+ (or word (syntax symbol))))))
2130 (push (match-string 1) accum)
2131 (setq length (+ length 1 (length (car accum)))))
2132 (when (= (current-indentation) 0)
2133 (throw 'done nil))))
2134 (when accum
2135 (when (and length-limit (> length length-limit))
2136 (setcar accum ".."))
2137 (mapconcat 'identity accum ".")))))
2139 (defun python-mark-block ()
2140 "Mark the block around point.
2141 Uses `python-beginning-of-block', `python-end-of-block'."
2142 (interactive)
2143 (push-mark)
2144 (python-beginning-of-block)
2145 (push-mark (point) nil t)
2146 (python-end-of-block)
2147 (exchange-point-and-mark))
2149 ;; Fixme: Provide a find-function-like command to find source of a
2150 ;; definition (separate from BicycleRepairMan). Complicated by
2151 ;; finding the right qualified name.
2153 ;;;; Completion.
2155 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
2156 (defvar python-imports "None"
2157 "String of top-level import statements updated by `python-find-imports'.")
2158 (make-variable-buffer-local 'python-imports)
2160 ;; Fixme: Should font-lock try to run this when it deals with an import?
2161 ;; Maybe not a good idea if it gets run multiple times when the
2162 ;; statement is being edited, and is more likely to end up with
2163 ;; something syntactically incorrect.
2164 ;; However, what we should do is to trundle up the block tree from point
2165 ;; to extract imports that appear to be in scope, and add those.
2166 (defun python-find-imports ()
2167 "Find top-level imports, updating `python-imports'."
2168 (interactive)
2169 (save-excursion
2170 (let (lines)
2171 (goto-char (point-min))
2172 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
2173 (unless (syntax-ppss-context (syntax-ppss))
2174 (let ((start (line-beginning-position)))
2175 ;; Skip over continued lines.
2176 (while (and (eq ?\\ (char-before (line-end-position)))
2177 (= 0 (forward-line 1)))
2179 (push (buffer-substring start (line-beginning-position 2))
2180 lines))))
2181 (setq python-imports
2182 (if lines
2183 (apply #'concat
2184 ;; This is probably best left out since you're unlikely to need the
2185 ;; doc for a function in the buffer and the import will lose if the
2186 ;; Python sub-process' working directory isn't the same as the
2187 ;; buffer's.
2188 ;; (if buffer-file-name
2189 ;; (concat
2190 ;; "import "
2191 ;; (file-name-sans-extension
2192 ;; (file-name-nondirectory buffer-file-name))))
2193 (nreverse lines))
2194 "None"))
2195 (when lines
2196 (set-text-properties 0 (length python-imports) nil python-imports)
2197 ;; The output ends up in the wrong place if the string we
2198 ;; send contains newlines (from the imports).
2199 (setq python-imports
2200 (replace-regexp-in-string "\n" "\\n"
2201 (format "%S" python-imports) t t))))))
2203 ;; Fixme: This fails the first time if the sub-process isn't already
2204 ;; running. Presumably a timing issue with i/o to the process.
2205 (defun python-symbol-completions (symbol)
2206 "Return a list of completions of the string SYMBOL from Python process.
2207 The list is sorted.
2208 Uses `python-imports' to load modules against which to complete."
2209 (when (stringp symbol)
2210 (let ((completions
2211 (condition-case ()
2212 (car (read-from-string
2213 (python-send-receive
2214 (format "emacs.complete(%S,%s)"
2215 (substring-no-properties symbol)
2216 python-imports))))
2217 (error nil))))
2218 (sort
2219 ;; We can get duplicates from the above -- don't know why.
2220 (delete-dups completions)
2221 #'string<))))
2223 (defun python-completion-at-point ()
2224 (let ((end (point))
2225 (start (save-excursion
2226 (and (re-search-backward
2227 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2228 (group (1+ (regexp "[[:alnum:]._]"))) point)
2229 nil t)
2230 (match-beginning 1)))))
2231 (when start
2232 (list start end
2233 (completion-table-dynamic 'python-symbol-completions)))))
2235 ;;;; FFAP support
2237 (defun python-module-path (module)
2238 "Function for `ffap-alist' to return path to MODULE."
2239 (python-send-receive (format "emacs.modpath (%S)" module)))
2241 (eval-after-load "ffap"
2242 '(push '(python-mode . python-module-path) ffap-alist))
2244 ;;;; Find-function support
2246 ;; Fixme: key binding?
2248 (defun python-find-function (name)
2249 "Find source of definition of function NAME.
2250 Interactively, prompt for name."
2251 (interactive
2252 (let ((symbol (with-syntax-table python-dotty-syntax-table
2253 (current-word)))
2254 (enable-recursive-minibuffers t))
2255 (list (read-string (if symbol
2256 (format "Find location of (default %s): " symbol)
2257 "Find location of: ")
2258 nil nil symbol))))
2259 (unless python-imports
2260 (error "Not called from buffer visiting Python file"))
2261 (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
2262 name python-imports)))
2263 (loc (car (read-from-string loc)))
2264 (file (car loc))
2265 (line (cdr loc)))
2266 (unless file (error "Don't know where `%s' is defined" name))
2267 (pop-to-buffer (find-file-noselect file))
2268 (when (integerp line)
2269 (goto-char (point-min))
2270 (forward-line (1- line)))))
2272 ;;;; Skeletons
2274 (defcustom python-use-skeletons nil
2275 "Non-nil means template skeletons will be automagically inserted.
2276 This happens when pressing \"if<SPACE>\", for example, to prompt for
2277 the if condition."
2278 :type 'boolean
2279 :group 'python)
2281 (define-abbrev-table 'python-mode-abbrev-table ()
2282 "Abbrev table for Python mode."
2283 :case-fixed t
2284 ;; Allow / inside abbrevs.
2285 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2286 ;; Only expand in code.
2287 :enable-function (lambda () (not (python-in-string/comment))))
2289 (eval-when-compile
2290 ;; Define a user-level skeleton and add it to the abbrev table.
2291 (defmacro def-python-skeleton (name &rest elements)
2292 (declare (indent 2))
2293 (let* ((name (symbol-name name))
2294 (function (intern (concat "python-insert-" name))))
2295 `(progn
2296 ;; Usual technique for inserting a skeleton, but expand
2297 ;; to the original abbrev instead if in a comment or string.
2298 (when python-use-skeletons
2299 (define-abbrev python-mode-abbrev-table ,name ""
2300 ',function
2301 nil t)) ; system abbrev
2302 (define-skeleton ,function
2303 ,(format "Insert Python \"%s\" template." name)
2304 ,@elements)))))
2306 ;; From `skeleton-further-elements' set below:
2307 ;; `<': outdent a level;
2308 ;; `^': delete indentation on current line and also previous newline.
2309 ;; Not quite like `delete-indentation'. Assumes point is at
2310 ;; beginning of indentation.
2312 (def-python-skeleton if
2313 "Condition: "
2314 "if " str ":" \n
2315 > -1 ; Fixme: I don't understand the spurious space this removes.
2316 _ \n
2317 ("other condition, %s: "
2318 < ; Avoid wrong indentation after block opening.
2319 "elif " str ":" \n
2320 > _ \n nil)
2321 '(python-else) | ^)
2323 (define-skeleton python-else
2324 "Auxiliary skeleton."
2326 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2327 (signal 'quit t))
2328 < "else:" \n
2329 > _ \n)
2331 (def-python-skeleton while
2332 "Condition: "
2333 "while " str ":" \n
2334 > -1 _ \n
2335 '(python-else) | ^)
2337 (def-python-skeleton for
2338 "Target, %s: "
2339 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2340 > -1 _ \n
2341 '(python-else) | ^)
2343 (def-python-skeleton try/except
2345 "try:" \n
2346 > -1 _ \n
2347 ("Exception, %s: "
2348 < "except " str '(python-target) ":" \n
2349 > _ \n nil)
2350 < "except:" \n
2351 > _ \n
2352 '(python-else) | ^)
2354 (define-skeleton python-target
2355 "Auxiliary skeleton."
2356 "Target, %s: " ", " str | -2)
2358 (def-python-skeleton try/finally
2360 "try:" \n
2361 > -1 _ \n
2362 < "finally:" \n
2363 > _ \n)
2365 (def-python-skeleton def
2366 "Name: "
2367 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2368 str) "):" \n
2369 "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
2370 > _ \n)
2372 (def-python-skeleton class
2373 "Name: "
2374 "class " str " (" ("Inheritance, %s: "
2375 (unless (equal ?\( (char-before)) ", ")
2376 str)
2377 & ")" | -2 ; close list or remove opening
2378 ":" \n
2379 "\"\"\"" - "\"\"\"" \n
2380 > _ \n)
2382 (defvar python-default-template "if"
2383 "Default template to expand by `python-expand-template'.
2384 Updated on each expansion.")
2386 (defun python-expand-template (name)
2387 "Expand template named NAME.
2388 Interactively, prompt for the name with completion."
2389 (interactive
2390 (list (completing-read (format "Template to expand (default %s): "
2391 python-default-template)
2392 python-mode-abbrev-table nil t nil nil
2393 python-default-template)))
2394 (if (equal "" name)
2395 (setq name python-default-template)
2396 (setq python-default-template name))
2397 (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
2398 (if sym
2399 (abbrev-insert sym)
2400 (error "Undefined template: %s" name))))
2402 ;;;; Bicycle Repair Man support
2404 (autoload 'pymacs-load "pymacs" nil t)
2405 (autoload 'brm-init "bikemacs")
2407 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2408 ;; the way it modifies files outside Emacs... Also note that the
2409 ;; current BRM loses with tabs used for indentation -- I submitted a
2410 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2411 (defun python-setup-brm ()
2412 "Set up Bicycle Repair Man refactoring tool (if available).
2414 Note that the `refactoring' features change files independently of
2415 Emacs and may modify and save the contents of the current buffer
2416 without confirmation."
2417 (interactive)
2418 (condition-case data
2419 (unless (fboundp 'brm-rename)
2420 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2421 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2422 (features (cons 'python-mode features))) ; and requires this
2423 (brm-init) ; second line of normal recipe
2424 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2425 '(lambda () (easy-menu-add brm-menu)))
2426 (easy-menu-define
2427 python-brm-menu python-mode-map
2428 "Bicycle Repair Man"
2429 '("BicycleRepairMan"
2430 :help "Interface to navigation and refactoring tool"
2431 "Queries"
2432 ["Find References" brm-find-references
2433 :help "Find references to name at point in compilation buffer"]
2434 ["Find Definition" brm-find-definition
2435 :help "Find definition of name at point"]
2437 "Refactoring"
2438 ["Rename" brm-rename
2439 :help "Replace name at point with a new name everywhere"]
2440 ["Extract Method" brm-extract-method
2441 :active (and mark-active (not buffer-read-only))
2442 :help "Replace statements in region with a method"]
2443 ["Extract Local Variable" brm-extract-local-variable
2444 :active (and mark-active (not buffer-read-only))
2445 :help "Replace expression in region with an assignment"]
2446 ["Inline Local Variable" brm-inline-local-variable
2447 :help
2448 "Substitute uses of variable at point with its definition"]
2449 ;; Fixme: Should check for anything to revert.
2450 ["Undo Last Refactoring" brm-undo :help ""]))))
2451 (error (error "BicycleRepairMan setup failed: %s" data))))
2453 ;;;; Modes.
2455 ;; pdb tracking is alert once this file is loaded, but takes no action if
2456 ;; `python-pdbtrack-do-tracking-p' is nil.
2457 (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2459 (defvar outline-heading-end-regexp)
2460 (defvar eldoc-documentation-function)
2461 (defvar python-mode-running) ;Dynamically scoped var.
2463 ;;;###autoload
2464 (define-derived-mode python-mode fundamental-mode "Python"
2465 "Major mode for editing Python files.
2466 Turns on Font Lock mode unconditionally since it is currently required
2467 for correct parsing of the source.
2468 See also `jython-mode', which is actually invoked if the buffer appears to
2469 contain Jython code. See also `run-python' and associated Python mode
2470 commands for running Python under Emacs.
2472 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2473 with nested `def' and `class' blocks. They take the innermost one as
2474 current without distinguishing method and class definitions. Used multiple
2475 times, they move over others at the same indentation level until they reach
2476 the end of definitions at that level, when they move up a level.
2477 \\<python-mode-map>
2478 Colon is electric: it outdents the line if appropriate, e.g. for
2479 an else statement. \\[python-backspace] at the beginning of an indented statement
2480 deletes a level of indentation to close the current block; otherwise it
2481 deletes a character backward. TAB indents the current line relative to
2482 the preceding code. Successive TABs, with no intervening command, cycle
2483 through the possibilities for indentation on the basis of enclosing blocks.
2485 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2486 effect outside them.
2488 Supports Eldoc mode (only for functions, using a Python process),
2489 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2490 lines count as headers. Symbol completion is available in the
2491 same way as in the Python shell using the `rlcompleter' module
2492 and this is added to the Hippie Expand functions locally if
2493 Hippie Expand mode is turned on. Completion of symbols of the
2494 form x.y only works if the components are literal
2495 module/attribute names, not variables. An abbrev table is set up
2496 with skeleton expansions for compound statement templates.
2498 \\{python-mode-map}"
2499 :group 'python
2500 (set (make-local-variable 'font-lock-defaults)
2501 '(python-font-lock-keywords nil nil nil nil
2502 ;; This probably isn't worth it.
2503 ;; (font-lock-syntactic-face-function
2504 ;; . python-font-lock-syntactic-face-function)
2506 (set (make-local-variable 'syntax-propertize-function)
2507 python-syntax-propertize-function)
2508 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2509 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2510 (set (make-local-variable 'comment-start) "# ")
2511 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2512 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2513 (set (make-local-variable 'paragraph-start) "\\s-*$")
2514 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2515 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2516 (set (make-local-variable 'add-log-current-defun-function)
2517 #'python-current-defun)
2518 (set (make-local-variable 'outline-regexp)
2519 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2520 "for" "if" "try" "while" "with")
2521 symbol-end))
2522 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2523 (set (make-local-variable 'outline-level) #'python-outline-level)
2524 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2525 (set (make-local-variable 'beginning-of-defun-function)
2526 'python-beginning-of-defun)
2527 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2528 (add-hook 'which-func-functions 'python-which-func nil t)
2529 (setq imenu-create-index-function #'python-imenu-create-index)
2530 (set (make-local-variable 'eldoc-documentation-function)
2531 #'python-eldoc-function)
2532 (add-hook 'eldoc-mode-hook
2533 (lambda () (run-python nil t)) ; need it running
2534 nil t)
2535 (add-hook 'completion-at-point-functions
2536 'python-completion-at-point nil 'local)
2537 ;; Fixme: should be in hideshow. This seems to be of limited use
2538 ;; since it isn't (can't be) indentation-based. Also hide-level
2539 ;; doesn't seem to work properly.
2540 (add-to-list 'hs-special-modes-alist
2541 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2542 ,(lambda (arg)
2543 (python-end-of-defun)
2544 (skip-chars-backward " \t\n"))
2545 nil))
2546 (set (make-local-variable 'skeleton-further-elements)
2547 '((< '(backward-delete-char-untabify (min python-indent
2548 (current-column))))
2549 (^ '(- (1+ (current-indentation))))))
2550 ;; Python defines TABs as being 8-char wide.
2551 (set (make-local-variable 'tab-width) 8)
2552 (unless font-lock-mode (font-lock-mode 1))
2553 (when python-guess-indent (python-guess-indent))
2554 ;; Let's make it harder for the user to shoot himself in the foot.
2555 (unless (= tab-width python-indent)
2556 (setq indent-tabs-mode nil))
2557 (set (make-local-variable 'python-command) python-python-command)
2558 (python-find-imports)
2559 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2560 (let ((python-mode-running t))
2561 (python-maybe-jython))))
2563 ;; Not done automatically in Emacs 21 or 22.
2564 (defcustom python-mode-hook nil
2565 "Hook run when entering Python mode."
2566 :group 'python
2567 :type 'hook)
2568 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2569 (custom-add-option 'python-mode-hook
2570 (lambda ()
2571 "Turn off Indent Tabs mode."
2572 (setq indent-tabs-mode nil)))
2573 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2574 (custom-add-option 'python-mode-hook 'abbrev-mode)
2575 (custom-add-option 'python-mode-hook 'python-setup-brm)
2577 ;;;###autoload
2578 (define-derived-mode jython-mode python-mode "Jython"
2579 "Major mode for editing Jython files.
2580 Like `python-mode', but sets up parameters for Jython subprocesses.
2581 Runs `jython-mode-hook' after `python-mode-hook'."
2582 :group 'python
2583 (set (make-local-variable 'python-command) python-jython-command))
2587 ;; pdbtrack features
2589 (defun python-comint-output-filter-function (string)
2590 "Watch output for Python prompt and exec next file waiting in queue.
2591 This function is appropriate for `comint-output-filter-functions'."
2592 ;; TBD: this should probably use split-string
2593 (when (and (string-match python--prompt-regexp string)
2594 python-file-queue)
2595 (condition-case nil
2596 (delete-file (car python-file-queue))
2597 (error nil))
2598 (setq python-file-queue (cdr python-file-queue))
2599 (if python-file-queue
2600 (let ((pyproc (get-buffer-process (current-buffer))))
2601 (python-execute-file pyproc (car python-file-queue))))))
2603 (defun python-pdbtrack-overlay-arrow (activation)
2604 "Activate or deactivate arrow at beginning-of-line in current buffer."
2605 (if activation
2606 (progn
2607 (setq overlay-arrow-position (make-marker)
2608 overlay-arrow-string "=>"
2609 python-pdbtrack-is-tracking-p t)
2610 (set-marker overlay-arrow-position
2611 (line-beginning-position)
2612 (current-buffer)))
2613 (setq overlay-arrow-position nil
2614 python-pdbtrack-is-tracking-p nil)))
2616 (defun python-pdbtrack-track-stack-file (text)
2617 "Show the file indicated by the pdb stack entry line, in a separate window.
2619 Activity is disabled if the buffer-local variable
2620 `python-pdbtrack-do-tracking-p' is nil.
2622 We depend on the pdb input prompt being a match for
2623 `python-pdbtrack-input-prompt'.
2625 If the traceback target file path is invalid, we look for the
2626 most recently visited python-mode buffer which either has the
2627 name of the current function or class, or which defines the
2628 function or class. This is to provide for scripts not in the
2629 local filesytem (e.g., Zope's 'Script \(Python)', but it's not
2630 Zope specific). If you put a copy of the script in a buffer
2631 named for the script and activate python-mode, then pdbtrack will
2632 find it."
2633 ;; Instead of trying to piece things together from partial text
2634 ;; (which can be almost useless depending on Emacs version), we
2635 ;; monitor to the point where we have the next pdb prompt, and then
2636 ;; check all text from comint-last-input-end to process-mark.
2638 ;; Also, we're very conservative about clearing the overlay arrow,
2639 ;; to minimize residue. This means, for instance, that executing
2640 ;; other pdb commands wipe out the highlight. You can always do a
2641 ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
2643 (let* ((origbuf (current-buffer))
2644 (currproc (get-buffer-process origbuf)))
2646 (if (not (and currproc python-pdbtrack-do-tracking-p))
2647 (python-pdbtrack-overlay-arrow nil)
2649 (let* ((procmark (process-mark currproc))
2650 (block (buffer-substring (max comint-last-input-end
2651 (- procmark
2652 python-pdbtrack-track-range))
2653 procmark))
2654 target target_fname target_lineno target_buffer)
2656 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2657 (python-pdbtrack-overlay-arrow nil)
2659 (setq target (python-pdbtrack-get-source-buffer block))
2661 (if (stringp target)
2662 (progn
2663 (python-pdbtrack-overlay-arrow nil)
2664 (message "pdbtrack: %s" target))
2666 (setq target_lineno (car target)
2667 target_buffer (cadr target)
2668 target_fname (buffer-file-name target_buffer))
2669 (switch-to-buffer-other-window target_buffer)
2670 (goto-char (point-min))
2671 (forward-line (1- target_lineno))
2672 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
2673 (python-pdbtrack-overlay-arrow t)
2674 (pop-to-buffer origbuf t)
2675 ;; in large shell buffers, above stuff may cause point to lag output
2676 (goto-char procmark)
2677 )))))
2680 (defun python-pdbtrack-get-source-buffer (block)
2681 "Return line number and buffer of code indicated by block's traceback text.
2683 We look first to visit the file indicated in the trace.
2685 Failing that, we look for the most recently visited python-mode buffer
2686 with the same name or having the named function.
2688 If we're unable find the source code we return a string describing the
2689 problem."
2691 (if (not (string-match python-pdbtrack-stack-entry-regexp block))
2693 "Traceback cue not found"
2695 (let* ((filename (match-string 1 block))
2696 (lineno (string-to-number (match-string 2 block)))
2697 (funcname (match-string 3 block))
2698 funcbuffer)
2700 (cond ((file-exists-p filename)
2701 (list lineno (find-file-noselect filename)))
2703 ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
2704 (if (string-match "/Script (Python)$" filename)
2705 ;; Add in number of lines for leading '##' comments:
2706 (setq lineno
2707 (+ lineno
2708 (with-current-buffer funcbuffer
2709 (if (equal (point-min)(point-max))
2711 (count-lines
2712 (point-min)
2713 (max (point-min)
2714 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
2715 (buffer-substring
2716 (point-min) (point-max)))
2717 )))))))
2718 (list lineno funcbuffer))
2720 ((= (elt filename 0) ?\<)
2721 (format "(Non-file source: '%s')" filename))
2723 (t (format "Not found: %s(), %s" funcname filename)))
2728 (defun python-pdbtrack-grub-for-buffer (funcname lineno)
2729 "Find recent python-mode buffer named, or having function named funcname."
2730 (let ((buffers (buffer-list))
2732 got)
2733 (while (and buffers (not got))
2734 (setq buf (car buffers)
2735 buffers (cdr buffers))
2736 (if (and (with-current-buffer buf
2737 (string= major-mode "python-mode"))
2738 (or (string-match funcname (buffer-name buf))
2739 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
2740 funcname "\\s-*(")
2741 (with-current-buffer buf
2742 (buffer-substring (point-min)
2743 (point-max))))))
2744 (setq got buf)))
2745 got))
2747 (defun python-toggle-shells (arg)
2748 "Toggles between the CPython and JPython shells.
2750 With positive argument ARG (interactively \\[universal-argument]),
2751 uses the CPython shell, with negative ARG uses the JPython shell, and
2752 with a zero argument, toggles the shell.
2754 Programmatically, ARG can also be one of the symbols `cpython' or
2755 `jpython', equivalent to positive arg and negative arg respectively."
2756 (interactive "P")
2757 ;; default is to toggle
2758 (if (null arg)
2759 (setq arg 0))
2760 ;; preprocess arg
2761 (cond
2762 ((equal arg 0)
2763 ;; toggle
2764 (if (string-equal python-which-bufname "Python")
2765 (setq arg -1)
2766 (setq arg 1)))
2767 ((equal arg 'cpython) (setq arg 1))
2768 ((equal arg 'jpython) (setq arg -1)))
2769 (let (msg)
2770 (cond
2771 ((< 0 arg)
2772 ;; set to CPython
2773 (setq python-which-shell python-python-command
2774 python-which-args python-python-command-args
2775 python-which-bufname "Python"
2776 msg "CPython"
2777 mode-name "Python"))
2778 ((> 0 arg)
2779 (setq python-which-shell python-jython-command
2780 python-which-args python-jython-command-args
2781 python-which-bufname "JPython"
2782 msg "JPython"
2783 mode-name "JPython")))
2784 (message "Using the %s shell" msg)))
2786 ;; Python subprocess utilities and filters
2787 (defun python-execute-file (proc filename)
2788 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
2789 Make that process's buffer visible and force display. Also make
2790 comint believe the user typed this string so that
2791 `kill-output-from-shell' does The Right Thing."
2792 (let ((curbuf (current-buffer))
2793 (procbuf (process-buffer proc))
2794 ; (comint-scroll-to-bottom-on-output t)
2795 (msg (format "## working on region in file %s...\n" filename))
2796 ;; add some comment, so that we can filter it out of history
2797 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
2798 (unwind-protect
2799 (with-current-buffer procbuf
2800 (goto-char (point-max))
2801 (move-marker (process-mark proc) (point))
2802 (funcall (process-filter proc) proc msg))
2803 (set-buffer curbuf))
2804 (process-send-string proc cmd)))
2806 ;;;###autoload
2807 (defun python-shell (&optional argprompt)
2808 "Start an interactive Python interpreter in another window.
2809 This is like Shell mode, except that Python is running in the window
2810 instead of a shell. See the `Interactive Shell' and `Shell Mode'
2811 sections of the Emacs manual for details, especially for the key
2812 bindings active in the `*Python*' buffer.
2814 With optional \\[universal-argument], the user is prompted for the
2815 flags to pass to the Python interpreter. This has no effect when this
2816 command is used to switch to an existing process, only when a new
2817 process is started. If you use this, you will probably want to ensure
2818 that the current arguments are retained (they will be included in the
2819 prompt). This argument is ignored when this function is called
2820 programmatically.
2822 Note: You can toggle between using the CPython interpreter and the
2823 JPython interpreter by hitting \\[python-toggle-shells]. This toggles
2824 buffer local variables which control whether all your subshell
2825 interactions happen to the `*JPython*' or `*Python*' buffers (the
2826 latter is the name used for the CPython buffer).
2828 Warning: Don't use an interactive Python if you change sys.ps1 or
2829 sys.ps2 from their default values, or if you're running code that
2830 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
2831 distinguish your output from Python's output, and assumes that `>>> '
2832 at the start of a line is a prompt from Python. Similarly, the Emacs
2833 Shell mode code assumes that both `>>> ' and `... ' at the start of a
2834 line are Python prompts. Bad things can happen if you fool either
2835 mode.
2837 Warning: If you do any editing *in* the process buffer *while* the
2838 buffer is accepting output from Python, do NOT attempt to `undo' the
2839 changes. Some of the output (nowhere near the parts you changed!) may
2840 be lost if you do. This appears to be an Emacs bug, an unfortunate
2841 interaction between undo and process filters; the same problem exists in
2842 non-Python process buffers using the default (Emacs-supplied) process
2843 filter."
2844 (interactive "P")
2845 (require 'ansi-color) ; For ipython
2846 ;; Set the default shell if not already set
2847 (when (null python-which-shell)
2848 (python-toggle-shells python-default-interpreter))
2849 (let ((args python-which-args))
2850 (when (and argprompt
2851 (called-interactively-p 'interactive)
2852 (fboundp 'split-string))
2853 ;; TBD: Perhaps force "-i" in the final list?
2854 (setq args (split-string
2855 (read-string (concat python-which-bufname
2856 " arguments: ")
2857 (concat
2858 (mapconcat 'identity python-which-args " ") " ")
2859 ))))
2860 (switch-to-buffer-other-window
2861 (apply 'make-comint python-which-bufname python-which-shell nil args))
2862 (set-process-sentinel (get-buffer-process (current-buffer))
2863 'python-sentinel)
2864 (python--set-prompt-regexp)
2865 (add-hook 'comint-output-filter-functions
2866 'python-comint-output-filter-function nil t)
2867 ;; pdbtrack
2868 (set-syntax-table python-mode-syntax-table)
2869 (use-local-map python-shell-map)))
2871 (defun python-pdbtrack-toggle-stack-tracking (arg)
2872 (interactive "P")
2873 (if (not (get-buffer-process (current-buffer)))
2874 (error "No process associated with buffer '%s'" (current-buffer)))
2875 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2876 (if (or (not arg)
2877 (zerop (setq arg (prefix-numeric-value arg))))
2878 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2879 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2880 (message "%sabled Python's pdbtrack"
2881 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2883 (defun turn-on-pdbtrack ()
2884 (interactive)
2885 (python-pdbtrack-toggle-stack-tracking 1))
2887 (defun turn-off-pdbtrack ()
2888 (interactive)
2889 (python-pdbtrack-toggle-stack-tracking 0))
2891 (defun python-sentinel (proc msg)
2892 (setq overlay-arrow-position nil))
2894 (provide 'python)
2895 (provide 'python-21)
2897 ;;; python.el ends here