1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003-2011 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:
30 ;; http://launchpad.net/python-mode
31 ;; used by XEmacs, and originally maintained with Python.
32 ;; That isn't covered by an FSF copyright assignment (?), unlike this
33 ;; code, and seems not to be well-maintained for Emacs (though I've
34 ;; submitted fixes). This mode is rather simpler and is better in
35 ;; other ways. In particular, using the syntax functions with text
36 ;; properties maintained by font-lock makes it more correct with
37 ;; arbitrary string and comment contents.
39 ;; This doesn't implement all the facilities of python-mode.el. Some
40 ;; just need doing, e.g. catching exceptions in the inferior Python
41 ;; buffer (but see M-x pdb for debugging). [Actually, the use of
42 ;; `compilation-shell-minor-mode' now is probably enough for that.]
43 ;; Others don't seem appropriate. For instance,
44 ;; `forward-into-nomenclature' should be done separately, since it's
45 ;; not specific to Python, and I've installed a minor mode to do the
46 ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
47 ;; feature, `subword-mode' which is intended to have a similar
48 ;; effect, but actually only affects word-oriented keybindings.]
50 ;; Other things seem more natural or canonical here, e.g. the
51 ;; {beginning,end}-of-defun implementation dealing with nested
52 ;; definitions, and the inferior mode following `cmuscheme'. (The
53 ;; inferior mode can find the source of errors from
54 ;; `python-send-region' & al via `compilation-shell-minor-mode'.)
55 ;; There is (limited) symbol completion using lookup in Python and
56 ;; Eldoc support also using the inferior process. Successive TABs
57 ;; cycle between possible indentations for the line.
59 ;; Even where it has similar facilities, this mode is incompatible
60 ;; with python-mode.el in some respects. For instance, various key
61 ;; bindings are changed to obey Emacs conventions.
63 ;; TODO: See various Fixmes below.
65 ;; Fixme: This doesn't support (the nascent) Python 3 .
73 (require 'hippie-exp))
75 (autoload 'comint-mode "comint")
78 "Silly walks in the Python language."
81 :link '(emacs-commentary-link "python"))
84 (add-to-list 'interpreter-mode-alist (cons (purecopy "jython") 'jython-mode))
86 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
88 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
92 (defvar python-font-lock-keywords
94 ;; From v 2.7 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"
105 (,(rx symbol-start "None" symbol-end) ; see § Keywords in 2.7 manual
106 . font-lock-constant-face)
108 (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
109 (1 font-lock-keyword-face) (2 font-lock-type-face))
110 (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
111 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
112 ;; Top-level assignments are worth highlighting.
113 (,(rx line-start (group (1+ (or word ?_))) (0+ space)
114 (opt (or "+" "-" "*" "**" "/" "//" "&" "%" "|" "^" "<<" ">>")) "=")
115 (1 font-lock-variable-name-face))
117 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
118 (0+ "." (1+ (or word ?_)))))
119 (1 font-lock-type-face))
120 ;; Built-ins. (The next three blocks are from
121 ;; `__builtin__.__dict__.keys()' in Python 2.7) These patterns
122 ;; are debatable, but they at least help to spot possible
123 ;; shadowing of builtins.
124 (,(rx symbol-start (or
126 "ArithmeticError" "AssertionError" "AttributeError"
127 "BaseException" "DeprecationWarning" "EOFError"
128 "EnvironmentError" "Exception" "FloatingPointError"
129 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
130 "ImportWarning" "IndentationError" "IndexError" "KeyError"
131 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
132 "NotImplemented" "NotImplementedError" "OSError"
133 "OverflowError" "PendingDeprecationWarning" "ReferenceError"
134 "RuntimeError" "RuntimeWarning" "StandardError"
135 "StopIteration" "SyntaxError" "SyntaxWarning" "SystemError"
136 "SystemExit" "TabError" "TypeError" "UnboundLocalError"
137 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
138 "UnicodeTranslateError" "UnicodeWarning" "UserWarning"
139 "ValueError" "Warning" "ZeroDivisionError"
141 "BufferError" "BytesWarning" "WindowsError") symbol-end)
142 . font-lock-type-face)
143 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
145 ;; callable built-ins, fontified when not appearing as
147 "abs" "all" "any" "apply" "basestring" "bool" "buffer" "callable"
148 "chr" "classmethod" "cmp" "coerce" "compile" "complex"
149 "copyright" "credits" "delattr" "dict" "dir" "divmod"
150 "enumerate" "eval" "execfile" "exit" "file" "filter" "float"
151 "frozenset" "getattr" "globals" "hasattr" "hash" "help"
152 "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
153 "iter" "len" "license" "list" "locals" "long" "map" "max"
154 "min" "object" "oct" "open" "ord" "pow" "property" "quit"
155 "range" "raw_input" "reduce" "reload" "repr" "reversed"
156 "round" "set" "setattr" "slice" "sorted" "staticmethod"
157 "str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars"
160 "bin" "bytearray" "bytes" "format" "memoryview" "next" "print"
162 (1 font-lock-builtin-face))
163 (,(rx symbol-start (or
165 "True" "False" "None" "Ellipsis"
166 "_" "__debug__" "__doc__" "__import__" "__name__" "__package__")
168 . font-lock-builtin-face)))
170 (defconst python-syntax-propertize-function
171 ;; Make outer chars of matching triple-quote sequences into generic
172 ;; string delimiters. Fixme: Is there a better way?
173 ;; First avoid a sequence preceded by an odd number of backslashes.
174 (syntax-propertize-rules
175 (;; ¡Backrefs don't work in syntax-propertize-rules!
176 (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
177 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
178 (3 (ignore (python-quote-syntax))))
179 ;; This doesn't really help.
180 ;;((rx (and ?\\ (group ?\n))) (1 " "))
183 (defun python-quote-syntax ()
184 "Put `syntax-table' property correctly on triple quote.
185 Used for syntactic keywords. N is the match number (1, 2 or 3)."
186 ;; Given a triple quote, we have to check the context to know
187 ;; whether this is an opening or closing triple or whether it's
188 ;; quoted anyhow, and should be ignored. (For that we need to do
189 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
190 ;; to use it here despite initial worries.) We also have to sort
191 ;; out a possible prefix -- well, we don't _have_ to, but I think it
192 ;; should be treated as part of the string.
195 ;; ur"""ar""" x='"' # """
198 ;; x '"""' x """ \"""" x
200 (goto-char (match-beginning 0))
201 (let ((syntax (save-match-data (syntax-ppss))))
203 ((eq t (nth 3 syntax)) ; after unclosed fence
204 ;; Consider property for the last char if in a fenced string.
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 (put-text-property (match-beginning 3) (match-end 3)
210 'syntax-table (string-to-syntax "|"))))
212 ;; Consider property for initial char, accounting for prefixes.
213 (put-text-property (match-beginning 1) (match-end 1)
214 'syntax-table (string-to-syntax "|")))
216 ;; Consider property for initial char, accounting for prefixes.
217 (put-text-property (match-beginning 2) (match-end 2)
218 'syntax-table (string-to-syntax "|"))))
221 ;; This isn't currently in `font-lock-defaults' as probably not worth
222 ;; it -- we basically only mess with a few normally-symbol characters.
224 ;; (defun python-font-lock-syntactic-face-function (state)
225 ;; "`font-lock-syntactic-face-function' for Python mode.
226 ;; Returns the string or comment face as usual, with side effect of putting
227 ;; a `syntax-table' property on the inside of the string or comment which is
228 ;; the standard syntax table."
231 ;; (goto-char (nth 8 state))
232 ;; (condition-case nil
235 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
236 ;; 'syntax-table (standard-syntax-table))
237 ;; 'font-lock-string-face)
238 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
239 ;; 'syntax-table (standard-syntax-table))
240 ;; 'font-lock-comment-face))
242 ;;;; Keymap and syntax
244 (defvar python-mode-map
245 (let ((map (make-sparse-keymap)))
246 ;; Mostly taken from python-mode.el.
247 (define-key map ":" 'python-electric-colon)
248 (define-key map "\177" 'python-backspace)
249 (define-key map "\C-c<" 'python-shift-left)
250 (define-key map "\C-c>" 'python-shift-right)
251 (define-key map "\C-c\C-k" 'python-mark-block)
252 (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking)
253 (define-key map "\C-c\C-n" 'python-next-statement)
254 (define-key map "\C-c\C-p" 'python-previous-statement)
255 (define-key map "\C-c\C-u" 'python-beginning-of-block)
256 (define-key map "\C-c\C-f" 'python-describe-symbol)
257 (define-key map "\C-c\C-w" 'python-check)
258 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
259 (define-key map "\C-c\C-s" 'python-send-string)
260 (define-key map [?\C-\M-x] 'python-send-defun)
261 (define-key map "\C-c\C-r" 'python-send-region)
262 (define-key map "\C-c\M-r" 'python-send-region-and-go)
263 (define-key map "\C-c\C-c" 'python-send-buffer)
264 (define-key map "\C-c\C-z" 'python-switch-to-python)
265 (define-key map "\C-c\C-m" 'python-load-file)
266 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
267 (substitute-key-definition 'complete-symbol 'completion-at-point
269 (define-key map "\C-c\C-i" 'python-find-imports)
270 (define-key map "\C-c\C-t" 'python-expand-template)
271 (easy-menu-define python-menu map "Python Mode menu"
273 :help "Python-specific Features"
274 ["Shift region left" python-shift-left :active mark-active
275 :help "Shift by a single indentation step"]
276 ["Shift region right" python-shift-right :active mark-active
277 :help "Shift by a single indentation step"]
279 ["Mark block" python-mark-block
280 :help "Mark innermost block around point"]
281 ["Mark def/class" mark-defun
282 :help "Mark innermost definition around point"]
284 ["Start of block" python-beginning-of-block
285 :help "Go to start of innermost definition around point"]
286 ["End of block" python-end-of-block
287 :help "Go to end of innermost definition around point"]
288 ["Start of def/class" beginning-of-defun
289 :help "Go to start of innermost definition around point"]
290 ["End of def/class" end-of-defun
291 :help "Go to end of innermost definition around point"]
294 :help "Expand templates for compound statements"
295 :filter (lambda (&rest junk)
296 (abbrev-table-menu python-mode-abbrev-table)))
298 ["Start interpreter" run-python
299 :help "Run `inferior' Python in separate buffer"]
300 ["Import/reload file" python-load-file
301 :help "Load into inferior Python session"]
302 ["Eval buffer" python-send-buffer
303 :help "Evaluate buffer en bloc in inferior Python session"]
304 ["Eval region" python-send-region :active mark-active
305 :help "Evaluate region en bloc in inferior Python session"]
306 ["Eval def/class" python-send-defun
307 :help "Evaluate current definition in inferior Python session"]
308 ["Switch to interpreter" python-switch-to-python
309 :help "Switch to inferior Python buffer"]
310 ["Set default process" python-set-proc
311 :help "Make buffer's inferior process the default"
312 :active (buffer-live-p python-buffer)]
313 ["Check file" python-check :help "Run pychecker"]
314 ["Debugger" pdb :help "Run pdb under GUD"]
316 ["Help on symbol" python-describe-symbol
317 :help "Use pydoc on symbol at point"]
318 ["Complete symbol" completion-at-point
319 :help "Complete (qualified) symbol before point"]
320 ["Find function" python-find-function
321 :help "Try to find source definition of function at point"]
322 ["Update imports" python-find-imports
323 :help "Update list of top-level imports for completion"]))
325 ;; Fixme: add toolbar stuff for useful things like symbol help, send
326 ;; region, at least. (Shouldn't be specific to Python, obviously.)
327 ;; eric has items including: (un)indent, (un)comment, restart script,
328 ;; run script, debug script; also things for profiling, unit testing.
330 (defvar python-mode-syntax-table
331 (let ((table (make-syntax-table)))
332 ;; Give punctuation syntax to ASCII that normally has symbol
333 ;; syntax or has word syntax and isn't a letter.
334 (let ((symbol (string-to-syntax "_"))
335 (sst (standard-syntax-table)))
338 (if (equal symbol (aref sst i))
339 (modify-syntax-entry i "." table)))))
340 (modify-syntax-entry ?$ "." table)
341 (modify-syntax-entry ?% "." table)
343 (modify-syntax-entry ?# "<" table)
344 (modify-syntax-entry ?\n ">" table)
345 (modify-syntax-entry ?' "\"" table)
346 (modify-syntax-entry ?` "$" table)
351 (defsubst python-in-string/comment ()
352 "Return non-nil if point is in a Python literal (a comment or string)."
353 ;; We don't need to save the match data.
354 (nth 8 (syntax-ppss)))
356 (defconst python-space-backslash-table
357 (let ((table (copy-syntax-table python-mode-syntax-table)))
358 (modify-syntax-entry ?\\ " " table)
360 "`python-mode-syntax-table' with backslash given whitespace syntax.")
362 (defun python-skip-comments/blanks (&optional backward)
363 "Skip comments and blank lines.
364 BACKWARD non-nil means go backwards, otherwise go forwards.
365 Backslash is treated as whitespace so that continued blank lines
366 are skipped. Doesn't move out of comments -- should be outside
368 (let ((arg (if backward
369 ;; If we're in a comment (including on the trailing
370 ;; newline), forward-comment doesn't move backwards out
371 ;; of it. Don't set the syntax table round this bit!
372 (let ((syntax (syntax-ppss)))
374 (goto-char (nth 8 syntax)))
377 (with-syntax-table python-space-backslash-table
378 (forward-comment arg))))
380 (defun python-backslash-continuation-line-p ()
381 "Non-nil if preceding line ends with backslash that is not in a comment."
382 (and (eq ?\\ (char-before (line-end-position 0)))
383 (not (syntax-ppss-context (syntax-ppss)))))
385 (defun python-continuation-line-p ()
386 "Return non-nil if current line continues a previous one.
387 The criteria are that the previous line ends in a backslash outside
388 comments and strings, or that point is within brackets/parens."
389 (or (python-backslash-continuation-line-p)
390 (let ((depth (syntax-ppss-depth
391 (save-excursion ; syntax-ppss with arg changes point
392 (syntax-ppss (line-beginning-position))))))
394 (if (< depth 0) ; Unbalanced brackets -- act locally
397 (progn (backward-up-list) t) ; actually within brackets
400 (defun python-comment-line-p ()
401 "Return non-nil if and only if current line has only a comment."
404 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
405 (back-to-indentation)
406 (looking-at (rx (or (syntax comment-start) line-end))))))
408 (defun python-blank-line-p ()
409 "Return non-nil if and only if current line is blank."
412 (looking-at "\\s-*$")))
414 (defun python-beginning-of-string ()
415 "Go to beginning of string around point.
416 Do nothing if not in string."
417 (let ((state (syntax-ppss)))
418 (when (eq 'string (syntax-ppss-context state))
419 (goto-char (nth 8 state)))))
421 (defun python-open-block-statement-p (&optional bos)
422 "Return non-nil if statement at point opens a block.
423 BOS non-nil means point is known to be at beginning of statement."
425 (unless bos (python-beginning-of-statement))
426 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
427 "class" "try" "except" "finally" "with")
430 (defun python-close-block-statement-p (&optional bos)
431 "Return non-nil if current line is a statement closing a block.
432 BOS non-nil means point is at beginning of statement.
433 The criteria are that the line isn't a comment or in string and
434 starts with keyword `raise', `break', `continue' or `pass'."
436 (unless bos (python-beginning-of-statement))
437 (back-to-indentation)
438 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
441 (defun python-outdent-p ()
442 "Return non-nil if current line should outdent a level."
444 (back-to-indentation)
445 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
447 (not (python-in-string/comment))
448 ;; Ensure there's a previous statement and move to it.
449 (zerop (python-previous-statement))
450 (not (python-close-block-statement-p t))
452 (not (python-open-block-statement-p)))))
456 (defcustom python-indent 4
457 "Number of columns for a unit of indentation in Python mode.
458 See also `\\[python-guess-indent]'"
461 (put 'python-indent 'safe-local-variable 'integerp)
463 (defcustom python-guess-indent t
464 "Non-nil means Python mode guesses `python-indent' for the buffer."
468 (defcustom python-indent-string-contents t
469 "Non-nil means indent contents of multi-line strings together.
470 This means indent them the same as the preceding non-blank line.
471 Otherwise preserve their indentation.
473 This only applies to `doc' strings, i.e. those that form statements;
474 the indentation is preserved in others."
475 :type '(choice (const :tag "Align with preceding" t)
476 (const :tag "Preserve indentation" nil))
479 (defcustom python-honour-comment-indentation nil
480 "Non-nil means indent relative to preceding comment line.
481 Only do this for comments where the leading comment character is
482 followed by space. This doesn't apply to comment lines, which
483 are always indented in lines with preceding comments."
487 (defcustom python-continuation-offset 4
488 "Number of columns of additional indentation for continuation lines.
489 Continuation lines follow a backslash-terminated line starting a
495 (defcustom python-pdbtrack-do-tracking-p t
496 "*Controls whether the pdbtrack feature is enabled or not.
498 When non-nil, pdbtrack is enabled in all comint-based buffers,
499 e.g. shell interaction buffers and the *Python* buffer.
501 When using pdb to debug a Python program, pdbtrack notices the
502 pdb prompt and presents the line in the source file where the
503 program is stopped in a pop-up buffer. It's similar to what
504 gud-mode does for debugging C programs with gdb, but without
505 having to restart the program."
508 (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
510 (defcustom python-pdbtrack-minor-mode-string " PDB"
511 "*Minor-mode sign to be displayed when pdbtrack is active."
515 ;; Add a designator to the minor mode strings
516 (or (assq 'python-pdbtrack-is-tracking-p minor-mode-alist)
517 (push '(python-pdbtrack-is-tracking-p python-pdbtrack-minor-mode-string)
520 (defcustom python-shell-prompt-alist
521 '(("ipython" . "^In \\[[0-9]+\\]: *")
523 "Alist of Python input prompts.
524 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
525 the value of `python-python-command' for the python process and
526 REGEXP is a regular expression matching the Python prompt.
527 PROGRAM can also be t, which specifies the default when no other
528 element matches `python-python-command'."
533 (defcustom python-shell-continuation-prompt-alist
534 '(("ipython" . "^ [.][.][.]+: *")
536 "Alist of Python continued-line prompts.
537 Each element has the form (PROGRAM . REGEXP), where PROGRAM is
538 the value of `python-python-command' for the python process and
539 REGEXP is a regular expression matching the Python prompt for
541 PROGRAM can also be t, which specifies the default when no other
542 element matches `python-python-command'."
547 (defvar python-pdbtrack-is-tracking-p nil)
549 (defconst python-pdbtrack-stack-entry-regexp
550 "^> \\(.*\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
551 "Regular expression pdbtrack uses to find a stack trace entry.")
553 (defconst python-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]db[>)]+ "
554 "Regular expression pdbtrack uses to recognize a pdb prompt.")
556 (defconst python-pdbtrack-track-range 10000
557 "Max number of characters from end of buffer to search for stack entry.")
559 (defun python-guess-indent ()
560 "Guess step for indentation of current buffer.
561 Set `python-indent' locally to the value guessed."
566 (goto-char (point-min))
568 (while (and (not done) (not (eobp)))
569 (when (and (re-search-forward (rx ?: (0+ space)
570 (or (syntax comment-start)
573 (python-open-block-statement-p))
575 (python-beginning-of-statement)
576 (let ((initial (current-indentation)))
577 (if (zerop (python-next-statement))
578 (setq indent (- (current-indentation) initial)))
579 (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
582 (when (/= indent (default-value 'python-indent))
583 (set (make-local-variable 'python-indent) indent)
584 (unless (= tab-width python-indent)
585 (setq indent-tabs-mode nil)))
588 ;; Alist of possible indentations and start of statement they would
589 ;; close. Used in indentation cycling (below).
590 (defvar python-indent-list nil
592 ;; Length of the above
593 (defvar python-indent-list-length nil
595 ;; Current index into the alist.
596 (defvar python-indent-index nil
599 (defun python-calculate-indentation ()
600 "Calculate Python indentation for line at point."
601 (setq python-indent-list nil
602 python-indent-list-length 1)
605 (let ((syntax (syntax-ppss))
608 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
609 (if (not python-indent-string-contents)
610 (current-indentation)
611 ;; Only respect `python-indent-string-contents' in doc
612 ;; strings (defined as those which form statements).
613 (if (not (save-excursion
614 (python-beginning-of-statement)
615 (looking-at (rx (or (syntax string-delimiter)
616 (syntax string-quote))))))
617 (current-indentation)
618 ;; Find indentation of preceding non-blank line within string.
619 (setq start (nth 8 syntax))
621 (while (and (< start (point)) (looking-at "\\s-*$"))
623 (current-indentation))))
624 ((python-continuation-line-p) ; after backslash, or bracketed
625 (let ((point (point))
626 (open-start (cadr syntax))
627 (backslash (python-backslash-continuation-line-p))
628 (colon (eq ?: (char-before (1- (line-beginning-position))))))
630 ;; Inside bracketed expression.
632 (goto-char (1+ open-start))
633 ;; Look for first item in list (preceding point) and
634 ;; align with it, if found.
635 (if (with-syntax-table python-space-backslash-table
636 (let ((parse-sexp-ignore-comments t))
638 (progn (forward-sexp)
642 ;; Extra level if we're backslash-continued or
644 (if (or backslash colon)
645 (+ python-indent (current-column))
647 ;; Otherwise indent relative to statement start, one
648 ;; level per bracketing level.
649 (goto-char (1+ open-start))
650 (python-beginning-of-statement)
651 (+ (current-indentation) (* (car syntax) python-indent))))
652 ;; Otherwise backslash-continued.
654 (if (python-continuation-line-p)
655 ;; We're past first continuation line. Align with
657 (current-indentation)
658 ;; First continuation line. Indent one step, with an
659 ;; extra one if statement opens a block.
660 (python-beginning-of-statement)
661 (+ (current-indentation) python-continuation-offset
662 (if (python-open-block-statement-p t)
666 ;; Fixme: Like python-mode.el; not convinced by this.
667 ((looking-at (rx (0+ space) (syntax comment-start)
668 (not (any " \t\n")))) ; non-indentable comment
669 (current-indentation))
670 ((and python-honour-comment-indentation
671 ;; Back over whitespace, newlines, non-indentable comments.
673 (while (cond ((bobp) nil)
674 ((not (forward-comment -1))
675 nil) ; not at comment start
676 ;; Now at start of comment -- trailing one?
677 ((/= (current-column) (current-indentation))
679 ;; Indentable comment, like python-mode.el?
680 ((and (looking-at (rx (syntax comment-start)
681 (or space line-end)))
682 (/= 0 (current-column)))
683 (throw 'done (current-column)))
684 ;; Else skip it (loop).
687 (python-indentation-levels)
688 ;; Prefer to indent comments with an immediately-following
693 (when (and (> python-indent-list-length 1)
694 (python-comment-line-p))
696 (unless (python-comment-line-p)
697 (let ((elt (assq (current-indentation) python-indent-list)))
698 (setq python-indent-list
699 (nconc (delete elt python-indent-list)
701 (caar (last python-indent-list)))))))
703 ;;;; Cycling through the possible indentations with successive TABs.
705 ;; These don't need to be buffer-local since they're only relevant
708 (defun python-initial-text ()
709 "Text of line following indentation and ignoring any trailing comment."
711 (buffer-substring (progn
712 (back-to-indentation)
719 (defconst python-block-pairs
720 '(("else" "if" "elif" "while" "for" "try" "except")
722 ("except" "try" "except")
723 ("finally" "else" "try" "except"))
724 "Alist of keyword matches.
725 The car of an element is a keyword introducing a statement which
726 can close a block opened by a keyword in the cdr.")
728 (defun python-first-word ()
729 "Return first word (actually symbol) on the line."
731 (back-to-indentation)
734 (defun python-indentation-levels ()
735 "Return a list of possible indentations for this line.
736 It is assumed not to be a continuation line or in a multi-line string.
737 Includes the default indentation and those which would close all
738 enclosing blocks. Elements of the list are actually pairs:
739 \(INDENTATION . TEXT), where TEXT is the initial text of the
740 corresponding block opening (or nil)."
744 ;; Only one possibility immediately following a block open
745 ;; statement, assuming it doesn't have a `suite' on the same line.
747 ((save-excursion (and (python-previous-statement)
748 (python-open-block-statement-p t)
749 (setq indent (current-indentation))
750 ;; Check we don't have something like:
752 (if (progn (python-end-of-statement)
753 (python-skip-comments/blanks t)
754 (eq ?: (char-before)))
755 (setq indent (+ python-indent indent)))))
756 (push (cons indent initial) levels))
757 ;; Only one possibility for comment line immediately following
760 (when (python-comment-line-p)
762 (if (python-comment-line-p)
763 (push (cons (current-indentation) initial) levels)))))
764 ;; Fixme: Maybe have a case here which indents (only) first
765 ;; line after a lambda.
767 (let ((start (car (assoc (python-first-word) python-block-pairs))))
768 (python-previous-statement)
769 ;; Is this a valid indentation for the line of interest?
770 (unless (or (if start ; potentially only outdentable
771 ;; Check for things like:
774 ;; where the second line need not be outdented.
775 (not (member (python-first-word)
777 python-block-pairs)))))
778 ;; Not sensible to indent to the same level as
779 ;; previous `return' &c.
780 (python-close-block-statement-p))
781 (push (cons (current-indentation) (python-initial-text))
783 (while (python-beginning-of-block)
784 (when (or (not start)
785 (member (python-first-word)
786 (cdr (assoc start python-block-pairs))))
787 (push (cons (current-indentation) (python-initial-text))
789 (prog1 (or levels (setq levels '((0 . ""))))
790 (setq python-indent-list levels
791 python-indent-list-length (length python-indent-list))))))
793 ;; This is basically what `python-indent-line' would be if we didn't
795 (defun python-indent-line-1 (&optional leave)
796 "Subroutine of `python-indent-line'.
797 Does non-repeated indentation. LEAVE non-nil means leave
798 indentation if it is valid, i.e. one of the positions returned by
799 `python-calculate-indentation'."
800 (let ((target (python-calculate-indentation))
801 (pos (- (point-max) (point))))
802 (if (or (= target (current-indentation))
803 ;; Maybe keep a valid indentation.
804 (and leave python-indent-list
805 (assq (current-indentation) python-indent-list)))
806 (if (< (current-column) (current-indentation))
807 (back-to-indentation))
809 (delete-horizontal-space)
811 (if (> (- (point-max) pos) (point))
812 (goto-char (- (point-max) pos))))))
814 (defun python-indent-line ()
815 "Indent current line as Python code.
816 When invoked via `indent-for-tab-command', cycle through possible
817 indentations for current line. The cycle is broken by a command
818 different from `indent-for-tab-command', i.e. successive TABs do
821 (if (and (eq this-command 'indent-for-tab-command)
822 (eq last-command this-command))
823 (if (= 1 python-indent-list-length)
824 (message "Sole indentation")
825 (progn (setq python-indent-index
826 (% (1+ python-indent-index) python-indent-list-length))
828 (delete-horizontal-space)
829 (indent-to (car (nth python-indent-index python-indent-list)))
830 (if (python-block-end-p)
831 (let ((text (cdr (nth python-indent-index
832 python-indent-list))))
834 (message "Closes: %s" text))))))
835 (python-indent-line-1)
836 (setq python-indent-index (1- python-indent-list-length))))
838 (defun python-indent-region (start end)
839 "`indent-region-function' for Python.
840 Leaves validly-indented lines alone, i.e. doesn't indent to
841 another valid position."
844 (setq end (point-marker))
846 (or (bolp) (forward-line 1))
847 (while (< (point) end)
848 (or (and (bolp) (eolp))
849 (python-indent-line-1 t))
851 (move-marker end nil)))
853 (defun python-block-end-p ()
854 "Non-nil if this is a line in a statement closing a block,
855 or a blank line indented to where it would close a block."
856 (and (not (python-comment-line-p))
857 (or (python-close-block-statement-p t)
858 (< (current-indentation)
860 (python-previous-statement)
861 (current-indentation))))))
865 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
866 ;; block, statement, depending on context.
868 (defun python-beginning-of-defun ()
869 "`beginning-of-defun-function' for Python.
870 Finds beginning of innermost nested class or method definition.
871 Returns the name of the definition found at the end, or nil if
872 reached start of buffer."
873 (let ((ci (current-indentation))
874 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
875 (group (1+ (or word (syntax symbol))))))
876 found lep) ;; def-line
877 (if (python-comment-line-p)
878 (setq ci most-positive-fixnum))
879 (while (and (not (bobp)) (not found))
880 ;; Treat bol at beginning of function as outside function so
881 ;; that successive C-M-a makes progress backwards.
882 ;;(setq def-line (looking-at def-re))
883 (unless (bolp) (end-of-line))
884 (setq lep (line-end-position))
885 (if (and (re-search-backward def-re nil 'move)
886 ;; Must be less indented or matching top level, or
887 ;; equally indented if we started on a definition line.
888 (let ((in (current-indentation)))
889 (or (and (zerop ci) (zerop in))
890 (= lep (line-end-position)) ; on initial line
891 ;; Not sure why it was like this -- fails in case of
892 ;; last internal function followed by first
893 ;; non-def statement of the main body.
894 ;; (and def-line (= in ci))
897 (not (python-in-string/comment)))
901 (defun python-end-of-defun ()
902 "`end-of-defun-function' for Python.
903 Finds end of innermost nested class or method definition."
905 (pattern (rx line-start (0+ space) (or "def" "class") space)))
906 ;; Go to start of current block and check whether it's at top
907 ;; level. If it is, and not a block start, look forward for
908 ;; definition statement.
909 (when (python-comment-line-p)
911 (forward-comment most-positive-fixnum))
912 (if (not (python-open-block-statement-p))
913 (python-beginning-of-block))
914 (if (zerop (current-indentation))
915 (unless (python-open-block-statement-p)
916 (while (and (re-search-forward pattern nil 'move)
917 (python-in-string/comment))) ; just loop
919 (beginning-of-line)))
920 ;; Don't move before top-level statement that would end defun.
922 (python-beginning-of-defun))
923 ;; If we got to the start of buffer, look forward for
924 ;; definition statement.
925 (if (and (bobp) (not (looking-at "def\\|class")))
926 (while (and (not (eobp))
927 (re-search-forward pattern nil 'move)
928 (python-in-string/comment)))) ; just loop
929 ;; We're at a definition statement (or end-of-buffer).
931 (python-end-of-block)
932 ;; Count trailing space in defun (but not trailing comments).
933 (skip-syntax-forward " >")
934 (unless (eobp) ; e.g. missing final newline
935 (beginning-of-line)))
936 ;; Catch pathological cases like this, where the beginning-of-defun
937 ;; skips to a definition we're not in:
945 (goto-char (point-max)))))
947 (defun python-beginning-of-statement ()
948 "Go to start of current statement.
949 Accounts for continuation lines, multi-line strings, and
950 multi-line bracketed expressions."
952 (if (python-backslash-continuation-line-p)
953 (progn (forward-line -1) t)
955 (or (python-beginning-of-string)
957 (back-to-indentation))
959 (defun python-skip-out (&optional forward syntax)
960 "Skip out of any nested brackets.
961 Skip forward if FORWARD is non-nil, else backward.
962 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
963 Return non-nil if and only if skipping was done."
964 ;; FIXME: Use syntax-ppss-toplevel-pos.
965 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
966 (forward (if forward -1 1)))
967 (unless (zerop depth)
969 ;; Skip forward out of nested brackets.
970 (condition-case () ; beware invalid syntax
971 (progn (backward-up-list (* forward depth)) t)
973 ;; Invalid syntax (too many closed brackets).
974 ;; Skip out of as many as possible.
976 (while (condition-case ()
977 (progn (backward-up-list forward)
982 (defun python-end-of-statement ()
983 "Go to the end of the current statement and return point.
984 Usually this is the start of the next line, but if this is a
985 multi-line statement we need to skip over the continuation lines.
986 On a comment line, go to end of line."
988 (while (let (comment)
989 ;; Move past any enclosing strings and sexps, or stop if
990 ;; we're in a comment.
991 (while (let ((s (syntax-ppss)))
992 (cond ((eq 'comment (syntax-ppss-context s))
995 ((eq 'string (syntax-ppss-context s))
996 ;; Go to start of string and skip it.
998 (goto-char (nth 8 s))
999 (condition-case () ; beware invalid syntax
1000 (progn (forward-sexp) t)
1001 ;; If there's a mismatched string, make sure
1002 ;; we still overall move *forward*.
1003 (error (goto-char pos) (end-of-line)))))
1004 ((python-skip-out t s))))
1007 (eq ?\\ (char-before)))) ; Line continued?
1008 (end-of-line 2)) ; Try next line.
1011 (defun python-previous-statement (&optional count)
1012 "Go to start of previous statement.
1013 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
1014 Return count of statements left to move."
1016 (unless count (setq count 1))
1018 (python-next-statement (- count))
1019 (python-beginning-of-statement)
1020 (while (and (> count 0) (not (bobp)))
1021 (python-skip-comments/blanks t)
1022 (python-beginning-of-statement)
1023 (unless (bobp) (setq count (1- count))))
1026 (defun python-next-statement (&optional count)
1027 "Go to start of next statement.
1028 With argument COUNT, do it COUNT times. Stop at end of buffer.
1029 Return count of statements left to move."
1031 (unless count (setq count 1))
1033 (python-previous-statement (- count))
1036 (while (and (> count 0) (not (eobp)) (not bogus))
1037 (python-end-of-statement)
1038 (python-skip-comments/blanks)
1039 (if (eq 'string (syntax-ppss-context (syntax-ppss)))
1042 (setq count (1- count))))))
1045 (defun python-beginning-of-block (&optional arg)
1046 "Go to start of current block.
1047 With numeric arg, do it that many times. If ARG is negative, call
1048 `python-end-of-block' instead.
1049 If point is on the first line of a block, use its outer block.
1050 If current statement is in column zero, don't move and return nil.
1051 Otherwise return non-nil."
1053 (unless arg (setq arg 1))
1056 ((< arg 0) (python-end-of-block (- arg)))
1058 (let ((point (point)))
1059 (if (or (python-comment-line-p)
1060 (python-blank-line-p))
1061 (python-skip-comments/blanks t))
1062 (python-beginning-of-statement)
1063 (let ((ci (current-indentation)))
1065 (not (goto-char point)) ; return nil
1066 ;; Look upwards for less indented statement.
1068 ;;; This is slower than the below.
1069 ;;; (while (zerop (python-previous-statement))
1070 ;;; (when (and (< (current-indentation) ci)
1071 ;;; (python-open-block-statement-p t))
1072 ;;; (beginning-of-line)
1073 ;;; (throw 'done t)))
1074 (while (and (zerop (forward-line -1)))
1075 (when (and (< (current-indentation) ci)
1076 (not (python-comment-line-p))
1077 ;; Move to beginning to save effort in case
1078 ;; this is in string.
1079 (progn (python-beginning-of-statement) t)
1080 (python-open-block-statement-p t))
1083 (not (goto-char point))) ; Failed -- return nil
1084 (python-beginning-of-block (1- arg)))))))))
1086 (defun python-end-of-block (&optional arg)
1087 "Go to end of current block.
1088 With numeric arg, do it that many times. If ARG is negative,
1089 call `python-beginning-of-block' instead.
1090 If current statement is in column zero and doesn't open a block,
1091 don't move and return nil. Otherwise return t."
1093 (unless arg (setq arg 1))
1095 (python-beginning-of-block (- arg))
1096 (while (and (> arg 0)
1097 (let* ((point (point))
1098 (_ (if (python-comment-line-p)
1099 (python-skip-comments/blanks t)))
1100 (ci (current-indentation))
1101 (open (python-open-block-statement-p)))
1102 (if (and (zerop ci) (not open))
1103 (not (goto-char point))
1105 (while (zerop (python-next-statement))
1106 (when (or (and open (<= (current-indentation) ci))
1107 (< (current-indentation) ci))
1108 (python-skip-comments/blanks t)
1109 (beginning-of-line 2)
1110 (throw 'done t)))))))
1111 (setq arg (1- arg)))
1114 (defvar python-which-func-length-limit 40
1115 "Non-strict length limit for `python-which-func' output.")
1117 (defun python-which-func ()
1118 (let ((function-name (python-current-defun python-which-func-length-limit)))
1119 (set-text-properties 0 (length function-name) nil function-name)
1125 ;; For possibly speeding this up, here's the top of the ELP profile
1126 ;; for rescanning pydoc.py (2.2k lines, 90kb):
1127 ;; Function Name Call Count Elapsed Time Average Time
1128 ;; ==================================== ========== ============= ============
1129 ;; python-imenu-create-index 156 2.430906 0.0155827307
1130 ;; python-end-of-defun 155 1.2718260000 0.0082053290
1131 ;; python-end-of-block 155 1.1898689999 0.0076765741
1132 ;; python-next-statement 2970 1.024717 0.0003450225
1133 ;; python-end-of-statement 2970 0.4332190000 0.0001458649
1134 ;; python-beginning-of-defun 265 0.0918479999 0.0003465962
1135 ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05
1137 (defvar python-recursing)
1138 (defun python-imenu-create-index ()
1139 "`imenu-create-index-function' for Python.
1141 Makes nested Imenu menus from nested `class' and `def' statements.
1142 The nested menus are headed by an item referencing the outer
1143 definition; it has a space prepended to the name so that it sorts
1144 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1146 (unless (boundp 'python-recursing) ; dynamically bound below
1147 ;; Normal call from Imenu.
1148 (goto-char (point-min))
1149 ;; Without this, we can get an infloop if the buffer isn't all
1150 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1151 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1152 ;; what's going on, but it must be something to do with timers in
1154 ;; This can't be right, especially not when jit-lock is not used. --Stef
1155 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1156 ;; (font-lock-fontify-region (point-min) (point-max)))
1158 (let (index-alist) ; accumulated value to return
1159 (while (re-search-forward
1160 (rx line-start (0+ space) ; leading space
1161 (or (group "def") (group "class")) ; type
1162 (1+ space) (group (1+ (or word ?_)))) ; name
1164 (unless (python-in-string/comment)
1165 (let ((pos (match-beginning 0))
1166 (name (match-string-no-properties 3)))
1167 (if (match-beginning 2) ; def or class?
1168 (setq name (concat "class " name)))
1171 (let* ((python-recursing t)
1172 (sublist (python-imenu-create-index)))
1174 (progn (push (cons (concat " " name) pos) sublist)
1175 (push (cons name sublist) index-alist))
1176 (push (cons name pos) index-alist)))))))
1177 (unless (boundp 'python-recursing)
1178 ;; Look for module variables.
1180 (goto-char (point-min))
1181 (while (re-search-forward
1182 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1184 (unless (python-in-string/comment)
1185 (push (cons (match-string 1) (match-beginning 1))
1187 (setq index-alist (nreverse index-alist))
1189 (push (cons "Module variables"
1194 ;;;; `Electric' commands.
1196 (defun python-electric-colon (arg)
1197 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1198 With numeric ARG, just insert that many colons. With \\[universal-argument],
1199 just insert a single colon."
1201 (self-insert-command (if (not (integerp arg)) 1 arg))
1205 (not (python-in-string/comment))
1206 (> (current-indentation) (python-calculate-indentation))
1207 (python-indent-line))) ; OK, do it
1208 (put 'python-electric-colon 'delete-selection t)
1210 (defun python-backspace (arg)
1211 "Maybe delete a level of indentation on the current line.
1212 Do so if point is at the end of the line's indentation outside
1213 strings and comments.
1214 Otherwise just call `backward-delete-char-untabify'.
1217 (if (or (/= (current-indentation) (current-column))
1219 (python-continuation-line-p)
1220 (python-in-string/comment))
1221 (backward-delete-char-untabify arg)
1222 ;; Look for the largest valid indentation which is smaller than
1223 ;; the current indentation.
1225 (ci (current-indentation))
1226 (indents (python-indentation-levels))
1230 (setq indent (max indent (car x)))))
1231 (setq initial (cdr (assq indent indents)))
1232 (if (> (length initial) 0)
1233 (message "Closes %s" initial))
1234 (delete-horizontal-space)
1235 (indent-to indent))))
1236 (put 'python-backspace 'delete-selection 'supersede)
1240 (defcustom python-check-command "pychecker --stdlib"
1241 "Command used to check a Python file."
1245 (defvar python-saved-check-command nil
1248 ;; After `sgml-validate-command'.
1249 (defun python-check (command)
1250 "Check a Python file (default current buffer's file).
1251 Runs COMMAND, a shell command, as if by `compile'.
1252 See `python-check-command' for the default."
1254 (list (read-string "Checker command: "
1255 (or python-saved-check-command
1256 (concat python-check-command " "
1257 (let ((name (buffer-file-name)))
1259 (file-name-nondirectory name))))))))
1260 (set (make-local-variable 'python-saved-check-command) command)
1261 (require 'compile) ;To define compilation-* variables.
1262 (save-some-buffers (not compilation-ask-about-save) nil)
1263 (let ((compilation-error-regexp-alist
1264 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1265 compilation-error-regexp-alist)))
1266 (compilation-start command)))
1268 ;;;; Inferior mode stuff (following cmuscheme).
1270 (defcustom python-python-command "python"
1271 "Shell command to run Python interpreter.
1272 Any arguments can't contain whitespace."
1276 (defcustom python-jython-command "jython"
1277 "Shell command to run Jython interpreter.
1278 Any arguments can't contain whitespace."
1282 (defvar python-command python-python-command
1283 "Actual command used to run Python.
1284 May be `python-python-command' or `python-jython-command', possibly
1285 modified by the user. Additional arguments are added when the command
1286 is used by `run-python' et al.")
1288 (defvar python-buffer nil
1289 "*The current Python process buffer.
1291 Commands that send text from source buffers to Python processes have
1292 to choose a process to send to. This is determined by buffer-local
1293 value of `python-buffer'. If its value in the current buffer,
1294 i.e. both any local value and the default one, is nil, `run-python'
1295 and commands that send to the Python process will start a new process.
1297 Whenever \\[run-python] starts a new process, it resets the default
1298 value of `python-buffer' to be the new process's buffer and sets the
1299 buffer-local value similarly if the current buffer is in Python mode
1300 or Inferior Python mode, so that source buffer stays associated with a
1301 specific sub-process.
1303 Use \\[python-set-proc] to set the default value from a buffer with a
1305 (make-variable-buffer-local 'python-buffer)
1307 (defconst python-compilation-regexp-alist
1308 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1309 ;; The first already is (for CAML), but the second isn't. Anyhow,
1310 ;; these are specific to the inferior buffer. -- fx
1311 `((,(rx line-start (1+ (any " \t")) "File \""
1312 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1313 "\", line " (group (1+ digit)))
1315 (,(rx " in file " (group (1+ not-newline)) " on line "
1319 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1320 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1322 "`compilation-error-regexp-alist' for inferior Python.")
1324 (defvar inferior-python-mode-map
1325 (let ((map (make-sparse-keymap)))
1326 ;; This will inherit from comint-mode-map.
1327 (define-key map "\C-c\C-l" 'python-load-file)
1328 (define-key map "\C-c\C-v" 'python-check)
1329 ;; Note that we _can_ still use these commands which send to the
1330 ;; Python process even at the prompt if we have a normal prompt,
1331 ;; i.e. '>>> ' and not '... '. See the comment before
1332 ;; python-send-region. Fixme: uncomment these if we address that.
1334 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1335 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1338 (defvar inferior-python-mode-syntax-table
1339 (let ((st (make-syntax-table python-mode-syntax-table)))
1340 ;; Don't get confused by apostrophes in the process's output (e.g. if
1341 ;; you execute "help(os)").
1342 (modify-syntax-entry ?\' "." st)
1343 ;; Maybe we should do the same for double quotes?
1344 ;; (modify-syntax-entry ?\" "." st)
1348 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1350 (defvar python--prompt-regexp nil)
1352 (defun python--set-prompt-regexp ()
1353 (let ((prompt (cdr-safe (or (assoc python-python-command
1354 python-shell-prompt-alist)
1355 (assq t python-shell-prompt-alist))))
1356 (cprompt (cdr-safe (or (assoc python-python-command
1357 python-shell-continuation-prompt-alist)
1358 (assq t python-shell-continuation-prompt-alist)))))
1359 (set (make-local-variable 'comint-prompt-regexp)
1361 (mapconcat 'identity
1362 (delq nil (list prompt cprompt "^([Pp]db) "))
1365 (set (make-local-variable 'python--prompt-regexp) prompt)))
1367 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1368 ;; not sure how much: at least some keybindings, like C-c C-f;
1369 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1370 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1371 "Major mode for interacting with an inferior Python process.
1372 A Python process can be started with \\[run-python].
1374 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1377 You can send text to the inferior Python process from other buffers
1378 containing Python source.
1379 * \\[python-switch-to-python] switches the current buffer to the Python
1381 * \\[python-send-region] sends the current region to the Python process.
1382 * \\[python-send-region-and-go] switches to the Python process buffer
1383 after sending the text.
1384 For running multiple processes in multiple buffers, see `run-python' and
1387 \\{inferior-python-mode-map}"
1389 (require 'ansi-color) ; for ipython
1390 (setq mode-line-process '(":%s"))
1391 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1392 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1394 (python--set-prompt-regexp)
1395 (set (make-local-variable 'compilation-error-regexp-alist)
1396 python-compilation-regexp-alist)
1397 (compilation-shell-minor-mode 1))
1399 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1400 "Input matching this regexp is not saved on the history list.
1401 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1405 (defcustom python-remove-cwd-from-path t
1406 "Whether to allow loading of Python modules from the current directory.
1407 If this is non-nil, Emacs removes '' from sys.path when starting
1408 an inferior Python process. This is the default, for security
1409 reasons, as it is easy for the Python process to be started
1410 without the user's realization (e.g. to perform completion)."
1415 (defun python-input-filter (str)
1416 "`comint-input-filter' function for inferior Python.
1417 Don't save anything for STR matching `inferior-python-filter-regexp'."
1418 (not (string-match inferior-python-filter-regexp str)))
1420 ;; Fixme: Loses with quoted whitespace.
1421 (defun python-args-to-list (string)
1422 (let ((where (string-match "[ \t]" string)))
1423 (cond ((null where) (list string))
1425 (cons (substring string 0 where)
1426 (python-args-to-list (substring string (+ 1 where)))))
1427 (t (let ((pos (string-match "[^ \t]" string)))
1428 (if pos (python-args-to-list (substring string pos))))))))
1430 (defvar python-preoutput-result nil
1431 "Data from last `_emacs_out' line seen by the preoutput filter.")
1433 (defvar python-preoutput-continuation nil
1434 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1436 (defvar python-preoutput-leftover nil)
1437 (defvar python-preoutput-skip-next-prompt nil)
1439 ;; Using this stops us getting lines in the buffer like
1441 ;; Also look for (and delete) an `_emacs_ok' string and call
1442 ;; `python-preoutput-continuation' if we get it.
1443 (defun python-preoutput-filter (s)
1444 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1445 (when python-preoutput-leftover
1446 (setq s (concat python-preoutput-leftover s))
1447 (setq python-preoutput-leftover nil))
1450 ;; First process whole lines.
1451 (while (string-match "\n" s start)
1452 (let ((line (substring s start (setq start (match-end 0)))))
1453 ;; Skip prompt if needed.
1454 (when (and python-preoutput-skip-next-prompt
1455 (string-match comint-prompt-regexp line))
1456 (setq python-preoutput-skip-next-prompt nil)
1457 (setq line (substring line (match-end 0))))
1458 ;; Recognize special _emacs_out lines.
1459 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1460 (local-variable-p 'python-preoutput-result))
1462 (setq python-preoutput-result (match-string 1 line))
1463 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1464 (setq res (concat res line)))))
1465 ;; Then process the remaining partial line.
1466 (unless (zerop start) (setq s (substring s start)))
1467 (cond ((and (string-match comint-prompt-regexp s)
1468 ;; Drop this prompt if it follows an _emacs_out...
1469 (or python-preoutput-skip-next-prompt
1470 ;; ... or if it's not gonna be inserted at BOL.
1471 ;; Maybe we could be more selective here.
1472 (if (zerop (length res))
1474 (string-match ".\\'" res))))
1475 ;; The need for this seems to be system-dependent:
1476 ;; What is this all about, exactly? --Stef
1477 ;; (if (and (eq ?. (aref s 0)))
1478 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1479 (setq python-preoutput-skip-next-prompt nil)
1481 ((let ((end (min (length "_emacs_out ") (length s))))
1482 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1483 ;; The leftover string is a prefix of _emacs_out so we don't know
1484 ;; yet whether it's an _emacs_out or something else: wait until we
1485 ;; get more output so we can resolve this ambiguity.
1486 (set (make-local-variable 'python-preoutput-leftover) s)
1488 (t (concat res s)))))
1490 (autoload 'comint-check-proc "comint")
1492 (defvar python-version-checked nil)
1493 (defun python-check-version (cmd)
1494 "Check that CMD runs a suitable version of Python."
1495 ;; Fixme: Check on Jython.
1496 (unless (or python-version-checked
1497 (equal 0 (string-match (regexp-quote python-python-command)
1499 (unless (shell-command-to-string cmd)
1500 (error "Can't run Python command `%s'" cmd))
1501 (let* ((res (shell-command-to-string
1503 " -c \"from sys import version_info;\
1504 print version_info >= (2, 2) and version_info < (3, 0)\""))))
1505 (unless (string-match "True" res)
1506 (error "Only Python versions >= 2.2 and < 3.0 are supported")))
1507 (setq python-version-checked t)))
1510 (defun run-python (&optional cmd noshow new)
1511 "Run an inferior Python process, input and output via buffer *Python*.
1512 CMD is the Python command to run. NOSHOW non-nil means don't
1513 show the buffer automatically.
1515 Interactively, a prefix arg means to prompt for the initial
1516 Python command line (default is `python-command').
1518 A new process is started if one isn't running attached to
1519 `python-buffer', or if called from Lisp with non-nil arg NEW.
1520 Otherwise, if a process is already running in `python-buffer',
1521 switch to that buffer.
1523 This command runs the hook `inferior-python-mode-hook' after
1524 running `comint-mode-hook'. Type \\[describe-mode] in the
1525 process buffer for a list of commands.
1527 By default, Emacs inhibits the loading of Python modules from the
1528 current working directory, for security reasons. To disable this
1529 behavior, change `python-remove-cwd-from-path' to nil."
1530 (interactive (if current-prefix-arg
1531 (list (read-string "Run Python: " python-command) nil t)
1532 (list python-command)))
1533 (require 'ansi-color) ; for ipython
1534 (unless cmd (setq cmd python-command))
1535 (python-check-version cmd)
1536 (setq python-command cmd)
1537 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1538 ;; (not a name) in Python buffers from which `run-python' &c is
1539 ;; invoked. Would support multiple processes better.
1540 (when (or new (not (comint-check-proc python-buffer)))
1541 (with-current-buffer
1543 (append (python-args-to-list cmd) '("-i")
1544 (if python-remove-cwd-from-path
1545 '("-c" "import sys; sys.path.remove('')"))))
1546 (path (getenv "PYTHONPATH"))
1547 (process-environment ; to import emacs.py
1548 (cons (concat "PYTHONPATH="
1549 (if path (concat path path-separator))
1551 process-environment))
1552 ;; If we use a pipe, Unicode characters are not printed
1553 ;; correctly (Bug#5794) and IPython does not work at
1555 (process-connection-type t))
1556 (apply 'make-comint-in-buffer "Python"
1557 (generate-new-buffer "*Python*")
1558 (car cmdlist) nil (cdr cmdlist)))
1559 (setq-default python-buffer (current-buffer))
1560 (setq python-buffer (current-buffer))
1561 (accept-process-output (get-buffer-process python-buffer) 5)
1562 (inferior-python-mode)
1563 ;; Load function definitions we need.
1564 ;; Before the preoutput function was used, this was done via -c in
1565 ;; cmdlist, but that loses the banner and doesn't run the startup
1566 ;; file. The code might be inline here, but there's enough that it
1567 ;; seems worth putting in a separate file, and it's probably cleaner
1568 ;; to put it in a module.
1569 ;; Ensure we're at a prompt before doing anything else.
1570 (python-send-string "import emacs")
1571 ;; The following line was meant to ensure that we're at a prompt
1572 ;; before doing anything else. However, this can cause Emacs to
1573 ;; hang waiting for a response, if that Python function fails
1574 ;; (i.e. raises an exception).
1575 ;; (python-send-receive "print '_emacs_out ()'")
1577 (if (derived-mode-p 'python-mode)
1578 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1579 ;; Without this, help output goes into the inferior python buffer if
1580 ;; the process isn't already running.
1581 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1582 (unless noshow (pop-to-buffer python-buffer t)))
1584 (defun python-send-command (command)
1585 "Like `python-send-string' but resets `compilation-shell-minor-mode'."
1586 (when (python-check-comint-prompt)
1587 (with-current-buffer (process-buffer (python-proc))
1588 (goto-char (point-max))
1589 (compilation-forget-errors)
1590 (python-send-string command)
1591 (setq compilation-last-buffer (current-buffer)))))
1593 (defun python-send-region (start end)
1594 "Send the region to the inferior Python process."
1595 ;; The region is evaluated from a temporary file. This avoids
1596 ;; problems with blank lines, which have different semantics
1597 ;; interactively and in files. It also saves the inferior process
1598 ;; buffer filling up with interpreter prompts. We need a Python
1599 ;; function to remove the temporary file when it has been evaluated
1600 ;; (though we could probably do it in Lisp with a Comint output
1601 ;; filter). This function also catches exceptions and truncates
1602 ;; tracebacks not to mention the frame of the function itself.
1604 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1605 ;; the reference to the temporary file to the source.
1607 ;; Fixme: Write a `coding' header to the temp file if the region is
1610 (let* ((f (make-temp-file "py"))
1612 ;; IPython puts the FakeModule module into __main__ so
1613 ;; emacs.eexecfile becomes useless.
1614 (if (string-match "^ipython" python-command)
1615 (format "execfile %S" f)
1616 (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)
1786 (called-interactively-p 'interactive))
1787 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1788 (help-print-return-message))))
1789 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1790 symbol python-imports)
1791 "*Help*" (python-proc) nil nil))
1793 (add-to-list 'debug-ignored-errors "^No symbol")
1795 (defun python-send-receive (string)
1796 "Send STRING to inferior Python (if any) and return result.
1797 The result is what follows `_emacs_out' in the output.
1798 This is a no-op if `python-check-comint-prompt' returns nil."
1799 (python-send-string string)
1800 (let ((proc (python-proc)))
1801 (with-current-buffer (process-buffer proc)
1802 (when (python-check-comint-prompt proc)
1803 (set (make-local-variable 'python-preoutput-result) nil)
1805 (accept-process-output proc 5)
1806 (null python-preoutput-result)))
1807 (prog1 python-preoutput-result
1808 (kill-local-variable 'python-preoutput-result))))))
1810 (defun python-check-comint-prompt (&optional proc)
1811 "Return non-nil if and only if there's a normal prompt in the inferior buffer.
1812 If there isn't, it's probably not appropriate to send input to return Eldoc
1813 information etc. If PROC is non-nil, check the buffer for that process."
1814 (with-current-buffer (process-buffer (or proc (python-proc)))
1817 (re-search-backward (concat python--prompt-regexp " *\\=")
1820 ;; Fixme: Is there anything reasonable we can do with random methods?
1821 ;; (Currently only works with functions.)
1822 (defun python-eldoc-function ()
1823 "`eldoc-documentation-function' for Python.
1824 Only works when point is in a function name, not its arg list, for
1825 instance. Assumes an inferior Python is running."
1826 (let ((symbol (with-syntax-table python-dotty-syntax-table
1828 ;; This is run from timers, so inhibit-quit tends to be set.
1830 ;; First try the symbol we're on.
1832 (python-send-receive (format "emacs.eargs(%S, %s)"
1833 symbol python-imports)))
1834 ;; Try moving to symbol before enclosing parens.
1835 (let ((s (syntax-ppss)))
1836 (unless (zerop (car s))
1837 (when (eq ?\( (char-after (nth 1 s)))
1839 (goto-char (nth 1 s))
1840 (skip-syntax-backward "-")
1841 (let ((point (point)))
1842 (skip-chars-backward "a-zA-Z._")
1843 (if (< (point) point)
1844 (python-send-receive
1845 (format "emacs.eargs(%S, %s)"
1846 (buffer-substring-no-properties (point) point)
1847 python-imports))))))))))))
1849 ;;;; Info-look functionality.
1851 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1854 (defun python-after-info-look ()
1855 "Set up info-look for Python.
1856 Used with `eval-after-load'."
1857 (let* ((version (let ((s (shell-command-to-string (concat python-command
1859 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1860 (match-string 1 s)))
1861 ;; Whether info files have a Python version suffix, e.g. in Debian.
1864 (with-no-warnings (Info-mode))
1866 ;; Don't use `info' because it would pop-up a *info* buffer.
1868 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1872 (info-lookup-maybe-add-help
1874 :regexp "[[:alnum:]_]+"
1876 ;; Fixme: Can this reasonably be made specific to indices with
1877 ;; different rules? Is the order of indices optimal?
1878 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1881 ;; The empty prefix just gets us highlighted terms.
1882 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1883 (,(concat "(python" version "-ref)Module Index" nil ""))
1884 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1886 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1888 (,(concat "(python" version "-lib)Module Index" nil ""))
1889 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1891 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1893 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1894 '(("(python-ref)Miscellaneous Index" nil "")
1895 ("(python-ref)Module Index" nil "")
1896 ("(python-ref)Function-Method-Variable Index" nil "")
1897 ("(python-ref)Class-Exception-Object Index" nil "")
1898 ("(python-lib)Module Index" nil "")
1899 ("(python-lib)Class-Exception-Object Index" nil "")
1900 ("(python-lib)Function-Method-Variable Index" nil "")
1901 ("(python-lib)Miscellaneous Index" nil ""))))))
1902 (eval-after-load "info-look" '(python-after-info-look))
1906 (defcustom python-jython-packages '("java" "javax" "org" "com")
1907 "Packages implying `jython-mode'.
1908 If these are imported near the beginning of the buffer, `python-mode'
1909 actually punts to `jython-mode'."
1910 :type '(repeat string)
1913 ;; Called from `python-mode', this causes a recursive call of the
1914 ;; mode. See logic there to break out of the recursion.
1915 (defun python-maybe-jython ()
1916 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1917 The criterion is either a match for `jython-mode' via
1918 `interpreter-mode-alist' or an import of a module from the list
1919 `python-jython-packages'."
1920 ;; The logic is taken from python-mode.el.
1924 (goto-char (point-min))
1925 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1927 (if (and interpreter (eq 'jython-mode
1928 (cdr (assoc (file-name-nondirectory
1930 interpreter-mode-alist))))
1933 (while (re-search-forward
1934 (rx line-start (or "import" "from") (1+ space)
1935 (group (1+ (not (any " \t\n.")))))
1936 (+ (point-min) 10000) ; Probably not worth customizing.
1938 (if (member (match-string 1) python-jython-packages)
1942 (defun python-fill-paragraph (&optional justify)
1943 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1944 If any of the current line is in or at the end of a multi-line string,
1945 fill the string or the paragraph of it that point is in, preserving
1946 the string's indentation."
1948 (or (fill-comment-paragraph justify)
1951 (let* ((syntax (syntax-ppss))
1954 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
1955 (let (fill-paragraph-function)
1956 (fill-paragraph justify)))
1957 ;; The `paragraph-start' and `paragraph-separate'
1958 ;; variables don't allow us to delimit the last
1959 ;; paragraph in a multi-line string properly, so narrow
1960 ;; to the string and then fill around (the end of) the
1962 ((eq t (nth 3 syntax)) ; in fenced string
1963 (goto-char (nth 8 syntax)) ; string start
1964 (setq start (line-beginning-position))
1965 (setq end (condition-case () ; for unbalanced quotes
1966 (progn (forward-sexp)
1968 (error (point-max)))))
1969 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
1973 (progn (backward-sexp)
1974 (setq start (line-beginning-position)))
1978 (narrow-to-region start end)
1980 ;; Avoid losing leading and trailing newlines in doc
1981 ;; strings written like:
1985 (let ((paragraph-separate
1986 ;; Note that the string could be part of an
1987 ;; expression, so it can have preceding and
1988 ;; trailing non-whitespace.
1991 ;; Opening triple quote without following text.
1993 (group (syntax string-delimiter))
1994 (repeat 2 (backref 1))
1995 ;; Fixme: Not sure about including
1996 ;; trailing whitespace.
1999 ;; Closing trailing quote without preceding text.
2000 (and (group (any ?\" ?')) (backref 2)
2001 (syntax string-delimiter))))
2002 "\\(?:" paragraph-separate "\\)"))
2003 fill-paragraph-function)
2004 (fill-paragraph justify))))))) t)
2006 (defun python-shift-left (start end &optional count)
2007 "Shift lines in region COUNT (the prefix arg) columns to the left.
2008 COUNT defaults to `python-indent'. If region isn't active, just shift
2009 current line. The region shifted includes the lines in which START and
2010 END lie. It is an error if any lines in the region are indented less than
2014 (list (region-beginning) (region-end) current-prefix-arg)
2015 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2017 (setq count (prefix-numeric-value count))
2018 (setq count python-indent))
2022 (while (< (point) end)
2023 (if (and (< (current-indentation) count)
2024 (not (looking-at "[ \t]*$")))
2025 (error "Can't shift all lines enough"))
2027 (indent-rigidly start end (- count)))))
2029 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
2031 (defun python-shift-right (start end &optional count)
2032 "Shift lines in region COUNT (the prefix arg) columns to the right.
2033 COUNT defaults to `python-indent'. If region isn't active, just shift
2034 current line. The region shifted includes the lines in which START and
2038 (list (region-beginning) (region-end) current-prefix-arg)
2039 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2041 (setq count (prefix-numeric-value count))
2042 (setq count python-indent))
2043 (indent-rigidly start end count))
2045 (defun python-outline-level ()
2046 "`outline-level' function for Python mode.
2047 The level is the number of `python-indent' steps of indentation
2049 (1+ (/ (current-indentation) python-indent)))
2051 ;; Fixme: Consider top-level assignments, imports, &c.
2052 (defun python-current-defun (&optional length-limit)
2053 "`add-log-current-defun-function' for Python."
2055 ;; Move up the tree of nested `class' and `def' blocks until we
2056 ;; get to zero indentation, accumulating the defined names.
2060 (while (or (null length-limit)
2062 (< length length-limit))
2063 (let ((started-from (point)))
2064 (python-beginning-of-block)
2066 (beginning-of-defun)
2067 (when (= (point) started-from)
2069 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
2070 (group (1+ (or word (syntax symbol))))))
2071 (push (match-string 1) accum)
2072 (setq length (+ length 1 (length (car accum)))))
2073 (when (= (current-indentation) 0)
2074 (throw 'done nil))))
2076 (when (and length-limit (> length length-limit))
2077 (setcar accum ".."))
2078 (mapconcat 'identity accum ".")))))
2080 (defun python-mark-block ()
2081 "Mark the block around point.
2082 Uses `python-beginning-of-block', `python-end-of-block'."
2085 (python-beginning-of-block)
2086 (push-mark (point) nil t)
2087 (python-end-of-block)
2088 (exchange-point-and-mark))
2090 ;; Fixme: Provide a find-function-like command to find source of a
2091 ;; definition (separate from BicycleRepairMan). Complicated by
2092 ;; finding the right qualified name.
2096 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
2097 (defvar python-imports "None"
2098 "String of top-level import statements updated by `python-find-imports'.")
2099 (make-variable-buffer-local 'python-imports)
2101 ;; Fixme: Should font-lock try to run this when it deals with an import?
2102 ;; Maybe not a good idea if it gets run multiple times when the
2103 ;; statement is being edited, and is more likely to end up with
2104 ;; something syntactically incorrect.
2105 ;; However, what we should do is to trundle up the block tree from point
2106 ;; to extract imports that appear to be in scope, and add those.
2107 (defun python-find-imports ()
2108 "Find top-level imports, updating `python-imports'."
2112 (goto-char (point-min))
2113 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
2114 (unless (syntax-ppss-context (syntax-ppss))
2115 (let ((start (line-beginning-position)))
2116 ;; Skip over continued lines.
2117 (while (and (eq ?\\ (char-before (line-end-position)))
2118 (= 0 (forward-line 1)))
2120 (push (buffer-substring start (line-beginning-position 2))
2122 (setq python-imports
2125 ;; This is probably best left out since you're unlikely to need the
2126 ;; doc for a function in the buffer and the import will lose if the
2127 ;; Python sub-process' working directory isn't the same as the
2129 ;; (if buffer-file-name
2132 ;; (file-name-sans-extension
2133 ;; (file-name-nondirectory buffer-file-name))))
2137 (set-text-properties 0 (length python-imports) nil python-imports)
2138 ;; The output ends up in the wrong place if the string we
2139 ;; send contains newlines (from the imports).
2140 (setq python-imports
2141 (replace-regexp-in-string "\n" "\\n"
2142 (format "%S" python-imports) t t))))))
2144 ;; Fixme: This fails the first time if the sub-process isn't already
2145 ;; running. Presumably a timing issue with i/o to the process.
2146 (defun python-symbol-completions (symbol)
2147 "Return a list of completions of the string SYMBOL from Python process.
2149 Uses `python-imports' to load modules against which to complete."
2150 (when (stringp symbol)
2153 (car (read-from-string
2154 (python-send-receive
2155 (format "emacs.complete(%S,%s)"
2156 (substring-no-properties symbol)
2160 ;; We can get duplicates from the above -- don't know why.
2161 (delete-dups completions)
2164 (defun python-completion-at-point ()
2166 (start (save-excursion
2167 (and (re-search-backward
2168 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2169 (group (1+ (regexp "[[:alnum:]._]"))) point)
2171 (match-beginning 1)))))
2174 (completion-table-dynamic 'python-symbol-completions)))))
2178 (defun python-module-path (module)
2179 "Function for `ffap-alist' to return path to MODULE."
2180 (python-send-receive (format "emacs.modpath (%S)" module)))
2182 (eval-after-load "ffap"
2183 '(push '(python-mode . python-module-path) ffap-alist))
2185 ;;;; Find-function support
2187 ;; Fixme: key binding?
2189 (defun python-find-function (name)
2190 "Find source of definition of function NAME.
2191 Interactively, prompt for name."
2193 (let ((symbol (with-syntax-table python-dotty-syntax-table
2195 (enable-recursive-minibuffers t))
2196 (list (read-string (if symbol
2197 (format "Find location of (default %s): " symbol)
2198 "Find location of: ")
2200 (unless python-imports
2201 (error "Not called from buffer visiting Python file"))
2202 (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
2203 name python-imports)))
2204 (loc (car (read-from-string loc)))
2207 (unless file (error "Don't know where `%s' is defined" name))
2208 (pop-to-buffer (find-file-noselect file))
2209 (when (integerp line)
2210 (goto-char (point-min))
2211 (forward-line (1- line)))))
2215 (defcustom python-use-skeletons nil
2216 "Non-nil means template skeletons will be automagically inserted.
2217 This happens when pressing \"if<SPACE>\", for example, to prompt for
2222 (define-abbrev-table 'python-mode-abbrev-table ()
2223 "Abbrev table for Python mode."
2225 ;; Allow / inside abbrevs.
2226 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2227 ;; Only expand in code.
2228 :enable-function (lambda () (not (python-in-string/comment))))
2231 ;; Define a user-level skeleton and add it to the abbrev table.
2232 (defmacro def-python-skeleton (name &rest elements)
2233 (declare (indent 2))
2234 (let* ((name (symbol-name name))
2235 (function (intern (concat "python-insert-" name))))
2237 ;; Usual technique for inserting a skeleton, but expand
2238 ;; to the original abbrev instead if in a comment or string.
2239 (when python-use-skeletons
2240 (define-abbrev python-mode-abbrev-table ,name ""
2242 nil t)) ; system abbrev
2243 (define-skeleton ,function
2244 ,(format "Insert Python \"%s\" template." name)
2247 ;; From `skeleton-further-elements' set below:
2248 ;; `<': outdent a level;
2249 ;; `^': delete indentation on current line and also previous newline.
2250 ;; Not quite like `delete-indentation'. Assumes point is at
2251 ;; beginning of indentation.
2253 (def-python-skeleton if
2256 > -1 ; Fixme: I don't understand the spurious space this removes.
2258 ("other condition, %s: "
2259 < ; Avoid wrong indentation after block opening.
2264 (define-skeleton python-else
2265 "Auxiliary skeleton."
2267 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2272 (def-python-skeleton while
2278 (def-python-skeleton for
2280 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2284 (def-python-skeleton try/except
2289 < "except " str '(python-target) ":" \n
2295 (define-skeleton python-target
2296 "Auxiliary skeleton."
2297 "Target, %s: " ", " str | -2)
2299 (def-python-skeleton try/finally
2306 (def-python-skeleton def
2308 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2310 "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
2313 (def-python-skeleton class
2315 "class " str " (" ("Inheritance, %s: "
2316 (unless (equal ?\( (char-before)) ", ")
2318 & ")" | -2 ; close list or remove opening
2320 "\"\"\"" - "\"\"\"" \n
2323 (defvar python-default-template "if"
2324 "Default template to expand by `python-expand-template'.
2325 Updated on each expansion.")
2327 (defun python-expand-template (name)
2328 "Expand template named NAME.
2329 Interactively, prompt for the name with completion."
2331 (list (completing-read (format "Template to expand (default %s): "
2332 python-default-template)
2333 python-mode-abbrev-table nil t nil nil
2334 python-default-template)))
2336 (setq name python-default-template)
2337 (setq python-default-template name))
2338 (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
2341 (error "Undefined template: %s" name))))
2343 ;;;; Bicycle Repair Man support
2345 (autoload 'pymacs-load "pymacs" nil t)
2346 (autoload 'brm-init "bikemacs")
2349 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2350 ;; the way it modifies files outside Emacs... Also note that the
2351 ;; current BRM loses with tabs used for indentation -- I submitted a
2352 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2353 (defun python-setup-brm ()
2354 "Set up Bicycle Repair Man refactoring tool (if available).
2356 Note that the `refactoring' features change files independently of
2357 Emacs and may modify and save the contents of the current buffer
2358 without confirmation."
2360 (condition-case data
2361 (unless (fboundp 'brm-rename)
2362 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2363 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2364 (features (cons 'python-mode features))) ; and requires this
2365 (brm-init) ; second line of normal recipe
2366 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2367 (lambda () (easy-menu-add brm-menu)))
2369 python-brm-menu python-mode-map
2370 "Bicycle Repair Man"
2371 '("BicycleRepairMan"
2372 :help "Interface to navigation and refactoring tool"
2374 ["Find References" brm-find-references
2375 :help "Find references to name at point in compilation buffer"]
2376 ["Find Definition" brm-find-definition
2377 :help "Find definition of name at point"]
2380 ["Rename" brm-rename
2381 :help "Replace name at point with a new name everywhere"]
2382 ["Extract Method" brm-extract-method
2383 :active (and mark-active (not buffer-read-only))
2384 :help "Replace statements in region with a method"]
2385 ["Extract Local Variable" brm-extract-local-variable
2386 :active (and mark-active (not buffer-read-only))
2387 :help "Replace expression in region with an assignment"]
2388 ["Inline Local Variable" brm-inline-local-variable
2390 "Substitute uses of variable at point with its definition"]
2391 ;; Fixme: Should check for anything to revert.
2392 ["Undo Last Refactoring" brm-undo :help ""]))))
2393 (error (error "BicycleRepairMan setup failed: %s" data))))
2397 ;; pdb tracking is alert once this file is loaded, but takes no action if
2398 ;; `python-pdbtrack-do-tracking-p' is nil.
2399 (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2401 (defvar outline-heading-end-regexp)
2402 (defvar eldoc-documentation-function)
2403 (defvar python-mode-running) ;Dynamically scoped var.
2406 (define-derived-mode python-mode prog-mode "Python"
2407 "Major mode for editing Python files.
2408 Turns on Font Lock mode unconditionally since it is currently required
2409 for correct parsing of the source.
2410 See also `jython-mode', which is actually invoked if the buffer appears to
2411 contain Jython code. See also `run-python' and associated Python mode
2412 commands for running Python under Emacs.
2414 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2415 with nested `def' and `class' blocks. They take the innermost one as
2416 current without distinguishing method and class definitions. Used multiple
2417 times, they move over others at the same indentation level until they reach
2418 the end of definitions at that level, when they move up a level.
2420 Colon is electric: it outdents the line if appropriate, e.g. for
2421 an else statement. \\[python-backspace] at the beginning of an indented statement
2422 deletes a level of indentation to close the current block; otherwise it
2423 deletes a character backward. TAB indents the current line relative to
2424 the preceding code. Successive TABs, with no intervening command, cycle
2425 through the possibilities for indentation on the basis of enclosing blocks.
2427 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2428 effect outside them.
2430 Supports Eldoc mode (only for functions, using a Python process),
2431 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2432 lines count as headers. Symbol completion is available in the
2433 same way as in the Python shell using the `rlcompleter' module
2434 and this is added to the Hippie Expand functions locally if
2435 Hippie Expand mode is turned on. Completion of symbols of the
2436 form x.y only works if the components are literal
2437 module/attribute names, not variables. An abbrev table is set up
2438 with skeleton expansions for compound statement templates.
2440 \\{python-mode-map}"
2442 (set (make-local-variable 'font-lock-defaults)
2443 '(python-font-lock-keywords nil nil nil nil
2444 ;; This probably isn't worth it.
2445 ;; (font-lock-syntactic-face-function
2446 ;; . python-font-lock-syntactic-face-function)
2448 (set (make-local-variable 'syntax-propertize-function)
2449 python-syntax-propertize-function)
2450 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2451 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2452 (set (make-local-variable 'comment-start) "# ")
2453 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2454 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2455 (set (make-local-variable 'paragraph-start) "\\s-*$")
2456 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2457 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2458 (set (make-local-variable 'add-log-current-defun-function)
2459 #'python-current-defun)
2460 (set (make-local-variable 'outline-regexp)
2461 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2462 "for" "if" "try" "while" "with")
2464 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2465 (set (make-local-variable 'outline-level) #'python-outline-level)
2466 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2467 (set (make-local-variable 'beginning-of-defun-function)
2468 'python-beginning-of-defun)
2469 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2470 (add-hook 'which-func-functions 'python-which-func nil t)
2471 (setq imenu-create-index-function #'python-imenu-create-index)
2472 (set (make-local-variable 'eldoc-documentation-function)
2473 #'python-eldoc-function)
2474 (add-hook 'eldoc-mode-hook
2475 (lambda () (run-python nil t)) ; need it running
2477 (add-hook 'completion-at-point-functions
2478 'python-completion-at-point nil 'local)
2479 ;; Fixme: should be in hideshow. This seems to be of limited use
2480 ;; since it isn't (can't be) indentation-based. Also hide-level
2481 ;; doesn't seem to work properly.
2482 (add-to-list 'hs-special-modes-alist
2483 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2485 (python-end-of-defun)
2486 (skip-chars-backward " \t\n"))
2488 (set (make-local-variable 'skeleton-further-elements)
2489 '((< '(backward-delete-char-untabify (min python-indent
2491 (^ '(- (1+ (current-indentation))))))
2492 ;; Python defines TABs as being 8-char wide.
2493 (set (make-local-variable 'tab-width) 8)
2494 (when python-guess-indent (python-guess-indent))
2495 ;; Let's make it harder for the user to shoot himself in the foot.
2496 (unless (= tab-width python-indent)
2497 (setq indent-tabs-mode nil))
2498 (set (make-local-variable 'python-command) python-python-command)
2499 (python-find-imports)
2500 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2501 (let ((python-mode-running t))
2502 (python-maybe-jython))))
2504 ;; Not done automatically in Emacs 21 or 22.
2505 (defcustom python-mode-hook nil
2506 "Hook run when entering Python mode."
2509 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2510 (custom-add-option 'python-mode-hook
2512 "Turn off Indent Tabs mode."
2513 (setq indent-tabs-mode nil)))
2514 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2515 (custom-add-option 'python-mode-hook 'abbrev-mode)
2516 (custom-add-option 'python-mode-hook 'python-setup-brm)
2519 (define-derived-mode jython-mode python-mode "Jython"
2520 "Major mode for editing Jython files.
2521 Like `python-mode', but sets up parameters for Jython subprocesses.
2522 Runs `jython-mode-hook' after `python-mode-hook'."
2524 (set (make-local-variable 'python-command) python-jython-command))
2528 ;; pdbtrack features
2530 (defun python-pdbtrack-overlay-arrow (activation)
2531 "Activate or deactivate arrow at beginning-of-line in current buffer."
2534 (setq overlay-arrow-position (make-marker)
2535 overlay-arrow-string "=>"
2536 python-pdbtrack-is-tracking-p t)
2537 (set-marker overlay-arrow-position
2538 (line-beginning-position)
2540 (setq overlay-arrow-position nil
2541 python-pdbtrack-is-tracking-p nil)))
2543 (defun python-pdbtrack-track-stack-file (_text)
2544 "Show the file indicated by the pdb stack entry line, in a separate window.
2546 Activity is disabled if the buffer-local variable
2547 `python-pdbtrack-do-tracking-p' is nil.
2549 We depend on the pdb input prompt being a match for
2550 `python-pdbtrack-input-prompt'.
2552 If the traceback target file path is invalid, we look for the
2553 most recently visited python-mode buffer which either has the
2554 name of the current function or class, or which defines the
2555 function or class. This is to provide for scripts not in the
2556 local file system (e.g., Zope's 'Script \(Python)', but it's not
2557 Zope specific). If you put a copy of the script in a buffer
2558 named for the script and activate python-mode, then pdbtrack will
2560 ;; Instead of trying to piece things together from partial text
2561 ;; (which can be almost useless depending on Emacs version), we
2562 ;; monitor to the point where we have the next pdb prompt, and then
2563 ;; check all text from comint-last-input-end to process-mark.
2565 ;; Also, we're very conservative about clearing the overlay arrow,
2566 ;; to minimize residue. This means, for instance, that executing
2567 ;; other pdb commands wipe out the highlight. You can always do a
2568 ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
2570 (let* ((origbuf (current-buffer))
2571 (currproc (get-buffer-process origbuf)))
2573 (if (not (and currproc python-pdbtrack-do-tracking-p))
2574 (python-pdbtrack-overlay-arrow nil)
2576 (let* ((procmark (process-mark currproc))
2577 (block (buffer-substring (max comint-last-input-end
2579 python-pdbtrack-track-range))
2581 target target_fname target_lineno target_buffer)
2583 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2584 (python-pdbtrack-overlay-arrow nil)
2586 (setq block (ansi-color-filter-apply block))
2587 (setq target (python-pdbtrack-get-source-buffer block))
2589 (if (stringp target)
2591 (python-pdbtrack-overlay-arrow nil)
2592 (message "pdbtrack: %s" target))
2594 (setq target_lineno (car target)
2595 target_buffer (cadr target)
2596 target_fname (buffer-file-name target_buffer))
2597 (switch-to-buffer-other-window target_buffer)
2598 (goto-char (point-min))
2599 (forward-line (1- target_lineno))
2600 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
2601 (python-pdbtrack-overlay-arrow t)
2602 (pop-to-buffer origbuf t)
2603 ;; in large shell buffers, above stuff may cause point to lag output
2604 (goto-char procmark)
2608 (defun python-pdbtrack-get-source-buffer (block)
2609 "Return line number and buffer of code indicated by block's traceback text.
2611 We look first to visit the file indicated in the trace.
2613 Failing that, we look for the most recently visited python-mode buffer
2614 with the same name or having the named function.
2616 If we're unable find the source code we return a string describing the
2619 (if (not (string-match python-pdbtrack-stack-entry-regexp block))
2621 "Traceback cue not found"
2623 (let* ((filename (match-string 1 block))
2624 (lineno (string-to-number (match-string 2 block)))
2625 (funcname (match-string 3 block))
2628 (cond ((file-exists-p filename)
2629 (list lineno (find-file-noselect filename)))
2631 ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
2632 (if (string-match "/Script (Python)$" filename)
2633 ;; Add in number of lines for leading '##' comments:
2636 (with-current-buffer funcbuffer
2637 (if (equal (point-min)(point-max))
2642 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
2644 (point-min) (point-max)))
2646 (list lineno funcbuffer))
2648 ((= (elt filename 0) ?\<)
2649 (format "(Non-file source: '%s')" filename))
2651 (t (format "Not found: %s(), %s" funcname filename)))
2656 (defun python-pdbtrack-grub-for-buffer (funcname _lineno)
2657 "Find recent Python mode buffer named, or having function named FUNCNAME."
2658 (let ((buffers (buffer-list))
2661 (while (and buffers (not got))
2662 (setq buf (car buffers)
2663 buffers (cdr buffers))
2664 (if (and (with-current-buffer buf
2665 (string= major-mode "python-mode"))
2666 (or (string-match funcname (buffer-name buf))
2667 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
2669 (with-current-buffer buf
2670 (buffer-substring (point-min)
2675 ;; Python subprocess utilities and filters
2676 (defun python-execute-file (proc filename)
2677 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
2678 Make that process's buffer visible and force display. Also make
2679 comint believe the user typed this string so that
2680 `kill-output-from-shell' does The Right Thing."
2681 (let ((curbuf (current-buffer))
2682 (procbuf (process-buffer proc))
2683 ; (comint-scroll-to-bottom-on-output t)
2684 (msg (format "## working on region in file %s...\n" filename))
2685 ;; add some comment, so that we can filter it out of history
2686 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
2688 (with-current-buffer procbuf
2689 (goto-char (point-max))
2690 (move-marker (process-mark proc) (point))
2691 (funcall (process-filter proc) proc msg))
2692 (set-buffer curbuf))
2693 (process-send-string proc cmd)))
2695 (defun python-pdbtrack-toggle-stack-tracking (arg)
2697 (if (not (get-buffer-process (current-buffer)))
2698 (error "No process associated with buffer '%s'" (current-buffer)))
2699 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2701 (zerop (setq arg (prefix-numeric-value arg))))
2702 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2703 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2704 (message "%sabled Python's pdbtrack"
2705 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2707 (defun turn-on-pdbtrack ()
2709 (python-pdbtrack-toggle-stack-tracking 1))
2711 (defun turn-off-pdbtrack ()
2713 (python-pdbtrack-toggle-stack-tracking 0))
2715 (defun python-sentinel (_proc _msg)
2716 (setq overlay-arrow-position nil))
2718 (defun python-unload-function ()
2719 "Unload the Python library."
2720 (remove-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2721 (setq minor-mode-alist (assq-delete-all 'python-pdbtrack-is-tracking-p
2723 (dolist (error '("^No symbol" "^Can't shift all lines enough"))
2724 (setq debug-ignored-errors (delete error debug-ignored-errors)))
2725 ;; continue standard unloading
2729 (provide 'python-21)
2731 ;;; python.el ends here