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