1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5 ;; Author: Dave Love <fx@gnu.org>
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
29 ;; Major mode for editing Python, with support for inferior processes.
31 ;; There is another Python mode, python-mode.el, used by XEmacs and
32 ;; maintained with Python. That isn't covered by an FSF copyright
33 ;; assignment, unlike this code, and seems not to be well-maintained
34 ;; for Emacs (though I've submitted fixes). This mode is rather
35 ;; simpler and is better in other ways. In particular, using the
36 ;; syntax functions with text properties maintained by font-lock makes
37 ;; it more correct with arbitrary string and comment contents.
39 ;; This doesn't implement all the facilities of python-mode.el. Some
40 ;; just need doing, e.g. catching exceptions in the inferior Python
41 ;; buffer (but see M-x pdb for debugging). [Actually, the use of
42 ;; `compilation-shell-minor-mode' now is probably enough for that.]
43 ;; Others don't seem appropriate. For instance,
44 ;; `forward-into-nomenclature' should be done separately, since it's
45 ;; not specific to Python, and I've installed a minor mode to do the
46 ;; job properly in Emacs 23. [CC mode 5.31 contains an incompatible
47 ;; feature, `c-subword-mode' which is intended to have a similar
48 ;; effect, but actually only affects word-oriented keybindings.]
50 ;; Other things seem more natural or canonical here, e.g. the
51 ;; {beginning,end}-of-defun implementation dealing with nested
52 ;; definitions, and the inferior mode following `cmuscheme'. (The
53 ;; inferior mode can find the source of errors from
54 ;; `python-send-region' & al via `compilation-shell-minor-mode'.)
55 ;; There is (limited) symbol completion using lookup in Python and
56 ;; Eldoc support also using the inferior process. Successive TABs
57 ;; cycle between possible indentations for the line.
59 ;; Even where it has similar facilities, this mode is incompatible
60 ;; with python-mode.el in some respects. For instance, various key
61 ;; bindings are changed to obey Emacs conventions.
63 ;; TODO: See various Fixmes below.
71 (require 'hippie-exp
))
73 (autoload 'comint-mode
"comint")
76 "Silly walks in the Python language."
79 :link
'(emacs-commentary-link "python"))
82 (add-to-list 'interpreter-mode-alist
'("jython" . jython-mode
))
84 (add-to-list 'interpreter-mode-alist
'("python" . python-mode
))
86 (add-to-list 'auto-mode-alist
'("\\.py\\'" . python-mode
))
90 (defvar python-font-lock-keywords
92 ;; From v 2.5 reference, § keywords.
93 ;; def and class dealt with separately below
94 (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
95 "except" "exec" "finally" "for" "from" "global" "if"
96 "import" "in" "is" "lambda" "not" "or" "pass" "print"
97 "raise" "return" "try" "while" "with" "yield"
98 ;; Not real keywords, but close enough to be fontified as such
99 "self" "True" "False")
101 (,(rx symbol-start
"None" symbol-end
) ; See § Keywords in 2.5 manual.
102 . font-lock-constant-face
)
104 (,(rx symbol-start
(group "class") (1+ space
) (group (1+ (or word ?_
))))
105 (1 font-lock-keyword-face
) (2 font-lock-type-face
))
106 (,(rx symbol-start
(group "def") (1+ space
) (group (1+ (or word ?_
))))
107 (1 font-lock-keyword-face
) (2 font-lock-function-name-face
))
108 ;; Top-level assignments are worth highlighting.
109 (,(rx line-start
(group (1+ (or word ?_
))) (0+ space
) "=")
110 (1 font-lock-variable-name-face
))
111 (,(rx "@" (1+ (or word ?_
))) ; decorators
112 (0 font-lock-preprocessor-face
))))
114 (defconst python-font-lock-syntactic-keywords
115 ;; Make outer chars of matching triple-quote sequences into generic
116 ;; string delimiters. Fixme: Is there a better way?
117 `((,(rx (or line-start buffer-start
118 (not (syntax escape
))) ; avoid escaped leading quote
119 (group (optional (any "uUrR"))) ; prefix gets syntax property
120 (optional (any "rR")) ; possible second prefix
121 (group (syntax string-quote
)) ; maybe gets property
122 (backref 2) ; per first quote
123 (group (backref 2))) ; maybe gets property
124 (1 (python-quote-syntax 1))
125 (2 (python-quote-syntax 2))
126 (3 (python-quote-syntax 3)))
127 ;; This doesn't really help.
128 ;;; (,(rx (and ?\\ (group ?\n))) (1 " "))
131 (defun python-quote-syntax (n)
132 "Put `syntax-table' property correctly on triple quote.
133 Used for syntactic keywords. N is the match number (1, 2 or 3)."
134 ;; Given a triple quote, we have to check the context to know
135 ;; whether this is an opening or closing triple or whether it's
136 ;; quoted anyhow, and should be ignored. (For that we need to do
137 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
138 ;; to use it here despite initial worries.) We also have to sort
139 ;; out a possible prefix -- well, we don't _have_ to, but I think it
140 ;; should be treated as part of the string.
143 ;; ur"""ar""" x='"' # """
146 ;; x '"""' x """ \"""" x
147 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
150 (goto-char (match-beginning 0))
152 ;; Consider property for the last char if in a fenced string.
154 (let* ((font-lock-syntactic-keywords nil
)
155 (syntax (syntax-ppss)))
156 (when (eq t
(nth 3 syntax
)) ; after unclosed fence
157 (goto-char (nth 8 syntax
)) ; fence position
158 (skip-chars-forward "uUrR") ; skip any prefix
159 ;; Is it a matching sequence?
160 (if (eq (char-after) (char-after (match-beginning 2)))
161 (eval-when-compile (string-to-syntax "|"))))))
162 ;; Consider property for initial char, accounting for prefixes.
163 ((or (and (= n
2) ; leading quote (not prefix)
164 (= (match-beginning 1) (match-end 1))) ; prefix is null
165 (and (= n
1) ; prefix
166 (/= (match-beginning 1) (match-end 1)))) ; non-empty
167 (let ((font-lock-syntactic-keywords nil
))
168 (unless (nth 3 (syntax-ppss))
169 (eval-when-compile (string-to-syntax "|")))))
170 ;; Otherwise (we're in a non-matching string) the property is
174 ;; This isn't currently in `font-lock-defaults' as probably not worth
175 ;; it -- we basically only mess with a few normally-symbol characters.
177 ;; (defun python-font-lock-syntactic-face-function (state)
178 ;; "`font-lock-syntactic-face-function' for Python mode.
179 ;; Returns the string or comment face as usual, with side effect of putting
180 ;; a `syntax-table' property on the inside of the string or comment which is
181 ;; the standard syntax table."
184 ;; (goto-char (nth 8 state))
185 ;; (condition-case nil
188 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
189 ;; 'syntax-table (standard-syntax-table))
190 ;; 'font-lock-string-face)
191 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
192 ;; 'syntax-table (standard-syntax-table))
193 ;; 'font-lock-comment-face))
195 ;;;; Keymap and syntax
197 (defvar python-mode-map
198 (let ((map (make-sparse-keymap)))
199 ;; Mostly taken from python-mode.el.
200 (define-key map
":" 'python-electric-colon
)
201 (define-key map
"\177" 'python-backspace
)
202 (define-key map
"\C-c<" 'python-shift-left
)
203 (define-key map
"\C-c>" 'python-shift-right
)
204 (define-key map
"\C-c\C-k" 'python-mark-block
)
205 (define-key map
"\C-c\C-n" 'python-next-statement
)
206 (define-key map
"\C-c\C-p" 'python-previous-statement
)
207 (define-key map
"\C-c\C-u" 'python-beginning-of-block
)
208 (define-key map
"\C-c\C-f" 'python-describe-symbol
)
209 (define-key map
"\C-c\C-w" 'python-check
)
210 (define-key map
"\C-c\C-v" 'python-check
) ; a la sgml-mode
211 (define-key map
"\C-c\C-s" 'python-send-string
)
212 (define-key map
[?\C-\M-x
] 'python-send-defun
)
213 (define-key map
"\C-c\C-r" 'python-send-region
)
214 (define-key map
"\C-c\M-r" 'python-send-region-and-go
)
215 (define-key map
"\C-c\C-c" 'python-send-buffer
)
216 (define-key map
"\C-c\C-z" 'python-switch-to-python
)
217 (define-key map
"\C-c\C-m" 'python-load-file
)
218 (define-key map
"\C-c\C-l" 'python-load-file
) ; a la cmuscheme
219 (substitute-key-definition 'complete-symbol
'python-complete-symbol
221 (define-key map
"\C-c\C-i" 'python-find-imports
)
222 (define-key map
"\C-c\C-t" 'python-expand-template
)
223 (easy-menu-define python-menu map
"Python Mode menu"
225 :help
"Python-specific Features"
226 ["Shift region left" python-shift-left
:active mark-active
227 :help
"Shift by a single indentation step"]
228 ["Shift region right" python-shift-right
:active mark-active
229 :help
"Shift by a single indentation step"]
231 ["Mark block" python-mark-block
232 :help
"Mark innermost block around point"]
233 ["Mark def/class" mark-defun
234 :help
"Mark innermost definition around point"]
236 ["Start of block" python-beginning-of-block
237 :help
"Go to start of innermost definition around point"]
238 ["End of block" python-end-of-block
239 :help
"Go to end of innermost definition around point"]
240 ["Start of def/class" beginning-of-defun
241 :help
"Go to start of innermost definition around point"]
242 ["End of def/class" end-of-defun
243 :help
"Go to end of innermost definition around point"]
246 :help
"Expand templates for compound statements"
247 :filter
(lambda (&rest junk
)
248 (mapcar (lambda (elt)
249 (vector (car elt
) (cdr elt
) t
))
250 python-skeletons
))) ; defined later
252 ["Start interpreter" run-python
253 :help
"Run `inferior' Python in separate buffer"]
254 ["Import/reload file" python-load-file
255 :help
"Load into inferior Python session"]
256 ["Eval buffer" python-send-buffer
257 :help
"Evaluate buffer en bloc in inferior Python session"]
258 ["Eval region" python-send-region
:active mark-active
259 :help
"Evaluate region en bloc in inferior Python session"]
260 ["Eval def/class" python-send-defun
261 :help
"Evaluate current definition in inferior Python session"]
262 ["Switch to interpreter" python-switch-to-python
263 :help
"Switch to inferior Python buffer"]
264 ["Set default process" python-set-proc
265 :help
"Make buffer's inferior process the default"
266 :active
(buffer-live-p python-buffer
)]
267 ["Check file" python-check
:help
"Run pychecker"]
268 ["Debugger" pdb
:help
"Run pdb under GUD"]
270 ["Help on symbol" python-describe-symbol
271 :help
"Use pydoc on symbol at point"]
272 ["Complete symbol" python-complete-symbol
273 :help
"Complete (qualified) symbol before point"]
274 ["Update imports" python-find-imports
275 :help
"Update list of top-level imports for completion"]))
277 ;; Fixme: add toolbar stuff for useful things like symbol help, send
278 ;; region, at least. (Shouldn't be specific to Python, obviously.)
279 ;; eric has items including: (un)indent, (un)comment, restart script,
280 ;; run script, debug script; also things for profiling, unit testing.
282 (defvar python-mode-syntax-table
283 (let ((table (make-syntax-table)))
284 ;; Give punctuation syntax to ASCII that normally has symbol
285 ;; syntax or has word syntax and isn't a letter.
286 (let ((symbol (string-to-syntax "_"))
287 (sst (standard-syntax-table)))
290 (if (equal symbol
(aref sst i
))
291 (modify-syntax-entry i
"." table
)))))
292 (modify-syntax-entry ?$
"." table
)
293 (modify-syntax-entry ?%
"." table
)
295 (modify-syntax-entry ?
# "<" table
)
296 (modify-syntax-entry ?
\n ">" table
)
297 (modify-syntax-entry ?
' "\"" table
)
298 (modify-syntax-entry ?
` "$" table
)
303 (defsubst python-in-string
/comment
()
304 "Return non-nil if point is in a Python literal (a comment or string)."
305 ;; We don't need to save the match data.
306 (nth 8 (syntax-ppss)))
308 (defconst python-space-backslash-table
309 (let ((table (copy-syntax-table python-mode-syntax-table
)))
310 (modify-syntax-entry ?
\\ " " table
)
312 "`python-mode-syntax-table' with backslash given whitespace syntax.")
314 (defun python-skip-comments/blanks
(&optional backward
)
315 "Skip comments and blank lines.
316 BACKWARD non-nil means go backwards, otherwise go forwards.
317 Backslash is treated as whitespace so that continued blank lines
318 are skipped. Doesn't move out of comments -- should be outside
320 (let ((arg (if backward
321 ;; If we're in a comment (including on the trailing
322 ;; newline), forward-comment doesn't move backwards out
323 ;; of it. Don't set the syntax table round this bit!
324 (let ((syntax (syntax-ppss)))
326 (goto-char (nth 8 syntax
)))
329 (with-syntax-table python-space-backslash-table
330 (forward-comment arg
))))
332 (defun python-backslash-continuation-line-p ()
333 "Non-nil if preceding line ends with backslash that is not in a comment."
334 (and (eq ?
\\ (char-before (line-end-position 0)))
335 (not (syntax-ppss-context (syntax-ppss)))))
337 (defun python-continuation-line-p ()
338 "Return non-nil if current line continues a previous one.
339 The criteria are that the previous line ends in a backslash outside
340 comments and strings, or that point is within brackets/parens."
341 (or (python-backslash-continuation-line-p)
342 (let ((depth (syntax-ppss-depth
343 (save-excursion ; syntax-ppss with arg changes point
344 (syntax-ppss (line-beginning-position))))))
346 (if (< depth
0) ; Unbalanced brackets -- act locally
349 (progn (backward-up-list) t
) ; actually within brackets
352 (defun python-comment-line-p ()
353 "Return non-nil iff current line has only a comment."
356 (when (eq 'comment
(syntax-ppss-context (syntax-ppss)))
357 (back-to-indentation)
358 (looking-at (rx (or (syntax comment-start
) line-end
))))))
360 (defun python-blank-line-p ()
361 "Return non-nil iff current line is blank."
364 (looking-at "\\s-*$")))
366 (defun python-beginning-of-string ()
367 "Go to beginning of string around point.
368 Do nothing if not in string."
369 (let ((state (syntax-ppss)))
370 (when (eq 'string
(syntax-ppss-context state
))
371 (goto-char (nth 8 state
)))))
373 (defun python-open-block-statement-p (&optional bos
)
374 "Return non-nil if statement at point opens a block.
375 BOS non-nil means point is known to be at beginning of statement."
377 (unless bos
(python-beginning-of-statement))
378 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
379 "class" "try" "except" "finally" "with")
382 (defun python-close-block-statement-p (&optional bos
)
383 "Return non-nil if current line is a statement closing a block.
384 BOS non-nil means point is at beginning of statement.
385 The criteria are that the line isn't a comment or in string and
386 starts with keyword `raise', `break', `continue' or `pass'."
388 (unless bos
(python-beginning-of-statement))
389 (back-to-indentation)
390 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
393 (defun python-outdent-p ()
394 "Return non-nil if current line should outdent a level."
396 (back-to-indentation)
397 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
399 (not (python-in-string/comment
))
400 ;; Ensure there's a previous statement and move to it.
401 (zerop (python-previous-statement))
402 (not (python-close-block-statement-p t
))
404 (not (python-open-block-statement-p)))))
408 (defcustom python-indent
4
409 "Number of columns for a unit of indentation in Python mode.
410 See also `\\[python-guess-indent]'"
413 (put 'python-indent
'safe-local-variable
'integerp
)
415 (defcustom python-guess-indent t
416 "Non-nil means Python mode guesses `python-indent' for the buffer."
420 (defcustom python-indent-string-contents t
421 "Non-nil means indent contents of multi-line strings together.
422 This means indent them the same as the preceding non-blank line.
423 Otherwise preserve their indentation.
425 This only applies to `doc' strings, i.e. those that form statements;
426 the indentation is preserved in others."
427 :type
'(choice (const :tag
"Align with preceding" t
)
428 (const :tag
"Preserve indentation" nil
))
431 (defcustom python-honour-comment-indentation nil
432 "Non-nil means indent relative to preceding comment line.
433 Only do this for comments where the leading comment character is
434 followed by space. This doesn't apply to comment lines, which
435 are always indented in lines with preceding comments."
439 (defcustom python-continuation-offset
4
440 "Number of columns of additional indentation for continuation lines.
441 Continuation lines follow a backslash-terminated line starting a
446 (defun python-guess-indent ()
447 "Guess step for indentation of current buffer.
448 Set `python-indent' locally to the value guessed."
453 (goto-char (point-min))
455 (while (and (not done
) (not (eobp)))
456 (when (and (re-search-forward (rx ?
: (0+ space
)
457 (or (syntax comment-start
)
460 (python-open-block-statement-p))
462 (python-beginning-of-statement)
463 (let ((initial (current-indentation)))
464 (if (zerop (python-next-statement))
465 (setq indent
(- (current-indentation) initial
)))
466 (if (and indent
(>= indent
2) (<= indent
8)) ; sanity check
469 (when (/= indent
(default-value 'python-indent
))
470 (set (make-local-variable 'python-indent
) indent
)
471 (unless (= tab-width python-indent
)
472 (setq indent-tabs-mode nil
)))
475 ;; Alist of possible indentations and start of statement they would
476 ;; close. Used in indentation cycling (below).
477 (defvar python-indent-list nil
479 ;; Length of the above
480 (defvar python-indent-list-length nil
482 ;; Current index into the alist.
483 (defvar python-indent-index nil
486 (defun python-calculate-indentation ()
487 "Calculate Python indentation for line at point."
488 (setq python-indent-list nil
489 python-indent-list-length
1)
492 (let ((syntax (syntax-ppss))
495 ((eq 'string
(syntax-ppss-context syntax
)) ; multi-line string
496 (if (not python-indent-string-contents
)
497 (current-indentation)
498 ;; Only respect `python-indent-string-contents' in doc
499 ;; strings (defined as those which form statements).
500 (if (not (save-excursion
501 (python-beginning-of-statement)
502 (looking-at (rx (or (syntax string-delimiter
)
503 (syntax string-quote
))))))
504 (current-indentation)
505 ;; Find indentation of preceding non-blank line within string.
506 (setq start
(nth 8 syntax
))
508 (while (and (< start
(point)) (looking-at "\\s-*$"))
510 (current-indentation))))
511 ((python-continuation-line-p) ; after backslash, or bracketed
512 (let ((point (point))
513 (open-start (cadr syntax
))
514 (backslash (python-backslash-continuation-line-p))
515 (colon (eq ?
: (char-before (1- (line-beginning-position))))))
517 ;; Inside bracketed expression.
519 (goto-char (1+ open-start
))
520 ;; Look for first item in list (preceding point) and
521 ;; align with it, if found.
522 (if (with-syntax-table python-space-backslash-table
523 (let ((parse-sexp-ignore-comments t
))
525 (progn (forward-sexp)
529 ;; Extra level if we're backslash-continued or
531 (if (or backslash colon
)
532 (+ python-indent
(current-column))
534 ;; Otherwise indent relative to statement start, one
535 ;; level per bracketing level.
536 (goto-char (1+ open-start
))
537 (python-beginning-of-statement)
538 (+ (current-indentation) (* (car syntax
) python-indent
))))
539 ;; Otherwise backslash-continued.
541 (if (python-continuation-line-p)
542 ;; We're past first continuation line. Align with
544 (current-indentation)
545 ;; First continuation line. Indent one step, with an
546 ;; extra one if statement opens a block.
547 (python-beginning-of-statement)
548 (+ (current-indentation) python-continuation-offset
549 (if (python-open-block-statement-p t
)
553 ;; Fixme: Like python-mode.el; not convinced by this.
554 ((looking-at (rx (0+ space
) (syntax comment-start
)
555 (not (any " \t\n")))) ; non-indentable comment
556 (current-indentation))
557 (t (if python-honour-comment-indentation
558 ;; Back over whitespace, newlines, non-indentable comments.
562 ;; not at comment start
563 ((not (forward-comment -
1))
564 (python-beginning-of-statement)
567 ((/= (current-column) (current-indentation))
568 (python-beginning-of-statement)
570 ;; indentable comment like python-mode.el
571 ((and (looking-at (rx (syntax comment-start
)
572 (or space line-end
)))
573 (/= 0 (current-column)))))
575 (python-indentation-levels)
576 ;; Prefer to indent comments with an immediately-following
581 (when (and (> python-indent-list-length
1)
582 (python-comment-line-p))
584 (unless (python-comment-line-p)
585 (let ((elt (assq (current-indentation) python-indent-list
)))
586 (setq python-indent-list
587 (nconc (delete elt python-indent-list
)
589 (caar (last python-indent-list
)))))))
591 ;;;; Cycling through the possible indentations with successive TABs.
593 ;; These don't need to be buffer-local since they're only relevant
596 (defun python-initial-text ()
597 "Text of line following indentation and ignoring any trailing comment."
599 (buffer-substring (progn
600 (back-to-indentation)
607 (defconst python-block-pairs
608 '(("else" "if" "elif" "while" "for" "try" "except")
610 ("except" "try" "except")
612 "Alist of keyword matches.
613 The car of an element is a keyword introducing a statement which
614 can close a block opened by a keyword in the cdr.")
616 (defun python-first-word ()
617 "Return first word (actually symbol) on the line."
619 (back-to-indentation)
622 (defun python-indentation-levels ()
623 "Return a list of possible indentations for this line.
624 It is assumed not to be a continuation line or in a multi-line string.
625 Includes the default indentation and those which would close all
626 enclosing blocks. Elements of the list are actually pairs:
627 \(INDENTATION . TEXT), where TEXT is the initial text of the
628 corresponding block opening (or nil)."
632 ;; Only one possibility immediately following a block open
633 ;; statement, assuming it doesn't have a `suite' on the same line.
635 ((save-excursion (and (python-previous-statement)
636 (python-open-block-statement-p t
)
637 (setq indent
(current-indentation))
638 ;; Check we don't have something like:
640 (if (progn (python-end-of-statement)
641 (python-skip-comments/blanks t
)
642 (eq ?
: (char-before)))
643 (setq indent
(+ python-indent indent
)))))
644 (push (cons indent initial
) levels
))
645 ;; Only one possibility for comment line immediately following
648 (when (python-comment-line-p)
650 (if (python-comment-line-p)
651 (push (cons (current-indentation) initial
) levels
)))))
652 ;; Fixme: Maybe have a case here which indents (only) first
653 ;; line after a lambda.
655 (let ((start (car (assoc (python-first-word) python-block-pairs
))))
656 (python-previous-statement)
657 ;; Is this a valid indentation for the line of interest?
658 (unless (or (if start
; potentially only outdentable
659 ;; Check for things like:
662 ;; where the second line need not be outdented.
663 (not (member (python-first-word)
665 python-block-pairs
)))))
666 ;; Not sensible to indent to the same level as
667 ;; previous `return' &c.
668 (python-close-block-statement-p))
669 (push (cons (current-indentation) (python-initial-text))
671 (while (python-beginning-of-block)
672 (when (or (not start
)
673 (member (python-first-word)
674 (cdr (assoc start python-block-pairs
))))
675 (push (cons (current-indentation) (python-initial-text))
677 (prog1 (or levels
(setq levels
'((0 .
""))))
678 (setq python-indent-list levels
679 python-indent-list-length
(length python-indent-list
))))))
681 ;; This is basically what `python-indent-line' would be if we didn't
683 (defun python-indent-line-1 (&optional leave
)
684 "Subroutine of `python-indent-line'.
685 Does non-repeated indentation. LEAVE non-nil means leave
686 indentation if it is valid, i.e. one of the positions returned by
687 `python-calculate-indentation'."
688 (let ((target (python-calculate-indentation))
689 (pos (- (point-max) (point))))
690 (if (or (= target
(current-indentation))
691 ;; Maybe keep a valid indentation.
692 (and leave python-indent-list
693 (assq (current-indentation) python-indent-list
)))
694 (if (< (current-column) (current-indentation))
695 (back-to-indentation))
697 (delete-horizontal-space)
699 (if (> (- (point-max) pos
) (point))
700 (goto-char (- (point-max) pos
))))))
702 (defun python-indent-line ()
703 "Indent current line as Python code.
704 When invoked via `indent-for-tab-command', cycle through possible
705 indentations for current line. The cycle is broken by a command
706 different from `indent-for-tab-command', i.e. successive TABs do
709 (if (and (eq this-command
'indent-for-tab-command
)
710 (eq last-command this-command
))
711 (if (= 1 python-indent-list-length
)
712 (message "Sole indentation")
713 (progn (setq python-indent-index
714 (%
(1+ python-indent-index
) python-indent-list-length
))
716 (delete-horizontal-space)
717 (indent-to (car (nth python-indent-index python-indent-list
)))
718 (if (python-block-end-p)
719 (let ((text (cdr (nth python-indent-index
720 python-indent-list
))))
722 (message "Closes: %s" text
))))))
723 (python-indent-line-1)
724 (setq python-indent-index
(1- python-indent-list-length
))))
726 (defun python-indent-region (start end
)
727 "`indent-region-function' for Python.
728 Leaves validly-indented lines alone, i.e. doesn't indent to
729 another valid position."
732 (setq end
(point-marker))
734 (or (bolp) (forward-line 1))
735 (while (< (point) end
)
736 (or (and (bolp) (eolp))
737 (python-indent-line-1 t
))
739 (move-marker end nil
)))
741 (defun python-block-end-p ()
742 "Non-nil if this is a line in a statement closing a block,
743 or a blank line indented to where it would close a block."
744 (and (not (python-comment-line-p))
745 (or (python-close-block-statement-p t
)
746 (< (current-indentation)
748 (python-previous-statement)
749 (current-indentation))))))
753 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
754 ;; block, statement, depending on context.
756 (defun python-beginning-of-defun ()
757 "`beginning-of-defun-function' for Python.
758 Finds beginning of innermost nested class or method definition.
759 Returns the name of the definition found at the end, or nil if
760 reached start of buffer."
761 (let ((ci (current-indentation))
762 (def-re (rx line-start
(0+ space
) (or "def" "class") (1+ space
)
763 (group (1+ (or word
(syntax symbol
))))))
764 found lep
) ;; def-line
765 (if (python-comment-line-p)
766 (setq ci most-positive-fixnum
))
767 (while (and (not (bobp)) (not found
))
768 ;; Treat bol at beginning of function as outside function so
769 ;; that successive C-M-a makes progress backwards.
770 ;;(setq def-line (looking-at def-re))
771 (unless (bolp) (end-of-line))
772 (setq lep
(line-end-position))
773 (if (and (re-search-backward def-re nil
'move
)
774 ;; Must be less indented or matching top level, or
775 ;; equally indented if we started on a definition line.
776 (let ((in (current-indentation)))
777 (or (and (zerop ci
) (zerop in
))
778 (= lep
(line-end-position)) ; on initial line
779 ;; Not sure why it was like this -- fails in case of
780 ;; last internal function followed by first
781 ;; non-def statement of the main body.
782 ;;(and def-line (= in ci))
785 (not (python-in-string/comment
)))
788 (defun python-end-of-defun ()
789 "`end-of-defun-function' for Python.
790 Finds end of innermost nested class or method definition."
792 (pattern (rx line-start
(0+ space
) (or "def" "class") space
)))
793 ;; Go to start of current block and check whether it's at top
794 ;; level. If it is, and not a block start, look forward for
795 ;; definition statement.
796 (when (python-comment-line-p)
798 (forward-comment most-positive-fixnum
))
799 (if (not (python-open-block-statement-p))
800 (python-beginning-of-block))
801 (if (zerop (current-indentation))
802 (unless (python-open-block-statement-p)
803 (while (and (re-search-forward pattern nil
'move
)
804 (python-in-string/comment
))) ; just loop
806 (beginning-of-line)))
807 ;; Don't move before top-level statement that would end defun.
809 (python-beginning-of-defun))
810 ;; If we got to the start of buffer, look forward for
811 ;; definition statement.
812 (if (and (bobp) (not (looking-at "def\\|class")))
813 (while (and (not (eobp))
814 (re-search-forward pattern nil
'move
)
815 (python-in-string/comment
)))) ; just loop
816 ;; We're at a definition statement (or end-of-buffer).
818 (python-end-of-block)
819 ;; Count trailing space in defun (but not trailing comments).
820 (skip-syntax-forward " >")
821 (unless (eobp) ; e.g. missing final newline
822 (beginning-of-line)))
823 ;; Catch pathological cases like this, where the beginning-of-defun
824 ;; skips to a definition we're not in:
832 (goto-char (point-max)))))
834 (defun python-beginning-of-statement ()
835 "Go to start of current statement.
836 Accounts for continuation lines, multi-line strings, and
837 multi-line bracketed expressions."
839 (python-beginning-of-string)
840 (while (python-continuation-line-p)
842 (if (python-backslash-continuation-line-p)
845 (while (python-backslash-continuation-line-p)
847 (python-beginning-of-string)
849 (back-to-indentation))
851 (defun python-skip-out (&optional forward syntax
)
852 "Skip out of any nested brackets.
853 Skip forward if FORWARD is non-nil, else backward.
854 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
855 Return non-nil iff skipping was done."
856 (let ((depth (syntax-ppss-depth (or syntax
(syntax-ppss))))
857 (forward (if forward -
1 1)))
858 (unless (zerop depth
)
860 ;; Skip forward out of nested brackets.
861 (condition-case () ; beware invalid syntax
862 (progn (backward-up-list (* forward depth
)) t
)
864 ;; Invalid syntax (too many closed brackets).
865 ;; Skip out of as many as possible.
867 (while (condition-case ()
868 (progn (backward-up-list forward
)
873 (defun python-end-of-statement ()
874 "Go to the end of the current statement and return point.
875 Usually this is the start of the next line, but if this is a
876 multi-line statement we need to skip over the continuation lines.
877 On a comment line, go to end of line."
879 (while (let (comment)
880 ;; Move past any enclosing strings and sexps, or stop if
881 ;; we're in a comment.
882 (while (let ((s (syntax-ppss)))
883 (cond ((eq 'comment
(syntax-ppss-context s
))
886 ((eq 'string
(syntax-ppss-context s
))
887 ;; 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 (error (end-of-line))))
892 ((python-skip-out t s
))))
895 (eq ?
\\ (char-before)))) ; Line continued?
896 (end-of-line 2)) ; Try next line.
899 (defun python-previous-statement (&optional count
)
900 "Go to start of previous statement.
901 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
902 Return count of statements left to move."
904 (unless count
(setq count
1))
906 (python-next-statement (- count
))
907 (python-beginning-of-statement)
908 (while (and (> count
0) (not (bobp)))
909 (python-skip-comments/blanks t
)
910 (python-beginning-of-statement)
911 (unless (bobp) (setq count
(1- count
))))
914 (defun python-next-statement (&optional count
)
915 "Go to start of next statement.
916 With argument COUNT, do it COUNT times. Stop at end of buffer.
917 Return count of statements left to move."
919 (unless count
(setq count
1))
921 (python-previous-statement (- count
))
923 (while (and (> count
0) (not (eobp)))
924 (python-end-of-statement)
925 (python-skip-comments/blanks
)
927 (setq count
(1- count
))))
930 (defun python-beginning-of-block (&optional arg
)
931 "Go to start of current block.
932 With numeric arg, do it that many times. If ARG is negative, call
933 `python-end-of-block' instead.
934 If point is on the first line of a block, use its outer block.
935 If current statement is in column zero, don't move and return nil.
936 Otherwise return non-nil."
938 (unless arg
(setq arg
1))
941 ((< arg
0) (python-end-of-block (- arg
)))
943 (let ((point (point)))
944 (if (or (python-comment-line-p)
945 (python-blank-line-p))
946 (python-skip-comments/blanks t
))
947 (python-beginning-of-statement)
948 (let ((ci (current-indentation)))
950 (not (goto-char point
)) ; return nil
951 ;; Look upwards for less indented statement.
953 ;;; This is slower than the below.
954 ;;; (while (zerop (python-previous-statement))
955 ;;; (when (and (< (current-indentation) ci)
956 ;;; (python-open-block-statement-p t))
957 ;;; (beginning-of-line)
958 ;;; (throw 'done t)))
959 (while (and (zerop (forward-line -
1)))
960 (when (and (< (current-indentation) ci
)
961 (not (python-comment-line-p))
962 ;; Move to beginning to save effort in case
963 ;; this is in string.
964 (progn (python-beginning-of-statement) t
)
965 (python-open-block-statement-p t
))
968 (not (goto-char point
))) ; Failed -- return nil
969 (python-beginning-of-block (1- arg
)))))))))
971 (defun python-end-of-block (&optional arg
)
972 "Go to end of current block.
973 With numeric arg, do it that many times. If ARG is negative,
974 call `python-beginning-of-block' instead.
975 If current statement is in column zero and doesn't open a block,
976 don't move and return nil. Otherwise return t."
978 (unless arg
(setq arg
1))
980 (python-beginning-of-block (- arg
))
981 (while (and (> arg
0)
982 (let* ((point (point))
983 (_ (if (python-comment-line-p)
984 (python-skip-comments/blanks t
)))
985 (ci (current-indentation))
986 (open (python-open-block-statement-p))
988 (if (and (zerop ci
) (not open
))
989 (not (goto-char point
))
991 (setq opoint
(point))
992 (while (and (zerop (python-next-statement))
993 (not (= opoint
(point))))
994 (setq opoint
(point))
995 (when (or (and open
(<= (current-indentation) ci
))
996 (< (current-indentation) ci
))
997 (python-skip-comments/blanks t
)
998 (beginning-of-line 2)
999 (throw 'done t
)))))))
1000 (setq arg
(1- arg
)))
1005 (defvar python-recursing
)
1006 (defun python-imenu-create-index ()
1007 "`imenu-create-index-function' for Python.
1009 Makes nested Imenu menus from nested `class' and `def' statements.
1010 The nested menus are headed by an item referencing the outer
1011 definition; it has a space prepended to the name so that it sorts
1012 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1014 (unless (boundp 'python-recursing
) ; dynamically bound below
1015 ;; Normal call from Imenu.
1016 (goto-char (point-min))
1017 ;; Without this, we can get an infloop if the buffer isn't all
1018 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1019 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1020 ;; what's going on, but it must be something to do with timers in
1022 ;; This can't be right, especially not when jit-lock is not used. --Stef
1023 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1024 ;; (font-lock-fontify-region (point-min) (point-max)))
1026 (let (index-alist) ; accumulated value to return
1027 (while (re-search-forward
1028 (rx line-start
(0+ space
) ; leading space
1029 (or (group "def") (group "class")) ; type
1030 (1+ space
) (group (1+ (or word ?_
)))) ; name
1032 (unless (python-in-string/comment
)
1033 (let ((pos (match-beginning 0))
1034 (name (match-string-no-properties 3)))
1035 (if (match-beginning 2) ; def or class?
1036 (setq name
(concat "class " name
)))
1039 (let* ((python-recursing t
)
1040 (sublist (python-imenu-create-index)))
1042 (progn (push (cons (concat " " name
) pos
) sublist
)
1043 (push (cons name sublist
) index-alist
))
1044 (push (cons name pos
) index-alist
)))))))
1045 (unless (boundp 'python-recursing
)
1046 ;; Look for module variables.
1048 (goto-char (point-min))
1049 (while (re-search-forward
1050 (rx line-start
(group (1+ (or word ?_
))) (0+ space
) "=")
1052 (unless (python-in-string/comment
)
1053 (push (cons (match-string 1) (match-beginning 1))
1055 (setq index-alist
(nreverse index-alist
))
1057 (push (cons "Module variables"
1062 ;;;; `Electric' commands.
1064 (defun python-electric-colon (arg)
1065 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1066 With numeric ARG, just insert that many colons. With \\[universal-argument],
1067 just insert a single colon."
1069 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1073 (not (python-in-string/comment
))
1074 (> (current-indentation) (python-calculate-indentation))
1075 (python-indent-line))) ; OK, do it
1076 (put 'python-electric-colon
'delete-selection t
)
1078 (defun python-backspace (arg)
1079 "Maybe delete a level of indentation on the current line.
1080 Do so if point is at the end of the line's indentation outside
1081 strings and comments.
1082 Otherwise just call `backward-delete-char-untabify'.
1085 (if (or (/= (current-indentation) (current-column))
1087 (python-continuation-line-p)
1088 (python-in-string/comment
))
1089 (backward-delete-char-untabify arg
)
1090 ;; Look for the largest valid indentation which is smaller than
1091 ;; the current indentation.
1093 (ci (current-indentation))
1094 (indents (python-indentation-levels))
1098 (setq indent
(max indent
(car x
)))))
1099 (setq initial
(cdr (assq indent indents
)))
1100 (if (> (length initial
) 0)
1101 (message "Closes %s" initial
))
1102 (delete-horizontal-space)
1103 (indent-to indent
))))
1104 (put 'python-backspace
'delete-selection
'supersede
)
1108 (defcustom python-check-command
"pychecker --stdlib"
1109 "Command used to check a Python file."
1113 (defvar python-saved-check-command nil
1116 ;; After `sgml-validate-command'.
1117 (defun python-check (command)
1118 "Check a Python file (default current buffer's file).
1119 Runs COMMAND, a shell command, as if by `compile'.
1120 See `python-check-command' for the default."
1122 (list (read-string "Checker command: "
1123 (or python-saved-check-command
1124 (concat python-check-command
" "
1125 (let ((name (buffer-file-name)))
1127 (file-name-nondirectory name
))))))))
1128 (setq python-saved-check-command command
)
1129 (require 'compile
) ;To define compilation-* variables.
1130 (save-some-buffers (not compilation-ask-about-save
) nil
)
1131 (let ((compilation-error-regexp-alist
1132 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1133 compilation-error-regexp-alist
)))
1134 (compilation-start command
)))
1136 ;;;; Inferior mode stuff (following cmuscheme).
1138 ;; Fixme: Make sure we can work with IPython.
1140 (defcustom python-python-command
"python"
1141 "Shell command to run Python interpreter.
1142 Any arguments can't contain whitespace.
1143 Note that IPython may not work properly; it must at least be used
1144 with the `-cl' flag, i.e. use `ipython -cl'."
1148 (defcustom python-jython-command
"jython"
1149 "Shell command to run Jython interpreter.
1150 Any arguments can't contain whitespace."
1154 (defvar python-command python-python-command
1155 "Actual command used to run Python.
1156 May be `python-python-command' or `python-jython-command', possibly
1157 modified by the user. Additional arguments are added when the command
1158 is used by `run-python' et al.")
1160 (defvar python-buffer nil
1161 "*The current Python process buffer.
1163 Commands that send text from source buffers to Python processes have
1164 to choose a process to send to. This is determined by buffer-local
1165 value of `python-buffer'. If its value in the current buffer,
1166 i.e. both any local value and the default one, is nil, `run-python'
1167 and commands that send to the Python process will start a new process.
1169 Whenever \\[run-python] starts a new process, it resets the default
1170 value of `python-buffer' to be the new process's buffer and sets the
1171 buffer-local value similarly if the current buffer is in Python mode
1172 or Inferior Python mode, so that source buffer stays associated with a
1173 specific sub-process.
1175 Use \\[python-set-proc] to set the default value from a buffer with a
1177 (make-variable-buffer-local 'python-buffer
)
1179 (defconst python-compilation-regexp-alist
1180 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1181 ;; The first already is (for CAML), but the second isn't. Anyhow,
1182 ;; these are specific to the inferior buffer. -- fx
1183 `((,(rx line-start
(1+ (any " \t")) "File \""
1184 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1185 "\", line " (group (1+ digit
)))
1187 (,(rx " in file " (group (1+ not-newline
)) " on line "
1191 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1192 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1194 "`compilation-error-regexp-alist' for inferior Python.")
1196 (defvar inferior-python-mode-map
1197 (let ((map (make-sparse-keymap)))
1198 ;; This will inherit from comint-mode-map.
1199 (define-key map
"\C-c\C-l" 'python-load-file
)
1200 (define-key map
"\C-c\C-v" 'python-check
)
1201 ;; Note that we _can_ still use these commands which send to the
1202 ;; Python process even at the prompt iff we have a normal prompt,
1203 ;; i.e. '>>> ' and not '... '. See the comment before
1204 ;; python-send-region. Fixme: uncomment these if we address that.
1206 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1207 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1210 (defvar inferior-python-mode-syntax-table
1211 (let ((st (make-syntax-table python-mode-syntax-table
)))
1212 ;; Don't get confused by apostrophes in the process's output (e.g. if
1213 ;; you execute "help(os)").
1214 (modify-syntax-entry ?
\' "." st
)
1215 ;; Maybe we should do the same for double quotes?
1216 ;; (modify-syntax-entry ?\" "." st)
1219 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1220 ;; not sure how much: at least some keybindings, like C-c C-f;
1221 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1222 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1223 "Major mode for interacting with an inferior Python process.
1224 A Python process can be started with \\[run-python].
1226 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1229 You can send text to the inferior Python process from other buffers
1230 containing Python source.
1231 * \\[python-switch-to-python] switches the current buffer to the Python
1233 * \\[python-send-region] sends the current region to the Python process.
1234 * \\[python-send-region-and-go] switches to the Python process buffer
1235 after sending the text.
1236 For running multiple processes in multiple buffers, see `run-python' and
1239 \\{inferior-python-mode-map}"
1241 (setq mode-line-process
'(":%s"))
1242 (set (make-local-variable 'comint-input-filter
) 'python-input-filter
)
1243 (add-hook 'comint-preoutput-filter-functions
#'python-preoutput-filter
1245 ;; Still required by `comint-redirect-send-command', for instance
1246 ;; (and we need to match things like `>>> ... >>> '):
1247 (set (make-local-variable 'comint-prompt-regexp
)
1248 (rx line-start
(1+ (and (or (repeat 3 (any ">.")) "(Pdb)") " "))))
1249 (set (make-local-variable 'compilation-error-regexp-alist
)
1250 python-compilation-regexp-alist
)
1251 (compilation-shell-minor-mode 1))
1253 (defcustom inferior-python-filter-regexp
"\\`\\s-*\\S-?\\S-?\\s-*\\'"
1254 "Input matching this regexp is not saved on the history list.
1255 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1259 (defun python-input-filter (str)
1260 "`comint-input-filter' function for inferior Python.
1261 Don't save anything for STR matching `inferior-python-filter-regexp'."
1262 (not (string-match inferior-python-filter-regexp str
)))
1264 ;; Fixme: Loses with quoted whitespace.
1265 (defun python-args-to-list (string)
1266 (let ((where (string-match "[ \t]" string
)))
1267 (cond ((null where
) (list string
))
1269 (cons (substring string
0 where
)
1270 (python-args-to-list (substring string
(+ 1 where
)))))
1271 (t (let ((pos (string-match "[^ \t]" string
)))
1272 (if pos
(python-args-to-list (substring string pos
))))))))
1274 (defvar python-preoutput-result nil
1275 "Data from last `_emacs_out' line seen by the preoutput filter.")
1277 (defvar python-preoutput-leftover nil
)
1278 (defvar python-preoutput-skip-next-prompt nil
)
1280 ;; Using this stops us getting lines in the buffer like
1282 (defun python-preoutput-filter (s)
1283 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1284 (when python-preoutput-leftover
1285 (setq s
(concat python-preoutput-leftover s
))
1286 (setq python-preoutput-leftover nil
))
1289 ;; First process whole lines.
1290 (while (string-match "\n" s start
)
1291 (let ((line (substring s start
(setq start
(match-end 0)))))
1292 ;; Skip prompt if needed.
1293 (when (and python-preoutput-skip-next-prompt
1294 (string-match comint-prompt-regexp line
))
1295 (setq python-preoutput-skip-next-prompt nil
)
1296 (setq line
(substring line
(match-end 0))))
1297 ;; Recognize special _emacs_out lines.
1298 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line
)
1299 (local-variable-p 'python-preoutput-result
))
1301 (setq python-preoutput-result
(match-string 1 line
))
1302 (set (make-local-variable 'python-preoutput-skip-next-prompt
) t
))
1303 (setq res
(concat res line
)))))
1304 ;; Then process the remaining partial line.
1305 (unless (zerop start
) (setq s
(substring s start
)))
1306 (cond ((and (string-match comint-prompt-regexp s
)
1307 ;; Drop this prompt if it follows an _emacs_out...
1308 (or python-preoutput-skip-next-prompt
1309 ;; ... or if it's not gonna be inserted at BOL.
1310 ;; Maybe we could be more selective here.
1311 (if (zerop (length res
))
1313 (string-match ".\\'" res
))))
1314 ;; The need for this seems to be system-dependent:
1315 ;; What is this all about, exactly? --Stef
1316 ;; (if (and (eq ?. (aref s 0)))
1317 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1318 (setq python-preoutput-skip-next-prompt nil
)
1320 ((let ((end (min (length "_emacs_out ") (length s
))))
1321 (eq t
(compare-strings s nil end
"_emacs_out " nil end
)))
1322 ;; The leftover string is a prefix of _emacs_out so we don't know
1323 ;; yet whether it's an _emacs_out or something else: wait until we
1324 ;; get more output so we can resolve this ambiguity.
1325 (set (make-local-variable 'python-preoutput-leftover
) s
)
1327 (t (concat res s
)))))
1329 (autoload 'comint-check-proc
"comint")
1332 (defun run-python (&optional cmd noshow new
)
1333 "Run an inferior Python process, input and output via buffer *Python*.
1334 CMD is the Python command to run. NOSHOW non-nil means don't show the
1335 buffer automatically.
1337 Normally, if there is a process already running in `python-buffer',
1338 switch to that buffer. Interactively, a prefix arg allows you to edit
1339 the initial command line (default is `python-command'); `-i' etc. args
1340 will be added to this as appropriate. A new process is started if:
1341 one isn't running attached to `python-buffer', or interactively the
1342 default `python-command', or argument NEW is non-nil. See also the
1343 documentation for `python-buffer'.
1345 Runs the hook `inferior-python-mode-hook' \(after the
1346 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1347 buffer for a list of commands.)"
1348 (interactive (if current-prefix-arg
1349 (list (read-string "Run Python: " python-command
) nil t
)
1350 (list python-command
)))
1351 (unless cmd
(setq cmd python-python-command
))
1352 (setq python-command cmd
)
1353 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1354 ;; (not a name) in Python buffers from which `run-python' &c is
1355 ;; invoked. Would support multiple processes better.
1356 (when (or new
(not (comint-check-proc python-buffer
)))
1357 (with-current-buffer
1358 (let* ((cmdlist (append (python-args-to-list cmd
) '("-i")))
1359 (path (getenv "PYTHONPATH"))
1360 (process-environment ; to import emacs.py
1361 (cons (concat "PYTHONPATH=" data-directory
1362 (if path
(concat path-separator path
)))
1363 process-environment
)))
1364 (apply 'make-comint-in-buffer
"Python"
1365 (if new
(generate-new-buffer "*Python*") "*Python*")
1366 (car cmdlist
) nil
(cdr cmdlist
)))
1367 (setq-default python-buffer
(current-buffer))
1368 (setq python-buffer
(current-buffer))
1369 (accept-process-output (get-buffer-process python-buffer
) 5)
1370 (inferior-python-mode)
1371 ;; Load function definitions we need.
1372 ;; Before the preoutput function was used, this was done via -c in
1373 ;; cmdlist, but that loses the banner and doesn't run the startup
1374 ;; file. The code might be inline here, but there's enough that it
1375 ;; seems worth putting in a separate file, and it's probably cleaner
1376 ;; to put it in a module.
1377 ;; Ensure we're at a prompt before doing anything else.
1378 (python-send-receive "import emacs; print '_emacs_out ()'")))
1379 (if (derived-mode-p 'python-mode
)
1380 (setq python-buffer
(default-value 'python-buffer
))) ; buffer-local
1381 ;; Without this, help output goes into the inferior python buffer if
1382 ;; the process isn't already running.
1383 (sit-for 1 t
) ;Should we use accept-process-output instead? --Stef
1384 (unless noshow
(pop-to-buffer python-buffer t
)))
1386 ;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1387 ;; e.g. prompt is `help> '. Probably raise an error if the form of
1388 ;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1389 ;; `... ', i.e. we're not inputting a block &c. However, this may not
1390 ;; be the place to check it, e.g. we might actually want to send
1391 ;; commands having set up such a state.
1393 (defun python-send-command (command)
1394 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1395 COMMAND should be a single statement."
1396 ;; (assert (not (string-match "\n" command)))
1397 ;; (let ((end (marker-position (process-mark (python-proc)))))
1398 (with-current-buffer (process-buffer (python-proc))
1399 (goto-char (point-max))
1400 (compilation-forget-errors)
1401 (python-send-string command
)
1402 (setq compilation-last-buffer
(current-buffer)))
1403 ;; No idea what this is for but it breaks the call to
1404 ;; compilation-fake-loc in python-send-region. -- Stef
1405 ;; Must wait until this has completed before re-setting variables below.
1406 ;; (python-send-receive "print '_emacs_out ()'")
1407 ;; (with-current-buffer python-buffer
1408 ;; (set-marker compilation-parsing-end end))
1411 (defun python-send-region (start end
)
1412 "Send the region to the inferior Python process."
1413 ;; The region is evaluated from a temporary file. This avoids
1414 ;; problems with blank lines, which have different semantics
1415 ;; interactively and in files. It also saves the inferior process
1416 ;; buffer filling up with interpreter prompts. We need a Python
1417 ;; function to remove the temporary file when it has been evaluated
1418 ;; (though we could probably do it in Lisp with a Comint output
1419 ;; filter). This function also catches exceptions and truncates
1420 ;; tracebacks not to mention the frame of the function itself.
1422 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1423 ;; the reference to the temporary file to the source.
1425 ;; Fixme: Write a `coding' header to the temp file if the region is
1428 (let* ((f (make-temp-file "py"))
1429 (command (format "emacs.eexecfile(%S)" f
))
1430 (orig-start (copy-marker start
)))
1431 (when (save-excursion
1433 (/= 0 (current-indentation))) ; need dummy block
1435 (goto-char orig-start
)
1436 ;; Wrong if we had indented code at buffer start.
1437 (set-marker orig-start
(line-beginning-position 0)))
1438 (write-region "if True:\n" nil f nil
'nomsg
))
1439 (write-region start end f t
'nomsg
)
1440 (python-send-command command
)
1441 (with-current-buffer (process-buffer (python-proc))
1442 ;; Tell compile.el to redirect error locations in file `f' to
1443 ;; positions past marker `orig-start'. It has to be done *after*
1444 ;; `python-send-command''s call to `compilation-forget-errors'.
1445 (compilation-fake-loc orig-start f
))))
1447 (defun python-send-string (string)
1448 "Evaluate STRING in inferior Python process."
1449 (interactive "sPython command: ")
1450 (comint-send-string (python-proc) string
)
1451 (unless (string-match "\n\\'" string
)
1452 ;; Make sure the text is properly LF-terminated.
1453 (comint-send-string (python-proc) "\n"))
1454 (when (string-match "\n[ \t].*\n?\\'" string
)
1455 ;; If the string contains a final indented line, add a second newline so
1456 ;; as to make sure we terminate the multiline instruction.
1457 (comint-send-string (python-proc) "\n")))
1459 (defun python-send-buffer ()
1460 "Send the current buffer to the inferior Python process."
1462 (python-send-region (point-min) (point-max)))
1464 ;; Fixme: Try to define the function or class within the relevant
1465 ;; module, not just at top level.
1466 (defun python-send-defun ()
1467 "Send the current defun (class or method) to the inferior Python process."
1469 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1470 (progn (end-of-defun) (point)))))
1472 (defun python-switch-to-python (eob-p)
1473 "Switch to the Python process buffer, maybe starting new process.
1474 With prefix arg, position cursor at end of buffer."
1476 (pop-to-buffer (process-buffer (python-proc)) t
) ;Runs python if needed.
1479 (goto-char (point-max))))
1481 (defun python-send-region-and-go (start end
)
1482 "Send the region to the inferior Python process.
1483 Then switch to the process buffer."
1485 (python-send-region start end
)
1486 (python-switch-to-python t
))
1488 (defcustom python-source-modes
'(python-mode jython-mode
)
1489 "Used to determine if a buffer contains Python source code.
1490 If a file is loaded into a buffer that is in one of these major modes,
1491 it is considered Python source by `python-load-file', which uses the
1492 value to determine defaults."
1493 :type
'(repeat function
)
1496 (defvar python-prev-dir
/file nil
1497 "Caches (directory . file) pair used in the last `python-load-file' command.
1498 Used for determining the default in the next one.")
1500 (autoload 'comint-get-source
"comint")
1502 (defun python-load-file (file-name)
1503 "Load a Python file FILE-NAME into the inferior Python process.
1504 If the file has extension `.py' import or reload it as a module.
1505 Treating it as a module keeps the global namespace clean, provides
1506 function location information for debugging, and supports users of
1507 module-qualified names."
1508 (interactive (comint-get-source "Load Python file: " python-prev-dir
/file
1510 t
)) ; because execfile needs exact name
1511 (comint-check-source file-name
) ; Check to see if buffer needs saving.
1512 (setq python-prev-dir
/file
(cons (file-name-directory file-name
)
1513 (file-name-nondirectory file-name
)))
1514 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1515 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1516 (python-send-command
1517 (if (string-match "\\.py\\'" file-name
)
1518 (let ((module (file-name-sans-extension
1519 (file-name-nondirectory file-name
))))
1520 (format "emacs.eimport(%S,%S)"
1521 module
(file-name-directory file-name
)))
1522 (format "execfile(%S)" file-name
)))
1523 (message "%s loaded" file-name
)))
1525 (defun python-proc ()
1526 "Return the current Python process.
1527 See variable `python-buffer'. Starts a new process if necessary."
1528 ;; Fixme: Maybe should look for another active process if there
1529 ;; isn't one for `python-buffer'.
1530 (unless (comint-check-proc python-buffer
)
1532 (get-buffer-process (if (derived-mode-p 'inferior-python-mode
)
1536 (defun python-set-proc ()
1537 "Set the default value of `python-buffer' to correspond to this buffer.
1538 If the current buffer has a local value of `python-buffer', set the
1539 default (global) value to that. The associated Python process is
1540 the one that gets input from \\[python-send-region] et al when used
1541 in a buffer that doesn't have a local value of `python-buffer'."
1543 (if (local-variable-p 'python-buffer
)
1544 (setq-default python-buffer python-buffer
)
1545 (error "No local value of `python-buffer'")))
1547 ;;;; Context-sensitive help.
1549 (defconst python-dotty-syntax-table
1550 (let ((table (make-syntax-table)))
1551 (set-char-table-parent table python-mode-syntax-table
)
1552 (modify-syntax-entry ?.
"_" table
)
1554 "Syntax table giving `.' symbol syntax.
1555 Otherwise inherits from `python-mode-syntax-table'.")
1557 (defvar view-return-to-alist
)
1558 (eval-when-compile (autoload 'help-buffer
"help-fns"))
1560 (defvar python-imports
) ; forward declaration
1562 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1563 ;; bound to C-h S? [Probably not, since info-look may work in cases
1564 ;; where this doesn't.]
1565 (defun python-describe-symbol (symbol)
1566 "Get help on SYMBOL using `help'.
1567 Interactively, prompt for symbol.
1569 Symbol may be anything recognized by the interpreter's `help'
1570 command -- e.g. `CALLS' -- not just variables in scope in the
1571 interpreter. This only works for Python version 2.2 or newer
1572 since earlier interpreters don't support `help'.
1574 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1576 ;; Note that we do this in the inferior process, not a separate one, to
1577 ;; ensure the environment is appropriate.
1579 (let ((symbol (with-syntax-table python-dotty-syntax-table
1581 (enable-recursive-minibuffers t
))
1582 (list (read-string (if symbol
1583 (format "Describe symbol (default %s): " symbol
)
1584 "Describe symbol: ")
1586 (if (equal symbol
"") (error "No symbol"))
1587 ;; Ensure we have a suitable help buffer.
1588 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1589 ;; allow C-c C-f in help buffer.
1590 (let ((temp-buffer-show-hook ; avoid xref stuff
1592 (toggle-read-only 1)
1593 (setq view-return-to-alist
1594 (list (cons (selected-window) help-return-method
))))))
1595 (with-output-to-temp-buffer (help-buffer)
1596 (with-current-buffer standard-output
1597 ;; Fixme: Is this actually useful?
1598 (help-setup-xref (list 'python-describe-symbol symbol
) (interactive-p))
1599 (set (make-local-variable 'comint-redirect-subvert-readonly
) t
)
1600 (print-help-return-message))))
1601 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1602 symbol python-imports
)
1603 "*Help*" (python-proc) nil nil
))
1605 (add-to-list 'debug-ignored-errors
"^No symbol")
1607 (defun python-send-receive (string)
1608 "Send STRING to inferior Python (if any) and return result.
1609 The result is what follows `_emacs_out' in the output."
1610 (python-send-string string
)
1611 (let ((proc (python-proc)))
1612 (with-current-buffer (process-buffer proc
)
1613 (set (make-local-variable 'python-preoutput-result
) nil
)
1615 (accept-process-output proc
5)
1616 (null python-preoutput-result
)))
1617 (prog1 python-preoutput-result
1618 (kill-local-variable 'python-preoutput-result
)))))
1620 ;; Fixme: Is there anything reasonable we can do with random methods?
1621 ;; (Currently only works with functions.)
1622 (defun python-eldoc-function ()
1623 "`eldoc-documentation-function' for Python.
1624 Only works when point is in a function name, not its arg list, for
1625 instance. Assumes an inferior Python is running."
1626 (let ((symbol (with-syntax-table python-dotty-syntax-table
1628 ;; This is run from timers, so inhibit-quit tends to be set.
1630 ;; First try the symbol we're on.
1632 (python-send-receive (format "emacs.eargs(%S, %s)"
1633 symbol python-imports
)))
1634 ;; Try moving to symbol before enclosing parens.
1635 (let ((s (syntax-ppss)))
1636 (unless (zerop (car s
))
1637 (when (eq ?\
( (char-after (nth 1 s
)))
1639 (goto-char (nth 1 s
))
1640 (skip-syntax-backward "-")
1641 (let ((point (point)))
1642 (skip-chars-backward "a-zA-Z._")
1643 (if (< (point) point
)
1644 (python-send-receive
1645 (format "emacs.eargs(%S, %s)"
1646 (buffer-substring-no-properties (point) point
)
1647 python-imports
))))))))))))
1649 ;;;; Info-look functionality.
1651 (defun python-after-info-look ()
1652 "Set up info-look for Python.
1653 Used with `eval-after-load'."
1654 (let* ((version (let ((s (shell-command-to-string (concat python-command
1656 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s
)
1657 (match-string 1 s
)))
1658 ;; Whether info files have a Python version suffix, e.g. in Debian.
1661 (with-no-warnings (Info-mode))
1663 ;; Don't use `info' because it would pop-up a *info* buffer.
1665 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1669 (info-lookup-maybe-add-help
1671 :regexp
"[[:alnum:]_]+"
1673 ;; Fixme: Can this reasonably be made specific to indices with
1674 ;; different rules? Is the order of indices optimal?
1675 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1678 ;; The empty prefix just gets us highlighted terms.
1679 `((,(concat "(python" version
"-ref)Miscellaneous Index") nil
"")
1680 (,(concat "(python" version
"-ref)Module Index" nil
""))
1681 (,(concat "(python" version
"-ref)Function-Method-Variable Index"
1683 (,(concat "(python" version
"-ref)Class-Exception-Object Index"
1685 (,(concat "(python" version
"-lib)Module Index" nil
""))
1686 (,(concat "(python" version
"-lib)Class-Exception-Object Index"
1688 (,(concat "(python" version
"-lib)Function-Method-Variable Index"
1690 (,(concat "(python" version
"-lib)Miscellaneous Index" nil
"")))
1691 '(("(python-ref)Miscellaneous Index" nil
"")
1692 ("(python-ref)Module Index" nil
"")
1693 ("(python-ref)Function-Method-Variable Index" nil
"")
1694 ("(python-ref)Class-Exception-Object Index" nil
"")
1695 ("(python-lib)Module Index" nil
"")
1696 ("(python-lib)Class-Exception-Object Index" nil
"")
1697 ("(python-lib)Function-Method-Variable Index" nil
"")
1698 ("(python-lib)Miscellaneous Index" nil
""))))))
1699 (eval-after-load "info-look" '(python-after-info-look))
1703 (defcustom python-jython-packages
'("java" "javax" "org" "com")
1704 "Packages implying `jython-mode'.
1705 If these are imported near the beginning of the buffer, `python-mode'
1706 actually punts to `jython-mode'."
1707 :type
'(repeat string
)
1710 ;; Called from `python-mode', this causes a recursive call of the
1711 ;; mode. See logic there to break out of the recursion.
1712 (defun python-maybe-jython ()
1713 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1714 The criterion is either a match for `jython-mode' via
1715 `interpreter-mode-alist' or an import of a module from the list
1716 `python-jython-packages'."
1717 ;; The logic is taken from python-mode.el.
1721 (goto-char (point-min))
1722 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp
)
1724 (if (and interpreter
(eq 'jython-mode
1725 (cdr (assoc (file-name-nondirectory
1727 interpreter-mode-alist
))))
1730 (while (re-search-forward
1731 (rx line-start
(or "import" "from") (1+ space
)
1732 (group (1+ (not (any " \t\n.")))))
1733 (+ (point-min) 10000) ; Probably not worth customizing.
1735 (if (member (match-string 1) python-jython-packages
)
1739 (defun python-fill-paragraph (&optional justify
)
1740 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1741 If any of the current line is in or at the end of a multi-line string,
1742 fill the string or the paragraph of it that point is in, preserving
1743 the strings's indentation."
1745 (or (fill-comment-paragraph justify
)
1748 (let* ((syntax (syntax-ppss))
1751 (cond ((nth 4 syntax
) ; comment. fixme: loses with trailing one
1752 (let (fill-paragraph-function)
1753 (fill-paragraph justify
)))
1754 ;; The `paragraph-start' and `paragraph-separate'
1755 ;; variables don't allow us to delimit the last
1756 ;; paragraph in a multi-line string properly, so narrow
1757 ;; to the string and then fill around (the end of) the
1759 ((eq t
(nth 3 syntax
)) ; in fenced string
1760 (goto-char (nth 8 syntax
)) ; string start
1761 (setq start
(line-beginning-position))
1762 (setq end
(condition-case () ; for unbalanced quotes
1763 (progn (forward-sexp)
1765 (error (point-max)))))
1766 ((re-search-backward "\\s|\\s-*\\=" nil t
) ; end of fenced string
1770 (progn (backward-sexp)
1771 (setq start
(line-beginning-position)))
1775 (narrow-to-region start end
)
1777 ;; Avoid losing leading and trailing newlines in doc
1778 ;; strings written like:
1782 (let* ((paragraph-separate
1783 (concat ".*\\s|\"\"$" ; newline after opening quotes
1784 "\\|\\(?:" paragraph-separate
"\\)"))
1786 (concat ".*\\s|\"\"[ \t]*[^ \t].*" ; not newline after
1788 "\\|\\(?:" paragraph-separate
"\\)"))
1789 (fill-paragraph-function))
1790 (fill-paragraph justify
))))))) t
)
1792 (defun python-shift-left (start end
&optional count
)
1793 "Shift lines in region COUNT (the prefix arg) columns to the left.
1794 COUNT defaults to `python-indent'. If region isn't active, just shift
1795 current line. The region shifted includes the lines in which START and
1796 END lie. It is an error if any lines in the region are indented less than
1798 (interactive (if mark-active
1799 (list (region-beginning) (region-end) current-prefix-arg
)
1800 (list (point) (point) current-prefix-arg
)))
1802 (setq count
(prefix-numeric-value count
))
1803 (setq count python-indent
))
1807 (while (< (point) end
)
1808 (if (and (< (current-indentation) count
)
1809 (not (looking-at "[ \t]*$")))
1810 (error "Can't shift all lines enough"))
1812 (indent-rigidly start end
(- count
)))))
1814 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1816 (defun python-shift-right (start end
&optional count
)
1817 "Shift lines in region COUNT (the prefix arg) columns to the right.
1818 COUNT defaults to `python-indent'. If region isn't active, just shift
1819 current line. The region shifted includes the lines in which START and
1821 (interactive (if mark-active
1822 (list (region-beginning) (region-end) current-prefix-arg
)
1823 (list (point) (point) current-prefix-arg
)))
1825 (setq count
(prefix-numeric-value count
))
1826 (setq count python-indent
))
1827 (indent-rigidly start end count
))
1829 (defun python-outline-level ()
1830 "`outline-level' function for Python mode.
1831 The level is the number of `python-indent' steps of indentation
1833 (1+ (/ (current-indentation) python-indent
)))
1835 ;; Fixme: Consider top-level assignments, imports, &c.
1836 (defun python-current-defun ()
1837 "`add-log-current-defun-function' for Python."
1839 ;; Move up the tree of nested `class' and `def' blocks until we
1840 ;; get to zero indentation, accumulating the defined names.
1843 (while (or start
(> (current-indentation) 0))
1845 (python-beginning-of-block)
1847 (beginning-of-defun)
1848 (if (looking-at (rx (0+ space
) (or "def" "class") (1+ space
)
1849 (group (1+ (or word
(syntax symbol
))))))
1850 (push (match-string 1) accum
)))
1851 (if accum
(mapconcat 'identity accum
".")))))
1853 (defun python-mark-block ()
1854 "Mark the block around point.
1855 Uses `python-beginning-of-block', `python-end-of-block'."
1858 (python-beginning-of-block)
1859 (push-mark (point) nil t
)
1860 (python-end-of-block)
1861 (exchange-point-and-mark))
1863 ;; Fixme: Provide a find-function-like command to find source of a
1864 ;; definition (separate from BicycleRepairMan). Complicated by
1865 ;; finding the right qualified name.
1869 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
1870 (defvar python-imports
"None"
1871 "String of top-level import statements updated by `python-find-imports'.")
1872 (make-variable-buffer-local 'python-imports
)
1874 ;; Fixme: Should font-lock try to run this when it deals with an import?
1875 ;; Maybe not a good idea if it gets run multiple times when the
1876 ;; statement is being edited, and is more likely to end up with
1877 ;; something syntactically incorrect.
1878 ;; However, what we should do is to trundle up the block tree from point
1879 ;; to extract imports that appear to be in scope, and add those.
1880 (defun python-find-imports ()
1881 "Find top-level imports, updating `python-imports'."
1885 (goto-char (point-min))
1886 (while (re-search-forward "^import\\>\\|^from\\>" nil t
)
1887 (unless (syntax-ppss-context (syntax-ppss))
1888 (let ((start (line-beginning-position)))
1889 ;; Skip over continued lines.
1890 (while (and (eq ?
\\ (char-before (line-end-position)))
1891 (= 0 (forward-line 1))))
1892 (push (buffer-substring start
(line-beginning-position 2))
1894 (setq python-imports
1897 ;; This is probably best left out since you're unlikely to need the
1898 ;; doc for a function in the buffer and the import will lose if the
1899 ;; Python sub-process' working directory isn't the same as the
1901 ;; (if buffer-file-name
1904 ;; (file-name-sans-extension
1905 ;; (file-name-nondirectory buffer-file-name))))
1909 (set-text-properties 0 (length python-imports
) nil python-imports
)
1910 ;; The output ends up in the wrong place if the string we
1911 ;; send contains newlines (from the imports).
1912 (setq python-imports
1913 (replace-regexp-in-string "\n" "\\n"
1914 (format "%S" python-imports
) t t
))))))
1916 ;; Fixme: This fails the first time if the sub-process isn't already
1917 ;; running. Presumably a timing issue with i/o to the process.
1918 (defun python-symbol-completions (symbol)
1919 "Return a list of completions of the string SYMBOL from Python process.
1921 Uses `python-imports' to load modules against which to complete."
1925 (car (read-from-string
1926 (python-send-receive
1927 (format "emacs.complete(%S,%s)" symbol python-imports
))))
1930 ;; We can get duplicates from the above -- don't know why.
1931 (delete-dups completions
)
1934 (defun python-partial-symbol ()
1935 "Return the partial symbol before point (for completion)."
1937 (start (save-excursion
1938 (and (re-search-backward
1939 (rx (or buffer-start
(regexp "[^[:alnum:]._]"))
1940 (group (1+ (regexp "[[:alnum:]._]"))) point
)
1942 (match-beginning 1)))))
1943 (if start
(buffer-substring-no-properties start end
))))
1945 (defun python-complete-symbol ()
1946 "Perform completion on the Python symbol preceding point.
1947 Repeating the command scrolls the completion window."
1949 (let ((window (get-buffer-window "*Completions*")))
1950 (if (and (eq last-command this-command
)
1951 window
(window-live-p window
) (window-buffer window
)
1952 (buffer-name (window-buffer window
)))
1953 (with-current-buffer (window-buffer window
)
1954 (if (pos-visible-in-window-p (point-max) window
)
1955 (set-window-start window
(point-min))
1956 (save-selected-window
1957 (select-window window
)
1960 (let* ((end (point))
1961 (symbol (python-partial-symbol))
1962 (completions (python-symbol-completions symbol
))
1963 (completion (if completions
1964 (try-completion symbol completions
))))
1966 (cond ((eq completion t
))
1968 (message "Can't find completion for \"%s\"" symbol
)
1970 ((not (string= symbol completion
))
1971 (delete-region (- end
(length symbol
)) end
)
1972 (insert completion
))
1974 (message "Making completion list...")
1975 (with-output-to-temp-buffer "*Completions*"
1976 (display-completion-list completions symbol
))
1977 (message "Making completion list...%s" "done"))))))))
1979 (defun python-try-complete (old)
1980 "Completion function for Python for use with `hippie-expand'."
1981 (when (derived-mode-p 'python-mode
) ; though we only add it locally
1983 (let ((symbol (python-partial-symbol)))
1984 (he-init-string (- (point) (length symbol
)) (point))
1985 (if (not (he-string-member he-search-string he-tried-table
))
1986 (push he-search-string he-tried-table
))
1987 (setq he-expand-list
1988 (and symbol
(python-symbol-completions symbol
)))))
1989 (while (and he-expand-list
1990 (he-string-member (car he-expand-list
) he-tried-table
))
1991 (pop he-expand-list
))
1994 (he-substitute-string (pop he-expand-list
))
1996 (if old
(he-reset-string))
2001 (defun python-module-path (module)
2002 "Function for `ffap-alist' to return path to MODULE."
2003 (python-send-receive (format "emacs.modpath (%S)" module
)))
2005 (eval-after-load "ffap"
2006 '(push '(python-mode . python-module-path
) ffap-alist
))
2010 (defcustom python-use-skeletons nil
2011 "Non-nil means template skeletons will be automagically inserted.
2012 This happens when pressing \"if<SPACE>\", for example, to prompt for
2017 (defvar python-skeletons nil
2018 "Alist of named skeletons for Python mode.
2019 Elements are of the form (NAME . EXPANDER-FUNCTION).")
2021 (defvar python-mode-abbrev-table nil
2022 "Abbrev table for Python mode.
2023 The default contents correspond to the elements of `python-skeletons'.")
2024 (define-abbrev-table 'python-mode-abbrev-table
())
2027 ;; Define a user-level skeleton and add it to `python-skeletons' and
2028 ;; the abbrev table.
2029 (defmacro def-python-skeleton
(name &rest elements
)
2030 (let* ((name (symbol-name name
))
2031 (function (intern (concat "python-insert-" name
))))
2033 (add-to-list 'python-skeletons
',(cons name function
))
2034 (if python-use-skeletons
2035 (define-abbrev python-mode-abbrev-table
,name
"" ',function nil t
))
2036 (define-skeleton ,function
2037 ,(format "Insert Python \"%s\" template." name
)
2039 (put 'def-python-skeleton
'lisp-indent-function
2)
2041 ;; From `skeleton-further-elements':
2042 ;; `<': outdent a level;
2043 ;; `^': delete indentation on current line and also previous newline.
2044 ;; Not quote like `delete-indentation'. Assumes point is at
2045 ;; beginning of indentation.
2047 (def-python-skeleton if
2051 ("other condition, %s: "
2052 < ; Avoid wrong indentation after block opening.
2057 (define-skeleton python-else
2058 "Auxiliary skeleton."
2060 (unless (eq ?y
(read-char "Add `else' clause? (y for yes or RET for no) "))
2065 (def-python-skeleton while
2071 (def-python-skeleton for
2073 "for " str
" in " (skeleton-read "Expression, %s: ") ":" \n
2077 (def-python-skeleton try
/except
2082 < "except " str
'(python-target) ":" \n
2088 (define-skeleton python-target
2089 "Auxiliary skeleton."
2090 "Target, %s: " ", " str | -
2)
2092 (def-python-skeleton try
/finally
2099 (def-python-skeleton def
2101 "def " str
" (" ("Parameter, %s: " (unless (equal ?\
( (char-before)) ", ")
2103 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2106 (def-python-skeleton class
2108 "class " str
" (" ("Inheritance, %s: "
2109 (unless (equal ?\
( (char-before)) ", ")
2111 & ")" | -
2 ; close list or remove opening
2113 "\"\"\"" @ " \"\"\"" \n
2116 (defvar python-default-template
"if"
2117 "Default template to expand by `python-expand-template'.
2118 Updated on each expansion.")
2120 (defun python-expand-template (name)
2121 "Expand template named NAME.
2122 Interactively, prompt for the name with completion."
2124 (list (completing-read (format "Template to expand (default %s): "
2125 python-default-template
)
2126 python-skeletons nil t
)))
2128 (setq name python-default-template
)
2129 (setq python-default-template name
))
2130 (let ((func (cdr (assoc name python-skeletons
))))
2133 (error "Undefined template: %s" name
))))
2135 ;;;; Bicycle Repair Man support
2137 (autoload 'pymacs-load
"pymacs" nil t
)
2138 (autoload 'brm-init
"bikemacs")
2140 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2141 ;; the way it modifies files outside Emacs... Also note that the
2142 ;; current BRM loses with tabs used for indentation -- I submitted a
2143 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2144 (defun python-setup-brm ()
2145 "Set up Bicycle Repair Man refactoring tool (if available).
2147 Note that the `refactoring' features change files independently of
2148 Emacs and may modify and save the contents of the current buffer
2149 without confirmation."
2151 (condition-case data
2152 (unless (fboundp 'brm-rename
)
2153 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2154 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2155 (features (cons 'python-mode features
))) ; and requires this
2156 (brm-init)) ; second line of normal recipe
2157 (remove-hook 'python-mode-hook
; undo this from `brm-init'
2158 '(lambda () (easy-menu-add brm-menu
)))
2160 python-brm-menu python-mode-map
2161 "Bicycle Repair Man"
2162 '("BicycleRepairMan"
2163 :help
"Interface to navigation and refactoring tool"
2165 ["Find References" brm-find-references
2166 :help
"Find references to name at point in compilation buffer"]
2167 ["Find Definition" brm-find-definition
2168 :help
"Find definition of name at point"]
2171 ["Rename" brm-rename
2172 :help
"Replace name at point with a new name everywhere"]
2173 ["Extract Method" brm-extract-method
2174 :active
(and mark-active
(not buffer-read-only
))
2175 :help
"Replace statements in region with a method"]
2176 ["Extract Local Variable" brm-extract-local-variable
2177 :active
(and mark-active
(not buffer-read-only
))
2178 :help
"Replace expression in region with an assignment"]
2179 ["Inline Local Variable" brm-inline-local-variable
2181 "Substitute uses of variable at point with its definition"]
2182 ;; Fixme: Should check for anything to revert.
2183 ["Undo Last Refactoring" brm-undo
:help
""])))
2184 (error (error "Bicyclerepairman setup failed: %s" data
))))
2188 (defvar outline-heading-end-regexp
)
2189 (defvar eldoc-documentation-function
)
2191 ;; Stuff to allow expanding abbrevs with non-word constituents.
2192 (defun python-abbrev-pc-hook ()
2193 "Set the syntax table before possibly expanding abbrevs."
2194 (remove-hook 'post-command-hook
'python-abbrev-pc-hook t
)
2195 (set-syntax-table python-mode-syntax-table
))
2197 (defvar python-abbrev-syntax-table
2198 (copy-syntax-table python-mode-syntax-table
)
2199 "Syntax table used when expanding abbrevs.")
2201 (defun python-pea-hook ()
2202 "Reset the syntax table after possibly expanding abbrevs."
2203 (set-syntax-table python-abbrev-syntax-table
)
2204 (add-hook 'post-command-hook
'python-abbrev-pc-hook nil t
))
2205 (modify-syntax-entry ?
/ "w" python-abbrev-syntax-table
)
2207 (defvar python-mode-running
) ;Dynamically scoped var.
2210 (define-derived-mode python-mode fundamental-mode
"Python"
2211 "Major mode for editing Python files.
2212 Font Lock mode is currently required for correct parsing of the source.
2213 See also `jython-mode', which is actually invoked if the buffer appears to
2214 contain Jython code. See also `run-python' and associated Python mode
2215 commands for running Python under Emacs.
2217 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2218 with nested `def' and `class' blocks. They take the innermost one as
2219 current without distinguishing method and class definitions. Used multiple
2220 times, they move over others at the same indentation level until they reach
2221 the end of definitions at that level, when they move up a level.
2223 Colon is electric: it outdents the line if appropriate, e.g. for
2224 an else statement. \\[python-backspace] at the beginning of an indented statement
2225 deletes a level of indentation to close the current block; otherwise it
2226 deletes a character backward. TAB indents the current line relative to
2227 the preceding code. Successive TABs, with no intervening command, cycle
2228 through the possibilities for indentation on the basis of enclosing blocks.
2230 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2231 effect outside them.
2233 Supports Eldoc mode (only for functions, using a Python process),
2234 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2235 lines count as headers. Symbol completion is available in the
2236 same way as in the Python shell using the `rlcompleter' module
2237 and this is added to the Hippie Expand functions locally if
2238 Hippie Expand mode is turned on. Completion of symbols of the
2239 form x.y only works if the components are literal
2240 module/attribute names, not variables. An abbrev table is set up
2241 with skeleton expansions for compound statement templates.
2243 \\{python-mode-map}"
2245 (set (make-local-variable 'font-lock-defaults
)
2246 '(python-font-lock-keywords nil nil nil nil
2247 (font-lock-syntactic-keywords
2248 . python-font-lock-syntactic-keywords
)
2249 ;; This probably isn't worth it.
2250 ;; (font-lock-syntactic-face-function
2251 ;; . python-font-lock-syntactic-face-function)
2253 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2254 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
2255 (set (make-local-variable 'comment-start
) "# ")
2256 (set (make-local-variable 'indent-line-function
) #'python-indent-line
)
2257 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2258 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2259 (set (make-local-variable 'fill-paragraph-function
) 'python-fill-paragraph
)
2260 (set (make-local-variable 'require-final-newline
) mode-require-final-newline
)
2261 (set (make-local-variable 'add-log-current-defun-function
)
2262 #'python-current-defun
)
2263 (set (make-local-variable 'outline-regexp
)
2264 (rx (* space
) (or "class" "def" "elif" "else" "except" "finally"
2265 "for" "if" "try" "while" "with")
2267 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
2268 (set (make-local-variable 'outline-level
) #'python-outline-level
)
2269 (set (make-local-variable 'open-paren-in-column-0-is-defun-start
) nil
)
2270 (make-local-variable 'python-saved-check-command
)
2271 (set (make-local-variable 'beginning-of-defun-function
)
2272 'python-beginning-of-defun
)
2273 (set (make-local-variable 'end-of-defun-function
) 'python-end-of-defun
)
2274 (setq imenu-create-index-function
#'python-imenu-create-index
)
2275 (set (make-local-variable 'eldoc-documentation-function
)
2276 #'python-eldoc-function
)
2277 (add-hook 'eldoc-mode-hook
2278 (lambda () (run-python nil t
)) ; need it running
2280 ;; Fixme: should be in hideshow. This seems to be of limited use
2281 ;; since it isn't (can't be) indentation-based. Also hide-level
2282 ;; doesn't seem to work properly.
2283 (add-to-list 'hs-special-modes-alist
2284 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
2286 (python-end-of-defun)
2287 (skip-chars-backward " \t\n"))
2289 (set (make-local-variable 'skeleton-further-elements
)
2290 '((< '(backward-delete-char-untabify (min python-indent
2292 (^
'(- (1+ (current-indentation))))))
2293 (add-hook 'pre-abbrev-expand-hook
'python-pea-hook nil t
)
2294 ;; Let's not mess with hippie-expand. Symbol-completion should rather be
2295 ;; bound to another key, since it has different performance requirements.
2296 ;; (if (featurep 'hippie-exp)
2297 ;; (set (make-local-variable 'hippie-expand-try-functions-list)
2298 ;; (cons 'python-try-complete hippie-expand-try-functions-list)))
2299 ;; Python defines TABs as being 8-char wide.
2300 (set (make-local-variable 'tab-width
) 8)
2301 (when python-guess-indent
(python-guess-indent))
2302 ;; Let's make it harder for the user to shoot himself in the foot.
2303 (unless (= tab-width python-indent
)
2304 (setq indent-tabs-mode nil
))
2305 (set (make-local-variable 'python-command
) python-python-command
)
2306 (python-find-imports)
2307 (unless (boundp 'python-mode-running
) ; kill the recursion from jython-mode
2308 (let ((python-mode-running t
))
2309 (python-maybe-jython))))
2311 (custom-add-option 'python-mode-hook
'imenu-add-menubar-index
)
2312 (custom-add-option 'python-mode-hook
2314 "Turn off Indent Tabs mode."
2315 (set (make-local-variable 'indent-tabs-mode
) nil
)))
2316 (custom-add-option 'python-mode-hook
'turn-on-eldoc-mode
)
2317 (custom-add-option 'python-mode-hook
'abbrev-mode
)
2318 (custom-add-option 'python-mode-hook
'python-setup-brm
)
2321 (define-derived-mode jython-mode python-mode
"Jython"
2322 "Major mode for editing Jython files.
2323 Like `python-mode', but sets up parameters for Jython subprocesses.
2324 Runs `jython-mode-hook' after `python-mode-hook'."
2326 (set (make-local-variable 'python-command
) python-jython-command
))
2329 (provide 'python-21
)
2330 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2331 ;;; python.el ends here