(python-eldoc-function): Re-enable quit while waiting for process.
[emacs.git] / lisp / progmodes / python.el
blob66d8cd4714f9f9425df57944569761f37fb19a84
1 ;;; python.el --- silly walks for Python
3 ;; Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5 ;; Author: Dave Love <fx@gnu.org>
6 ;; Maintainer: FSF
7 ;; Created: Nov 2003
8 ;; Keywords: languages
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 2, or (at your option)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; 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.
27 ;;; Commentary:
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.
65 ;;; Code:
67 (eval-when-compile
68 (require 'cl)
69 (require 'compile)
70 (require 'comint))
72 (autoload 'comint-mode "comint")
74 (defgroup python nil
75 "Silly walks in the Python language."
76 :group 'languages
77 :version "22.1"
78 :link '(emacs-commentary-link "python"))
80 ;;;###autoload
81 (add-to-list 'interpreter-mode-alist '("jython" . jython-mode))
82 ;;;###autoload
83 (add-to-list 'interpreter-mode-alist '("python" . python-mode))
84 ;;;###autoload
85 (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
87 ;;;; Font lock
89 (defvar python-font-lock-keywords
90 `(,(rx symbol-start
91 ;; From v 2.4 reference.
92 ;; def and class dealt with separately below
93 (or "and" "assert" "break" "continue" "del" "elif" "else"
94 "except" "exec" "finally" "for" "from" "global" "if"
95 "import" "in" "is" "lambda" "not" "or" "pass" "print"
96 "raise" "return" "try" "while" "yield"
97 ;; Future keywords
98 "as" "None")
99 symbol-end)
100 ;; Definitions
101 (,(rx symbol-start (group "class") (1+ space) (group (1+ (or word ?_))))
102 (1 font-lock-keyword-face) (2 font-lock-type-face))
103 (,(rx symbol-start (group "def") (1+ space) (group (1+ (or word ?_))))
104 (1 font-lock-keyword-face) (2 font-lock-function-name-face))
105 ;; Top-level assignments are worth highlighting.
106 (,(rx line-start (group (1+ (or word ?_))) (0+ space) "=")
107 (1 font-lock-variable-name-face))
108 (,(rx "@" (1+ (or word ?_))) ; decorators
109 (0 font-lock-preprocessor-face))))
111 (defconst python-font-lock-syntactic-keywords
112 ;; Make outer chars of matching triple-quote sequences into generic
113 ;; string delimiters. Fixme: Is there a better way?
114 `((,(rx (or line-start buffer-start
115 (not (syntax escape))) ; avoid escaped leading quote
116 (group (optional (any "uUrR"))) ; prefix gets syntax property
117 (optional (any "rR")) ; possible second prefix
118 (group (syntax string-quote)) ; maybe gets property
119 (backref 2) ; per first quote
120 (group (backref 2))) ; maybe gets property
121 (1 (python-quote-syntax 1))
122 (2 (python-quote-syntax 2))
123 (3 (python-quote-syntax 3)))
124 ;; This doesn't really help.
125 ;;; (,(rx (and ?\\ (group ?\n))) (1 " "))
128 (defun python-quote-syntax (n)
129 "Put `syntax-table' property correctly on triple quote.
130 Used for syntactic keywords. N is the match number (1, 2 or 3)."
131 ;; Given a triple quote, we have to check the context to know
132 ;; whether this is an opening or closing triple or whether it's
133 ;; quoted anyhow, and should be ignored. (For that we need to do
134 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
135 ;; to use it here despite initial worries.) We also have to sort
136 ;; out a possible prefix -- well, we don't _have_ to, but I think it
137 ;; should be treated as part of the string.
139 ;; Test cases:
140 ;; ur"""ar""" x='"' # """
141 ;; x = ''' """ ' a
142 ;; '''
143 ;; x '"""' x """ \"""" x
144 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
145 ;; fence context).
146 (save-excursion
147 (goto-char (match-beginning 0))
148 (cond
149 ;; Consider property for the last char if in a fenced string.
150 ((= n 3)
151 (let ((syntax (syntax-ppss)))
152 (when (eq t (nth 3 syntax)) ; after unclosed fence
153 (goto-char (nth 8 syntax)) ; fence position
154 (skip-chars-forward "uUrR") ; skip any prefix
155 ;; Is it a matching sequence?
156 (if (eq (char-after) (char-after (match-beginning 2)))
157 (eval-when-compile (string-to-syntax "|"))))))
158 ;; Consider property for initial char, accounting for prefixes.
159 ((or (and (= n 2) ; leading quote (not prefix)
160 (= (match-beginning 1) (match-end 1))) ; prefix is null
161 (and (= n 1) ; prefix
162 (/= (match-beginning 1) (match-end 1)))) ; non-empty
163 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
164 (eval-when-compile (string-to-syntax "|"))))
165 ;; Otherwise (we're in a non-matching string) the property is
166 ;; nil, which is OK.
169 ;; This isn't currently in `font-lock-defaults' as probably not worth
170 ;; it -- we basically only mess with a few normally-symbol characters.
172 ;; (defun python-font-lock-syntactic-face-function (state)
173 ;; "`font-lock-syntactic-face-function' for Python mode.
174 ;; Returns the string or comment face as usual, with side effect of putting
175 ;; a `syntax-table' property on the inside of the string or comment which is
176 ;; the standard syntax table."
177 ;; (if (nth 3 state)
178 ;; (save-excursion
179 ;; (goto-char (nth 8 state))
180 ;; (condition-case nil
181 ;; (forward-sexp)
182 ;; (error nil))
183 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
184 ;; 'syntax-table (standard-syntax-table))
185 ;; 'font-lock-string-face)
186 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
187 ;; 'syntax-table (standard-syntax-table))
188 ;; 'font-lock-comment-face))
190 ;;;; Keymap and syntax
192 (defvar python-mode-map
193 (let ((map (make-sparse-keymap)))
194 ;; Mostly taken from python-mode.el.
195 (define-key map ":" 'python-electric-colon)
196 (define-key map "\177" 'python-backspace)
197 (define-key map "\C-c<" 'python-shift-left)
198 (define-key map "\C-c>" 'python-shift-right)
199 (define-key map "\C-c\C-k" 'python-mark-block)
200 (define-key map "\C-c\C-n" 'python-next-statement)
201 (define-key map "\C-c\C-p" 'python-previous-statement)
202 (define-key map "\C-c\C-u" 'python-beginning-of-block)
203 (define-key map "\C-c\C-f" 'python-describe-symbol)
204 (define-key map "\C-c\C-w" 'python-check)
205 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
206 (define-key map "\C-c\C-s" 'python-send-string)
207 (define-key map [?\C-\M-x] 'python-send-defun)
208 (define-key map "\C-c\C-r" 'python-send-region)
209 (define-key map "\C-c\M-r" 'python-send-region-and-go)
210 (define-key map "\C-c\C-c" 'python-send-buffer)
211 (define-key map "\C-c\C-z" 'python-switch-to-python)
212 (define-key map "\C-c\C-m" 'python-load-file)
213 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
214 (substitute-key-definition 'complete-symbol 'python-complete-symbol
215 map global-map)
216 (define-key map "\C-c\C-i" 'python-find-imports)
217 (define-key map "\C-c\C-t" 'python-expand-template)
218 (easy-menu-define python-menu map "Python Mode menu"
219 `("Python"
220 :help "Python-specific Features"
221 ["Shift region left" python-shift-left :active mark-active
222 :help "Shift by a single indentation step"]
223 ["Shift region right" python-shift-right :active mark-active
224 :help "Shift by a single indentation step"]
226 ["Mark block" python-mark-block
227 :help "Mark innermost block around point"]
228 ["Mark def/class" mark-defun
229 :help "Mark innermost definition around point"]
231 ["Start of block" python-beginning-of-block
232 :help "Go to start of innermost definition around point"]
233 ["End of block" python-end-of-block
234 :help "Go to end of innermost definition around point"]
235 ["Start of def/class" beginning-of-defun
236 :help "Go to start of innermost definition around point"]
237 ["End of def/class" end-of-defun
238 :help "Go to end of innermost definition around point"]
240 ("Templates..."
241 :help "Expand templates for compound statements"
242 :filter (lambda (&rest junk)
243 (mapcar (lambda (elt)
244 (vector (car elt) (cdr elt) t))
245 python-skeletons))) ; defined later
247 ["Start interpreter" run-python
248 :help "Run `inferior' Python in separate buffer"]
249 ["Import/reload file" python-load-file
250 :help "Load into inferior Python session"]
251 ["Eval buffer" python-send-buffer
252 :help "Evaluate buffer en bloc in inferior Python session"]
253 ["Eval region" python-send-region :active mark-active
254 :help "Evaluate region en bloc in inferior Python session"]
255 ["Eval def/class" python-send-defun
256 :help "Evaluate current definition in inferior Python session"]
257 ["Switch to interpreter" python-switch-to-python
258 :help "Switch to inferior Python buffer"]
259 ["Set default process" python-set-proc
260 :help "Make buffer's inferior process the default"
261 :active (buffer-live-p python-buffer)]
262 ["Check file" python-check :help "Run pychecker"]
263 ["Debugger" pdb :help "Run pdb under GUD"]
265 ["Help on symbol" python-describe-symbol
266 :help "Use pydoc on symbol at point"]
267 ["Complete symbol" python-complete-symbol
268 :help "Complete (qualified) symbol before point"]
269 ["Update imports" python-find-imports
270 :help "Update list of top-level imports for completion"]))
271 map))
272 ;; Fixme: add toolbar stuff for useful things like symbol help, send
273 ;; region, at least. (Shouldn't be specific to Python, obviously.)
274 ;; eric has items including: (un)indent, (un)comment, restart script,
275 ;; run script, debug script; also things for profiling, unit testing.
277 (defvar python-mode-syntax-table
278 (let ((table (make-syntax-table)))
279 ;; Give punctuation syntax to ASCII that normally has symbol
280 ;; syntax or has word syntax and isn't a letter.
281 (let ((symbol (string-to-syntax "_"))
282 (sst (standard-syntax-table)))
283 (dotimes (i 128)
284 (unless (= i ?_)
285 (if (equal symbol (aref sst i))
286 (modify-syntax-entry i "." table)))))
287 (modify-syntax-entry ?$ "." table)
288 (modify-syntax-entry ?% "." table)
289 ;; exceptions
290 (modify-syntax-entry ?# "<" table)
291 (modify-syntax-entry ?\n ">" table)
292 (modify-syntax-entry ?' "\"" table)
293 (modify-syntax-entry ?` "$" table)
294 table))
296 ;;;; Utility stuff
298 (defsubst python-in-string/comment ()
299 "Return non-nil if point is in a Python literal (a comment or string)."
300 ;; We don't need to save the match data.
301 (nth 8 (syntax-ppss)))
303 (defconst python-space-backslash-table
304 (let ((table (copy-syntax-table python-mode-syntax-table)))
305 (modify-syntax-entry ?\\ " " table)
306 table)
307 "`python-mode-syntax-table' with backslash given whitespace syntax.")
309 (defun python-skip-comments/blanks (&optional backward)
310 "Skip comments and blank lines.
311 BACKWARD non-nil means go backwards, otherwise go forwards.
312 Backslash is treated as whitespace so that continued blank lines
313 are skipped. Doesn't move out of comments -- should be outside
314 or at end of line."
315 (let ((arg (if backward
316 ;; If we're in a comment (including on the trailing
317 ;; newline), forward-comment doesn't move backwards out
318 ;; of it. Don't set the syntax table round this bit!
319 (let ((syntax (syntax-ppss)))
320 (if (nth 4 syntax)
321 (goto-char (nth 8 syntax)))
322 (- (point-max)))
323 (point-max))))
324 (with-syntax-table python-space-backslash-table
325 (forward-comment arg))))
327 (defun python-backslash-continuation-line-p ()
328 "Non-nil if preceding line ends with backslash that is not in a comment."
329 (and (eq ?\\ (char-before (line-end-position 0)))
330 (not (syntax-ppss-context (syntax-ppss)))))
332 (defun python-continuation-line-p ()
333 "Return non-nil if current line continues a previous one.
334 The criteria are that the previous line ends in a backslash outside
335 comments and strings, or that point is within brackets/parens."
336 (or (python-backslash-continuation-line-p)
337 (let ((depth (syntax-ppss-depth
338 (save-excursion ; syntax-ppss with arg changes point
339 (syntax-ppss (line-beginning-position))))))
340 (or (> depth 0)
341 (if (< depth 0) ; Unbalanced brackets -- act locally
342 (save-excursion
343 (condition-case ()
344 (progn (backward-up-list) t) ; actually within brackets
345 (error nil))))))))
347 (defun python-comment-line-p ()
348 "Return non-nil iff current line has only a comment."
349 (save-excursion
350 (end-of-line)
351 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
352 (back-to-indentation)
353 (looking-at (rx (or (syntax comment-start) line-end))))))
355 (defun python-blank-line-p ()
356 "Return non-nil iff current line is blank."
357 (save-excursion
358 (beginning-of-line)
359 (looking-at "\\s-*$")))
361 (defun python-beginning-of-string ()
362 "Go to beginning of string around point.
363 Do nothing if not in string."
364 (let ((state (syntax-ppss)))
365 (when (eq 'string (syntax-ppss-context state))
366 (goto-char (nth 8 state)))))
368 (defun python-open-block-statement-p (&optional bos)
369 "Return non-nil if statement at point opens a block.
370 BOS non-nil means point is known to be at beginning of statement."
371 (save-excursion
372 (unless bos (python-beginning-of-statement))
373 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
374 "class" "try" "except" "finally")
375 symbol-end)))))
377 (defun python-close-block-statement-p (&optional bos)
378 "Return non-nil if current line is a statement closing a block.
379 BOS non-nil means point is at beginning of statement.
380 The criteria are that the line isn't a comment or in string and
381 starts with keyword `raise', `break', `continue' or `pass'."
382 (save-excursion
383 (unless bos (python-beginning-of-statement))
384 (back-to-indentation)
385 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
386 symbol-end))))
388 (defun python-outdent-p ()
389 "Return non-nil if current line should outdent a level."
390 (save-excursion
391 (back-to-indentation)
392 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
393 symbol-end)))
394 (not (python-in-string/comment))
395 ;; Ensure there's a previous statement and move to it.
396 (zerop (python-previous-statement))
397 (not (python-close-block-statement-p t))
398 ;; Fixme: check this
399 (not (python-open-block-statement-p)))))
401 ;;;; Indentation.
403 (defcustom python-indent 4
404 "Number of columns for a unit of indentation in Python mode.
405 See also `\\[python-guess-indent]'"
406 :group 'python
407 :type 'integer)
409 (defcustom python-guess-indent t
410 "Non-nil means Python mode guesses `python-indent' for the buffer."
411 :type 'boolean
412 :group 'python)
414 (defcustom python-indent-string-contents t
415 "Non-nil means indent contents of multi-line strings together.
416 This means indent them the same as the preceding non-blank line.
417 Otherwise preserve their indentation.
419 This only applies to `doc' strings, i.e. those that form statements;
420 the indentation is preserved in others."
421 :type '(choice (const :tag "Align with preceding" t)
422 (const :tag "Preserve indentation" nil))
423 :group 'python)
425 (defcustom python-honour-comment-indentation nil
426 "Non-nil means indent relative to preceding comment line.
427 Only do this for comments where the leading comment character is
428 followed by space. This doesn't apply to comment lines, which
429 are always indented in lines with preceding comments."
430 :type 'boolean
431 :group 'python)
433 (defcustom python-continuation-offset 4
434 "Number of columns of additional indentation for continuation lines.
435 Continuation lines follow a backslash-terminated line starting a
436 statement."
437 :group 'python
438 :type 'integer)
440 (defun python-guess-indent ()
441 "Guess step for indentation of current buffer.
442 Set `python-indent' locally to the value guessed."
443 (interactive)
444 (save-excursion
445 (save-restriction
446 (widen)
447 (goto-char (point-min))
448 (let (done indent)
449 (while (and (not done) (not (eobp)))
450 (when (and (re-search-forward (rx ?: (0+ space)
451 (or (syntax comment-start)
452 line-end))
453 nil 'move)
454 (python-open-block-statement-p))
455 (save-excursion
456 (python-beginning-of-statement)
457 (let ((initial (current-indentation)))
458 (if (zerop (python-next-statement))
459 (setq indent (- (current-indentation) initial)))
460 (if (and (>= indent 2) (<= indent 8)) ; sanity check
461 (setq done t))))))
462 (when done
463 (when (/= indent (default-value 'python-indent))
464 (set (make-local-variable 'python-indent) indent)
465 (unless (= tab-width python-indent)
466 (setq indent-tabs-mode nil)))
467 indent)))))
469 ;; Alist of possible indentations and start of statement they would
470 ;; close. Used in indentation cycling (below).
471 (defvar python-indent-list nil
472 "Internal use.")
473 ;; Length of the above
474 (defvar python-indent-list-length nil
475 "Internal use.")
476 ;; Current index into the alist.
477 (defvar python-indent-index nil
478 "Internal use.")
480 (defun python-calculate-indentation ()
481 "Calculate Python indentation for line at point."
482 (setq python-indent-list nil
483 python-indent-list-length 1)
484 (save-excursion
485 (beginning-of-line)
486 (let ((syntax (syntax-ppss))
487 start)
488 (cond
489 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
490 (if (not python-indent-string-contents)
491 (current-indentation)
492 ;; Only respect `python-indent-string-contents' in doc
493 ;; strings (defined as those which form statements).
494 (if (not (save-excursion
495 (python-beginning-of-statement)
496 (looking-at (rx (or (syntax string-delimiter)
497 (syntax string-quote))))))
498 (current-indentation)
499 ;; Find indentation of preceding non-blank line within string.
500 (setq start (nth 8 syntax))
501 (forward-line -1)
502 (while (and (< start (point)) (looking-at "\\s-*$"))
503 (forward-line -1))
504 (current-indentation))))
505 ((python-continuation-line-p) ; after backslash, or bracketed
506 (let ((point (point))
507 (open-start (cadr syntax))
508 (backslash (python-backslash-continuation-line-p))
509 (colon (eq ?: (char-before (1- (line-beginning-position))))))
510 (if open-start
511 ;; Inside bracketed expression.
512 (progn
513 (goto-char (1+ open-start))
514 ;; Look for first item in list (preceding point) and
515 ;; align with it, if found.
516 (if (with-syntax-table python-space-backslash-table
517 (let ((parse-sexp-ignore-comments t))
518 (condition-case ()
519 (progn (forward-sexp)
520 (backward-sexp)
521 (< (point) point))
522 (error nil))))
523 ;; Extra level if we're backslash-continued or
524 ;; following a key.
525 (if (or backslash colon)
526 (+ python-indent (current-column))
527 (current-column))
528 ;; Otherwise indent relative to statement start, one
529 ;; level per bracketing level.
530 (goto-char (1+ open-start))
531 (python-beginning-of-statement)
532 (+ (current-indentation) (* (car syntax) python-indent))))
533 ;; Otherwise backslash-continued.
534 (forward-line -1)
535 (if (python-continuation-line-p)
536 ;; We're past first continuation line. Align with
537 ;; previous line.
538 (current-indentation)
539 ;; First continuation line. Indent one step, with an
540 ;; extra one if statement opens a block.
541 (python-beginning-of-statement)
542 (+ (current-indentation) python-continuation-offset
543 (if (python-open-block-statement-p t)
544 python-indent
545 0))))))
546 ((bobp) 0)
547 ;; Fixme: Like python-mode.el; not convinced by this.
548 ((looking-at (rx (0+ space) (syntax comment-start)
549 (not (any " \t\n")))) ; non-indentable comment
550 (current-indentation))
551 (t (if python-honour-comment-indentation
552 ;; Back over whitespace, newlines, non-indentable comments.
553 (catch 'done
554 (while t
555 (if (cond ((bobp))
556 ;; not at comment start
557 ((not (forward-comment -1))
558 (python-beginning-of-statement)
560 ;; trailing comment
561 ((/= (current-column) (current-indentation))
562 (python-beginning-of-statement)
564 ;; indentable comment like python-mode.el
565 ((and (looking-at (rx (syntax comment-start)
566 (or space line-end)))
567 (/= 0 (current-column)))))
568 (throw 'done t)))))
569 (python-indentation-levels)
570 ;; Prefer to indent comments with an immediately-following
571 ;; statement, e.g.
572 ;; ...
573 ;; # ...
574 ;; def ...
575 (when (and (> python-indent-list-length 1)
576 (python-comment-line-p))
577 (forward-line)
578 (unless (python-comment-line-p)
579 (let ((elt (assq (current-indentation) python-indent-list)))
580 (setq python-indent-list
581 (nconc (delete elt python-indent-list)
582 (list elt))))))
583 (caar (last python-indent-list)))))))
585 ;;;; Cycling through the possible indentations with successive TABs.
587 ;; These don't need to be buffer-local since they're only relevant
588 ;; during a cycle.
590 (defun python-initial-text ()
591 "Text of line following indentation and ignoring any trailing comment."
592 (save-excursion
593 (buffer-substring (progn
594 (back-to-indentation)
595 (point))
596 (progn
597 (end-of-line)
598 (forward-comment -1)
599 (point)))))
601 (defconst python-block-pairs
602 '(("else" "if" "elif" "while" "for" "try" "except")
603 ("elif" "if" "elif")
604 ("except" "try" "except")
605 ("finally" "try"))
606 "Alist of keyword matches.
607 The car of an element is a keyword introducing a statement which
608 can close a block opened by a keyword in the cdr.")
610 (defun python-first-word ()
611 "Return first word (actually symbol) on the line."
612 (save-excursion
613 (back-to-indentation)
614 (current-word t)))
616 (defun python-indentation-levels ()
617 "Return a list of possible indentations for this line.
618 It is assumed not to be a continuation line or in a multi-line string.
619 Includes the default indentation and those which would close all
620 enclosing blocks. Elements of the list are actually pairs:
621 \(INDENTATION . TEXT), where TEXT is the initial text of the
622 corresponding block opening (or nil)."
623 (save-excursion
624 (let ((initial "")
625 levels indent)
626 ;; Only one possibility immediately following a block open
627 ;; statement, assuming it doesn't have a `suite' on the same line.
628 (cond
629 ((save-excursion (and (python-previous-statement)
630 (python-open-block-statement-p t)
631 (setq indent (current-indentation))
632 ;; Check we don't have something like:
633 ;; if ...: ...
634 (if (progn (python-end-of-statement)
635 (python-skip-comments/blanks t)
636 (eq ?: (char-before)))
637 (setq indent (+ python-indent indent)))))
638 (push (cons indent initial) levels))
639 ;; Only one possibility for comment line immediately following
640 ;; another.
641 ((save-excursion
642 (when (python-comment-line-p)
643 (forward-line -1)
644 (if (python-comment-line-p)
645 (push (cons (current-indentation) initial) levels)))))
646 ;; Fixme: Maybe have a case here which indents (only) first
647 ;; line after a lambda.
649 (let ((start (car (assoc (python-first-word) python-block-pairs))))
650 (python-previous-statement)
651 ;; Is this a valid indentation for the line of interest?
652 (unless (or (if start ; potentially only outdentable
653 ;; Check for things like:
654 ;; if ...: ...
655 ;; else ...:
656 ;; where the second line need not be outdented.
657 (not (member (python-first-word)
658 (cdr (assoc start
659 python-block-pairs)))))
660 ;; Not sensible to indent to the same level as
661 ;; previous `return' &c.
662 (python-close-block-statement-p))
663 (push (cons (current-indentation) (python-initial-text))
664 levels))
665 (while (python-beginning-of-block)
666 (when (or (not start)
667 (member (python-first-word)
668 (cdr (assoc start python-block-pairs))))
669 (push (cons (current-indentation) (python-initial-text))
670 levels))))))
671 (prog1 (or levels (setq levels '((0 . ""))))
672 (setq python-indent-list levels
673 python-indent-list-length (length python-indent-list))))))
675 ;; This is basically what `python-indent-line' would be if we didn't
676 ;; do the cycling.
677 (defun python-indent-line-1 (&optional leave)
678 "Subroutine of `python-indent-line'.
679 Does non-repeated indentation. LEAVE non-nil means leave
680 indentation if it is valid, i.e. one of the positions returned by
681 `python-calculate-indentation'."
682 (let ((target (python-calculate-indentation))
683 (pos (- (point-max) (point))))
684 (if (or (= target (current-indentation))
685 ;; Maybe keep a valid indentation.
686 (and leave python-indent-list
687 (assq (current-indentation) python-indent-list)))
688 (if (< (current-column) (current-indentation))
689 (back-to-indentation))
690 (beginning-of-line)
691 (delete-horizontal-space)
692 (indent-to target)
693 (if (> (- (point-max) pos) (point))
694 (goto-char (- (point-max) pos))))))
696 (defun python-indent-line ()
697 "Indent current line as Python code.
698 When invoked via `indent-for-tab-command', cycle through possible
699 indentations for current line. The cycle is broken by a command
700 different from `indent-for-tab-command', i.e. successive TABs do
701 the cycling."
702 (interactive)
703 (if (and (eq this-command 'indent-for-tab-command)
704 (eq last-command this-command))
705 (if (= 1 python-indent-list-length)
706 (message "Sole indentation")
707 (progn (setq python-indent-index
708 (% (1+ python-indent-index) python-indent-list-length))
709 (beginning-of-line)
710 (delete-horizontal-space)
711 (indent-to (car (nth python-indent-index python-indent-list)))
712 (if (python-block-end-p)
713 (let ((text (cdr (nth python-indent-index
714 python-indent-list))))
715 (if text
716 (message "Closes: %s" text))))))
717 (python-indent-line-1)
718 (setq python-indent-index (1- python-indent-list-length))))
720 (defun python-indent-region (start end)
721 "`indent-region-function' for Python.
722 Leaves validly-indented lines alone, i.e. doesn't indent to
723 another valid position."
724 (save-excursion
725 (goto-char end)
726 (setq end (point-marker))
727 (goto-char start)
728 (or (bolp) (forward-line 1))
729 (while (< (point) end)
730 (or (and (bolp) (eolp))
731 (python-indent-line-1 t))
732 (forward-line 1))
733 (move-marker end nil)))
735 (defun python-block-end-p ()
736 "Non-nil if this is a line in a statement closing a block,
737 or a blank line indented to where it would close a block."
738 (and (not (python-comment-line-p))
739 (or (python-close-block-statement-p t)
740 (< (current-indentation)
741 (save-excursion
742 (python-previous-statement)
743 (current-indentation))))))
745 ;;;; Movement.
747 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
748 ;; block, statement, depending on context.
750 (defun python-beginning-of-defun ()
751 "`beginning-of-defun-function' for Python.
752 Finds beginning of innermost nested class or method definition.
753 Returns the name of the definition found at the end, or nil if
754 reached start of buffer."
755 (let ((ci (current-indentation))
756 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
757 (group (1+ (or word (syntax symbol))))))
758 found lep) ;; def-line
759 (if (python-comment-line-p)
760 (setq ci most-positive-fixnum))
761 (while (and (not (bobp)) (not found))
762 ;; Treat bol at beginning of function as outside function so
763 ;; that successive C-M-a makes progress backwards.
764 ;;(setq def-line (looking-at def-re))
765 (unless (bolp) (end-of-line))
766 (setq lep (line-end-position))
767 (if (and (re-search-backward def-re nil 'move)
768 ;; Must be less indented or matching top level, or
769 ;; equally indented if we started on a definition line.
770 (let ((in (current-indentation)))
771 (or (and (zerop ci) (zerop in))
772 (= lep (line-end-position)) ; on initial line
773 ;; Not sure why it was like this -- fails in case of
774 ;; last internal function followed by first
775 ;; non-def statement of the main body.
776 ;;(and def-line (= in ci))
777 (= in ci)
778 (< in ci)))
779 (not (python-in-string/comment)))
780 (setq found t)))))
782 (defun python-end-of-defun ()
783 "`end-of-defun-function' for Python.
784 Finds end of innermost nested class or method definition."
785 (let ((orig (point))
786 (pattern (rx line-start (0+ space) (or "def" "class") space)))
787 ;; Go to start of current block and check whether it's at top
788 ;; level. If it is, and not a block start, look forward for
789 ;; definition statement.
790 (when (python-comment-line-p)
791 (end-of-line)
792 (forward-comment most-positive-fixnum))
793 (if (not (python-open-block-statement-p))
794 (python-beginning-of-block))
795 (if (zerop (current-indentation))
796 (unless (python-open-block-statement-p)
797 (while (and (re-search-forward pattern nil 'move)
798 (python-in-string/comment))) ; just loop
799 (unless (eobp)
800 (beginning-of-line)))
801 ;; Don't move before top-level statement that would end defun.
802 (end-of-line)
803 (python-beginning-of-defun))
804 ;; If we got to the start of buffer, look forward for
805 ;; definition statement.
806 (if (and (bobp) (not (looking-at "def\\|class")))
807 (while (and (not (eobp))
808 (re-search-forward pattern nil 'move)
809 (python-in-string/comment)))) ; just loop
810 ;; We're at a definition statement (or end-of-buffer).
811 (unless (eobp)
812 (python-end-of-block)
813 ;; Count trailing space in defun (but not trailing comments).
814 (skip-syntax-forward " >")
815 (unless (eobp) ; e.g. missing final newline
816 (beginning-of-line)))
817 ;; Catch pathological cases like this, where the beginning-of-defun
818 ;; skips to a definition we're not in:
819 ;; if ...:
820 ;; ...
821 ;; else:
822 ;; ... # point here
823 ;; ...
824 ;; def ...
825 (if (< (point) orig)
826 (goto-char (point-max)))))
828 (defun python-beginning-of-statement ()
829 "Go to start of current statement.
830 Accounts for continuation lines, multi-line strings, and
831 multi-line bracketed expressions."
832 (beginning-of-line)
833 (python-beginning-of-string)
834 (while (python-continuation-line-p)
835 (beginning-of-line)
836 (if (python-backslash-continuation-line-p)
837 (progn
838 (forward-line -1)
839 (while (python-backslash-continuation-line-p)
840 (forward-line -1)))
841 (python-beginning-of-string)
842 (python-skip-out)))
843 (back-to-indentation))
845 (defun python-skip-out (&optional forward syntax)
846 "Skip out of any nested brackets.
847 Skip forward if FORWARD is non-nil, else backward.
848 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
849 Return non-nil iff skipping was done."
850 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
851 (forward (if forward -1 1)))
852 (unless (zerop depth)
853 (if (> depth 0)
854 ;; Skip forward out of nested brackets.
855 (condition-case () ; beware invalid syntax
856 (progn (backward-up-list (* forward depth)) t)
857 (error nil))
858 ;; Invalid syntax (too many closed brackets).
859 ;; Skip out of as many as possible.
860 (let (done)
861 (while (condition-case ()
862 (progn (backward-up-list forward)
863 (setq done t))
864 (error nil)))
865 done)))))
867 (defun python-end-of-statement ()
868 "Go to the end of the current statement and return point.
869 Usually this is the start of the next line, but if this is a
870 multi-line statement we need to skip over the continuation lines.
871 On a comment line, go to end of line."
872 (end-of-line)
873 (while (let (comment)
874 ;; Move past any enclosing strings and sexps, or stop if
875 ;; we're in a comment.
876 (while (let ((s (syntax-ppss)))
877 (cond ((eq 'comment (syntax-ppss-context s))
878 (setq comment t)
879 nil)
880 ((eq 'string (syntax-ppss-context s))
881 ;; Go to start of string and skip it.
882 (goto-char (nth 8 s))
883 (condition-case () ; beware invalid syntax
884 (progn (forward-sexp) t)
885 (error (end-of-line))))
886 ((python-skip-out t s))))
887 (end-of-line))
888 (unless comment
889 (eq ?\\ (char-before)))) ; Line continued?
890 (end-of-line 2)) ; Try next line.
891 (point))
893 (defun python-previous-statement (&optional count)
894 "Go to start of previous statement.
895 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
896 Return count of statements left to move."
897 (interactive "p")
898 (unless count (setq count 1))
899 (if (< count 0)
900 (python-next-statement (- count))
901 (python-beginning-of-statement)
902 (while (and (> count 0) (not (bobp)))
903 (python-skip-comments/blanks t)
904 (python-beginning-of-statement)
905 (unless (bobp) (setq count (1- count))))
906 count))
908 (defun python-next-statement (&optional count)
909 "Go to start of next statement.
910 With argument COUNT, do it COUNT times. Stop at end of buffer.
911 Return count of statements left to move."
912 (interactive "p")
913 (unless count (setq count 1))
914 (if (< count 0)
915 (python-previous-statement (- count))
916 (beginning-of-line)
917 (while (and (> count 0) (not (eobp)))
918 (python-end-of-statement)
919 (python-skip-comments/blanks)
920 (unless (eobp)
921 (setq count (1- count))))
922 count))
924 (defun python-beginning-of-block (&optional arg)
925 "Go to start of current block.
926 With numeric arg, do it that many times. If ARG is negative, call
927 `python-end-of-block' instead.
928 If point is on the first line of a block, use its outer block.
929 If current statement is in column zero, don't move and return nil.
930 Otherwise return non-nil."
931 (interactive "p")
932 (unless arg (setq arg 1))
933 (cond
934 ((zerop arg))
935 ((< arg 0) (python-end-of-block (- arg)))
937 (let ((point (point)))
938 (if (or (python-comment-line-p)
939 (python-blank-line-p))
940 (python-skip-comments/blanks t))
941 (python-beginning-of-statement)
942 (let ((ci (current-indentation)))
943 (if (zerop ci)
944 (not (goto-char point)) ; return nil
945 ;; Look upwards for less indented statement.
946 (if (catch 'done
947 ;;; This is slower than the below.
948 ;;; (while (zerop (python-previous-statement))
949 ;;; (when (and (< (current-indentation) ci)
950 ;;; (python-open-block-statement-p t))
951 ;;; (beginning-of-line)
952 ;;; (throw 'done t)))
953 (while (and (zerop (forward-line -1)))
954 (when (and (< (current-indentation) ci)
955 (not (python-comment-line-p))
956 ;; Move to beginning to save effort in case
957 ;; this is in string.
958 (progn (python-beginning-of-statement) t)
959 (python-open-block-statement-p t))
960 (beginning-of-line)
961 (throw 'done t)))
962 (not (goto-char point))) ; Failed -- return nil
963 (python-beginning-of-block (1- arg)))))))))
965 (defun python-end-of-block (&optional arg)
966 "Go to end of current block.
967 With numeric arg, do it that many times. If ARG is negative,
968 call `python-beginning-of-block' instead.
969 If current statement is in column zero and doesn't open a block,
970 don't move and return nil. Otherwise return t."
971 (interactive "p")
972 (unless arg (setq arg 1))
973 (if (< arg 0)
974 (python-beginning-of-block (- arg))
975 (while (and (> arg 0)
976 (let* ((point (point))
977 (_ (if (python-comment-line-p)
978 (python-skip-comments/blanks t)))
979 (ci (current-indentation))
980 (open (python-open-block-statement-p)))
981 (if (and (zerop ci) (not open))
982 (not (goto-char point))
983 (catch 'done
984 (while (zerop (python-next-statement))
985 (when (or (and open (<= (current-indentation) ci))
986 (< (current-indentation) ci))
987 (python-skip-comments/blanks t)
988 (beginning-of-line 2)
989 (throw 'done t)))))))
990 (setq arg (1- arg)))
991 (zerop arg)))
993 ;;;; Imenu.
995 (defvar python-recursing)
996 (defun python-imenu-create-index ()
997 "`imenu-create-index-function' for Python.
999 Makes nested Imenu menus from nested `class' and `def' statements.
1000 The nested menus are headed by an item referencing the outer
1001 definition; it has a space prepended to the name so that it sorts
1002 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1003 precede it)."
1004 (unless (boundp 'python-recursing) ; dynamically bound below
1005 ;; Normal call from Imenu.
1006 (goto-char (point-min))
1007 ;; Without this, we can get an infloop if the buffer isn't all
1008 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1009 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1010 ;; what's going on, but it must be something to do with timers in
1011 ;; font-lock.
1012 ;; This can't be right, especially not when jit-lock is not used. --Stef
1013 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1014 ;; (font-lock-fontify-region (point-min) (point-max)))
1016 (let (index-alist) ; accumulated value to return
1017 (while (re-search-forward
1018 (rx line-start (0+ space) ; leading space
1019 (or (group "def") (group "class")) ; type
1020 (1+ space) (group (1+ (or word ?_)))) ; name
1021 nil t)
1022 (unless (python-in-string/comment)
1023 (let ((pos (match-beginning 0))
1024 (name (match-string-no-properties 3)))
1025 (if (match-beginning 2) ; def or class?
1026 (setq name (concat "class " name)))
1027 (save-restriction
1028 (narrow-to-defun)
1029 (let* ((python-recursing t)
1030 (sublist (python-imenu-create-index)))
1031 (if sublist
1032 (progn (push (cons (concat " " name) pos) sublist)
1033 (push (cons name sublist) index-alist))
1034 (push (cons name pos) index-alist)))))))
1035 (unless (boundp 'python-recursing)
1036 ;; Look for module variables.
1037 (let (vars)
1038 (goto-char (point-min))
1039 (while (re-search-forward
1040 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1041 nil t)
1042 (unless (python-in-string/comment)
1043 (push (cons (match-string 1) (match-beginning 1))
1044 vars)))
1045 (setq index-alist (nreverse index-alist))
1046 (if vars
1047 (push (cons "Module variables"
1048 (nreverse vars))
1049 index-alist))))
1050 index-alist))
1052 ;;;; `Electric' commands.
1054 (defun python-electric-colon (arg)
1055 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1056 With numeric ARG, just insert that many colons. With \\[universal-argument],
1057 just insert a single colon."
1058 (interactive "*P")
1059 (self-insert-command (if (not (integerp arg)) 1 arg))
1060 (and (not arg)
1061 (eolp)
1062 (python-outdent-p)
1063 (not (python-in-string/comment))
1064 (> (current-indentation) (python-calculate-indentation))
1065 (python-indent-line))) ; OK, do it
1066 (put 'python-electric-colon 'delete-selection t)
1068 (defun python-backspace (arg)
1069 "Maybe delete a level of indentation on the current line.
1070 Do so if point is at the end of the line's indentation.
1071 Otherwise just call `backward-delete-char-untabify'.
1072 Repeat ARG times."
1073 (interactive "*p")
1074 (if (or (/= (current-indentation) (current-column))
1075 (bolp)
1076 (python-continuation-line-p))
1077 (backward-delete-char-untabify arg)
1078 ;; Look for the largest valid indentation which is smaller than
1079 ;; the current indentation.
1080 (let ((indent 0)
1081 (ci (current-indentation))
1082 (indents (python-indentation-levels))
1083 initial)
1084 (dolist (x indents)
1085 (if (< (car x) ci)
1086 (setq indent (max indent (car x)))))
1087 (setq initial (cdr (assq indent indents)))
1088 (if (> (length initial) 0)
1089 (message "Closes %s" initial))
1090 (delete-horizontal-space)
1091 (indent-to indent))))
1092 (put 'python-backspace 'delete-selection 'supersede)
1094 ;;;; pychecker
1096 (defcustom python-check-command "pychecker --stdlib"
1097 "Command used to check a Python file."
1098 :type 'string
1099 :group 'python)
1101 (defvar python-saved-check-command nil
1102 "Internal use.")
1104 ;; After `sgml-validate-command'.
1105 (defun python-check (command)
1106 "Check a Python file (default current buffer's file).
1107 Runs COMMAND, a shell command, as if by `compile'.
1108 See `python-check-command' for the default."
1109 (interactive
1110 (list (read-string "Checker command: "
1111 (or python-saved-check-command
1112 (concat python-check-command " "
1113 (let ((name (buffer-file-name)))
1114 (if name
1115 (file-name-nondirectory name))))))))
1116 (setq python-saved-check-command command)
1117 (require 'compile) ;To define compilation-* variables.
1118 (save-some-buffers (not compilation-ask-about-save) nil)
1119 (let ((compilation-error-regexp-alist
1120 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1121 compilation-error-regexp-alist)))
1122 (compilation-start command)))
1124 ;;;; Inferior mode stuff (following cmuscheme).
1126 ;; Fixme: Make sure we can work with IPython.
1128 (defcustom python-python-command "python"
1129 "Shell command to run Python interpreter.
1130 Any arguments can't contain whitespace.
1131 Note that IPython may not work properly; it must at least be used
1132 with the `-cl' flag, i.e. use `ipython -cl'."
1133 :group 'python
1134 :type 'string)
1136 (defcustom python-jython-command "jython"
1137 "Shell command to run Jython interpreter.
1138 Any arguments can't contain whitespace."
1139 :group 'python
1140 :type 'string)
1142 (defvar python-command python-python-command
1143 "Actual command used to run Python.
1144 May be `python-python-command' or `python-jython-command', possibly
1145 modified by the user. Additional arguments are added when the command
1146 is used by `run-python' et al.")
1148 (defvar python-buffer nil
1149 "*The current python process buffer.
1151 Commands that send text from source buffers to Python processes have
1152 to choose a process to send to. This is determined by buffer-local
1153 value of `python-buffer'. If its value in the current buffer,
1154 i.e. both any local value and the default one, is nil, `run-python'
1155 and commands that send to the Python process will start a new process.
1157 Whenever \\[run-python] starts a new process, it resets the default
1158 value of `python-buffer' to be the new process's buffer and sets the
1159 buffer-local value similarly if the current buffer is in Python mode
1160 or Inferior Python mode, so that source buffer stays associated with a
1161 specific sub-process.
1163 Use \\[python-set-proc] to set the default value from a buffer with a
1164 local value.")
1165 (make-variable-buffer-local 'python-buffer)
1167 (defconst python-compilation-regexp-alist
1168 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1169 ;; The first already is (for CAML), but the second isn't. Anyhow,
1170 ;; these are specific to the inferior buffer. -- fx
1171 `((,(rx line-start (1+ (any " \t")) "File \""
1172 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1173 "\", line " (group (1+ digit)))
1174 1 2)
1175 (,(rx " in file " (group (1+ not-newline)) " on line "
1176 (group (1+ digit)))
1177 1 2))
1178 "`compilation-error-regexp-alist' for inferior Python.")
1180 (defvar inferior-python-mode-map
1181 (let ((map (make-sparse-keymap)))
1182 ;; This will inherit from comint-mode-map.
1183 (define-key map "\C-c\C-l" 'python-load-file)
1184 (define-key map "\C-c\C-v" 'python-check)
1185 ;; Note that we _can_ still use these commands which send to the
1186 ;; Python process even at the prompt iff we have a normal prompt,
1187 ;; i.e. '>>> ' and not '... '. See the comment before
1188 ;; python-send-region. Fixme: uncomment these if we address that.
1190 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1191 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1192 map))
1194 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1195 ;; not sure how much: at least some keybindings, like C-c C-f;
1196 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1197 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1198 "Major mode for interacting with an inferior Python process.
1199 A Python process can be started with \\[run-python].
1201 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1202 that order.
1204 You can send text to the inferior Python process from other buffers
1205 containing Python source.
1206 * \\[python-switch-to-python] switches the current buffer to the Python
1207 process buffer.
1208 * \\[python-send-region] sends the current region to the Python process.
1209 * \\[python-send-region-and-go] switches to the Python process buffer
1210 after sending the text.
1211 For running multiple processes in multiple buffers, see `run-python' and
1212 `python-buffer'.
1214 \\{inferior-python-mode-map}"
1215 :group 'python
1216 (set-syntax-table python-mode-syntax-table)
1217 (setq mode-line-process '(":%s"))
1218 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1219 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1220 nil t)
1221 ;; Still required by `comint-redirect-send-command', for instance
1222 ;; (and we need to match things like `>>> ... >>> '):
1223 (set (make-local-variable 'comint-prompt-regexp)
1224 (rx line-start (1+ (and (repeat 3 (any ">.")) " "))))
1225 (set (make-local-variable 'compilation-error-regexp-alist)
1226 python-compilation-regexp-alist)
1227 (compilation-shell-minor-mode 1))
1229 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1230 "Input matching this regexp is not saved on the history list.
1231 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1232 :type 'regexp
1233 :group 'python)
1235 (defun python-input-filter (str)
1236 "`comint-input-filter' function for inferior Python.
1237 Don't save anything for STR matching `inferior-python-filter-regexp'."
1238 (not (string-match inferior-python-filter-regexp str)))
1240 ;; Fixme: Loses with quoted whitespace.
1241 (defun python-args-to-list (string)
1242 (let ((where (string-match "[ \t]" string)))
1243 (cond ((null where) (list string))
1244 ((not (= where 0))
1245 (cons (substring string 0 where)
1246 (python-args-to-list (substring string (+ 1 where)))))
1247 (t (let ((pos (string-match "[^ \t]" string)))
1248 (if pos (python-args-to-list (substring string pos))))))))
1250 (defvar python-preoutput-result nil
1251 "Data from last `_emacs_out' line seen by the preoutput filter.")
1253 (defvar python-preoutput-leftover nil)
1254 (defvar python-preoutput-skip-next-prompt nil)
1256 ;; Using this stops us getting lines in the buffer like
1257 ;; >>> ... ... >>>
1258 (defun python-preoutput-filter (s)
1259 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1260 (when python-preoutput-leftover
1261 (setq s (concat python-preoutput-leftover s))
1262 (setq python-preoutput-leftover nil))
1263 (let ((start 0)
1264 (res ""))
1265 ;; First process whole lines.
1266 (while (string-match "\n" s start)
1267 (let ((line (substring s start (setq start (match-end 0)))))
1268 ;; Skip prompt if needed.
1269 (when (and python-preoutput-skip-next-prompt
1270 (string-match comint-prompt-regexp line))
1271 (setq python-preoutput-skip-next-prompt nil)
1272 (setq line (substring line (match-end 0))))
1273 ;; Recognize special _emacs_out lines.
1274 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1275 (local-variable-p 'python-preoutput-result))
1276 (progn
1277 (setq python-preoutput-result (match-string 1 line))
1278 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1279 (setq res (concat res line)))))
1280 ;; Then process the remaining partial line.
1281 (unless (zerop start) (setq s (substring s start)))
1282 (cond ((and (string-match comint-prompt-regexp s)
1283 ;; Drop this prompt if it follows an _emacs_out...
1284 (or python-preoutput-skip-next-prompt
1285 ;; ... or if it's not gonna be inserted at BOL.
1286 ;; Maybe we could be more selective here.
1287 (if (zerop (length res))
1288 (not (bolp))
1289 (string-match res ".\\'"))))
1290 ;; The need for this seems to be system-dependent:
1291 ;; What is this all about, exactly? --Stef
1292 ;; (if (and (eq ?. (aref s 0)))
1293 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1294 (setq python-preoutput-skip-next-prompt nil)
1295 res)
1296 ((let ((end (min (length "_emacs_out ") (length s))))
1297 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1298 ;; The leftover string is a prefix of _emacs_out so we don't know
1299 ;; yet whether it's an _emacs_out or something else: wait until we
1300 ;; get more output so we can resolve this ambiguity.
1301 (set (make-local-variable 'python-preoutput-leftover) s)
1302 res)
1303 (t (concat res s)))))
1305 (autoload 'comint-check-proc "comint")
1307 ;;;###autoload
1308 (defun run-python (&optional cmd noshow new)
1309 "Run an inferior Python process, input and output via buffer *Python*.
1310 CMD is the Python command to run. NOSHOW non-nil means don't show the
1311 buffer automatically.
1313 Normally, if there is a process already running in `python-buffer',
1314 switch to that buffer. Interactively, a prefix arg allows you to edit
1315 the initial command line (default is `python-command'); `-i' etc. args
1316 will be added to this as appropriate. A new process is started if:
1317 one isn't running attached to `python-buffer', or interactively the
1318 default `python-command', or argument NEW is non-nil. See also the
1319 documentation for `python-buffer'.
1321 Runs the hook `inferior-python-mode-hook' \(after the
1322 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1323 buffer for a list of commands.)"
1324 (interactive (if current-prefix-arg
1325 (list (read-string "Run Python: " python-command) nil t)
1326 (list python-command)))
1327 (unless cmd (setq cmd python-python-command))
1328 (setq python-command cmd)
1329 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1330 ;; (not a name) in Python buffers from which `run-python' &c is
1331 ;; invoked. Would support multiple processes better.
1332 (when (or new (not (comint-check-proc python-buffer)))
1333 (with-current-buffer
1334 (let* ((cmdlist (append (python-args-to-list cmd) '("-i")))
1335 (path (getenv "PYTHONPATH"))
1336 (process-environment ; to import emacs.py
1337 (cons (concat "PYTHONPATH=" data-directory
1338 (if path (concat ":" path)))
1339 process-environment)))
1340 (apply 'make-comint-in-buffer "Python"
1341 (if new (generate-new-buffer "*Python*") "*Python*")
1342 (car cmdlist) nil (cdr cmdlist)))
1343 (setq-default python-buffer (current-buffer))
1344 (setq python-buffer (current-buffer))
1345 (accept-process-output (get-buffer-process python-buffer) 5)
1346 (inferior-python-mode)
1347 ;; Load function definitions we need.
1348 ;; Before the preoutput function was used, this was done via -c in
1349 ;; cmdlist, but that loses the banner and doesn't run the startup
1350 ;; file. The code might be inline here, but there's enough that it
1351 ;; seems worth putting in a separate file, and it's probably cleaner
1352 ;; to put it in a module.
1353 ;; Ensure we're at a prompt before doing anything else.
1354 (python-send-receive "import emacs; print '_emacs_out ()'")))
1355 (if (derived-mode-p 'python-mode)
1356 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1357 ;; Without this, help output goes into the inferior python buffer if
1358 ;; the process isn't already running.
1359 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1360 (unless noshow (pop-to-buffer python-buffer t)))
1362 ;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1363 ;; e.g. prompt is `help> '. Probably raise an error if the form of
1364 ;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1365 ;; `... ', i.e. we're not inputting a block &c. However, this may not
1366 ;; be the place to check it, e.g. we might actually want to send
1367 ;; commands having set up such a state.
1369 (defun python-send-command (command)
1370 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1371 COMMAND should be a single statement."
1372 ;; (assert (not (string-match "\n" command)))
1373 ;; (let ((end (marker-position (process-mark (python-proc)))))
1374 (with-current-buffer python-buffer (goto-char (point-max)))
1375 (compilation-forget-errors)
1376 (python-send-string command)
1377 (with-current-buffer python-buffer
1378 (setq compilation-last-buffer (current-buffer)))
1379 ;; No idea what this is for but it breaks the call to
1380 ;; compilation-fake-loc in python-send-region. -- Stef
1381 ;; Must wait until this has completed before re-setting variables below.
1382 ;; (python-send-receive "print '_emacs_out ()'")
1383 ;; (with-current-buffer python-buffer
1384 ;; (set-marker compilation-parsing-end end))
1385 ) ;;)
1387 (defun python-send-region (start end)
1388 "Send the region to the inferior Python process."
1389 ;; The region is evaluated from a temporary file. This avoids
1390 ;; problems with blank lines, which have different semantics
1391 ;; interactively and in files. It also saves the inferior process
1392 ;; buffer filling up with interpreter prompts. We need a Python
1393 ;; function to remove the temporary file when it has been evaluated
1394 ;; (though we could probably do it in Lisp with a Comint output
1395 ;; filter). This function also catches exceptions and truncates
1396 ;; tracebacks not to mention the frame of the function itself.
1398 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1399 ;; the reference to the temporary file to the source.
1401 ;; Fixme: Write a `coding' header to the temp file if the region is
1402 ;; non-ASCII.
1403 (interactive "r")
1404 (let* ((f (make-temp-file "py"))
1405 (command (format "emacs.eexecfile(%S)" f))
1406 (orig-start (copy-marker start)))
1407 (when (save-excursion
1408 (goto-char start)
1409 (/= 0 (current-indentation))) ; need dummy block
1410 (save-excursion
1411 (goto-char orig-start)
1412 ;; Wrong if we had indented code at buffer start.
1413 (set-marker orig-start (line-beginning-position 0)))
1414 (write-region "if True:\n" nil f nil 'nomsg))
1415 (write-region start end f t 'nomsg)
1416 (python-send-command command)
1417 (with-current-buffer (process-buffer (python-proc))
1418 ;; Tell compile.el to redirect error locations in file `f' to
1419 ;; positions past marker `orig-start'. It has to be done *after*
1420 ;; `python-send-command''s call to `compilation-forget-errors'.
1421 (compilation-fake-loc orig-start f))))
1423 (defun python-send-string (string)
1424 "Evaluate STRING in inferior Python process."
1425 (interactive "sPython command: ")
1426 (comint-send-string (python-proc) string)
1427 (comint-send-string (python-proc)
1428 ;; If the string is single-line or if it ends with \n,
1429 ;; only add a single \n, otherwise add 2, so as to
1430 ;; make sure we terminate the multiline instruction.
1431 (if (string-match "\n.+\\'" string) "\n\n" "\n")))
1433 (defun python-send-buffer ()
1434 "Send the current buffer to the inferior Python process."
1435 (interactive)
1436 (python-send-region (point-min) (point-max)))
1438 ;; Fixme: Try to define the function or class within the relevant
1439 ;; module, not just at top level.
1440 (defun python-send-defun ()
1441 "Send the current defun (class or method) to the inferior Python process."
1442 (interactive)
1443 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1444 (progn (end-of-defun) (point)))))
1446 (defun python-switch-to-python (eob-p)
1447 "Switch to the Python process buffer, maybe starting new process.
1448 With prefix arg, position cursor at end of buffer."
1449 (interactive "P")
1450 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1451 (when eob-p
1452 (push-mark)
1453 (goto-char (point-max))))
1455 (defun python-send-region-and-go (start end)
1456 "Send the region to the inferior Python process.
1457 Then switch to the process buffer."
1458 (interactive "r")
1459 (python-send-region start end)
1460 (python-switch-to-python t))
1462 (defcustom python-source-modes '(python-mode jython-mode)
1463 "Used to determine if a buffer contains Python source code.
1464 If a file is loaded into a buffer that is in one of these major modes,
1465 it is considered Python source by `python-load-file', which uses the
1466 value to determine defaults."
1467 :type '(repeat function)
1468 :group 'python)
1470 (defvar python-prev-dir/file nil
1471 "Caches (directory . file) pair used in the last `python-load-file' command.
1472 Used for determining the default in the next one.")
1474 (autoload 'comint-get-source "comint")
1476 (defun python-load-file (file-name)
1477 "Load a Python file FILE-NAME into the inferior Python process.
1478 If the file has extension `.py' import or reload it as a module.
1479 Treating it as a module keeps the global namespace clean, provides
1480 function location information for debugging, and supports users of
1481 module-qualified names."
1482 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1483 python-source-modes
1484 t)) ; because execfile needs exact name
1485 (comint-check-source file-name) ; Check to see if buffer needs saving.
1486 (setq python-prev-dir/file (cons (file-name-directory file-name)
1487 (file-name-nondirectory file-name)))
1488 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1489 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1490 (python-send-command
1491 (if (string-match "\\.py\\'" file-name)
1492 (let ((module (file-name-sans-extension
1493 (file-name-nondirectory file-name))))
1494 (format "emacs.eimport(%S,%S)"
1495 module (file-name-directory file-name)))
1496 (format "execfile(%S)" file-name)))
1497 (message "%s loaded" file-name)))
1499 (defun python-proc ()
1500 "Return the current Python process.
1501 See variable `python-buffer'. Starts a new process if necessary."
1502 ;; Fixme: Maybe should look for another active process if there
1503 ;; isn't one for `python-buffer'.
1504 (unless (comint-check-proc python-buffer)
1505 (run-python nil t))
1506 (get-buffer-process (or (if (derived-mode-p 'inferior-python-mode)
1507 (current-buffer)
1508 python-buffer))))
1510 (defun python-set-proc ()
1511 "Set the default value of `python-buffer' to correspond to this buffer.
1512 If the current buffer has a local value of `python-buffer', set the
1513 default (global) value to that. The associated Python process is
1514 the one that gets input from \\[python-send-region] et al when used
1515 in a buffer that doesn't have a local value of `python-buffer'."
1516 (interactive)
1517 (if (local-variable-p 'python-buffer)
1518 (setq-default python-buffer python-buffer)
1519 (error "No local value of `python-buffer'")))
1521 ;;;; Context-sensitive help.
1523 (defconst python-dotty-syntax-table
1524 (let ((table (make-syntax-table)))
1525 (set-char-table-parent table python-mode-syntax-table)
1526 (modify-syntax-entry ?. "_" table)
1527 table)
1528 "Syntax table giving `.' symbol syntax.
1529 Otherwise inherits from `python-mode-syntax-table'.")
1531 (defvar view-return-to-alist)
1532 (eval-when-compile (autoload 'help-buffer "help-fns"))
1534 (defvar python-imports) ; forward declaration
1536 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1537 ;; bound to C-h S? [Probably not, since info-look may work in cases
1538 ;; where this doesn't.]
1539 (defun python-describe-symbol (symbol)
1540 "Get help on SYMBOL using `help'.
1541 Interactively, prompt for symbol.
1543 Symbol may be anything recognized by the interpreter's `help'
1544 command -- e.g. `CALLS' -- not just variables in scope in the
1545 interpreter. This only works for Python version 2.2 or newer
1546 since earlier interpreters don't support `help'.
1548 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1549 will."
1550 ;; Note that we do this in the inferior process, not a separate one, to
1551 ;; ensure the environment is appropriate.
1552 (interactive
1553 (let ((symbol (with-syntax-table python-dotty-syntax-table
1554 (current-word)))
1555 (enable-recursive-minibuffers t))
1556 (list (read-string (if symbol
1557 (format "Describe symbol (default %s): " symbol)
1558 "Describe symbol: ")
1559 nil nil symbol))))
1560 (if (equal symbol "") (error "No symbol"))
1561 ;; Ensure we have a suitable help buffer.
1562 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1563 ;; allow C-c C-f in help buffer.
1564 (let ((temp-buffer-show-hook ; avoid xref stuff
1565 (lambda ()
1566 (toggle-read-only 1)
1567 (setq view-return-to-alist
1568 (list (cons (selected-window) help-return-method))))))
1569 (with-output-to-temp-buffer (help-buffer)
1570 (with-current-buffer standard-output
1571 ;; Fixme: Is this actually useful?
1572 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p))
1573 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1574 (print-help-return-message))))
1575 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1576 symbol python-imports)
1577 "*Help*" (python-proc) nil nil))
1579 (add-to-list 'debug-ignored-errors "^No symbol")
1581 (defun python-send-receive (string)
1582 "Send STRING to inferior Python (if any) and return result.
1583 The result is what follows `_emacs_out' in the output."
1584 (python-send-string string)
1585 (let ((proc (python-proc)))
1586 (with-current-buffer (process-buffer proc)
1587 (set (make-local-variable 'python-preoutput-result) nil)
1588 (while (progn
1589 (accept-process-output proc 5)
1590 (null python-preoutput-result)))
1591 (prog1 python-preoutput-result
1592 (kill-local-variable 'python-preoutput-result)))))
1594 ;; Fixme: Is there anything reasonable we can do with random methods?
1595 ;; (Currently only works with functions.)
1596 (defun python-eldoc-function ()
1597 "`eldoc-print-current-symbol-info' for Python.
1598 Only works when point is in a function name, not its arg list, for
1599 instance. Assumes an inferior Python is running."
1600 (let ((symbol (with-syntax-table python-dotty-syntax-table
1601 (current-word))))
1602 ;; This is run from timers, so inhibit-quit tends to be set.
1603 (with-local-quit
1604 ;; First try the symbol we're on.
1605 (or (and symbol
1606 (python-send-receive (format "emacs.eargs(%S, %s)"
1607 symbol python-imports)))
1608 ;; Try moving to symbol before enclosing parens.
1609 (let ((s (syntax-ppss)))
1610 (unless (zerop (car s))
1611 (when (eq ?\( (char-after (nth 1 s)))
1612 (save-excursion
1613 (goto-char (nth 1 s))
1614 (skip-syntax-backward "-")
1615 (let ((point (point)))
1616 (skip-chars-backward "a-zA-Z._")
1617 (if (< (point) point)
1618 (python-send-receive
1619 (format "emacs.eargs(%S, %s)"
1620 (buffer-substring-no-properties (point) point)
1621 python-imports))))))))))))
1623 ;;;; Info-look functionality.
1625 (defun python-after-info-look ()
1626 "Set up info-look for Python.
1627 Used with `eval-after-load'."
1628 (let* ((version (let ((s (shell-command-to-string (concat python-command
1629 " -V"))))
1630 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1631 (match-string 1 s)))
1632 ;; Whether info files have a Python version suffix, e.g. in Debian.
1633 (versioned
1634 (with-temp-buffer
1635 (with-no-warnings (Info-mode))
1636 (condition-case ()
1637 ;; Don't use `info' because it would pop-up a *info* buffer.
1638 (with-no-warnings
1639 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1640 version))
1642 (error nil)))))
1643 (info-lookup-maybe-add-help
1644 :mode 'python-mode
1645 :regexp "[[:alnum:]_]+"
1646 :doc-spec
1647 ;; Fixme: Can this reasonably be made specific to indices with
1648 ;; different rules? Is the order of indices optimal?
1649 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1650 ;; instance.)
1651 (if versioned
1652 ;; The empty prefix just gets us highlighted terms.
1653 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1654 (,(concat "(python" version "-ref)Module Index" nil ""))
1655 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1656 nil ""))
1657 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1658 nil ""))
1659 (,(concat "(python" version "-lib)Module Index" nil ""))
1660 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1661 nil ""))
1662 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1663 nil ""))
1664 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1665 '(("(python-ref)Miscellaneous Index" nil "")
1666 ("(python-ref)Module Index" nil "")
1667 ("(python-ref)Function-Method-Variable Index" nil "")
1668 ("(python-ref)Class-Exception-Object Index" nil "")
1669 ("(python-lib)Module Index" nil "")
1670 ("(python-lib)Class-Exception-Object Index" nil "")
1671 ("(python-lib)Function-Method-Variable Index" nil "")
1672 ("(python-lib)Miscellaneous Index" nil ""))))))
1673 (eval-after-load "info-look" '(python-after-info-look))
1675 ;;;; Miscellany.
1677 (defcustom python-jython-packages '("java" "javax" "org" "com")
1678 "Packages implying `jython-mode'.
1679 If these are imported near the beginning of the buffer, `python-mode'
1680 actually punts to `jython-mode'."
1681 :type '(repeat string)
1682 :group 'python)
1684 ;; Called from `python-mode', this causes a recursive call of the
1685 ;; mode. See logic there to break out of the recursion.
1686 (defun python-maybe-jython ()
1687 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1688 The criterion is either a match for `jython-mode' via
1689 `interpreter-mode-alist' or an import of a module from the list
1690 `python-jython-packages'."
1691 ;; The logic is taken from python-mode.el.
1692 (save-excursion
1693 (save-restriction
1694 (widen)
1695 (goto-char (point-min))
1696 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1697 (match-string 2))))
1698 (if (and interpreter (eq 'jython-mode
1699 (cdr (assoc (file-name-nondirectory
1700 interpreter)
1701 interpreter-mode-alist))))
1702 (jython-mode)
1703 (if (catch 'done
1704 (while (re-search-forward
1705 (rx line-start (or "import" "from") (1+ space)
1706 (group (1+ (not (any " \t\n.")))))
1707 (+ (point-min) 10000) ; Probably not worth customizing.
1709 (if (member (match-string 1) python-jython-packages)
1710 (throw 'done t))))
1711 (jython-mode)))))))
1713 (defun python-fill-paragraph (&optional justify)
1714 "`fill-paragraph-function' handling comments and multi-line strings.
1715 If any of the current line is a comment, fill the comment or the
1716 paragraph of it that point is in, preserving the comment's
1717 indentation and initial comment characters. Similarly if the end
1718 of the current line is in or at the end of a multi-line string.
1719 Otherwise, do nothing."
1720 (interactive "P")
1721 (or (fill-comment-paragraph justify)
1722 ;; The `paragraph-start' and `paragraph-separate' variables
1723 ;; don't allow us to delimit the last paragraph in a multi-line
1724 ;; string properly, so narrow to the string and then fill around
1725 ;; (the end of) the current line.
1726 (save-excursion
1727 (end-of-line)
1728 (let* ((syntax (syntax-ppss))
1729 (orig (point))
1730 (start (nth 8 syntax))
1731 end)
1732 (cond ((eq t (nth 3 syntax)) ; in fenced string
1733 (goto-char (nth 8 syntax)) ; string start
1734 (condition-case () ; for unbalanced quotes
1735 (progn (forward-sexp)
1736 (setq end (point)))
1737 (error (setq end (point-max)))))
1738 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced
1739 ; string
1740 (forward-char)
1741 (setq end (point))
1742 (condition-case ()
1743 (progn (backward-sexp)
1744 (setq start (point)))
1745 (error nil))))
1746 (when end
1747 (save-restriction
1748 (narrow-to-region start end)
1749 (goto-char orig)
1750 (fill-paragraph justify))))))
1753 (defun python-shift-left (start end &optional count)
1754 "Shift lines in region COUNT (the prefix arg) columns to the left.
1755 COUNT defaults to `python-indent'. If region isn't active, just shift
1756 current line. The region shifted includes the lines in which START and
1757 END lie. It is an error if any lines in the region are indented less than
1758 COUNT columns."
1759 (interactive (if mark-active
1760 (list (region-beginning) (region-end) current-prefix-arg)
1761 (list (point) (point) current-prefix-arg)))
1762 (if count
1763 (setq count (prefix-numeric-value count))
1764 (setq count python-indent))
1765 (when (> count 0)
1766 (save-excursion
1767 (goto-char start)
1768 (while (< (point) end)
1769 (if (and (< (current-indentation) count)
1770 (not (looking-at "[ \t]*$")))
1771 (error "Can't shift all lines enough"))
1772 (forward-line))
1773 (indent-rigidly start end (- count)))))
1775 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1777 (defun python-shift-right (start end &optional count)
1778 "Shift lines in region COUNT (the prefix arg) columns to the right.
1779 COUNT defaults to `python-indent'. If region isn't active, just shift
1780 current line. The region shifted includes the lines in which START and
1781 END lie."
1782 (interactive (if mark-active
1783 (list (region-beginning) (region-end) current-prefix-arg)
1784 (list (point) (point) current-prefix-arg)))
1785 (if count
1786 (setq count (prefix-numeric-value count))
1787 (setq count python-indent))
1788 (indent-rigidly start end count))
1790 (defun python-outline-level ()
1791 "`outline-level' function for Python mode.
1792 The level is the number of `python-indent' steps of indentation
1793 of current line."
1794 (1+ (/ (current-indentation) python-indent)))
1796 ;; Fixme: Consider top-level assignments, imports, &c.
1797 (defun python-current-defun ()
1798 "`add-log-current-defun-function' for Python."
1799 (save-excursion
1800 ;; Move up the tree of nested `class' and `def' blocks until we
1801 ;; get to zero indentation, accumulating the defined names.
1802 (let ((start t)
1803 accum)
1804 (while (or start (> (current-indentation) 0))
1805 (setq start nil)
1806 (python-beginning-of-block)
1807 (end-of-line)
1808 (beginning-of-defun)
1809 (if (looking-at (rx (0+ space) (or "def" "class") (1+ space)
1810 (group (1+ (or word (syntax symbol))))))
1811 (push (match-string 1) accum)))
1812 (if accum (mapconcat 'identity accum ".")))))
1814 (defun python-mark-block ()
1815 "Mark the block around point.
1816 Uses `python-beginning-of-block', `python-end-of-block'."
1817 (interactive)
1818 (push-mark)
1819 (python-beginning-of-block)
1820 (push-mark (point) nil t)
1821 (python-end-of-block)
1822 (exchange-point-and-mark))
1824 ;; Fixme: Provide a find-function-like command to find source of a
1825 ;; definition (separate from BicycleRepairMan). Complicated by
1826 ;; finding the right qualified name.
1828 ;;;; Completion.
1830 (defvar python-imports nil
1831 "String of top-level import statements updated by `python-find-imports'.")
1832 (make-variable-buffer-local 'python-imports)
1834 ;; Fixme: Should font-lock try to run this when it deals with an import?
1835 ;; Maybe not a good idea if it gets run multiple times when the
1836 ;; statement is being edited, and is more likely to end up with
1837 ;; something syntactically incorrect.
1838 ;; However, what we should do is to trundle up the block tree from point
1839 ;; to extract imports that appear to be in scope, and add those.
1840 (defun python-find-imports ()
1841 "Find top-level imports, updating `python-imports'."
1842 (interactive)
1843 (save-excursion
1844 (let (lines)
1845 (goto-char (point-min))
1846 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
1847 (unless (syntax-ppss-context (syntax-ppss))
1848 (push (buffer-substring (line-beginning-position)
1849 (line-beginning-position 2))
1850 lines)))
1851 (setq python-imports
1852 (if lines
1853 (apply #'concat
1854 ;; This is probably best left out since you're unlikely to need the
1855 ;; doc for a function in the buffer and the import will lose if the
1856 ;; Python sub-process' working directory isn't the same as the
1857 ;; buffer's.
1858 ;; (if buffer-file-name
1859 ;; (concat
1860 ;; "import "
1861 ;; (file-name-sans-extension
1862 ;; (file-name-nondirectory buffer-file-name))))
1863 (nreverse lines))
1864 "None"))
1865 (when lines
1866 (set-text-properties 0 (length python-imports) nil python-imports)
1867 ;; The output ends up in the wrong place if the string we
1868 ;; send contains newlines (from the imports).
1869 (setq python-imports
1870 (replace-regexp-in-string "\n" "\\n"
1871 (format "%S" python-imports) t t))))))
1873 ;; Fixme: This fails the first time if the sub-process isn't already
1874 ;; running. Presumably a timing issue with i/o to the process.
1875 (defun python-symbol-completions (symbol)
1876 "Return a list of completions of the string SYMBOL from Python process.
1877 The list is sorted.
1878 Uses `python-imports' to load modules against which to complete."
1879 (when symbol
1880 (let ((completions
1881 (condition-case ()
1882 (car (read-from-string
1883 (python-send-receive
1884 (format "emacs.complete(%S,%s)" symbol python-imports))))
1885 (error nil))))
1886 (sort
1887 ;; We can get duplicates from the above -- don't know why.
1888 (delete-dups completions)
1889 #'string<))))
1891 (defun python-partial-symbol ()
1892 "Return the partial symbol before point (for completion)."
1893 (let ((end (point))
1894 (start (save-excursion
1895 (and (re-search-backward
1896 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
1897 (group (1+ (regexp "[[:alnum:]._]"))) point)
1898 nil t)
1899 (match-beginning 1)))))
1900 (if start (buffer-substring-no-properties start end))))
1902 (defun python-complete-symbol ()
1903 "Perform completion on the Python symbol preceding point.
1904 Repeating the command scrolls the completion window."
1905 (interactive)
1906 (let ((window (get-buffer-window "*Completions*")))
1907 (if (and (eq last-command this-command)
1908 window (window-live-p window) (window-buffer window)
1909 (buffer-name (window-buffer window)))
1910 (with-current-buffer (window-buffer window)
1911 (if (pos-visible-in-window-p (point-max) window)
1912 (set-window-start window (point-min))
1913 (save-selected-window
1914 (select-window window)
1915 (scroll-up))))
1916 ;; Do completion.
1917 (let* ((end (point))
1918 (symbol (python-partial-symbol))
1919 (completions (python-symbol-completions symbol))
1920 (completion (if completions
1921 (try-completion symbol completions))))
1922 (when symbol
1923 (cond ((eq completion t))
1924 ((null completion)
1925 (message "Can't find completion for \"%s\"" symbol)
1926 (ding))
1927 ((not (string= symbol completion))
1928 (delete-region (- end (length symbol)) end)
1929 (insert completion))
1931 (message "Making completion list...")
1932 (with-output-to-temp-buffer "*Completions*"
1933 (display-completion-list completions symbol))
1934 (message "Making completion list...%s" "done"))))))))
1936 (defun python-try-complete (old)
1937 "Completion function for Python for use with `hippie-expand'."
1938 (when (derived-mode-p 'python-mode) ; though we only add it locally
1939 (unless old
1940 (let ((symbol (python-partial-symbol)))
1941 (he-init-string (- (point) (length symbol)) (point))
1942 (if (not (he-string-member he-search-string he-tried-table))
1943 (push he-search-string he-tried-table))
1944 (setq he-expand-list
1945 (and symbol (python-symbol-completions symbol)))))
1946 (while (and he-expand-list
1947 (he-string-member (car he-expand-list) he-tried-table))
1948 (pop he-expand-list))
1949 (if he-expand-list
1950 (progn
1951 (he-substitute-string (pop he-expand-list))
1953 (if old (he-reset-string))
1954 nil)))
1956 ;;;; FFAP support
1958 (defun python-module-path (module)
1959 "Function for `ffap-alist' to return path to MODULE."
1960 (python-send-receive (format "emacs.modpath (%S)" module)))
1962 (eval-after-load "ffap"
1963 '(push '(python-mode . python-module-path) ffap-alist))
1965 ;;;; Skeletons
1967 (defvar python-skeletons nil
1968 "Alist of named skeletons for Python mode.
1969 Elements are of the form (NAME . EXPANDER-FUNCTION).")
1971 (defvar python-mode-abbrev-table nil
1972 "Abbrev table for Python mode.
1973 The default contents correspond to the elements of `python-skeletons'.")
1974 (define-abbrev-table 'python-mode-abbrev-table ())
1976 (eval-when-compile
1977 ;; Define a user-level skeleton and add it to `python-skeletons' and
1978 ;; the abbrev table.
1979 (defmacro def-python-skeleton (name &rest elements)
1980 (let* ((name (symbol-name name))
1981 (function (intern (concat "python-insert-" name))))
1982 `(progn
1983 (add-to-list 'python-skeletons ',(cons name function))
1984 (define-abbrev python-mode-abbrev-table ,name "" ',function nil t)
1985 (define-skeleton ,function
1986 ,(format "Insert Python \"%s\" template." name)
1987 ,@elements)))))
1988 (put 'def-python-skeleton 'lisp-indent-function 2)
1990 ;; From `skeleton-further-elements':
1991 ;; `<': outdent a level;
1992 ;; `^': delete indentation on current line and also previous newline.
1993 ;; Not quote like `delete-indentation'. Assumes point is at
1994 ;; beginning of indentation.
1996 (def-python-skeleton if
1997 "Condition: "
1998 "if " str ":" \n
1999 > _ \n
2000 ("other condition, %s: "
2001 < ; Avoid wrong indentation after block opening.
2002 "elif " str ":" \n
2003 > _ \n nil)
2004 (python-else) | ^)
2006 (define-skeleton python-else
2007 "Auxiliary skeleton."
2009 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2010 (signal 'quit t))
2011 < "else:" \n
2012 > _ \n)
2014 (def-python-skeleton while
2015 "Condition: "
2016 "while " str ":" \n
2017 > _ \n
2018 (python-else) | ^)
2020 (def-python-skeleton for
2021 "Target, %s: "
2022 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2023 > _ \n
2024 (python-else) | ^)
2026 (def-python-skeleton try/except
2028 "try:" \n
2029 > _ \n
2030 ("Exception, %s: "
2031 < "except " str (python-target) ":" \n
2032 > _ \n nil)
2033 < "except:" \n
2034 > _ \n
2035 (python-else) | ^)
2037 (define-skeleton python-target
2038 "Auxiliary skeleton."
2039 "Target, %s: " ", " str | -2)
2041 (def-python-skeleton try/finally
2043 "try:" \n
2044 > _ \n
2045 < "finally:" \n
2046 > _ \n)
2048 (def-python-skeleton def
2049 "Name: "
2050 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2051 str) "):" \n
2052 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2053 > _ \n)
2055 (def-python-skeleton class
2056 "Name: "
2057 "class " str " (" ("Inheritance, %s: "
2058 (unless (equal ?\( (char-before)) ", ")
2059 str)
2060 & ")" | -2 ; close list or remove opening
2061 ":" \n
2062 "\"\"\"" @ " \"\"\"" \n
2063 > _ \n)
2065 (defvar python-default-template "if"
2066 "Default template to expand by `python-insert-template'.
2067 Updated on each expansion.")
2069 (defun python-expand-template (name)
2070 "Expand template named NAME.
2071 Interactively, prompt for the name with completion."
2072 (interactive
2073 (list (completing-read (format "Template to expand (default %s): "
2074 python-default-template)
2075 python-skeletons nil t)))
2076 (if (equal "" name)
2077 (setq name python-default-template)
2078 (setq python-default-template name))
2079 (let ((func (cdr (assoc name python-skeletons))))
2080 (if func
2081 (funcall func)
2082 (error "Undefined template: %s" name))))
2084 ;;;; Bicycle Repair Man support
2086 (autoload 'pymacs-load "pymacs" nil t)
2087 (autoload 'brm-init "bikemacs")
2089 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2090 ;; the way it modifies files outside Emacs... Also note that the
2091 ;; current BRM loses with tabs used for indentation -- I submitted a
2092 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2093 (defun python-setup-brm ()
2094 "Set up Bicycle Repair Man refactoring tool (if available).
2096 Note that the `refactoring' features change files independently of
2097 Emacs and may modify and save the contents of the current buffer
2098 without confirmation."
2099 (interactive)
2100 (condition-case data
2101 (unless (fboundp 'brm-rename)
2102 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2103 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2104 (features (cons 'python-mode features))) ; and requires this
2105 (brm-init)) ; second line of normal recipe
2106 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2107 '(lambda () (easy-menu-add brm-menu)))
2108 (easy-menu-define
2109 python-brm-menu python-mode-map
2110 "Bicycle Repair Man"
2111 '("BicycleRepairMan"
2112 :help "Interface to navigation and refactoring tool"
2113 "Queries"
2114 ["Find References" brm-find-references
2115 :help "Find references to name at point in compilation buffer"]
2116 ["Find Definition" brm-find-definition
2117 :help "Find definition of name at point"]
2119 "Refactoring"
2120 ["Rename" brm-rename
2121 :help "Replace name at point with a new name everywhere"]
2122 ["Extract Method" brm-extract-method
2123 :active (and mark-active (not buffer-read-only))
2124 :help "Replace statements in region with a method"]
2125 ["Extract Local Variable" brm-extract-local-variable
2126 :active (and mark-active (not buffer-read-only))
2127 :help "Replace expression in region with an assignment"]
2128 ["Inline Local Variable" brm-inline-local-variable
2129 :help
2130 "Substitute uses of variable at point with its definition"]
2131 ;; Fixme: Should check for anything to revert.
2132 ["Undo Last Refactoring" brm-undo :help ""])))
2133 (error (error "Bicyclerepairman setup failed: %s" data))))
2135 ;;;; Modes.
2137 (defvar outline-heading-end-regexp)
2138 (defvar eldoc-documentation-function)
2140 ;; Stuff to allow expanding abbrevs with non-word constituents.
2141 (defun python-abbrev-pc-hook ()
2142 "Set the syntax table before possibly expanding abbrevs."
2143 (remove-hook 'post-command-hook 'python-abbrev-pc-hook t)
2144 (set-syntax-table python-mode-syntax-table))
2146 (defvar python-abbrev-syntax-table
2147 (copy-syntax-table python-mode-syntax-table)
2148 "Syntax table used when expanding abbrevs.")
2150 (defun python-pea-hook ()
2151 "Reset the syntax table after possibly expanding abbrevs."
2152 (set-syntax-table python-abbrev-syntax-table)
2153 (add-hook 'post-command-hook 'python-abbrev-pc-hook nil t))
2154 (modify-syntax-entry ?/ "w" python-abbrev-syntax-table)
2156 (defvar python-mode-running) ;Dynamically scoped var.
2158 ;;;###autoload
2159 (define-derived-mode python-mode fundamental-mode "Python"
2160 "Major mode for editing Python files.
2161 Font Lock mode is currently required for correct parsing of the source.
2162 See also `jython-mode', which is actually invoked if the buffer appears to
2163 contain Jython code. See also `run-python' and associated Python mode
2164 commands for running Python under Emacs.
2166 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2167 with nested `def' and `class' blocks. They take the innermost one as
2168 current without distinguishing method and class definitions. Used multiple
2169 times, they move over others at the same indentation level until they reach
2170 the end of definitions at that level, when they move up a level.
2171 \\<python-mode-map>
2172 Colon is electric: it outdents the line if appropriate, e.g. for
2173 an else statement. \\[python-backspace] at the beginning of an indented statement
2174 deletes a level of indentation to close the current block; otherwise it
2175 deletes a character backward. TAB indents the current line relative to
2176 the preceding code. Successive TABs, with no intervening command, cycle
2177 through the possibilities for indentation on the basis of enclosing blocks.
2179 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2180 effect outside them.
2182 Supports Eldoc mode (only for functions, using a Python process),
2183 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2184 lines count as headers. Symbol completion is available in the
2185 same way as in the Python shell using the `rlcompleter' module
2186 and this is added to the Hippie Expand functions locally if
2187 Hippie Expand mode is turned on. Completion of symbols of the
2188 form x.y only works if the components are literal
2189 module/attribute names, not variables. An abbrev table is set up
2190 with skeleton expansions for compound statement templates.
2192 \\{python-mode-map}"
2193 :group 'python
2194 (set (make-local-variable 'font-lock-defaults)
2195 '(python-font-lock-keywords nil nil nil nil
2196 (font-lock-syntactic-keywords
2197 . python-font-lock-syntactic-keywords)
2198 ;; This probably isn't worth it.
2199 ;; (font-lock-syntactic-face-function
2200 ;; . python-font-lock-syntactic-face-function)
2202 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2203 (set (make-local-variable 'comment-start) "# ")
2204 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2205 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2206 (set (make-local-variable 'paragraph-start) "\\s-*$")
2207 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2208 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2209 (set (make-local-variable 'add-log-current-defun-function)
2210 #'python-current-defun)
2211 (set (make-local-variable 'outline-regexp)
2212 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2213 "for" "if" "try" "while")
2214 symbol-end))
2215 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2216 (set (make-local-variable 'outline-level) #'python-outline-level)
2217 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2218 (make-local-variable 'python-saved-check-command)
2219 (set (make-local-variable 'beginning-of-defun-function)
2220 'python-beginning-of-defun)
2221 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2222 (setq imenu-create-index-function #'python-imenu-create-index)
2223 (set (make-local-variable 'eldoc-documentation-function)
2224 #'python-eldoc-function)
2225 (add-hook 'eldoc-mode-hook
2226 (lambda () (run-python nil t)) ; need it running
2227 nil t)
2228 ;; Fixme: should be in hideshow. This seems to be of limited use
2229 ;; since it isn't (can't be) indentation-based. Also hide-level
2230 ;; doesn't seem to work properly.
2231 (add-to-list 'hs-special-modes-alist
2232 `(python-mode "^\\s-*def\\>" nil "#"
2233 ,(lambda (arg)
2234 (python-end-of-defun)
2235 (skip-chars-backward " \t\n"))
2236 nil))
2237 (set (make-local-variable 'skeleton-further-elements)
2238 '((< '(backward-delete-char-untabify (min python-indent
2239 (current-column))))
2240 (^ '(- (1+ (current-indentation))))))
2241 (add-hook 'pre-abbrev-expand-hook 'python-pea-hook nil t)
2242 (if (featurep 'hippie-exp)
2243 (set (make-local-variable 'hippie-expand-try-functions-list)
2244 (cons 'python-try-complete hippie-expand-try-functions-list)))
2245 ;; Python defines TABs as being 8-char wide.
2246 (set (make-local-variable 'tab-width) 8)
2247 (when python-guess-indent (python-guess-indent))
2248 ;; Let's make it harder for the user to shoot himself in the foot.
2249 (unless (= tab-width python-indent)
2250 (setq indent-tabs-mode nil))
2251 (set (make-local-variable 'python-command) python-python-command)
2252 (python-find-imports)
2253 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2254 (let ((python-mode-running t))
2255 (python-maybe-jython))))
2257 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2258 (custom-add-option 'python-mode-hook
2259 (lambda ()
2260 "Turn off Indent Tabs mode."
2261 (set (make-local-variable 'indent-tabs-mode) nil)))
2262 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2263 (custom-add-option 'python-mode-hook 'abbrev-mode)
2264 (custom-add-option 'python-mode-hook 'python-setup-brm)
2266 ;;;###autoload
2267 (define-derived-mode jython-mode python-mode "Jython"
2268 "Major mode for editing Jython files.
2269 Like `python-mode', but sets up parameters for Jython subprocesses.
2270 Runs `jython-mode-hook' after `python-mode-hook'."
2271 :group 'python
2272 (set (make-local-variable 'python-command) python-jython-command))
2274 (provide 'python)
2275 (provide 'python-21)
2276 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2277 ;;; python.el ends here