Merge from trunk
[emacs.git] / lisp / progmodes / python.el
blob214599b52bc9f5de25a4cfe0bb5b32f5d6c90bae
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 (eval-when-compile (autoload 'help-buffer "help-fns"))
1764 (defvar python-imports) ; forward declaration
1766 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1767 ;; bound to C-h S? [Probably not, since info-look may work in cases
1768 ;; where this doesn't.]
1769 (defun python-describe-symbol (symbol)
1770 "Get help on SYMBOL using `help'.
1771 Interactively, prompt for symbol.
1773 Symbol may be anything recognized by the interpreter's `help'
1774 command -- e.g. `CALLS' -- not just variables in scope in the
1775 interpreter. This only works for Python version 2.2 or newer
1776 since earlier interpreters don't support `help'.
1778 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1779 will."
1780 ;; Note that we do this in the inferior process, not a separate one, to
1781 ;; ensure the environment is appropriate.
1782 (interactive
1783 (let ((symbol (with-syntax-table python-dotty-syntax-table
1784 (current-word)))
1785 (enable-recursive-minibuffers t))
1786 (list (read-string (if symbol
1787 (format "Describe symbol (default %s): " symbol)
1788 "Describe symbol: ")
1789 nil nil symbol))))
1790 (if (equal symbol "") (error "No symbol"))
1791 ;; Ensure we have a suitable help buffer.
1792 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1793 ;; allow C-c C-f in help buffer.
1794 (let ((temp-buffer-show-hook ; avoid xref stuff
1795 (lambda ()
1796 (toggle-read-only 1))))
1797 (with-help-window (help-buffer)
1798 (with-current-buffer standard-output
1799 ;; Fixme: Is this actually useful?
1800 (help-setup-xref (list 'python-describe-symbol symbol)
1801 (called-interactively-p 'interactive))
1802 (set (make-local-variable 'comint-redirect-subvert-readonly) t))))
1803 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1804 symbol python-imports)
1805 "*Help*" (python-proc) nil nil))
1807 (add-to-list 'debug-ignored-errors "^No symbol")
1809 (defun python-send-receive (string)
1810 "Send STRING to inferior Python (if any) and return result.
1811 The result is what follows `_emacs_out' in the output.
1812 This is a no-op if `python-check-comint-prompt' returns nil."
1813 (python-send-string string)
1814 (let ((proc (python-proc)))
1815 (with-current-buffer (process-buffer proc)
1816 (when (python-check-comint-prompt proc)
1817 (set (make-local-variable 'python-preoutput-result) nil)
1818 (while (progn
1819 (accept-process-output proc 5)
1820 (null python-preoutput-result)))
1821 (prog1 python-preoutput-result
1822 (kill-local-variable 'python-preoutput-result))))))
1824 (defun python-check-comint-prompt (&optional proc)
1825 "Return non-nil if and only if there's a normal prompt in the inferior buffer.
1826 If there isn't, it's probably not appropriate to send input to return Eldoc
1827 information etc. If PROC is non-nil, check the buffer for that process."
1828 (with-current-buffer (process-buffer (or proc (python-proc)))
1829 (save-excursion
1830 (save-match-data
1831 (re-search-backward (concat python--prompt-regexp " *\\=")
1832 nil t)))))
1834 ;; Fixme: Is there anything reasonable we can do with random methods?
1835 ;; (Currently only works with functions.)
1836 (defun python-eldoc-function ()
1837 "`eldoc-documentation-function' for Python.
1838 Only works when point is in a function name, not its arg list, for
1839 instance. Assumes an inferior Python is running."
1840 (let ((symbol (with-syntax-table python-dotty-syntax-table
1841 (current-word))))
1842 ;; This is run from timers, so inhibit-quit tends to be set.
1843 (with-local-quit
1844 ;; First try the symbol we're on.
1845 (or (and symbol
1846 (python-send-receive (format "emacs.eargs(%S, %s)"
1847 symbol python-imports)))
1848 ;; Try moving to symbol before enclosing parens.
1849 (let ((s (syntax-ppss)))
1850 (unless (zerop (car s))
1851 (when (eq ?\( (char-after (nth 1 s)))
1852 (save-excursion
1853 (goto-char (nth 1 s))
1854 (skip-syntax-backward "-")
1855 (let ((point (point)))
1856 (skip-chars-backward "a-zA-Z._")
1857 (if (< (point) point)
1858 (python-send-receive
1859 (format "emacs.eargs(%S, %s)"
1860 (buffer-substring-no-properties (point) point)
1861 python-imports))))))))))))
1863 ;;;; Info-look functionality.
1865 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1867 (defun python-after-info-look ()
1868 "Set up info-look for Python.
1869 Used with `eval-after-load'."
1870 (let* ((version (let ((s (shell-command-to-string (concat python-command
1871 " -V"))))
1872 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1873 (match-string 1 s)))
1874 ;; Whether info files have a Python version suffix, e.g. in Debian.
1875 (versioned
1876 (with-temp-buffer
1877 (with-no-warnings (Info-mode))
1878 (condition-case ()
1879 ;; Don't use `info' because it would pop-up a *info* buffer.
1880 (with-no-warnings
1881 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1882 version))
1884 (error nil)))))
1885 (info-lookup-maybe-add-help
1886 :mode 'python-mode
1887 :regexp "[[:alnum:]_]+"
1888 :doc-spec
1889 ;; Fixme: Can this reasonably be made specific to indices with
1890 ;; different rules? Is the order of indices optimal?
1891 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1892 ;; instance.)
1893 (if versioned
1894 ;; The empty prefix just gets us highlighted terms.
1895 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1896 (,(concat "(python" version "-ref)Module Index" nil ""))
1897 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1898 nil ""))
1899 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1900 nil ""))
1901 (,(concat "(python" version "-lib)Module Index" nil ""))
1902 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1903 nil ""))
1904 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1905 nil ""))
1906 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1907 '(("(python-ref)Miscellaneous Index" nil "")
1908 ("(python-ref)Module Index" nil "")
1909 ("(python-ref)Function-Method-Variable Index" nil "")
1910 ("(python-ref)Class-Exception-Object Index" nil "")
1911 ("(python-lib)Module Index" nil "")
1912 ("(python-lib)Class-Exception-Object Index" nil "")
1913 ("(python-lib)Function-Method-Variable Index" nil "")
1914 ("(python-lib)Miscellaneous Index" nil ""))))))
1915 (eval-after-load "info-look" '(python-after-info-look))
1917 ;;;; Miscellany.
1919 (defcustom python-jython-packages '("java" "javax" "org" "com")
1920 "Packages implying `jython-mode'.
1921 If these are imported near the beginning of the buffer, `python-mode'
1922 actually punts to `jython-mode'."
1923 :type '(repeat string)
1924 :group 'python)
1926 ;; Called from `python-mode', this causes a recursive call of the
1927 ;; mode. See logic there to break out of the recursion.
1928 (defun python-maybe-jython ()
1929 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1930 The criterion is either a match for `jython-mode' via
1931 `interpreter-mode-alist' or an import of a module from the list
1932 `python-jython-packages'."
1933 ;; The logic is taken from python-mode.el.
1934 (save-excursion
1935 (save-restriction
1936 (widen)
1937 (goto-char (point-min))
1938 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1939 (match-string 2))))
1940 (if (and interpreter (eq 'jython-mode
1941 (cdr (assoc (file-name-nondirectory
1942 interpreter)
1943 interpreter-mode-alist))))
1944 (jython-mode)
1945 (if (catch 'done
1946 (while (re-search-forward
1947 (rx line-start (or "import" "from") (1+ space)
1948 (group (1+ (not (any " \t\n.")))))
1949 (+ (point-min) 10000) ; Probably not worth customizing.
1951 (if (member (match-string 1) python-jython-packages)
1952 (throw 'done t))))
1953 (jython-mode)))))))
1955 (defun python-fill-paragraph (&optional justify)
1956 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1957 If any of the current line is in or at the end of a multi-line string,
1958 fill the string or the paragraph of it that point is in, preserving
1959 the string's indentation."
1960 (interactive "P")
1961 (or (fill-comment-paragraph justify)
1962 (save-excursion
1963 (end-of-line)
1964 (let* ((syntax (syntax-ppss))
1965 (orig (point))
1966 start end)
1967 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
1968 (let (fill-paragraph-function)
1969 (fill-paragraph justify)))
1970 ;; The `paragraph-start' and `paragraph-separate'
1971 ;; variables don't allow us to delimit the last
1972 ;; paragraph in a multi-line string properly, so narrow
1973 ;; to the string and then fill around (the end of) the
1974 ;; current line.
1975 ((eq t (nth 3 syntax)) ; in fenced string
1976 (goto-char (nth 8 syntax)) ; string start
1977 (setq start (line-beginning-position))
1978 (setq end (condition-case () ; for unbalanced quotes
1979 (progn (forward-sexp)
1980 (- (point) 3))
1981 (error (point-max)))))
1982 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
1983 (forward-char)
1984 (setq end (point))
1985 (condition-case ()
1986 (progn (backward-sexp)
1987 (setq start (line-beginning-position)))
1988 (error nil))))
1989 (when end
1990 (save-restriction
1991 (narrow-to-region start end)
1992 (goto-char orig)
1993 ;; Avoid losing leading and trailing newlines in doc
1994 ;; strings written like:
1995 ;; """
1996 ;; ...
1997 ;; """
1998 (let ((paragraph-separate
1999 ;; Note that the string could be part of an
2000 ;; expression, so it can have preceding and
2001 ;; trailing non-whitespace.
2002 (concat
2003 (rx (or
2004 ;; Opening triple quote without following text.
2005 (and (* nonl)
2006 (group (syntax string-delimiter))
2007 (repeat 2 (backref 1))
2008 ;; Fixme: Not sure about including
2009 ;; trailing whitespace.
2010 (* (any " \t"))
2011 eol)
2012 ;; Closing trailing quote without preceding text.
2013 (and (group (any ?\" ?')) (backref 2)
2014 (syntax string-delimiter))))
2015 "\\(?:" paragraph-separate "\\)"))
2016 fill-paragraph-function)
2017 (fill-paragraph justify))))))) t)
2019 (defun python-shift-left (start end &optional count)
2020 "Shift lines in region COUNT (the prefix arg) columns to the left.
2021 COUNT defaults to `python-indent'. If region isn't active, just shift
2022 current line. The region shifted includes the lines in which START and
2023 END lie. It is an error if any lines in the region are indented less than
2024 COUNT columns."
2025 (interactive
2026 (if mark-active
2027 (list (region-beginning) (region-end) current-prefix-arg)
2028 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2029 (if count
2030 (setq count (prefix-numeric-value count))
2031 (setq count python-indent))
2032 (when (> count 0)
2033 (save-excursion
2034 (goto-char start)
2035 (while (< (point) end)
2036 (if (and (< (current-indentation) count)
2037 (not (looking-at "[ \t]*$")))
2038 (error "Can't shift all lines enough"))
2039 (forward-line))
2040 (indent-rigidly start end (- count)))))
2042 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
2044 (defun python-shift-right (start end &optional count)
2045 "Shift lines in region COUNT (the prefix arg) columns to the right.
2046 COUNT defaults to `python-indent'. If region isn't active, just shift
2047 current line. The region shifted includes the lines in which START and
2048 END lie."
2049 (interactive
2050 (if mark-active
2051 (list (region-beginning) (region-end) current-prefix-arg)
2052 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2053 (if count
2054 (setq count (prefix-numeric-value count))
2055 (setq count python-indent))
2056 (indent-rigidly start end count))
2058 (defun python-outline-level ()
2059 "`outline-level' function for Python mode.
2060 The level is the number of `python-indent' steps of indentation
2061 of current line."
2062 (1+ (/ (current-indentation) python-indent)))
2064 ;; Fixme: Consider top-level assignments, imports, &c.
2065 (defun python-current-defun (&optional length-limit)
2066 "`add-log-current-defun-function' for Python."
2067 (save-excursion
2068 ;; Move up the tree of nested `class' and `def' blocks until we
2069 ;; get to zero indentation, accumulating the defined names.
2070 (let ((accum)
2071 (length -1))
2072 (catch 'done
2073 (while (or (null length-limit)
2074 (null (cdr accum))
2075 (< length length-limit))
2076 (let ((started-from (point)))
2077 (python-beginning-of-block)
2078 (end-of-line)
2079 (beginning-of-defun)
2080 (when (= (point) started-from)
2081 (throw 'done nil)))
2082 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
2083 (group (1+ (or word (syntax symbol))))))
2084 (push (match-string 1) accum)
2085 (setq length (+ length 1 (length (car accum)))))
2086 (when (= (current-indentation) 0)
2087 (throw 'done nil))))
2088 (when accum
2089 (when (and length-limit (> length length-limit))
2090 (setcar accum ".."))
2091 (mapconcat 'identity accum ".")))))
2093 (defun python-mark-block ()
2094 "Mark the block around point.
2095 Uses `python-beginning-of-block', `python-end-of-block'."
2096 (interactive)
2097 (push-mark)
2098 (python-beginning-of-block)
2099 (push-mark (point) nil t)
2100 (python-end-of-block)
2101 (exchange-point-and-mark))
2103 ;; Fixme: Provide a find-function-like command to find source of a
2104 ;; definition (separate from BicycleRepairMan). Complicated by
2105 ;; finding the right qualified name.
2107 ;;;; Completion.
2109 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
2110 (defvar python-imports "None"
2111 "String of top-level import statements updated by `python-find-imports'.")
2112 (make-variable-buffer-local 'python-imports)
2114 ;; Fixme: Should font-lock try to run this when it deals with an import?
2115 ;; Maybe not a good idea if it gets run multiple times when the
2116 ;; statement is being edited, and is more likely to end up with
2117 ;; something syntactically incorrect.
2118 ;; However, what we should do is to trundle up the block tree from point
2119 ;; to extract imports that appear to be in scope, and add those.
2120 (defun python-find-imports ()
2121 "Find top-level imports, updating `python-imports'."
2122 (interactive)
2123 (save-excursion
2124 (let (lines)
2125 (goto-char (point-min))
2126 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
2127 (unless (syntax-ppss-context (syntax-ppss))
2128 (let ((start (line-beginning-position)))
2129 ;; Skip over continued lines.
2130 (while (and (eq ?\\ (char-before (line-end-position)))
2131 (= 0 (forward-line 1)))
2133 (push (buffer-substring start (line-beginning-position 2))
2134 lines))))
2135 (setq python-imports
2136 (if lines
2137 (apply #'concat
2138 ;; This is probably best left out since you're unlikely to need the
2139 ;; doc for a function in the buffer and the import will lose if the
2140 ;; Python sub-process' working directory isn't the same as the
2141 ;; buffer's.
2142 ;; (if buffer-file-name
2143 ;; (concat
2144 ;; "import "
2145 ;; (file-name-sans-extension
2146 ;; (file-name-nondirectory buffer-file-name))))
2147 (nreverse lines))
2148 "None"))
2149 (when lines
2150 (set-text-properties 0 (length python-imports) nil python-imports)
2151 ;; The output ends up in the wrong place if the string we
2152 ;; send contains newlines (from the imports).
2153 (setq python-imports
2154 (replace-regexp-in-string "\n" "\\n"
2155 (format "%S" python-imports) t t))))))
2157 ;; Fixme: This fails the first time if the sub-process isn't already
2158 ;; running. Presumably a timing issue with i/o to the process.
2159 (defun python-symbol-completions (symbol)
2160 "Return a list of completions of the string SYMBOL from Python process.
2161 The list is sorted.
2162 Uses `python-imports' to load modules against which to complete."
2163 (when (stringp symbol)
2164 (let ((completions
2165 (condition-case ()
2166 (car (read-from-string
2167 (python-send-receive
2168 (format "emacs.complete(%S,%s)"
2169 (substring-no-properties symbol)
2170 python-imports))))
2171 (error nil))))
2172 (sort
2173 ;; We can get duplicates from the above -- don't know why.
2174 (delete-dups completions)
2175 #'string<))))
2177 (defun python-completion-at-point ()
2178 (let ((end (point))
2179 (start (save-excursion
2180 (and (re-search-backward
2181 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2182 (group (1+ (regexp "[[:alnum:]._]"))) point)
2183 nil t)
2184 (match-beginning 1)))))
2185 (when start
2186 (list start end
2187 (completion-table-dynamic 'python-symbol-completions)))))
2189 ;;;; FFAP support
2191 (defun python-module-path (module)
2192 "Function for `ffap-alist' to return path to MODULE."
2193 (python-send-receive (format "emacs.modpath (%S)" module)))
2195 (eval-after-load "ffap"
2196 '(push '(python-mode . python-module-path) ffap-alist))
2198 ;;;; Find-function support
2200 ;; Fixme: key binding?
2202 (defun python-find-function (name)
2203 "Find source of definition of function NAME.
2204 Interactively, prompt for name."
2205 (interactive
2206 (let ((symbol (with-syntax-table python-dotty-syntax-table
2207 (current-word)))
2208 (enable-recursive-minibuffers t))
2209 (list (read-string (if symbol
2210 (format "Find location of (default %s): " symbol)
2211 "Find location of: ")
2212 nil nil symbol))))
2213 (unless python-imports
2214 (error "Not called from buffer visiting Python file"))
2215 (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
2216 name python-imports)))
2217 (loc (car (read-from-string loc)))
2218 (file (car loc))
2219 (line (cdr loc)))
2220 (unless file (error "Don't know where `%s' is defined" name))
2221 (pop-to-buffer (find-file-noselect file))
2222 (when (integerp line)
2223 (goto-char (point-min))
2224 (forward-line (1- line)))))
2226 ;;;; Skeletons
2228 (defcustom python-use-skeletons nil
2229 "Non-nil means template skeletons will be automagically inserted.
2230 This happens when pressing \"if<SPACE>\", for example, to prompt for
2231 the if condition."
2232 :type 'boolean
2233 :group 'python)
2235 (define-abbrev-table 'python-mode-abbrev-table ()
2236 "Abbrev table for Python mode."
2237 :case-fixed t
2238 ;; Allow / inside abbrevs.
2239 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2240 ;; Only expand in code.
2241 :enable-function (lambda () (not (python-in-string/comment))))
2243 (eval-when-compile
2244 ;; Define a user-level skeleton and add it to the abbrev table.
2245 (defmacro def-python-skeleton (name &rest elements)
2246 (declare (indent 2))
2247 (let* ((name (symbol-name name))
2248 (function (intern (concat "python-insert-" name))))
2249 `(progn
2250 ;; Usual technique for inserting a skeleton, but expand
2251 ;; to the original abbrev instead if in a comment or string.
2252 (when python-use-skeletons
2253 (define-abbrev python-mode-abbrev-table ,name ""
2254 ',function
2255 nil t)) ; system abbrev
2256 (define-skeleton ,function
2257 ,(format "Insert Python \"%s\" template." name)
2258 ,@elements)))))
2260 ;; From `skeleton-further-elements' set below:
2261 ;; `<': outdent a level;
2262 ;; `^': delete indentation on current line and also previous newline.
2263 ;; Not quite like `delete-indentation'. Assumes point is at
2264 ;; beginning of indentation.
2266 (def-python-skeleton if
2267 "Condition: "
2268 "if " str ":" \n
2269 > -1 ; Fixme: I don't understand the spurious space this removes.
2270 _ \n
2271 ("other condition, %s: "
2272 < ; Avoid wrong indentation after block opening.
2273 "elif " str ":" \n
2274 > _ \n nil)
2275 '(python-else) | ^)
2277 (define-skeleton python-else
2278 "Auxiliary skeleton."
2280 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2281 (signal 'quit t))
2282 < "else:" \n
2283 > _ \n)
2285 (def-python-skeleton while
2286 "Condition: "
2287 "while " str ":" \n
2288 > -1 _ \n
2289 '(python-else) | ^)
2291 (def-python-skeleton for
2292 "Target, %s: "
2293 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2294 > -1 _ \n
2295 '(python-else) | ^)
2297 (def-python-skeleton try/except
2299 "try:" \n
2300 > -1 _ \n
2301 ("Exception, %s: "
2302 < "except " str '(python-target) ":" \n
2303 > _ \n nil)
2304 < "except:" \n
2305 > _ \n
2306 '(python-else) | ^)
2308 (define-skeleton python-target
2309 "Auxiliary skeleton."
2310 "Target, %s: " ", " str | -2)
2312 (def-python-skeleton try/finally
2314 "try:" \n
2315 > -1 _ \n
2316 < "finally:" \n
2317 > _ \n)
2319 (def-python-skeleton def
2320 "Name: "
2321 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2322 str) "):" \n
2323 "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
2324 > _ \n)
2326 (def-python-skeleton class
2327 "Name: "
2328 "class " str " (" ("Inheritance, %s: "
2329 (unless (equal ?\( (char-before)) ", ")
2330 str)
2331 & ")" | -2 ; close list or remove opening
2332 ":" \n
2333 "\"\"\"" - "\"\"\"" \n
2334 > _ \n)
2336 (defvar python-default-template "if"
2337 "Default template to expand by `python-expand-template'.
2338 Updated on each expansion.")
2340 (defun python-expand-template (name)
2341 "Expand template named NAME.
2342 Interactively, prompt for the name with completion."
2343 (interactive
2344 (list (completing-read (format "Template to expand (default %s): "
2345 python-default-template)
2346 python-mode-abbrev-table nil t nil nil
2347 python-default-template)))
2348 (if (equal "" name)
2349 (setq name python-default-template)
2350 (setq python-default-template name))
2351 (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
2352 (if sym
2353 (abbrev-insert sym)
2354 (error "Undefined template: %s" name))))
2356 ;;;; Bicycle Repair Man support
2358 (autoload 'pymacs-load "pymacs" nil t)
2359 (autoload 'brm-init "bikemacs")
2360 (defvar brm-menu)
2362 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2363 ;; the way it modifies files outside Emacs... Also note that the
2364 ;; current BRM loses with tabs used for indentation -- I submitted a
2365 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2366 (defun python-setup-brm ()
2367 "Set up Bicycle Repair Man refactoring tool (if available).
2369 Note that the `refactoring' features change files independently of
2370 Emacs and may modify and save the contents of the current buffer
2371 without confirmation."
2372 (interactive)
2373 (condition-case data
2374 (unless (fboundp 'brm-rename)
2375 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2376 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2377 (features (cons 'python-mode features))) ; and requires this
2378 (brm-init) ; second line of normal recipe
2379 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2380 (lambda () (easy-menu-add brm-menu)))
2381 (easy-menu-define
2382 python-brm-menu python-mode-map
2383 "Bicycle Repair Man"
2384 '("BicycleRepairMan"
2385 :help "Interface to navigation and refactoring tool"
2386 "Queries"
2387 ["Find References" brm-find-references
2388 :help "Find references to name at point in compilation buffer"]
2389 ["Find Definition" brm-find-definition
2390 :help "Find definition of name at point"]
2392 "Refactoring"
2393 ["Rename" brm-rename
2394 :help "Replace name at point with a new name everywhere"]
2395 ["Extract Method" brm-extract-method
2396 :active (and mark-active (not buffer-read-only))
2397 :help "Replace statements in region with a method"]
2398 ["Extract Local Variable" brm-extract-local-variable
2399 :active (and mark-active (not buffer-read-only))
2400 :help "Replace expression in region with an assignment"]
2401 ["Inline Local Variable" brm-inline-local-variable
2402 :help
2403 "Substitute uses of variable at point with its definition"]
2404 ;; Fixme: Should check for anything to revert.
2405 ["Undo Last Refactoring" brm-undo :help ""]))))
2406 (error (error "BicycleRepairMan setup failed: %s" data))))
2408 ;;;; Modes.
2410 ;; pdb tracking is alert once this file is loaded, but takes no action if
2411 ;; `python-pdbtrack-do-tracking-p' is nil.
2412 (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2414 (defvar outline-heading-end-regexp)
2415 (defvar eldoc-documentation-function)
2416 (defvar python-mode-running) ;Dynamically scoped var.
2418 ;;;###autoload
2419 (define-derived-mode python-mode fundamental-mode "Python"
2420 "Major mode for editing Python files.
2421 Turns on Font Lock mode unconditionally since it is currently required
2422 for correct parsing of the source.
2423 See also `jython-mode', which is actually invoked if the buffer appears to
2424 contain Jython code. See also `run-python' and associated Python mode
2425 commands for running Python under Emacs.
2427 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2428 with nested `def' and `class' blocks. They take the innermost one as
2429 current without distinguishing method and class definitions. Used multiple
2430 times, they move over others at the same indentation level until they reach
2431 the end of definitions at that level, when they move up a level.
2432 \\<python-mode-map>
2433 Colon is electric: it outdents the line if appropriate, e.g. for
2434 an else statement. \\[python-backspace] at the beginning of an indented statement
2435 deletes a level of indentation to close the current block; otherwise it
2436 deletes a character backward. TAB indents the current line relative to
2437 the preceding code. Successive TABs, with no intervening command, cycle
2438 through the possibilities for indentation on the basis of enclosing blocks.
2440 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2441 effect outside them.
2443 Supports Eldoc mode (only for functions, using a Python process),
2444 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2445 lines count as headers. Symbol completion is available in the
2446 same way as in the Python shell using the `rlcompleter' module
2447 and this is added to the Hippie Expand functions locally if
2448 Hippie Expand mode is turned on. Completion of symbols of the
2449 form x.y only works if the components are literal
2450 module/attribute names, not variables. An abbrev table is set up
2451 with skeleton expansions for compound statement templates.
2453 \\{python-mode-map}"
2454 :group 'python
2455 (set (make-local-variable 'font-lock-defaults)
2456 '(python-font-lock-keywords nil nil nil nil
2457 ;; This probably isn't worth it.
2458 ;; (font-lock-syntactic-face-function
2459 ;; . python-font-lock-syntactic-face-function)
2461 (set (make-local-variable 'syntax-propertize-function)
2462 python-syntax-propertize-function)
2463 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2464 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2465 (set (make-local-variable 'comment-start) "# ")
2466 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2467 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2468 (set (make-local-variable 'paragraph-start) "\\s-*$")
2469 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2470 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2471 (set (make-local-variable 'add-log-current-defun-function)
2472 #'python-current-defun)
2473 (set (make-local-variable 'outline-regexp)
2474 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2475 "for" "if" "try" "while" "with")
2476 symbol-end))
2477 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2478 (set (make-local-variable 'outline-level) #'python-outline-level)
2479 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2480 (set (make-local-variable 'beginning-of-defun-function)
2481 'python-beginning-of-defun)
2482 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2483 (add-hook 'which-func-functions 'python-which-func nil t)
2484 (setq imenu-create-index-function #'python-imenu-create-index)
2485 (set (make-local-variable 'eldoc-documentation-function)
2486 #'python-eldoc-function)
2487 (add-hook 'eldoc-mode-hook
2488 (lambda () (run-python nil t)) ; need it running
2489 nil t)
2490 (add-hook 'completion-at-point-functions
2491 'python-completion-at-point nil 'local)
2492 ;; Fixme: should be in hideshow. This seems to be of limited use
2493 ;; since it isn't (can't be) indentation-based. Also hide-level
2494 ;; doesn't seem to work properly.
2495 (add-to-list 'hs-special-modes-alist
2496 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2497 ,(lambda (_arg)
2498 (python-end-of-defun)
2499 (skip-chars-backward " \t\n"))
2500 nil))
2501 (set (make-local-variable 'skeleton-further-elements)
2502 '((< '(backward-delete-char-untabify (min python-indent
2503 (current-column))))
2504 (^ '(- (1+ (current-indentation))))))
2505 ;; Python defines TABs as being 8-char wide.
2506 (set (make-local-variable 'tab-width) 8)
2507 (when python-guess-indent (python-guess-indent))
2508 ;; Let's make it harder for the user to shoot himself in the foot.
2509 (unless (= tab-width python-indent)
2510 (setq indent-tabs-mode nil))
2511 (set (make-local-variable 'python-command) python-python-command)
2512 (python-find-imports)
2513 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2514 (let ((python-mode-running t))
2515 (python-maybe-jython))))
2517 ;; Not done automatically in Emacs 21 or 22.
2518 (defcustom python-mode-hook nil
2519 "Hook run when entering Python mode."
2520 :group 'python
2521 :type 'hook)
2522 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2523 (custom-add-option 'python-mode-hook
2524 (lambda ()
2525 "Turn off Indent Tabs mode."
2526 (setq indent-tabs-mode nil)))
2527 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2528 (custom-add-option 'python-mode-hook 'abbrev-mode)
2529 (custom-add-option 'python-mode-hook 'python-setup-brm)
2531 ;;;###autoload
2532 (define-derived-mode jython-mode python-mode "Jython"
2533 "Major mode for editing Jython files.
2534 Like `python-mode', but sets up parameters for Jython subprocesses.
2535 Runs `jython-mode-hook' after `python-mode-hook'."
2536 :group 'python
2537 (set (make-local-variable 'python-command) python-jython-command))
2541 ;; pdbtrack features
2543 (defun python-pdbtrack-overlay-arrow (activation)
2544 "Activate or deactivate arrow at beginning-of-line in current buffer."
2545 (if activation
2546 (progn
2547 (setq overlay-arrow-position (make-marker)
2548 overlay-arrow-string "=>"
2549 python-pdbtrack-is-tracking-p t)
2550 (set-marker overlay-arrow-position
2551 (line-beginning-position)
2552 (current-buffer)))
2553 (setq overlay-arrow-position nil
2554 python-pdbtrack-is-tracking-p nil)))
2556 (defun python-pdbtrack-track-stack-file (_text)
2557 "Show the file indicated by the pdb stack entry line, in a separate window.
2559 Activity is disabled if the buffer-local variable
2560 `python-pdbtrack-do-tracking-p' is nil.
2562 We depend on the pdb input prompt being a match for
2563 `python-pdbtrack-input-prompt'.
2565 If the traceback target file path is invalid, we look for the
2566 most recently visited python-mode buffer which either has the
2567 name of the current function or class, or which defines the
2568 function or class. This is to provide for scripts not in the
2569 local filesytem (e.g., Zope's 'Script \(Python)', but it's not
2570 Zope specific). If you put a copy of the script in a buffer
2571 named for the script and activate python-mode, then pdbtrack will
2572 find it."
2573 ;; Instead of trying to piece things together from partial text
2574 ;; (which can be almost useless depending on Emacs version), we
2575 ;; monitor to the point where we have the next pdb prompt, and then
2576 ;; check all text from comint-last-input-end to process-mark.
2578 ;; Also, we're very conservative about clearing the overlay arrow,
2579 ;; to minimize residue. This means, for instance, that executing
2580 ;; other pdb commands wipe out the highlight. You can always do a
2581 ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
2583 (let* ((origbuf (current-buffer))
2584 (currproc (get-buffer-process origbuf)))
2586 (if (not (and currproc python-pdbtrack-do-tracking-p))
2587 (python-pdbtrack-overlay-arrow nil)
2589 (let* ((procmark (process-mark currproc))
2590 (block (buffer-substring (max comint-last-input-end
2591 (- procmark
2592 python-pdbtrack-track-range))
2593 procmark))
2594 target target_fname target_lineno target_buffer)
2596 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2597 (python-pdbtrack-overlay-arrow nil)
2599 (setq target (python-pdbtrack-get-source-buffer block))
2601 (if (stringp target)
2602 (progn
2603 (python-pdbtrack-overlay-arrow nil)
2604 (message "pdbtrack: %s" target))
2606 (setq target_lineno (car target)
2607 target_buffer (cadr target)
2608 target_fname (buffer-file-name target_buffer))
2609 (switch-to-buffer-other-window target_buffer)
2610 (goto-char (point-min))
2611 (forward-line (1- target_lineno))
2612 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
2613 (python-pdbtrack-overlay-arrow t)
2614 (pop-to-buffer origbuf t)
2615 ;; in large shell buffers, above stuff may cause point to lag output
2616 (goto-char procmark)
2617 )))))
2620 (defun python-pdbtrack-get-source-buffer (block)
2621 "Return line number and buffer of code indicated by block's traceback text.
2623 We look first to visit the file indicated in the trace.
2625 Failing that, we look for the most recently visited python-mode buffer
2626 with the same name or having the named function.
2628 If we're unable find the source code we return a string describing the
2629 problem."
2631 (if (not (string-match python-pdbtrack-stack-entry-regexp block))
2633 "Traceback cue not found"
2635 (let* ((filename (match-string 1 block))
2636 (lineno (string-to-number (match-string 2 block)))
2637 (funcname (match-string 3 block))
2638 funcbuffer)
2640 (cond ((file-exists-p filename)
2641 (list lineno (find-file-noselect filename)))
2643 ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
2644 (if (string-match "/Script (Python)$" filename)
2645 ;; Add in number of lines for leading '##' comments:
2646 (setq lineno
2647 (+ lineno
2648 (with-current-buffer funcbuffer
2649 (if (equal (point-min)(point-max))
2651 (count-lines
2652 (point-min)
2653 (max (point-min)
2654 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
2655 (buffer-substring
2656 (point-min) (point-max)))
2657 )))))))
2658 (list lineno funcbuffer))
2660 ((= (elt filename 0) ?\<)
2661 (format "(Non-file source: '%s')" filename))
2663 (t (format "Not found: %s(), %s" funcname filename)))
2668 (defun python-pdbtrack-grub-for-buffer (funcname _lineno)
2669 "Find recent Python mode buffer named, or having function named FUNCNAME."
2670 (let ((buffers (buffer-list))
2672 got)
2673 (while (and buffers (not got))
2674 (setq buf (car buffers)
2675 buffers (cdr buffers))
2676 (if (and (with-current-buffer buf
2677 (string= major-mode "python-mode"))
2678 (or (string-match funcname (buffer-name buf))
2679 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
2680 funcname "\\s-*(")
2681 (with-current-buffer buf
2682 (buffer-substring (point-min)
2683 (point-max))))))
2684 (setq got buf)))
2685 got))
2687 ;; Python subprocess utilities and filters
2688 (defun python-execute-file (proc filename)
2689 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
2690 Make that process's buffer visible and force display. Also make
2691 comint believe the user typed this string so that
2692 `kill-output-from-shell' does The Right Thing."
2693 (let ((curbuf (current-buffer))
2694 (procbuf (process-buffer proc))
2695 ; (comint-scroll-to-bottom-on-output t)
2696 (msg (format "## working on region in file %s...\n" filename))
2697 ;; add some comment, so that we can filter it out of history
2698 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
2699 (unwind-protect
2700 (with-current-buffer procbuf
2701 (goto-char (point-max))
2702 (move-marker (process-mark proc) (point))
2703 (funcall (process-filter proc) proc msg))
2704 (set-buffer curbuf))
2705 (process-send-string proc cmd)))
2707 (defun python-pdbtrack-toggle-stack-tracking (arg)
2708 (interactive "P")
2709 (if (not (get-buffer-process (current-buffer)))
2710 (error "No process associated with buffer '%s'" (current-buffer)))
2711 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2712 (if (or (not arg)
2713 (zerop (setq arg (prefix-numeric-value arg))))
2714 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2715 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2716 (message "%sabled Python's pdbtrack"
2717 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2719 (defun turn-on-pdbtrack ()
2720 (interactive)
2721 (python-pdbtrack-toggle-stack-tracking 1))
2723 (defun turn-off-pdbtrack ()
2724 (interactive)
2725 (python-pdbtrack-toggle-stack-tracking 0))
2727 (defun python-sentinel (_proc _msg)
2728 (setq overlay-arrow-position nil))
2730 (provide 'python)
2731 (provide 'python-21)
2733 ;;; python.el ends here