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