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