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