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