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