1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
5 ;; Author: Dave Love <fx@gnu.org>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; Major mode for editing Python, with support for inferior processes.
31 ;; There is another Python mode, python-mode.el, used by XEmacs and
32 ;; maintained with Python. That isn't covered by an FSF copyright
33 ;; assignment, unlike this code, and seems not to be well-maintained
34 ;; for Emacs (though I've submitted fixes). This mode is rather
35 ;; simpler and is better in other ways. In particular, using the
36 ;; syntax functions with text properties maintained by font-lock makes
37 ;; it more correct with arbitrary string and comment contents.
39 ;; This doesn't implement all the facilities of python-mode.el. Some
40 ;; just need doing, e.g. catching exceptions in the inferior Python
41 ;; buffer (but see M-x pdb for debugging). [Actually, the use of
42 ;; `compilation-shell-minor-mode' now is probably enough for that.]
43 ;; Others don't seem appropriate. For instance,
44 ;; `forward-into-nomenclature' should be done separately, since it's
45 ;; not specific to Python, and I've installed a minor mode to do the
46 ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
47 ;; feature, `c-subword-mode' which is intended to have a similar
48 ;; effect, but actually only affects word-oriented keybindings.]
50 ;; Other things seem more natural or canonical here, e.g. the
51 ;; {beginning,end}-of-defun implementation dealing with nested
52 ;; definitions, and the inferior mode following `cmuscheme'. (The
53 ;; inferior mode can find the source of errors from
54 ;; `python-send-region' & al via `compilation-shell-minor-mode'.)
55 ;; There is (limited) symbol completion using lookup in Python and
56 ;; Eldoc support also using the inferior process. Successive TABs
57 ;; cycle between possible indentations for the line.
59 ;; Even where it has similar facilities, this mode is incompatible
60 ;; with python-mode.el in some respects. For instance, various key
61 ;; bindings are changed to obey Emacs conventions.
63 ;; TODO: See various Fixmes below.
70 (require 'hippie-exp
))
72 (autoload 'comint-mode
"comint")
75 "Silly walks in the Python language."
78 :link
'(emacs-commentary-link "python"))
81 (add-to-list 'interpreter-mode-alist
'("jython" . jython-mode
))
83 (add-to-list 'interpreter-mode-alist
'("python" . python-mode
))
85 (add-to-list 'auto-mode-alist
'("\\.py\\'" . python-mode
))
89 (defvar python-font-lock-keywords
91 ;; From v 2.5 reference, § keywords.
92 ;; def and class dealt with separately below
93 (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
94 "except" "exec" "finally" "for" "from" "global" "if"
95 "import" "in" "is" "lambda" "not" "or" "pass" "print"
96 "raise" "return" "try" "while" "with" "yield"
97 ;; Not real keywords, but close enough to be fontified as such
98 "self" "True" "False")
100 (,(rx symbol-start
"None" symbol-end
) ; See § Keywords in 2.5 manual.
101 . font-lock-constant-face
)
103 (,(rx symbol-start
(group "class") (1+ space
) (group (1+ (or word ?_
))))
104 (1 font-lock-keyword-face
) (2 font-lock-type-face
))
105 (,(rx symbol-start
(group "def") (1+ space
) (group (1+ (or word ?_
))))
106 (1 font-lock-keyword-face
) (2 font-lock-function-name-face
))
107 ;; Top-level assignments are worth highlighting.
108 (,(rx line-start
(group (1+ (or word ?_
))) (0+ space
) "=")
109 (1 font-lock-variable-name-face
))
110 (,(rx "@" (1+ (or word ?_
))) ; decorators
111 (0 font-lock-preprocessor-face
))))
113 (defconst python-font-lock-syntactic-keywords
114 ;; Make outer chars of matching triple-quote sequences into generic
115 ;; string delimiters. Fixme: Is there a better way?
116 `((,(rx (or line-start buffer-start
117 (not (syntax escape
))) ; avoid escaped leading quote
118 (group (optional (any "uUrR"))) ; prefix gets syntax property
119 (optional (any "rR")) ; possible second prefix
120 (group (syntax string-quote
)) ; maybe gets property
121 (backref 2) ; per first quote
122 (group (backref 2))) ; maybe gets property
123 (1 (python-quote-syntax 1))
124 (2 (python-quote-syntax 2))
125 (3 (python-quote-syntax 3)))
126 ;; This doesn't really help.
127 ;;; (,(rx (and ?\\ (group ?\n))) (1 " "))
130 (defun python-quote-syntax (n)
131 "Put `syntax-table' property correctly on triple quote.
132 Used for syntactic keywords. N is the match number (1, 2 or 3)."
133 ;; Given a triple quote, we have to check the context to know
134 ;; whether this is an opening or closing triple or whether it's
135 ;; quoted anyhow, and should be ignored. (For that we need to do
136 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
137 ;; to use it here despite initial worries.) We also have to sort
138 ;; out a possible prefix -- well, we don't _have_ to, but I think it
139 ;; should be treated as part of the string.
142 ;; ur"""ar""" x='"' # """
145 ;; x '"""' x """ \"""" x
146 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
149 (goto-char (match-beginning 0))
151 ;; Consider property for the last char if in a fenced string.
153 (let* ((font-lock-syntactic-keywords nil
)
154 (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 (let ((font-lock-syntactic-keywords nil
))
167 (unless (nth 3 (syntax-ppss))
168 (eval-when-compile (string-to-syntax "|")))))
169 ;; Otherwise (we're in a non-matching string) the property is
173 ;; This isn't currently in `font-lock-defaults' as probably not worth
174 ;; it -- we basically only mess with a few normally-symbol characters.
176 ;; (defun python-font-lock-syntactic-face-function (state)
177 ;; "`font-lock-syntactic-face-function' for Python mode.
178 ;; Returns the string or comment face as usual, with side effect of putting
179 ;; a `syntax-table' property on the inside of the string or comment which is
180 ;; the standard syntax table."
183 ;; (goto-char (nth 8 state))
184 ;; (condition-case nil
187 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
188 ;; 'syntax-table (standard-syntax-table))
189 ;; 'font-lock-string-face)
190 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
191 ;; 'syntax-table (standard-syntax-table))
192 ;; 'font-lock-comment-face))
194 ;;;; Keymap and syntax
196 (defvar python-mode-map
197 (let ((map (make-sparse-keymap)))
198 ;; Mostly taken from python-mode.el.
199 (define-key map
":" 'python-electric-colon
)
200 (define-key map
"\177" 'python-backspace
)
201 (define-key map
"\C-c<" 'python-shift-left
)
202 (define-key map
"\C-c>" 'python-shift-right
)
203 (define-key map
"\C-c\C-k" 'python-mark-block
)
204 (define-key map
"\C-c\C-n" 'python-next-statement
)
205 (define-key map
"\C-c\C-p" 'python-previous-statement
)
206 (define-key map
"\C-c\C-u" 'python-beginning-of-block
)
207 (define-key map
"\C-c\C-f" 'python-describe-symbol
)
208 (define-key map
"\C-c\C-w" 'python-check
)
209 (define-key map
"\C-c\C-v" 'python-check
) ; a la sgml-mode
210 (define-key map
"\C-c\C-s" 'python-send-string
)
211 (define-key map
[?\C-\M-x
] 'python-send-defun
)
212 (define-key map
"\C-c\C-r" 'python-send-region
)
213 (define-key map
"\C-c\M-r" 'python-send-region-and-go
)
214 (define-key map
"\C-c\C-c" 'python-send-buffer
)
215 (define-key map
"\C-c\C-z" 'python-switch-to-python
)
216 (define-key map
"\C-c\C-m" 'python-load-file
)
217 (define-key map
"\C-c\C-l" 'python-load-file
) ; a la cmuscheme
218 (substitute-key-definition 'complete-symbol
'python-complete-symbol
220 (define-key map
"\C-c\C-i" 'python-find-imports
)
221 (define-key map
"\C-c\C-t" 'python-expand-template
)
222 (easy-menu-define python-menu map
"Python Mode menu"
224 :help
"Python-specific Features"
225 ["Shift region left" python-shift-left
:active mark-active
226 :help
"Shift by a single indentation step"]
227 ["Shift region right" python-shift-right
:active mark-active
228 :help
"Shift by a single indentation step"]
230 ["Mark block" python-mark-block
231 :help
"Mark innermost block around point"]
232 ["Mark def/class" mark-defun
233 :help
"Mark innermost definition around point"]
235 ["Start of block" python-beginning-of-block
236 :help
"Go to start of innermost definition around point"]
237 ["End of block" python-end-of-block
238 :help
"Go to end of innermost definition around point"]
239 ["Start of def/class" beginning-of-defun
240 :help
"Go to start of innermost definition around point"]
241 ["End of def/class" end-of-defun
242 :help
"Go to end of innermost definition around point"]
245 :help
"Expand templates for compound statements"
246 :filter
(lambda (&rest junk
)
247 (mapcar (lambda (elt)
248 (vector (car elt
) (cdr elt
) t
))
249 python-skeletons
))) ; defined later
251 ["Start interpreter" run-python
252 :help
"Run `inferior' Python in separate buffer"]
253 ["Import/reload file" python-load-file
254 :help
"Load into inferior Python session"]
255 ["Eval buffer" python-send-buffer
256 :help
"Evaluate buffer en bloc in inferior Python session"]
257 ["Eval region" python-send-region
:active mark-active
258 :help
"Evaluate region en bloc in inferior Python session"]
259 ["Eval def/class" python-send-defun
260 :help
"Evaluate current definition in inferior Python session"]
261 ["Switch to interpreter" python-switch-to-python
262 :help
"Switch to inferior Python buffer"]
263 ["Set default process" python-set-proc
264 :help
"Make buffer's inferior process the default"
265 :active
(buffer-live-p python-buffer
)]
266 ["Check file" python-check
:help
"Run pychecker"]
267 ["Debugger" pdb
:help
"Run pdb under GUD"]
269 ["Help on symbol" python-describe-symbol
270 :help
"Use pydoc on symbol at point"]
271 ["Complete symbol" python-complete-symbol
272 :help
"Complete (qualified) symbol before point"]
273 ["Update imports" python-find-imports
274 :help
"Update list of top-level imports for completion"]))
276 ;; Fixme: add toolbar stuff for useful things like symbol help, send
277 ;; region, at least. (Shouldn't be specific to Python, obviously.)
278 ;; eric has items including: (un)indent, (un)comment, restart script,
279 ;; run script, debug script; also things for profiling, unit testing.
281 (defvar python-mode-syntax-table
282 (let ((table (make-syntax-table)))
283 ;; Give punctuation syntax to ASCII that normally has symbol
284 ;; syntax or has word syntax and isn't a letter.
285 (let ((symbol (string-to-syntax "_"))
286 (sst (standard-syntax-table)))
289 (if (equal symbol
(aref sst i
))
290 (modify-syntax-entry i
"." table
)))))
291 (modify-syntax-entry ?$
"." table
)
292 (modify-syntax-entry ?%
"." table
)
294 (modify-syntax-entry ?
# "<" table
)
295 (modify-syntax-entry ?
\n ">" table
)
296 (modify-syntax-entry ?
' "\"" table
)
297 (modify-syntax-entry ?
` "$" table
)
302 (defsubst python-in-string
/comment
()
303 "Return non-nil if point is in a Python literal (a comment or string)."
304 ;; We don't need to save the match data.
305 (nth 8 (syntax-ppss)))
307 (defconst python-space-backslash-table
308 (let ((table (copy-syntax-table python-mode-syntax-table
)))
309 (modify-syntax-entry ?
\\ " " table
)
311 "`python-mode-syntax-table' with backslash given whitespace syntax.")
313 (defun python-skip-comments/blanks
(&optional backward
)
314 "Skip comments and blank lines.
315 BACKWARD non-nil means go backwards, otherwise go forwards.
316 Backslash is treated as whitespace so that continued blank lines
317 are skipped. Doesn't move out of comments -- should be outside
319 (let ((arg (if backward
320 ;; If we're in a comment (including on the trailing
321 ;; newline), forward-comment doesn't move backwards out
322 ;; of it. Don't set the syntax table round this bit!
323 (let ((syntax (syntax-ppss)))
325 (goto-char (nth 8 syntax
)))
328 (with-syntax-table python-space-backslash-table
329 (forward-comment arg
))))
331 (defun python-backslash-continuation-line-p ()
332 "Non-nil if preceding line ends with backslash that is not in a comment."
333 (and (eq ?
\\ (char-before (line-end-position 0)))
334 (not (syntax-ppss-context (syntax-ppss)))))
336 (defun python-continuation-line-p ()
337 "Return non-nil if current line continues a previous one.
338 The criteria are that the previous line ends in a backslash outside
339 comments and strings, or that point is within brackets/parens."
340 (or (python-backslash-continuation-line-p)
341 (let ((depth (syntax-ppss-depth
342 (save-excursion ; syntax-ppss with arg changes point
343 (syntax-ppss (line-beginning-position))))))
345 (if (< depth
0) ; Unbalanced brackets -- act locally
348 (progn (backward-up-list) t
) ; actually within brackets
351 (defun python-comment-line-p ()
352 "Return non-nil iff current line has only a comment."
355 (when (eq 'comment
(syntax-ppss-context (syntax-ppss)))
356 (back-to-indentation)
357 (looking-at (rx (or (syntax comment-start
) line-end
))))))
359 (defun python-blank-line-p ()
360 "Return non-nil iff current line is blank."
363 (looking-at "\\s-*$")))
365 (defun python-beginning-of-string ()
366 "Go to beginning of string around point.
367 Do nothing if not in string."
368 (let ((state (syntax-ppss)))
369 (when (eq 'string
(syntax-ppss-context state
))
370 (goto-char (nth 8 state
)))))
372 (defun python-open-block-statement-p (&optional bos
)
373 "Return non-nil if statement at point opens a block.
374 BOS non-nil means point is known to be at beginning of statement."
376 (unless bos
(python-beginning-of-statement))
377 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
378 "class" "try" "except" "finally" "with")
381 (defun python-close-block-statement-p (&optional bos
)
382 "Return non-nil if current line is a statement closing a block.
383 BOS non-nil means point is at beginning of statement.
384 The criteria are that the line isn't a comment or in string and
385 starts with keyword `raise', `break', `continue' or `pass'."
387 (unless bos
(python-beginning-of-statement))
388 (back-to-indentation)
389 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
392 (defun python-outdent-p ()
393 "Return non-nil if current line should outdent a level."
395 (back-to-indentation)
396 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
398 (not (python-in-string/comment
))
399 ;; Ensure there's a previous statement and move to it.
400 (zerop (python-previous-statement))
401 (not (python-close-block-statement-p t
))
403 (not (python-open-block-statement-p)))))
407 (defcustom python-indent
4
408 "Number of columns for a unit of indentation in Python mode.
409 See also `\\[python-guess-indent]'"
412 (put 'python-indent
'safe-local-variable
'integerp
)
414 (defcustom python-guess-indent t
415 "Non-nil means Python mode guesses `python-indent' for the buffer."
419 (defcustom python-indent-string-contents t
420 "Non-nil means indent contents of multi-line strings together.
421 This means indent them the same as the preceding non-blank line.
422 Otherwise preserve their indentation.
424 This only applies to `doc' strings, i.e. those that form statements;
425 the indentation is preserved in others."
426 :type
'(choice (const :tag
"Align with preceding" t
)
427 (const :tag
"Preserve indentation" nil
))
430 (defcustom python-honour-comment-indentation nil
431 "Non-nil means indent relative to preceding comment line.
432 Only do this for comments where the leading comment character is
433 followed by space. This doesn't apply to comment lines, which
434 are always indented in lines with preceding comments."
438 (defcustom python-continuation-offset
4
439 "Number of columns of additional indentation for continuation lines.
440 Continuation lines follow a backslash-terminated line starting a
445 (defun python-guess-indent ()
446 "Guess step for indentation of current buffer.
447 Set `python-indent' locally to the value guessed."
452 (goto-char (point-min))
454 (while (and (not done
) (not (eobp)))
455 (when (and (re-search-forward (rx ?
: (0+ space
)
456 (or (syntax comment-start
)
459 (python-open-block-statement-p))
461 (python-beginning-of-statement)
462 (let ((initial (current-indentation)))
463 (if (zerop (python-next-statement))
464 (setq indent
(- (current-indentation) initial
)))
465 (if (and indent
(>= indent
2) (<= indent
8)) ; sanity check
468 (when (/= indent
(default-value 'python-indent
))
469 (set (make-local-variable 'python-indent
) indent
)
470 (unless (= tab-width python-indent
)
471 (setq indent-tabs-mode nil
)))
474 ;; Alist of possible indentations and start of statement they would
475 ;; close. Used in indentation cycling (below).
476 (defvar python-indent-list nil
478 ;; Length of the above
479 (defvar python-indent-list-length nil
481 ;; Current index into the alist.
482 (defvar python-indent-index nil
485 (defun python-calculate-indentation ()
486 "Calculate Python indentation for line at point."
487 (setq python-indent-list nil
488 python-indent-list-length
1)
491 (let ((syntax (syntax-ppss))
494 ((eq 'string
(syntax-ppss-context syntax
)) ; multi-line string
495 (if (not python-indent-string-contents
)
496 (current-indentation)
497 ;; Only respect `python-indent-string-contents' in doc
498 ;; strings (defined as those which form statements).
499 (if (not (save-excursion
500 (python-beginning-of-statement)
501 (looking-at (rx (or (syntax string-delimiter
)
502 (syntax string-quote
))))))
503 (current-indentation)
504 ;; Find indentation of preceding non-blank line within string.
505 (setq start
(nth 8 syntax
))
507 (while (and (< start
(point)) (looking-at "\\s-*$"))
509 (current-indentation))))
510 ((python-continuation-line-p) ; after backslash, or bracketed
511 (let ((point (point))
512 (open-start (cadr syntax
))
513 (backslash (python-backslash-continuation-line-p))
514 (colon (eq ?
: (char-before (1- (line-beginning-position))))))
516 ;; Inside bracketed expression.
518 (goto-char (1+ open-start
))
519 ;; Look for first item in list (preceding point) and
520 ;; align with it, if found.
521 (if (with-syntax-table python-space-backslash-table
522 (let ((parse-sexp-ignore-comments t
))
524 (progn (forward-sexp)
528 ;; Extra level if we're backslash-continued or
530 (if (or backslash colon
)
531 (+ python-indent
(current-column))
533 ;; Otherwise indent relative to statement start, one
534 ;; level per bracketing level.
535 (goto-char (1+ open-start
))
536 (python-beginning-of-statement)
537 (+ (current-indentation) (* (car syntax
) python-indent
))))
538 ;; Otherwise backslash-continued.
540 (if (python-continuation-line-p)
541 ;; We're past first continuation line. Align with
543 (current-indentation)
544 ;; First continuation line. Indent one step, with an
545 ;; extra one if statement opens a block.
546 (python-beginning-of-statement)
547 (+ (current-indentation) python-continuation-offset
548 (if (python-open-block-statement-p t
)
552 ;; Fixme: Like python-mode.el; not convinced by this.
553 ((looking-at (rx (0+ space
) (syntax comment-start
)
554 (not (any " \t\n")))) ; non-indentable comment
555 (current-indentation))
556 (t (if python-honour-comment-indentation
557 ;; Back over whitespace, newlines, non-indentable comments.
561 ;; not at comment start
562 ((not (forward-comment -
1))
563 (python-beginning-of-statement)
566 ((/= (current-column) (current-indentation))
567 (python-beginning-of-statement)
569 ;; indentable comment like python-mode.el
570 ((and (looking-at (rx (syntax comment-start
)
571 (or space line-end
)))
572 (/= 0 (current-column)))))
574 (python-indentation-levels)
575 ;; Prefer to indent comments with an immediately-following
580 (when (and (> python-indent-list-length
1)
581 (python-comment-line-p))
583 (unless (python-comment-line-p)
584 (let ((elt (assq (current-indentation) python-indent-list
)))
585 (setq python-indent-list
586 (nconc (delete elt python-indent-list
)
588 (caar (last python-indent-list
)))))))
590 ;;;; Cycling through the possible indentations with successive TABs.
592 ;; These don't need to be buffer-local since they're only relevant
595 (defun python-initial-text ()
596 "Text of line following indentation and ignoring any trailing comment."
598 (buffer-substring (progn
599 (back-to-indentation)
606 (defconst python-block-pairs
607 '(("else" "if" "elif" "while" "for" "try" "except")
609 ("except" "try" "except")
611 "Alist of keyword matches.
612 The car of an element is a keyword introducing a statement which
613 can close a block opened by a keyword in the cdr.")
615 (defun python-first-word ()
616 "Return first word (actually symbol) on the line."
618 (back-to-indentation)
621 (defun python-indentation-levels ()
622 "Return a list of possible indentations for this line.
623 It is assumed not to be a continuation line or in a multi-line string.
624 Includes the default indentation and those which would close all
625 enclosing blocks. Elements of the list are actually pairs:
626 \(INDENTATION . TEXT), where TEXT is the initial text of the
627 corresponding block opening (or nil)."
631 ;; Only one possibility immediately following a block open
632 ;; statement, assuming it doesn't have a `suite' on the same line.
634 ((save-excursion (and (python-previous-statement)
635 (python-open-block-statement-p t
)
636 (setq indent
(current-indentation))
637 ;; Check we don't have something like:
639 (if (progn (python-end-of-statement)
640 (python-skip-comments/blanks t
)
641 (eq ?
: (char-before)))
642 (setq indent
(+ python-indent indent
)))))
643 (push (cons indent initial
) levels
))
644 ;; Only one possibility for comment line immediately following
647 (when (python-comment-line-p)
649 (if (python-comment-line-p)
650 (push (cons (current-indentation) initial
) levels
)))))
651 ;; Fixme: Maybe have a case here which indents (only) first
652 ;; line after a lambda.
654 (let ((start (car (assoc (python-first-word) python-block-pairs
))))
655 (python-previous-statement)
656 ;; Is this a valid indentation for the line of interest?
657 (unless (or (if start
; potentially only outdentable
658 ;; Check for things like:
661 ;; where the second line need not be outdented.
662 (not (member (python-first-word)
664 python-block-pairs
)))))
665 ;; Not sensible to indent to the same level as
666 ;; previous `return' &c.
667 (python-close-block-statement-p))
668 (push (cons (current-indentation) (python-initial-text))
670 (while (python-beginning-of-block)
671 (when (or (not start
)
672 (member (python-first-word)
673 (cdr (assoc start python-block-pairs
))))
674 (push (cons (current-indentation) (python-initial-text))
676 (prog1 (or levels
(setq levels
'((0 .
""))))
677 (setq python-indent-list levels
678 python-indent-list-length
(length python-indent-list
))))))
680 ;; This is basically what `python-indent-line' would be if we didn't
682 (defun python-indent-line-1 (&optional leave
)
683 "Subroutine of `python-indent-line'.
684 Does non-repeated indentation. LEAVE non-nil means leave
685 indentation if it is valid, i.e. one of the positions returned by
686 `python-calculate-indentation'."
687 (let ((target (python-calculate-indentation))
688 (pos (- (point-max) (point))))
689 (if (or (= target
(current-indentation))
690 ;; Maybe keep a valid indentation.
691 (and leave python-indent-list
692 (assq (current-indentation) python-indent-list
)))
693 (if (< (current-column) (current-indentation))
694 (back-to-indentation))
696 (delete-horizontal-space)
698 (if (> (- (point-max) pos
) (point))
699 (goto-char (- (point-max) pos
))))))
701 (defun python-indent-line ()
702 "Indent current line as Python code.
703 When invoked via `indent-for-tab-command', cycle through possible
704 indentations for current line. The cycle is broken by a command
705 different from `indent-for-tab-command', i.e. successive TABs do
708 (if (and (eq this-command
'indent-for-tab-command
)
709 (eq last-command this-command
))
710 (if (= 1 python-indent-list-length
)
711 (message "Sole indentation")
712 (progn (setq python-indent-index
713 (%
(1+ python-indent-index
) python-indent-list-length
))
715 (delete-horizontal-space)
716 (indent-to (car (nth python-indent-index python-indent-list
)))
717 (if (python-block-end-p)
718 (let ((text (cdr (nth python-indent-index
719 python-indent-list
))))
721 (message "Closes: %s" text
))))))
722 (python-indent-line-1)
723 (setq python-indent-index
(1- python-indent-list-length
))))
725 (defun python-indent-region (start end
)
726 "`indent-region-function' for Python.
727 Leaves validly-indented lines alone, i.e. doesn't indent to
728 another valid position."
731 (setq end
(point-marker))
733 (or (bolp) (forward-line 1))
734 (while (< (point) end
)
735 (or (and (bolp) (eolp))
736 (python-indent-line-1 t
))
738 (move-marker end nil
)))
740 (defun python-block-end-p ()
741 "Non-nil if this is a line in a statement closing a block,
742 or a blank line indented to where it would close a block."
743 (and (not (python-comment-line-p))
744 (or (python-close-block-statement-p t
)
745 (< (current-indentation)
747 (python-previous-statement)
748 (current-indentation))))))
752 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
753 ;; block, statement, depending on context.
755 (defun python-beginning-of-defun ()
756 "`beginning-of-defun-function' for Python.
757 Finds beginning of innermost nested class or method definition.
758 Returns the name of the definition found at the end, or nil if
759 reached start of buffer."
760 (let ((ci (current-indentation))
761 (def-re (rx line-start
(0+ space
) (or "def" "class") (1+ space
)
762 (group (1+ (or word
(syntax symbol
))))))
763 found lep
) ;; def-line
764 (if (python-comment-line-p)
765 (setq ci most-positive-fixnum
))
766 (while (and (not (bobp)) (not found
))
767 ;; Treat bol at beginning of function as outside function so
768 ;; that successive C-M-a makes progress backwards.
769 ;;(setq def-line (looking-at def-re))
770 (unless (bolp) (end-of-line))
771 (setq lep
(line-end-position))
772 (if (and (re-search-backward def-re nil
'move
)
773 ;; Must be less indented or matching top level, or
774 ;; equally indented if we started on a definition line.
775 (let ((in (current-indentation)))
776 (or (and (zerop ci
) (zerop in
))
777 (= lep
(line-end-position)) ; on initial line
778 ;; Not sure why it was like this -- fails in case of
779 ;; last internal function followed by first
780 ;; non-def statement of the main body.
781 ;;(and def-line (= in ci))
784 (not (python-in-string/comment
)))
787 (defun python-end-of-defun ()
788 "`end-of-defun-function' for Python.
789 Finds end of innermost nested class or method definition."
791 (pattern (rx line-start
(0+ space
) (or "def" "class") space
)))
792 ;; Go to start of current block and check whether it's at top
793 ;; level. If it is, and not a block start, look forward for
794 ;; definition statement.
795 (when (python-comment-line-p)
797 (forward-comment most-positive-fixnum
))
798 (if (not (python-open-block-statement-p))
799 (python-beginning-of-block))
800 (if (zerop (current-indentation))
801 (unless (python-open-block-statement-p)
802 (while (and (re-search-forward pattern nil
'move
)
803 (python-in-string/comment
))) ; just loop
805 (beginning-of-line)))
806 ;; Don't move before top-level statement that would end defun.
808 (python-beginning-of-defun))
809 ;; If we got to the start of buffer, look forward for
810 ;; definition statement.
811 (if (and (bobp) (not (looking-at "def\\|class")))
812 (while (and (not (eobp))
813 (re-search-forward pattern nil
'move
)
814 (python-in-string/comment
)))) ; just loop
815 ;; We're at a definition statement (or end-of-buffer).
817 (python-end-of-block)
818 ;; Count trailing space in defun (but not trailing comments).
819 (skip-syntax-forward " >")
820 (unless (eobp) ; e.g. missing final newline
821 (beginning-of-line)))
822 ;; Catch pathological cases like this, where the beginning-of-defun
823 ;; skips to a definition we're not in:
831 (goto-char (point-max)))))
833 (defun python-beginning-of-statement ()
834 "Go to start of current statement.
835 Accounts for continuation lines, multi-line strings, and
836 multi-line bracketed expressions."
838 (python-beginning-of-string)
839 (while (python-continuation-line-p)
841 (if (python-backslash-continuation-line-p)
844 (while (python-backslash-continuation-line-p)
846 (python-beginning-of-string)
848 (back-to-indentation))
850 (defun python-skip-out (&optional forward syntax
)
851 "Skip out of any nested brackets.
852 Skip forward if FORWARD is non-nil, else backward.
853 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
854 Return non-nil iff skipping was done."
855 (let ((depth (syntax-ppss-depth (or syntax
(syntax-ppss))))
856 (forward (if forward -
1 1)))
857 (unless (zerop depth
)
859 ;; Skip forward out of nested brackets.
860 (condition-case () ; beware invalid syntax
861 (progn (backward-up-list (* forward depth
)) t
)
863 ;; Invalid syntax (too many closed brackets).
864 ;; Skip out of as many as possible.
866 (while (condition-case ()
867 (progn (backward-up-list forward
)
872 (defun python-end-of-statement ()
873 "Go to the end of the current statement and return point.
874 Usually this is the start of the next line, but if this is a
875 multi-line statement we need to skip over the continuation lines.
876 On a comment line, go to end of line."
878 (while (let (comment)
879 ;; Move past any enclosing strings and sexps, or stop if
880 ;; we're in a comment.
881 (while (let ((s (syntax-ppss)))
882 (cond ((eq 'comment
(syntax-ppss-context s
))
885 ((eq 'string
(syntax-ppss-context s
))
886 ;; Go to start of string and skip it.
888 (goto-char (nth 8 s
))
889 (condition-case () ; beware invalid syntax
890 (progn (forward-sexp) t
)
891 ;; If there's a mismatched string, make sure
892 ;; we still overall move *forward*.
893 (error (goto-char pos
) (end-of-line)))))
894 ((python-skip-out t s
))))
897 (eq ?
\\ (char-before)))) ; Line continued?
898 (end-of-line 2)) ; Try next line.
901 (defun python-previous-statement (&optional count
)
902 "Go to start of previous statement.
903 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
904 Return count of statements left to move."
906 (unless count
(setq count
1))
908 (python-next-statement (- count
))
909 (python-beginning-of-statement)
910 (while (and (> count
0) (not (bobp)))
911 (python-skip-comments/blanks t
)
912 (python-beginning-of-statement)
913 (unless (bobp) (setq count
(1- count
))))
916 (defun python-next-statement (&optional count
)
917 "Go to start of next statement.
918 With argument COUNT, do it COUNT times. Stop at end of buffer.
919 Return count of statements left to move."
921 (unless count
(setq count
1))
923 (python-previous-statement (- count
))
925 (while (and (> count
0) (not (eobp)))
926 (python-end-of-statement)
927 (python-skip-comments/blanks
)
929 (setq count
(1- count
))))
932 (defun python-beginning-of-block (&optional arg
)
933 "Go to start of current block.
934 With numeric arg, do it that many times. If ARG is negative, call
935 `python-end-of-block' instead.
936 If point is on the first line of a block, use its outer block.
937 If current statement is in column zero, don't move and return nil.
938 Otherwise return non-nil."
940 (unless arg
(setq arg
1))
943 ((< arg
0) (python-end-of-block (- arg
)))
945 (let ((point (point)))
946 (if (or (python-comment-line-p)
947 (python-blank-line-p))
948 (python-skip-comments/blanks t
))
949 (python-beginning-of-statement)
950 (let ((ci (current-indentation)))
952 (not (goto-char point
)) ; return nil
953 ;; Look upwards for less indented statement.
955 ;;; This is slower than the below.
956 ;;; (while (zerop (python-previous-statement))
957 ;;; (when (and (< (current-indentation) ci)
958 ;;; (python-open-block-statement-p t))
959 ;;; (beginning-of-line)
960 ;;; (throw 'done t)))
961 (while (and (zerop (forward-line -
1)))
962 (when (and (< (current-indentation) ci
)
963 (not (python-comment-line-p))
964 ;; Move to beginning to save effort in case
965 ;; this is in string.
966 (progn (python-beginning-of-statement) t
)
967 (python-open-block-statement-p t
))
970 (not (goto-char point
))) ; Failed -- return nil
971 (python-beginning-of-block (1- arg
)))))))))
973 (defun python-end-of-block (&optional arg
)
974 "Go to end of current block.
975 With numeric arg, do it that many times. If ARG is negative,
976 call `python-beginning-of-block' instead.
977 If current statement is in column zero and doesn't open a block,
978 don't move and return nil. Otherwise return t."
980 (unless arg
(setq arg
1))
982 (python-beginning-of-block (- arg
))
983 (while (and (> arg
0)
984 (let* ((point (point))
985 (_ (if (python-comment-line-p)
986 (python-skip-comments/blanks t
)))
987 (ci (current-indentation))
988 (open (python-open-block-statement-p)))
989 (if (and (zerop ci
) (not open
))
990 (not (goto-char point
))
992 (while (zerop (python-next-statement))
993 (when (or (and open
(<= (current-indentation) ci
))
994 (< (current-indentation) ci
))
995 (python-skip-comments/blanks t
)
996 (beginning-of-line 2)
997 (throw 'done t
)))))))
1001 (defvar python-which-func-length-limit
40
1002 "Non-strict length limit for `python-which-func' output.")
1004 (defun python-which-func ()
1005 (let ((function-name (python-current-defun python-which-func-length-limit)))
1006 (set-text-properties 0 (length function-name
) nil function-name
)
1012 (defvar python-recursing
)
1013 (defun python-imenu-create-index ()
1014 "`imenu-create-index-function' for Python.
1016 Makes nested Imenu menus from nested `class' and `def' statements.
1017 The nested menus are headed by an item referencing the outer
1018 definition; it has a space prepended to the name so that it sorts
1019 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1021 (unless (boundp 'python-recursing
) ; dynamically bound below
1022 ;; Normal call from Imenu.
1023 (goto-char (point-min))
1024 ;; Without this, we can get an infloop if the buffer isn't all
1025 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1026 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1027 ;; what's going on, but it must be something to do with timers in
1029 ;; This can't be right, especially not when jit-lock is not used. --Stef
1030 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1031 ;; (font-lock-fontify-region (point-min) (point-max)))
1033 (let (index-alist) ; accumulated value to return
1034 (while (re-search-forward
1035 (rx line-start
(0+ space
) ; leading space
1036 (or (group "def") (group "class")) ; type
1037 (1+ space
) (group (1+ (or word ?_
)))) ; name
1039 (unless (python-in-string/comment
)
1040 (let ((pos (match-beginning 0))
1041 (name (match-string-no-properties 3)))
1042 (if (match-beginning 2) ; def or class?
1043 (setq name
(concat "class " name
)))
1046 (let* ((python-recursing t
)
1047 (sublist (python-imenu-create-index)))
1049 (progn (push (cons (concat " " name
) pos
) sublist
)
1050 (push (cons name sublist
) index-alist
))
1051 (push (cons name pos
) index-alist
)))))))
1052 (unless (boundp 'python-recursing
)
1053 ;; Look for module variables.
1055 (goto-char (point-min))
1056 (while (re-search-forward
1057 (rx line-start
(group (1+ (or word ?_
))) (0+ space
) "=")
1059 (unless (python-in-string/comment
)
1060 (push (cons (match-string 1) (match-beginning 1))
1062 (setq index-alist
(nreverse index-alist
))
1064 (push (cons "Module variables"
1069 ;;;; `Electric' commands.
1071 (defun python-electric-colon (arg)
1072 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1073 With numeric ARG, just insert that many colons. With \\[universal-argument],
1074 just insert a single colon."
1076 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1080 (not (python-in-string/comment
))
1081 (> (current-indentation) (python-calculate-indentation))
1082 (python-indent-line))) ; OK, do it
1083 (put 'python-electric-colon
'delete-selection t
)
1085 (defun python-backspace (arg)
1086 "Maybe delete a level of indentation on the current line.
1087 Do so if point is at the end of the line's indentation outside
1088 strings and comments.
1089 Otherwise just call `backward-delete-char-untabify'.
1092 (if (or (/= (current-indentation) (current-column))
1094 (python-continuation-line-p)
1095 (python-in-string/comment
))
1096 (backward-delete-char-untabify arg
)
1097 ;; Look for the largest valid indentation which is smaller than
1098 ;; the current indentation.
1100 (ci (current-indentation))
1101 (indents (python-indentation-levels))
1105 (setq indent
(max indent
(car x
)))))
1106 (setq initial
(cdr (assq indent indents
)))
1107 (if (> (length initial
) 0)
1108 (message "Closes %s" initial
))
1109 (delete-horizontal-space)
1110 (indent-to indent
))))
1111 (put 'python-backspace
'delete-selection
'supersede
)
1115 (defcustom python-check-command
"pychecker --stdlib"
1116 "Command used to check a Python file."
1120 (defvar python-saved-check-command nil
1123 ;; After `sgml-validate-command'.
1124 (defun python-check (command)
1125 "Check a Python file (default current buffer's file).
1126 Runs COMMAND, a shell command, as if by `compile'.
1127 See `python-check-command' for the default."
1129 (list (read-string "Checker command: "
1130 (or python-saved-check-command
1131 (concat python-check-command
" "
1132 (let ((name (buffer-file-name)))
1134 (file-name-nondirectory name
))))))))
1135 (setq python-saved-check-command command
)
1136 (require 'compile
) ;To define compilation-* variables.
1137 (save-some-buffers (not compilation-ask-about-save
) nil
)
1138 (let ((compilation-error-regexp-alist
1139 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1140 compilation-error-regexp-alist
)))
1141 (compilation-start command
)))
1143 ;;;; Inferior mode stuff (following cmuscheme).
1145 ;; Fixme: Make sure we can work with IPython.
1147 (defcustom python-python-command
"python"
1148 "Shell command to run Python interpreter.
1149 Any arguments can't contain whitespace.
1150 Note that IPython may not work properly; it must at least be used
1151 with the `-cl' flag, i.e. use `ipython -cl'."
1155 (defcustom python-jython-command
"jython"
1156 "Shell command to run Jython interpreter.
1157 Any arguments can't contain whitespace."
1161 (defvar python-command python-python-command
1162 "Actual command used to run Python.
1163 May be `python-python-command' or `python-jython-command', possibly
1164 modified by the user. Additional arguments are added when the command
1165 is used by `run-python' et al.")
1167 (defvar python-buffer nil
1168 "*The current Python process buffer.
1170 Commands that send text from source buffers to Python processes have
1171 to choose a process to send to. This is determined by buffer-local
1172 value of `python-buffer'. If its value in the current buffer,
1173 i.e. both any local value and the default one, is nil, `run-python'
1174 and commands that send to the Python process will start a new process.
1176 Whenever \\[run-python] starts a new process, it resets the default
1177 value of `python-buffer' to be the new process's buffer and sets the
1178 buffer-local value similarly if the current buffer is in Python mode
1179 or Inferior Python mode, so that source buffer stays associated with a
1180 specific sub-process.
1182 Use \\[python-set-proc] to set the default value from a buffer with a
1184 (make-variable-buffer-local 'python-buffer
)
1186 (defconst python-compilation-regexp-alist
1187 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1188 ;; The first already is (for CAML), but the second isn't. Anyhow,
1189 ;; these are specific to the inferior buffer. -- fx
1190 `((,(rx line-start
(1+ (any " \t")) "File \""
1191 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1192 "\", line " (group (1+ digit
)))
1194 (,(rx " in file " (group (1+ not-newline
)) " on line "
1198 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1199 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1201 "`compilation-error-regexp-alist' for inferior Python.")
1203 (defvar inferior-python-mode-map
1204 (let ((map (make-sparse-keymap)))
1205 ;; This will inherit from comint-mode-map.
1206 (define-key map
"\C-c\C-l" 'python-load-file
)
1207 (define-key map
"\C-c\C-v" 'python-check
)
1208 ;; Note that we _can_ still use these commands which send to the
1209 ;; Python process even at the prompt iff we have a normal prompt,
1210 ;; i.e. '>>> ' and not '... '. See the comment before
1211 ;; python-send-region. Fixme: uncomment these if we address that.
1213 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1214 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1217 (defvar inferior-python-mode-syntax-table
1218 (let ((st (make-syntax-table python-mode-syntax-table
)))
1219 ;; Don't get confused by apostrophes in the process's output (e.g. if
1220 ;; you execute "help(os)").
1221 (modify-syntax-entry ?
\' "." st
)
1222 ;; Maybe we should do the same for double quotes?
1223 ;; (modify-syntax-entry ?\" "." st)
1227 (declare-function compilation-shell-minor-mode
"compile" (&optional arg
))
1229 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1230 ;; not sure how much: at least some keybindings, like C-c C-f;
1231 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1232 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1233 "Major mode for interacting with an inferior Python process.
1234 A Python process can be started with \\[run-python].
1236 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1239 You can send text to the inferior Python process from other buffers
1240 containing Python source.
1241 * \\[python-switch-to-python] switches the current buffer to the Python
1243 * \\[python-send-region] sends the current region to the Python process.
1244 * \\[python-send-region-and-go] switches to the Python process buffer
1245 after sending the text.
1246 For running multiple processes in multiple buffers, see `run-python' and
1249 \\{inferior-python-mode-map}"
1251 (setq mode-line-process
'(":%s"))
1252 (set (make-local-variable 'comint-input-filter
) 'python-input-filter
)
1253 (add-hook 'comint-preoutput-filter-functions
#'python-preoutput-filter
1255 ;; Still required by `comint-redirect-send-command', for instance
1256 ;; (and we need to match things like `>>> ... >>> '):
1257 (set (make-local-variable 'comint-prompt-regexp
)
1258 (rx line-start
(1+ (and (or (repeat 3 (any ">.")) "(Pdb)") " "))))
1259 (set (make-local-variable 'compilation-error-regexp-alist
)
1260 python-compilation-regexp-alist
)
1261 (compilation-shell-minor-mode 1))
1263 (defcustom inferior-python-filter-regexp
"\\`\\s-*\\S-?\\S-?\\s-*\\'"
1264 "Input matching this regexp is not saved on the history list.
1265 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1269 (defun python-input-filter (str)
1270 "`comint-input-filter' function for inferior Python.
1271 Don't save anything for STR matching `inferior-python-filter-regexp'."
1272 (not (string-match inferior-python-filter-regexp str
)))
1274 ;; Fixme: Loses with quoted whitespace.
1275 (defun python-args-to-list (string)
1276 (let ((where (string-match "[ \t]" string
)))
1277 (cond ((null where
) (list string
))
1279 (cons (substring string
0 where
)
1280 (python-args-to-list (substring string
(+ 1 where
)))))
1281 (t (let ((pos (string-match "[^ \t]" string
)))
1282 (if pos
(python-args-to-list (substring string pos
))))))))
1284 (defvar python-preoutput-result nil
1285 "Data from last `_emacs_out' line seen by the preoutput filter.")
1287 (defvar python-preoutput-leftover nil
)
1288 (defvar python-preoutput-skip-next-prompt nil
)
1290 ;; Using this stops us getting lines in the buffer like
1292 (defun python-preoutput-filter (s)
1293 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1294 (when python-preoutput-leftover
1295 (setq s
(concat python-preoutput-leftover s
))
1296 (setq python-preoutput-leftover nil
))
1299 ;; First process whole lines.
1300 (while (string-match "\n" s start
)
1301 (let ((line (substring s start
(setq start
(match-end 0)))))
1302 ;; Skip prompt if needed.
1303 (when (and python-preoutput-skip-next-prompt
1304 (string-match comint-prompt-regexp line
))
1305 (setq python-preoutput-skip-next-prompt nil
)
1306 (setq line
(substring line
(match-end 0))))
1307 ;; Recognize special _emacs_out lines.
1308 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line
)
1309 (local-variable-p 'python-preoutput-result
))
1311 (setq python-preoutput-result
(match-string 1 line
))
1312 (set (make-local-variable 'python-preoutput-skip-next-prompt
) t
))
1313 (setq res
(concat res line
)))))
1314 ;; Then process the remaining partial line.
1315 (unless (zerop start
) (setq s
(substring s start
)))
1316 (cond ((and (string-match comint-prompt-regexp s
)
1317 ;; Drop this prompt if it follows an _emacs_out...
1318 (or python-preoutput-skip-next-prompt
1319 ;; ... or if it's not gonna be inserted at BOL.
1320 ;; Maybe we could be more selective here.
1321 (if (zerop (length res
))
1323 (string-match ".\\'" res
))))
1324 ;; The need for this seems to be system-dependent:
1325 ;; What is this all about, exactly? --Stef
1326 ;; (if (and (eq ?. (aref s 0)))
1327 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1328 (setq python-preoutput-skip-next-prompt nil
)
1330 ((let ((end (min (length "_emacs_out ") (length s
))))
1331 (eq t
(compare-strings s nil end
"_emacs_out " nil end
)))
1332 ;; The leftover string is a prefix of _emacs_out so we don't know
1333 ;; yet whether it's an _emacs_out or something else: wait until we
1334 ;; get more output so we can resolve this ambiguity.
1335 (set (make-local-variable 'python-preoutput-leftover
) s
)
1337 (t (concat res s
)))))
1339 (autoload 'comint-check-proc
"comint")
1342 (defun run-python (&optional cmd noshow new
)
1343 "Run an inferior Python process, input and output via buffer *Python*.
1344 CMD is the Python command to run. NOSHOW non-nil means don't show the
1345 buffer automatically.
1347 Normally, if there is a process already running in `python-buffer',
1348 switch to that buffer. Interactively, a prefix arg allows you to edit
1349 the initial command line (default is `python-command'); `-i' etc. args
1350 will be added to this as appropriate. A new process is started if:
1351 one isn't running attached to `python-buffer', or interactively the
1352 default `python-command', or argument NEW is non-nil. See also the
1353 documentation for `python-buffer'.
1355 Runs the hook `inferior-python-mode-hook' \(after the
1356 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1357 buffer for a list of commands.)"
1358 (interactive (if current-prefix-arg
1359 (list (read-string "Run Python: " python-command
) nil t
)
1360 (list python-command
)))
1361 (unless cmd
(setq cmd python-python-command
))
1362 (setq python-command cmd
)
1363 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1364 ;; (not a name) in Python buffers from which `run-python' &c is
1365 ;; invoked. Would support multiple processes better.
1366 (when (or new
(not (comint-check-proc python-buffer
)))
1367 (with-current-buffer
1368 (let* ((cmdlist (append (python-args-to-list cmd
) '("-i")))
1369 (path (getenv "PYTHONPATH"))
1370 (process-environment ; to import emacs.py
1371 (cons (concat "PYTHONPATH=" data-directory
1372 (if path
(concat path-separator path
)))
1373 process-environment
)))
1374 (apply 'make-comint-in-buffer
"Python"
1375 (if new
(generate-new-buffer "*Python*") "*Python*")
1376 (car cmdlist
) nil
(cdr cmdlist
)))
1377 (setq-default python-buffer
(current-buffer))
1378 (setq python-buffer
(current-buffer))
1379 (accept-process-output (get-buffer-process python-buffer
) 5)
1380 (inferior-python-mode)
1381 ;; Load function definitions we need.
1382 ;; Before the preoutput function was used, this was done via -c in
1383 ;; cmdlist, but that loses the banner and doesn't run the startup
1384 ;; file. The code might be inline here, but there's enough that it
1385 ;; seems worth putting in a separate file, and it's probably cleaner
1386 ;; to put it in a module.
1387 ;; Ensure we're at a prompt before doing anything else.
1388 (python-send-string "import emacs")))
1389 (if (derived-mode-p 'python-mode
)
1390 (setq python-buffer
(default-value 'python-buffer
))) ; buffer-local
1391 ;; Without this, help output goes into the inferior python buffer if
1392 ;; the process isn't already running.
1393 (sit-for 1 t
) ;Should we use accept-process-output instead? --Stef
1394 (unless noshow
(pop-to-buffer python-buffer t
)))
1396 ;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1397 ;; e.g. prompt is `help> '. Probably raise an error if the form of
1398 ;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1399 ;; `... ', i.e. we're not inputting a block &c. However, this may not
1400 ;; be the place to check it, e.g. we might actually want to send
1401 ;; commands having set up such a state.
1403 (defun python-send-command (command)
1404 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1405 COMMAND should be a single statement."
1406 ;; (assert (not (string-match "\n" command)))
1407 ;; (let ((end (marker-position (process-mark (python-proc)))))
1408 (with-current-buffer (process-buffer (python-proc))
1409 (goto-char (point-max))
1410 (compilation-forget-errors)
1411 (python-send-string command
)
1412 (setq compilation-last-buffer
(current-buffer)))
1413 ;; No idea what this is for but it breaks the call to
1414 ;; compilation-fake-loc in python-send-region. -- Stef
1415 ;; Must wait until this has completed before re-setting variables below.
1416 ;; (python-send-receive "print '_emacs_out ()'")
1417 ;; (with-current-buffer python-buffer
1418 ;; (set-marker compilation-parsing-end end))
1421 (defun python-send-region (start end
)
1422 "Send the region to the inferior Python process."
1423 ;; The region is evaluated from a temporary file. This avoids
1424 ;; problems with blank lines, which have different semantics
1425 ;; interactively and in files. It also saves the inferior process
1426 ;; buffer filling up with interpreter prompts. We need a Python
1427 ;; function to remove the temporary file when it has been evaluated
1428 ;; (though we could probably do it in Lisp with a Comint output
1429 ;; filter). This function also catches exceptions and truncates
1430 ;; tracebacks not to mention the frame of the function itself.
1432 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1433 ;; the reference to the temporary file to the source.
1435 ;; Fixme: Write a `coding' header to the temp file if the region is
1438 (let* ((f (make-temp-file "py"))
1439 (command (format "emacs.eexecfile(%S)" f
))
1440 (orig-start (copy-marker start
)))
1441 (when (save-excursion
1443 (/= 0 (current-indentation))) ; need dummy block
1445 (goto-char orig-start
)
1446 ;; Wrong if we had indented code at buffer start.
1447 (set-marker orig-start
(line-beginning-position 0)))
1448 (write-region "if True:\n" nil f nil
'nomsg
))
1449 (write-region start end f t
'nomsg
)
1450 (python-send-command command
)
1451 (with-current-buffer (process-buffer (python-proc))
1452 ;; Tell compile.el to redirect error locations in file `f' to
1453 ;; positions past marker `orig-start'. It has to be done *after*
1454 ;; `python-send-command''s call to `compilation-forget-errors'.
1455 (compilation-fake-loc orig-start f
))))
1457 (defun python-send-string (string)
1458 "Evaluate STRING in inferior Python process."
1459 (interactive "sPython command: ")
1460 (comint-send-string (python-proc) string
)
1461 (unless (string-match "\n\\'" string
)
1462 ;; Make sure the text is properly LF-terminated.
1463 (comint-send-string (python-proc) "\n"))
1464 (when (string-match "\n[ \t].*\n?\\'" string
)
1465 ;; If the string contains a final indented line, add a second newline so
1466 ;; as to make sure we terminate the multiline instruction.
1467 (comint-send-string (python-proc) "\n")))
1469 (defun python-send-buffer ()
1470 "Send the current buffer to the inferior Python process."
1472 (python-send-region (point-min) (point-max)))
1474 ;; Fixme: Try to define the function or class within the relevant
1475 ;; module, not just at top level.
1476 (defun python-send-defun ()
1477 "Send the current defun (class or method) to the inferior Python process."
1479 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1480 (progn (end-of-defun) (point)))))
1482 (defun python-switch-to-python (eob-p)
1483 "Switch to the Python process buffer, maybe starting new process.
1484 With prefix arg, position cursor at end of buffer."
1486 (pop-to-buffer (process-buffer (python-proc)) t
) ;Runs python if needed.
1489 (goto-char (point-max))))
1491 (defun python-send-region-and-go (start end
)
1492 "Send the region to the inferior Python process.
1493 Then switch to the process buffer."
1495 (python-send-region start end
)
1496 (python-switch-to-python t
))
1498 (defcustom python-source-modes
'(python-mode jython-mode
)
1499 "Used to determine if a buffer contains Python source code.
1500 If a file is loaded into a buffer that is in one of these major modes,
1501 it is considered Python source by `python-load-file', which uses the
1502 value to determine defaults."
1503 :type
'(repeat function
)
1506 (defvar python-prev-dir
/file nil
1507 "Caches (directory . file) pair used in the last `python-load-file' command.
1508 Used for determining the default in the next one.")
1510 (autoload 'comint-get-source
"comint")
1512 (defun python-load-file (file-name)
1513 "Load a Python file FILE-NAME into the inferior Python process.
1514 If the file has extension `.py' import or reload it as a module.
1515 Treating it as a module keeps the global namespace clean, provides
1516 function location information for debugging, and supports users of
1517 module-qualified names."
1518 (interactive (comint-get-source "Load Python file: " python-prev-dir
/file
1520 t
)) ; because execfile needs exact name
1521 (comint-check-source file-name
) ; Check to see if buffer needs saving.
1522 (setq python-prev-dir
/file
(cons (file-name-directory file-name
)
1523 (file-name-nondirectory file-name
)))
1524 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1525 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1526 (python-send-command
1527 (if (string-match "\\.py\\'" file-name
)
1528 (let ((module (file-name-sans-extension
1529 (file-name-nondirectory file-name
))))
1530 (format "emacs.eimport(%S,%S)"
1531 module
(file-name-directory file-name
)))
1532 (format "execfile(%S)" file-name
)))
1533 (message "%s loaded" file-name
)))
1535 (defun python-proc ()
1536 "Return the current Python process.
1537 See variable `python-buffer'. Starts a new process if necessary."
1538 ;; Fixme: Maybe should look for another active process if there
1539 ;; isn't one for `python-buffer'.
1540 (unless (comint-check-proc python-buffer
)
1542 (get-buffer-process (if (derived-mode-p 'inferior-python-mode
)
1546 (defun python-set-proc ()
1547 "Set the default value of `python-buffer' to correspond to this buffer.
1548 If the current buffer has a local value of `python-buffer', set the
1549 default (global) value to that. The associated Python process is
1550 the one that gets input from \\[python-send-region] et al when used
1551 in a buffer that doesn't have a local value of `python-buffer'."
1553 (if (local-variable-p 'python-buffer
)
1554 (setq-default python-buffer python-buffer
)
1555 (error "No local value of `python-buffer'")))
1557 ;;;; Context-sensitive help.
1559 (defconst python-dotty-syntax-table
1560 (let ((table (make-syntax-table)))
1561 (set-char-table-parent table python-mode-syntax-table
)
1562 (modify-syntax-entry ?.
"_" table
)
1564 "Syntax table giving `.' symbol syntax.
1565 Otherwise inherits from `python-mode-syntax-table'.")
1567 (defvar view-return-to-alist
)
1568 (eval-when-compile (autoload 'help-buffer
"help-fns"))
1570 (defvar python-imports
) ; forward declaration
1572 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1573 ;; bound to C-h S? [Probably not, since info-look may work in cases
1574 ;; where this doesn't.]
1575 (defun python-describe-symbol (symbol)
1576 "Get help on SYMBOL using `help'.
1577 Interactively, prompt for symbol.
1579 Symbol may be anything recognized by the interpreter's `help'
1580 command -- e.g. `CALLS' -- not just variables in scope in the
1581 interpreter. This only works for Python version 2.2 or newer
1582 since earlier interpreters don't support `help'.
1584 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1586 ;; Note that we do this in the inferior process, not a separate one, to
1587 ;; ensure the environment is appropriate.
1589 (let ((symbol (with-syntax-table python-dotty-syntax-table
1591 (enable-recursive-minibuffers t
))
1592 (list (read-string (if symbol
1593 (format "Describe symbol (default %s): " symbol
)
1594 "Describe symbol: ")
1596 (if (equal symbol
"") (error "No symbol"))
1597 ;; Ensure we have a suitable help buffer.
1598 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1599 ;; allow C-c C-f in help buffer.
1600 (let ((temp-buffer-show-hook ; avoid xref stuff
1602 (toggle-read-only 1)
1603 (setq view-return-to-alist
1604 (list (cons (selected-window) help-return-method
))))))
1605 (with-output-to-temp-buffer (help-buffer)
1606 (with-current-buffer standard-output
1607 ;; Fixme: Is this actually useful?
1608 (help-setup-xref (list 'python-describe-symbol symbol
) (interactive-p))
1609 (set (make-local-variable 'comint-redirect-subvert-readonly
) t
)
1610 (print-help-return-message))))
1611 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1612 symbol python-imports
)
1613 "*Help*" (python-proc) nil nil
))
1615 (add-to-list 'debug-ignored-errors
"^No symbol")
1617 (defun python-send-receive (string)
1618 "Send STRING to inferior Python (if any) and return result.
1619 The result is what follows `_emacs_out' in the output."
1620 (python-send-string string
)
1621 (let ((proc (python-proc)))
1622 (with-current-buffer (process-buffer proc
)
1623 (set (make-local-variable 'python-preoutput-result
) nil
)
1625 (accept-process-output proc
5)
1626 (null python-preoutput-result
)))
1627 (prog1 python-preoutput-result
1628 (kill-local-variable 'python-preoutput-result
)))))
1630 ;; Fixme: Is there anything reasonable we can do with random methods?
1631 ;; (Currently only works with functions.)
1632 (defun python-eldoc-function ()
1633 "`eldoc-documentation-function' for Python.
1634 Only works when point is in a function name, not its arg list, for
1635 instance. Assumes an inferior Python is running."
1636 (let ((symbol (with-syntax-table python-dotty-syntax-table
1638 ;; This is run from timers, so inhibit-quit tends to be set.
1640 ;; First try the symbol we're on.
1642 (python-send-receive (format "emacs.eargs(%S, %s)"
1643 symbol python-imports
)))
1644 ;; Try moving to symbol before enclosing parens.
1645 (let ((s (syntax-ppss)))
1646 (unless (zerop (car s
))
1647 (when (eq ?\
( (char-after (nth 1 s
)))
1649 (goto-char (nth 1 s
))
1650 (skip-syntax-backward "-")
1651 (let ((point (point)))
1652 (skip-chars-backward "a-zA-Z._")
1653 (if (< (point) point
)
1654 (python-send-receive
1655 (format "emacs.eargs(%S, %s)"
1656 (buffer-substring-no-properties (point) point
)
1657 python-imports
))))))))))))
1659 ;;;; Info-look functionality.
1661 (declare-function info-lookup-maybe-add-help
"info-look" (&rest arg
))
1663 (defun python-after-info-look ()
1664 "Set up info-look for Python.
1665 Used with `eval-after-load'."
1666 (let* ((version (let ((s (shell-command-to-string (concat python-command
1668 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s
)
1669 (match-string 1 s
)))
1670 ;; Whether info files have a Python version suffix, e.g. in Debian.
1673 (with-no-warnings (Info-mode))
1675 ;; Don't use `info' because it would pop-up a *info* buffer.
1677 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1681 (info-lookup-maybe-add-help
1683 :regexp
"[[:alnum:]_]+"
1685 ;; Fixme: Can this reasonably be made specific to indices with
1686 ;; different rules? Is the order of indices optimal?
1687 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1690 ;; The empty prefix just gets us highlighted terms.
1691 `((,(concat "(python" version
"-ref)Miscellaneous Index") nil
"")
1692 (,(concat "(python" version
"-ref)Module Index" nil
""))
1693 (,(concat "(python" version
"-ref)Function-Method-Variable Index"
1695 (,(concat "(python" version
"-ref)Class-Exception-Object Index"
1697 (,(concat "(python" version
"-lib)Module Index" nil
""))
1698 (,(concat "(python" version
"-lib)Class-Exception-Object Index"
1700 (,(concat "(python" version
"-lib)Function-Method-Variable Index"
1702 (,(concat "(python" version
"-lib)Miscellaneous Index" nil
"")))
1703 '(("(python-ref)Miscellaneous Index" nil
"")
1704 ("(python-ref)Module Index" nil
"")
1705 ("(python-ref)Function-Method-Variable Index" nil
"")
1706 ("(python-ref)Class-Exception-Object Index" nil
"")
1707 ("(python-lib)Module Index" nil
"")
1708 ("(python-lib)Class-Exception-Object Index" nil
"")
1709 ("(python-lib)Function-Method-Variable Index" nil
"")
1710 ("(python-lib)Miscellaneous Index" nil
""))))))
1711 (eval-after-load "info-look" '(python-after-info-look))
1715 (defcustom python-jython-packages
'("java" "javax" "org" "com")
1716 "Packages implying `jython-mode'.
1717 If these are imported near the beginning of the buffer, `python-mode'
1718 actually punts to `jython-mode'."
1719 :type
'(repeat string
)
1722 ;; Called from `python-mode', this causes a recursive call of the
1723 ;; mode. See logic there to break out of the recursion.
1724 (defun python-maybe-jython ()
1725 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1726 The criterion is either a match for `jython-mode' via
1727 `interpreter-mode-alist' or an import of a module from the list
1728 `python-jython-packages'."
1729 ;; The logic is taken from python-mode.el.
1733 (goto-char (point-min))
1734 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp
)
1736 (if (and interpreter
(eq 'jython-mode
1737 (cdr (assoc (file-name-nondirectory
1739 interpreter-mode-alist
))))
1742 (while (re-search-forward
1743 (rx line-start
(or "import" "from") (1+ space
)
1744 (group (1+ (not (any " \t\n.")))))
1745 (+ (point-min) 10000) ; Probably not worth customizing.
1747 (if (member (match-string 1) python-jython-packages
)
1751 (defun python-fill-paragraph (&optional justify
)
1752 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1753 If any of the current line is in or at the end of a multi-line string,
1754 fill the string or the paragraph of it that point is in, preserving
1755 the strings's indentation."
1757 (or (fill-comment-paragraph justify
)
1760 (let* ((syntax (syntax-ppss))
1763 (cond ((nth 4 syntax
) ; comment. fixme: loses with trailing one
1764 (let (fill-paragraph-function)
1765 (fill-paragraph justify
)))
1766 ;; The `paragraph-start' and `paragraph-separate'
1767 ;; variables don't allow us to delimit the last
1768 ;; paragraph in a multi-line string properly, so narrow
1769 ;; to the string and then fill around (the end of) the
1771 ((eq t
(nth 3 syntax
)) ; in fenced string
1772 (goto-char (nth 8 syntax
)) ; string start
1773 (setq start
(line-beginning-position))
1774 (setq end
(condition-case () ; for unbalanced quotes
1775 (progn (forward-sexp)
1777 (error (point-max)))))
1778 ((re-search-backward "\\s|\\s-*\\=" nil t
) ; end of fenced string
1782 (progn (backward-sexp)
1783 (setq start
(line-beginning-position)))
1787 (narrow-to-region start end
)
1789 ;; Avoid losing leading and trailing newlines in doc
1790 ;; strings written like:
1794 (let* ((paragraph-separate
1795 (concat ".*\\s|\"\"$" ; newline after opening quotes
1796 "\\|\\(?:" paragraph-separate
"\\)"))
1798 (concat ".*\\s|\"\"[ \t]*[^ \t].*" ; not newline after
1800 "\\|\\(?:" paragraph-separate
"\\)"))
1801 (fill-paragraph-function))
1802 (fill-paragraph justify
))))))) t
)
1804 (defun python-shift-left (start end
&optional count
)
1805 "Shift lines in region COUNT (the prefix arg) columns to the left.
1806 COUNT defaults to `python-indent'. If region isn't active, just shift
1807 current line. The region shifted includes the lines in which START and
1808 END lie. It is an error if any lines in the region are indented less than
1810 (interactive (if mark-active
1811 (list (region-beginning) (region-end) current-prefix-arg
)
1812 (list (point) (point) current-prefix-arg
)))
1814 (setq count
(prefix-numeric-value count
))
1815 (setq count python-indent
))
1819 (while (< (point) end
)
1820 (if (and (< (current-indentation) count
)
1821 (not (looking-at "[ \t]*$")))
1822 (error "Can't shift all lines enough"))
1824 (indent-rigidly start end
(- count
)))))
1826 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1828 (defun python-shift-right (start end
&optional count
)
1829 "Shift lines in region COUNT (the prefix arg) columns to the right.
1830 COUNT defaults to `python-indent'. If region isn't active, just shift
1831 current line. The region shifted includes the lines in which START and
1833 (interactive (if mark-active
1834 (list (region-beginning) (region-end) current-prefix-arg
)
1835 (list (point) (point) current-prefix-arg
)))
1837 (setq count
(prefix-numeric-value count
))
1838 (setq count python-indent
))
1839 (indent-rigidly start end count
))
1841 (defun python-outline-level ()
1842 "`outline-level' function for Python mode.
1843 The level is the number of `python-indent' steps of indentation
1845 (1+ (/ (current-indentation) python-indent
)))
1847 ;; Fixme: Consider top-level assignments, imports, &c.
1848 (defun python-current-defun (&optional length-limit
)
1849 "`add-log-current-defun-function' for Python."
1851 ;; Move up the tree of nested `class' and `def' blocks until we
1852 ;; get to zero indentation, accumulating the defined names.
1856 (while (or (null length-limit
)
1858 (< length length-limit
))
1859 (let ((started-from (point)))
1860 (python-beginning-of-block)
1862 (beginning-of-defun)
1863 (when (= (point) started-from
)
1865 (when (looking-at (rx (0+ space
) (or "def" "class") (1+ space
)
1866 (group (1+ (or word
(syntax symbol
))))))
1867 (push (match-string 1) accum
)
1868 (setq length
(+ length
1 (length (car accum
)))))
1869 (when (= (current-indentation) 0)
1870 (throw 'done nil
))))
1872 (when (and length-limit
(> length length-limit
))
1873 (setcar accum
".."))
1874 (mapconcat 'identity accum
".")))))
1876 (defun python-mark-block ()
1877 "Mark the block around point.
1878 Uses `python-beginning-of-block', `python-end-of-block'."
1881 (python-beginning-of-block)
1882 (push-mark (point) nil t
)
1883 (python-end-of-block)
1884 (exchange-point-and-mark))
1886 ;; Fixme: Provide a find-function-like command to find source of a
1887 ;; definition (separate from BicycleRepairMan). Complicated by
1888 ;; finding the right qualified name.
1892 (defvar python-imports nil
1893 "String of top-level import statements updated by `python-find-imports'.")
1894 (make-variable-buffer-local 'python-imports
)
1896 ;; Fixme: Should font-lock try to run this when it deals with an import?
1897 ;; Maybe not a good idea if it gets run multiple times when the
1898 ;; statement is being edited, and is more likely to end up with
1899 ;; something syntactically incorrect.
1900 ;; However, what we should do is to trundle up the block tree from point
1901 ;; to extract imports that appear to be in scope, and add those.
1902 (defun python-find-imports ()
1903 "Find top-level imports, updating `python-imports'."
1907 (goto-char (point-min))
1908 (while (re-search-forward "^import\\>\\|^from\\>" nil t
)
1909 (unless (syntax-ppss-context (syntax-ppss))
1910 (let ((start (line-beginning-position)))
1911 ;; Skip over continued lines.
1912 (while (and (eq ?
\\ (char-before (line-end-position)))
1913 (= 0 (forward-line 1))))
1914 (push (buffer-substring start
(line-beginning-position 2))
1916 (setq python-imports
1919 ;; This is probably best left out since you're unlikely to need the
1920 ;; doc for a function in the buffer and the import will lose if the
1921 ;; Python sub-process' working directory isn't the same as the
1923 ;; (if buffer-file-name
1926 ;; (file-name-sans-extension
1927 ;; (file-name-nondirectory buffer-file-name))))
1931 (set-text-properties 0 (length python-imports
) nil python-imports
)
1932 ;; The output ends up in the wrong place if the string we
1933 ;; send contains newlines (from the imports).
1934 (setq python-imports
1935 (replace-regexp-in-string "\n" "\\n"
1936 (format "%S" python-imports
) t t
))))))
1938 ;; Fixme: This fails the first time if the sub-process isn't already
1939 ;; running. Presumably a timing issue with i/o to the process.
1940 (defun python-symbol-completions (symbol)
1941 "Return a list of completions of the string SYMBOL from Python process.
1943 Uses `python-imports' to load modules against which to complete."
1947 (car (read-from-string
1948 (python-send-receive
1949 (format "emacs.complete(%S,%s)" symbol python-imports
))))
1952 ;; We can get duplicates from the above -- don't know why.
1953 (delete-dups completions
)
1956 (defun python-partial-symbol ()
1957 "Return the partial symbol before point (for completion)."
1959 (start (save-excursion
1960 (and (re-search-backward
1961 (rx (or buffer-start
(regexp "[^[:alnum:]._]"))
1962 (group (1+ (regexp "[[:alnum:]._]"))) point
)
1964 (match-beginning 1)))))
1965 (if start
(buffer-substring-no-properties start end
))))
1967 (defun python-complete-symbol ()
1968 "Perform completion on the Python symbol preceding point.
1969 Repeating the command scrolls the completion window."
1971 (let ((window (get-buffer-window "*Completions*")))
1972 (if (and (eq last-command this-command
)
1973 (window-live-p window
) (window-buffer window
)
1974 (buffer-name (window-buffer window
)))
1975 (with-current-buffer (window-buffer window
)
1976 (if (pos-visible-in-window-p (point-max) window
)
1977 (set-window-start window
(point-min))
1978 (save-selected-window
1979 (select-window window
)
1982 (let* ((end (point))
1983 (symbol (python-partial-symbol))
1984 (completions (python-symbol-completions symbol
))
1985 (completion (if completions
1986 (try-completion symbol completions
))))
1988 (cond ((eq completion t
))
1990 (message "Can't find completion for \"%s\"" symbol
)
1992 ((not (string= symbol completion
))
1993 (delete-region (- end
(length symbol
)) end
)
1994 (insert completion
))
1996 (message "Making completion list...")
1997 (with-output-to-temp-buffer "*Completions*"
1998 (display-completion-list completions symbol
))
1999 (message "Making completion list...%s" "done"))))))))
2001 (defun python-try-complete (old)
2002 "Completion function for Python for use with `hippie-expand'."
2003 (when (derived-mode-p 'python-mode
) ; though we only add it locally
2005 (let ((symbol (python-partial-symbol)))
2006 (he-init-string (- (point) (length symbol
)) (point))
2007 (if (not (he-string-member he-search-string he-tried-table
))
2008 (push he-search-string he-tried-table
))
2009 (setq he-expand-list
2010 (and symbol
(python-symbol-completions symbol
)))))
2011 (while (and he-expand-list
2012 (he-string-member (car he-expand-list
) he-tried-table
))
2013 (pop he-expand-list
))
2016 (he-substitute-string (pop he-expand-list
))
2018 (if old
(he-reset-string))
2023 (defun python-module-path (module)
2024 "Function for `ffap-alist' to return path to MODULE."
2025 (python-send-receive (format "emacs.modpath (%S)" module
)))
2027 (eval-after-load "ffap"
2028 '(push '(python-mode . python-module-path
) ffap-alist
))
2032 (defcustom python-use-skeletons nil
2033 "Non-nil means template skeletons will be automagically inserted.
2034 This happens when pressing \"if<SPACE>\", for example, to prompt for
2039 (defvar python-skeletons nil
2040 "Alist of named skeletons for Python mode.
2041 Elements are of the form (NAME . EXPANDER-FUNCTION).")
2043 (define-abbrev-table 'python-mode-abbrev-table
()
2044 "Abbrev table for Python mode.
2045 The default contents correspond to the elements of `python-skeletons'."
2046 ;; Allow / in abbrevs.
2047 :regexp
"\\<\\([[:word:]/]+\\)\\W*")
2050 ;; Define a user-level skeleton and add it to `python-skeletons' and
2051 ;; the abbrev table.
2052 (defmacro def-python-skeleton
(name &rest elements
)
2053 (let* ((name (symbol-name name
))
2054 (function (intern (concat "python-insert-" name
))))
2056 (add-to-list 'python-skeletons
',(cons name function
))
2057 (define-abbrev python-mode-abbrev-table
,name
"" ',function
2058 :system t
:case-fixed t
2059 :enable-function
(lambda () python-use-skeletons
))
2060 (define-skeleton ,function
2061 ,(format "Insert Python \"%s\" template." name
)
2063 (put 'def-python-skeleton
'lisp-indent-function
2)
2065 ;; From `skeleton-further-elements':
2066 ;; `<': outdent a level;
2067 ;; `^': delete indentation on current line and also previous newline.
2068 ;; Not quote like `delete-indentation'. Assumes point is at
2069 ;; beginning of indentation.
2071 (def-python-skeleton if
2075 ("other condition, %s: "
2076 < ; Avoid wrong indentation after block opening.
2081 (define-skeleton python-else
2082 "Auxiliary skeleton."
2084 (unless (eq ?y
(read-char "Add `else' clause? (y for yes or RET for no) "))
2089 (def-python-skeleton while
2095 (def-python-skeleton for
2097 "for " str
" in " (skeleton-read "Expression, %s: ") ":" \n
2101 (def-python-skeleton try
/except
2106 < "except " str
(python-target) ":" \n
2112 (define-skeleton python-target
2113 "Auxiliary skeleton."
2114 "Target, %s: " ", " str | -
2)
2116 (def-python-skeleton try
/finally
2123 (def-python-skeleton def
2125 "def " str
" (" ("Parameter, %s: " (unless (equal ?\
( (char-before)) ", ")
2127 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2130 (def-python-skeleton class
2132 "class " str
" (" ("Inheritance, %s: "
2133 (unless (equal ?\
( (char-before)) ", ")
2135 & ")" | -
2 ; close list or remove opening
2137 "\"\"\"" @ " \"\"\"" \n
2140 (defvar python-default-template
"if"
2141 "Default template to expand by `python-expand-template'.
2142 Updated on each expansion.")
2144 (defun python-expand-template (name)
2145 "Expand template named NAME.
2146 Interactively, prompt for the name with completion."
2148 (list (completing-read (format "Template to expand (default %s): "
2149 python-default-template
)
2150 python-skeletons nil t
)))
2152 (setq name python-default-template
)
2153 (setq python-default-template name
))
2154 (let ((func (cdr (assoc name python-skeletons
))))
2157 (error "Undefined template: %s" name
))))
2159 ;;;; Bicycle Repair Man support
2161 (autoload 'pymacs-load
"pymacs" nil t
)
2162 (autoload 'brm-init
"bikemacs")
2164 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2165 ;; the way it modifies files outside Emacs... Also note that the
2166 ;; current BRM loses with tabs used for indentation -- I submitted a
2167 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2168 (defun python-setup-brm ()
2169 "Set up Bicycle Repair Man refactoring tool (if available).
2171 Note that the `refactoring' features change files independently of
2172 Emacs and may modify and save the contents of the current buffer
2173 without confirmation."
2175 (condition-case data
2176 (unless (fboundp 'brm-rename
)
2177 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2178 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2179 (features (cons 'python-mode features
))) ; and requires this
2180 (brm-init)) ; second line of normal recipe
2181 (remove-hook 'python-mode-hook
; undo this from `brm-init'
2182 '(lambda () (easy-menu-add brm-menu
)))
2184 python-brm-menu python-mode-map
2185 "Bicycle Repair Man"
2186 '("BicycleRepairMan"
2187 :help
"Interface to navigation and refactoring tool"
2189 ["Find References" brm-find-references
2190 :help
"Find references to name at point in compilation buffer"]
2191 ["Find Definition" brm-find-definition
2192 :help
"Find definition of name at point"]
2195 ["Rename" brm-rename
2196 :help
"Replace name at point with a new name everywhere"]
2197 ["Extract Method" brm-extract-method
2198 :active
(and mark-active
(not buffer-read-only
))
2199 :help
"Replace statements in region with a method"]
2200 ["Extract Local Variable" brm-extract-local-variable
2201 :active
(and mark-active
(not buffer-read-only
))
2202 :help
"Replace expression in region with an assignment"]
2203 ["Inline Local Variable" brm-inline-local-variable
2205 "Substitute uses of variable at point with its definition"]
2206 ;; Fixme: Should check for anything to revert.
2207 ["Undo Last Refactoring" brm-undo
:help
""])))
2208 (error (error "Bicyclerepairman setup failed: %s" data
))))
2212 (defvar outline-heading-end-regexp
)
2213 (defvar eldoc-documentation-function
)
2214 (defvar python-mode-running
) ;Dynamically scoped var.
2217 (define-derived-mode python-mode fundamental-mode
"Python"
2218 "Major mode for editing Python files.
2219 Font Lock mode is currently required for correct parsing of the source.
2220 See also `jython-mode', which is actually invoked if the buffer appears to
2221 contain Jython code. See also `run-python' and associated Python mode
2222 commands for running Python under Emacs.
2224 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2225 with nested `def' and `class' blocks. They take the innermost one as
2226 current without distinguishing method and class definitions. Used multiple
2227 times, they move over others at the same indentation level until they reach
2228 the end of definitions at that level, when they move up a level.
2230 Colon is electric: it outdents the line if appropriate, e.g. for
2231 an else statement. \\[python-backspace] at the beginning of an indented statement
2232 deletes a level of indentation to close the current block; otherwise it
2233 deletes a character backward. TAB indents the current line relative to
2234 the preceding code. Successive TABs, with no intervening command, cycle
2235 through the possibilities for indentation on the basis of enclosing blocks.
2237 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2238 effect outside them.
2240 Supports Eldoc mode (only for functions, using a Python process),
2241 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2242 lines count as headers. Symbol completion is available in the
2243 same way as in the Python shell using the `rlcompleter' module
2244 and this is added to the Hippie Expand functions locally if
2245 Hippie Expand mode is turned on. Completion of symbols of the
2246 form x.y only works if the components are literal
2247 module/attribute names, not variables. An abbrev table is set up
2248 with skeleton expansions for compound statement templates.
2250 \\{python-mode-map}"
2252 (set (make-local-variable 'font-lock-defaults
)
2253 '(python-font-lock-keywords nil nil nil nil
2254 (font-lock-syntactic-keywords
2255 . python-font-lock-syntactic-keywords
)
2256 ;; This probably isn't worth it.
2257 ;; (font-lock-syntactic-face-function
2258 ;; . python-font-lock-syntactic-face-function)
2260 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2261 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
2262 (set (make-local-variable 'comment-start
) "# ")
2263 (set (make-local-variable 'indent-line-function
) #'python-indent-line
)
2264 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2265 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2266 (set (make-local-variable 'fill-paragraph-function
) 'python-fill-paragraph
)
2267 (set (make-local-variable 'require-final-newline
) mode-require-final-newline
)
2268 (set (make-local-variable 'add-log-current-defun-function
)
2269 #'python-current-defun
)
2270 (set (make-local-variable 'outline-regexp
)
2271 (rx (* space
) (or "class" "def" "elif" "else" "except" "finally"
2272 "for" "if" "try" "while" "with")
2274 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
2275 (set (make-local-variable 'outline-level
) #'python-outline-level
)
2276 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
2277 (make-local-variable 'python-saved-check-command
)
2278 (set (make-local-variable 'beginning-of-defun-function
)
2279 'python-beginning-of-defun
)
2280 (set (make-local-variable 'end-of-defun-function
) 'python-end-of-defun
)
2281 (add-hook 'which-func-functions
'python-which-func nil t
)
2282 (setq imenu-create-index-function
#'python-imenu-create-index
)
2283 (set (make-local-variable 'eldoc-documentation-function
)
2284 #'python-eldoc-function
)
2285 (add-hook 'eldoc-mode-hook
2286 (lambda () (run-python nil t
)) ; need it running
2288 ;; Fixme: should be in hideshow. This seems to be of limited use
2289 ;; since it isn't (can't be) indentation-based. Also hide-level
2290 ;; doesn't seem to work properly.
2291 (add-to-list 'hs-special-modes-alist
2292 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
2294 (python-end-of-defun)
2295 (skip-chars-backward " \t\n"))
2297 (set (make-local-variable 'skeleton-further-elements
)
2298 '((< '(backward-delete-char-untabify (min python-indent
2300 (^
'(- (1+ (current-indentation))))))
2301 (if (featurep 'hippie-exp
)
2302 (set (make-local-variable 'hippie-expand-try-functions-list
)
2303 (cons 'python-try-complete hippie-expand-try-functions-list
)))
2304 ;; Python defines TABs as being 8-char wide.
2305 (set (make-local-variable 'tab-width
) 8)
2306 (when python-guess-indent
(python-guess-indent))
2307 ;; Let's make it harder for the user to shoot himself in the foot.
2308 (unless (= tab-width python-indent
)
2309 (setq indent-tabs-mode nil
))
2310 (set (make-local-variable 'python-command
) python-python-command
)
2311 (python-find-imports)
2312 (unless (boundp 'python-mode-running
) ; kill the recursion from jython-mode
2313 (let ((python-mode-running t
))
2314 (python-maybe-jython))))
2316 (custom-add-option 'python-mode-hook
'imenu-add-menubar-index
)
2317 (custom-add-option 'python-mode-hook
2319 "Turn off Indent Tabs mode."
2320 (set (make-local-variable 'indent-tabs-mode
) nil
)))
2321 (custom-add-option 'python-mode-hook
'turn-on-eldoc-mode
)
2322 (custom-add-option 'python-mode-hook
'abbrev-mode
)
2323 (custom-add-option 'python-mode-hook
'python-setup-brm
)
2326 (define-derived-mode jython-mode python-mode
"Jython"
2327 "Major mode for editing Jython files.
2328 Like `python-mode', but sets up parameters for Jython subprocesses.
2329 Runs `jython-mode-hook' after `python-mode-hook'."
2331 (set (make-local-variable 'python-command
) python-jython-command
))
2334 (provide 'python-21
)
2335 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2336 ;;; python.el ends here