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