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