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