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