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