1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
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-syntax-propertize-function
170 ;; Make outer chars of matching triple-quote sequences into generic
171 ;; string delimiters. Fixme: Is there a better way?
172 ;; First avoid a sequence preceded by an odd number of backslashes.
173 (syntax-propertize-rules
174 (;; (rx (not (any ?\\))
175 ;; ?\\ (* (and ?\\ ?\\))
176 ;; (group (syntax string-quote))
178 ;; (group (backref 1)))
179 ;; ¡Backrefs don't work in syntax-propertize-rules!
180 "[^\\]\\\\\\(\\\\\\\\\\)*\\(?:''\\('\\)\\|\"\"\\(?2:\"\\)\\)"
182 (;; (rx (optional (group (any "uUrR"))) ; prefix gets syntax property
183 ;; (optional (any "rR")) ; possible second prefix
184 ;; (group (syntax string-quote)) ; maybe gets property
185 ;; (backref 2) ; per first quote
186 ;; (group (backref 2))) ; maybe gets property
187 ;; ¡Backrefs don't work in syntax-propertize-rules!
188 "\\([RUru]\\)?[Rr]?\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)"
189 (3 (ignore (python-quote-syntax))))
190 ;; This doesn't really help.
191 ;;((rx (and ?\\ (group ?\n))) (1 " "))
194 (defun python-quote-syntax ()
195 "Put `syntax-table' property correctly on triple quote.
196 Used for syntactic keywords. N is the match number (1, 2 or 3)."
197 ;; Given a triple quote, we have to check the context to know
198 ;; whether this is an opening or closing triple or whether it's
199 ;; quoted anyhow, and should be ignored. (For that we need to do
200 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
201 ;; to use it here despite initial worries.) We also have to sort
202 ;; out a possible prefix -- well, we don't _have_ to, but I think it
203 ;; should be treated as part of the string.
206 ;; ur"""ar""" x='"' # """
209 ;; x '"""' x """ \"""" x
211 (goto-char (match-beginning 0))
212 (let ((syntax (save-match-data (syntax-ppss))))
214 ((eq t
(nth 3 syntax
)) ; after unclosed fence
215 ;; Consider property for the last char if in a fenced string.
216 (goto-char (nth 8 syntax
)) ; fence position
217 (skip-chars-forward "uUrR") ; skip any prefix
218 ;; Is it a matching sequence?
219 (if (eq (char-after) (char-after (match-beginning 2)))
220 (put-text-property (match-beginning 3) (match-end 3)
221 'syntax-table
(string-to-syntax "|"))))
223 ;; Consider property for initial char, accounting for prefixes.
224 (put-text-property (match-beginning 1) (match-end 1)
225 'syntax-table
(string-to-syntax "|")))
227 ;; Consider property for initial char, accounting for prefixes.
228 (put-text-property (match-beginning 2) (match-end 2)
229 'syntax-table
(string-to-syntax "|"))))
232 ;; This isn't currently in `font-lock-defaults' as probably not worth
233 ;; it -- we basically only mess with a few normally-symbol characters.
235 ;; (defun python-font-lock-syntactic-face-function (state)
236 ;; "`font-lock-syntactic-face-function' for Python mode.
237 ;; Returns the string or comment face as usual, with side effect of putting
238 ;; a `syntax-table' property on the inside of the string or comment which is
239 ;; the standard syntax table."
242 ;; (goto-char (nth 8 state))
243 ;; (condition-case nil
246 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
247 ;; 'syntax-table (standard-syntax-table))
248 ;; 'font-lock-string-face)
249 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
250 ;; 'syntax-table (standard-syntax-table))
251 ;; 'font-lock-comment-face))
253 ;;;; Keymap and syntax
255 (defvar python-mode-map
256 (let ((map (make-sparse-keymap)))
257 ;; Mostly taken from python-mode.el.
258 (define-key map
":" 'python-electric-colon
)
259 (define-key map
"\177" 'python-backspace
)
260 (define-key map
"\C-c<" 'python-shift-left
)
261 (define-key map
"\C-c>" 'python-shift-right
)
262 (define-key map
"\C-c\C-k" 'python-mark-block
)
263 (define-key map
"\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking
)
264 (define-key map
"\C-c\C-n" 'python-next-statement
)
265 (define-key map
"\C-c\C-p" 'python-previous-statement
)
266 (define-key map
"\C-c\C-u" 'python-beginning-of-block
)
267 (define-key map
"\C-c\C-f" 'python-describe-symbol
)
268 (define-key map
"\C-c\C-w" 'python-check
)
269 (define-key map
"\C-c\C-v" 'python-check
) ; a la sgml-mode
270 (define-key map
"\C-c\C-s" 'python-send-string
)
271 (define-key map
[?\C-\M-x
] 'python-send-defun
)
272 (define-key map
"\C-c\C-r" 'python-send-region
)
273 (define-key map
"\C-c\M-r" 'python-send-region-and-go
)
274 (define-key map
"\C-c\C-c" 'python-send-buffer
)
275 (define-key map
"\C-c\C-z" 'python-switch-to-python
)
276 (define-key map
"\C-c\C-m" 'python-load-file
)
277 (define-key map
"\C-c\C-l" 'python-load-file
) ; a la cmuscheme
278 (substitute-key-definition 'complete-symbol
'completion-at-point
280 (define-key map
"\C-c\C-i" 'python-find-imports
)
281 (define-key map
"\C-c\C-t" 'python-expand-template
)
282 (easy-menu-define python-menu map
"Python Mode menu"
284 :help
"Python-specific Features"
285 ["Shift region left" python-shift-left
:active mark-active
286 :help
"Shift by a single indentation step"]
287 ["Shift region right" python-shift-right
:active mark-active
288 :help
"Shift by a single indentation step"]
290 ["Mark block" python-mark-block
291 :help
"Mark innermost block around point"]
292 ["Mark def/class" mark-defun
293 :help
"Mark innermost definition around point"]
295 ["Start of block" python-beginning-of-block
296 :help
"Go to start of innermost definition around point"]
297 ["End of block" python-end-of-block
298 :help
"Go to end of innermost definition around point"]
299 ["Start of def/class" beginning-of-defun
300 :help
"Go to start of innermost definition around point"]
301 ["End of def/class" end-of-defun
302 :help
"Go to end of innermost definition around point"]
305 :help
"Expand templates for compound statements"
306 :filter
(lambda (&rest junk
)
307 (abbrev-table-menu python-mode-abbrev-table
)))
309 ["Start interpreter" python-shell
310 :help
"Run `inferior' Python in separate buffer"]
311 ["Import/reload file" python-load-file
312 :help
"Load into inferior Python session"]
313 ["Eval buffer" python-send-buffer
314 :help
"Evaluate buffer en bloc in inferior Python session"]
315 ["Eval region" python-send-region
:active mark-active
316 :help
"Evaluate region en bloc in inferior Python session"]
317 ["Eval def/class" python-send-defun
318 :help
"Evaluate current definition in inferior Python session"]
319 ["Switch to interpreter" python-switch-to-python
320 :help
"Switch to inferior Python buffer"]
321 ["Set default process" python-set-proc
322 :help
"Make buffer's inferior process the default"
323 :active
(buffer-live-p python-buffer
)]
324 ["Check file" python-check
:help
"Run pychecker"]
325 ["Debugger" pdb
:help
"Run pdb under GUD"]
327 ["Help on symbol" python-describe-symbol
328 :help
"Use pydoc on symbol at point"]
329 ["Complete symbol" completion-at-point
330 :help
"Complete (qualified) symbol before point"]
331 ["Find function" python-find-function
332 :help
"Try to find source definition of function at point"]
333 ["Update imports" python-find-imports
334 :help
"Update list of top-level imports for completion"]))
336 ;; Fixme: add toolbar stuff for useful things like symbol help, send
337 ;; region, at least. (Shouldn't be specific to Python, obviously.)
338 ;; eric has items including: (un)indent, (un)comment, restart script,
339 ;; run script, debug script; also things for profiling, unit testing.
341 (defvar python-shell-map
342 (let ((map (copy-keymap comint-mode-map
)))
343 (define-key map
[tab] 'tab-to-tab-stop)
344 (define-key map "\C-c-" 'py-up-exception)
345 (define-key map "\C-c=" 'py-down-exception)
347 "Keymap used in *Python* shell buffers.")
349 (defvar python-mode-syntax-table
350 (let ((table (make-syntax-table)))
351 ;; Give punctuation syntax to ASCII that normally has symbol
352 ;; syntax or has word syntax and isn't a letter.
353 (let ((symbol (string-to-syntax "_"))
354 (sst (standard-syntax-table)))
357 (if (equal symbol (aref sst i))
358 (modify-syntax-entry i "." table)))))
359 (modify-syntax-entry ?$ "." table)
360 (modify-syntax-entry ?% "." table)
362 (modify-syntax-entry ?# "<" table)
363 (modify-syntax-entry ?\n ">" table)
364 (modify-syntax-entry ?' "\"" table)
365 (modify-syntax-entry ?` "$" table)
370 (defsubst python-in-string/comment ()
371 "Return non-nil if point is in a Python literal (a comment or string)."
372 ;; We don't need to save the match data.
373 (nth 8 (syntax-ppss)))
375 (defconst python-space-backslash-table
376 (let ((table (copy-syntax-table python-mode-syntax-table)))
377 (modify-syntax-entry ?\\ " " table)
379 "`python-mode-syntax-table' with backslash given whitespace syntax.")
381 (defun python-skip-comments/blanks (&optional backward)
382 "Skip comments and blank lines.
383 BACKWARD non-nil means go backwards, otherwise go forwards.
384 Backslash is treated as whitespace so that continued blank lines
385 are skipped. Doesn't move out of comments -- should be outside
387 (let ((arg (if backward
388 ;; If we're in a comment (including on the trailing
389 ;; newline), forward-comment doesn't move backwards out
390 ;; of it. Don't set the syntax table round this bit!
391 (let ((syntax (syntax-ppss)))
393 (goto-char (nth 8 syntax)))
396 (with-syntax-table python-space-backslash-table
397 (forward-comment arg))))
399 (defun python-backslash-continuation-line-p ()
400 "Non-nil if preceding line ends with backslash that is not in a comment."
401 (and (eq ?\\ (char-before (line-end-position 0)))
402 (not (syntax-ppss-context (syntax-ppss)))))
404 (defun python-continuation-line-p ()
405 "Return non-nil if current line continues a previous one.
406 The criteria are that the previous line ends in a backslash outside
407 comments and strings, or that point is within brackets/parens."
408 (or (python-backslash-continuation-line-p)
409 (let ((depth (syntax-ppss-depth
410 (save-excursion ; syntax-ppss with arg changes point
411 (syntax-ppss (line-beginning-position))))))
413 (if (< depth 0) ; Unbalanced brackets -- act locally
416 (progn (backward-up-list) t) ; actually within brackets
419 (defun python-comment-line-p ()
420 "Return non-nil if and only if current line has only a comment."
423 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
424 (back-to-indentation)
425 (looking-at (rx (or (syntax comment-start) line-end))))))
427 (defun python-blank-line-p ()
428 "Return non-nil if and only if current line is blank."
431 (looking-at "\\s-*$")))
433 (defun python-beginning-of-string ()
434 "Go to beginning of string around point.
435 Do nothing if not in string."
436 (let ((state (syntax-ppss)))
437 (when (eq 'string (syntax-ppss-context state))
438 (goto-char (nth 8 state)))))
440 (defun python-open-block-statement-p (&optional bos)
441 "Return non-nil if statement at point opens a block.
442 BOS non-nil means point is known to be at beginning of statement."
444 (unless bos (python-beginning-of-statement))
445 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
446 "class" "try" "except" "finally" "with")
449 (defun python-close-block-statement-p (&optional bos)
450 "Return non-nil if current line is a statement closing a block.
451 BOS non-nil means point is at beginning of statement.
452 The criteria are that the line isn't a comment or in string and
453 starts with keyword `raise', `break', `continue' or `pass'."
455 (unless bos (python-beginning-of-statement))
456 (back-to-indentation)
457 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
460 (defun python-outdent-p ()
461 "Return non-nil if current line should outdent a level."
463 (back-to-indentation)
464 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
466 (not (python-in-string/comment))
467 ;; Ensure there's a previous statement and move to it.
468 (zerop (python-previous-statement))
469 (not (python-close-block-statement-p t))
471 (not (python-open-block-statement-p)))))
475 (defcustom python-indent 4
476 "Number of columns for a unit of indentation in Python mode.
477 See also `\\[python-guess-indent]'"
480 (put 'python-indent 'safe-local-variable 'integerp)
482 (defcustom python-guess-indent t
483 "Non-nil means Python mode guesses `python-indent' for the buffer."
487 (defcustom python-indent-string-contents t
488 "Non-nil means indent contents of multi-line strings together.
489 This means indent them the same as the preceding non-blank line.
490 Otherwise preserve their indentation.
492 This only applies to `doc' strings, i.e. those that form statements;
493 the indentation is preserved in others."
494 :type '(choice (const :tag "Align with preceding" t)
495 (const :tag "Preserve indentation" nil))
498 (defcustom python-honour-comment-indentation nil
499 "Non-nil means indent relative to preceding comment line.
500 Only do this for comments where the leading comment character is
501 followed by space. This doesn't apply to comment lines, which
502 are always indented in lines with preceding comments."
506 (defcustom python-continuation-offset 4
507 "Number of columns of additional indentation for continuation lines.
508 Continuation lines follow a backslash-terminated line starting a
514 (defcustom python-default-interpreter 'cpython
515 "*Which Python interpreter is used by default.
516 The value for this variable can be either `cpython' or `jpython'.
518 When the value is `cpython', the variables `python-python-command' and
519 `python-python-command-args' are consulted to determine the interpreter
520 and arguments to use.
522 When the value is `jpython', the variables `python-jpython-command' and
523 `python-jpython-command-args' are consulted to determine the interpreter
524 and arguments to use.
526 Note that this variable is consulted only the first time that a Python
527 mode buffer is visited during an Emacs session. After that, use
528 \\[python-toggle-shells] to change the interpreter shell."
529 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
530 (const :tag "JPython" jpython))
533 (defcustom python-python-command-args '("-i")
534 "*List of string arguments to be used when starting a Python shell."
535 :type '(repeat string)
538 (defcustom python-jython-command-args '("-i")
539 "*List of string arguments to be used when starting a Jython shell."
540 :type '(repeat string)
542 :tag "JPython Command Args")
544 ;; for toggling between CPython and JPython
545 (defvar python-which-shell nil)
546 (defvar python-which-args python-python-command-args)
547 (defvar python-which-bufname "Python")
548 (make-variable-buffer-local 'python-which-shell)
549 (make-variable-buffer-local 'python-which-args)
550 (make-variable-buffer-local 'python-which-bufname)
552 (defcustom python-pdbtrack-do-tracking-p t
553 "*Controls whether the pdbtrack feature is enabled or not.
555 When non-nil, pdbtrack is enabled in all comint-based buffers,
556 e.g. shell interaction buffers and the *Python* buffer.
558 When using pdb to debug a Python program, pdbtrack notices the
559 pdb prompt and presents the line in the source file where the
560 program is stopped in a pop-up buffer. It's similar to what
561 gud-mode does for debugging C programs with gdb, but without
562 having to restart the program."
565 (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
567 (defcustom python-pdbtrack-minor-mode-string " PDB"
568 "*Minor-mode sign to be displayed when pdbtrack is active."
572 ;; Add a designator to the minor mode strings
573 (or (assq 'python-pdbtrack-is-tracking-p minor-mode-alist)
574 (push '(python-pdbtrack-is-tracking-p python-pdbtrack-minor-mode-string)
577 ;; Bind python-file-queue before installing the kill-emacs-hook.
578 (defvar python-file-queue nil
579 "Queue of Python temp files awaiting execution.
580 Currently-active file is at the head of the list.")
582 (defcustom python-shell-prompt-alist
583 '(("ipython" . "^In \\[[0-9]+\\]: *")
585 "Alist of Python input prompts.
586 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
587 the value of `python-python-command' for the python process and
588 REGEXP is a regular expression matching the Python prompt.
589 PROGRAM can also be t, which specifies the default when no other
590 element matches `python-python-command'."
595 (defcustom python-shell-continuation-prompt-alist
596 '(("ipython" . "^ [.][.][.]+: *")
598 "Alist of Python continued-line prompts.
599 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
600 the value of `python-python-command' for the python process and
601 REGEXP is a regular expression matching the Python prompt for
603 PROGRAM can also be t, which specifies the default when no other
604 element matches `python-python-command'."
609 (defvar python-pdbtrack-is-tracking-p nil)
611 (defconst python-pdbtrack-stack-entry-regexp
612 "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
613 "Regular expression pdbtrack uses to find a stack trace entry.")
615 (defconst python-pdbtrack-input-prompt "\n[(<]*[Pp]db[>)]+ "
616 "Regular expression pdbtrack uses to recognize a pdb prompt.")
618 (defconst python-pdbtrack-track-range 10000
619 "Max number of characters from end of buffer to search for stack entry.")
621 (defun python-guess-indent ()
622 "Guess step for indentation of current buffer.
623 Set `python-indent' locally to the value guessed."
628 (goto-char (point-min))
630 (while (and (not done) (not (eobp)))
631 (when (and (re-search-forward (rx ?: (0+ space)
632 (or (syntax comment-start)
635 (python-open-block-statement-p))
637 (python-beginning-of-statement)
638 (let ((initial (current-indentation)))
639 (if (zerop (python-next-statement))
640 (setq indent (- (current-indentation) initial)))
641 (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
644 (when (/= indent (default-value 'python-indent))
645 (set (make-local-variable 'python-indent) indent)
646 (unless (= tab-width python-indent)
647 (setq indent-tabs-mode nil)))
650 ;; Alist of possible indentations and start of statement they would
651 ;; close. Used in indentation cycling (below).
652 (defvar python-indent-list nil
654 ;; Length of the above
655 (defvar python-indent-list-length nil
657 ;; Current index into the alist.
658 (defvar python-indent-index nil
661 (defun python-calculate-indentation ()
662 "Calculate Python indentation for line at point."
663 (setq python-indent-list nil
664 python-indent-list-length 1)
667 (let ((syntax (syntax-ppss))
670 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
671 (if (not python-indent-string-contents)
672 (current-indentation)
673 ;; Only respect `python-indent-string-contents' in doc
674 ;; strings (defined as those which form statements).
675 (if (not (save-excursion
676 (python-beginning-of-statement)
677 (looking-at (rx (or (syntax string-delimiter)
678 (syntax string-quote))))))
679 (current-indentation)
680 ;; Find indentation of preceding non-blank line within string.
681 (setq start (nth 8 syntax))
683 (while (and (< start (point)) (looking-at "\\s-*$"))
685 (current-indentation))))
686 ((python-continuation-line-p) ; after backslash, or bracketed
687 (let ((point (point))
688 (open-start (cadr syntax))
689 (backslash (python-backslash-continuation-line-p))
690 (colon (eq ?: (char-before (1- (line-beginning-position))))))
692 ;; Inside bracketed expression.
694 (goto-char (1+ open-start))
695 ;; Look for first item in list (preceding point) and
696 ;; align with it, if found.
697 (if (with-syntax-table python-space-backslash-table
698 (let ((parse-sexp-ignore-comments t))
700 (progn (forward-sexp)
704 ;; Extra level if we're backslash-continued or
706 (if (or backslash colon)
707 (+ python-indent (current-column))
709 ;; Otherwise indent relative to statement start, one
710 ;; level per bracketing level.
711 (goto-char (1+ open-start))
712 (python-beginning-of-statement)
713 (+ (current-indentation) (* (car syntax) python-indent))))
714 ;; Otherwise backslash-continued.
716 (if (python-continuation-line-p)
717 ;; We're past first continuation line. Align with
719 (current-indentation)
720 ;; First continuation line. Indent one step, with an
721 ;; extra one if statement opens a block.
722 (python-beginning-of-statement)
723 (+ (current-indentation) python-continuation-offset
724 (if (python-open-block-statement-p t)
728 ;; Fixme: Like python-mode.el; not convinced by this.
729 ((looking-at (rx (0+ space) (syntax comment-start)
730 (not (any " \t\n")))) ; non-indentable comment
731 (current-indentation))
732 ((and python-honour-comment-indentation
733 ;; Back over whitespace, newlines, non-indentable comments.
735 (while (cond ((bobp) nil)
736 ((not (forward-comment -1))
737 nil) ; not at comment start
738 ;; Now at start of comment -- trailing one?
739 ((/= (current-column) (current-indentation))
741 ;; Indentable comment, like python-mode.el?
742 ((and (looking-at (rx (syntax comment-start)
743 (or space line-end)))
744 (/= 0 (current-column)))
745 (throw 'done (current-column)))
746 ;; Else skip it (loop).
749 (python-indentation-levels)
750 ;; Prefer to indent comments with an immediately-following
755 (when (and (> python-indent-list-length 1)
756 (python-comment-line-p))
758 (unless (python-comment-line-p)
759 (let ((elt (assq (current-indentation) python-indent-list)))
760 (setq python-indent-list
761 (nconc (delete elt python-indent-list)
763 (caar (last python-indent-list)))))))
765 ;;;; Cycling through the possible indentations with successive TABs.
767 ;; These don't need to be buffer-local since they're only relevant
770 (defun python-initial-text ()
771 "Text of line following indentation and ignoring any trailing comment."
773 (buffer-substring (progn
774 (back-to-indentation)
781 (defconst python-block-pairs
782 '(("else" "if" "elif" "while" "for" "try" "except")
784 ("except" "try" "except")
785 ("finally" "else" "try" "except"))
786 "Alist of keyword matches.
787 The car of an element is a keyword introducing a statement which
788 can close a block opened by a keyword in the cdr.")
790 (defun python-first-word ()
791 "Return first word (actually symbol) on the line."
793 (back-to-indentation)
796 (defun python-indentation-levels ()
797 "Return a list of possible indentations for this line.
798 It is assumed not to be a continuation line or in a multi-line string.
799 Includes the default indentation and those which would close all
800 enclosing blocks. Elements of the list are actually pairs:
801 \(INDENTATION . TEXT), where TEXT is the initial text of the
802 corresponding block opening (or nil)."
806 ;; Only one possibility immediately following a block open
807 ;; statement, assuming it doesn't have a `suite' on the same line.
809 ((save-excursion (and (python-previous-statement)
810 (python-open-block-statement-p t)
811 (setq indent (current-indentation))
812 ;; Check we don't have something like:
814 (if (progn (python-end-of-statement)
815 (python-skip-comments/blanks t)
816 (eq ?: (char-before)))
817 (setq indent (+ python-indent indent)))))
818 (push (cons indent initial) levels))
819 ;; Only one possibility for comment line immediately following
822 (when (python-comment-line-p)
824 (if (python-comment-line-p)
825 (push (cons (current-indentation) initial) levels)))))
826 ;; Fixme: Maybe have a case here which indents (only) first
827 ;; line after a lambda.
829 (let ((start (car (assoc (python-first-word) python-block-pairs))))
830 (python-previous-statement)
831 ;; Is this a valid indentation for the line of interest?
832 (unless (or (if start ; potentially only outdentable
833 ;; Check for things like:
836 ;; where the second line need not be outdented.
837 (not (member (python-first-word)
839 python-block-pairs)))))
840 ;; Not sensible to indent to the same level as
841 ;; previous `return' &c.
842 (python-close-block-statement-p))
843 (push (cons (current-indentation) (python-initial-text))
845 (while (python-beginning-of-block)
846 (when (or (not start)
847 (member (python-first-word)
848 (cdr (assoc start python-block-pairs))))
849 (push (cons (current-indentation) (python-initial-text))
851 (prog1 (or levels (setq levels '((0 . ""))))
852 (setq python-indent-list levels
853 python-indent-list-length (length python-indent-list))))))
855 ;; This is basically what `python-indent-line' would be if we didn't
857 (defun python-indent-line-1 (&optional leave)
858 "Subroutine of `python-indent-line'.
859 Does non-repeated indentation. LEAVE non-nil means leave
860 indentation if it is valid, i.e. one of the positions returned by
861 `python-calculate-indentation'."
862 (let ((target (python-calculate-indentation))
863 (pos (- (point-max) (point))))
864 (if (or (= target (current-indentation))
865 ;; Maybe keep a valid indentation.
866 (and leave python-indent-list
867 (assq (current-indentation) python-indent-list)))
868 (if (< (current-column) (current-indentation))
869 (back-to-indentation))
871 (delete-horizontal-space)
873 (if (> (- (point-max) pos) (point))
874 (goto-char (- (point-max) pos))))))
876 (defun python-indent-line ()
877 "Indent current line as Python code.
878 When invoked via `indent-for-tab-command', cycle through possible
879 indentations for current line. The cycle is broken by a command
880 different from `indent-for-tab-command', i.e. successive TABs do
883 (if (and (eq this-command 'indent-for-tab-command)
884 (eq last-command this-command))
885 (if (= 1 python-indent-list-length)
886 (message "Sole indentation")
887 (progn (setq python-indent-index
888 (% (1+ python-indent-index) python-indent-list-length))
890 (delete-horizontal-space)
891 (indent-to (car (nth python-indent-index python-indent-list)))
892 (if (python-block-end-p)
893 (let ((text (cdr (nth python-indent-index
894 python-indent-list))))
896 (message "Closes: %s" text))))))
897 (python-indent-line-1)
898 (setq python-indent-index (1- python-indent-list-length))))
900 (defun python-indent-region (start end)
901 "`indent-region-function' for Python.
902 Leaves validly-indented lines alone, i.e. doesn't indent to
903 another valid position."
906 (setq end (point-marker))
908 (or (bolp) (forward-line 1))
909 (while (< (point) end)
910 (or (and (bolp) (eolp))
911 (python-indent-line-1 t))
913 (move-marker end nil)))
915 (defun python-block-end-p ()
916 "Non-nil if this is a line in a statement closing a block,
917 or a blank line indented to where it would close a block."
918 (and (not (python-comment-line-p))
919 (or (python-close-block-statement-p t)
920 (< (current-indentation)
922 (python-previous-statement)
923 (current-indentation))))))
927 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
928 ;; block, statement, depending on context.
930 (defun python-beginning-of-defun ()
931 "`beginning-of-defun-function' for Python.
932 Finds beginning of innermost nested class or method definition.
933 Returns the name of the definition found at the end, or nil if
934 reached start of buffer."
935 (let ((ci (current-indentation))
936 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
937 (group (1+ (or word (syntax symbol))))))
938 found lep) ;; def-line
939 (if (python-comment-line-p)
940 (setq ci most-positive-fixnum))
941 (while (and (not (bobp)) (not found))
942 ;; Treat bol at beginning of function as outside function so
943 ;; that successive C-M-a makes progress backwards.
944 ;;(setq def-line (looking-at def-re))
945 (unless (bolp) (end-of-line))
946 (setq lep (line-end-position))
947 (if (and (re-search-backward def-re nil 'move)
948 ;; Must be less indented or matching top level, or
949 ;; equally indented if we started on a definition line.
950 (let ((in (current-indentation)))
951 (or (and (zerop ci) (zerop in))
952 (= lep (line-end-position)) ; on initial line
953 ;; Not sure why it was like this -- fails in case of
954 ;; last internal function followed by first
955 ;; non-def statement of the main body.
956 ;; (and def-line (= in ci))
959 (not (python-in-string/comment)))
963 (defun python-end-of-defun ()
964 "`end-of-defun-function' for Python.
965 Finds end of innermost nested class or method definition."
967 (pattern (rx line-start (0+ space) (or "def" "class") space)))
968 ;; Go to start of current block and check whether it's at top
969 ;; level. If it is, and not a block start, look forward for
970 ;; definition statement.
971 (when (python-comment-line-p)
973 (forward-comment most-positive-fixnum))
974 (if (not (python-open-block-statement-p))
975 (python-beginning-of-block))
976 (if (zerop (current-indentation))
977 (unless (python-open-block-statement-p)
978 (while (and (re-search-forward pattern nil 'move)
979 (python-in-string/comment))) ; just loop
981 (beginning-of-line)))
982 ;; Don't move before top-level statement that would end defun.
984 (python-beginning-of-defun))
985 ;; If we got to the start of buffer, look forward for
986 ;; definition statement.
987 (if (and (bobp) (not (looking-at "def\\|class")))
988 (while (and (not (eobp))
989 (re-search-forward pattern nil 'move)
990 (python-in-string/comment)))) ; just loop
991 ;; We're at a definition statement (or end-of-buffer).
993 (python-end-of-block)
994 ;; Count trailing space in defun (but not trailing comments).
995 (skip-syntax-forward " >")
996 (unless (eobp) ; e.g. missing final newline
997 (beginning-of-line)))
998 ;; Catch pathological cases like this, where the beginning-of-defun
999 ;; skips to a definition we're not in:
1006 (if (< (point) orig)
1007 (goto-char (point-max)))))
1009 (defun python-beginning-of-statement ()
1010 "Go to start of current statement.
1011 Accounts for continuation lines, multi-line strings, and
1012 multi-line bracketed expressions."
1014 (python-beginning-of-string)
1016 (while (and (python-continuation-line-p)
1021 (if (python-backslash-continuation-line-p)
1024 (while (python-backslash-continuation-line-p)
1026 (python-beginning-of-string)
1028 (setq point (point))))
1029 (back-to-indentation))
1031 (defun python-skip-out (&optional forward syntax)
1032 "Skip out of any nested brackets.
1033 Skip forward if FORWARD is non-nil, else backward.
1034 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
1035 Return non-nil if and only if skipping was done."
1036 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
1037 (forward (if forward -1 1)))
1038 (unless (zerop depth)
1040 ;; Skip forward out of nested brackets.
1041 (condition-case () ; beware invalid syntax
1042 (progn (backward-up-list (* forward depth)) t)
1044 ;; Invalid syntax (too many closed brackets).
1045 ;; Skip out of as many as possible.
1047 (while (condition-case ()
1048 (progn (backward-up-list forward)
1053 (defun python-end-of-statement ()
1054 "Go to the end of the current statement and return point.
1055 Usually this is the start of the next line, but if this is a
1056 multi-line statement we need to skip over the continuation lines.
1057 On a comment line, go to end of line."
1059 (while (let (comment)
1060 ;; Move past any enclosing strings and sexps, or stop if
1061 ;; we're in a comment.
1062 (while (let ((s (syntax-ppss)))
1063 (cond ((eq 'comment (syntax-ppss-context s))
1066 ((eq 'string (syntax-ppss-context s))
1067 ;; Go to start of string and skip it.
1068 (let ((pos (point)))
1069 (goto-char (nth 8 s))
1070 (condition-case () ; beware invalid syntax
1071 (progn (forward-sexp) t)
1072 ;; If there's a mismatched string, make sure
1073 ;; we still overall move *forward*.
1074 (error (goto-char pos) (end-of-line)))))
1075 ((python-skip-out t s))))
1078 (eq ?\\ (char-before)))) ; Line continued?
1079 (end-of-line 2)) ; Try next line.
1082 (defun python-previous-statement (&optional count)
1083 "Go to start of previous statement.
1084 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
1085 Return count of statements left to move."
1087 (unless count (setq count 1))
1089 (python-next-statement (- count))
1090 (python-beginning-of-statement)
1091 (while (and (> count 0) (not (bobp)))
1092 (python-skip-comments/blanks t)
1093 (python-beginning-of-statement)
1094 (unless (bobp) (setq count (1- count))))
1097 (defun python-next-statement (&optional count)
1098 "Go to start of next statement.
1099 With argument COUNT, do it COUNT times. Stop at end of buffer.
1100 Return count of statements left to move."
1102 (unless count (setq count 1))
1104 (python-previous-statement (- count))
1107 (while (and (> count 0) (not (eobp)) (not bogus))
1108 (python-end-of-statement)
1109 (python-skip-comments/blanks)
1110 (if (eq 'string (syntax-ppss-context (syntax-ppss)))
1113 (setq count (1- count))))))
1116 (defun python-beginning-of-block (&optional arg)
1117 "Go to start of current block.
1118 With numeric arg, do it that many times. If ARG is negative, call
1119 `python-end-of-block' instead.
1120 If point is on the first line of a block, use its outer block.
1121 If current statement is in column zero, don't move and return nil.
1122 Otherwise return non-nil."
1124 (unless arg (setq arg 1))
1127 ((< arg 0) (python-end-of-block (- arg)))
1129 (let ((point (point)))
1130 (if (or (python-comment-line-p)
1131 (python-blank-line-p))
1132 (python-skip-comments/blanks t))
1133 (python-beginning-of-statement)
1134 (let ((ci (current-indentation)))
1136 (not (goto-char point)) ; return nil
1137 ;; Look upwards for less indented statement.
1139 ;;; This is slower than the below.
1140 ;;; (while (zerop (python-previous-statement))
1141 ;;; (when (and (< (current-indentation) ci)
1142 ;;; (python-open-block-statement-p t))
1143 ;;; (beginning-of-line)
1144 ;;; (throw 'done t)))
1145 (while (and (zerop (forward-line -1)))
1146 (when (and (< (current-indentation) ci)
1147 (not (python-comment-line-p))
1148 ;; Move to beginning to save effort in case
1149 ;; this is in string.
1150 (progn (python-beginning-of-statement) t)
1151 (python-open-block-statement-p t))
1154 (not (goto-char point))) ; Failed -- return nil
1155 (python-beginning-of-block (1- arg)))))))))
1157 (defun python-end-of-block (&optional arg)
1158 "Go to end of current block.
1159 With numeric arg, do it that many times. If ARG is negative,
1160 call `python-beginning-of-block' instead.
1161 If current statement is in column zero and doesn't open a block,
1162 don't move and return nil. Otherwise return t."
1164 (unless arg (setq arg 1))
1166 (python-beginning-of-block (- arg))
1167 (while (and (> arg 0)
1168 (let* ((point (point))
1169 (_ (if (python-comment-line-p)
1170 (python-skip-comments/blanks t)))
1171 (ci (current-indentation))
1172 (open (python-open-block-statement-p)))
1173 (if (and (zerop ci) (not open))
1174 (not (goto-char point))
1176 (while (zerop (python-next-statement))
1177 (when (or (and open (<= (current-indentation) ci))
1178 (< (current-indentation) ci))
1179 (python-skip-comments/blanks t)
1180 (beginning-of-line 2)
1181 (throw 'done t)))))))
1182 (setq arg (1- arg)))
1185 (defvar python-which-func-length-limit 40
1186 "Non-strict length limit for `python-which-func' output.")
1188 (defun python-which-func ()
1189 (let ((function-name (python-current-defun python-which-func-length-limit)))
1190 (set-text-properties 0 (length function-name) nil function-name)
1196 ;; For possibily speeding this up, here's the top of the ELP profile
1197 ;; for rescanning pydoc.py (2.2k lines, 90kb):
1198 ;; Function Name Call Count Elapsed Time Average Time
1199 ;; ==================================== ========== ============= ============
1200 ;; python-imenu-create-index 156 2.430906 0.0155827307
1201 ;; python-end-of-defun 155 1.2718260000 0.0082053290
1202 ;; python-end-of-block 155 1.1898689999 0.0076765741
1203 ;; python-next-statement 2970 1.024717 0.0003450225
1204 ;; python-end-of-statement 2970 0.4332190000 0.0001458649
1205 ;; python-beginning-of-defun 265 0.0918479999 0.0003465962
1206 ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05
1208 (defvar python-recursing)
1209 (defun python-imenu-create-index ()
1210 "`imenu-create-index-function' for Python.
1212 Makes nested Imenu menus from nested `class' and `def' statements.
1213 The nested menus are headed by an item referencing the outer
1214 definition; it has a space prepended to the name so that it sorts
1215 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1217 (unless (boundp 'python-recursing) ; dynamically bound below
1218 ;; Normal call from Imenu.
1219 (goto-char (point-min))
1220 ;; Without this, we can get an infloop if the buffer isn't all
1221 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1222 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1223 ;; what's going on, but it must be something to do with timers in
1225 ;; This can't be right, especially not when jit-lock is not used. --Stef
1226 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1227 ;; (font-lock-fontify-region (point-min) (point-max)))
1229 (let (index-alist) ; accumulated value to return
1230 (while (re-search-forward
1231 (rx line-start (0+ space) ; leading space
1232 (or (group "def") (group "class")) ; type
1233 (1+ space) (group (1+ (or word ?_)))) ; name
1235 (unless (python-in-string/comment)
1236 (let ((pos (match-beginning 0))
1237 (name (match-string-no-properties 3)))
1238 (if (match-beginning 2) ; def or class?
1239 (setq name (concat "class " name)))
1242 (let* ((python-recursing t)
1243 (sublist (python-imenu-create-index)))
1245 (progn (push (cons (concat " " name) pos) sublist)
1246 (push (cons name sublist) index-alist))
1247 (push (cons name pos) index-alist)))))))
1248 (unless (boundp 'python-recursing)
1249 ;; Look for module variables.
1251 (goto-char (point-min))
1252 (while (re-search-forward
1253 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1255 (unless (python-in-string/comment)
1256 (push (cons (match-string 1) (match-beginning 1))
1258 (setq index-alist (nreverse index-alist))
1260 (push (cons "Module variables"
1265 ;;;; `Electric' commands.
1267 (defun python-electric-colon (arg)
1268 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1269 With numeric ARG, just insert that many colons. With \\[universal-argument],
1270 just insert a single colon."
1272 (self-insert-command (if (not (integerp arg)) 1 arg))
1276 (not (python-in-string/comment))
1277 (> (current-indentation) (python-calculate-indentation))
1278 (python-indent-line))) ; OK, do it
1279 (put 'python-electric-colon 'delete-selection t)
1281 (defun python-backspace (arg)
1282 "Maybe delete a level of indentation on the current line.
1283 Do so if point is at the end of the line's indentation outside
1284 strings and comments.
1285 Otherwise just call `backward-delete-char-untabify'.
1288 (if (or (/= (current-indentation) (current-column))
1290 (python-continuation-line-p)
1291 (python-in-string/comment))
1292 (backward-delete-char-untabify arg)
1293 ;; Look for the largest valid indentation which is smaller than
1294 ;; the current indentation.
1296 (ci (current-indentation))
1297 (indents (python-indentation-levels))
1301 (setq indent (max indent (car x)))))
1302 (setq initial (cdr (assq indent indents)))
1303 (if (> (length initial) 0)
1304 (message "Closes %s" initial))
1305 (delete-horizontal-space)
1306 (indent-to indent))))
1307 (put 'python-backspace 'delete-selection 'supersede)
1311 (defcustom python-check-command "pychecker --stdlib"
1312 "Command used to check a Python file."
1316 (defvar python-saved-check-command nil
1319 ;; After `sgml-validate-command'.
1320 (defun python-check (command)
1321 "Check a Python file (default current buffer's file).
1322 Runs COMMAND, a shell command, as if by `compile'.
1323 See `python-check-command' for the default."
1325 (list (read-string "Checker command: "
1326 (or python-saved-check-command
1327 (concat python-check-command " "
1328 (let ((name (buffer-file-name)))
1330 (file-name-nondirectory name))))))))
1331 (setq python-saved-check-command command)
1332 (require 'compile) ;To define compilation-* variables.
1333 (save-some-buffers (not compilation-ask-about-save) nil)
1334 (let ((compilation-error-regexp-alist
1335 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1336 compilation-error-regexp-alist)))
1337 (compilation-start command)))
1339 ;;;; Inferior mode stuff (following cmuscheme).
1341 (defcustom python-python-command "python"
1342 "Shell command to run Python interpreter.
1343 Any arguments can't contain whitespace."
1347 (defcustom python-jython-command "jython"
1348 "Shell command to run Jython interpreter.
1349 Any arguments can't contain whitespace."
1353 (defvar python-command python-python-command
1354 "Actual command used to run Python.
1355 May be `python-python-command' or `python-jython-command', possibly
1356 modified by the user. Additional arguments are added when the command
1357 is used by `run-python' et al.")
1359 (defvar python-buffer nil
1360 "*The current Python process buffer.
1362 Commands that send text from source buffers to Python processes have
1363 to choose a process to send to. This is determined by buffer-local
1364 value of `python-buffer'. If its value in the current buffer,
1365 i.e. both any local value and the default one, is nil, `run-python'
1366 and commands that send to the Python process will start a new process.
1368 Whenever \\[run-python] starts a new process, it resets the default
1369 value of `python-buffer' to be the new process's buffer and sets the
1370 buffer-local value similarly if the current buffer is in Python mode
1371 or Inferior Python mode, so that source buffer stays associated with a
1372 specific sub-process.
1374 Use \\[python-set-proc] to set the default value from a buffer with a
1376 (make-variable-buffer-local 'python-buffer)
1378 (defconst python-compilation-regexp-alist
1379 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1380 ;; The first already is (for CAML), but the second isn't. Anyhow,
1381 ;; these are specific to the inferior buffer. -- fx
1382 `((,(rx line-start (1+ (any " \t")) "File \""
1383 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1384 "\", line " (group (1+ digit)))
1386 (,(rx " in file " (group (1+ not-newline)) " on line "
1390 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1391 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1393 "`compilation-error-regexp-alist' for inferior Python.")
1395 (defvar inferior-python-mode-map
1396 (let ((map (make-sparse-keymap)))
1397 ;; This will inherit from comint-mode-map.
1398 (define-key map "\C-c\C-l" 'python-load-file)
1399 (define-key map "\C-c\C-v" 'python-check)
1400 ;; Note that we _can_ still use these commands which send to the
1401 ;; Python process even at the prompt iff we have a normal prompt,
1402 ;; i.e. '>>> ' and not '... '. See the comment before
1403 ;; python-send-region. Fixme: uncomment these if we address that.
1405 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1406 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1409 (defvar inferior-python-mode-syntax-table
1410 (let ((st (make-syntax-table python-mode-syntax-table)))
1411 ;; Don't get confused by apostrophes in the process's output (e.g. if
1412 ;; you execute "help(os)").
1413 (modify-syntax-entry ?\' "." st)
1414 ;; Maybe we should do the same for double quotes?
1415 ;; (modify-syntax-entry ?\" "." st)
1419 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1421 (defvar python--prompt-regexp nil)
1423 (defun python--set-prompt-regexp ()
1424 (let ((prompt (cdr-safe (or (assoc python-python-command
1425 python-shell-prompt-alist)
1426 (assq t python-shell-prompt-alist))))
1427 (cprompt (cdr-safe (or (assoc python-python-command
1428 python-shell-continuation-prompt-alist)
1429 (assq t python-shell-continuation-prompt-alist)))))
1430 (set (make-local-variable 'comint-prompt-regexp)
1432 (mapconcat 'identity
1433 (delq nil (list prompt cprompt "^([Pp]db) "))
1436 (set (make-local-variable 'python--prompt-regexp) prompt)))
1438 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1439 ;; not sure how much: at least some keybindings, like C-c C-f;
1440 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1441 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1442 "Major mode for interacting with an inferior Python process.
1443 A Python process can be started with \\[run-python].
1445 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1448 You can send text to the inferior Python process from other buffers
1449 containing Python source.
1450 * \\[python-switch-to-python] switches the current buffer to the Python
1452 * \\[python-send-region] sends the current region to the Python process.
1453 * \\[python-send-region-and-go] switches to the Python process buffer
1454 after sending the text.
1455 For running multiple processes in multiple buffers, see `run-python' and
1458 \\{inferior-python-mode-map}"
1460 (require 'ansi-color) ; for ipython
1461 (setq mode-line-process '(":%s"))
1462 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1463 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1465 (python--set-prompt-regexp)
1466 (set (make-local-variable 'compilation-error-regexp-alist)
1467 python-compilation-regexp-alist)
1468 (compilation-shell-minor-mode 1))
1470 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1471 "Input matching this regexp is not saved on the history list.
1472 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1476 (defun python-input-filter (str)
1477 "`comint-input-filter' function for inferior Python.
1478 Don't save anything for STR matching `inferior-python-filter-regexp'."
1479 (not (string-match inferior-python-filter-regexp str)))
1481 ;; Fixme: Loses with quoted whitespace.
1482 (defun python-args-to-list (string)
1483 (let ((where (string-match "[ \t]" string)))
1484 (cond ((null where) (list string))
1486 (cons (substring string 0 where)
1487 (python-args-to-list (substring string (+ 1 where)))))
1488 (t (let ((pos (string-match "[^ \t]" string)))
1489 (if pos (python-args-to-list (substring string pos))))))))
1491 (defvar python-preoutput-result nil
1492 "Data from last `_emacs_out' line seen by the preoutput filter.")
1494 (defvar python-preoutput-continuation nil
1495 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1497 (defvar python-preoutput-leftover nil)
1498 (defvar python-preoutput-skip-next-prompt nil)
1500 ;; Using this stops us getting lines in the buffer like
1502 ;; Also look for (and delete) an `_emacs_ok' string and call
1503 ;; `python-preoutput-continuation' if we get it.
1504 (defun python-preoutput-filter (s)
1505 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1506 (when python-preoutput-leftover
1507 (setq s (concat python-preoutput-leftover s))
1508 (setq python-preoutput-leftover nil))
1511 ;; First process whole lines.
1512 (while (string-match "\n" s start)
1513 (let ((line (substring s start (setq start (match-end 0)))))
1514 ;; Skip prompt if needed.
1515 (when (and python-preoutput-skip-next-prompt
1516 (string-match comint-prompt-regexp line))
1517 (setq python-preoutput-skip-next-prompt nil)
1518 (setq line (substring line (match-end 0))))
1519 ;; Recognize special _emacs_out lines.
1520 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1521 (local-variable-p 'python-preoutput-result))
1523 (setq python-preoutput-result (match-string 1 line))
1524 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1525 (setq res (concat res line)))))
1526 ;; Then process the remaining partial line.
1527 (unless (zerop start) (setq s (substring s start)))
1528 (cond ((and (string-match comint-prompt-regexp s)
1529 ;; Drop this prompt if it follows an _emacs_out...
1530 (or python-preoutput-skip-next-prompt
1531 ;; ... or if it's not gonna be inserted at BOL.
1532 ;; Maybe we could be more selective here.
1533 (if (zerop (length res))
1535 (string-match ".\\'" res))))
1536 ;; The need for this seems to be system-dependent:
1537 ;; What is this all about, exactly? --Stef
1538 ;; (if (and (eq ?. (aref s 0)))
1539 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1540 (setq python-preoutput-skip-next-prompt nil)
1542 ((let ((end (min (length "_emacs_out ") (length s))))
1543 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1544 ;; The leftover string is a prefix of _emacs_out so we don't know
1545 ;; yet whether it's an _emacs_out or something else: wait until we
1546 ;; get more output so we can resolve this ambiguity.
1547 (set (make-local-variable 'python-preoutput-leftover) s)
1549 (t (concat res s)))))
1551 (autoload 'comint-check-proc "comint")
1553 (defvar python-version-checked nil)
1554 (defun python-check-version (cmd)
1555 "Check that CMD runs a suitable version of Python."
1556 ;; Fixme: Check on Jython.
1557 (unless (or python-version-checked
1558 (equal 0 (string-match (regexp-quote python-python-command)
1560 (unless (shell-command-to-string cmd)
1561 (error "Can't run Python command `%s'" cmd))
1562 (let* ((res (shell-command-to-string
1564 " -c \"from sys import version_info;\
1565 print version_info >= (2, 2) and version_info < (3, 0)\""))))
1566 (unless (string-match "True" res)
1567 (error "Only Python versions >= 2.2 and < 3.0 are supported")))
1568 (setq python-version-checked t)))
1571 (defun run-python (&optional cmd noshow new)
1572 "Run an inferior Python process, input and output via buffer *Python*.
1573 CMD is the Python command to run. NOSHOW non-nil means don't show the
1574 buffer automatically.
1576 Normally, if there is a process already running in `python-buffer',
1577 switch to that buffer. Interactively, a prefix arg allows you to edit
1578 the initial command line (default is `python-command'); `-i' etc. args
1579 will be added to this as appropriate. A new process is started if:
1580 one isn't running attached to `python-buffer', or interactively the
1581 default `python-command', or argument NEW is non-nil. See also the
1582 documentation for `python-buffer'.
1584 Runs the hook `inferior-python-mode-hook' \(after the
1585 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1586 buffer for a list of commands.)"
1587 (interactive (if current-prefix-arg
1588 (list (read-string "Run Python: " python-command) nil t)
1589 (list python-command)))
1590 (require 'ansi-color) ; for ipython
1591 (unless cmd (setq cmd python-command))
1592 (python-check-version cmd)
1593 (setq python-command cmd)
1594 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1595 ;; (not a name) in Python buffers from which `run-python' &c is
1596 ;; invoked. Would support multiple processes better.
1597 (when (or new (not (comint-check-proc python-buffer)))
1598 (with-current-buffer
1600 (append (python-args-to-list cmd)
1601 '("-i" "-c" "import sys; sys.path.remove('')")))
1602 (path (getenv "PYTHONPATH"))
1603 (process-environment ; to import emacs.py
1604 (cons (concat "PYTHONPATH="
1605 (if path (concat path path-separator))
1607 process-environment))
1608 ;; If we use a pipe, unicode characters are not printed
1609 ;; correctly (Bug#5794) and IPython does not work at
1611 (process-connection-type t))
1612 (apply 'make-comint-in-buffer "Python"
1613 (generate-new-buffer "*Python*")
1614 (car cmdlist) nil (cdr cmdlist)))
1615 (setq-default python-buffer (current-buffer))
1616 (setq python-buffer (current-buffer))
1617 (accept-process-output (get-buffer-process python-buffer) 5)
1618 (inferior-python-mode)
1619 ;; Load function definitions we need.
1620 ;; Before the preoutput function was used, this was done via -c in
1621 ;; cmdlist, but that loses the banner and doesn't run the startup
1622 ;; file. The code might be inline here, but there's enough that it
1623 ;; seems worth putting in a separate file, and it's probably cleaner
1624 ;; to put it in a module.
1625 ;; Ensure we're at a prompt before doing anything else.
1626 (python-send-string "import emacs")
1627 ;; The following line was meant to ensure that we're at a prompt
1628 ;; before doing anything else. However, this can cause Emacs to
1629 ;; hang waiting for a response, if that Python function fails
1630 ;; (i.e. raises an exception).
1631 ;; (python-send-receive "print '_emacs_out ()'")
1633 (if (derived-mode-p 'python-mode)
1634 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1635 ;; Without this, help output goes into the inferior python buffer if
1636 ;; the process isn't already running.
1637 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1638 (unless noshow (pop-to-buffer python-buffer t)))
1640 (defun python-send-command (command)
1641 "Like `python-send-string' but resets `compilation-shell-minor-mode'."
1642 (when (python-check-comint-prompt)
1643 (with-current-buffer (process-buffer (python-proc))
1644 (goto-char (point-max))
1645 (compilation-forget-errors)
1646 (python-send-string command)
1647 (setq compilation-last-buffer (current-buffer)))))
1649 (defun python-send-region (start end)
1650 "Send the region to the inferior Python process."
1651 ;; The region is evaluated from a temporary file. This avoids
1652 ;; problems with blank lines, which have different semantics
1653 ;; interactively and in files. It also saves the inferior process
1654 ;; buffer filling up with interpreter prompts. We need a Python
1655 ;; function to remove the temporary file when it has been evaluated
1656 ;; (though we could probably do it in Lisp with a Comint output
1657 ;; filter). This function also catches exceptions and truncates
1658 ;; tracebacks not to mention the frame of the function itself.
1660 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1661 ;; the reference to the temporary file to the source.
1663 ;; Fixme: Write a `coding' header to the temp file if the region is
1666 (let* ((f (make-temp-file "py"))
1668 ;; IPython puts the FakeModule module into __main__ so
1669 ;; emacs.eexecfile becomes useless.
1670 (if (string-match "^ipython" python-command)
1671 (format "execfile %S" f)
1672 (format "emacs.eexecfile(%S)" f)))
1673 (orig-start (copy-marker start)))
1674 (when (save-excursion
1676 (/= 0 (current-indentation))) ; need dummy block
1678 (goto-char orig-start)
1679 ;; Wrong if we had indented code at buffer start.
1680 (set-marker orig-start (line-beginning-position 0)))
1681 (write-region "if True:\n" nil f nil 'nomsg))
1682 (write-region start end f t 'nomsg)
1683 (python-send-command command)
1684 (with-current-buffer (process-buffer (python-proc))
1685 ;; Tell compile.el to redirect error locations in file `f' to
1686 ;; positions past marker `orig-start'. It has to be done *after*
1687 ;; `python-send-command''s call to `compilation-forget-errors'.
1688 (compilation-fake-loc orig-start f))))
1690 (defun python-send-string (string)
1691 "Evaluate STRING in inferior Python process."
1692 (interactive "sPython command: ")
1693 (comint-send-string (python-proc) string)
1694 (unless (string-match "\n\\'" string)
1695 ;; Make sure the text is properly LF-terminated.
1696 (comint-send-string (python-proc) "\n"))
1697 (when (string-match "\n[ \t].*\n?\\'" string)
1698 ;; If the string contains a final indented line, add a second newline so
1699 ;; as to make sure we terminate the multiline instruction.
1700 (comint-send-string (python-proc) "\n")))
1702 (defun python-send-buffer ()
1703 "Send the current buffer to the inferior Python process."
1705 (python-send-region (point-min) (point-max)))
1707 ;; Fixme: Try to define the function or class within the relevant
1708 ;; module, not just at top level.
1709 (defun python-send-defun ()
1710 "Send the current defun (class or method) to the inferior Python process."
1712 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1713 (progn (end-of-defun) (point)))))
1715 (defun python-switch-to-python (eob-p)
1716 "Switch to the Python process buffer, maybe starting new process.
1717 With prefix arg, position cursor at end of buffer."
1719 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1722 (goto-char (point-max))))
1724 (defun python-send-region-and-go (start end)
1725 "Send the region to the inferior Python process.
1726 Then switch to the process buffer."
1728 (python-send-region start end)
1729 (python-switch-to-python t))
1731 (defcustom python-source-modes '(python-mode jython-mode)
1732 "Used to determine if a buffer contains Python source code.
1733 If a file is loaded into a buffer that is in one of these major modes,
1734 it is considered Python source by `python-load-file', which uses the
1735 value to determine defaults."
1736 :type '(repeat function)
1739 (defvar python-prev-dir/file nil
1740 "Caches (directory . file) pair used in the last `python-load-file' command.
1741 Used for determining the default in the next one.")
1743 (autoload 'comint-get-source "comint")
1745 (defun python-load-file (file-name)
1746 "Load a Python file FILE-NAME into the inferior Python process.
1747 If the file has extension `.py' import or reload it as a module.
1748 Treating it as a module keeps the global namespace clean, provides
1749 function location information for debugging, and supports users of
1750 module-qualified names."
1751 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1753 t)) ; because execfile needs exact name
1754 (comint-check-source file-name) ; Check to see if buffer needs saving.
1755 (setq python-prev-dir/file (cons (file-name-directory file-name)
1756 (file-name-nondirectory file-name)))
1757 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1758 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1759 (python-send-command
1760 (if (string-match "\\.py\\'" file-name)
1761 (let ((module (file-name-sans-extension
1762 (file-name-nondirectory file-name))))
1763 (format "emacs.eimport(%S,%S)"
1764 module (file-name-directory file-name)))
1765 (format "execfile(%S)" file-name)))
1766 (message "%s loaded" file-name)))
1768 (defun python-proc ()
1769 "Return the current Python process.
1770 See variable `python-buffer'. Starts a new process if necessary."
1771 ;; Fixme: Maybe should look for another active process if there
1772 ;; isn't one for `python-buffer'.
1773 (unless (comint-check-proc python-buffer)
1775 (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
1779 (defun python-set-proc ()
1780 "Set the default value of `python-buffer' to correspond to this buffer.
1781 If the current buffer has a local value of `python-buffer', set the
1782 default (global) value to that. The associated Python process is
1783 the one that gets input from \\[python-send-region] et al when used
1784 in a buffer that doesn't have a local value of `python-buffer'."
1786 (if (local-variable-p 'python-buffer)
1787 (setq-default python-buffer python-buffer)
1788 (error "No local value of `python-buffer'")))
1790 ;;;; Context-sensitive help.
1792 (defconst python-dotty-syntax-table
1793 (let ((table (make-syntax-table)))
1794 (set-char-table-parent table python-mode-syntax-table)
1795 (modify-syntax-entry ?. "_" table)
1797 "Syntax table giving `.' symbol syntax.
1798 Otherwise inherits from `python-mode-syntax-table'.")
1800 (eval-when-compile (autoload 'help-buffer "help-fns"))
1802 (defvar python-imports) ; forward declaration
1804 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1805 ;; bound to C-h S? [Probably not, since info-look may work in cases
1806 ;; where this doesn't.]
1807 (defun python-describe-symbol (symbol)
1808 "Get help on SYMBOL using `help'.
1809 Interactively, prompt for symbol.
1811 Symbol may be anything recognized by the interpreter's `help'
1812 command -- e.g. `CALLS' -- not just variables in scope in the
1813 interpreter. This only works for Python version 2.2 or newer
1814 since earlier interpreters don't support `help'.
1816 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1818 ;; Note that we do this in the inferior process, not a separate one, to
1819 ;; ensure the environment is appropriate.
1821 (let ((symbol (with-syntax-table python-dotty-syntax-table
1823 (enable-recursive-minibuffers t))
1824 (list (read-string (if symbol
1825 (format "Describe symbol (default %s): " symbol)
1826 "Describe symbol: ")
1828 (if (equal symbol "") (error "No symbol"))
1829 ;; Ensure we have a suitable help buffer.
1830 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1831 ;; allow C-c C-f in help buffer.
1832 (let ((temp-buffer-show-hook ; avoid xref stuff
1834 (toggle-read-only 1))))
1835 (with-help-window (help-buffer)
1836 (with-current-buffer standard-output
1837 ;; Fixme: Is this actually useful?
1838 (help-setup-xref (list 'python-describe-symbol symbol)
1839 (called-interactively-p 'interactive))
1840 (set (make-local-variable 'comint-redirect-subvert-readonly) t))))
1841 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1842 symbol python-imports)
1843 "*Help*" (python-proc) nil nil))
1845 (add-to-list 'debug-ignored-errors "^No symbol")
1847 (defun python-send-receive (string)
1848 "Send STRING to inferior Python (if any) and return result.
1849 The result is what follows `_emacs_out' in the output.
1850 This is a no-op if `python-check-comint-prompt' returns nil."
1851 (python-send-string string)
1852 (let ((proc (python-proc)))
1853 (with-current-buffer (process-buffer proc)
1854 (when (python-check-comint-prompt proc)
1855 (set (make-local-variable 'python-preoutput-result) nil)
1857 (accept-process-output proc 5)
1858 (null python-preoutput-result)))
1859 (prog1 python-preoutput-result
1860 (kill-local-variable 'python-preoutput-result))))))
1862 (defun python-check-comint-prompt (&optional proc)
1863 "Return non-nil if and only if there's a normal prompt in the inferior buffer.
1864 If there isn't, it's probably not appropriate to send input to return Eldoc
1865 information etc. If PROC is non-nil, check the buffer for that process."
1866 (with-current-buffer (process-buffer (or proc (python-proc)))
1869 (re-search-backward (concat python--prompt-regexp " *\\=")
1872 ;; Fixme: Is there anything reasonable we can do with random methods?
1873 ;; (Currently only works with functions.)
1874 (defun python-eldoc-function ()
1875 "`eldoc-documentation-function' for Python.
1876 Only works when point is in a function name, not its arg list, for
1877 instance. Assumes an inferior Python is running."
1878 (let ((symbol (with-syntax-table python-dotty-syntax-table
1880 ;; This is run from timers, so inhibit-quit tends to be set.
1882 ;; First try the symbol we're on.
1884 (python-send-receive (format "emacs.eargs(%S, %s)"
1885 symbol python-imports)))
1886 ;; Try moving to symbol before enclosing parens.
1887 (let ((s (syntax-ppss)))
1888 (unless (zerop (car s))
1889 (when (eq ?\( (char-after (nth 1 s)))
1891 (goto-char (nth 1 s))
1892 (skip-syntax-backward "-")
1893 (let ((point (point)))
1894 (skip-chars-backward "a-zA-Z._")
1895 (if (< (point) point)
1896 (python-send-receive
1897 (format "emacs.eargs(%S, %s)"
1898 (buffer-substring-no-properties (point) point)
1899 python-imports))))))))))))
1901 ;;;; Info-look functionality.
1903 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1905 (defun python-after-info-look ()
1906 "Set up info-look for Python.
1907 Used with `eval-after-load'."
1908 (let* ((version (let ((s (shell-command-to-string (concat python-command
1910 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1911 (match-string 1 s)))
1912 ;; Whether info files have a Python version suffix, e.g. in Debian.
1915 (with-no-warnings (Info-mode))
1917 ;; Don't use `info' because it would pop-up a *info* buffer.
1919 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1923 (info-lookup-maybe-add-help
1925 :regexp "[[:alnum:]_]+"
1927 ;; Fixme: Can this reasonably be made specific to indices with
1928 ;; different rules? Is the order of indices optimal?
1929 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1932 ;; The empty prefix just gets us highlighted terms.
1933 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1934 (,(concat "(python" version "-ref)Module Index" nil ""))
1935 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1937 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1939 (,(concat "(python" version "-lib)Module Index" nil ""))
1940 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1942 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1944 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1945 '(("(python-ref)Miscellaneous Index" nil "")
1946 ("(python-ref)Module Index" nil "")
1947 ("(python-ref)Function-Method-Variable Index" nil "")
1948 ("(python-ref)Class-Exception-Object Index" nil "")
1949 ("(python-lib)Module Index" nil "")
1950 ("(python-lib)Class-Exception-Object Index" nil "")
1951 ("(python-lib)Function-Method-Variable Index" nil "")
1952 ("(python-lib)Miscellaneous Index" nil ""))))))
1953 (eval-after-load "info-look" '(python-after-info-look))
1957 (defcustom python-jython-packages '("java" "javax" "org" "com")
1958 "Packages implying `jython-mode'.
1959 If these are imported near the beginning of the buffer, `python-mode'
1960 actually punts to `jython-mode'."
1961 :type '(repeat string)
1964 ;; Called from `python-mode', this causes a recursive call of the
1965 ;; mode. See logic there to break out of the recursion.
1966 (defun python-maybe-jython ()
1967 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1968 The criterion is either a match for `jython-mode' via
1969 `interpreter-mode-alist' or an import of a module from the list
1970 `python-jython-packages'."
1971 ;; The logic is taken from python-mode.el.
1975 (goto-char (point-min))
1976 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1978 (if (and interpreter (eq 'jython-mode
1979 (cdr (assoc (file-name-nondirectory
1981 interpreter-mode-alist))))
1984 (while (re-search-forward
1985 (rx line-start (or "import" "from") (1+ space)
1986 (group (1+ (not (any " \t\n.")))))
1987 (+ (point-min) 10000) ; Probably not worth customizing.
1989 (if (member (match-string 1) python-jython-packages)
1993 (defun python-fill-paragraph (&optional justify)
1994 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1995 If any of the current line is in or at the end of a multi-line string,
1996 fill the string or the paragraph of it that point is in, preserving
1997 the string's indentation."
1999 (or (fill-comment-paragraph justify)
2002 (let* ((syntax (syntax-ppss))
2005 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
2006 (let (fill-paragraph-function)
2007 (fill-paragraph justify)))
2008 ;; The `paragraph-start' and `paragraph-separate'
2009 ;; variables don't allow us to delimit the last
2010 ;; paragraph in a multi-line string properly, so narrow
2011 ;; to the string and then fill around (the end of) the
2013 ((eq t (nth 3 syntax)) ; in fenced string
2014 (goto-char (nth 8 syntax)) ; string start
2015 (setq start (line-beginning-position))
2016 (setq end (condition-case () ; for unbalanced quotes
2017 (progn (forward-sexp)
2019 (error (point-max)))))
2020 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
2024 (progn (backward-sexp)
2025 (setq start (line-beginning-position)))
2029 (narrow-to-region start end)
2031 ;; Avoid losing leading and trailing newlines in doc
2032 ;; strings written like:
2036 (let ((paragraph-separate
2037 ;; Note that the string could be part of an
2038 ;; expression, so it can have preceding and
2039 ;; trailing non-whitespace.
2042 ;; Opening triple quote without following text.
2044 (group (syntax string-delimiter))
2045 (repeat 2 (backref 1))
2046 ;; Fixme: Not sure about including
2047 ;; trailing whitespace.
2050 ;; Closing trailing quote without preceding text.
2051 (and (group (any ?\" ?')) (backref 2)
2052 (syntax string-delimiter))))
2053 "\\(?:" paragraph-separate "\\)"))
2054 fill-paragraph-function)
2055 (fill-paragraph justify))))))) t)
2057 (defun python-shift-left (start end &optional count)
2058 "Shift lines in region COUNT (the prefix arg) columns to the left.
2059 COUNT defaults to `python-indent'. If region isn't active, just shift
2060 current line. The region shifted includes the lines in which START and
2061 END lie. It is an error if any lines in the region are indented less than
2065 (list (region-beginning) (region-end) current-prefix-arg)
2066 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2068 (setq count (prefix-numeric-value count))
2069 (setq count python-indent))
2073 (while (< (point) end)
2074 (if (and (< (current-indentation) count)
2075 (not (looking-at "[ \t]*$")))
2076 (error "Can't shift all lines enough"))
2078 (indent-rigidly start end (- count)))))
2080 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
2082 (defun python-shift-right (start end &optional count)
2083 "Shift lines in region COUNT (the prefix arg) columns to the right.
2084 COUNT defaults to `python-indent'. If region isn't active, just shift
2085 current line. The region shifted includes the lines in which START and
2089 (list (region-beginning) (region-end) current-prefix-arg)
2090 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2092 (setq count (prefix-numeric-value count))
2093 (setq count python-indent))
2094 (indent-rigidly start end count))
2096 (defun python-outline-level ()
2097 "`outline-level' function for Python mode.
2098 The level is the number of `python-indent' steps of indentation
2100 (1+ (/ (current-indentation) python-indent)))
2102 ;; Fixme: Consider top-level assignments, imports, &c.
2103 (defun python-current-defun (&optional length-limit)
2104 "`add-log-current-defun-function' for Python."
2106 ;; Move up the tree of nested `class' and `def' blocks until we
2107 ;; get to zero indentation, accumulating the defined names.
2111 (while (or (null length-limit)
2113 (< length length-limit))
2114 (let ((started-from (point)))
2115 (python-beginning-of-block)
2117 (beginning-of-defun)
2118 (when (= (point) started-from)
2120 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
2121 (group (1+ (or word (syntax symbol))))))
2122 (push (match-string 1) accum)
2123 (setq length (+ length 1 (length (car accum)))))
2124 (when (= (current-indentation) 0)
2125 (throw 'done nil))))
2127 (when (and length-limit (> length length-limit))
2128 (setcar accum ".."))
2129 (mapconcat 'identity accum ".")))))
2131 (defun python-mark-block ()
2132 "Mark the block around point.
2133 Uses `python-beginning-of-block', `python-end-of-block'."
2136 (python-beginning-of-block)
2137 (push-mark (point) nil t)
2138 (python-end-of-block)
2139 (exchange-point-and-mark))
2141 ;; Fixme: Provide a find-function-like command to find source of a
2142 ;; definition (separate from BicycleRepairMan). Complicated by
2143 ;; finding the right qualified name.
2147 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
2148 (defvar python-imports "None"
2149 "String of top-level import statements updated by `python-find-imports'.")
2150 (make-variable-buffer-local 'python-imports)
2152 ;; Fixme: Should font-lock try to run this when it deals with an import?
2153 ;; Maybe not a good idea if it gets run multiple times when the
2154 ;; statement is being edited, and is more likely to end up with
2155 ;; something syntactically incorrect.
2156 ;; However, what we should do is to trundle up the block tree from point
2157 ;; to extract imports that appear to be in scope, and add those.
2158 (defun python-find-imports ()
2159 "Find top-level imports, updating `python-imports'."
2163 (goto-char (point-min))
2164 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
2165 (unless (syntax-ppss-context (syntax-ppss))
2166 (let ((start (line-beginning-position)))
2167 ;; Skip over continued lines.
2168 (while (and (eq ?\\ (char-before (line-end-position)))
2169 (= 0 (forward-line 1)))
2171 (push (buffer-substring start (line-beginning-position 2))
2173 (setq python-imports
2176 ;; This is probably best left out since you're unlikely to need the
2177 ;; doc for a function in the buffer and the import will lose if the
2178 ;; Python sub-process' working directory isn't the same as the
2180 ;; (if buffer-file-name
2183 ;; (file-name-sans-extension
2184 ;; (file-name-nondirectory buffer-file-name))))
2188 (set-text-properties 0 (length python-imports) nil python-imports)
2189 ;; The output ends up in the wrong place if the string we
2190 ;; send contains newlines (from the imports).
2191 (setq python-imports
2192 (replace-regexp-in-string "\n" "\\n"
2193 (format "%S" python-imports) t t))))))
2195 ;; Fixme: This fails the first time if the sub-process isn't already
2196 ;; running. Presumably a timing issue with i/o to the process.
2197 (defun python-symbol-completions (symbol)
2198 "Return a list of completions of the string SYMBOL from Python process.
2200 Uses `python-imports' to load modules against which to complete."
2201 (when (stringp symbol)
2204 (car (read-from-string
2205 (python-send-receive
2206 (format "emacs.complete(%S,%s)"
2207 (substring-no-properties symbol)
2211 ;; We can get duplicates from the above -- don't know why.
2212 (delete-dups completions)
2215 (defun python-completion-at-point ()
2217 (start (save-excursion
2218 (and (re-search-backward
2219 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2220 (group (1+ (regexp "[[:alnum:]._]"))) point)
2222 (match-beginning 1)))))
2225 (completion-table-dynamic 'python-symbol-completions)))))
2229 (defun python-module-path (module)
2230 "Function for `ffap-alist' to return path to MODULE."
2231 (python-send-receive (format "emacs.modpath (%S)" module)))
2233 (eval-after-load "ffap"
2234 '(push '(python-mode . python-module-path) ffap-alist))
2236 ;;;; Find-function support
2238 ;; Fixme: key binding?
2240 (defun python-find-function (name)
2241 "Find source of definition of function NAME.
2242 Interactively, prompt for name."
2244 (let ((symbol (with-syntax-table python-dotty-syntax-table
2246 (enable-recursive-minibuffers t))
2247 (list (read-string (if symbol
2248 (format "Find location of (default %s): " symbol)
2249 "Find location of: ")
2251 (unless python-imports
2252 (error "Not called from buffer visiting Python file"))
2253 (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
2254 name python-imports)))
2255 (loc (car (read-from-string loc)))
2258 (unless file (error "Don't know where `%s' is defined" name))
2259 (pop-to-buffer (find-file-noselect file))
2260 (when (integerp line)
2261 (goto-char (point-min))
2262 (forward-line (1- line)))))
2266 (defcustom python-use-skeletons nil
2267 "Non-nil means template skeletons will be automagically inserted.
2268 This happens when pressing \"if<SPACE>\", for example, to prompt for
2273 (define-abbrev-table 'python-mode-abbrev-table ()
2274 "Abbrev table for Python mode."
2276 ;; Allow / inside abbrevs.
2277 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2278 ;; Only expand in code.
2279 :enable-function (lambda () (not (python-in-string/comment))))
2282 ;; Define a user-level skeleton and add it to the abbrev table.
2283 (defmacro def-python-skeleton (name &rest elements)
2284 (declare (indent 2))
2285 (let* ((name (symbol-name name))
2286 (function (intern (concat "python-insert-" name))))
2288 ;; Usual technique for inserting a skeleton, but expand
2289 ;; to the original abbrev instead if in a comment or string.
2290 (when python-use-skeletons
2291 (define-abbrev python-mode-abbrev-table ,name ""
2293 nil t)) ; system abbrev
2294 (define-skeleton ,function
2295 ,(format "Insert Python \"%s\" template." name)
2298 ;; From `skeleton-further-elements' set below:
2299 ;; `<': outdent a level;
2300 ;; `^': delete indentation on current line and also previous newline.
2301 ;; Not quite like `delete-indentation'. Assumes point is at
2302 ;; beginning of indentation.
2304 (def-python-skeleton if
2307 > -1 ; Fixme: I don't understand the spurious space this removes.
2309 ("other condition, %s: "
2310 < ; Avoid wrong indentation after block opening.
2315 (define-skeleton python-else
2316 "Auxiliary skeleton."
2318 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2323 (def-python-skeleton while
2329 (def-python-skeleton for
2331 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2335 (def-python-skeleton try/except
2340 < "except " str '(python-target) ":" \n
2346 (define-skeleton python-target
2347 "Auxiliary skeleton."
2348 "Target, %s: " ", " str | -2)
2350 (def-python-skeleton try/finally
2357 (def-python-skeleton def
2359 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2361 "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
2364 (def-python-skeleton class
2366 "class " str " (" ("Inheritance, %s: "
2367 (unless (equal ?\( (char-before)) ", ")
2369 & ")" | -2 ; close list or remove opening
2371 "\"\"\"" - "\"\"\"" \n
2374 (defvar python-default-template "if"
2375 "Default template to expand by `python-expand-template'.
2376 Updated on each expansion.")
2378 (defun python-expand-template (name)
2379 "Expand template named NAME.
2380 Interactively, prompt for the name with completion."
2382 (list (completing-read (format "Template to expand (default %s): "
2383 python-default-template)
2384 python-mode-abbrev-table nil t nil nil
2385 python-default-template)))
2387 (setq name python-default-template)
2388 (setq python-default-template name))
2389 (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
2392 (error "Undefined template: %s" name))))
2394 ;;;; Bicycle Repair Man support
2396 (autoload 'pymacs-load "pymacs" nil t)
2397 (autoload 'brm-init "bikemacs")
2399 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2400 ;; the way it modifies files outside Emacs... Also note that the
2401 ;; current BRM loses with tabs used for indentation -- I submitted a
2402 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2403 (defun python-setup-brm ()
2404 "Set up Bicycle Repair Man refactoring tool (if available).
2406 Note that the `refactoring' features change files independently of
2407 Emacs and may modify and save the contents of the current buffer
2408 without confirmation."
2410 (condition-case data
2411 (unless (fboundp 'brm-rename)
2412 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2413 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2414 (features (cons 'python-mode features))) ; and requires this
2415 (brm-init) ; second line of normal recipe
2416 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2417 '(lambda () (easy-menu-add brm-menu)))
2419 python-brm-menu python-mode-map
2420 "Bicycle Repair Man"
2421 '("BicycleRepairMan"
2422 :help "Interface to navigation and refactoring tool"
2424 ["Find References" brm-find-references
2425 :help "Find references to name at point in compilation buffer"]
2426 ["Find Definition" brm-find-definition
2427 :help "Find definition of name at point"]
2430 ["Rename" brm-rename
2431 :help "Replace name at point with a new name everywhere"]
2432 ["Extract Method" brm-extract-method
2433 :active (and mark-active (not buffer-read-only))
2434 :help "Replace statements in region with a method"]
2435 ["Extract Local Variable" brm-extract-local-variable
2436 :active (and mark-active (not buffer-read-only))
2437 :help "Replace expression in region with an assignment"]
2438 ["Inline Local Variable" brm-inline-local-variable
2440 "Substitute uses of variable at point with its definition"]
2441 ;; Fixme: Should check for anything to revert.
2442 ["Undo Last Refactoring" brm-undo :help ""]))))
2443 (error (error "BicycleRepairMan setup failed: %s" data))))
2447 ;; pdb tracking is alert once this file is loaded, but takes no action if
2448 ;; `python-pdbtrack-do-tracking-p' is nil.
2449 (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2451 (defvar outline-heading-end-regexp)
2452 (defvar eldoc-documentation-function)
2453 (defvar python-mode-running) ;Dynamically scoped var.
2456 (define-derived-mode python-mode fundamental-mode "Python"
2457 "Major mode for editing Python files.
2458 Turns on Font Lock mode unconditionally since it is currently required
2459 for correct parsing of the source.
2460 See also `jython-mode', which is actually invoked if the buffer appears to
2461 contain Jython code. See also `run-python' and associated Python mode
2462 commands for running Python under Emacs.
2464 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2465 with nested `def' and `class' blocks. They take the innermost one as
2466 current without distinguishing method and class definitions. Used multiple
2467 times, they move over others at the same indentation level until they reach
2468 the end of definitions at that level, when they move up a level.
2470 Colon is electric: it outdents the line if appropriate, e.g. for
2471 an else statement. \\[python-backspace] at the beginning of an indented statement
2472 deletes a level of indentation to close the current block; otherwise it
2473 deletes a character backward. TAB indents the current line relative to
2474 the preceding code. Successive TABs, with no intervening command, cycle
2475 through the possibilities for indentation on the basis of enclosing blocks.
2477 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2478 effect outside them.
2480 Supports Eldoc mode (only for functions, using a Python process),
2481 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2482 lines count as headers. Symbol completion is available in the
2483 same way as in the Python shell using the `rlcompleter' module
2484 and this is added to the Hippie Expand functions locally if
2485 Hippie Expand mode is turned on. Completion of symbols of the
2486 form x.y only works if the components are literal
2487 module/attribute names, not variables. An abbrev table is set up
2488 with skeleton expansions for compound statement templates.
2490 \\{python-mode-map}"
2492 (set (make-local-variable 'font-lock-defaults)
2493 '(python-font-lock-keywords nil nil nil nil
2494 ;; This probably isn't worth it.
2495 ;; (font-lock-syntactic-face-function
2496 ;; . python-font-lock-syntactic-face-function)
2498 (set (make-local-variable 'syntax-propertize-function)
2499 python-syntax-propertize-function)
2500 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2501 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2502 (set (make-local-variable 'comment-start) "# ")
2503 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2504 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2505 (set (make-local-variable 'paragraph-start) "\\s-*$")
2506 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2507 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2508 (set (make-local-variable 'add-log-current-defun-function)
2509 #'python-current-defun)
2510 (set (make-local-variable 'outline-regexp)
2511 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2512 "for" "if" "try" "while" "with")
2514 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2515 (set (make-local-variable 'outline-level) #'python-outline-level)
2516 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2517 (make-local-variable 'python-saved-check-command)
2518 (set (make-local-variable 'beginning-of-defun-function)
2519 'python-beginning-of-defun)
2520 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2521 (add-hook 'which-func-functions 'python-which-func nil t)
2522 (setq imenu-create-index-function #'python-imenu-create-index)
2523 (set (make-local-variable 'eldoc-documentation-function)
2524 #'python-eldoc-function)
2525 (add-hook 'eldoc-mode-hook
2526 (lambda () (run-python nil t)) ; need it running
2528 (add-hook 'completion-at-point-functions
2529 'python-completion-at-point nil 'local)
2530 ;; Fixme: should be in hideshow. This seems to be of limited use
2531 ;; since it isn't (can't be) indentation-based. Also hide-level
2532 ;; doesn't seem to work properly.
2533 (add-to-list 'hs-special-modes-alist
2534 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2536 (python-end-of-defun)
2537 (skip-chars-backward " \t\n"))
2539 (set (make-local-variable 'skeleton-further-elements)
2540 '((< '(backward-delete-char-untabify (min python-indent
2542 (^ '(- (1+ (current-indentation))))))
2543 ;; Python defines TABs as being 8-char wide.
2544 (set (make-local-variable 'tab-width) 8)
2545 (unless font-lock-mode (font-lock-mode 1))
2546 (when python-guess-indent (python-guess-indent))
2547 ;; Let's make it harder for the user to shoot himself in the foot.
2548 (unless (= tab-width python-indent)
2549 (setq indent-tabs-mode nil))
2550 (set (make-local-variable 'python-command) python-python-command)
2551 (python-find-imports)
2552 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2553 (let ((python-mode-running t))
2554 (python-maybe-jython))))
2556 ;; Not done automatically in Emacs 21 or 22.
2557 (defcustom python-mode-hook nil
2558 "Hook run when entering Python mode."
2561 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2562 (custom-add-option 'python-mode-hook
2564 "Turn off Indent Tabs mode."
2565 (setq indent-tabs-mode nil)))
2566 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2567 (custom-add-option 'python-mode-hook 'abbrev-mode)
2568 (custom-add-option 'python-mode-hook 'python-setup-brm)
2571 (define-derived-mode jython-mode python-mode "Jython"
2572 "Major mode for editing Jython files.
2573 Like `python-mode', but sets up parameters for Jython subprocesses.
2574 Runs `jython-mode-hook' after `python-mode-hook'."
2576 (set (make-local-variable 'python-command) python-jython-command))
2580 ;; pdbtrack features
2582 (defun python-comint-output-filter-function (string)
2583 "Watch output for Python prompt and exec next file waiting in queue.
2584 This function is appropriate for `comint-output-filter-functions'."
2585 ;; TBD: this should probably use split-string
2586 (when (and (string-match python--prompt-regexp string)
2589 (delete-file (car python-file-queue))
2591 (setq python-file-queue (cdr python-file-queue))
2592 (if python-file-queue
2593 (let ((pyproc (get-buffer-process (current-buffer))))
2594 (python-execute-file pyproc (car python-file-queue))))))
2596 (defun python-pdbtrack-overlay-arrow (activation)
2597 "Activate or deactivate arrow at beginning-of-line in current buffer."
2600 (setq overlay-arrow-position (make-marker)
2601 overlay-arrow-string "=>"
2602 python-pdbtrack-is-tracking-p t)
2603 (set-marker overlay-arrow-position
2604 (line-beginning-position)
2606 (setq overlay-arrow-position nil
2607 python-pdbtrack-is-tracking-p nil)))
2609 (defun python-pdbtrack-track-stack-file (text)
2610 "Show the file indicated by the pdb stack entry line, in a separate window.
2612 Activity is disabled if the buffer-local variable
2613 `python-pdbtrack-do-tracking-p' is nil.
2615 We depend on the pdb input prompt being a match for
2616 `python-pdbtrack-input-prompt'.
2618 If the traceback target file path is invalid, we look for the
2619 most recently visited python-mode buffer which either has the
2620 name of the current function or class, or which defines the
2621 function or class. This is to provide for scripts not in the
2622 local filesytem (e.g., Zope's 'Script \(Python)', but it's not
2623 Zope specific). If you put a copy of the script in a buffer
2624 named for the script and activate python-mode, then pdbtrack will
2626 ;; Instead of trying to piece things together from partial text
2627 ;; (which can be almost useless depending on Emacs version), we
2628 ;; monitor to the point where we have the next pdb prompt, and then
2629 ;; check all text from comint-last-input-end to process-mark.
2631 ;; Also, we're very conservative about clearing the overlay arrow,
2632 ;; to minimize residue. This means, for instance, that executing
2633 ;; other pdb commands wipe out the highlight. You can always do a
2634 ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
2636 (let* ((origbuf (current-buffer))
2637 (currproc (get-buffer-process origbuf)))
2639 (if (not (and currproc python-pdbtrack-do-tracking-p))
2640 (python-pdbtrack-overlay-arrow nil)
2642 (let* ((procmark (process-mark currproc))
2643 (block (buffer-substring (max comint-last-input-end
2645 python-pdbtrack-track-range))
2647 target target_fname target_lineno target_buffer)
2649 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2650 (python-pdbtrack-overlay-arrow nil)
2652 (setq target (python-pdbtrack-get-source-buffer block))
2654 (if (stringp target)
2656 (python-pdbtrack-overlay-arrow nil)
2657 (message "pdbtrack: %s" target))
2659 (setq target_lineno (car target)
2660 target_buffer (cadr target)
2661 target_fname (buffer-file-name target_buffer))
2662 (switch-to-buffer-other-window target_buffer)
2663 (goto-char (point-min))
2664 (forward-line (1- target_lineno))
2665 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
2666 (python-pdbtrack-overlay-arrow t)
2667 (pop-to-buffer origbuf t)
2668 ;; in large shell buffers, above stuff may cause point to lag output
2669 (goto-char procmark)
2673 (defun python-pdbtrack-get-source-buffer (block)
2674 "Return line number and buffer of code indicated by block's traceback text.
2676 We look first to visit the file indicated in the trace.
2678 Failing that, we look for the most recently visited python-mode buffer
2679 with the same name or having the named function.
2681 If we're unable find the source code we return a string describing the
2684 (if (not (string-match python-pdbtrack-stack-entry-regexp block))
2686 "Traceback cue not found"
2688 (let* ((filename (match-string 1 block))
2689 (lineno (string-to-number (match-string 2 block)))
2690 (funcname (match-string 3 block))
2693 (cond ((file-exists-p filename)
2694 (list lineno (find-file-noselect filename)))
2696 ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
2697 (if (string-match "/Script (Python)$" filename)
2698 ;; Add in number of lines for leading '##' comments:
2701 (with-current-buffer funcbuffer
2702 (if (equal (point-min)(point-max))
2707 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
2709 (point-min) (point-max)))
2711 (list lineno funcbuffer))
2713 ((= (elt filename 0) ?\<)
2714 (format "(Non-file source: '%s')" filename))
2716 (t (format "Not found: %s(), %s" funcname filename)))
2721 (defun python-pdbtrack-grub-for-buffer (funcname lineno)
2722 "Find recent python-mode buffer named, or having function named funcname."
2723 (let ((buffers (buffer-list))
2726 (while (and buffers (not got))
2727 (setq buf (car buffers)
2728 buffers (cdr buffers))
2729 (if (and (with-current-buffer buf
2730 (string= major-mode "python-mode"))
2731 (or (string-match funcname (buffer-name buf))
2732 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
2734 (with-current-buffer buf
2735 (buffer-substring (point-min)
2740 (defun python-toggle-shells (arg)
2741 "Toggles between the CPython and JPython shells.
2743 With positive argument ARG (interactively \\[universal-argument]),
2744 uses the CPython shell, with negative ARG uses the JPython shell, and
2745 with a zero argument, toggles the shell.
2747 Programmatically, ARG can also be one of the symbols `cpython' or
2748 `jpython', equivalent to positive arg and negative arg respectively."
2750 ;; default is to toggle
2757 (if (string-equal python-which-bufname "Python")
2760 ((equal arg 'cpython) (setq arg 1))
2761 ((equal arg 'jpython) (setq arg -1)))
2766 (setq python-which-shell python-python-command
2767 python-which-args python-python-command-args
2768 python-which-bufname "Python"
2770 mode-name "Python"))
2772 (setq python-which-shell python-jython-command
2773 python-which-args python-jython-command-args
2774 python-which-bufname "JPython"
2776 mode-name "JPython")))
2777 (message "Using the %s shell" msg)))
2779 ;; Python subprocess utilities and filters
2780 (defun python-execute-file (proc filename)
2781 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
2782 Make that process's buffer visible and force display. Also make
2783 comint believe the user typed this string so that
2784 `kill-output-from-shell' does The Right Thing."
2785 (let ((curbuf (current-buffer))
2786 (procbuf (process-buffer proc))
2787 ; (comint-scroll-to-bottom-on-output t)
2788 (msg (format "## working on region in file %s...\n" filename))
2789 ;; add some comment, so that we can filter it out of history
2790 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
2792 (with-current-buffer procbuf
2793 (goto-char (point-max))
2794 (move-marker (process-mark proc) (point))
2795 (funcall (process-filter proc) proc msg))
2796 (set-buffer curbuf))
2797 (process-send-string proc cmd)))
2800 (defun python-shell (&optional argprompt)
2801 "Start an interactive Python interpreter in another window.
2802 This is like Shell mode, except that Python is running in the window
2803 instead of a shell. See the `Interactive Shell' and `Shell Mode'
2804 sections of the Emacs manual for details, especially for the key
2805 bindings active in the `*Python*' buffer.
2807 With optional \\[universal-argument], the user is prompted for the
2808 flags to pass to the Python interpreter. This has no effect when this
2809 command is used to switch to an existing process, only when a new
2810 process is started. If you use this, you will probably want to ensure
2811 that the current arguments are retained (they will be included in the
2812 prompt). This argument is ignored when this function is called
2813 programmatically, or when running in Emacs 19.34 or older.
2815 Note: You can toggle between using the CPython interpreter and the
2816 JPython interpreter by hitting \\[python-toggle-shells]. This toggles
2817 buffer local variables which control whether all your subshell
2818 interactions happen to the `*JPython*' or `*Python*' buffers (the
2819 latter is the name used for the CPython buffer).
2821 Warning: Don't use an interactive Python if you change sys.ps1 or
2822 sys.ps2 from their default values, or if you're running code that
2823 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
2824 distinguish your output from Python's output, and assumes that `>>> '
2825 at the start of a line is a prompt from Python. Similarly, the Emacs
2826 Shell mode code assumes that both `>>> ' and `... ' at the start of a
2827 line are Python prompts. Bad things can happen if you fool either
2830 Warning: If you do any editing *in* the process buffer *while* the
2831 buffer is accepting output from Python, do NOT attempt to `undo' the
2832 changes. Some of the output (nowhere near the parts you changed!) may
2833 be lost if you do. This appears to be an Emacs bug, an unfortunate
2834 interaction between undo and process filters; the same problem exists in
2835 non-Python process buffers using the default (Emacs-supplied) process
2838 (require 'ansi-color) ; For ipython
2839 ;; Set the default shell if not already set
2840 (when (null python-which-shell)
2841 (python-toggle-shells python-default-interpreter))
2842 (let ((args python-which-args))
2843 (when (and argprompt
2844 (called-interactively-p 'interactive)
2845 (fboundp 'split-string))
2846 ;; TBD: Perhaps force "-i" in the final list?
2847 (setq args (split-string
2848 (read-string (concat python-which-bufname
2851 (mapconcat 'identity python-which-args " ") " ")
2853 (switch-to-buffer-other-window
2854 (apply 'make-comint python-which-bufname python-which-shell nil args))
2855 (set-process-sentinel (get-buffer-process (current-buffer))
2857 (python--set-prompt-regexp)
2858 (add-hook 'comint-output-filter-functions
2859 'python-comint-output-filter-function nil t)
2861 (set-syntax-table python-mode-syntax-table)
2862 (use-local-map python-shell-map)))
2864 (defun python-pdbtrack-toggle-stack-tracking (arg)
2866 (if (not (get-buffer-process (current-buffer)))
2867 (error "No process associated with buffer '%s'" (current-buffer)))
2868 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2870 (zerop (setq arg (prefix-numeric-value arg))))
2871 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2872 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2873 (message "%sabled Python's pdbtrack"
2874 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2876 (defun turn-on-pdbtrack ()
2878 (python-pdbtrack-toggle-stack-tracking 1))
2880 (defun turn-off-pdbtrack ()
2882 (python-pdbtrack-toggle-stack-tracking 0))
2884 (defun python-sentinel (proc msg)
2885 (setq overlay-arrow-position nil))
2888 (provide 'python-21)
2890 ;;; python.el ends here