* hl-line.el (hl-line): New face.
[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
72 (autoload 'comint-mode "comint")
73
74 (defgroup python nil
75 "Silly walks in the Python language."
76 :group 'languages
77 :version "22.1"
78 :link '(emacs-commentary-link "python"))
79 \f
80 ;;;###autoload
81 (add-to-list 'interpreter-mode-alist '("jython" . jython-mode))
82 ;;;###autoload
83 (add-to-list 'interpreter-mode-alist '("python" . python-mode))
84 ;;;###autoload
85 (add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
86 \f
87 ;;;; Font lock
88
89 (defvar python-font-lock-keywords
90 `(,(rx symbol-start
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"
97 ;; Future keywords
98 "as" "None")
99 symbol-end)
100 ;; Definitions
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))))
110
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 " "))
126 ))
127
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.
138
139 ;; Test cases:
140 ;; ur"""ar""" x='"' # """
141 ;; x = ''' """ ' a
142 ;; '''
143 ;; x '"""' x """ \"""" x
144 ;; Fixme: """""" goes wrong (due to syntax-ppss not getting the string
145 ;; fence context).
146 (save-excursion
147 (goto-char (match-beginning 0))
148 (cond
149 ;; Consider property for the last char if in a fenced string.
150 ((= n 3)
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
166 ;; nil, which is OK.
167 )))
168
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.
171
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."
177 ;; (if (nth 3 state)
178 ;; (save-excursion
179 ;; (goto-char (nth 8 state))
180 ;; (condition-case nil
181 ;; (forward-sexp)
182 ;; (error 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))
189 \f
190 ;;;; Keymap and syntax
191
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
215 map global-map)
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"
219 `("Python"
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"]
225 "-"
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"]
230 "-"
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"]
239 "-"
240 ("Templates..."
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
246 "-"
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"]
264 "-"
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"]))
271 map))
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.
276
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)))
283 (dotimes (i 128)
284 (unless (= i ?_)
285 (if (equal symbol (aref sst i))
286 (modify-syntax-entry i "." table)))))
287 (modify-syntax-entry ?$ "." table)
288 (modify-syntax-entry ?% "." table)
289 ;; exceptions
290 (modify-syntax-entry ?# "<" table)
291 (modify-syntax-entry ?\n ">" table)
292 (modify-syntax-entry ?' "\"" table)
293 (modify-syntax-entry ?` "$" table)
294 table))
295 \f
296 ;;;; Utility stuff
297
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)))
302
303 (defconst python-space-backslash-table
304 (let ((table (copy-syntax-table python-mode-syntax-table)))
305 (modify-syntax-entry ?\\ " " table)
306 table)
307 "`python-mode-syntax-table' with backslash given whitespace syntax.")
308
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
314 or at end of line."
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)))
320 (if (nth 4 syntax)
321 (goto-char (nth 8 syntax)))
322 (- (point-max)))
323 (point-max))))
324 (with-syntax-table python-space-backslash-table
325 (forward-comment arg))))
326
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)))))
331
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))))))
340 (or (> depth 0)
341 (if (< depth 0) ; Unbalanced brackets -- act locally
342 (save-excursion
343 (condition-case ()
344 (progn (backward-up-list) t) ; actually within brackets
345 (error nil))))))))
346
347 (defun python-comment-line-p ()
348 "Return non-nil iff current line has only a comment."
349 (save-excursion
350 (end-of-line)
351 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
352 (back-to-indentation)
353 (looking-at (rx (or (syntax comment-start) line-end))))))
354
355 (defun python-blank-line-p ()
356 "Return non-nil iff current line is blank."
357 (save-excursion
358 (beginning-of-line)
359 (looking-at "\\s-*$")))
360
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)))))
367
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."
371 (save-excursion
372 (unless bos (python-beginning-of-statement))
373 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
374 "class" "try" "except" "finally")
375 symbol-end)))))
376
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'."
382 (save-excursion
383 (unless bos (python-beginning-of-statement))
384 (back-to-indentation)
385 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
386 symbol-end))))
387
388 (defun python-outdent-p ()
389 "Return non-nil if current line should outdent a level."
390 (save-excursion
391 (back-to-indentation)
392 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
393 symbol-end)))
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))
398 ;; Fixme: check this
399 (not (python-open-block-statement-p)))))
400 \f
401 ;;;; Indentation.
402
403 (defcustom python-indent 4
404 "Number of columns for a unit of indentation in Python mode.
405 See also `\\[python-guess-indent]'"
406 :group 'python
407 :type 'integer)
408
409 (defcustom python-guess-indent t
410 "Non-nil means Python mode guesses `python-indent' for the buffer."
411 :type 'boolean
412 :group 'python)
413
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.
418
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))
423 :group 'python)
424
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."
430 :type 'boolean
431 :group 'python)
432
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
436 statement."
437 :group 'python
438 :type 'integer)
439
440 (defun python-guess-indent ()
441 "Guess step for indentation of current buffer.
442 Set `python-indent' locally to the value guessed."
443 (interactive)
444 (save-excursion
445 (save-restriction
446 (widen)
447 (goto-char (point-min))
448 (let (done indent)
449 (while (and (not done) (not (eobp)))
450 (when (and (re-search-forward (rx ?: (0+ space)
451 (or (syntax comment-start)
452 line-end))
453 nil 'move)
454 (python-open-block-statement-p))
455 (save-excursion
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
461 (setq done t))))))
462 (when done
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)))
467 indent)))))
468
469 ;; Alist of possible indentations and start of statement they would
470 ;; close. Used in indentation cycling (below).
471 (defvar python-indent-list nil
472 "Internal use.")
473 ;; Length of the above
474 (defvar python-indent-list-length nil
475 "Internal use.")
476 ;; Current index into the alist.
477 (defvar python-indent-index nil
478 "Internal use.")
479
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)
484 (save-excursion
485 (beginning-of-line)
486 (let ((syntax (syntax-ppss))
487 start)
488 (cond
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))
501 (forward-line -1)
502 (while (and (< start (point)) (looking-at "\\s-*$"))
503 (forward-line -1))
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))))))
510 (if open-start
511 ;; Inside bracketed expression.
512 (progn
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))
518 (condition-case ()
519 (progn (forward-sexp)
520 (backward-sexp)
521 (< (point) point))
522 (error nil))))
523 ;; Extra level if we're backslash-continued or
524 ;; following a key.
525 (if (or backslash colon)
526 (+ python-indent (current-column))
527 (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.
534 (forward-line -1)
535 (if (python-continuation-line-p)
536 ;; We're past first continuation line. Align with
537 ;; previous line.
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)
544 python-indent
545 0))))))
546 ((bobp) 0)
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.
553 (catch 'done
554 (while t
555 (if (cond ((bobp))
556 ;; not at comment start
557 ((not (forward-comment -1))
558 (python-beginning-of-statement)
559 t)
560 ;; trailing comment
561 ((/= (current-column) (current-indentation))
562 (python-beginning-of-statement)
563 t)
564 ;; indentable comment like python-mode.el
565 ((and (looking-at (rx (syntax comment-start)
566 (or space line-end)))
567 (/= 0 (current-column)))))
568 (throw 'done t)))))
569 (python-indentation-levels)
570 ;; Prefer to indent comments with an immediately-following
571 ;; statement, e.g.
572 ;; ...
573 ;; # ...
574 ;; def ...
575 (when (and (> python-indent-list-length 1)
576 (python-comment-line-p))
577 (forward-line)
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)
582 (list elt))))))
583 (caar (last python-indent-list)))))))
584
585 ;;;; Cycling through the possible indentations with successive TABs.
586
587 ;; These don't need to be buffer-local since they're only relevant
588 ;; during a cycle.
589
590 (defun python-initial-text ()
591 "Text of line following indentation and ignoring any trailing comment."
592 (save-excursion
593 (buffer-substring (progn
594 (back-to-indentation)
595 (point))
596 (progn
597 (end-of-line)
598 (forward-comment -1)
599 (point)))))
600
601 (defconst python-block-pairs
602 '(("else" "if" "elif" "while" "for" "try" "except")
603 ("elif" "if" "elif")
604 ("except" "try" "except")
605 ("finally" "try"))
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.")
609
610 (defun python-first-word ()
611 "Return first word (actually symbol) on the line."
612 (save-excursion
613 (back-to-indentation)
614 (current-word t)))
615
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)."
623 (save-excursion
624 (let ((initial "")
625 levels indent)
626 ;; Only one possibility immediately following a block open
627 ;; statement, assuming it doesn't have a `suite' on the same line.
628 (cond
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:
633 ;; if ...: ...
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
640 ;; another.
641 ((save-excursion
642 (when (python-comment-line-p)
643 (forward-line -1)
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.
648 (t
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:
654 ;; if ...: ...
655 ;; else ...:
656 ;; where the second line need not be outdented.
657 (not (member (python-first-word)
658 (cdr (assoc start
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))
664 levels))
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))
670 levels))))))
671 (prog1 (or levels (setq levels '((0 . ""))))
672 (setq python-indent-list levels
673 python-indent-list-length (length python-indent-list))))))
674
675 ;; This is basically what `python-indent-line' would be if we didn't
676 ;; do the cycling.
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))
690 (beginning-of-line)
691 (delete-horizontal-space)
692 (indent-to target)
693 (if (> (- (point-max) pos) (point))
694 (goto-char (- (point-max) pos))))))
695
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
701 the cycling."
702 (interactive)
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))
709 (beginning-of-line)
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))))
715 (if text
716 (message "Closes: %s" text))))))
717 (python-indent-line-1)
718 (setq python-indent-index (1- python-indent-list-length))))
719
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."
724 (save-excursion
725 (goto-char end)
726 (setq end (point-marker))
727 (goto-char start)
728 (or (bolp) (forward-line 1))
729 (while (< (point) end)
730 (or (and (bolp) (eolp))
731 (python-indent-line-1 t))
732 (forward-line 1))
733 (move-marker end nil)))
734
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)
741 (save-excursion
742 (python-previous-statement)
743 (current-indentation))))))
744 \f
745 ;;;; Movement.
746
747 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
748 ;; block, statement, depending on context.
749
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))
777 (= in ci)
778 (< in ci)))
779 (not (python-in-string/comment)))
780 (setq found t)))))
781
782 (defun python-end-of-defun ()
783 "`end-of-defun-function' for Python.
784 Finds end of innermost nested class or method definition."
785 (let ((orig (point))
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)
791 (end-of-line)
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
799 (unless (eobp)
800 (beginning-of-line)))
801 ;; Don't move before top-level statement that would end defun.
802 (end-of-line)
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).
811 (unless (eobp)
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:
819 ;; if ...:
820 ;; ...
821 ;; else:
822 ;; ... # point here
823 ;; ...
824 ;; def ...
825 (if (< (point) orig)
826 (goto-char (point-max)))))
827
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."
832 (beginning-of-line)
833 (python-beginning-of-string)
834 (while (python-continuation-line-p)
835 (beginning-of-line)
836 (if (python-backslash-continuation-line-p)
837 (progn
838 (forward-line -1)
839 (while (python-backslash-continuation-line-p)
840 (forward-line -1)))
841 (python-beginning-of-string)
842 (python-skip-out)))
843 (back-to-indentation))
844
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)
853 (if (> depth 0)
854 ;; Skip forward out of nested brackets.
855 (condition-case () ; beware invalid syntax
856 (progn (backward-up-list (* forward depth)) t)
857 (error nil))
858 ;; Invalid syntax (too many closed brackets).
859 ;; Skip out of as many as possible.
860 (let (done)
861 (while (condition-case ()
862 (progn (backward-up-list forward)
863 (setq done t))
864 (error nil)))
865 done)))))
866
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."
872 (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))
878 (setq comment t)
879 nil)
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))))
887 (end-of-line))
888 (unless comment
889 (eq ?\\ (char-before)))) ; Line continued?
890 (end-of-line 2)) ; Try next line.
891 (point))
892
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."
897 (interactive "p")
898 (unless count (setq count 1))
899 (if (< count 0)
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))))
906 count))
907
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."
912 (interactive "p")
913 (unless count (setq count 1))
914 (if (< count 0)
915 (python-previous-statement (- count))
916 (beginning-of-line)
917 (while (and (> count 0) (not (eobp)))
918 (python-end-of-statement)
919 (python-skip-comments/blanks)
920 (unless (eobp)
921 (setq count (1- count))))
922 count))
923
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."
931 (interactive "p")
932 (unless arg (setq arg 1))
933 (cond
934 ((zerop arg))
935 ((< arg 0) (python-end-of-block (- arg)))
936 (t
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)))
943 (if (zerop ci)
944 (not (goto-char point)) ; return nil
945 ;; Look upwards for less indented statement.
946 (if (catch 'done
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))
960 (beginning-of-line)
961 (throw 'done t)))
962 (not (goto-char point))) ; Failed -- return nil
963 (python-beginning-of-block (1- arg)))))))))
964
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."
971 (interactive "p")
972 (unless arg (setq arg 1))
973 (if (< arg 0)
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))
983 (catch 'done
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)))))))
990 (setq arg (1- arg)))
991 (zerop arg)))
992 \f
993 ;;;; Imenu.
994
995 (defvar python-recursing)
996 (defun python-imenu-create-index ()
997 "`imenu-create-index-function' for Python.
998
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
1003 precede it)."
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
1011 ;; font-lock.
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)))
1015 )
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
1021 nil t)
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)))
1027 (save-restriction
1028 (narrow-to-defun)
1029 (let* ((python-recursing t)
1030 (sublist (python-imenu-create-index)))
1031 (if sublist
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.
1037 (let (vars)
1038 (goto-char (point-min))
1039 (while (re-search-forward
1040 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1041 nil t)
1042 (unless (python-in-string/comment)
1043 (push (cons (match-string 1) (match-beginning 1))
1044 vars)))
1045 (setq index-alist (nreverse index-alist))
1046 (if vars
1047 (push (cons "Module variables"
1048 (nreverse vars))
1049 index-alist))))
1050 index-alist))
1051 \f
1052 ;;;; `Electric' commands.
1053
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."
1058 (interactive "*P")
1059 (self-insert-command (if (not (integerp arg)) 1 arg))
1060 (and (not arg)
1061 (eolp)
1062 (python-outdent-p)
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)
1067
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'.
1072 Repeat ARG times."
1073 (interactive "*p")
1074 (if (or (/= (current-indentation) (current-column))
1075 (bolp)
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.
1080 (let ((indent 0)
1081 (ci (current-indentation))
1082 (indents (python-indentation-levels))
1083 initial)
1084 (dolist (x indents)
1085 (if (< (car x) ci)
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)
1093 \f
1094 ;;;; pychecker
1095
1096 (defcustom python-check-command "pychecker --stdlib"
1097 "Command used to check a Python file."
1098 :type 'string
1099 :group 'python)
1100
1101 (defvar python-saved-check-command nil
1102 "Internal use.")
1103
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."
1109 (interactive
1110 (list (read-string "Checker command: "
1111 (or python-saved-check-command
1112 (concat python-check-command " "
1113 (let ((name (buffer-file-name)))
1114 (if 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)))
1123 \f
1124 ;;;; Inferior mode stuff (following cmuscheme).
1125
1126 ;; Fixme: Make sure we can work with IPython.
1127
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'."
1133 :group 'python
1134 :type 'string)
1135
1136 (defcustom python-jython-command "jython"
1137 "Shell command to run Jython interpreter.
1138 Any arguments can't contain whitespace."
1139 :group 'python
1140 :type 'string)
1141
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.")
1147
1148 (defvar python-buffer nil
1149 "*The current python process buffer.
1150
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.
1156
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.
1162
1163 Use \\[python-set-proc] to set the default value from a buffer with a
1164 local value.")
1165 (make-variable-buffer-local 'python-buffer)
1166
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)))
1174 1 2)
1175 (,(rx " in file " (group (1+ not-newline)) " on line "
1176 (group (1+ digit)))
1177 1 2))
1178 "`compilation-error-regexp-alist' for inferior Python.")
1179
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.
1189
1190 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1191 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1192 map))
1193
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].
1200
1201 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1202 that order.
1203
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
1207 process buffer.
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
1212 `python-buffer'.
1213
1214 \\{inferior-python-mode-map}"
1215 :group 'python
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
1220 nil t)
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))
1228
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."
1232 :type 'regexp
1233 :group 'python)
1234
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)))
1239
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))
1244 ((not (= where 0))
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))))))))
1249
1250 (defvar python-preoutput-result nil
1251 "Data from last `_emacs_out' line seen by the preoutput filter.")
1252
1253 (defvar python-preoutput-leftover nil)
1254 (defvar python-preoutput-skip-next-prompt nil)
1255
1256 ;; Using this stops us getting lines in the buffer like
1257 ;; >>> ... ... >>>
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))
1263 (let ((start 0)
1264 (res ""))
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))
1276 (progn
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))
1288 (not (bolp))
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)
1295 res)
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)
1302 res)
1303 (t (concat res s)))))
1304
1305 (autoload 'comint-check-proc "comint")
1306
1307 ;;;###autoload
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.
1312
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'.
1320
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)))
1361
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.
1368
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))
1385 ) ;;)
1386
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.
1397 ;;
1398 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1399 ;; the reference to the temporary file to the source.
1400 ;;
1401 ;; Fixme: Write a `coding' header to the temp file if the region is
1402 ;; non-ASCII.
1403 (interactive "r")
1404 (let* ((f (make-temp-file "py"))
1405 (command (format "emacs.eexecfile(%S)" f))
1406 (orig-start (copy-marker start)))
1407 (when (save-excursion
1408 (goto-char start)
1409 (/= 0 (current-indentation))) ; need dummy block
1410 (save-excursion
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))))
1422
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")))
1432
1433 (defun python-send-buffer ()
1434 "Send the current buffer to the inferior Python process."
1435 (interactive)
1436 (python-send-region (point-min) (point-max)))
1437
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."
1442 (interactive)
1443 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1444 (progn (end-of-defun) (point)))))
1445
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."
1449 (interactive "P")
1450 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1451 (when eob-p
1452 (push-mark)
1453 (goto-char (point-max))))
1454
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."
1458 (interactive "r")
1459 (python-send-region start end)
1460 (python-switch-to-python t))
1461
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)
1468 :group 'python)
1469
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.")
1473
1474 (autoload 'comint-get-source "comint")
1475
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
1483 python-source-modes
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)))
1498
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)
1505 (run-python nil t))
1506 (get-buffer-process (or (if (derived-mode-p 'inferior-python-mode)
1507 (current-buffer)
1508 python-buffer))))
1509
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'."
1516 (interactive)
1517 (if (local-variable-p 'python-buffer)
1518 (setq-default python-buffer python-buffer)
1519 (error "No local value of `python-buffer'")))
1520 \f
1521 ;;;; Context-sensitive help.
1522
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)
1527 table)
1528 "Syntax table giving `.' symbol syntax.
1529 Otherwise inherits from `python-mode-syntax-table'.")
1530
1531 (defvar view-return-to-alist)
1532 (eval-when-compile (autoload 'help-buffer "help-fns"))
1533
1534 (defvar python-imports) ; forward declaration
1535
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.
1542
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'.
1547
1548 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1549 will."
1550 ;; Note that we do this in the inferior process, not a separate one, to
1551 ;; ensure the environment is appropriate.
1552 (interactive
1553 (let ((symbol (with-syntax-table python-dotty-syntax-table
1554 (current-word)))
1555 (enable-recursive-minibuffers t))
1556 (list (read-string (if symbol
1557 (format "Describe symbol (default %s): " symbol)
1558 "Describe symbol: ")
1559 nil nil 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
1565 (lambda ()
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))
1578
1579 (add-to-list 'debug-ignored-errors "^No symbol")
1580
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)
1588 (while (progn
1589 (accept-process-output proc 5)
1590 (null python-preoutput-result)))
1591 (prog1 python-preoutput-result
1592 (kill-local-variable 'python-preoutput-result)))))
1593
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
1601 (current-word))))
1602 ;; First try the symbol we're on.
1603 (or (and symbol
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)))
1610 (save-excursion
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)))))))))))
1620 \f
1621 ;;;; Info-look functionality.
1622
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
1627 " -V"))))
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.
1631 (versioned
1632 (with-temp-buffer
1633 (with-no-warnings (Info-mode))
1634 (condition-case ()
1635 ;; Don't use `info' because it would pop-up a *info* buffer.
1636 (with-no-warnings
1637 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1638 version))
1639 t)
1640 (error nil)))))
1641 (info-lookup-maybe-add-help
1642 :mode 'python-mode
1643 :regexp "[[:alnum:]_]+"
1644 :doc-spec
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
1648 ;; instance.)
1649 (if versioned
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"
1654 nil ""))
1655 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1656 nil ""))
1657 (,(concat "(python" version "-lib)Module Index" nil ""))
1658 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1659 nil ""))
1660 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1661 nil ""))
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))
1672 \f
1673 ;;;; Miscellany.
1674
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)
1680 :group 'python)
1681
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.
1690 (save-excursion
1691 (save-restriction
1692 (widen)
1693 (goto-char (point-min))
1694 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1695 (match-string 2))))
1696 (if (and interpreter (eq 'jython-mode
1697 (cdr (assoc (file-name-nondirectory
1698 interpreter)
1699 interpreter-mode-alist))))
1700 (jython-mode)
1701 (if (catch 'done
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.
1706 t)
1707 (if (member (match-string 1) python-jython-packages)
1708 (throw 'done t))))
1709 (jython-mode)))))))
1710
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."
1718 (interactive "P")
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.
1724 (save-excursion
1725 (end-of-line)
1726 (let* ((syntax (syntax-ppss))
1727 (orig (point))
1728 (start (nth 8 syntax))
1729 end)
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)
1734 (setq end (point)))
1735 (error (setq end (point-max)))))
1736 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced
1737 ; string
1738 (forward-char)
1739 (setq end (point))
1740 (condition-case ()
1741 (progn (backward-sexp)
1742 (setq start (point)))
1743 (error nil))))
1744 (when end
1745 (save-restriction
1746 (narrow-to-region start end)
1747 (goto-char orig)
1748 (fill-paragraph justify))))))
1749 t)
1750
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
1756 COUNT columns."
1757 (interactive (if mark-active
1758 (list (region-beginning) (region-end) current-prefix-arg)
1759 (list (point) (point) current-prefix-arg)))
1760 (if count
1761 (setq count (prefix-numeric-value count))
1762 (setq count python-indent))
1763 (when (> count 0)
1764 (save-excursion
1765 (goto-char start)
1766 (while (< (point) end)
1767 (if (and (< (current-indentation) count)
1768 (not (looking-at "[ \t]*$")))
1769 (error "Can't shift all lines enough"))
1770 (forward-line))
1771 (indent-rigidly start end (- count)))))
1772
1773 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1774
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
1779 END lie."
1780 (interactive (if mark-active
1781 (list (region-beginning) (region-end) current-prefix-arg)
1782 (list (point) (point) current-prefix-arg)))
1783 (if count
1784 (setq count (prefix-numeric-value count))
1785 (setq count python-indent))
1786 (indent-rigidly start end count))
1787
1788 (defun python-outline-level ()
1789 "`outline-level' function for Python mode.
1790 The level is the number of `python-indent' steps of indentation
1791 of current line."
1792 (1+ (/ (current-indentation) python-indent)))
1793
1794 ;; Fixme: Consider top-level assignments, imports, &c.
1795 (defun python-current-defun ()
1796 "`add-log-current-defun-function' for Python."
1797 (save-excursion
1798 ;; Move up the tree of nested `class' and `def' blocks until we
1799 ;; get to zero indentation, accumulating the defined names.
1800 (let ((start t)
1801 accum)
1802 (while (or start (> (current-indentation) 0))
1803 (setq start nil)
1804 (python-beginning-of-block)
1805 (end-of-line)
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 ".")))))
1811
1812 (defun python-mark-block ()
1813 "Mark the block around point.
1814 Uses `python-beginning-of-block', `python-end-of-block'."
1815 (interactive)
1816 (push-mark)
1817 (python-beginning-of-block)
1818 (push-mark (point) nil t)
1819 (python-end-of-block)
1820 (exchange-point-and-mark))
1821
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.
1825 \f
1826 ;;;; Completion.
1827
1828 (defvar python-imports nil
1829 "String of top-level import statements updated by `python-find-imports'.")
1830 (make-variable-buffer-local 'python-imports)
1831
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'."
1840 (interactive)
1841 (save-excursion
1842 (let (lines)
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))
1848 lines)))
1849 (setq python-imports
1850 (if lines
1851 (apply #'concat
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
1855 ;; buffer's.
1856 ;; (if buffer-file-name
1857 ;; (concat
1858 ;; "import "
1859 ;; (file-name-sans-extension
1860 ;; (file-name-nondirectory buffer-file-name))))
1861 (nreverse lines))
1862 "None"))
1863 (when lines
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))))))
1870
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.
1875 The list is sorted.
1876 Uses `python-imports' to load modules against which to complete."
1877 (when symbol
1878 (let ((completions
1879 (condition-case ()
1880 (car (read-from-string
1881 (python-send-receive
1882 (format "emacs.complete(%S,%s)" symbol python-imports))))
1883 (error nil))))
1884 (sort
1885 ;; We can get duplicates from the above -- don't know why.
1886 (delete-dups completions)
1887 #'string<))))
1888
1889 (defun python-partial-symbol ()
1890 "Return the partial symbol before point (for completion)."
1891 (let ((end (point))
1892 (start (save-excursion
1893 (and (re-search-backward
1894 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
1895 (group (1+ (regexp "[[:alnum:]._]"))) point)
1896 nil t)
1897 (match-beginning 1)))))
1898 (if start (buffer-substring-no-properties start end))))
1899
1900 (defun python-complete-symbol ()
1901 "Perform completion on the Python symbol preceding point.
1902 Repeating the command scrolls the completion window."
1903 (interactive)
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)
1913 (scroll-up))))
1914 ;; Do completion.
1915 (let* ((end (point))
1916 (symbol (python-partial-symbol))
1917 (completions (python-symbol-completions symbol))
1918 (completion (if completions
1919 (try-completion symbol completions))))
1920 (when symbol
1921 (cond ((eq completion t))
1922 ((null completion)
1923 (message "Can't find completion for \"%s\"" symbol)
1924 (ding))
1925 ((not (string= symbol completion))
1926 (delete-region (- end (length symbol)) end)
1927 (insert completion))
1928 (t
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"))))))))
1933
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
1937 (unless old
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))
1947 (if he-expand-list
1948 (progn
1949 (he-substitute-string (pop he-expand-list))
1950 t)
1951 (if old (he-reset-string))
1952 nil)))
1953 \f
1954 ;;;; FFAP support
1955
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)))
1959
1960 (eval-after-load "ffap"
1961 '(push '(python-mode . python-module-path) ffap-alist))
1962 \f
1963 ;;;; Skeletons
1964
1965 (defvar python-skeletons nil
1966 "Alist of named skeletons for Python mode.
1967 Elements are of the form (NAME . EXPANDER-FUNCTION).")
1968
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 ())
1973
1974 (eval-when-compile
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))))
1980 `(progn
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)
1985 ,@elements)))))
1986 (put 'def-python-skeleton 'lisp-indent-function 2)
1987
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.
1993
1994 (def-python-skeleton if
1995 "Condition: "
1996 "if " str ":" \n
1997 > _ \n
1998 ("other condition, %s: "
1999 < ; Avoid wrong indentation after block opening.
2000 "elif " str ":" \n
2001 > _ \n nil)
2002 (python-else) | ^)
2003
2004 (define-skeleton python-else
2005 "Auxiliary skeleton."
2006 nil
2007 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2008 (signal 'quit t))
2009 < "else:" \n
2010 > _ \n)
2011
2012 (def-python-skeleton while
2013 "Condition: "
2014 "while " str ":" \n
2015 > _ \n
2016 (python-else) | ^)
2017
2018 (def-python-skeleton for
2019 "Target, %s: "
2020 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2021 > _ \n
2022 (python-else) | ^)
2023
2024 (def-python-skeleton try/except
2025 nil
2026 "try:" \n
2027 > _ \n
2028 ("Exception, %s: "
2029 < "except " str (python-target) ":" \n
2030 > _ \n nil)
2031 < "except:" \n
2032 > _ \n
2033 (python-else) | ^)
2034
2035 (define-skeleton python-target
2036 "Auxiliary skeleton."
2037 "Target, %s: " ", " str | -2)
2038
2039 (def-python-skeleton try/finally
2040 nil
2041 "try:" \n
2042 > _ \n
2043 < "finally:" \n
2044 > _ \n)
2045
2046 (def-python-skeleton def
2047 "Name: "
2048 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2049 str) "):" \n
2050 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2051 > _ \n)
2052
2053 (def-python-skeleton class
2054 "Name: "
2055 "class " str " (" ("Inheritance, %s: "
2056 (unless (equal ?\( (char-before)) ", ")
2057 str)
2058 & ")" | -2 ; close list or remove opening
2059 ":" \n
2060 "\"\"\"" @ " \"\"\"" \n
2061 > _ \n)
2062
2063 (defvar python-default-template "if"
2064 "Default template to expand by `python-insert-template'.
2065 Updated on each expansion.")
2066
2067 (defun python-expand-template (name)
2068 "Expand template named NAME.
2069 Interactively, prompt for the name with completion."
2070 (interactive
2071 (list (completing-read (format "Template to expand (default %s): "
2072 python-default-template)
2073 python-skeletons nil t)))
2074 (if (equal "" name)
2075 (setq name python-default-template)
2076 (setq python-default-template name))
2077 (let ((func (cdr (assoc name python-skeletons))))
2078 (if func
2079 (funcall func)
2080 (error "Undefined template: %s" name))))
2081 \f
2082 ;;;; Bicycle Repair Man support
2083
2084 (autoload 'pymacs-load "pymacs" nil t)
2085 (autoload 'brm-init "bikemacs")
2086
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).
2093
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."
2097 (interactive)
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)))
2106 (easy-menu-define
2107 python-brm-menu python-mode-map
2108 "Bicycle Repair Man"
2109 '("BicycleRepairMan"
2110 :help "Interface to navigation and refactoring tool"
2111 "Queries"
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"]
2116 "-"
2117 "Refactoring"
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
2127 :help
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))))
2132 \f
2133 ;;;; Modes.
2134
2135 (defvar outline-heading-end-regexp)
2136 (defvar eldoc-documentation-function)
2137
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))
2143
2144 (defvar python-abbrev-syntax-table
2145 (copy-syntax-table python-mode-syntax-table)
2146 "Syntax table used when expanding abbrevs.")
2147
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)
2153
2154 (defvar python-mode-running) ;Dynamically scoped var.
2155
2156 ;;;###autoload
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.
2163
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.
2169 \\<python-mode-map>
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.
2176
2177 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2178 effect outside them.
2179
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.
2189
2190 \\{python-mode-map}"
2191 :group 'python
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)
2199 ))
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")
2212 symbol-end))
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
2225 nil t)
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 "#"
2231 ,(lambda (arg)
2232 (python-end-of-defun)
2233 (skip-chars-backward " \t\n"))
2234 nil))
2235 (set (make-local-variable 'skeleton-further-elements)
2236 '((< '(backward-delete-char-untabify (min python-indent
2237 (current-column))))
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))))
2254
2255 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2256 (custom-add-option 'python-mode-hook
2257 (lambda ()
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)
2263
2264 ;;;###autoload
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'."
2269 :group 'python
2270 (set (make-local-variable 'python-command) python-jython-command))
2271
2272 (provide 'python)
2273 (provide 'python-21)
2274 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2275 ;;; python.el ends here