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 debateable, 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[(<]*[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 (python-beginning-of-string)
954 (while (and (python-continuation-line-p)
959 (if (python-backslash-continuation-line-p)
962 (while (python-backslash-continuation-line-p)
964 (python-beginning-of-string)
966 (setq point (point))))
967 (back-to-indentation))
969 (defun python-skip-out (&optional forward syntax)
970 "Skip out of any nested brackets.
971 Skip forward if FORWARD is non-nil, else backward.
972 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
973 Return non-nil if and only if skipping was done."
974 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
975 (forward (if forward -1 1)))
976 (unless (zerop depth)
978 ;; Skip forward out of nested brackets.
979 (condition-case () ; beware invalid syntax
980 (progn (backward-up-list (* forward depth)) t)
982 ;; Invalid syntax (too many closed brackets).
983 ;; Skip out of as many as possible.
985 (while (condition-case ()
986 (progn (backward-up-list forward)
991 (defun python-end-of-statement ()
992 "Go to the end of the current statement and return point.
993 Usually this is the start of the next line, but if this is a
994 multi-line statement we need to skip over the continuation lines.
995 On a comment line, go to end of line."
997 (while (let (comment)
998 ;; Move past any enclosing strings and sexps, or stop if
999 ;; we're in a comment.
1000 (while (let ((s (syntax-ppss)))
1001 (cond ((eq 'comment (syntax-ppss-context s))
1004 ((eq 'string (syntax-ppss-context s))
1005 ;; Go to start of string and skip it.
1006 (let ((pos (point)))
1007 (goto-char (nth 8 s))
1008 (condition-case () ; beware invalid syntax
1009 (progn (forward-sexp) t)
1010 ;; If there's a mismatched string, make sure
1011 ;; we still overall move *forward*.
1012 (error (goto-char pos) (end-of-line)))))
1013 ((python-skip-out t s))))
1016 (eq ?\\ (char-before)))) ; Line continued?
1017 (end-of-line 2)) ; Try next line.
1020 (defun python-previous-statement (&optional count)
1021 "Go to start of previous statement.
1022 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
1023 Return count of statements left to move."
1025 (unless count (setq count 1))
1027 (python-next-statement (- count))
1028 (python-beginning-of-statement)
1029 (while (and (> count 0) (not (bobp)))
1030 (python-skip-comments/blanks t)
1031 (python-beginning-of-statement)
1032 (unless (bobp) (setq count (1- count))))
1035 (defun python-next-statement (&optional count)
1036 "Go to start of next statement.
1037 With argument COUNT, do it COUNT times. Stop at end of buffer.
1038 Return count of statements left to move."
1040 (unless count (setq count 1))
1042 (python-previous-statement (- count))
1045 (while (and (> count 0) (not (eobp)) (not bogus))
1046 (python-end-of-statement)
1047 (python-skip-comments/blanks)
1048 (if (eq 'string (syntax-ppss-context (syntax-ppss)))
1051 (setq count (1- count))))))
1054 (defun python-beginning-of-block (&optional arg)
1055 "Go to start of current block.
1056 With numeric arg, do it that many times. If ARG is negative, call
1057 `python-end-of-block' instead.
1058 If point is on the first line of a block, use its outer block.
1059 If current statement is in column zero, don't move and return nil.
1060 Otherwise return non-nil."
1062 (unless arg (setq arg 1))
1065 ((< arg 0) (python-end-of-block (- arg)))
1067 (let ((point (point)))
1068 (if (or (python-comment-line-p)
1069 (python-blank-line-p))
1070 (python-skip-comments/blanks t))
1071 (python-beginning-of-statement)
1072 (let ((ci (current-indentation)))
1074 (not (goto-char point)) ; return nil
1075 ;; Look upwards for less indented statement.
1077 ;;; This is slower than the below.
1078 ;;; (while (zerop (python-previous-statement))
1079 ;;; (when (and (< (current-indentation) ci)
1080 ;;; (python-open-block-statement-p t))
1081 ;;; (beginning-of-line)
1082 ;;; (throw 'done t)))
1083 (while (and (zerop (forward-line -1)))
1084 (when (and (< (current-indentation) ci)
1085 (not (python-comment-line-p))
1086 ;; Move to beginning to save effort in case
1087 ;; this is in string.
1088 (progn (python-beginning-of-statement) t)
1089 (python-open-block-statement-p t))
1092 (not (goto-char point))) ; Failed -- return nil
1093 (python-beginning-of-block (1- arg)))))))))
1095 (defun python-end-of-block (&optional arg)
1096 "Go to end of current block.
1097 With numeric arg, do it that many times. If ARG is negative,
1098 call `python-beginning-of-block' instead.
1099 If current statement is in column zero and doesn't open a block,
1100 don't move and return nil. Otherwise return t."
1102 (unless arg (setq arg 1))
1104 (python-beginning-of-block (- arg))
1105 (while (and (> arg 0)
1106 (let* ((point (point))
1107 (_ (if (python-comment-line-p)
1108 (python-skip-comments/blanks t)))
1109 (ci (current-indentation))
1110 (open (python-open-block-statement-p)))
1111 (if (and (zerop ci) (not open))
1112 (not (goto-char point))
1114 (while (zerop (python-next-statement))
1115 (when (or (and open (<= (current-indentation) ci))
1116 (< (current-indentation) ci))
1117 (python-skip-comments/blanks t)
1118 (beginning-of-line 2)
1119 (throw 'done t)))))))
1120 (setq arg (1- arg)))
1123 (defvar python-which-func-length-limit 40
1124 "Non-strict length limit for `python-which-func' output.")
1126 (defun python-which-func ()
1127 (let ((function-name (python-current-defun python-which-func-length-limit)))
1128 (set-text-properties 0 (length function-name) nil function-name)
1134 ;; For possibily speeding this up, here's the top of the ELP profile
1135 ;; for rescanning pydoc.py (2.2k lines, 90kb):
1136 ;; Function Name Call Count Elapsed Time Average Time
1137 ;; ==================================== ========== ============= ============
1138 ;; python-imenu-create-index 156 2.430906 0.0155827307
1139 ;; python-end-of-defun 155 1.2718260000 0.0082053290
1140 ;; python-end-of-block 155 1.1898689999 0.0076765741
1141 ;; python-next-statement 2970 1.024717 0.0003450225
1142 ;; python-end-of-statement 2970 0.4332190000 0.0001458649
1143 ;; python-beginning-of-defun 265 0.0918479999 0.0003465962
1144 ;; python-skip-comments/blanks 3125 0.0753319999 2.410...e-05
1146 (defvar python-recursing)
1147 (defun python-imenu-create-index ()
1148 "`imenu-create-index-function' for Python.
1150 Makes nested Imenu menus from nested `class' and `def' statements.
1151 The nested menus are headed by an item referencing the outer
1152 definition; it has a space prepended to the name so that it sorts
1153 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1155 (unless (boundp 'python-recursing) ; dynamically bound below
1156 ;; Normal call from Imenu.
1157 (goto-char (point-min))
1158 ;; Without this, we can get an infloop if the buffer isn't all
1159 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1160 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1161 ;; what's going on, but it must be something to do with timers in
1163 ;; This can't be right, especially not when jit-lock is not used. --Stef
1164 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1165 ;; (font-lock-fontify-region (point-min) (point-max)))
1167 (let (index-alist) ; accumulated value to return
1168 (while (re-search-forward
1169 (rx line-start (0+ space) ; leading space
1170 (or (group "def") (group "class")) ; type
1171 (1+ space) (group (1+ (or word ?_)))) ; name
1173 (unless (python-in-string/comment)
1174 (let ((pos (match-beginning 0))
1175 (name (match-string-no-properties 3)))
1176 (if (match-beginning 2) ; def or class?
1177 (setq name (concat "class " name)))
1180 (let* ((python-recursing t)
1181 (sublist (python-imenu-create-index)))
1183 (progn (push (cons (concat " " name) pos) sublist)
1184 (push (cons name sublist) index-alist))
1185 (push (cons name pos) index-alist)))))))
1186 (unless (boundp 'python-recursing)
1187 ;; Look for module variables.
1189 (goto-char (point-min))
1190 (while (re-search-forward
1191 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1193 (unless (python-in-string/comment)
1194 (push (cons (match-string 1) (match-beginning 1))
1196 (setq index-alist (nreverse index-alist))
1198 (push (cons "Module variables"
1203 ;;;; `Electric' commands.
1205 (defun python-electric-colon (arg)
1206 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1207 With numeric ARG, just insert that many colons. With \\[universal-argument],
1208 just insert a single colon."
1210 (self-insert-command (if (not (integerp arg)) 1 arg))
1214 (not (python-in-string/comment))
1215 (> (current-indentation) (python-calculate-indentation))
1216 (python-indent-line))) ; OK, do it
1217 (put 'python-electric-colon 'delete-selection t)
1219 (defun python-backspace (arg)
1220 "Maybe delete a level of indentation on the current line.
1221 Do so if point is at the end of the line's indentation outside
1222 strings and comments.
1223 Otherwise just call `backward-delete-char-untabify'.
1226 (if (or (/= (current-indentation) (current-column))
1228 (python-continuation-line-p)
1229 (python-in-string/comment))
1230 (backward-delete-char-untabify arg)
1231 ;; Look for the largest valid indentation which is smaller than
1232 ;; the current indentation.
1234 (ci (current-indentation))
1235 (indents (python-indentation-levels))
1239 (setq indent (max indent (car x)))))
1240 (setq initial (cdr (assq indent indents)))
1241 (if (> (length initial) 0)
1242 (message "Closes %s" initial))
1243 (delete-horizontal-space)
1244 (indent-to indent))))
1245 (put 'python-backspace 'delete-selection 'supersede)
1249 (defcustom python-check-command "pychecker --stdlib"
1250 "Command used to check a Python file."
1254 (defvar python-saved-check-command nil
1257 ;; After `sgml-validate-command'.
1258 (defun python-check (command)
1259 "Check a Python file (default current buffer's file).
1260 Runs COMMAND, a shell command, as if by `compile'.
1261 See `python-check-command' for the default."
1263 (list (read-string "Checker command: "
1264 (or python-saved-check-command
1265 (concat python-check-command " "
1266 (let ((name (buffer-file-name)))
1268 (file-name-nondirectory name))))))))
1269 (set (make-local-variable 'python-saved-check-command) command)
1270 (require 'compile) ;To define compilation-* variables.
1271 (save-some-buffers (not compilation-ask-about-save) nil)
1272 (let ((compilation-error-regexp-alist
1273 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1274 compilation-error-regexp-alist)))
1275 (compilation-start command)))
1277 ;;;; Inferior mode stuff (following cmuscheme).
1279 (defcustom python-python-command "python"
1280 "Shell command to run Python interpreter.
1281 Any arguments can't contain whitespace."
1285 (defcustom python-jython-command "jython"
1286 "Shell command to run Jython interpreter.
1287 Any arguments can't contain whitespace."
1291 (defvar python-command python-python-command
1292 "Actual command used to run Python.
1293 May be `python-python-command' or `python-jython-command', possibly
1294 modified by the user. Additional arguments are added when the command
1295 is used by `run-python' et al.")
1297 (defvar python-buffer nil
1298 "*The current Python process buffer.
1300 Commands that send text from source buffers to Python processes have
1301 to choose a process to send to. This is determined by buffer-local
1302 value of `python-buffer'. If its value in the current buffer,
1303 i.e. both any local value and the default one, is nil, `run-python'
1304 and commands that send to the Python process will start a new process.
1306 Whenever \\[run-python] starts a new process, it resets the default
1307 value of `python-buffer' to be the new process's buffer and sets the
1308 buffer-local value similarly if the current buffer is in Python mode
1309 or Inferior Python mode, so that source buffer stays associated with a
1310 specific sub-process.
1312 Use \\[python-set-proc] to set the default value from a buffer with a
1314 (make-variable-buffer-local 'python-buffer)
1316 (defconst python-compilation-regexp-alist
1317 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1318 ;; The first already is (for CAML), but the second isn't. Anyhow,
1319 ;; these are specific to the inferior buffer. -- fx
1320 `((,(rx line-start (1+ (any " \t")) "File \""
1321 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1322 "\", line " (group (1+ digit)))
1324 (,(rx " in file " (group (1+ not-newline)) " on line "
1328 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1329 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1331 "`compilation-error-regexp-alist' for inferior Python.")
1333 (defvar inferior-python-mode-map
1334 (let ((map (make-sparse-keymap)))
1335 ;; This will inherit from comint-mode-map.
1336 (define-key map "\C-c\C-l" 'python-load-file)
1337 (define-key map "\C-c\C-v" 'python-check)
1338 ;; Note that we _can_ still use these commands which send to the
1339 ;; Python process even at the prompt if we have a normal prompt,
1340 ;; i.e. '>>> ' and not '... '. See the comment before
1341 ;; python-send-region. Fixme: uncomment these if we address that.
1343 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1344 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1347 (defvar inferior-python-mode-syntax-table
1348 (let ((st (make-syntax-table python-mode-syntax-table)))
1349 ;; Don't get confused by apostrophes in the process's output (e.g. if
1350 ;; you execute "help(os)").
1351 (modify-syntax-entry ?\' "." st)
1352 ;; Maybe we should do the same for double quotes?
1353 ;; (modify-syntax-entry ?\" "." st)
1357 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1359 (defvar python--prompt-regexp nil)
1361 (defun python--set-prompt-regexp ()
1362 (let ((prompt (cdr-safe (or (assoc python-python-command
1363 python-shell-prompt-alist)
1364 (assq t python-shell-prompt-alist))))
1365 (cprompt (cdr-safe (or (assoc python-python-command
1366 python-shell-continuation-prompt-alist)
1367 (assq t python-shell-continuation-prompt-alist)))))
1368 (set (make-local-variable 'comint-prompt-regexp)
1370 (mapconcat 'identity
1371 (delq nil (list prompt cprompt "^([Pp]db) "))
1374 (set (make-local-variable 'python--prompt-regexp) prompt)))
1376 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1377 ;; not sure how much: at least some keybindings, like C-c C-f;
1378 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1379 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1380 "Major mode for interacting with an inferior Python process.
1381 A Python process can be started with \\[run-python].
1383 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1386 You can send text to the inferior Python process from other buffers
1387 containing Python source.
1388 * \\[python-switch-to-python] switches the current buffer to the Python
1390 * \\[python-send-region] sends the current region to the Python process.
1391 * \\[python-send-region-and-go] switches to the Python process buffer
1392 after sending the text.
1393 For running multiple processes in multiple buffers, see `run-python' and
1396 \\{inferior-python-mode-map}"
1398 (require 'ansi-color) ; for ipython
1399 (setq mode-line-process '(":%s"))
1400 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1401 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1403 (python--set-prompt-regexp)
1404 (set (make-local-variable 'compilation-error-regexp-alist)
1405 python-compilation-regexp-alist)
1406 (compilation-shell-minor-mode 1))
1408 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1409 "Input matching this regexp is not saved on the history list.
1410 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1414 (defcustom python-remove-cwd-from-path t
1415 "Whether to allow loading of Python modules from the current directory.
1416 If this is non-nil, Emacs removes '' from sys.path when starting
1417 an inferior Python process. This is the default, for security
1418 reasons, as it is easy for the Python process to be started
1419 without the user's realization (e.g. to perform completion)."
1424 (defun python-input-filter (str)
1425 "`comint-input-filter' function for inferior Python.
1426 Don't save anything for STR matching `inferior-python-filter-regexp'."
1427 (not (string-match inferior-python-filter-regexp str)))
1429 ;; Fixme: Loses with quoted whitespace.
1430 (defun python-args-to-list (string)
1431 (let ((where (string-match "[ \t]" string)))
1432 (cond ((null where) (list string))
1434 (cons (substring string 0 where)
1435 (python-args-to-list (substring string (+ 1 where)))))
1436 (t (let ((pos (string-match "[^ \t]" string)))
1437 (if pos (python-args-to-list (substring string pos))))))))
1439 (defvar python-preoutput-result nil
1440 "Data from last `_emacs_out' line seen by the preoutput filter.")
1442 (defvar python-preoutput-continuation nil
1443 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1445 (defvar python-preoutput-leftover nil)
1446 (defvar python-preoutput-skip-next-prompt nil)
1448 ;; Using this stops us getting lines in the buffer like
1450 ;; Also look for (and delete) an `_emacs_ok' string and call
1451 ;; `python-preoutput-continuation' if we get it.
1452 (defun python-preoutput-filter (s)
1453 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1454 (when python-preoutput-leftover
1455 (setq s (concat python-preoutput-leftover s))
1456 (setq python-preoutput-leftover nil))
1459 ;; First process whole lines.
1460 (while (string-match "\n" s start)
1461 (let ((line (substring s start (setq start (match-end 0)))))
1462 ;; Skip prompt if needed.
1463 (when (and python-preoutput-skip-next-prompt
1464 (string-match comint-prompt-regexp line))
1465 (setq python-preoutput-skip-next-prompt nil)
1466 (setq line (substring line (match-end 0))))
1467 ;; Recognize special _emacs_out lines.
1468 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1469 (local-variable-p 'python-preoutput-result))
1471 (setq python-preoutput-result (match-string 1 line))
1472 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1473 (setq res (concat res line)))))
1474 ;; Then process the remaining partial line.
1475 (unless (zerop start) (setq s (substring s start)))
1476 (cond ((and (string-match comint-prompt-regexp s)
1477 ;; Drop this prompt if it follows an _emacs_out...
1478 (or python-preoutput-skip-next-prompt
1479 ;; ... or if it's not gonna be inserted at BOL.
1480 ;; Maybe we could be more selective here.
1481 (if (zerop (length res))
1483 (string-match ".\\'" res))))
1484 ;; The need for this seems to be system-dependent:
1485 ;; What is this all about, exactly? --Stef
1486 ;; (if (and (eq ?. (aref s 0)))
1487 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1488 (setq python-preoutput-skip-next-prompt nil)
1490 ((let ((end (min (length "_emacs_out ") (length s))))
1491 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1492 ;; The leftover string is a prefix of _emacs_out so we don't know
1493 ;; yet whether it's an _emacs_out or something else: wait until we
1494 ;; get more output so we can resolve this ambiguity.
1495 (set (make-local-variable 'python-preoutput-leftover) s)
1497 (t (concat res s)))))
1499 (autoload 'comint-check-proc "comint")
1501 (defvar python-version-checked nil)
1502 (defun python-check-version (cmd)
1503 "Check that CMD runs a suitable version of Python."
1504 ;; Fixme: Check on Jython.
1505 (unless (or python-version-checked
1506 (equal 0 (string-match (regexp-quote python-python-command)
1508 (unless (shell-command-to-string cmd)
1509 (error "Can't run Python command `%s'" cmd))
1510 (let* ((res (shell-command-to-string
1512 " -c \"from sys import version_info;\
1513 print version_info >= (2, 2) and version_info < (3, 0)\""))))
1514 (unless (string-match "True" res)
1515 (error "Only Python versions >= 2.2 and < 3.0 are supported")))
1516 (setq python-version-checked t)))
1519 (defun run-python (&optional cmd noshow new)
1520 "Run an inferior Python process, input and output via buffer *Python*.
1521 CMD is the Python command to run. NOSHOW non-nil means don't
1522 show the buffer automatically.
1524 Interactively, a prefix arg means to prompt for the initial
1525 Python command line (default is `python-command').
1527 A new process is started if one isn't running attached to
1528 `python-buffer', or if called from Lisp with non-nil arg NEW.
1529 Otherwise, if a process is already running in `python-buffer',
1530 switch to that buffer.
1532 This command runs the hook `inferior-python-mode-hook' after
1533 running `comint-mode-hook'. Type \\[describe-mode] in the
1534 process buffer for a list of commands.
1536 By default, Emacs inhibits the loading of Python modules from the
1537 current working directory, for security reasons. To disable this
1538 behavior, change `python-remove-cwd-from-path' to nil."
1539 (interactive (if current-prefix-arg
1540 (list (read-string "Run Python: " python-command) nil t)
1541 (list python-command)))
1542 (require 'ansi-color) ; for ipython
1543 (unless cmd (setq cmd python-command))
1544 (python-check-version cmd)
1545 (setq python-command cmd)
1546 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1547 ;; (not a name) in Python buffers from which `run-python' &c is
1548 ;; invoked. Would support multiple processes better.
1549 (when (or new (not (comint-check-proc python-buffer)))
1550 (with-current-buffer
1552 (append (python-args-to-list cmd) '("-i")
1553 (if python-remove-cwd-from-path
1554 '("-c" "import sys; sys.path.remove('')"))))
1555 (path (getenv "PYTHONPATH"))
1556 (process-environment ; to import emacs.py
1557 (cons (concat "PYTHONPATH="
1558 (if path (concat path path-separator))
1560 process-environment))
1561 ;; If we use a pipe, unicode characters are not printed
1562 ;; correctly (Bug#5794) and IPython does not work at
1564 (process-connection-type t))
1565 (apply 'make-comint-in-buffer "Python"
1566 (generate-new-buffer "*Python*")
1567 (car cmdlist) nil (cdr cmdlist)))
1568 (setq-default python-buffer (current-buffer))
1569 (setq python-buffer (current-buffer))
1570 (accept-process-output (get-buffer-process python-buffer) 5)
1571 (inferior-python-mode)
1572 ;; Load function definitions we need.
1573 ;; Before the preoutput function was used, this was done via -c in
1574 ;; cmdlist, but that loses the banner and doesn't run the startup
1575 ;; file. The code might be inline here, but there's enough that it
1576 ;; seems worth putting in a separate file, and it's probably cleaner
1577 ;; to put it in a module.
1578 ;; Ensure we're at a prompt before doing anything else.
1579 (python-send-string "import emacs")
1580 ;; The following line was meant to ensure that we're at a prompt
1581 ;; before doing anything else. However, this can cause Emacs to
1582 ;; hang waiting for a response, if that Python function fails
1583 ;; (i.e. raises an exception).
1584 ;; (python-send-receive "print '_emacs_out ()'")
1586 (if (derived-mode-p 'python-mode)
1587 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1588 ;; Without this, help output goes into the inferior python buffer if
1589 ;; the process isn't already running.
1590 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1591 (unless noshow (pop-to-buffer python-buffer t)))
1593 (defun python-send-command (command)
1594 "Like `python-send-string' but resets `compilation-shell-minor-mode'."
1595 (when (python-check-comint-prompt)
1596 (with-current-buffer (process-buffer (python-proc))
1597 (goto-char (point-max))
1598 (compilation-forget-errors)
1599 (python-send-string command)
1600 (setq compilation-last-buffer (current-buffer)))))
1602 (defun python-send-region (start end)
1603 "Send the region to the inferior Python process."
1604 ;; The region is evaluated from a temporary file. This avoids
1605 ;; problems with blank lines, which have different semantics
1606 ;; interactively and in files. It also saves the inferior process
1607 ;; buffer filling up with interpreter prompts. We need a Python
1608 ;; function to remove the temporary file when it has been evaluated
1609 ;; (though we could probably do it in Lisp with a Comint output
1610 ;; filter). This function also catches exceptions and truncates
1611 ;; tracebacks not to mention the frame of the function itself.
1613 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1614 ;; the reference to the temporary file to the source.
1616 ;; Fixme: Write a `coding' header to the temp file if the region is
1619 (let* ((f (make-temp-file "py"))
1621 ;; IPython puts the FakeModule module into __main__ so
1622 ;; emacs.eexecfile becomes useless.
1623 (if (string-match "^ipython" python-command)
1624 (format "execfile %S" f)
1625 (format "emacs.eexecfile(%S)" f)))
1626 (orig-start (copy-marker start)))
1627 (when (save-excursion
1629 (/= 0 (current-indentation))) ; need dummy block
1631 (goto-char orig-start)
1632 ;; Wrong if we had indented code at buffer start.
1633 (set-marker orig-start (line-beginning-position 0)))
1634 (write-region "if True:\n" nil f nil 'nomsg))
1635 (write-region start end f t 'nomsg)
1636 (python-send-command command)
1637 (with-current-buffer (process-buffer (python-proc))
1638 ;; Tell compile.el to redirect error locations in file `f' to
1639 ;; positions past marker `orig-start'. It has to be done *after*
1640 ;; `python-send-command''s call to `compilation-forget-errors'.
1641 (compilation-fake-loc orig-start f))))
1643 (defun python-send-string (string)
1644 "Evaluate STRING in inferior Python process."
1645 (interactive "sPython command: ")
1646 (comint-send-string (python-proc) string)
1647 (unless (string-match "\n\\'" string)
1648 ;; Make sure the text is properly LF-terminated.
1649 (comint-send-string (python-proc) "\n"))
1650 (when (string-match "\n[ \t].*\n?\\'" string)
1651 ;; If the string contains a final indented line, add a second newline so
1652 ;; as to make sure we terminate the multiline instruction.
1653 (comint-send-string (python-proc) "\n")))
1655 (defun python-send-buffer ()
1656 "Send the current buffer to the inferior Python process."
1658 (python-send-region (point-min) (point-max)))
1660 ;; Fixme: Try to define the function or class within the relevant
1661 ;; module, not just at top level.
1662 (defun python-send-defun ()
1663 "Send the current defun (class or method) to the inferior Python process."
1665 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1666 (progn (end-of-defun) (point)))))
1668 (defun python-switch-to-python (eob-p)
1669 "Switch to the Python process buffer, maybe starting new process.
1670 With prefix arg, position cursor at end of buffer."
1672 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1675 (goto-char (point-max))))
1677 (defun python-send-region-and-go (start end)
1678 "Send the region to the inferior Python process.
1679 Then switch to the process buffer."
1681 (python-send-region start end)
1682 (python-switch-to-python t))
1684 (defcustom python-source-modes '(python-mode jython-mode)
1685 "Used to determine if a buffer contains Python source code.
1686 If a file is loaded into a buffer that is in one of these major modes,
1687 it is considered Python source by `python-load-file', which uses the
1688 value to determine defaults."
1689 :type '(repeat function)
1692 (defvar python-prev-dir/file nil
1693 "Caches (directory . file) pair used in the last `python-load-file' command.
1694 Used for determining the default in the next one.")
1696 (autoload 'comint-get-source "comint")
1698 (defun python-load-file (file-name)
1699 "Load a Python file FILE-NAME into the inferior Python process.
1700 If the file has extension `.py' import or reload it as a module.
1701 Treating it as a module keeps the global namespace clean, provides
1702 function location information for debugging, and supports users of
1703 module-qualified names."
1704 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1706 t)) ; because execfile needs exact name
1707 (comint-check-source file-name) ; Check to see if buffer needs saving.
1708 (setq python-prev-dir/file (cons (file-name-directory file-name)
1709 (file-name-nondirectory file-name)))
1710 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1711 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1712 (python-send-command
1713 (if (string-match "\\.py\\'" file-name)
1714 (let ((module (file-name-sans-extension
1715 (file-name-nondirectory file-name))))
1716 (format "emacs.eimport(%S,%S)"
1717 module (file-name-directory file-name)))
1718 (format "execfile(%S)" file-name)))
1719 (message "%s loaded" file-name)))
1721 (defun python-proc ()
1722 "Return the current Python process.
1723 See variable `python-buffer'. Starts a new process if necessary."
1724 ;; Fixme: Maybe should look for another active process if there
1725 ;; isn't one for `python-buffer'.
1726 (unless (comint-check-proc python-buffer)
1728 (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
1732 (defun python-set-proc ()
1733 "Set the default value of `python-buffer' to correspond to this buffer.
1734 If the current buffer has a local value of `python-buffer', set the
1735 default (global) value to that. The associated Python process is
1736 the one that gets input from \\[python-send-region] et al when used
1737 in a buffer that doesn't have a local value of `python-buffer'."
1739 (if (local-variable-p 'python-buffer)
1740 (setq-default python-buffer python-buffer)
1741 (error "No local value of `python-buffer'")))
1743 ;;;; Context-sensitive help.
1745 (defconst python-dotty-syntax-table
1746 (let ((table (make-syntax-table)))
1747 (set-char-table-parent table python-mode-syntax-table)
1748 (modify-syntax-entry ?. "_" table)
1750 "Syntax table giving `.' symbol syntax.
1751 Otherwise inherits from `python-mode-syntax-table'.")
1753 (defvar view-return-to-alist)
1754 (eval-when-compile (autoload 'help-buffer "help-fns"))
1756 (defvar python-imports) ; forward declaration
1758 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1759 ;; bound to C-h S? [Probably not, since info-look may work in cases
1760 ;; where this doesn't.]
1761 (defun python-describe-symbol (symbol)
1762 "Get help on SYMBOL using `help'.
1763 Interactively, prompt for symbol.
1765 Symbol may be anything recognized by the interpreter's `help'
1766 command -- e.g. `CALLS' -- not just variables in scope in the
1767 interpreter. This only works for Python version 2.2 or newer
1768 since earlier interpreters don't support `help'.
1770 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1772 ;; Note that we do this in the inferior process, not a separate one, to
1773 ;; ensure the environment is appropriate.
1775 (let ((symbol (with-syntax-table python-dotty-syntax-table
1777 (enable-recursive-minibuffers t))
1778 (list (read-string (if symbol
1779 (format "Describe symbol (default %s): " symbol)
1780 "Describe symbol: ")
1782 (if (equal symbol "") (error "No symbol"))
1783 ;; Ensure we have a suitable help buffer.
1784 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1785 ;; allow C-c C-f in help buffer.
1786 (let ((temp-buffer-show-hook ; avoid xref stuff
1788 (toggle-read-only 1)
1789 (setq view-return-to-alist
1790 (list (cons (selected-window) help-return-method))))))
1791 (with-output-to-temp-buffer (help-buffer)
1792 (with-current-buffer standard-output
1793 ;; Fixme: Is this actually useful?
1794 (help-setup-xref (list 'python-describe-symbol symbol)
1795 (called-interactively-p 'interactive))
1796 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1797 (help-print-return-message))))
1798 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1799 symbol python-imports)
1800 "*Help*" (python-proc) nil nil))
1802 (add-to-list 'debug-ignored-errors "^No symbol")
1804 (defun python-send-receive (string)
1805 "Send STRING to inferior Python (if any) and return result.
1806 The result is what follows `_emacs_out' in the output.
1807 This is a no-op if `python-check-comint-prompt' returns nil."
1808 (python-send-string string)
1809 (let ((proc (python-proc)))
1810 (with-current-buffer (process-buffer proc)
1811 (when (python-check-comint-prompt proc)
1812 (set (make-local-variable 'python-preoutput-result) nil)
1814 (accept-process-output proc 5)
1815 (null python-preoutput-result)))
1816 (prog1 python-preoutput-result
1817 (kill-local-variable 'python-preoutput-result))))))
1819 (defun python-check-comint-prompt (&optional proc)
1820 "Return non-nil if and only if there's a normal prompt in the inferior buffer.
1821 If there isn't, it's probably not appropriate to send input to return Eldoc
1822 information etc. If PROC is non-nil, check the buffer for that process."
1823 (with-current-buffer (process-buffer (or proc (python-proc)))
1826 (re-search-backward (concat python--prompt-regexp " *\\=")
1829 ;; Fixme: Is there anything reasonable we can do with random methods?
1830 ;; (Currently only works with functions.)
1831 (defun python-eldoc-function ()
1832 "`eldoc-documentation-function' for Python.
1833 Only works when point is in a function name, not its arg list, for
1834 instance. Assumes an inferior Python is running."
1835 (let ((symbol (with-syntax-table python-dotty-syntax-table
1837 ;; This is run from timers, so inhibit-quit tends to be set.
1839 ;; First try the symbol we're on.
1841 (python-send-receive (format "emacs.eargs(%S, %s)"
1842 symbol python-imports)))
1843 ;; Try moving to symbol before enclosing parens.
1844 (let ((s (syntax-ppss)))
1845 (unless (zerop (car s))
1846 (when (eq ?\( (char-after (nth 1 s)))
1848 (goto-char (nth 1 s))
1849 (skip-syntax-backward "-")
1850 (let ((point (point)))
1851 (skip-chars-backward "a-zA-Z._")
1852 (if (< (point) point)
1853 (python-send-receive
1854 (format "emacs.eargs(%S, %s)"
1855 (buffer-substring-no-properties (point) point)
1856 python-imports))))))))))))
1858 ;;;; Info-look functionality.
1860 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1863 (defun python-after-info-look ()
1864 "Set up info-look for Python.
1865 Used with `eval-after-load'."
1866 (let* ((version (let ((s (shell-command-to-string (concat python-command
1868 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1869 (match-string 1 s)))
1870 ;; Whether info files have a Python version suffix, e.g. in Debian.
1873 (with-no-warnings (Info-mode))
1875 ;; Don't use `info' because it would pop-up a *info* buffer.
1877 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1881 (info-lookup-maybe-add-help
1883 :regexp "[[:alnum:]_]+"
1885 ;; Fixme: Can this reasonably be made specific to indices with
1886 ;; different rules? Is the order of indices optimal?
1887 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1890 ;; The empty prefix just gets us highlighted terms.
1891 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1892 (,(concat "(python" version "-ref)Module Index" nil ""))
1893 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1895 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1897 (,(concat "(python" version "-lib)Module Index" nil ""))
1898 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1900 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1902 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1903 '(("(python-ref)Miscellaneous Index" nil "")
1904 ("(python-ref)Module Index" nil "")
1905 ("(python-ref)Function-Method-Variable Index" nil "")
1906 ("(python-ref)Class-Exception-Object Index" nil "")
1907 ("(python-lib)Module Index" nil "")
1908 ("(python-lib)Class-Exception-Object Index" nil "")
1909 ("(python-lib)Function-Method-Variable Index" nil "")
1910 ("(python-lib)Miscellaneous Index" nil ""))))))
1911 (eval-after-load "info-look" '(python-after-info-look))
1915 (defcustom python-jython-packages '("java" "javax" "org" "com")
1916 "Packages implying `jython-mode'.
1917 If these are imported near the beginning of the buffer, `python-mode'
1918 actually punts to `jython-mode'."
1919 :type '(repeat string)
1922 ;; Called from `python-mode', this causes a recursive call of the
1923 ;; mode. See logic there to break out of the recursion.
1924 (defun python-maybe-jython ()
1925 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1926 The criterion is either a match for `jython-mode' via
1927 `interpreter-mode-alist' or an import of a module from the list
1928 `python-jython-packages'."
1929 ;; The logic is taken from python-mode.el.
1933 (goto-char (point-min))
1934 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1936 (if (and interpreter (eq 'jython-mode
1937 (cdr (assoc (file-name-nondirectory
1939 interpreter-mode-alist))))
1942 (while (re-search-forward
1943 (rx line-start (or "import" "from") (1+ space)
1944 (group (1+ (not (any " \t\n.")))))
1945 (+ (point-min) 10000) ; Probably not worth customizing.
1947 (if (member (match-string 1) python-jython-packages)
1951 (defun python-fill-paragraph (&optional justify)
1952 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1953 If any of the current line is in or at the end of a multi-line string,
1954 fill the string or the paragraph of it that point is in, preserving
1955 the string's indentation."
1957 (or (fill-comment-paragraph justify)
1960 (let* ((syntax (syntax-ppss))
1963 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
1964 (let (fill-paragraph-function)
1965 (fill-paragraph justify)))
1966 ;; The `paragraph-start' and `paragraph-separate'
1967 ;; variables don't allow us to delimit the last
1968 ;; paragraph in a multi-line string properly, so narrow
1969 ;; to the string and then fill around (the end of) the
1971 ((eq t (nth 3 syntax)) ; in fenced string
1972 (goto-char (nth 8 syntax)) ; string start
1973 (setq start (line-beginning-position))
1974 (setq end (condition-case () ; for unbalanced quotes
1975 (progn (forward-sexp)
1977 (error (point-max)))))
1978 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
1982 (progn (backward-sexp)
1983 (setq start (line-beginning-position)))
1987 (narrow-to-region start end)
1989 ;; Avoid losing leading and trailing newlines in doc
1990 ;; strings written like:
1994 (let ((paragraph-separate
1995 ;; Note that the string could be part of an
1996 ;; expression, so it can have preceding and
1997 ;; trailing non-whitespace.
2000 ;; Opening triple quote without following text.
2002 (group (syntax string-delimiter))
2003 (repeat 2 (backref 1))
2004 ;; Fixme: Not sure about including
2005 ;; trailing whitespace.
2008 ;; Closing trailing quote without preceding text.
2009 (and (group (any ?\" ?')) (backref 2)
2010 (syntax string-delimiter))))
2011 "\\(?:" paragraph-separate "\\)"))
2012 fill-paragraph-function)
2013 (fill-paragraph justify))))))) t)
2015 (defun python-shift-left (start end &optional count)
2016 "Shift lines in region COUNT (the prefix arg) columns to the left.
2017 COUNT defaults to `python-indent'. If region isn't active, just shift
2018 current line. The region shifted includes the lines in which START and
2019 END lie. It is an error if any lines in the region are indented less than
2023 (list (region-beginning) (region-end) current-prefix-arg)
2024 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2026 (setq count (prefix-numeric-value count))
2027 (setq count python-indent))
2031 (while (< (point) end)
2032 (if (and (< (current-indentation) count)
2033 (not (looking-at "[ \t]*$")))
2034 (error "Can't shift all lines enough"))
2036 (indent-rigidly start end (- count)))))
2038 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
2040 (defun python-shift-right (start end &optional count)
2041 "Shift lines in region COUNT (the prefix arg) columns to the right.
2042 COUNT defaults to `python-indent'. If region isn't active, just shift
2043 current line. The region shifted includes the lines in which START and
2047 (list (region-beginning) (region-end) current-prefix-arg)
2048 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
2050 (setq count (prefix-numeric-value count))
2051 (setq count python-indent))
2052 (indent-rigidly start end count))
2054 (defun python-outline-level ()
2055 "`outline-level' function for Python mode.
2056 The level is the number of `python-indent' steps of indentation
2058 (1+ (/ (current-indentation) python-indent)))
2060 ;; Fixme: Consider top-level assignments, imports, &c.
2061 (defun python-current-defun (&optional length-limit)
2062 "`add-log-current-defun-function' for Python."
2064 ;; Move up the tree of nested `class' and `def' blocks until we
2065 ;; get to zero indentation, accumulating the defined names.
2069 (while (or (null length-limit)
2071 (< length length-limit))
2072 (let ((started-from (point)))
2073 (python-beginning-of-block)
2075 (beginning-of-defun)
2076 (when (= (point) started-from)
2078 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
2079 (group (1+ (or word (syntax symbol))))))
2080 (push (match-string 1) accum)
2081 (setq length (+ length 1 (length (car accum)))))
2082 (when (= (current-indentation) 0)
2083 (throw 'done nil))))
2085 (when (and length-limit (> length length-limit))
2086 (setcar accum ".."))
2087 (mapconcat 'identity accum ".")))))
2089 (defun python-mark-block ()
2090 "Mark the block around point.
2091 Uses `python-beginning-of-block', `python-end-of-block'."
2094 (python-beginning-of-block)
2095 (push-mark (point) nil t)
2096 (python-end-of-block)
2097 (exchange-point-and-mark))
2099 ;; Fixme: Provide a find-function-like command to find source of a
2100 ;; definition (separate from BicycleRepairMan). Complicated by
2101 ;; finding the right qualified name.
2105 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
2106 (defvar python-imports "None"
2107 "String of top-level import statements updated by `python-find-imports'.")
2108 (make-variable-buffer-local 'python-imports)
2110 ;; Fixme: Should font-lock try to run this when it deals with an import?
2111 ;; Maybe not a good idea if it gets run multiple times when the
2112 ;; statement is being edited, and is more likely to end up with
2113 ;; something syntactically incorrect.
2114 ;; However, what we should do is to trundle up the block tree from point
2115 ;; to extract imports that appear to be in scope, and add those.
2116 (defun python-find-imports ()
2117 "Find top-level imports, updating `python-imports'."
2121 (goto-char (point-min))
2122 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
2123 (unless (syntax-ppss-context (syntax-ppss))
2124 (let ((start (line-beginning-position)))
2125 ;; Skip over continued lines.
2126 (while (and (eq ?\\ (char-before (line-end-position)))
2127 (= 0 (forward-line 1)))
2129 (push (buffer-substring start (line-beginning-position 2))
2131 (setq python-imports
2134 ;; This is probably best left out since you're unlikely to need the
2135 ;; doc for a function in the buffer and the import will lose if the
2136 ;; Python sub-process' working directory isn't the same as the
2138 ;; (if buffer-file-name
2141 ;; (file-name-sans-extension
2142 ;; (file-name-nondirectory buffer-file-name))))
2146 (set-text-properties 0 (length python-imports) nil python-imports)
2147 ;; The output ends up in the wrong place if the string we
2148 ;; send contains newlines (from the imports).
2149 (setq python-imports
2150 (replace-regexp-in-string "\n" "\\n"
2151 (format "%S" python-imports) t t))))))
2153 ;; Fixme: This fails the first time if the sub-process isn't already
2154 ;; running. Presumably a timing issue with i/o to the process.
2155 (defun python-symbol-completions (symbol)
2156 "Return a list of completions of the string SYMBOL from Python process.
2158 Uses `python-imports' to load modules against which to complete."
2159 (when (stringp symbol)
2162 (car (read-from-string
2163 (python-send-receive
2164 (format "emacs.complete(%S,%s)"
2165 (substring-no-properties symbol)
2169 ;; We can get duplicates from the above -- don't know why.
2170 (delete-dups completions)
2173 (defun python-completion-at-point ()
2175 (start (save-excursion
2176 (and (re-search-backward
2177 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2178 (group (1+ (regexp "[[:alnum:]._]"))) point)
2180 (match-beginning 1)))))
2183 (completion-table-dynamic 'python-symbol-completions)))))
2187 (defun python-module-path (module)
2188 "Function for `ffap-alist' to return path to MODULE."
2189 (python-send-receive (format "emacs.modpath (%S)" module)))
2191 (eval-after-load "ffap"
2192 '(push '(python-mode . python-module-path) ffap-alist))
2194 ;;;; Find-function support
2196 ;; Fixme: key binding?
2198 (defun python-find-function (name)
2199 "Find source of definition of function NAME.
2200 Interactively, prompt for name."
2202 (let ((symbol (with-syntax-table python-dotty-syntax-table
2204 (enable-recursive-minibuffers t))
2205 (list (read-string (if symbol
2206 (format "Find location of (default %s): " symbol)
2207 "Find location of: ")
2209 (unless python-imports
2210 (error "Not called from buffer visiting Python file"))
2211 (let* ((loc (python-send-receive (format "emacs.location_of (%S, %s)"
2212 name python-imports)))
2213 (loc (car (read-from-string loc)))
2216 (unless file (error "Don't know where `%s' is defined" name))
2217 (pop-to-buffer (find-file-noselect file))
2218 (when (integerp line)
2219 (goto-char (point-min))
2220 (forward-line (1- line)))))
2224 (defcustom python-use-skeletons nil
2225 "Non-nil means template skeletons will be automagically inserted.
2226 This happens when pressing \"if<SPACE>\", for example, to prompt for
2231 (define-abbrev-table 'python-mode-abbrev-table ()
2232 "Abbrev table for Python mode."
2234 ;; Allow / inside abbrevs.
2235 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2236 ;; Only expand in code.
2237 :enable-function (lambda () (not (python-in-string/comment))))
2240 ;; Define a user-level skeleton and add it to the abbrev table.
2241 (defmacro def-python-skeleton (name &rest elements)
2242 (declare (indent 2))
2243 (let* ((name (symbol-name name))
2244 (function (intern (concat "python-insert-" name))))
2246 ;; Usual technique for inserting a skeleton, but expand
2247 ;; to the original abbrev instead if in a comment or string.
2248 (when python-use-skeletons
2249 (define-abbrev python-mode-abbrev-table ,name ""
2251 nil t)) ; system abbrev
2252 (define-skeleton ,function
2253 ,(format "Insert Python \"%s\" template." name)
2256 ;; From `skeleton-further-elements' set below:
2257 ;; `<': outdent a level;
2258 ;; `^': delete indentation on current line and also previous newline.
2259 ;; Not quite like `delete-indentation'. Assumes point is at
2260 ;; beginning of indentation.
2262 (def-python-skeleton if
2265 > -1 ; Fixme: I don't understand the spurious space this removes.
2267 ("other condition, %s: "
2268 < ; Avoid wrong indentation after block opening.
2273 (define-skeleton python-else
2274 "Auxiliary skeleton."
2276 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2281 (def-python-skeleton while
2287 (def-python-skeleton for
2289 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2293 (def-python-skeleton try/except
2298 < "except " str '(python-target) ":" \n
2304 (define-skeleton python-target
2305 "Auxiliary skeleton."
2306 "Target, %s: " ", " str | -2)
2308 (def-python-skeleton try/finally
2315 (def-python-skeleton def
2317 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2319 "\"\"\"" - "\"\"\"" \n ; Fixme: extra space inserted -- why?).
2322 (def-python-skeleton class
2324 "class " str " (" ("Inheritance, %s: "
2325 (unless (equal ?\( (char-before)) ", ")
2327 & ")" | -2 ; close list or remove opening
2329 "\"\"\"" - "\"\"\"" \n
2332 (defvar python-default-template "if"
2333 "Default template to expand by `python-expand-template'.
2334 Updated on each expansion.")
2336 (defun python-expand-template (name)
2337 "Expand template named NAME.
2338 Interactively, prompt for the name with completion."
2340 (list (completing-read (format "Template to expand (default %s): "
2341 python-default-template)
2342 python-mode-abbrev-table nil t nil nil
2343 python-default-template)))
2345 (setq name python-default-template)
2346 (setq python-default-template name))
2347 (let ((sym (abbrev-symbol name python-mode-abbrev-table)))
2350 (error "Undefined template: %s" name))))
2352 ;;;; Bicycle Repair Man support
2354 (autoload 'pymacs-load "pymacs" nil t)
2355 (autoload 'brm-init "bikemacs")
2358 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2359 ;; the way it modifies files outside Emacs... Also note that the
2360 ;; current BRM loses with tabs used for indentation -- I submitted a
2361 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2362 (defun python-setup-brm ()
2363 "Set up Bicycle Repair Man refactoring tool (if available).
2365 Note that the `refactoring' features change files independently of
2366 Emacs and may modify and save the contents of the current buffer
2367 without confirmation."
2369 (condition-case data
2370 (unless (fboundp 'brm-rename)
2371 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2372 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2373 (features (cons 'python-mode features))) ; and requires this
2374 (brm-init) ; second line of normal recipe
2375 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2376 (lambda () (easy-menu-add brm-menu)))
2378 python-brm-menu python-mode-map
2379 "Bicycle Repair Man"
2380 '("BicycleRepairMan"
2381 :help "Interface to navigation and refactoring tool"
2383 ["Find References" brm-find-references
2384 :help "Find references to name at point in compilation buffer"]
2385 ["Find Definition" brm-find-definition
2386 :help "Find definition of name at point"]
2389 ["Rename" brm-rename
2390 :help "Replace name at point with a new name everywhere"]
2391 ["Extract Method" brm-extract-method
2392 :active (and mark-active (not buffer-read-only))
2393 :help "Replace statements in region with a method"]
2394 ["Extract Local Variable" brm-extract-local-variable
2395 :active (and mark-active (not buffer-read-only))
2396 :help "Replace expression in region with an assignment"]
2397 ["Inline Local Variable" brm-inline-local-variable
2399 "Substitute uses of variable at point with its definition"]
2400 ;; Fixme: Should check for anything to revert.
2401 ["Undo Last Refactoring" brm-undo :help ""]))))
2402 (error (error "BicycleRepairMan setup failed: %s" data))))
2406 ;; pdb tracking is alert once this file is loaded, but takes no action if
2407 ;; `python-pdbtrack-do-tracking-p' is nil.
2408 (add-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2410 (defvar outline-heading-end-regexp)
2411 (defvar eldoc-documentation-function)
2412 (defvar python-mode-running) ;Dynamically scoped var.
2415 (define-derived-mode python-mode prog-mode "Python"
2416 "Major mode for editing Python files.
2417 Turns on Font Lock mode unconditionally since it is currently required
2418 for correct parsing of the source.
2419 See also `jython-mode', which is actually invoked if the buffer appears to
2420 contain Jython code. See also `run-python' and associated Python mode
2421 commands for running Python under Emacs.
2423 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2424 with nested `def' and `class' blocks. They take the innermost one as
2425 current without distinguishing method and class definitions. Used multiple
2426 times, they move over others at the same indentation level until they reach
2427 the end of definitions at that level, when they move up a level.
2429 Colon is electric: it outdents the line if appropriate, e.g. for
2430 an else statement. \\[python-backspace] at the beginning of an indented statement
2431 deletes a level of indentation to close the current block; otherwise it
2432 deletes a character backward. TAB indents the current line relative to
2433 the preceding code. Successive TABs, with no intervening command, cycle
2434 through the possibilities for indentation on the basis of enclosing blocks.
2436 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2437 effect outside them.
2439 Supports Eldoc mode (only for functions, using a Python process),
2440 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2441 lines count as headers. Symbol completion is available in the
2442 same way as in the Python shell using the `rlcompleter' module
2443 and this is added to the Hippie Expand functions locally if
2444 Hippie Expand mode is turned on. Completion of symbols of the
2445 form x.y only works if the components are literal
2446 module/attribute names, not variables. An abbrev table is set up
2447 with skeleton expansions for compound statement templates.
2449 \\{python-mode-map}"
2451 (set (make-local-variable 'font-lock-defaults)
2452 '(python-font-lock-keywords nil nil nil nil
2453 ;; This probably isn't worth it.
2454 ;; (font-lock-syntactic-face-function
2455 ;; . python-font-lock-syntactic-face-function)
2457 (set (make-local-variable 'syntax-propertize-function)
2458 python-syntax-propertize-function)
2459 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2460 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2461 (set (make-local-variable 'comment-start) "# ")
2462 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2463 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2464 (set (make-local-variable 'paragraph-start) "\\s-*$")
2465 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2466 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2467 (set (make-local-variable 'add-log-current-defun-function)
2468 #'python-current-defun)
2469 (set (make-local-variable 'outline-regexp)
2470 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2471 "for" "if" "try" "while" "with")
2473 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2474 (set (make-local-variable 'outline-level) #'python-outline-level)
2475 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2476 (set (make-local-variable 'beginning-of-defun-function)
2477 'python-beginning-of-defun)
2478 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2479 (add-hook 'which-func-functions 'python-which-func nil t)
2480 (setq imenu-create-index-function #'python-imenu-create-index)
2481 (set (make-local-variable 'eldoc-documentation-function)
2482 #'python-eldoc-function)
2483 (add-hook 'eldoc-mode-hook
2484 (lambda () (run-python nil t)) ; need it running
2486 (add-hook 'completion-at-point-functions
2487 'python-completion-at-point nil 'local)
2488 ;; Fixme: should be in hideshow. This seems to be of limited use
2489 ;; since it isn't (can't be) indentation-based. Also hide-level
2490 ;; doesn't seem to work properly.
2491 (add-to-list 'hs-special-modes-alist
2492 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2494 (python-end-of-defun)
2495 (skip-chars-backward " \t\n"))
2497 (set (make-local-variable 'skeleton-further-elements)
2498 '((< '(backward-delete-char-untabify (min python-indent
2500 (^ '(- (1+ (current-indentation))))))
2501 ;; Python defines TABs as being 8-char wide.
2502 (set (make-local-variable 'tab-width) 8)
2503 (when python-guess-indent (python-guess-indent))
2504 ;; Let's make it harder for the user to shoot himself in the foot.
2505 (unless (= tab-width python-indent)
2506 (setq indent-tabs-mode nil))
2507 (set (make-local-variable 'python-command) python-python-command)
2508 (python-find-imports)
2509 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2510 (let ((python-mode-running t))
2511 (python-maybe-jython))))
2513 ;; Not done automatically in Emacs 21 or 22.
2514 (defcustom python-mode-hook nil
2515 "Hook run when entering Python mode."
2518 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2519 (custom-add-option 'python-mode-hook
2521 "Turn off Indent Tabs mode."
2522 (setq indent-tabs-mode nil)))
2523 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2524 (custom-add-option 'python-mode-hook 'abbrev-mode)
2525 (custom-add-option 'python-mode-hook 'python-setup-brm)
2528 (define-derived-mode jython-mode python-mode "Jython"
2529 "Major mode for editing Jython files.
2530 Like `python-mode', but sets up parameters for Jython subprocesses.
2531 Runs `jython-mode-hook' after `python-mode-hook'."
2533 (set (make-local-variable 'python-command) python-jython-command))
2537 ;; pdbtrack features
2539 (defun python-pdbtrack-overlay-arrow (activation)
2540 "Activate or deactivate arrow at beginning-of-line in current buffer."
2543 (setq overlay-arrow-position (make-marker)
2544 overlay-arrow-string "=>"
2545 python-pdbtrack-is-tracking-p t)
2546 (set-marker overlay-arrow-position
2547 (line-beginning-position)
2549 (setq overlay-arrow-position nil
2550 python-pdbtrack-is-tracking-p nil)))
2552 (defun python-pdbtrack-track-stack-file (_text)
2553 "Show the file indicated by the pdb stack entry line, in a separate window.
2555 Activity is disabled if the buffer-local variable
2556 `python-pdbtrack-do-tracking-p' is nil.
2558 We depend on the pdb input prompt being a match for
2559 `python-pdbtrack-input-prompt'.
2561 If the traceback target file path is invalid, we look for the
2562 most recently visited python-mode buffer which either has the
2563 name of the current function or class, or which defines the
2564 function or class. This is to provide for scripts not in the
2565 local filesytem (e.g., Zope's 'Script \(Python)', but it's not
2566 Zope specific). If you put a copy of the script in a buffer
2567 named for the script and activate python-mode, then pdbtrack will
2569 ;; Instead of trying to piece things together from partial text
2570 ;; (which can be almost useless depending on Emacs version), we
2571 ;; monitor to the point where we have the next pdb prompt, and then
2572 ;; check all text from comint-last-input-end to process-mark.
2574 ;; Also, we're very conservative about clearing the overlay arrow,
2575 ;; to minimize residue. This means, for instance, that executing
2576 ;; other pdb commands wipe out the highlight. You can always do a
2577 ;; 'where' (aka 'w') PDB command to reveal the overlay arrow.
2579 (let* ((origbuf (current-buffer))
2580 (currproc (get-buffer-process origbuf)))
2582 (if (not (and currproc python-pdbtrack-do-tracking-p))
2583 (python-pdbtrack-overlay-arrow nil)
2585 (let* ((procmark (process-mark currproc))
2586 (block (buffer-substring (max comint-last-input-end
2588 python-pdbtrack-track-range))
2590 target target_fname target_lineno target_buffer)
2592 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2593 (python-pdbtrack-overlay-arrow nil)
2595 (setq target (python-pdbtrack-get-source-buffer block))
2597 (if (stringp target)
2599 (python-pdbtrack-overlay-arrow nil)
2600 (message "pdbtrack: %s" target))
2602 (setq target_lineno (car target)
2603 target_buffer (cadr target)
2604 target_fname (buffer-file-name target_buffer))
2605 (switch-to-buffer-other-window target_buffer)
2606 (goto-char (point-min))
2607 (forward-line (1- target_lineno))
2608 (message "pdbtrack: line %s, file %s" target_lineno target_fname)
2609 (python-pdbtrack-overlay-arrow t)
2610 (pop-to-buffer origbuf t)
2611 ;; in large shell buffers, above stuff may cause point to lag output
2612 (goto-char procmark)
2616 (defun python-pdbtrack-get-source-buffer (block)
2617 "Return line number and buffer of code indicated by block's traceback text.
2619 We look first to visit the file indicated in the trace.
2621 Failing that, we look for the most recently visited python-mode buffer
2622 with the same name or having the named function.
2624 If we're unable find the source code we return a string describing the
2627 (if (not (string-match python-pdbtrack-stack-entry-regexp block))
2629 "Traceback cue not found"
2631 (let* ((filename (match-string 1 block))
2632 (lineno (string-to-number (match-string 2 block)))
2633 (funcname (match-string 3 block))
2636 (cond ((file-exists-p filename)
2637 (list lineno (find-file-noselect filename)))
2639 ((setq funcbuffer (python-pdbtrack-grub-for-buffer funcname lineno))
2640 (if (string-match "/Script (Python)$" filename)
2641 ;; Add in number of lines for leading '##' comments:
2644 (with-current-buffer funcbuffer
2645 (if (equal (point-min)(point-max))
2650 (string-match "^\\([^#]\\|#[^#]\\|#$\\)"
2652 (point-min) (point-max)))
2654 (list lineno funcbuffer))
2656 ((= (elt filename 0) ?\<)
2657 (format "(Non-file source: '%s')" filename))
2659 (t (format "Not found: %s(), %s" funcname filename)))
2664 (defun python-pdbtrack-grub-for-buffer (funcname _lineno)
2665 "Find recent Python mode buffer named, or having function named FUNCNAME."
2666 (let ((buffers (buffer-list))
2669 (while (and buffers (not got))
2670 (setq buf (car buffers)
2671 buffers (cdr buffers))
2672 (if (and (with-current-buffer buf
2673 (string= major-mode "python-mode"))
2674 (or (string-match funcname (buffer-name buf))
2675 (string-match (concat "^\\s-*\\(def\\|class\\)\\s-+"
2677 (with-current-buffer buf
2678 (buffer-substring (point-min)
2683 ;; Python subprocess utilities and filters
2684 (defun python-execute-file (proc filename)
2685 "Send to Python interpreter process PROC \"execfile('FILENAME')\".
2686 Make that process's buffer visible and force display. Also make
2687 comint believe the user typed this string so that
2688 `kill-output-from-shell' does The Right Thing."
2689 (let ((curbuf (current-buffer))
2690 (procbuf (process-buffer proc))
2691 ; (comint-scroll-to-bottom-on-output t)
2692 (msg (format "## working on region in file %s...\n" filename))
2693 ;; add some comment, so that we can filter it out of history
2694 (cmd (format "execfile(r'%s') # PYTHON-MODE\n" filename)))
2696 (with-current-buffer procbuf
2697 (goto-char (point-max))
2698 (move-marker (process-mark proc) (point))
2699 (funcall (process-filter proc) proc msg))
2700 (set-buffer curbuf))
2701 (process-send-string proc cmd)))
2703 (defun python-pdbtrack-toggle-stack-tracking (arg)
2705 (if (not (get-buffer-process (current-buffer)))
2706 (error "No process associated with buffer '%s'" (current-buffer)))
2707 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2709 (zerop (setq arg (prefix-numeric-value arg))))
2710 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2711 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2712 (message "%sabled Python's pdbtrack"
2713 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2715 (defun turn-on-pdbtrack ()
2717 (python-pdbtrack-toggle-stack-tracking 1))
2719 (defun turn-off-pdbtrack ()
2721 (python-pdbtrack-toggle-stack-tracking 0))
2723 (defun python-sentinel (_proc _msg)
2724 (setq overlay-arrow-position nil))
2726 (defun python-unload-function ()
2727 "Unload the Python library."
2728 (remove-hook 'comint-output-filter-functions 'python-pdbtrack-track-stack-file)
2729 (setq minor-mode-alist (assq-delete-all 'python-pdbtrack-is-tracking-p
2731 (dolist (error '("^No symbol" "^Can't shift all lines enough"))
2732 (setq debug-ignored-errors (delete error debug-ignored-errors)))
2733 ;; continue standard unloading
2737 (provide 'python-21)
2739 ;;; python.el ends here