1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Dave Love <fx@gnu.org>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; Major mode for editing Python, with support for inferior processes.
31 ;; There is another Python mode, python-mode.el, used by XEmacs and
32 ;; maintained with Python. That isn't covered by an FSF copyright
33 ;; assignment, unlike this code, and seems not to be well-maintained
34 ;; for Emacs (though I've submitted fixes). This mode is rather
35 ;; simpler and is better in other ways. In particular, using the
36 ;; syntax functions with text properties maintained by font-lock makes
37 ;; it more correct with 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, `c-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.
71 (require 'hippie-exp))
73 (autoload 'comint-mode "comint")
76 "Silly walks in the Python language."
79 :link '(emacs-commentary-link "python"))
82 (add-to-list 'interpreter-mode-alist '("jython" . jython-mode))
84 (add-to-list 'interpreter-mode-alist '("python" . python-mode))
86 (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
90 (defvar python-font-lock-keywords
92 ;; From v 2.5 reference, § keywords.
93 ;; def and class dealt with separately below
94 (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
95 "except" "exec" "finally" "for" "from" "global" "if"
96 "import" "in" "is" "lambda" "not" "or" "pass" "print"
97 "raise" "return" "try" "while" "with" "yield"
98 ;; Not real keywords, but close enough to be fontified as such
99 "self" "True" "False")
101 (,(rx symbol-start "None" symbol-end) ; See § Keywords in 2.5 manual.
102 . font-lock-constant-face)
104 (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
105 (1 font-lock-keyword-face) (2 font-lock-type-face))
106 (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
107 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
108 ;; Top-level assignments are worth highlighting.
109 (,(rx line-start (group (1+ (or word ?_))) (0+ space) "=")
110 (1 font-lock-variable-name-face))
111 (,(rx "@" (1+ (or word ?_))) ; decorators
112 (0 font-lock-preprocessor-face))))
114 (defconst python-font-lock-syntactic-keywords
115 ;; Make outer chars of matching triple-quote sequences into generic
116 ;; string delimiters. Fixme: Is there a better way?
117 `((,(rx (or line-start buffer-start
118 (not (syntax escape))) ; avoid escaped leading quote
119 (group (optional (any "uUrR"))) ; prefix gets syntax property
120 (optional (any "rR")) ; possible second prefix
121 (group (syntax string-quote)) ; maybe gets property
122 (backref 2) ; per first quote
123 (group (backref 2))) ; maybe gets property
124 (1 (python-quote-syntax 1))
125 (2 (python-quote-syntax 2))
126 (3 (python-quote-syntax 3)))
127 ;; This doesn't really help.
128 ;;; (,(rx (and ?\\ (group ?\n))) (1 " "))
131 (defun python-quote-syntax (n)
132 "Put `syntax-table' property correctly on triple quote.
133 Used for syntactic keywords. N is the match number (1, 2 or 3)."
134 ;; Given a triple quote, we have to check the context to know
135 ;; whether this is an opening or closing triple or whether it's
136 ;; quoted anyhow, and should be ignored. (For that we need to do
137 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
138 ;; to use it here despite initial worries.) We also have to sort
139 ;; out a possible prefix -- well, we don't _have_ to, but I think it
140 ;; should be treated as part of the string.
143 ;; ur"""ar""" x='"' # """
146 ;; x '"""' x """ \"""" x
147 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
150 (goto-char (match-beginning 0))
152 ;; Consider property for the last char if in a fenced string.
154 (let* ((font-lock-syntactic-keywords nil)
155 (syntax (syntax-ppss)))
156 (when (eq t (nth 3 syntax)) ; after unclosed fence
157 (goto-char (nth 8 syntax)) ; fence position
158 (skip-chars-forward "uUrR") ; skip any prefix
159 ;; Is it a matching sequence?
160 (if (eq (char-after) (char-after (match-beginning 2)))
161 (eval-when-compile (string-to-syntax "|"))))))
162 ;; Consider property for initial char, accounting for prefixes.
163 ((or (and (= n 2) ; leading quote (not prefix)
164 (= (match-beginning 1) (match-end 1))) ; prefix is null
165 (and (= n 1) ; prefix
166 (/= (match-beginning 1) (match-end 1)))) ; non-empty
167 (let ((font-lock-syntactic-keywords nil))
168 (unless (nth 3 (syntax-ppss))
169 (eval-when-compile (string-to-syntax "|")))))
170 ;; Otherwise (we're in a non-matching string) the property is
174 ;; This isn't currently in `font-lock-defaults' as probably not worth
175 ;; it -- we basically only mess with a few normally-symbol characters.
177 ;; (defun python-font-lock-syntactic-face-function (state)
178 ;; "`font-lock-syntactic-face-function' for Python mode.
179 ;; Returns the string or comment face as usual, with side effect of putting
180 ;; a `syntax-table' property on the inside of the string or comment which is
181 ;; the standard syntax table."
184 ;; (goto-char (nth 8 state))
185 ;; (condition-case nil
188 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
189 ;; 'syntax-table (standard-syntax-table))
190 ;; 'font-lock-string-face)
191 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
192 ;; 'syntax-table (standard-syntax-table))
193 ;; 'font-lock-comment-face))
195 ;;;; Keymap and syntax
197 (defvar python-mode-map
198 (let ((map (make-sparse-keymap)))
199 ;; Mostly taken from python-mode.el.
200 (define-key map ":" 'python-electric-colon)
201 (define-key map "\177" 'python-backspace)
202 (define-key map "\C-c<" 'python-shift-left)
203 (define-key map "\C-c>" 'python-shift-right)
204 (define-key map "\C-c\C-k" 'python-mark-block)
205 (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking)
206 (define-key map "\C-c\C-n" 'python-next-statement)
207 (define-key map "\C-c\C-p" 'python-previous-statement)
208 (define-key map "\C-c\C-u" 'python-beginning-of-block)
209 (define-key map "\C-c\C-f" 'python-describe-symbol)
210 (define-key map "\C-c\C-w" 'python-check)
211 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
212 (define-key map "\C-c\C-s" 'python-send-string)
213 (define-key map [?\C-\M-x] 'python-send-defun)
214 (define-key map "\C-c\C-r" 'python-send-region)
215 (define-key map "\C-c\M-r" 'python-send-region-and-go)
216 (define-key map "\C-c\C-c" 'python-send-buffer)
217 (define-key map "\C-c\C-z" 'python-switch-to-python)
218 (define-key map "\C-c\C-m" 'python-load-file)
219 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
220 (substitute-key-definition 'complete-symbol 'python-complete-symbol
222 (define-key map "\C-c\C-i" 'python-find-imports)
223 (define-key map "\C-c\C-t" 'python-expand-template)
224 (easy-menu-define python-menu map "Python Mode menu"
226 :help "Python-specific Features"
227 ["Shift region left" python-shift-left :active mark-active
228 :help "Shift by a single indentation step"]
229 ["Shift region right" python-shift-right :active mark-active
230 :help "Shift by a single indentation step"]
232 ["Mark block" python-mark-block
233 :help "Mark innermost block around point"]
234 ["Mark def/class" mark-defun
235 :help "Mark innermost definition around point"]
237 ["Start of block" python-beginning-of-block
238 :help "Go to start of innermost definition around point"]
239 ["End of block" python-end-of-block
240 :help "Go to end of innermost definition around point"]
241 ["Start of def/class" beginning-of-defun
242 :help "Go to start of innermost definition around point"]
243 ["End of def/class" end-of-defun
244 :help "Go to end of innermost definition around point"]
247 :help "Expand templates for compound statements"
248 :filter (lambda (&rest junk)
249 (mapcar (lambda (elt)
250 (vector (car elt) (cdr elt) t))
251 python-skeletons))) ; defined later
253 ["Start interpreter" python-shell
254 :help "Run `inferior' Python in separate buffer"]
255 ["Import/reload file" python-load-file
256 :help "Load into inferior Python session"]
257 ["Eval buffer" python-send-buffer
258 :help "Evaluate buffer en bloc in inferior Python session"]
259 ["Eval region" python-send-region :active mark-active
260 :help "Evaluate region en bloc in inferior Python session"]
261 ["Eval def/class" python-send-defun
262 :help "Evaluate current definition in inferior Python session"]
263 ["Switch to interpreter" python-switch-to-python
264 :help "Switch to inferior Python buffer"]
265 ["Set default process" python-set-proc
266 :help "Make buffer's inferior process the default"
267 :active (buffer-live-p python-buffer)]
268 ["Check file" python-check :help "Run pychecker"]
269 ["Debugger" pdb :help "Run pdb under GUD"]
271 ["Help on symbol" python-describe-symbol
272 :help "Use pydoc on symbol at point"]
273 ["Complete symbol" python-complete-symbol
274 :help "Complete (qualified) symbol before point"]
275 ["Update imports" python-find-imports
276 :help "Update list of top-level imports for completion"]))
278 ;; Fixme: add toolbar stuff for useful things like symbol help, send
279 ;; region, at least. (Shouldn't be specific to Python, obviously.)
280 ;; eric has items including: (un)indent, (un)comment, restart script,
281 ;; run script, debug script; also things for profiling, unit testing.
283 (defvar python-shell-map
284 (let ((map (copy-keymap comint-mode-map)))
285 (define-key map [tab] 'tab-to-tab-stop)
286 (define-key map "\C-c-" 'py-up-exception)
287 (define-key map "\C-c=" 'py-down-exception)
289 "Keymap used in *Python* shell buffers.")
291 (defvar python-mode-syntax-table
292 (let ((table (make-syntax-table)))
293 ;; Give punctuation syntax to ASCII that normally has symbol
294 ;; syntax or has word syntax and isn't a letter.
295 (let ((symbol (string-to-syntax "_"))
296 (sst (standard-syntax-table)))
299 (if (equal symbol (aref sst i))
300 (modify-syntax-entry i "." table)))))
301 (modify-syntax-entry ?$ "." table)
302 (modify-syntax-entry ?% "." table)
304 (modify-syntax-entry ?# "<" table)
305 (modify-syntax-entry ?\n ">" table)
306 (modify-syntax-entry ?' "\"" table)
307 (modify-syntax-entry ?` "$" table)
312 (defsubst python-in-string/comment ()
313 "Return non-nil if point is in a Python literal (a comment or string)."
314 ;; We don't need to save the match data.
315 (nth 8 (syntax-ppss)))
317 (defconst python-space-backslash-table
318 (let ((table (copy-syntax-table python-mode-syntax-table)))
319 (modify-syntax-entry ?\\ " " table)
321 "`python-mode-syntax-table' with backslash given whitespace syntax.")
323 (defun python-skip-comments/blanks (&optional backward)
324 "Skip comments and blank lines.
325 BACKWARD non-nil means go backwards, otherwise go forwards.
326 Backslash is treated as whitespace so that continued blank lines
327 are skipped. Doesn't move out of comments -- should be outside
329 (let ((arg (if backward
330 ;; If we're in a comment (including on the trailing
331 ;; newline), forward-comment doesn't move backwards out
332 ;; of it. Don't set the syntax table round this bit!
333 (let ((syntax (syntax-ppss)))
335 (goto-char (nth 8 syntax)))
338 (with-syntax-table python-space-backslash-table
339 (forward-comment arg))))
341 (defun python-backslash-continuation-line-p ()
342 "Non-nil if preceding line ends with backslash that is not in a comment."
343 (and (eq ?\\ (char-before (line-end-position 0)))
344 (not (syntax-ppss-context (syntax-ppss)))))
346 (defun python-continuation-line-p ()
347 "Return non-nil if current line continues a previous one.
348 The criteria are that the previous line ends in a backslash outside
349 comments and strings, or that point is within brackets/parens."
350 (or (python-backslash-continuation-line-p)
351 (let ((depth (syntax-ppss-depth
352 (save-excursion ; syntax-ppss with arg changes point
353 (syntax-ppss (line-beginning-position))))))
355 (if (< depth 0) ; Unbalanced brackets -- act locally
358 (progn (backward-up-list) t) ; actually within brackets
361 (defun python-comment-line-p ()
362 "Return non-nil iff current line has only a comment."
365 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
366 (back-to-indentation)
367 (looking-at (rx (or (syntax comment-start) line-end))))))
369 (defun python-blank-line-p ()
370 "Return non-nil iff current line is blank."
373 (looking-at "\\s-*$")))
375 (defun python-beginning-of-string ()
376 "Go to beginning of string around point.
377 Do nothing if not in string."
378 (let ((state (syntax-ppss)))
379 (when (eq 'string (syntax-ppss-context state))
380 (goto-char (nth 8 state)))))
382 (defun python-open-block-statement-p (&optional bos)
383 "Return non-nil if statement at point opens a block.
384 BOS non-nil means point is known to be at beginning of statement."
386 (unless bos (python-beginning-of-statement))
387 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
388 "class" "try" "except" "finally" "with")
391 (defun python-close-block-statement-p (&optional bos)
392 "Return non-nil if current line is a statement closing a block.
393 BOS non-nil means point is at beginning of statement.
394 The criteria are that the line isn't a comment or in string and
395 starts with keyword `raise', `break', `continue' or `pass'."
397 (unless bos (python-beginning-of-statement))
398 (back-to-indentation)
399 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
402 (defun python-outdent-p ()
403 "Return non-nil if current line should outdent a level."
405 (back-to-indentation)
406 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
408 (not (python-in-string/comment))
409 ;; Ensure there's a previous statement and move to it.
410 (zerop (python-previous-statement))
411 (not (python-close-block-statement-p t))
413 (not (python-open-block-statement-p)))))
417 (defcustom python-indent 4
418 "Number of columns for a unit of indentation in Python mode.
419 See also `\\[python-guess-indent]'"
422 (put 'python-indent 'safe-local-variable 'integerp)
424 (defcustom python-guess-indent t
425 "Non-nil means Python mode guesses `python-indent' for the buffer."
429 (defcustom python-indent-string-contents t
430 "Non-nil means indent contents of multi-line strings together.
431 This means indent them the same as the preceding non-blank line.
432 Otherwise preserve their indentation.
434 This only applies to `doc' strings, i.e. those that form statements;
435 the indentation is preserved in others."
436 :type '(choice (const :tag "Align with preceding" t)
437 (const :tag "Preserve indentation" nil))
440 (defcustom python-honour-comment-indentation nil
441 "Non-nil means indent relative to preceding comment line.
442 Only do this for comments where the leading comment character is
443 followed by space. This doesn't apply to comment lines, which
444 are always indented in lines with preceding comments."
448 (defcustom python-continuation-offset 4
449 "Number of columns of additional indentation for continuation lines.
450 Continuation lines follow a backslash-terminated line starting a
456 (defcustom python-default-interpreter 'cpython
457 "*Which Python interpreter is used by default.
458 The value for this variable can be either `cpython' or `jpython'.
460 When the value is `cpython', the variables `python-python-command' and
461 `python-python-command-args' are consulted to determine the interpreter
462 and arguments to use.
464 When the value is `jpython', the variables `python-jpython-command' and
465 `python-jpython-command-args' are consulted to determine the interpreter
466 and arguments to use.
468 Note that this variable is consulted only the first time that a Python
469 mode buffer is visited during an Emacs session. After that, use
470 \\[python-toggle-shells] to change the interpreter shell."
471 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
472 (const :tag "JPython" jpython))
475 (defcustom python-python-command-args '("-i")
476 "*List of string arguments to be used when starting a Python shell."
477 :type '(repeat string)
480 (defcustom python-jython-command-args '("-i")
481 "*List of string arguments to be used when starting a Jython shell."
482 :type '(repeat string)
484 :tag "JPython Command Args")
486 ;; for toggling between CPython and JPython
487 (defvar python-which-shell nil)
488 (defvar python-which-args python-python-command-args)
489 (defvar python-which-bufname "Python")
490 (make-variable-buffer-local 'python-which-shell)
491 (make-variable-buffer-local 'python-which-args)
492 (make-variable-buffer-local 'python-which-bufname)
494 (defcustom python-pdbtrack-do-tracking-p t
495 "*Controls whether the pdbtrack feature is enabled or not.
496 When non-nil, pdbtrack is enabled in all comint-based buffers,
497 e.g. shell buffers and the *Python* buffer. When using pdb to debug a
498 Python program, pdbtrack notices the pdb prompt and displays the
499 source file and line that the program is stopped at, much the same way
500 as gud-mode does for debugging C programs with gdb."
503 (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
505 ;; Bind python-file-queue before installing the kill-emacs-hook.
506 (defvar python-file-queue nil
507 "Queue of Python temp files awaiting execution.
508 Currently-active file is at the head of the list.")
510 (defvar python-pdbtrack-is-tracking-p nil)
512 (defconst python-pdbtrack-stack-entry-regexp
513 "> \\([^(]+\\)(\\([0-9]+\\))[?a-zA-Z0-9_]+()"
514 "Regular expression pdbtrack uses to find a stack trace entry.")
516 (defconst python-pdbtrack-input-prompt "\n[(<]?pdb[>)]? "
517 "Regular expression pdbtrack uses to recognize a pdb prompt.")
519 (defconst python-pdbtrack-track-range 10000
520 "Max number of characters from end of buffer to search for stack entry.")
522 (defun python-guess-indent ()
523 "Guess step for indentation of current buffer.
524 Set `python-indent' locally to the value guessed."
529 (goto-char (point-min))
531 (while (and (not done) (not (eobp)))
532 (when (and (re-search-forward (rx ?: (0+ space)
533 (or (syntax comment-start)
536 (python-open-block-statement-p))
538 (python-beginning-of-statement)
539 (let ((initial (current-indentation)))
540 (if (zerop (python-next-statement))
541 (setq indent (- (current-indentation) initial)))
542 (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
545 (when (/= indent (default-value 'python-indent))
546 (set (make-local-variable 'python-indent) indent)
547 (unless (= tab-width python-indent)
548 (setq indent-tabs-mode nil)))
551 ;; Alist of possible indentations and start of statement they would
552 ;; close. Used in indentation cycling (below).
553 (defvar python-indent-list nil
555 ;; Length of the above
556 (defvar python-indent-list-length nil
558 ;; Current index into the alist.
559 (defvar python-indent-index nil
562 (defun python-calculate-indentation ()
563 "Calculate Python indentation for line at point."
564 (setq python-indent-list nil
565 python-indent-list-length 1)
568 (let ((syntax (syntax-ppss))
571 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
572 (if (not python-indent-string-contents)
573 (current-indentation)
574 ;; Only respect `python-indent-string-contents' in doc
575 ;; strings (defined as those which form statements).
576 (if (not (save-excursion
577 (python-beginning-of-statement)
578 (looking-at (rx (or (syntax string-delimiter)
579 (syntax string-quote))))))
580 (current-indentation)
581 ;; Find indentation of preceding non-blank line within string.
582 (setq start (nth 8 syntax))
584 (while (and (< start (point)) (looking-at "\\s-*$"))
586 (current-indentation))))
587 ((python-continuation-line-p) ; after backslash, or bracketed
588 (let ((point (point))
589 (open-start (cadr syntax))
590 (backslash (python-backslash-continuation-line-p))
591 (colon (eq ?: (char-before (1- (line-beginning-position))))))
593 ;; Inside bracketed expression.
595 (goto-char (1+ open-start))
596 ;; Look for first item in list (preceding point) and
597 ;; align with it, if found.
598 (if (with-syntax-table python-space-backslash-table
599 (let ((parse-sexp-ignore-comments t))
601 (progn (forward-sexp)
605 ;; Extra level if we're backslash-continued or
607 (if (or backslash colon)
608 (+ python-indent (current-column))
610 ;; Otherwise indent relative to statement start, one
611 ;; level per bracketing level.
612 (goto-char (1+ open-start))
613 (python-beginning-of-statement)
614 (+ (current-indentation) (* (car syntax) python-indent))))
615 ;; Otherwise backslash-continued.
617 (if (python-continuation-line-p)
618 ;; We're past first continuation line. Align with
620 (current-indentation)
621 ;; First continuation line. Indent one step, with an
622 ;; extra one if statement opens a block.
623 (python-beginning-of-statement)
624 (+ (current-indentation) python-continuation-offset
625 (if (python-open-block-statement-p t)
629 ;; Fixme: Like python-mode.el; not convinced by this.
630 ((looking-at (rx (0+ space) (syntax comment-start)
631 (not (any " \t\n")))) ; non-indentable comment
632 (current-indentation))
633 (t (if python-honour-comment-indentation
634 ;; Back over whitespace, newlines, non-indentable comments.
638 ;; not at comment start
639 ((not (forward-comment -1))
640 (python-beginning-of-statement)
643 ((/= (current-column) (current-indentation))
644 (python-beginning-of-statement)
646 ;; indentable comment like python-mode.el
647 ((and (looking-at (rx (syntax comment-start)
648 (or space line-end)))
649 (/= 0 (current-column)))))
651 (python-indentation-levels)
652 ;; Prefer to indent comments with an immediately-following
657 (when (and (> python-indent-list-length 1)
658 (python-comment-line-p))
660 (unless (python-comment-line-p)
661 (let ((elt (assq (current-indentation) python-indent-list)))
662 (setq python-indent-list
663 (nconc (delete elt python-indent-list)
665 (caar (last python-indent-list)))))))
667 ;;;; Cycling through the possible indentations with successive TABs.
669 ;; These don't need to be buffer-local since they're only relevant
672 (defun python-initial-text ()
673 "Text of line following indentation and ignoring any trailing comment."
675 (buffer-substring (progn
676 (back-to-indentation)
683 (defconst python-block-pairs
684 '(("else" "if" "elif" "while" "for" "try" "except")
686 ("except" "try" "except")
688 "Alist of keyword matches.
689 The car of an element is a keyword introducing a statement which
690 can close a block opened by a keyword in the cdr.")
692 (defun python-first-word ()
693 "Return first word (actually symbol) on the line."
695 (back-to-indentation)
698 (defun python-indentation-levels ()
699 "Return a list of possible indentations for this line.
700 It is assumed not to be a continuation line or in a multi-line string.
701 Includes the default indentation and those which would close all
702 enclosing blocks. Elements of the list are actually pairs:
703 \(INDENTATION . TEXT), where TEXT is the initial text of the
704 corresponding block opening (or nil)."
708 ;; Only one possibility immediately following a block open
709 ;; statement, assuming it doesn't have a `suite' on the same line.
711 ((save-excursion (and (python-previous-statement)
712 (python-open-block-statement-p t)
713 (setq indent (current-indentation))
714 ;; Check we don't have something like:
716 (if (progn (python-end-of-statement)
717 (python-skip-comments/blanks t)
718 (eq ?: (char-before)))
719 (setq indent (+ python-indent indent)))))
720 (push (cons indent initial) levels))
721 ;; Only one possibility for comment line immediately following
724 (when (python-comment-line-p)
726 (if (python-comment-line-p)
727 (push (cons (current-indentation) initial) levels)))))
728 ;; Fixme: Maybe have a case here which indents (only) first
729 ;; line after a lambda.
731 (let ((start (car (assoc (python-first-word) python-block-pairs))))
732 (python-previous-statement)
733 ;; Is this a valid indentation for the line of interest?
734 (unless (or (if start ; potentially only outdentable
735 ;; Check for things like:
738 ;; where the second line need not be outdented.
739 (not (member (python-first-word)
741 python-block-pairs)))))
742 ;; Not sensible to indent to the same level as
743 ;; previous `return' &c.
744 (python-close-block-statement-p))
745 (push (cons (current-indentation) (python-initial-text))
747 (while (python-beginning-of-block)
748 (when (or (not start)
749 (member (python-first-word)
750 (cdr (assoc start python-block-pairs))))
751 (push (cons (current-indentation) (python-initial-text))
753 (prog1 (or levels (setq levels '((0 . ""))))
754 (setq python-indent-list levels
755 python-indent-list-length (length python-indent-list))))))
757 ;; This is basically what `python-indent-line' would be if we didn't
759 (defun python-indent-line-1 (&optional leave)
760 "Subroutine of `python-indent-line'.
761 Does non-repeated indentation. LEAVE non-nil means leave
762 indentation if it is valid, i.e. one of the positions returned by
763 `python-calculate-indentation'."
764 (let ((target (python-calculate-indentation))
765 (pos (- (point-max) (point))))
766 (if (or (= target (current-indentation))
767 ;; Maybe keep a valid indentation.
768 (and leave python-indent-list
769 (assq (current-indentation) python-indent-list)))
770 (if (< (current-column) (current-indentation))
771 (back-to-indentation))
773 (delete-horizontal-space)
775 (if (> (- (point-max) pos) (point))
776 (goto-char (- (point-max) pos))))))
778 (defun python-indent-line ()
779 "Indent current line as Python code.
780 When invoked via `indent-for-tab-command', cycle through possible
781 indentations for current line. The cycle is broken by a command
782 different from `indent-for-tab-command', i.e. successive TABs do
785 (if (and (eq this-command 'indent-for-tab-command)
786 (eq last-command this-command))
787 (if (= 1 python-indent-list-length)
788 (message "Sole indentation")
789 (progn (setq python-indent-index
790 (% (1+ python-indent-index) python-indent-list-length))
792 (delete-horizontal-space)
793 (indent-to (car (nth python-indent-index python-indent-list)))
794 (if (python-block-end-p)
795 (let ((text (cdr (nth python-indent-index
796 python-indent-list))))
798 (message "Closes: %s" text))))))
799 (python-indent-line-1)
800 (setq python-indent-index (1- python-indent-list-length))))
802 (defun python-indent-region (start end)
803 "`indent-region-function' for Python.
804 Leaves validly-indented lines alone, i.e. doesn't indent to
805 another valid position."
808 (setq end (point-marker))
810 (or (bolp) (forward-line 1))
811 (while (< (point) end)
812 (or (and (bolp) (eolp))
813 (python-indent-line-1 t))
815 (move-marker end nil)))
817 (defun python-block-end-p ()
818 "Non-nil if this is a line in a statement closing a block,
819 or a blank line indented to where it would close a block."
820 (and (not (python-comment-line-p))
821 (or (python-close-block-statement-p t)
822 (< (current-indentation)
824 (python-previous-statement)
825 (current-indentation))))))
829 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
830 ;; block, statement, depending on context.
832 (defun python-beginning-of-defun ()
833 "`beginning-of-defun-function' for Python.
834 Finds beginning of innermost nested class or method definition.
835 Returns the name of the definition found at the end, or nil if
836 reached start of buffer."
837 (let ((ci (current-indentation))
838 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
839 (group (1+ (or word (syntax symbol))))))
840 found lep) ;; def-line
841 (if (python-comment-line-p)
842 (setq ci most-positive-fixnum))
843 (while (and (not (bobp)) (not found))
844 ;; Treat bol at beginning of function as outside function so
845 ;; that successive C-M-a makes progress backwards.
846 ;;(setq def-line (looking-at def-re))
847 (unless (bolp) (end-of-line))
848 (setq lep (line-end-position))
849 (if (and (re-search-backward def-re nil 'move)
850 ;; Must be less indented or matching top level, or
851 ;; equally indented if we started on a definition line.
852 (let ((in (current-indentation)))
853 (or (and (zerop ci) (zerop in))
854 (= lep (line-end-position)) ; on initial line
855 ;; Not sure why it was like this -- fails in case of
856 ;; last internal function followed by first
857 ;; non-def statement of the main body.
858 ;;(and def-line (= in ci))
861 (not (python-in-string/comment)))
864 (defun python-end-of-defun ()
865 "`end-of-defun-function' for Python.
866 Finds end of innermost nested class or method definition."
868 (pattern (rx line-start (0+ space) (or "def" "class") space)))
869 ;; Go to start of current block and check whether it's at top
870 ;; level. If it is, and not a block start, look forward for
871 ;; definition statement.
872 (when (python-comment-line-p)
874 (forward-comment most-positive-fixnum))
875 (if (not (python-open-block-statement-p))
876 (python-beginning-of-block))
877 (if (zerop (current-indentation))
878 (unless (python-open-block-statement-p)
879 (while (and (re-search-forward pattern nil 'move)
880 (python-in-string/comment))) ; just loop
882 (beginning-of-line)))
883 ;; Don't move before top-level statement that would end defun.
885 (python-beginning-of-defun))
886 ;; If we got to the start of buffer, look forward for
887 ;; definition statement.
888 (if (and (bobp) (not (looking-at "def\\|class")))
889 (while (and (not (eobp))
890 (re-search-forward pattern nil 'move)
891 (python-in-string/comment)))) ; just loop
892 ;; We're at a definition statement (or end-of-buffer).
894 (python-end-of-block)
895 ;; Count trailing space in defun (but not trailing comments).
896 (skip-syntax-forward " >")
897 (unless (eobp) ; e.g. missing final newline
898 (beginning-of-line)))
899 ;; Catch pathological cases like this, where the beginning-of-defun
900 ;; skips to a definition we're not in:
908 (goto-char (point-max)))))
910 (defun python-beginning-of-statement ()
911 "Go to start of current statement.
912 Accounts for continuation lines, multi-line strings, and
913 multi-line bracketed expressions."
915 (python-beginning-of-string)
916 (while (python-continuation-line-p)
918 (if (python-backslash-continuation-line-p)
921 (while (python-backslash-continuation-line-p)
923 (python-beginning-of-string)
925 (back-to-indentation))
927 (defun python-skip-out (&optional forward syntax)
928 "Skip out of any nested brackets.
929 Skip forward if FORWARD is non-nil, else backward.
930 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
931 Return non-nil iff skipping was done."
932 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
933 (forward (if forward -1 1)))
934 (unless (zerop depth)
936 ;; Skip forward out of nested brackets.
937 (condition-case () ; beware invalid syntax
938 (progn (backward-up-list (* forward depth)) t)
940 ;; Invalid syntax (too many closed brackets).
941 ;; Skip out of as many as possible.
943 (while (condition-case ()
944 (progn (backward-up-list forward)
949 (defun python-end-of-statement ()
950 "Go to the end of the current statement and return point.
951 Usually this is the start of the next line, but if this is a
952 multi-line statement we need to skip over the continuation lines.
953 On a comment line, go to end of line."
955 (while (let (comment)
956 ;; Move past any enclosing strings and sexps, or stop if
957 ;; we're in a comment.
958 (while (let ((s (syntax-ppss)))
959 (cond ((eq 'comment (syntax-ppss-context s))
962 ((eq 'string (syntax-ppss-context s))
963 ;; Go to start of string and skip it.
965 (goto-char (nth 8 s))
966 (condition-case () ; beware invalid syntax
967 (progn (forward-sexp) t)
968 ;; If there's a mismatched string, make sure
969 ;; we still overall move *forward*.
970 (error (goto-char pos) (end-of-line)))))
971 ((python-skip-out t s))))
974 (eq ?\\ (char-before)))) ; Line continued?
975 (end-of-line 2)) ; Try next line.
978 (defun python-previous-statement (&optional count)
979 "Go to start of previous statement.
980 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
981 Return count of statements left to move."
983 (unless count (setq count 1))
985 (python-next-statement (- count))
986 (python-beginning-of-statement)
987 (while (and (> count 0) (not (bobp)))
988 (python-skip-comments/blanks t)
989 (python-beginning-of-statement)
990 (unless (bobp) (setq count (1- count))))
993 (defun python-next-statement (&optional count)
994 "Go to start of next statement.
995 With argument COUNT, do it COUNT times. Stop at end of buffer.
996 Return count of statements left to move."
998 (unless count (setq count 1))
1000 (python-previous-statement (- count))
1002 (while (and (> count 0) (not (eobp)))
1003 (python-end-of-statement)
1004 (python-skip-comments/blanks)
1006 (setq count (1- count))))
1009 (defun python-beginning-of-block (&optional arg)
1010 "Go to start of current block.
1011 With numeric arg, do it that many times. If ARG is negative, call
1012 `python-end-of-block' instead.
1013 If point is on the first line of a block, use its outer block.
1014 If current statement is in column zero, don't move and return nil.
1015 Otherwise return non-nil."
1017 (unless arg (setq arg 1))
1020 ((< arg 0) (python-end-of-block (- arg)))
1022 (let ((point (point)))
1023 (if (or (python-comment-line-p)
1024 (python-blank-line-p))
1025 (python-skip-comments/blanks t))
1026 (python-beginning-of-statement)
1027 (let ((ci (current-indentation)))
1029 (not (goto-char point)) ; return nil
1030 ;; Look upwards for less indented statement.
1032 ;;; This is slower than the below.
1033 ;;; (while (zerop (python-previous-statement))
1034 ;;; (when (and (< (current-indentation) ci)
1035 ;;; (python-open-block-statement-p t))
1036 ;;; (beginning-of-line)
1037 ;;; (throw 'done t)))
1038 (while (and (zerop (forward-line -1)))
1039 (when (and (< (current-indentation) ci)
1040 (not (python-comment-line-p))
1041 ;; Move to beginning to save effort in case
1042 ;; this is in string.
1043 (progn (python-beginning-of-statement) t)
1044 (python-open-block-statement-p t))
1047 (not (goto-char point))) ; Failed -- return nil
1048 (python-beginning-of-block (1- arg)))))))))
1050 (defun python-end-of-block (&optional arg)
1051 "Go to end of current block.
1052 With numeric arg, do it that many times. If ARG is negative,
1053 call `python-beginning-of-block' instead.
1054 If current statement is in column zero and doesn't open a block,
1055 don't move and return nil. Otherwise return t."
1057 (unless arg (setq arg 1))
1059 (python-beginning-of-block (- arg))
1060 (while (and (> arg 0)
1061 (let* ((point (point))
1062 (_ (if (python-comment-line-p)
1063 (python-skip-comments/blanks t)))
1064 (ci (current-indentation))
1065 (open (python-open-block-statement-p)))
1066 (if (and (zerop ci) (not open))
1067 (not (goto-char point))
1069 (while (zerop (python-next-statement))
1070 (when (or (and open (<= (current-indentation) ci))
1071 (< (current-indentation) ci))
1072 (python-skip-comments/blanks t)
1073 (beginning-of-line 2)
1074 (throw 'done t)))))))
1075 (setq arg (1- arg)))
1078 (defvar python-which-func-length-limit 40
1079 "Non-strict length limit for `python-which-func' output.")
1081 (defun python-which-func ()
1082 (let ((function-name (python-current-defun python-which-func-length-limit)))
1083 (set-text-properties 0 (length function-name) nil function-name)
1089 (defvar python-recursing)
1090 (defun python-imenu-create-index ()
1091 "`imenu-create-index-function' for Python.
1093 Makes nested Imenu menus from nested `class' and `def' statements.
1094 The nested menus are headed by an item referencing the outer
1095 definition; it has a space prepended to the name so that it sorts
1096 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1098 (unless (boundp 'python-recursing) ; dynamically bound below
1099 ;; Normal call from Imenu.
1100 (goto-char (point-min))
1101 ;; Without this, we can get an infloop if the buffer isn't all
1102 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1103 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1104 ;; what's going on, but it must be something to do with timers in
1106 ;; This can't be right, especially not when jit-lock is not used. --Stef
1107 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1108 ;; (font-lock-fontify-region (point-min) (point-max)))
1110 (let (index-alist) ; accumulated value to return
1111 (while (re-search-forward
1112 (rx line-start (0+ space) ; leading space
1113 (or (group "def") (group "class")) ; type
1114 (1+ space) (group (1+ (or word ?_)))) ; name
1116 (unless (python-in-string/comment)
1117 (let ((pos (match-beginning 0))
1118 (name (match-string-no-properties 3)))
1119 (if (match-beginning 2) ; def or class?
1120 (setq name (concat "class " name)))
1123 (let* ((python-recursing t)
1124 (sublist (python-imenu-create-index)))
1126 (progn (push (cons (concat " " name) pos) sublist)
1127 (push (cons name sublist) index-alist))
1128 (push (cons name pos) index-alist)))))))
1129 (unless (boundp 'python-recursing)
1130 ;; Look for module variables.
1132 (goto-char (point-min))
1133 (while (re-search-forward
1134 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1136 (unless (python-in-string/comment)
1137 (push (cons (match-string 1) (match-beginning 1))
1139 (setq index-alist (nreverse index-alist))
1141 (push (cons "Module variables"
1146 ;;;; `Electric' commands.
1148 (defun python-electric-colon (arg)
1149 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1150 With numeric ARG, just insert that many colons. With \\[universal-argument],
1151 just insert a single colon."
1153 (self-insert-command (if (not (integerp arg)) 1 arg))
1157 (not (python-in-string/comment))
1158 (> (current-indentation) (python-calculate-indentation))
1159 (python-indent-line))) ; OK, do it
1160 (put 'python-electric-colon 'delete-selection t)
1162 (defun python-backspace (arg)
1163 "Maybe delete a level of indentation on the current line.
1164 Do so if point is at the end of the line's indentation outside
1165 strings and comments.
1166 Otherwise just call `backward-delete-char-untabify'.
1169 (if (or (/= (current-indentation) (current-column))
1171 (python-continuation-line-p)
1172 (python-in-string/comment))
1173 (backward-delete-char-untabify arg)
1174 ;; Look for the largest valid indentation which is smaller than
1175 ;; the current indentation.
1177 (ci (current-indentation))
1178 (indents (python-indentation-levels))
1182 (setq indent (max indent (car x)))))
1183 (setq initial (cdr (assq indent indents)))
1184 (if (> (length initial) 0)
1185 (message "Closes %s" initial))
1186 (delete-horizontal-space)
1187 (indent-to indent))))
1188 (put 'python-backspace 'delete-selection 'supersede)
1192 (defcustom python-check-command "pychecker --stdlib"
1193 "Command used to check a Python file."
1197 (defvar python-saved-check-command nil
1200 ;; After `sgml-validate-command'.
1201 (defun python-check (command)
1202 "Check a Python file (default current buffer's file).
1203 Runs COMMAND, a shell command, as if by `compile'.
1204 See `python-check-command' for the default."
1206 (list (read-string "Checker command: "
1207 (or python-saved-check-command
1208 (concat python-check-command " "
1209 (let ((name (buffer-file-name)))
1211 (file-name-nondirectory name))))))))
1212 (setq python-saved-check-command command)
1213 (require 'compile) ;To define compilation-* variables.
1214 (save-some-buffers (not compilation-ask-about-save) nil)
1215 (let ((compilation-error-regexp-alist
1216 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1217 compilation-error-regexp-alist)))
1218 (compilation-start command)))
1220 ;;;; Inferior mode stuff (following cmuscheme).
1222 ;; Fixme: Make sure we can work with IPython.
1224 (defcustom python-python-command "python"
1225 "Shell command to run Python interpreter.
1226 Any arguments can't contain whitespace.
1227 Note that IPython may not work properly; it must at least be used
1228 with the `-cl' flag, i.e. use `ipython -cl'."
1232 (defcustom python-jython-command "jython"
1233 "Shell command to run Jython interpreter.
1234 Any arguments can't contain whitespace."
1238 (defvar python-command python-python-command
1239 "Actual command used to run Python.
1240 May be `python-python-command' or `python-jython-command', possibly
1241 modified by the user. Additional arguments are added when the command
1242 is used by `run-python' et al.")
1244 (defvar python-buffer nil
1245 "*The current Python process buffer.
1247 Commands that send text from source buffers to Python processes have
1248 to choose a process to send to. This is determined by buffer-local
1249 value of `python-buffer'. If its value in the current buffer,
1250 i.e. both any local value and the default one, is nil, `run-python'
1251 and commands that send to the Python process will start a new process.
1253 Whenever \\[run-python] starts a new process, it resets the default
1254 value of `python-buffer' to be the new process's buffer and sets the
1255 buffer-local value similarly if the current buffer is in Python mode
1256 or Inferior Python mode, so that source buffer stays associated with a
1257 specific sub-process.
1259 Use \\[python-set-proc] to set the default value from a buffer with a
1261 (make-variable-buffer-local 'python-buffer)
1263 (defconst python-compilation-regexp-alist
1264 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1265 ;; The first already is (for CAML), but the second isn't. Anyhow,
1266 ;; these are specific to the inferior buffer. -- fx
1267 `((,(rx line-start (1+ (any " \t")) "File \""
1268 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1269 "\", line " (group (1+ digit)))
1271 (,(rx " in file " (group (1+ not-newline)) " on line "
1275 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1276 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1278 "`compilation-error-regexp-alist' for inferior Python.")
1280 (defvar inferior-python-mode-map
1281 (let ((map (make-sparse-keymap)))
1282 ;; This will inherit from comint-mode-map.
1283 (define-key map "\C-c\C-l" 'python-load-file)
1284 (define-key map "\C-c\C-v" 'python-check)
1285 ;; Note that we _can_ still use these commands which send to the
1286 ;; Python process even at the prompt iff we have a normal prompt,
1287 ;; i.e. '>>> ' and not '... '. See the comment before
1288 ;; python-send-region. Fixme: uncomment these if we address that.
1290 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1291 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1294 (defvar inferior-python-mode-syntax-table
1295 (let ((st (make-syntax-table python-mode-syntax-table)))
1296 ;; Don't get confused by apostrophes in the process's output (e.g. if
1297 ;; you execute "help(os)").
1298 (modify-syntax-entry ?\' "." st)
1299 ;; Maybe we should do the same for double quotes?
1300 ;; (modify-syntax-entry ?\" "." st)
1304 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1306 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1307 ;; not sure how much: at least some keybindings, like C-c C-f;
1308 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1309 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1310 "Major mode for interacting with an inferior Python process.
1311 A Python process can be started with \\[run-python].
1313 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1316 You can send text to the inferior Python process from other buffers
1317 containing Python source.
1318 * \\[python-switch-to-python] switches the current buffer to the Python
1320 * \\[python-send-region] sends the current region to the Python process.
1321 * \\[python-send-region-and-go] switches to the Python process buffer
1322 after sending the text.
1323 For running multiple processes in multiple buffers, see `run-python' and
1326 \\{inferior-python-mode-map}"
1328 (setq mode-line-process '(":%s"))
1329 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1330 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1332 ;; Still required by `comint-redirect-send-command', for instance
1333 ;; (and we need to match things like `>>> ... >>> '):
1334 (set (make-local-variable 'comint-prompt-regexp)
1335 (rx line-start (1+ (and (or (repeat 3 (any ">.")) "(Pdb)") " "))))
1336 (set (make-local-variable 'compilation-error-regexp-alist)
1337 python-compilation-regexp-alist)
1338 (compilation-shell-minor-mode 1))
1340 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1341 "Input matching this regexp is not saved on the history list.
1342 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1346 (defun python-input-filter (str)
1347 "`comint-input-filter' function for inferior Python.
1348 Don't save anything for STR matching `inferior-python-filter-regexp'."
1349 (not (string-match inferior-python-filter-regexp str)))
1351 ;; Fixme: Loses with quoted whitespace.
1352 (defun python-args-to-list (string)
1353 (let ((where (string-match "[ \t]" string)))
1354 (cond ((null where) (list string))
1356 (cons (substring string 0 where)
1357 (python-args-to-list (substring string (+ 1 where)))))
1358 (t (let ((pos (string-match "[^ \t]" string)))
1359 (if pos (python-args-to-list (substring string pos))))))))
1361 (defvar python-preoutput-result nil
1362 "Data from last `_emacs_out' line seen by the preoutput filter.")
1364 (defvar python-preoutput-leftover nil)
1365 (defvar python-preoutput-skip-next-prompt nil)
1367 ;; Using this stops us getting lines in the buffer like
1369 (defun python-preoutput-filter (s)
1370 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1371 (when python-preoutput-leftover
1372 (setq s (concat python-preoutput-leftover s))
1373 (setq python-preoutput-leftover nil))
1376 ;; First process whole lines.
1377 (while (string-match "\n" s start)
1378 (let ((line (substring s start (setq start (match-end 0)))))
1379 ;; Skip prompt if needed.
1380 (when (and python-preoutput-skip-next-prompt
1381 (string-match comint-prompt-regexp line))
1382 (setq python-preoutput-skip-next-prompt nil)
1383 (setq line (substring line (match-end 0))))
1384 ;; Recognize special _emacs_out lines.
1385 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1386 (local-variable-p 'python-preoutput-result))
1388 (setq python-preoutput-result (match-string 1 line))
1389 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1390 (setq res (concat res line)))))
1391 ;; Then process the remaining partial line.
1392 (unless (zerop start) (setq s (substring s start)))
1393 (cond ((and (string-match comint-prompt-regexp s)
1394 ;; Drop this prompt if it follows an _emacs_out...
1395 (or python-preoutput-skip-next-prompt
1396 ;; ... or if it's not gonna be inserted at BOL.
1397 ;; Maybe we could be more selective here.
1398 (if (zerop (length res))
1400 (string-match ".\\'" res))))
1401 ;; The need for this seems to be system-dependent:
1402 ;; What is this all about, exactly? --Stef
1403 ;; (if (and (eq ?. (aref s 0)))
1404 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1405 (setq python-preoutput-skip-next-prompt nil)
1407 ((let ((end (min (length "_emacs_out ") (length s))))
1408 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1409 ;; The leftover string is a prefix of _emacs_out so we don't know
1410 ;; yet whether it's an _emacs_out or something else: wait until we
1411 ;; get more output so we can resolve this ambiguity.
1412 (set (make-local-variable 'python-preoutput-leftover) s)
1414 (t (concat res s)))))
1416 (autoload 'comint-check-proc "comint")
1419 (defun run-python (&optional cmd noshow new)
1420 "Run an inferior Python process, input and output via buffer *Python*.
1421 CMD is the Python command to run. NOSHOW non-nil means don't show the
1422 buffer automatically.
1424 Normally, if there is a process already running in `python-buffer',
1425 switch to that buffer. Interactively, a prefix arg allows you to edit
1426 the initial command line (default is `python-command'); `-i' etc. args
1427 will be added to this as appropriate. A new process is started if:
1428 one isn't running attached to `python-buffer', or interactively the
1429 default `python-command', or argument NEW is non-nil. See also the
1430 documentation for `python-buffer'.
1432 Runs the hook `inferior-python-mode-hook' \(after the
1433 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1434 buffer for a list of commands.)"
1435 (interactive (if current-prefix-arg
1436 (list (read-string "Run Python: " python-command) nil t)
1437 (list python-command)))
1438 (unless cmd (setq cmd python-python-command))
1439 (setq python-command cmd)
1440 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1441 ;; (not a name) in Python buffers from which `run-python' &c is
1442 ;; invoked. Would support multiple processes better.
1443 (when (or new (not (comint-check-proc python-buffer)))
1444 (with-current-buffer
1445 (let* ((cmdlist (append (python-args-to-list cmd) '("-i")))
1446 (path (getenv "PYTHONPATH"))
1447 (process-environment ; to import emacs.py
1448 (cons (concat "PYTHONPATH=" data-directory
1449 (if path (concat path-separator path)))
1450 process-environment)))
1451 (apply 'make-comint-in-buffer "Python"
1452 (if new (generate-new-buffer "*Python*") "*Python*")
1453 (car cmdlist) nil (cdr cmdlist)))
1454 (setq-default python-buffer (current-buffer))
1455 (setq python-buffer (current-buffer))
1456 (accept-process-output (get-buffer-process python-buffer) 5)
1457 (inferior-python-mode)
1458 ;; Load function definitions we need.
1459 ;; Before the preoutput function was used, this was done via -c in
1460 ;; cmdlist, but that loses the banner and doesn't run the startup
1461 ;; file. The code might be inline here, but there's enough that it
1462 ;; seems worth putting in a separate file, and it's probably cleaner
1463 ;; to put it in a module.
1464 ;; Ensure we're at a prompt before doing anything else.
1465 (python-send-string "import emacs")))
1466 (if (derived-mode-p 'python-mode)
1467 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1468 ;; Without this, help output goes into the inferior python buffer if
1469 ;; the process isn't already running.
1470 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1471 (unless noshow (pop-to-buffer python-buffer t)))
1473 ;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1474 ;; e.g. prompt is `help> '. Probably raise an error if the form of
1475 ;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1476 ;; `... ', i.e. we're not inputting a block &c. However, this may not
1477 ;; be the place to check it, e.g. we might actually want to send
1478 ;; commands having set up such a state.
1480 (defun python-send-command (command)
1481 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1482 COMMAND should be a single statement."
1483 ;; (assert (not (string-match "\n" command)))
1484 ;; (let ((end (marker-position (process-mark (python-proc)))))
1485 (with-current-buffer (process-buffer (python-proc))
1486 (goto-char (point-max))
1487 (compilation-forget-errors)
1488 (python-send-string command)
1489 (setq compilation-last-buffer (current-buffer)))
1490 ;; No idea what this is for but it breaks the call to
1491 ;; compilation-fake-loc in python-send-region. -- Stef
1492 ;; Must wait until this has completed before re-setting variables below.
1493 ;; (python-send-receive "print '_emacs_out ()'")
1494 ;; (with-current-buffer python-buffer
1495 ;; (set-marker compilation-parsing-end end))
1498 (defun python-send-region (start end)
1499 "Send the region to the inferior Python process."
1500 ;; The region is evaluated from a temporary file. This avoids
1501 ;; problems with blank lines, which have different semantics
1502 ;; interactively and in files. It also saves the inferior process
1503 ;; buffer filling up with interpreter prompts. We need a Python
1504 ;; function to remove the temporary file when it has been evaluated
1505 ;; (though we could probably do it in Lisp with a Comint output
1506 ;; filter). This function also catches exceptions and truncates
1507 ;; tracebacks not to mention the frame of the function itself.
1509 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1510 ;; the reference to the temporary file to the source.
1512 ;; Fixme: Write a `coding' header to the temp file if the region is
1515 (let* ((f (make-temp-file "py"))
1516 (command (format "emacs.eexecfile(%S)" f))
1517 (orig-start (copy-marker start)))
1518 (when (save-excursion
1520 (/= 0 (current-indentation))) ; need dummy block
1522 (goto-char orig-start)
1523 ;; Wrong if we had indented code at buffer start.
1524 (set-marker orig-start (line-beginning-position 0)))
1525 (write-region "if True:\n" nil f nil 'nomsg))
1526 (write-region start end f t 'nomsg)
1527 (python-send-command command)
1528 (with-current-buffer (process-buffer (python-proc))
1529 ;; Tell compile.el to redirect error locations in file `f' to
1530 ;; positions past marker `orig-start'. It has to be done *after*
1531 ;; `python-send-command''s call to `compilation-forget-errors'.
1532 (compilation-fake-loc orig-start f))))
1534 (defun python-send-string (string)
1535 "Evaluate STRING in inferior Python process."
1536 (interactive "sPython command: ")
1537 (comint-send-string (python-proc) string)
1538 (unless (string-match "\n\\'" string)
1539 ;; Make sure the text is properly LF-terminated.
1540 (comint-send-string (python-proc) "\n"))
1541 (when (string-match "\n[ \t].*\n?\\'" string)
1542 ;; If the string contains a final indented line, add a second newline so
1543 ;; as to make sure we terminate the multiline instruction.
1544 (comint-send-string (python-proc) "\n")))
1546 (defun python-send-buffer ()
1547 "Send the current buffer to the inferior Python process."
1549 (python-send-region (point-min) (point-max)))
1551 ;; Fixme: Try to define the function or class within the relevant
1552 ;; module, not just at top level.
1553 (defun python-send-defun ()
1554 "Send the current defun (class or method) to the inferior Python process."
1556 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1557 (progn (end-of-defun) (point)))))
1559 (defun python-switch-to-python (eob-p)
1560 "Switch to the Python process buffer, maybe starting new process.
1561 With prefix arg, position cursor at end of buffer."
1563 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1566 (goto-char (point-max))))
1568 (defun python-send-region-and-go (start end)
1569 "Send the region to the inferior Python process.
1570 Then switch to the process buffer."
1572 (python-send-region start end)
1573 (python-switch-to-python t))
1575 (defcustom python-source-modes '(python-mode jython-mode)
1576 "Used to determine if a buffer contains Python source code.
1577 If a file is loaded into a buffer that is in one of these major modes,
1578 it is considered Python source by `python-load-file', which uses the
1579 value to determine defaults."
1580 :type '(repeat function)
1583 (defvar python-prev-dir/file nil
1584 "Caches (directory . file) pair used in the last `python-load-file' command.
1585 Used for determining the default in the next one.")
1587 (autoload 'comint-get-source "comint")
1589 (defun python-load-file (file-name)
1590 "Load a Python file FILE-NAME into the inferior Python process.
1591 If the file has extension `.py' import or reload it as a module.
1592 Treating it as a module keeps the global namespace clean, provides
1593 function location information for debugging, and supports users of
1594 module-qualified names."
1595 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1597 t)) ; because execfile needs exact name
1598 (comint-check-source file-name) ; Check to see if buffer needs saving.
1599 (setq python-prev-dir/file (cons (file-name-directory file-name)
1600 (file-name-nondirectory file-name)))
1601 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1602 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1603 (python-send-command
1604 (if (string-match "\\.py\\'" file-name)
1605 (let ((module (file-name-sans-extension
1606 (file-name-nondirectory file-name))))
1607 (format "emacs.eimport(%S,%S)"
1608 module (file-name-directory file-name)))
1609 (format "execfile(%S)" file-name)))
1610 (message "%s loaded" file-name)))
1612 (defun python-proc ()
1613 "Return the current Python process.
1614 See variable `python-buffer'. Starts a new process if necessary."
1615 ;; Fixme: Maybe should look for another active process if there
1616 ;; isn't one for `python-buffer'.
1617 (unless (comint-check-proc python-buffer)
1619 (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
1623 (defun python-set-proc ()
1624 "Set the default value of `python-buffer' to correspond to this buffer.
1625 If the current buffer has a local value of `python-buffer', set the
1626 default (global) value to that. The associated Python process is
1627 the one that gets input from \\[python-send-region] et al when used
1628 in a buffer that doesn't have a local value of `python-buffer'."
1630 (if (local-variable-p 'python-buffer)
1631 (setq-default python-buffer python-buffer)
1632 (error "No local value of `python-buffer'")))
1634 ;;;; Context-sensitive help.
1636 (defconst python-dotty-syntax-table
1637 (let ((table (make-syntax-table)))
1638 (set-char-table-parent table python-mode-syntax-table)
1639 (modify-syntax-entry ?. "_" table)
1641 "Syntax table giving `.' symbol syntax.
1642 Otherwise inherits from `python-mode-syntax-table'.")
1644 (defvar view-return-to-alist)
1645 (eval-when-compile (autoload 'help-buffer "help-fns"))
1647 (defvar python-imports) ; forward declaration
1649 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1650 ;; bound to C-h S? [Probably not, since info-look may work in cases
1651 ;; where this doesn't.]
1652 (defun python-describe-symbol (symbol)
1653 "Get help on SYMBOL using `help'.
1654 Interactively, prompt for symbol.
1656 Symbol may be anything recognized by the interpreter's `help'
1657 command -- e.g. `CALLS' -- not just variables in scope in the
1658 interpreter. This only works for Python version 2.2 or newer
1659 since earlier interpreters don't support `help'.
1661 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1663 ;; Note that we do this in the inferior process, not a separate one, to
1664 ;; ensure the environment is appropriate.
1666 (let ((symbol (with-syntax-table python-dotty-syntax-table
1668 (enable-recursive-minibuffers t))
1669 (list (read-string (if symbol
1670 (format "Describe symbol (default %s): " symbol)
1671 "Describe symbol: ")
1673 (if (equal symbol "") (error "No symbol"))
1674 ;; Ensure we have a suitable help buffer.
1675 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1676 ;; allow C-c C-f in help buffer.
1677 (let ((temp-buffer-show-hook ; avoid xref stuff
1679 (toggle-read-only 1)
1680 (setq view-return-to-alist
1681 (list (cons (selected-window) help-return-method))))))
1682 (with-output-to-temp-buffer (help-buffer)
1683 (with-current-buffer standard-output
1684 ;; Fixme: Is this actually useful?
1685 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p))
1686 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1687 (print-help-return-message))))
1688 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1689 symbol python-imports)
1690 "*Help*" (python-proc) nil nil))
1692 (add-to-list 'debug-ignored-errors "^No symbol")
1694 (defun python-send-receive (string)
1695 "Send STRING to inferior Python (if any) and return result.
1696 The result is what follows `_emacs_out' in the output."
1697 (python-send-string string)
1698 (let ((proc (python-proc)))
1699 (with-current-buffer (process-buffer proc)
1700 (set (make-local-variable 'python-preoutput-result) nil)
1702 (accept-process-output proc 5)
1703 (null python-preoutput-result)))
1704 (prog1 python-preoutput-result
1705 (kill-local-variable 'python-preoutput-result)))))
1707 ;; Fixme: Is there anything reasonable we can do with random methods?
1708 ;; (Currently only works with functions.)
1709 (defun python-eldoc-function ()
1710 "`eldoc-documentation-function' for Python.
1711 Only works when point is in a function name, not its arg list, for
1712 instance. Assumes an inferior Python is running."
1713 (let ((symbol (with-syntax-table python-dotty-syntax-table
1715 ;; This is run from timers, so inhibit-quit tends to be set.
1717 ;; First try the symbol we're on.
1719 (python-send-receive (format "emacs.eargs(%S, %s)"
1720 symbol python-imports)))
1721 ;; Try moving to symbol before enclosing parens.
1722 (let ((s (syntax-ppss)))
1723 (unless (zerop (car s))
1724 (when (eq ?\( (char-after (nth 1 s)))
1726 (goto-char (nth 1 s))
1727 (skip-syntax-backward "-")
1728 (let ((point (point)))
1729 (skip-chars-backward "a-zA-Z._")
1730 (if (< (point) point)
1731 (python-send-receive
1732 (format "emacs.eargs(%S, %s)"
1733 (buffer-substring-no-properties (point) point)
1734 python-imports))))))))))))
1736 ;;;; Info-look functionality.
1738 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1740 (defun python-after-info-look ()
1741 "Set up info-look for Python.
1742 Used with `eval-after-load'."
1743 (let* ((version (let ((s (shell-command-to-string (concat python-command
1745 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1746 (match-string 1 s)))
1747 ;; Whether info files have a Python version suffix, e.g. in Debian.
1750 (with-no-warnings (Info-mode))
1752 ;; Don't use `info' because it would pop-up a *info* buffer.
1754 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1758 (info-lookup-maybe-add-help
1760 :regexp "[[:alnum:]_]+"
1762 ;; Fixme: Can this reasonably be made specific to indices with
1763 ;; different rules? Is the order of indices optimal?
1764 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1767 ;; The empty prefix just gets us highlighted terms.
1768 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1769 (,(concat "(python" version "-ref)Module Index" nil ""))
1770 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1772 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1774 (,(concat "(python" version "-lib)Module Index" nil ""))
1775 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1777 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1779 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1780 '(("(python-ref)Miscellaneous Index" nil "")
1781 ("(python-ref)Module Index" nil "")
1782 ("(python-ref)Function-Method-Variable Index" nil "")
1783 ("(python-ref)Class-Exception-Object Index" nil "")
1784 ("(python-lib)Module Index" nil "")
1785 ("(python-lib)Class-Exception-Object Index" nil "")
1786 ("(python-lib)Function-Method-Variable Index" nil "")
1787 ("(python-lib)Miscellaneous Index" nil ""))))))
1788 (eval-after-load "info-look" '(python-after-info-look))
1792 (defcustom python-jython-packages '("java" "javax" "org" "com")
1793 "Packages implying `jython-mode'.
1794 If these are imported near the beginning of the buffer, `python-mode'
1795 actually punts to `jython-mode'."
1796 :type '(repeat string)
1799 ;; Called from `python-mode', this causes a recursive call of the
1800 ;; mode. See logic there to break out of the recursion.
1801 (defun python-maybe-jython ()
1802 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1803 The criterion is either a match for `jython-mode' via
1804 `interpreter-mode-alist' or an import of a module from the list
1805 `python-jython-packages'."
1806 ;; The logic is taken from python-mode.el.
1810 (goto-char (point-min))
1811 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1813 (if (and interpreter (eq 'jython-mode
1814 (cdr (assoc (file-name-nondirectory
1816 interpreter-mode-alist))))
1819 (while (re-search-forward
1820 (rx line-start (or "import" "from") (1+ space)
1821 (group (1+ (not (any " \t\n.")))))
1822 (+ (point-min) 10000) ; Probably not worth customizing.
1824 (if (member (match-string 1) python-jython-packages)
1828 (defun python-fill-paragraph (&optional justify)
1829 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1830 If any of the current line is in or at the end of a multi-line string,
1831 fill the string or the paragraph of it that point is in, preserving
1832 the strings's indentation."
1834 (or (fill-comment-paragraph justify)
1837 (let* ((syntax (syntax-ppss))
1840 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
1841 (let (fill-paragraph-function)
1842 (fill-paragraph justify)))
1843 ;; The `paragraph-start' and `paragraph-separate'
1844 ;; variables don't allow us to delimit the last
1845 ;; paragraph in a multi-line string properly, so narrow
1846 ;; to the string and then fill around (the end of) the
1848 ((eq t (nth 3 syntax)) ; in fenced string
1849 (goto-char (nth 8 syntax)) ; string start
1850 (setq start (line-beginning-position))
1851 (setq end (condition-case () ; for unbalanced quotes
1852 (progn (forward-sexp)
1854 (error (point-max)))))
1855 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
1859 (progn (backward-sexp)
1860 (setq start (line-beginning-position)))
1864 (narrow-to-region start end)
1866 ;; Avoid losing leading and trailing newlines in doc
1867 ;; strings written like:
1871 (let* ((paragraph-separate
1872 (concat ".*\\s|\"\"$" ; newline after opening quotes
1873 "\\|\\(?:" paragraph-separate "\\)"))
1875 (concat ".*\\s|\"\"[ \t]*[^ \t].*" ; not newline after
1877 "\\|\\(?:" paragraph-separate "\\)"))
1878 (fill-paragraph-function))
1879 (fill-paragraph justify))))))) t)
1881 (defun python-shift-left (start end &optional count)
1882 "Shift lines in region COUNT (the prefix arg) columns to the left.
1883 COUNT defaults to `python-indent'. If region isn't active, just shift
1884 current line. The region shifted includes the lines in which START and
1885 END lie. It is an error if any lines in the region are indented less than
1887 (interactive (if mark-active
1888 (list (region-beginning) (region-end) current-prefix-arg)
1889 (list (point) (point) current-prefix-arg)))
1891 (setq count (prefix-numeric-value count))
1892 (setq count python-indent))
1896 (while (< (point) end)
1897 (if (and (< (current-indentation) count)
1898 (not (looking-at "[ \t]*$")))
1899 (error "Can't shift all lines enough"))
1901 (indent-rigidly start end (- count)))))
1903 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1905 (defun python-shift-right (start end &optional count)
1906 "Shift lines in region COUNT (the prefix arg) columns to the right.
1907 COUNT defaults to `python-indent'. If region isn't active, just shift
1908 current line. The region shifted includes the lines in which START and
1910 (interactive (if mark-active
1911 (list (region-beginning) (region-end) current-prefix-arg)
1912 (list (point) (point) current-prefix-arg)))
1914 (setq count (prefix-numeric-value count))
1915 (setq count python-indent))
1916 (indent-rigidly start end count))
1918 (defun python-outline-level ()
1919 "`outline-level' function for Python mode.
1920 The level is the number of `python-indent' steps of indentation
1922 (1+ (/ (current-indentation) python-indent)))
1924 ;; Fixme: Consider top-level assignments, imports, &c.
1925 (defun python-current-defun (&optional length-limit)
1926 "`add-log-current-defun-function' for Python."
1928 ;; Move up the tree of nested `class' and `def' blocks until we
1929 ;; get to zero indentation, accumulating the defined names.
1933 (while (or (null length-limit)
1935 (< length length-limit))
1936 (let ((started-from (point)))
1937 (python-beginning-of-block)
1939 (beginning-of-defun)
1940 (when (= (point) started-from)
1942 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
1943 (group (1+ (or word (syntax symbol))))))
1944 (push (match-string 1) accum)
1945 (setq length (+ length 1 (length (car accum)))))
1946 (when (= (current-indentation) 0)
1947 (throw 'done nil))))
1949 (when (and length-limit (> length length-limit))
1950 (setcar accum ".."))
1951 (mapconcat 'identity accum ".")))))
1953 (defun python-mark-block ()
1954 "Mark the block around point.
1955 Uses `python-beginning-of-block', `python-end-of-block'."
1958 (python-beginning-of-block)
1959 (push-mark (point) nil t)
1960 (python-end-of-block)
1961 (exchange-point-and-mark))
1963 ;; Fixme: Provide a find-function-like command to find source of a
1964 ;; definition (separate from BicycleRepairMan). Complicated by
1965 ;; finding the right qualified name.
1969 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
1970 (defvar python-imports "None"
1971 "String of top-level import statements updated by `python-find-imports'.")
1972 (make-variable-buffer-local 'python-imports)
1974 ;; Fixme: Should font-lock try to run this when it deals with an import?
1975 ;; Maybe not a good idea if it gets run multiple times when the
1976 ;; statement is being edited, and is more likely to end up with
1977 ;; something syntactically incorrect.
1978 ;; However, what we should do is to trundle up the block tree from point
1979 ;; to extract imports that appear to be in scope, and add those.
1980 (defun python-find-imports ()
1981 "Find top-level imports, updating `python-imports'."
1985 (goto-char (point-min))
1986 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
1987 (unless (syntax-ppss-context (syntax-ppss))
1988 (let ((start (line-beginning-position)))
1989 ;; Skip over continued lines.
1990 (while (and (eq ?\\ (char-before (line-end-position)))
1991 (= 0 (forward-line 1))))
1992 (push (buffer-substring start (line-beginning-position 2))
1994 (setq python-imports
1997 ;; This is probably best left out since you're unlikely to need the
1998 ;; doc for a function in the buffer and the import will lose if the
1999 ;; Python sub-process' working directory isn't the same as the
2001 ;; (if buffer-file-name
2004 ;; (file-name-sans-extension
2005 ;; (file-name-nondirectory buffer-file-name))))
2009 (set-text-properties 0 (length python-imports) nil python-imports)
2010 ;; The output ends up in the wrong place if the string we
2011 ;; send contains newlines (from the imports).
2012 (setq python-imports
2013 (replace-regexp-in-string "\n" "\\n"
2014 (format "%S" python-imports) t t))))))
2016 ;; Fixme: This fails the first time if the sub-process isn't already
2017 ;; running. Presumably a timing issue with i/o to the process.
2018 (defun python-symbol-completions (symbol)
2019 "Return a list of completions of the string SYMBOL from Python process.
2021 Uses `python-imports' to load modules against which to complete."
2025 (car (read-from-string
2026 (python-send-receive
2027 (format "emacs.complete(%S,%s)" symbol python-imports))))
2030 ;; We can get duplicates from the above -- don't know why.
2031 (delete-dups completions)
2034 (defun python-partial-symbol ()
2035 "Return the partial symbol before point (for completion)."
2037 (start (save-excursion
2038 (and (re-search-backward
2039 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2040 (group (1+ (regexp "[[:alnum:]._]"))) point)
2042 (match-beginning 1)))))
2043 (if start (buffer-substring-no-properties start end))))
2045 (defun python-complete-symbol ()
2046 "Perform completion on the Python symbol preceding point.
2047 Repeating the command scrolls the completion window."
2049 (let ((window (get-buffer-window "*Completions*")))
2050 (if (and (eq last-command this-command)
2051 (window-live-p window) (window-buffer window)
2052 (buffer-name (window-buffer window)))
2053 (with-current-buffer (window-buffer window)
2054 (if (pos-visible-in-window-p (point-max) window)
2055 (set-window-start window (point-min))
2056 (save-selected-window
2057 (select-window window)
2060 (let* ((end (point))
2061 (symbol (python-partial-symbol))
2062 (completions (python-symbol-completions symbol))
2063 (completion (if completions
2064 (try-completion symbol completions))))
2066 (cond ((eq completion t))
2068 (message "Can't find completion for \"%s\"" symbol)
2070 ((not (string= symbol completion))
2071 (delete-region (- end (length symbol)) end)
2072 (insert completion))
2074 (message "Making completion list...")
2075 (with-output-to-temp-buffer "*Completions*"
2076 (display-completion-list completions symbol))
2077 (message "Making completion list...%s" "done"))))))))
2079 (defun python-try-complete (old)
2080 "Completion function for Python for use with `hippie-expand'."
2081 (when (derived-mode-p 'python-mode) ; though we only add it locally
2083 (let ((symbol (python-partial-symbol)))
2084 (he-init-string (- (point) (length symbol)) (point))
2085 (if (not (he-string-member he-search-string he-tried-table))
2086 (push he-search-string he-tried-table))
2087 (setq he-expand-list
2088 (and symbol (python-symbol-completions symbol)))))
2089 (while (and he-expand-list
2090 (he-string-member (car he-expand-list) he-tried-table))
2091 (pop he-expand-list))
2094 (he-substitute-string (pop he-expand-list))
2096 (if old (he-reset-string))
2101 (defun python-module-path (module)
2102 "Function for `ffap-alist' to return path to MODULE."
2103 (python-send-receive (format "emacs.modpath (%S)" module)))
2105 (eval-after-load "ffap"
2106 '(push '(python-mode . python-module-path) ffap-alist))
2110 (defcustom python-use-skeletons nil
2111 "Non-nil means template skeletons will be automagically inserted.
2112 This happens when pressing \"if<SPACE>\", for example, to prompt for
2117 (defvar python-skeletons nil
2118 "Alist of named skeletons for Python mode.
2119 Elements are of the form (NAME . EXPANDER-FUNCTION).")
2121 (define-abbrev-table 'python-mode-abbrev-table ()
2122 "Abbrev table for Python mode.
2123 The default contents correspond to the elements of `python-skeletons'."
2124 ;; Allow / in abbrevs.
2125 :regexp "\\<\\([[:word:]/]+\\)\\W*")
2128 ;; Define a user-level skeleton and add it to `python-skeletons' and
2129 ;; the abbrev table.
2130 (defmacro def-python-skeleton (name &rest elements)
2131 (let* ((name (symbol-name name))
2132 (function (intern (concat "python-insert-" name))))
2134 (add-to-list 'python-skeletons ',(cons name function))
2135 (define-abbrev python-mode-abbrev-table ,name "" ',function
2136 :system t :case-fixed t
2137 :enable-function (lambda () python-use-skeletons))
2138 (define-skeleton ,function
2139 ,(format "Insert Python \"%s\" template." name)
2141 (put 'def-python-skeleton 'lisp-indent-function 2)
2143 ;; From `skeleton-further-elements':
2144 ;; `<': outdent a level;
2145 ;; `^': delete indentation on current line and also previous newline.
2146 ;; Not quote like `delete-indentation'. Assumes point is at
2147 ;; beginning of indentation.
2149 (def-python-skeleton if
2153 ("other condition, %s: "
2154 < ; Avoid wrong indentation after block opening.
2159 (define-skeleton python-else
2160 "Auxiliary skeleton."
2162 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2167 (def-python-skeleton while
2173 (def-python-skeleton for
2175 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2179 (def-python-skeleton try/except
2184 < "except " str '(python-target) ":" \n
2190 (define-skeleton python-target
2191 "Auxiliary skeleton."
2192 "Target, %s: " ", " str | -2)
2194 (def-python-skeleton try/finally
2201 (def-python-skeleton def
2203 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2205 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2208 (def-python-skeleton class
2210 "class " str " (" ("Inheritance, %s: "
2211 (unless (equal ?\( (char-before)) ", ")
2213 & ")" | -2 ; close list or remove opening
2215 "\"\"\"" @ " \"\"\"" \n
2218 (defvar python-default-template "if"
2219 "Default template to expand by `python-expand-template'.
2220 Updated on each expansion.")
2222 (defun python-expand-template (name)
2223 "Expand template named NAME.
2224 Interactively, prompt for the name with completion."
2226 (list (completing-read (format "Template to expand (default %s): "
2227 python-default-template)
2228 python-skeletons nil t)))
2230 (setq name python-default-template)
2231 (setq python-default-template name))
2232 (let ((func (cdr (assoc name python-skeletons))))
2235 (error "Undefined template: %s" name))))
2237 ;;;; Bicycle Repair Man support
2239 (autoload 'pymacs-load "pymacs" nil t)
2240 (autoload 'brm-init "bikemacs")
2242 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2243 ;; the way it modifies files outside Emacs... Also note that the
2244 ;; current BRM loses with tabs used for indentation -- I submitted a
2245 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2246 (defun python-setup-brm ()
2247 "Set up Bicycle Repair Man refactoring tool (if available).
2249 Note that the `refactoring' features change files independently of
2250 Emacs and may modify and save the contents of the current buffer
2251 without confirmation."
2253 (condition-case data
2254 (unless (fboundp 'brm-rename)
2255 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2256 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2257 (features (cons 'python-mode features))) ; and requires this
2258 (brm-init)) ; second line of normal recipe
2259 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2260 '(lambda () (easy-menu-add brm-menu)))
2262 python-brm-menu python-mode-map
2263 "Bicycle Repair Man"
2264 '("BicycleRepairMan"
2265 :help "Interface to navigation and refactoring tool"
2267 ["Find References" brm-find-references
2268 :help "Find references to name at point in compilation buffer"]
2269 ["Find Definition" brm-find-definition
2270 :help "Find definition of name at point"]
2273 ["Rename" brm-rename
2274 :help "Replace name at point with a new name everywhere"]
2275 ["Extract Method" brm-extract-method
2276 :active (and mark-active (not buffer-read-only))
2277 :help "Replace statements in region with a method"]
2278 ["Extract Local Variable" brm-extract-local-variable
2279 :active (and mark-active (not buffer-read-only))
2280 :help "Replace expression in region with an assignment"]
2281 ["Inline Local Variable" brm-inline-local-variable
2283 "Substitute uses of variable at point with its definition"]
2284 ;; Fixme: Should check for anything to revert.
2285 ["Undo Last Refactoring" brm-undo :help ""])))
2286 (error (error "Bicyclerepairman setup failed: %s" data))))
2290 (defvar outline-heading-end-regexp)
2291 (defvar eldoc-documentation-function)
2292 (defvar python-mode-running) ;Dynamically scoped var.
2295 (define-derived-mode python-mode fundamental-mode "Python"
2296 "Major mode for editing Python files.
2297 Font Lock mode is currently required for correct parsing of the source.
2298 See also `jython-mode', which is actually invoked if the buffer appears to
2299 contain Jython code. See also `run-python' and associated Python mode
2300 commands for running Python under Emacs.
2302 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2303 with nested `def' and `class' blocks. They take the innermost one as
2304 current without distinguishing method and class definitions. Used multiple
2305 times, they move over others at the same indentation level until they reach
2306 the end of definitions at that level, when they move up a level.
2308 Colon is electric: it outdents the line if appropriate, e.g. for
2309 an else statement. \\[python-backspace] at the beginning of an indented statement
2310 deletes a level of indentation to close the current block; otherwise it
2311 deletes a character backward. TAB indents the current line relative to
2312 the preceding code. Successive TABs, with no intervening command, cycle
2313 through the possibilities for indentation on the basis of enclosing blocks.
2315 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2316 effect outside them.
2318 Supports Eldoc mode (only for functions, using a Python process),
2319 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2320 lines count as headers. Symbol completion is available in the
2321 same way as in the Python shell using the `rlcompleter' module
2322 and this is added to the Hippie Expand functions locally if
2323 Hippie Expand mode is turned on. Completion of symbols of the
2324 form x.y only works if the components are literal
2325 module/attribute names, not variables. An abbrev table is set up
2326 with skeleton expansions for compound statement templates.
2328 \\{python-mode-map}"
2330 (set (make-local-variable 'font-lock-defaults)
2331 '(python-font-lock-keywords nil nil nil nil
2332 (font-lock-syntactic-keywords
2333 . python-font-lock-syntactic-keywords)
2334 ;; This probably isn't worth it.
2335 ;; (font-lock-syntactic-face-function
2336 ;; . python-font-lock-syntactic-face-function)
2338 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2339 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2340 (set (make-local-variable 'comment-start) "# ")
2341 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2342 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2343 (set (make-local-variable 'paragraph-start) "\\s-*$")
2344 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2345 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2346 (set (make-local-variable 'add-log-current-defun-function)
2347 #'python-current-defun)
2348 (set (make-local-variable 'outline-regexp)
2349 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2350 "for" "if" "try" "while" "with")
2352 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2353 (set (make-local-variable 'outline-level) #'python-outline-level)
2354 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2355 (make-local-variable 'python-saved-check-command)
2356 (set (make-local-variable 'beginning-of-defun-function)
2357 'python-beginning-of-defun)
2358 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2359 (add-hook 'which-func-functions 'python-which-func nil t)
2360 (setq imenu-create-index-function #'python-imenu-create-index)
2361 (set (make-local-variable 'eldoc-documentation-function)
2362 #'python-eldoc-function)
2363 (add-hook 'eldoc-mode-hook
2364 (lambda () (run-python nil t)) ; need it running
2366 ;; Fixme: should be in hideshow. This seems to be of limited use
2367 ;; since it isn't (can't be) indentation-based. Also hide-level
2368 ;; doesn't seem to work properly.
2369 (add-to-list 'hs-special-modes-alist
2370 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2372 (python-end-of-defun)
2373 (skip-chars-backward " \t\n"))
2375 (set (make-local-variable 'skeleton-further-elements)
2376 '((< '(backward-delete-char-untabify (min python-indent
2378 (^ '(- (1+ (current-indentation))))))
2379 (if (featurep 'hippie-exp)
2380 (set (make-local-variable 'hippie-expand-try-functions-list)
2381 (cons 'python-try-complete hippie-expand-try-functions-list)))
2382 ;; Python defines TABs as being 8-char wide.
2383 (set (make-local-variable 'tab-width) 8)
2384 (when python-guess-indent (python-guess-indent))
2385 ;; Let's make it harder for the user to shoot himself in the foot.
2386 (unless (= tab-width python-indent)
2387 (setq indent-tabs-mode nil))
2388 (set (make-local-variable 'python-command) python-python-command)
2389 (python-find-imports)
2390 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2391 (let ((python-mode-running t))
2392 (python-maybe-jython))))
2394 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2395 (custom-add-option 'python-mode-hook
2397 "Turn off Indent Tabs mode."
2398 (set (make-local-variable 'indent-tabs-mode) nil)))
2399 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2400 (custom-add-option 'python-mode-hook 'abbrev-mode)
2401 (custom-add-option 'python-mode-hook 'python-setup-brm)
2404 (define-derived-mode jython-mode python-mode "Jython"
2405 "Major mode for editing Jython files.
2406 Like `python-mode', but sets up parameters for Jython subprocesses.
2407 Runs `jython-mode-hook' after `python-mode-hook'."
2409 (set (make-local-variable 'python-command) python-jython-command))
2413 ;; pdbtrack features
2415 (defsubst python-point (position)
2416 "Returns the value of point at certain commonly referenced POSITIONs.
2417 POSITION can be one of the following symbols:
2419 bol -- beginning of line
2421 bod -- beginning of def or class
2422 eod -- end of def or class
2423 bob -- beginning of buffer
2424 eob -- end of buffer
2425 boi -- back to indentation
2426 bos -- beginning of statement
2428 This function does not modify point or mark."
2429 (let ((here (point)))
2431 ((eq position 'bol) (beginning-of-line))
2432 ((eq position 'eol) (end-of-line))
2433 ((eq position 'bod) (python-beginning-of-def-or-class))
2434 ((eq position 'eod) (python-end-of-def-or-class))
2435 ;; Kind of funny, I know, but useful for python-up-exception.
2436 ((eq position 'bob) (goto-char (point-min)))
2437 ((eq position 'eob) (goto-char (point-max)))
2438 ((eq position 'boi) (back-to-indentation))
2439 ((eq position 'bos) (python-goto-initial-line))
2440 (t (error "Unknown buffer position requested: %s" position)))
2445 (defun python-end-of-def-or-class (&optional class count)
2446 "Move point beyond end of `def' or `class' body.
2448 By default, looks for an appropriate `def'. If you supply a prefix
2449 arg, looks for a `class' instead. The docs below assume the `def'
2450 case; just substitute `class' for `def' for the other case.
2451 Programmatically, if CLASS is `either', then moves to either `class'
2454 When second optional argument is given programmatically, move to the
2455 COUNTth end of `def'.
2457 If point is in a `def' statement already, this is the `def' we use.
2459 Else, if the `def' found by `\\[python-beginning-of-def-or-class]'
2460 contains the statement you started on, that's the `def' we use.
2462 Otherwise, we search forward for the closest following `def', and use that.
2464 If a `def' can be found by these rules, point is moved to the start of
2465 the line immediately following the `def' block, and the position of the
2466 start of the `def' is returned.
2468 Else point is moved to the end of the buffer, and nil is returned.
2470 Note that doing this command repeatedly will take you closer to the
2471 end of the buffer each time.
2473 To mark the current `def', see `\\[python-mark-def-or-class]'."
2474 (interactive "P") ; raw prefix arg
2475 (if (and count (/= count 1))
2476 (python-beginning-of-def-or-class (- 1 count)))
2477 (let ((start (progn (python-goto-initial-line) (point)))
2478 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2482 ;; move point to start of appropriate def/class
2483 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2484 (setq state 'at-beginning)
2485 ;; else see if python-beginning-of-def-or-class hits container
2486 (if (and (python-beginning-of-def-or-class class)
2487 (progn (python-goto-beyond-block)
2489 (setq state 'at-end)
2490 ;; else search forward
2492 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2493 (progn (setq state 'at-beginning)
2494 (beginning-of-line)))))
2496 ((eq state 'at-beginning) (python-goto-beyond-block) t)
2497 ((eq state 'at-end) t)
2498 ((eq state 'not-found) nil)
2499 (t (error "Internal error in `python-end-of-def-or-class'")))))
2501 (defun python-beginning-of-def-or-class (&optional class count)
2502 "Move point to start of `def' or `class'.
2504 Searches back for the closest preceding `def'. If you supply a prefix
2505 arg, looks for a `class' instead. The docs below assume the `def'
2506 case; just substitute `class' for `def' for the other case.
2507 Programmatically, if CLASS is `either', then moves to either `class'
2510 When second optional argument is given programmatically, move to the
2511 COUNTth start of `def'.
2513 If point is in a `def' statement already, and after the `d', simply
2514 moves point to the start of the statement.
2516 Otherwise (i.e. when point is not in a `def' statement, or at or
2517 before the `d' of a `def' statement), searches for the closest
2518 preceding `def' statement, and leaves point at its start. If no such
2519 statement can be found, leaves point at the start of the buffer.
2521 Returns t iff a `def' statement is found by these rules.
2523 Note that doing this command repeatedly will take you closer to the
2524 start of the buffer each time.
2526 To mark the current `def', see `\\[python-mark-def-or-class]'."
2527 (interactive "P") ; raw prefix arg
2528 (setq count (or count 1))
2529 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2530 (start-of-line (goto-char (python-point 'bol)))
2531 (start-of-stmt (goto-char (python-point 'bos)))
2532 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2533 (class "^[ \t]*class\\>")
2534 (t "^[ \t]*def\\>"))))
2535 ;; searching backward
2536 (if (and (< 0 count)
2537 (or (/= start-of-stmt start-of-line)
2538 (not at-or-before-p)))
2541 (if (and (> 0 count)
2542 (zerop (current-column))
2543 (looking-at start-re))
2545 (if (re-search-backward start-re nil 'move count)
2546 (goto-char (match-beginning 0)))))
2548 (defun python-goto-initial-line ()
2549 "Go to the initial line of the current statement.
2550 Usually this is the line we're on, but if we're on the 2nd or
2551 following lines of a continuation block, we need to go up to the first
2553 ;; Tricky: We want to avoid quadratic-time behavior for long
2554 ;; continued blocks, whether of the backslash or open-bracket
2555 ;; varieties, or a mix of the two. The following manages to do that
2556 ;; in the usual cases.
2558 ;; Also, if we're sitting inside a triple quoted string, this will
2559 ;; drop us at the line that begins the string.
2560 (let (open-bracket-pos)
2561 (while (python-continuation-line-p)
2563 (if (python-backslash-continuation-line-p)
2564 (while (python-backslash-continuation-line-p)
2566 ;; else zip out of nested brackets/braces/parens
2567 (while (setq open-bracket-pos (python-nesting-level))
2568 (goto-char open-bracket-pos)))))
2569 (beginning-of-line))
2571 (defun python-comint-output-filter-function (string)
2572 "Watch output for Python prompt and exec next file waiting in queue.
2573 This function is appropriate for `comint-output-filter-functions'."
2574 ;; TBD: this should probably use split-string
2575 (when (and (or (string-equal string ">>> ")
2576 (and (>= (length string) 5)
2577 (string-equal (substring string -5) "\n>>> ")))
2579 (python-safe (delete-file (car python-file-queue)))
2580 (setq python-file-queue (cdr python-file-queue))
2581 (if python-file-queue
2582 (let ((pyproc (get-buffer-process (current-buffer))))
2583 (python-execute-file pyproc (car python-file-queue))))))
2585 (defun python-pdbtrack-overlay-arrow (activation)
2586 "Activate or de arrow at beginning-of-line in current buffer."
2587 ;; This was derived/simplified from edebug-overlay-arrow
2589 (setq overlay-arrow-position (make-marker))
2590 (setq overlay-arrow-string "=>")
2591 (set-marker overlay-arrow-position
2592 (python-point 'bol) (current-buffer))
2593 (setq python-pdbtrack-is-tracking-p t))
2594 (python-pdbtrack-is-tracking-p
2595 (setq overlay-arrow-position nil)
2596 (setq python-pdbtrack-is-tracking-p nil))))
2598 (defun python-pdbtrack-track-stack-file (text)
2599 "Show the file indicated by the pdb stack entry line, in a separate window.
2601 Activity is disabled if the buffer-local variable
2602 `python-pdbtrack-do-tracking-p' is nil.
2604 We depend on the pdb input prompt matching `python-pdbtrack-input-prompt'
2605 at the beginning of the line."
2606 ;; Instead of trying to piece things together from partial text
2607 ;; (which can be almost useless depending on Emacs version), we
2608 ;; monitor to the point where we have the next pdb prompt, and then
2609 ;; check all text from comint-last-input-end to process-mark.
2611 ;; KLM: It might be nice to provide an optional override, so this
2612 ;; routine could be fed debugger output strings as the text
2613 ;; argument, for deliberate application elsewhere.
2615 ;; KLM: We're very conservative about clearing the overlay arrow, to
2616 ;; minimize residue. This means, for instance, that executing other
2617 ;; pdb commands wipes out the highlight.
2618 (let* ((origbuf (current-buffer))
2619 (currproc (get-buffer-process origbuf)))
2620 (if (not (and currproc python-pdbtrack-do-tracking-p))
2621 (python-pdbtrack-overlay-arrow nil)
2622 (let* (;(origdir default-directory)
2623 (procmark (process-mark currproc))
2624 (block (buffer-substring (max comint-last-input-end
2626 python-pdbtrack-track-range))
2629 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2630 (python-pdbtrack-overlay-arrow nil)
2631 (if (not (string-match
2632 (concat ".*" python-pdbtrack-stack-entry-regexp ".*")
2634 (python-pdbtrack-overlay-arrow nil)
2635 (setq fname (match-string 1 block)
2636 lineno (match-string 2 block))
2637 (if (file-exists-p fname)
2639 (find-file-other-window fname)
2640 (goto-line (string-to-number lineno))
2641 (message "pdbtrack: line %s, file %s" lineno fname)
2642 (python-pdbtrack-overlay-arrow t)
2643 (pop-to-buffer origbuf t) )
2644 (if (= (elt fname 0) ?\<)
2645 (message "pdbtrack: (Non-file source: '%s')" fname)
2646 (message "pdbtrack: File not found: %s" fname)))))))))
2648 (defun python-toggle-shells (arg)
2649 "Toggles between the CPython and JPython shells.
2651 With positive argument ARG (interactively \\[universal-argument]),
2652 uses the CPython shell, with negative ARG uses the JPython shell, and
2653 with a zero argument, toggles the shell.
2655 Programmatically, ARG can also be one of the symbols `cpython' or
2656 `jpython', equivalent to positive arg and negative arg respectively."
2658 ;; default is to toggle
2665 (if (string-equal python-which-bufname "Python")
2668 ((equal arg 'cpython) (setq arg 1))
2669 ((equal arg 'jpython) (setq arg -1)))
2674 (setq python-which-shell python-python-command
2675 python-which-args python-python-command-args
2676 python-which-bufname "Python"
2678 mode-name "Python"))
2680 (setq python-which-shell python-jython-command
2681 python-which-args python-jython-command-args
2682 python-which-bufname "JPython"
2684 mode-name "JPython")))
2685 (message "Using the %s shell" msg)))
2688 (defun python-shell (&optional argprompt)
2689 "Start an interactive Python interpreter in another window.
2690 This is like Shell mode, except that Python is running in the window
2691 instead of a shell. See the `Interactive Shell' and `Shell Mode'
2692 sections of the Emacs manual for details, especially for the key
2693 bindings active in the `*Python*' buffer.
2695 With optional \\[universal-argument], the user is prompted for the
2696 flags to pass to the Python interpreter. This has no effect when this
2697 command is used to switch to an existing process, only when a new
2698 process is started. If you use this, you will probably want to ensure
2699 that the current arguments are retained (they will be included in the
2700 prompt). This argument is ignored when this function is called
2701 programmatically, or when running in Emacs 19.34 or older.
2703 Note: You can toggle between using the CPython interpreter and the
2704 JPython interpreter by hitting \\[python-toggle-shells]. This toggles
2705 buffer local variables which control whether all your subshell
2706 interactions happen to the `*JPython*' or `*Python*' buffers (the
2707 latter is the name used for the CPython buffer).
2709 Warning: Don't use an interactive Python if you change sys.ps1 or
2710 sys.ps2 from their default values, or if you're running code that
2711 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
2712 distinguish your output from Python's output, and assumes that `>>> '
2713 at the start of a line is a prompt from Python. Similarly, the Emacs
2714 Shell mode code assumes that both `>>> ' and `... ' at the start of a
2715 line are Python prompts. Bad things can happen if you fool either
2718 Warning: If you do any editing *in* the process buffer *while* the
2719 buffer is accepting output from Python, do NOT attempt to `undo' the
2720 changes. Some of the output (nowhere near the parts you changed!) may
2721 be lost if you do. This appears to be an Emacs bug, an unfortunate
2722 interaction between undo and process filters; the same problem exists in
2723 non-Python process buffers using the default (Emacs-supplied) process
2726 ;; Set the default shell if not already set
2727 (when (null python-which-shell)
2728 (python-toggle-shells python-default-interpreter))
2729 (let ((args python-which-args))
2730 (when (and argprompt
2732 (fboundp 'split-string))
2733 ;; TBD: Perhaps force "-i" in the final list?
2734 (setq args (split-string
2735 (read-string (concat python-which-bufname
2738 (mapconcat 'identity python-which-args " ") " ")
2740 (switch-to-buffer-other-window
2741 (apply 'make-comint python-which-bufname python-which-shell nil args))
2742 (make-local-variable 'comint-prompt-regexp)
2743 (set-process-sentinel (get-buffer-process (current-buffer)) 'python-sentinel)
2744 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
2745 (add-hook 'comint-output-filter-functions
2746 'python-comint-output-filter-function nil t)
2748 (add-hook 'comint-output-filter-functions
2749 'python-pdbtrack-track-stack-file nil t)
2750 (setq python-pdbtrack-do-tracking-p t)
2751 (set-syntax-table python-mode-syntax-table)
2752 (use-local-map python-shell-map)))
2754 (defun python-pdbtrack-toggle-stack-tracking (arg)
2756 (if (not (get-buffer-process (current-buffer)))
2757 (error "No process associated with buffer '%s'" (current-buffer)))
2758 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2760 (zerop (setq arg (prefix-numeric-value arg))))
2761 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2762 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2763 (message "%sabled Python's pdbtrack"
2764 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2766 (defun turn-on-pdbtrack ()
2768 (python-pdbtrack-toggle-stack-tracking 1))
2770 (defun turn-off-pdbtrack ()
2772 (python-pdbtrack-toggle-stack-tracking 0))
2774 (defun python-sentinel (proc msg)
2775 (setq overlay-arrow-position nil))
2778 (provide 'python-21)
2779 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2780 ;;; python.el ends here