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