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