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