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