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