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