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