]> code.delx.au - gnu-emacs/blob - lisp/progmodes/python.el
Also require comint when loading.
[gnu-emacs] / lisp / progmodes / python.el
1 ;;; python.el --- silly walks for Python -*- coding: iso-8859-1 -*-
2
3 ;; Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 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 3, 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 (require 'comint)
68
69 (eval-when-compile
70 (require 'compile)
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.5 reference, § keywords.
93 ;; def and class dealt with separately below
94 (or "and" "as" "assert" "break" "continue" "del" "elif" "else"
95 "except" "exec" "finally" "for" "from" "global" "if"
96 "import" "in" "is" "lambda" "not" "or" "pass" "print"
97 "raise" "return" "try" "while" "with" "yield"
98 ;; Not real keywords, but close enough to be fontified as such
99 "self" "True" "False")
100 symbol-end)
101 (,(rx symbol-start "None" symbol-end) ; See § Keywords in 2.5 manual.
102 . font-lock-constant-face)
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* ((font-lock-syntactic-keywords nil)
155 (syntax (syntax-ppss)))
156 (when (eq t (nth 3 syntax)) ; after unclosed fence
157 (goto-char (nth 8 syntax)) ; fence position
158 (skip-chars-forward "uUrR") ; skip any prefix
159 ;; Is it a matching sequence?
160 (if (eq (char-after) (char-after (match-beginning 2)))
161 (eval-when-compile (string-to-syntax "|"))))))
162 ;; Consider property for initial char, accounting for prefixes.
163 ((or (and (= n 2) ; leading quote (not prefix)
164 (= (match-beginning 1) (match-end 1))) ; prefix is null
165 (and (= n 1) ; prefix
166 (/= (match-beginning 1) (match-end 1)))) ; non-empty
167 (let ((font-lock-syntactic-keywords nil))
168 (unless (nth 3 (syntax-ppss))
169 (eval-when-compile (string-to-syntax "|")))))
170 ;; Otherwise (we're in a non-matching string) the property is
171 ;; nil, which is OK.
172 )))
173
174 ;; This isn't currently in `font-lock-defaults' as probably not worth
175 ;; it -- we basically only mess with a few normally-symbol characters.
176
177 ;; (defun python-font-lock-syntactic-face-function (state)
178 ;; "`font-lock-syntactic-face-function' for Python mode.
179 ;; Returns the string or comment face as usual, with side effect of putting
180 ;; a `syntax-table' property on the inside of the string or comment which is
181 ;; the standard syntax table."
182 ;; (if (nth 3 state)
183 ;; (save-excursion
184 ;; (goto-char (nth 8 state))
185 ;; (condition-case nil
186 ;; (forward-sexp)
187 ;; (error nil))
188 ;; (put-text-property (1+ (nth 8 state)) (1- (point))
189 ;; 'syntax-table (standard-syntax-table))
190 ;; 'font-lock-string-face)
191 ;; (put-text-property (1+ (nth 8 state)) (line-end-position)
192 ;; 'syntax-table (standard-syntax-table))
193 ;; 'font-lock-comment-face))
194 \f
195 ;;;; Keymap and syntax
196
197 (defvar python-mode-map
198 (let ((map (make-sparse-keymap)))
199 ;; Mostly taken from python-mode.el.
200 (define-key map ":" 'python-electric-colon)
201 (define-key map "\177" 'python-backspace)
202 (define-key map "\C-c<" 'python-shift-left)
203 (define-key map "\C-c>" 'python-shift-right)
204 (define-key map "\C-c\C-k" 'python-mark-block)
205 (define-key map "\C-c\C-d" 'python-pdbtrack-toggle-stack-tracking)
206 (define-key map "\C-c\C-n" 'python-next-statement)
207 (define-key map "\C-c\C-p" 'python-previous-statement)
208 (define-key map "\C-c\C-u" 'python-beginning-of-block)
209 (define-key map "\C-c\C-f" 'python-describe-symbol)
210 (define-key map "\C-c\C-w" 'python-check)
211 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
212 (define-key map "\C-c\C-s" 'python-send-string)
213 (define-key map [?\C-\M-x] 'python-send-defun)
214 (define-key map "\C-c\C-r" 'python-send-region)
215 (define-key map "\C-c\M-r" 'python-send-region-and-go)
216 (define-key map "\C-c\C-c" 'python-send-buffer)
217 (define-key map "\C-c\C-z" 'python-switch-to-python)
218 (define-key map "\C-c\C-m" 'python-load-file)
219 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
220 (substitute-key-definition 'complete-symbol 'python-complete-symbol
221 map global-map)
222 (define-key map "\C-c\C-i" 'python-find-imports)
223 (define-key map "\C-c\C-t" 'python-expand-template)
224 (easy-menu-define python-menu map "Python Mode menu"
225 `("Python"
226 :help "Python-specific Features"
227 ["Shift region left" python-shift-left :active mark-active
228 :help "Shift by a single indentation step"]
229 ["Shift region right" python-shift-right :active mark-active
230 :help "Shift by a single indentation step"]
231 "-"
232 ["Mark block" python-mark-block
233 :help "Mark innermost block around point"]
234 ["Mark def/class" mark-defun
235 :help "Mark innermost definition around point"]
236 "-"
237 ["Start of block" python-beginning-of-block
238 :help "Go to start of innermost definition around point"]
239 ["End of block" python-end-of-block
240 :help "Go to end of innermost definition around point"]
241 ["Start of def/class" beginning-of-defun
242 :help "Go to start of innermost definition around point"]
243 ["End of def/class" end-of-defun
244 :help "Go to end of innermost definition around point"]
245 "-"
246 ("Templates..."
247 :help "Expand templates for compound statements"
248 :filter (lambda (&rest junk)
249 (mapcar (lambda (elt)
250 (vector (car elt) (cdr elt) t))
251 python-skeletons))) ; defined later
252 "-"
253 ["Start interpreter" python-shell
254 :help "Run `inferior' Python in separate buffer"]
255 ["Import/reload file" python-load-file
256 :help "Load into inferior Python session"]
257 ["Eval buffer" python-send-buffer
258 :help "Evaluate buffer en bloc in inferior Python session"]
259 ["Eval region" python-send-region :active mark-active
260 :help "Evaluate region en bloc in inferior Python session"]
261 ["Eval def/class" python-send-defun
262 :help "Evaluate current definition in inferior Python session"]
263 ["Switch to interpreter" python-switch-to-python
264 :help "Switch to inferior Python buffer"]
265 ["Set default process" python-set-proc
266 :help "Make buffer's inferior process the default"
267 :active (buffer-live-p python-buffer)]
268 ["Check file" python-check :help "Run pychecker"]
269 ["Debugger" pdb :help "Run pdb under GUD"]
270 "-"
271 ["Help on symbol" python-describe-symbol
272 :help "Use pydoc on symbol at point"]
273 ["Complete symbol" python-complete-symbol
274 :help "Complete (qualified) symbol before point"]
275 ["Update imports" python-find-imports
276 :help "Update list of top-level imports for completion"]))
277 map))
278 ;; Fixme: add toolbar stuff for useful things like symbol help, send
279 ;; region, at least. (Shouldn't be specific to Python, obviously.)
280 ;; eric has items including: (un)indent, (un)comment, restart script,
281 ;; run script, debug script; also things for profiling, unit testing.
282
283 (defvar python-shell-map
284 (let ((map (copy-keymap comint-mode-map)))
285 (define-key map [tab] 'tab-to-tab-stop)
286 (define-key map "\C-c-" 'py-up-exception)
287 (define-key map "\C-c=" 'py-down-exception)
288 map)
289 "Keymap used in *Python* shell buffers.")
290
291 (defvar python-mode-syntax-table
292 (let ((table (make-syntax-table)))
293 ;; Give punctuation syntax to ASCII that normally has symbol
294 ;; syntax or has word syntax and isn't a letter.
295 (let ((symbol (string-to-syntax "_"))
296 (sst (standard-syntax-table)))
297 (dotimes (i 128)
298 (unless (= i ?_)
299 (if (equal symbol (aref sst i))
300 (modify-syntax-entry i "." table)))))
301 (modify-syntax-entry ?$ "." table)
302 (modify-syntax-entry ?% "." table)
303 ;; exceptions
304 (modify-syntax-entry ?# "<" table)
305 (modify-syntax-entry ?\n ">" table)
306 (modify-syntax-entry ?' "\"" table)
307 (modify-syntax-entry ?` "$" table)
308 table))
309 \f
310 ;;;; Utility stuff
311
312 (defsubst python-in-string/comment ()
313 "Return non-nil if point is in a Python literal (a comment or string)."
314 ;; We don't need to save the match data.
315 (nth 8 (syntax-ppss)))
316
317 (defconst python-space-backslash-table
318 (let ((table (copy-syntax-table python-mode-syntax-table)))
319 (modify-syntax-entry ?\\ " " table)
320 table)
321 "`python-mode-syntax-table' with backslash given whitespace syntax.")
322
323 (defun python-skip-comments/blanks (&optional backward)
324 "Skip comments and blank lines.
325 BACKWARD non-nil means go backwards, otherwise go forwards.
326 Backslash is treated as whitespace so that continued blank lines
327 are skipped. Doesn't move out of comments -- should be outside
328 or at end of line."
329 (let ((arg (if backward
330 ;; If we're in a comment (including on the trailing
331 ;; newline), forward-comment doesn't move backwards out
332 ;; of it. Don't set the syntax table round this bit!
333 (let ((syntax (syntax-ppss)))
334 (if (nth 4 syntax)
335 (goto-char (nth 8 syntax)))
336 (- (point-max)))
337 (point-max))))
338 (with-syntax-table python-space-backslash-table
339 (forward-comment arg))))
340
341 (defun python-backslash-continuation-line-p ()
342 "Non-nil if preceding line ends with backslash that is not in a comment."
343 (and (eq ?\\ (char-before (line-end-position 0)))
344 (not (syntax-ppss-context (syntax-ppss)))))
345
346 (defun python-continuation-line-p ()
347 "Return non-nil if current line continues a previous one.
348 The criteria are that the previous line ends in a backslash outside
349 comments and strings, or that point is within brackets/parens."
350 (or (python-backslash-continuation-line-p)
351 (let ((depth (syntax-ppss-depth
352 (save-excursion ; syntax-ppss with arg changes point
353 (syntax-ppss (line-beginning-position))))))
354 (or (> depth 0)
355 (if (< depth 0) ; Unbalanced brackets -- act locally
356 (save-excursion
357 (condition-case ()
358 (progn (backward-up-list) t) ; actually within brackets
359 (error nil))))))))
360
361 (defun python-comment-line-p ()
362 "Return non-nil iff current line has only a comment."
363 (save-excursion
364 (end-of-line)
365 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
366 (back-to-indentation)
367 (looking-at (rx (or (syntax comment-start) line-end))))))
368
369 (defun python-blank-line-p ()
370 "Return non-nil iff current line is blank."
371 (save-excursion
372 (beginning-of-line)
373 (looking-at "\\s-*$")))
374
375 (defun python-beginning-of-string ()
376 "Go to beginning of string around point.
377 Do nothing if not in string."
378 (let ((state (syntax-ppss)))
379 (when (eq 'string (syntax-ppss-context state))
380 (goto-char (nth 8 state)))))
381
382 (defun python-open-block-statement-p (&optional bos)
383 "Return non-nil if statement at point opens a block.
384 BOS non-nil means point is known to be at beginning of statement."
385 (save-excursion
386 (unless bos (python-beginning-of-statement))
387 (looking-at (rx (and (or "if" "else" "elif" "while" "for" "def"
388 "class" "try" "except" "finally" "with")
389 symbol-end)))))
390
391 (defun python-close-block-statement-p (&optional bos)
392 "Return non-nil if current line is a statement closing a block.
393 BOS non-nil means point is at beginning of statement.
394 The criteria are that the line isn't a comment or in string and
395 starts with keyword `raise', `break', `continue' or `pass'."
396 (save-excursion
397 (unless bos (python-beginning-of-statement))
398 (back-to-indentation)
399 (looking-at (rx (or "return" "raise" "break" "continue" "pass")
400 symbol-end))))
401
402 (defun python-outdent-p ()
403 "Return non-nil if current line should outdent a level."
404 (save-excursion
405 (back-to-indentation)
406 (and (looking-at (rx (and (or "else" "finally" "except" "elif")
407 symbol-end)))
408 (not (python-in-string/comment))
409 ;; Ensure there's a previous statement and move to it.
410 (zerop (python-previous-statement))
411 (not (python-close-block-statement-p t))
412 ;; Fixme: check this
413 (not (python-open-block-statement-p)))))
414 \f
415 ;;;; Indentation.
416
417 (defcustom python-indent 4
418 "Number of columns for a unit of indentation in Python mode.
419 See also `\\[python-guess-indent]'"
420 :group 'python
421 :type 'integer)
422 (put 'python-indent 'safe-local-variable 'integerp)
423
424 (defcustom python-guess-indent t
425 "Non-nil means Python mode guesses `python-indent' for the buffer."
426 :type 'boolean
427 :group 'python)
428
429 (defcustom python-indent-string-contents t
430 "Non-nil means indent contents of multi-line strings together.
431 This means indent them the same as the preceding non-blank line.
432 Otherwise preserve their indentation.
433
434 This only applies to `doc' strings, i.e. those that form statements;
435 the indentation is preserved in others."
436 :type '(choice (const :tag "Align with preceding" t)
437 (const :tag "Preserve indentation" nil))
438 :group 'python)
439
440 (defcustom python-honour-comment-indentation nil
441 "Non-nil means indent relative to preceding comment line.
442 Only do this for comments where the leading comment character is
443 followed by space. This doesn't apply to comment lines, which
444 are always indented in lines with preceding comments."
445 :type 'boolean
446 :group 'python)
447
448 (defcustom python-continuation-offset 4
449 "Number of columns of additional indentation for continuation lines.
450 Continuation lines follow a backslash-terminated line starting a
451 statement."
452 :group 'python
453 :type 'integer)
454
455
456 (defcustom python-default-interpreter 'cpython
457 "*Which Python interpreter is used by default.
458 The value for this variable can be either `cpython' or `jpython'.
459
460 When the value is `cpython', the variables `python-python-command' and
461 `python-python-command-args' are consulted to determine the interpreter
462 and arguments to use.
463
464 When the value is `jpython', the variables `python-jpython-command' and
465 `python-jpython-command-args' are consulted to determine the interpreter
466 and arguments to use.
467
468 Note that this variable is consulted only the first time that a Python
469 mode buffer is visited during an Emacs session. After that, use
470 \\[python-toggle-shells] to change the interpreter shell."
471 :type '(choice (const :tag "Python (a.k.a. CPython)" cpython)
472 (const :tag "JPython" jpython))
473 :group 'python)
474
475 (defcustom python-python-command-args '("-i")
476 "*List of string arguments to be used when starting a Python shell."
477 :type '(repeat string)
478 :group 'python)
479
480 (defcustom python-jython-command-args '("-i")
481 "*List of string arguments to be used when starting a Jython shell."
482 :type '(repeat string)
483 :group 'python
484 :tag "JPython Command Args")
485
486 ;; for toggling between CPython and JPython
487 (defvar python-which-shell nil)
488 (defvar python-which-args python-python-command-args)
489 (defvar python-which-bufname "Python")
490 (make-variable-buffer-local 'python-which-shell)
491 (make-variable-buffer-local 'python-which-args)
492 (make-variable-buffer-local 'python-which-bufname)
493
494 (defcustom python-pdbtrack-do-tracking-p t
495 "*Controls whether the pdbtrack feature is enabled or not.
496 When non-nil, pdbtrack is enabled in all comint-based buffers,
497 e.g. shell buffers and the *Python* buffer. When using pdb to debug a
498 Python program, pdbtrack notices the pdb prompt and displays the
499 source file and line that the program is stopped at, much the same way
500 as gud-mode does for debugging C programs with gdb."
501 :type 'boolean
502 :group 'python)
503 (make-variable-buffer-local 'python-pdbtrack-do-tracking-p)
504
505 ;; Bind python-file-queue before installing the kill-emacs-hook.
506 (defvar python-file-queue nil
507 "Queue of Python temp files awaiting execution.
508 Currently-active file is at the head of the list.")
509
510 (defvar python-pdbtrack-is-tracking-p nil)
511
512 (defconst python-pdbtrack-stack-entry-regexp
513 "> \\([^(]+\\)(\\([0-9]+\\))[?a-zA-Z0-9_]+()"
514 "Regular expression pdbtrack uses to find a stack trace entry.")
515
516 (defconst python-pdbtrack-input-prompt "\n[(<]?pdb[>)]? "
517 "Regular expression pdbtrack uses to recognize a pdb prompt.")
518
519 (defconst python-pdbtrack-track-range 10000
520 "Max number of characters from end of buffer to search for stack entry.")
521
522 (defun python-guess-indent ()
523 "Guess step for indentation of current buffer.
524 Set `python-indent' locally to the value guessed."
525 (interactive)
526 (save-excursion
527 (save-restriction
528 (widen)
529 (goto-char (point-min))
530 (let (done indent)
531 (while (and (not done) (not (eobp)))
532 (when (and (re-search-forward (rx ?: (0+ space)
533 (or (syntax comment-start)
534 line-end))
535 nil 'move)
536 (python-open-block-statement-p))
537 (save-excursion
538 (python-beginning-of-statement)
539 (let ((initial (current-indentation)))
540 (if (zerop (python-next-statement))
541 (setq indent (- (current-indentation) initial)))
542 (if (and indent (>= indent 2) (<= indent 8)) ; sanity check
543 (setq done t))))))
544 (when done
545 (when (/= indent (default-value 'python-indent))
546 (set (make-local-variable 'python-indent) indent)
547 (unless (= tab-width python-indent)
548 (setq indent-tabs-mode nil)))
549 indent)))))
550
551 ;; Alist of possible indentations and start of statement they would
552 ;; close. Used in indentation cycling (below).
553 (defvar python-indent-list nil
554 "Internal use.")
555 ;; Length of the above
556 (defvar python-indent-list-length nil
557 "Internal use.")
558 ;; Current index into the alist.
559 (defvar python-indent-index nil
560 "Internal use.")
561
562 (defun python-calculate-indentation ()
563 "Calculate Python indentation for line at point."
564 (setq python-indent-list nil
565 python-indent-list-length 1)
566 (save-excursion
567 (beginning-of-line)
568 (let ((syntax (syntax-ppss))
569 start)
570 (cond
571 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
572 (if (not python-indent-string-contents)
573 (current-indentation)
574 ;; Only respect `python-indent-string-contents' in doc
575 ;; strings (defined as those which form statements).
576 (if (not (save-excursion
577 (python-beginning-of-statement)
578 (looking-at (rx (or (syntax string-delimiter)
579 (syntax string-quote))))))
580 (current-indentation)
581 ;; Find indentation of preceding non-blank line within string.
582 (setq start (nth 8 syntax))
583 (forward-line -1)
584 (while (and (< start (point)) (looking-at "\\s-*$"))
585 (forward-line -1))
586 (current-indentation))))
587 ((python-continuation-line-p) ; after backslash, or bracketed
588 (let ((point (point))
589 (open-start (cadr syntax))
590 (backslash (python-backslash-continuation-line-p))
591 (colon (eq ?: (char-before (1- (line-beginning-position))))))
592 (if open-start
593 ;; Inside bracketed expression.
594 (progn
595 (goto-char (1+ open-start))
596 ;; Look for first item in list (preceding point) and
597 ;; align with it, if found.
598 (if (with-syntax-table python-space-backslash-table
599 (let ((parse-sexp-ignore-comments t))
600 (condition-case ()
601 (progn (forward-sexp)
602 (backward-sexp)
603 (< (point) point))
604 (error nil))))
605 ;; Extra level if we're backslash-continued or
606 ;; following a key.
607 (if (or backslash colon)
608 (+ python-indent (current-column))
609 (current-column))
610 ;; Otherwise indent relative to statement start, one
611 ;; level per bracketing level.
612 (goto-char (1+ open-start))
613 (python-beginning-of-statement)
614 (+ (current-indentation) (* (car syntax) python-indent))))
615 ;; Otherwise backslash-continued.
616 (forward-line -1)
617 (if (python-continuation-line-p)
618 ;; We're past first continuation line. Align with
619 ;; previous line.
620 (current-indentation)
621 ;; First continuation line. Indent one step, with an
622 ;; extra one if statement opens a block.
623 (python-beginning-of-statement)
624 (+ (current-indentation) python-continuation-offset
625 (if (python-open-block-statement-p t)
626 python-indent
627 0))))))
628 ((bobp) 0)
629 ;; Fixme: Like python-mode.el; not convinced by this.
630 ((looking-at (rx (0+ space) (syntax comment-start)
631 (not (any " \t\n")))) ; non-indentable comment
632 (current-indentation))
633 (t (if python-honour-comment-indentation
634 ;; Back over whitespace, newlines, non-indentable comments.
635 (catch 'done
636 (while t
637 (if (cond ((bobp))
638 ;; not at comment start
639 ((not (forward-comment -1))
640 (python-beginning-of-statement)
641 t)
642 ;; trailing comment
643 ((/= (current-column) (current-indentation))
644 (python-beginning-of-statement)
645 t)
646 ;; indentable comment like python-mode.el
647 ((and (looking-at (rx (syntax comment-start)
648 (or space line-end)))
649 (/= 0 (current-column)))))
650 (throw 'done t)))))
651 (python-indentation-levels)
652 ;; Prefer to indent comments with an immediately-following
653 ;; statement, e.g.
654 ;; ...
655 ;; # ...
656 ;; def ...
657 (when (and (> python-indent-list-length 1)
658 (python-comment-line-p))
659 (forward-line)
660 (unless (python-comment-line-p)
661 (let ((elt (assq (current-indentation) python-indent-list)))
662 (setq python-indent-list
663 (nconc (delete elt python-indent-list)
664 (list elt))))))
665 (caar (last python-indent-list)))))))
666
667 ;;;; Cycling through the possible indentations with successive TABs.
668
669 ;; These don't need to be buffer-local since they're only relevant
670 ;; during a cycle.
671
672 (defun python-initial-text ()
673 "Text of line following indentation and ignoring any trailing comment."
674 (save-excursion
675 (buffer-substring (progn
676 (back-to-indentation)
677 (point))
678 (progn
679 (end-of-line)
680 (forward-comment -1)
681 (point)))))
682
683 (defconst python-block-pairs
684 '(("else" "if" "elif" "while" "for" "try" "except")
685 ("elif" "if" "elif")
686 ("except" "try" "except")
687 ("finally" "try"))
688 "Alist of keyword matches.
689 The car of an element is a keyword introducing a statement which
690 can close a block opened by a keyword in the cdr.")
691
692 (defun python-first-word ()
693 "Return first word (actually symbol) on the line."
694 (save-excursion
695 (back-to-indentation)
696 (current-word t)))
697
698 (defun python-indentation-levels ()
699 "Return a list of possible indentations for this line.
700 It is assumed not to be a continuation line or in a multi-line string.
701 Includes the default indentation and those which would close all
702 enclosing blocks. Elements of the list are actually pairs:
703 \(INDENTATION . TEXT), where TEXT is the initial text of the
704 corresponding block opening (or nil)."
705 (save-excursion
706 (let ((initial "")
707 levels indent)
708 ;; Only one possibility immediately following a block open
709 ;; statement, assuming it doesn't have a `suite' on the same line.
710 (cond
711 ((save-excursion (and (python-previous-statement)
712 (python-open-block-statement-p t)
713 (setq indent (current-indentation))
714 ;; Check we don't have something like:
715 ;; if ...: ...
716 (if (progn (python-end-of-statement)
717 (python-skip-comments/blanks t)
718 (eq ?: (char-before)))
719 (setq indent (+ python-indent indent)))))
720 (push (cons indent initial) levels))
721 ;; Only one possibility for comment line immediately following
722 ;; another.
723 ((save-excursion
724 (when (python-comment-line-p)
725 (forward-line -1)
726 (if (python-comment-line-p)
727 (push (cons (current-indentation) initial) levels)))))
728 ;; Fixme: Maybe have a case here which indents (only) first
729 ;; line after a lambda.
730 (t
731 (let ((start (car (assoc (python-first-word) python-block-pairs))))
732 (python-previous-statement)
733 ;; Is this a valid indentation for the line of interest?
734 (unless (or (if start ; potentially only outdentable
735 ;; Check for things like:
736 ;; if ...: ...
737 ;; else ...:
738 ;; where the second line need not be outdented.
739 (not (member (python-first-word)
740 (cdr (assoc start
741 python-block-pairs)))))
742 ;; Not sensible to indent to the same level as
743 ;; previous `return' &c.
744 (python-close-block-statement-p))
745 (push (cons (current-indentation) (python-initial-text))
746 levels))
747 (while (python-beginning-of-block)
748 (when (or (not start)
749 (member (python-first-word)
750 (cdr (assoc start python-block-pairs))))
751 (push (cons (current-indentation) (python-initial-text))
752 levels))))))
753 (prog1 (or levels (setq levels '((0 . ""))))
754 (setq python-indent-list levels
755 python-indent-list-length (length python-indent-list))))))
756
757 ;; This is basically what `python-indent-line' would be if we didn't
758 ;; do the cycling.
759 (defun python-indent-line-1 (&optional leave)
760 "Subroutine of `python-indent-line'.
761 Does non-repeated indentation. LEAVE non-nil means leave
762 indentation if it is valid, i.e. one of the positions returned by
763 `python-calculate-indentation'."
764 (let ((target (python-calculate-indentation))
765 (pos (- (point-max) (point))))
766 (if (or (= target (current-indentation))
767 ;; Maybe keep a valid indentation.
768 (and leave python-indent-list
769 (assq (current-indentation) python-indent-list)))
770 (if (< (current-column) (current-indentation))
771 (back-to-indentation))
772 (beginning-of-line)
773 (delete-horizontal-space)
774 (indent-to target)
775 (if (> (- (point-max) pos) (point))
776 (goto-char (- (point-max) pos))))))
777
778 (defun python-indent-line ()
779 "Indent current line as Python code.
780 When invoked via `indent-for-tab-command', cycle through possible
781 indentations for current line. The cycle is broken by a command
782 different from `indent-for-tab-command', i.e. successive TABs do
783 the cycling."
784 (interactive)
785 (if (and (eq this-command 'indent-for-tab-command)
786 (eq last-command this-command))
787 (if (= 1 python-indent-list-length)
788 (message "Sole indentation")
789 (progn (setq python-indent-index
790 (% (1+ python-indent-index) python-indent-list-length))
791 (beginning-of-line)
792 (delete-horizontal-space)
793 (indent-to (car (nth python-indent-index python-indent-list)))
794 (if (python-block-end-p)
795 (let ((text (cdr (nth python-indent-index
796 python-indent-list))))
797 (if text
798 (message "Closes: %s" text))))))
799 (python-indent-line-1)
800 (setq python-indent-index (1- python-indent-list-length))))
801
802 (defun python-indent-region (start end)
803 "`indent-region-function' for Python.
804 Leaves validly-indented lines alone, i.e. doesn't indent to
805 another valid position."
806 (save-excursion
807 (goto-char end)
808 (setq end (point-marker))
809 (goto-char start)
810 (or (bolp) (forward-line 1))
811 (while (< (point) end)
812 (or (and (bolp) (eolp))
813 (python-indent-line-1 t))
814 (forward-line 1))
815 (move-marker end nil)))
816
817 (defun python-block-end-p ()
818 "Non-nil if this is a line in a statement closing a block,
819 or a blank line indented to where it would close a block."
820 (and (not (python-comment-line-p))
821 (or (python-close-block-statement-p t)
822 (< (current-indentation)
823 (save-excursion
824 (python-previous-statement)
825 (current-indentation))))))
826 \f
827 ;;;; Movement.
828
829 ;; Fixme: Define {for,back}ward-sexp-function? Maybe skip units like
830 ;; block, statement, depending on context.
831
832 (defun python-beginning-of-defun ()
833 "`beginning-of-defun-function' for Python.
834 Finds beginning of innermost nested class or method definition.
835 Returns the name of the definition found at the end, or nil if
836 reached start of buffer."
837 (let ((ci (current-indentation))
838 (def-re (rx line-start (0+ space) (or "def" "class") (1+ space)
839 (group (1+ (or word (syntax symbol))))))
840 found lep) ;; def-line
841 (if (python-comment-line-p)
842 (setq ci most-positive-fixnum))
843 (while (and (not (bobp)) (not found))
844 ;; Treat bol at beginning of function as outside function so
845 ;; that successive C-M-a makes progress backwards.
846 ;;(setq def-line (looking-at def-re))
847 (unless (bolp) (end-of-line))
848 (setq lep (line-end-position))
849 (if (and (re-search-backward def-re nil 'move)
850 ;; Must be less indented or matching top level, or
851 ;; equally indented if we started on a definition line.
852 (let ((in (current-indentation)))
853 (or (and (zerop ci) (zerop in))
854 (= lep (line-end-position)) ; on initial line
855 ;; Not sure why it was like this -- fails in case of
856 ;; last internal function followed by first
857 ;; non-def statement of the main body.
858 ;;(and def-line (= in ci))
859 (= in ci)
860 (< in ci)))
861 (not (python-in-string/comment)))
862 (setq found t)))))
863
864 (defun python-end-of-defun ()
865 "`end-of-defun-function' for Python.
866 Finds end of innermost nested class or method definition."
867 (let ((orig (point))
868 (pattern (rx line-start (0+ space) (or "def" "class") space)))
869 ;; Go to start of current block and check whether it's at top
870 ;; level. If it is, and not a block start, look forward for
871 ;; definition statement.
872 (when (python-comment-line-p)
873 (end-of-line)
874 (forward-comment most-positive-fixnum))
875 (if (not (python-open-block-statement-p))
876 (python-beginning-of-block))
877 (if (zerop (current-indentation))
878 (unless (python-open-block-statement-p)
879 (while (and (re-search-forward pattern nil 'move)
880 (python-in-string/comment))) ; just loop
881 (unless (eobp)
882 (beginning-of-line)))
883 ;; Don't move before top-level statement that would end defun.
884 (end-of-line)
885 (python-beginning-of-defun))
886 ;; If we got to the start of buffer, look forward for
887 ;; definition statement.
888 (if (and (bobp) (not (looking-at "def\\|class")))
889 (while (and (not (eobp))
890 (re-search-forward pattern nil 'move)
891 (python-in-string/comment)))) ; just loop
892 ;; We're at a definition statement (or end-of-buffer).
893 (unless (eobp)
894 (python-end-of-block)
895 ;; Count trailing space in defun (but not trailing comments).
896 (skip-syntax-forward " >")
897 (unless (eobp) ; e.g. missing final newline
898 (beginning-of-line)))
899 ;; Catch pathological cases like this, where the beginning-of-defun
900 ;; skips to a definition we're not in:
901 ;; if ...:
902 ;; ...
903 ;; else:
904 ;; ... # point here
905 ;; ...
906 ;; def ...
907 (if (< (point) orig)
908 (goto-char (point-max)))))
909
910 (defun python-beginning-of-statement ()
911 "Go to start of current statement.
912 Accounts for continuation lines, multi-line strings, and
913 multi-line bracketed expressions."
914 (beginning-of-line)
915 (python-beginning-of-string)
916 (while (python-continuation-line-p)
917 (beginning-of-line)
918 (if (python-backslash-continuation-line-p)
919 (progn
920 (forward-line -1)
921 (while (python-backslash-continuation-line-p)
922 (forward-line -1)))
923 (python-beginning-of-string)
924 (python-skip-out)))
925 (back-to-indentation))
926
927 (defun python-skip-out (&optional forward syntax)
928 "Skip out of any nested brackets.
929 Skip forward if FORWARD is non-nil, else backward.
930 If SYNTAX is non-nil it is the state returned by `syntax-ppss' at point.
931 Return non-nil iff skipping was done."
932 (let ((depth (syntax-ppss-depth (or syntax (syntax-ppss))))
933 (forward (if forward -1 1)))
934 (unless (zerop depth)
935 (if (> depth 0)
936 ;; Skip forward out of nested brackets.
937 (condition-case () ; beware invalid syntax
938 (progn (backward-up-list (* forward depth)) t)
939 (error nil))
940 ;; Invalid syntax (too many closed brackets).
941 ;; Skip out of as many as possible.
942 (let (done)
943 (while (condition-case ()
944 (progn (backward-up-list forward)
945 (setq done t))
946 (error nil)))
947 done)))))
948
949 (defun python-end-of-statement ()
950 "Go to the end of the current statement and return point.
951 Usually this is the start of the next line, but if this is a
952 multi-line statement we need to skip over the continuation lines.
953 On a comment line, go to end of line."
954 (end-of-line)
955 (while (let (comment)
956 ;; Move past any enclosing strings and sexps, or stop if
957 ;; we're in a comment.
958 (while (let ((s (syntax-ppss)))
959 (cond ((eq 'comment (syntax-ppss-context s))
960 (setq comment t)
961 nil)
962 ((eq 'string (syntax-ppss-context s))
963 ;; Go to start of string and skip it.
964 (let ((pos (point)))
965 (goto-char (nth 8 s))
966 (condition-case () ; beware invalid syntax
967 (progn (forward-sexp) t)
968 ;; If there's a mismatched string, make sure
969 ;; we still overall move *forward*.
970 (error (goto-char pos) (end-of-line)))))
971 ((python-skip-out t s))))
972 (end-of-line))
973 (unless comment
974 (eq ?\\ (char-before)))) ; Line continued?
975 (end-of-line 2)) ; Try next line.
976 (point))
977
978 (defun python-previous-statement (&optional count)
979 "Go to start of previous statement.
980 With argument COUNT, do it COUNT times. Stop at beginning of buffer.
981 Return count of statements left to move."
982 (interactive "p")
983 (unless count (setq count 1))
984 (if (< count 0)
985 (python-next-statement (- count))
986 (python-beginning-of-statement)
987 (while (and (> count 0) (not (bobp)))
988 (python-skip-comments/blanks t)
989 (python-beginning-of-statement)
990 (unless (bobp) (setq count (1- count))))
991 count))
992
993 (defun python-next-statement (&optional count)
994 "Go to start of next statement.
995 With argument COUNT, do it COUNT times. Stop at end of buffer.
996 Return count of statements left to move."
997 (interactive "p")
998 (unless count (setq count 1))
999 (if (< count 0)
1000 (python-previous-statement (- count))
1001 (beginning-of-line)
1002 (while (and (> count 0) (not (eobp)))
1003 (python-end-of-statement)
1004 (python-skip-comments/blanks)
1005 (unless (eobp)
1006 (setq count (1- count))))
1007 count))
1008
1009 (defun python-beginning-of-block (&optional arg)
1010 "Go to start of current block.
1011 With numeric arg, do it that many times. If ARG is negative, call
1012 `python-end-of-block' instead.
1013 If point is on the first line of a block, use its outer block.
1014 If current statement is in column zero, don't move and return nil.
1015 Otherwise return non-nil."
1016 (interactive "p")
1017 (unless arg (setq arg 1))
1018 (cond
1019 ((zerop arg))
1020 ((< arg 0) (python-end-of-block (- arg)))
1021 (t
1022 (let ((point (point)))
1023 (if (or (python-comment-line-p)
1024 (python-blank-line-p))
1025 (python-skip-comments/blanks t))
1026 (python-beginning-of-statement)
1027 (let ((ci (current-indentation)))
1028 (if (zerop ci)
1029 (not (goto-char point)) ; return nil
1030 ;; Look upwards for less indented statement.
1031 (if (catch 'done
1032 ;;; This is slower than the below.
1033 ;;; (while (zerop (python-previous-statement))
1034 ;;; (when (and (< (current-indentation) ci)
1035 ;;; (python-open-block-statement-p t))
1036 ;;; (beginning-of-line)
1037 ;;; (throw 'done t)))
1038 (while (and (zerop (forward-line -1)))
1039 (when (and (< (current-indentation) ci)
1040 (not (python-comment-line-p))
1041 ;; Move to beginning to save effort in case
1042 ;; this is in string.
1043 (progn (python-beginning-of-statement) t)
1044 (python-open-block-statement-p t))
1045 (beginning-of-line)
1046 (throw 'done t)))
1047 (not (goto-char point))) ; Failed -- return nil
1048 (python-beginning-of-block (1- arg)))))))))
1049
1050 (defun python-end-of-block (&optional arg)
1051 "Go to end of current block.
1052 With numeric arg, do it that many times. If ARG is negative,
1053 call `python-beginning-of-block' instead.
1054 If current statement is in column zero and doesn't open a block,
1055 don't move and return nil. Otherwise return t."
1056 (interactive "p")
1057 (unless arg (setq arg 1))
1058 (if (< arg 0)
1059 (python-beginning-of-block (- arg))
1060 (while (and (> arg 0)
1061 (let* ((point (point))
1062 (_ (if (python-comment-line-p)
1063 (python-skip-comments/blanks t)))
1064 (ci (current-indentation))
1065 (open (python-open-block-statement-p)))
1066 (if (and (zerop ci) (not open))
1067 (not (goto-char point))
1068 (catch 'done
1069 (while (zerop (python-next-statement))
1070 (when (or (and open (<= (current-indentation) ci))
1071 (< (current-indentation) ci))
1072 (python-skip-comments/blanks t)
1073 (beginning-of-line 2)
1074 (throw 'done t)))))))
1075 (setq arg (1- arg)))
1076 (zerop arg)))
1077
1078 (defvar python-which-func-length-limit 40
1079 "Non-strict length limit for `python-which-func' output.")
1080
1081 (defun python-which-func ()
1082 (let ((function-name (python-current-defun python-which-func-length-limit)))
1083 (set-text-properties 0 (length function-name) nil function-name)
1084 function-name))
1085
1086
1087 ;;;; Imenu.
1088
1089 (defvar python-recursing)
1090 (defun python-imenu-create-index ()
1091 "`imenu-create-index-function' for Python.
1092
1093 Makes nested Imenu menus from nested `class' and `def' statements.
1094 The nested menus are headed by an item referencing the outer
1095 definition; it has a space prepended to the name so that it sorts
1096 first with `imenu--sort-by-name' (though, unfortunately, sub-menus
1097 precede it)."
1098 (unless (boundp 'python-recursing) ; dynamically bound below
1099 ;; Normal call from Imenu.
1100 (goto-char (point-min))
1101 ;; Without this, we can get an infloop if the buffer isn't all
1102 ;; fontified. I guess this is really a bug in syntax.el. OTOH,
1103 ;; _with_ this, imenu doesn't immediately work; I can't figure out
1104 ;; what's going on, but it must be something to do with timers in
1105 ;; font-lock.
1106 ;; This can't be right, especially not when jit-lock is not used. --Stef
1107 ;; (unless (get-text-property (1- (point-max)) 'fontified)
1108 ;; (font-lock-fontify-region (point-min) (point-max)))
1109 )
1110 (let (index-alist) ; accumulated value to return
1111 (while (re-search-forward
1112 (rx line-start (0+ space) ; leading space
1113 (or (group "def") (group "class")) ; type
1114 (1+ space) (group (1+ (or word ?_)))) ; name
1115 nil t)
1116 (unless (python-in-string/comment)
1117 (let ((pos (match-beginning 0))
1118 (name (match-string-no-properties 3)))
1119 (if (match-beginning 2) ; def or class?
1120 (setq name (concat "class " name)))
1121 (save-restriction
1122 (narrow-to-defun)
1123 (let* ((python-recursing t)
1124 (sublist (python-imenu-create-index)))
1125 (if sublist
1126 (progn (push (cons (concat " " name) pos) sublist)
1127 (push (cons name sublist) index-alist))
1128 (push (cons name pos) index-alist)))))))
1129 (unless (boundp 'python-recursing)
1130 ;; Look for module variables.
1131 (let (vars)
1132 (goto-char (point-min))
1133 (while (re-search-forward
1134 (rx line-start (group (1+ (or word ?_))) (0+ space) "=")
1135 nil t)
1136 (unless (python-in-string/comment)
1137 (push (cons (match-string 1) (match-beginning 1))
1138 vars)))
1139 (setq index-alist (nreverse index-alist))
1140 (if vars
1141 (push (cons "Module variables"
1142 (nreverse vars))
1143 index-alist))))
1144 index-alist))
1145 \f
1146 ;;;; `Electric' commands.
1147
1148 (defun python-electric-colon (arg)
1149 "Insert a colon and maybe outdent the line if it is a statement like `else'.
1150 With numeric ARG, just insert that many colons. With \\[universal-argument],
1151 just insert a single colon."
1152 (interactive "*P")
1153 (self-insert-command (if (not (integerp arg)) 1 arg))
1154 (and (not arg)
1155 (eolp)
1156 (python-outdent-p)
1157 (not (python-in-string/comment))
1158 (> (current-indentation) (python-calculate-indentation))
1159 (python-indent-line))) ; OK, do it
1160 (put 'python-electric-colon 'delete-selection t)
1161
1162 (defun python-backspace (arg)
1163 "Maybe delete a level of indentation on the current line.
1164 Do so if point is at the end of the line's indentation outside
1165 strings and comments.
1166 Otherwise just call `backward-delete-char-untabify'.
1167 Repeat ARG times."
1168 (interactive "*p")
1169 (if (or (/= (current-indentation) (current-column))
1170 (bolp)
1171 (python-continuation-line-p)
1172 (python-in-string/comment))
1173 (backward-delete-char-untabify arg)
1174 ;; Look for the largest valid indentation which is smaller than
1175 ;; the current indentation.
1176 (let ((indent 0)
1177 (ci (current-indentation))
1178 (indents (python-indentation-levels))
1179 initial)
1180 (dolist (x indents)
1181 (if (< (car x) ci)
1182 (setq indent (max indent (car x)))))
1183 (setq initial (cdr (assq indent indents)))
1184 (if (> (length initial) 0)
1185 (message "Closes %s" initial))
1186 (delete-horizontal-space)
1187 (indent-to indent))))
1188 (put 'python-backspace 'delete-selection 'supersede)
1189 \f
1190 ;;;; pychecker
1191
1192 (defcustom python-check-command "pychecker --stdlib"
1193 "Command used to check a Python file."
1194 :type 'string
1195 :group 'python)
1196
1197 (defvar python-saved-check-command nil
1198 "Internal use.")
1199
1200 ;; After `sgml-validate-command'.
1201 (defun python-check (command)
1202 "Check a Python file (default current buffer's file).
1203 Runs COMMAND, a shell command, as if by `compile'.
1204 See `python-check-command' for the default."
1205 (interactive
1206 (list (read-string "Checker command: "
1207 (or python-saved-check-command
1208 (concat python-check-command " "
1209 (let ((name (buffer-file-name)))
1210 (if name
1211 (file-name-nondirectory name))))))))
1212 (setq python-saved-check-command command)
1213 (require 'compile) ;To define compilation-* variables.
1214 (save-some-buffers (not compilation-ask-about-save) nil)
1215 (let ((compilation-error-regexp-alist
1216 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
1217 compilation-error-regexp-alist)))
1218 (compilation-start command)))
1219 \f
1220 ;;;; Inferior mode stuff (following cmuscheme).
1221
1222 ;; Fixme: Make sure we can work with IPython.
1223
1224 (defcustom python-python-command "python"
1225 "Shell command to run Python interpreter.
1226 Any arguments can't contain whitespace.
1227 Note that IPython may not work properly; it must at least be used
1228 with the `-cl' flag, i.e. use `ipython -cl'."
1229 :group 'python
1230 :type 'string)
1231
1232 (defcustom python-jython-command "jython"
1233 "Shell command to run Jython interpreter.
1234 Any arguments can't contain whitespace."
1235 :group 'python
1236 :type 'string)
1237
1238 (defvar python-command python-python-command
1239 "Actual command used to run Python.
1240 May be `python-python-command' or `python-jython-command', possibly
1241 modified by the user. Additional arguments are added when the command
1242 is used by `run-python' et al.")
1243
1244 (defvar python-buffer nil
1245 "*The current Python process buffer.
1246
1247 Commands that send text from source buffers to Python processes have
1248 to choose a process to send to. This is determined by buffer-local
1249 value of `python-buffer'. If its value in the current buffer,
1250 i.e. both any local value and the default one, is nil, `run-python'
1251 and commands that send to the Python process will start a new process.
1252
1253 Whenever \\[run-python] starts a new process, it resets the default
1254 value of `python-buffer' to be the new process's buffer and sets the
1255 buffer-local value similarly if the current buffer is in Python mode
1256 or Inferior Python mode, so that source buffer stays associated with a
1257 specific sub-process.
1258
1259 Use \\[python-set-proc] to set the default value from a buffer with a
1260 local value.")
1261 (make-variable-buffer-local 'python-buffer)
1262
1263 (defconst python-compilation-regexp-alist
1264 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
1265 ;; The first already is (for CAML), but the second isn't. Anyhow,
1266 ;; these are specific to the inferior buffer. -- fx
1267 `((,(rx line-start (1+ (any " \t")) "File \""
1268 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1269 "\", line " (group (1+ digit)))
1270 1 2)
1271 (,(rx " in file " (group (1+ not-newline)) " on line "
1272 (group (1+ digit)))
1273 1 2)
1274 ;; pdb stack trace
1275 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1276 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1277 1 2))
1278 "`compilation-error-regexp-alist' for inferior Python.")
1279
1280 (defvar inferior-python-mode-map
1281 (let ((map (make-sparse-keymap)))
1282 ;; This will inherit from comint-mode-map.
1283 (define-key map "\C-c\C-l" 'python-load-file)
1284 (define-key map "\C-c\C-v" 'python-check)
1285 ;; Note that we _can_ still use these commands which send to the
1286 ;; Python process even at the prompt iff we have a normal prompt,
1287 ;; i.e. '>>> ' and not '... '. See the comment before
1288 ;; python-send-region. Fixme: uncomment these if we address that.
1289
1290 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1291 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1292 map))
1293
1294 (defvar inferior-python-mode-syntax-table
1295 (let ((st (make-syntax-table python-mode-syntax-table)))
1296 ;; Don't get confused by apostrophes in the process's output (e.g. if
1297 ;; you execute "help(os)").
1298 (modify-syntax-entry ?\' "." st)
1299 ;; Maybe we should do the same for double quotes?
1300 ;; (modify-syntax-entry ?\" "." st)
1301 st))
1302
1303 ;; Autoloaded.
1304 (declare-function compilation-shell-minor-mode "compile" (&optional arg))
1305
1306 ;; Fixme: This should inherit some stuff from `python-mode', but I'm
1307 ;; not sure how much: at least some keybindings, like C-c C-f;
1308 ;; syntax?; font-locking, e.g. for triple-quoted strings?
1309 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1310 "Major mode for interacting with an inferior Python process.
1311 A Python process can be started with \\[run-python].
1312
1313 Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1314 that order.
1315
1316 You can send text to the inferior Python process from other buffers
1317 containing Python source.
1318 * \\[python-switch-to-python] switches the current buffer to the Python
1319 process buffer.
1320 * \\[python-send-region] sends the current region to the Python process.
1321 * \\[python-send-region-and-go] switches to the Python process buffer
1322 after sending the text.
1323 For running multiple processes in multiple buffers, see `run-python' and
1324 `python-buffer'.
1325
1326 \\{inferior-python-mode-map}"
1327 :group 'python
1328 (setq mode-line-process '(":%s"))
1329 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
1330 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1331 nil t)
1332 ;; Still required by `comint-redirect-send-command', for instance
1333 ;; (and we need to match things like `>>> ... >>> '):
1334 (set (make-local-variable 'comint-prompt-regexp)
1335 (rx line-start (1+ (and (or (repeat 3 (any ">.")) "(Pdb)") " "))))
1336 (set (make-local-variable 'compilation-error-regexp-alist)
1337 python-compilation-regexp-alist)
1338 (compilation-shell-minor-mode 1))
1339
1340 (defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1341 "Input matching this regexp is not saved on the history list.
1342 Default ignores all inputs of 0, 1, or 2 non-blank characters."
1343 :type 'regexp
1344 :group 'python)
1345
1346 (defun python-input-filter (str)
1347 "`comint-input-filter' function for inferior Python.
1348 Don't save anything for STR matching `inferior-python-filter-regexp'."
1349 (not (string-match inferior-python-filter-regexp str)))
1350
1351 ;; Fixme: Loses with quoted whitespace.
1352 (defun python-args-to-list (string)
1353 (let ((where (string-match "[ \t]" string)))
1354 (cond ((null where) (list string))
1355 ((not (= where 0))
1356 (cons (substring string 0 where)
1357 (python-args-to-list (substring string (+ 1 where)))))
1358 (t (let ((pos (string-match "[^ \t]" string)))
1359 (if pos (python-args-to-list (substring string pos))))))))
1360
1361 (defvar python-preoutput-result nil
1362 "Data from last `_emacs_out' line seen by the preoutput filter.")
1363
1364 (defvar python-preoutput-leftover nil)
1365 (defvar python-preoutput-skip-next-prompt nil)
1366
1367 ;; Using this stops us getting lines in the buffer like
1368 ;; >>> ... ... >>>
1369 (defun python-preoutput-filter (s)
1370 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
1371 (when python-preoutput-leftover
1372 (setq s (concat python-preoutput-leftover s))
1373 (setq python-preoutput-leftover nil))
1374 (let ((start 0)
1375 (res ""))
1376 ;; First process whole lines.
1377 (while (string-match "\n" s start)
1378 (let ((line (substring s start (setq start (match-end 0)))))
1379 ;; Skip prompt if needed.
1380 (when (and python-preoutput-skip-next-prompt
1381 (string-match comint-prompt-regexp line))
1382 (setq python-preoutput-skip-next-prompt nil)
1383 (setq line (substring line (match-end 0))))
1384 ;; Recognize special _emacs_out lines.
1385 (if (and (string-match "\\`_emacs_out \\(.*\\)\n\\'" line)
1386 (local-variable-p 'python-preoutput-result))
1387 (progn
1388 (setq python-preoutput-result (match-string 1 line))
1389 (set (make-local-variable 'python-preoutput-skip-next-prompt) t))
1390 (setq res (concat res line)))))
1391 ;; Then process the remaining partial line.
1392 (unless (zerop start) (setq s (substring s start)))
1393 (cond ((and (string-match comint-prompt-regexp s)
1394 ;; Drop this prompt if it follows an _emacs_out...
1395 (or python-preoutput-skip-next-prompt
1396 ;; ... or if it's not gonna be inserted at BOL.
1397 ;; Maybe we could be more selective here.
1398 (if (zerop (length res))
1399 (not (bolp))
1400 (string-match ".\\'" res))))
1401 ;; The need for this seems to be system-dependent:
1402 ;; What is this all about, exactly? --Stef
1403 ;; (if (and (eq ?. (aref s 0)))
1404 ;; (accept-process-output (get-buffer-process (current-buffer)) 1))
1405 (setq python-preoutput-skip-next-prompt nil)
1406 res)
1407 ((let ((end (min (length "_emacs_out ") (length s))))
1408 (eq t (compare-strings s nil end "_emacs_out " nil end)))
1409 ;; The leftover string is a prefix of _emacs_out so we don't know
1410 ;; yet whether it's an _emacs_out or something else: wait until we
1411 ;; get more output so we can resolve this ambiguity.
1412 (set (make-local-variable 'python-preoutput-leftover) s)
1413 res)
1414 (t (concat res s)))))
1415
1416 (autoload 'comint-check-proc "comint")
1417
1418 ;;;###autoload
1419 (defun run-python (&optional cmd noshow new)
1420 "Run an inferior Python process, input and output via buffer *Python*.
1421 CMD is the Python command to run. NOSHOW non-nil means don't show the
1422 buffer automatically.
1423
1424 Normally, if there is a process already running in `python-buffer',
1425 switch to that buffer. Interactively, a prefix arg allows you to edit
1426 the initial command line (default is `python-command'); `-i' etc. args
1427 will be added to this as appropriate. A new process is started if:
1428 one isn't running attached to `python-buffer', or interactively the
1429 default `python-command', or argument NEW is non-nil. See also the
1430 documentation for `python-buffer'.
1431
1432 Runs the hook `inferior-python-mode-hook' \(after the
1433 `comint-mode-hook' is run). \(Type \\[describe-mode] in the process
1434 buffer for a list of commands.)"
1435 (interactive (if current-prefix-arg
1436 (list (read-string "Run Python: " python-command) nil t)
1437 (list python-command)))
1438 (unless cmd (setq cmd python-python-command))
1439 (setq python-command cmd)
1440 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1441 ;; (not a name) in Python buffers from which `run-python' &c is
1442 ;; invoked. Would support multiple processes better.
1443 (when (or new (not (comint-check-proc python-buffer)))
1444 (with-current-buffer
1445 (let* ((cmdlist (append (python-args-to-list cmd) '("-i")))
1446 (path (getenv "PYTHONPATH"))
1447 (process-environment ; to import emacs.py
1448 (cons (concat "PYTHONPATH=" data-directory
1449 (if path (concat path-separator path)))
1450 process-environment)))
1451 (apply 'make-comint-in-buffer "Python"
1452 (if new (generate-new-buffer "*Python*") "*Python*")
1453 (car cmdlist) nil (cdr cmdlist)))
1454 (setq-default python-buffer (current-buffer))
1455 (setq python-buffer (current-buffer))
1456 (accept-process-output (get-buffer-process python-buffer) 5)
1457 (inferior-python-mode)
1458 ;; Load function definitions we need.
1459 ;; Before the preoutput function was used, this was done via -c in
1460 ;; cmdlist, but that loses the banner and doesn't run the startup
1461 ;; file. The code might be inline here, but there's enough that it
1462 ;; seems worth putting in a separate file, and it's probably cleaner
1463 ;; to put it in a module.
1464 ;; Ensure we're at a prompt before doing anything else.
1465 (python-send-string "import emacs")))
1466 (if (derived-mode-p 'python-mode)
1467 (setq python-buffer (default-value 'python-buffer))) ; buffer-local
1468 ;; Without this, help output goes into the inferior python buffer if
1469 ;; the process isn't already running.
1470 (sit-for 1 t) ;Should we use accept-process-output instead? --Stef
1471 (unless noshow (pop-to-buffer python-buffer t)))
1472
1473 ;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1474 ;; e.g. prompt is `help> '. Probably raise an error if the form of
1475 ;; the prompt is unexpected. Actually, it needs to be `>>> ', not
1476 ;; `... ', i.e. we're not inputting a block &c. However, this may not
1477 ;; be the place to check it, e.g. we might actually want to send
1478 ;; commands having set up such a state.
1479
1480 (defun python-send-command (command)
1481 "Like `python-send-string' but resets `compilation-shell-minor-mode'.
1482 COMMAND should be a single statement."
1483 ;; (assert (not (string-match "\n" command)))
1484 ;; (let ((end (marker-position (process-mark (python-proc)))))
1485 (with-current-buffer (process-buffer (python-proc))
1486 (goto-char (point-max))
1487 (compilation-forget-errors)
1488 (python-send-string command)
1489 (setq compilation-last-buffer (current-buffer)))
1490 ;; No idea what this is for but it breaks the call to
1491 ;; compilation-fake-loc in python-send-region. -- Stef
1492 ;; Must wait until this has completed before re-setting variables below.
1493 ;; (python-send-receive "print '_emacs_out ()'")
1494 ;; (with-current-buffer python-buffer
1495 ;; (set-marker compilation-parsing-end end))
1496 ) ;;)
1497
1498 (defun python-send-region (start end)
1499 "Send the region to the inferior Python process."
1500 ;; The region is evaluated from a temporary file. This avoids
1501 ;; problems with blank lines, which have different semantics
1502 ;; interactively and in files. It also saves the inferior process
1503 ;; buffer filling up with interpreter prompts. We need a Python
1504 ;; function to remove the temporary file when it has been evaluated
1505 ;; (though we could probably do it in Lisp with a Comint output
1506 ;; filter). This function also catches exceptions and truncates
1507 ;; tracebacks not to mention the frame of the function itself.
1508 ;;
1509 ;; The `compilation-shell-minor-mode' parsing takes care of relating
1510 ;; the reference to the temporary file to the source.
1511 ;;
1512 ;; Fixme: Write a `coding' header to the temp file if the region is
1513 ;; non-ASCII.
1514 (interactive "r")
1515 (let* ((f (make-temp-file "py"))
1516 (command (format "emacs.eexecfile(%S)" f))
1517 (orig-start (copy-marker start)))
1518 (when (save-excursion
1519 (goto-char start)
1520 (/= 0 (current-indentation))) ; need dummy block
1521 (save-excursion
1522 (goto-char orig-start)
1523 ;; Wrong if we had indented code at buffer start.
1524 (set-marker orig-start (line-beginning-position 0)))
1525 (write-region "if True:\n" nil f nil 'nomsg))
1526 (write-region start end f t 'nomsg)
1527 (python-send-command command)
1528 (with-current-buffer (process-buffer (python-proc))
1529 ;; Tell compile.el to redirect error locations in file `f' to
1530 ;; positions past marker `orig-start'. It has to be done *after*
1531 ;; `python-send-command''s call to `compilation-forget-errors'.
1532 (compilation-fake-loc orig-start f))))
1533
1534 (defun python-send-string (string)
1535 "Evaluate STRING in inferior Python process."
1536 (interactive "sPython command: ")
1537 (comint-send-string (python-proc) string)
1538 (unless (string-match "\n\\'" string)
1539 ;; Make sure the text is properly LF-terminated.
1540 (comint-send-string (python-proc) "\n"))
1541 (when (string-match "\n[ \t].*\n?\\'" string)
1542 ;; If the string contains a final indented line, add a second newline so
1543 ;; as to make sure we terminate the multiline instruction.
1544 (comint-send-string (python-proc) "\n")))
1545
1546 (defun python-send-buffer ()
1547 "Send the current buffer to the inferior Python process."
1548 (interactive)
1549 (python-send-region (point-min) (point-max)))
1550
1551 ;; Fixme: Try to define the function or class within the relevant
1552 ;; module, not just at top level.
1553 (defun python-send-defun ()
1554 "Send the current defun (class or method) to the inferior Python process."
1555 (interactive)
1556 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1557 (progn (end-of-defun) (point)))))
1558
1559 (defun python-switch-to-python (eob-p)
1560 "Switch to the Python process buffer, maybe starting new process.
1561 With prefix arg, position cursor at end of buffer."
1562 (interactive "P")
1563 (pop-to-buffer (process-buffer (python-proc)) t) ;Runs python if needed.
1564 (when eob-p
1565 (push-mark)
1566 (goto-char (point-max))))
1567
1568 (defun python-send-region-and-go (start end)
1569 "Send the region to the inferior Python process.
1570 Then switch to the process buffer."
1571 (interactive "r")
1572 (python-send-region start end)
1573 (python-switch-to-python t))
1574
1575 (defcustom python-source-modes '(python-mode jython-mode)
1576 "Used to determine if a buffer contains Python source code.
1577 If a file is loaded into a buffer that is in one of these major modes,
1578 it is considered Python source by `python-load-file', which uses the
1579 value to determine defaults."
1580 :type '(repeat function)
1581 :group 'python)
1582
1583 (defvar python-prev-dir/file nil
1584 "Caches (directory . file) pair used in the last `python-load-file' command.
1585 Used for determining the default in the next one.")
1586
1587 (autoload 'comint-get-source "comint")
1588
1589 (defun python-load-file (file-name)
1590 "Load a Python file FILE-NAME into the inferior Python process.
1591 If the file has extension `.py' import or reload it as a module.
1592 Treating it as a module keeps the global namespace clean, provides
1593 function location information for debugging, and supports users of
1594 module-qualified names."
1595 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1596 python-source-modes
1597 t)) ; because execfile needs exact name
1598 (comint-check-source file-name) ; Check to see if buffer needs saving.
1599 (setq python-prev-dir/file (cons (file-name-directory file-name)
1600 (file-name-nondirectory file-name)))
1601 (with-current-buffer (process-buffer (python-proc)) ;Runs python if needed.
1602 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1603 (python-send-command
1604 (if (string-match "\\.py\\'" file-name)
1605 (let ((module (file-name-sans-extension
1606 (file-name-nondirectory file-name))))
1607 (format "emacs.eimport(%S,%S)"
1608 module (file-name-directory file-name)))
1609 (format "execfile(%S)" file-name)))
1610 (message "%s loaded" file-name)))
1611
1612 (defun python-proc ()
1613 "Return the current Python process.
1614 See variable `python-buffer'. Starts a new process if necessary."
1615 ;; Fixme: Maybe should look for another active process if there
1616 ;; isn't one for `python-buffer'.
1617 (unless (comint-check-proc python-buffer)
1618 (run-python nil t))
1619 (get-buffer-process (if (derived-mode-p 'inferior-python-mode)
1620 (current-buffer)
1621 python-buffer)))
1622
1623 (defun python-set-proc ()
1624 "Set the default value of `python-buffer' to correspond to this buffer.
1625 If the current buffer has a local value of `python-buffer', set the
1626 default (global) value to that. The associated Python process is
1627 the one that gets input from \\[python-send-region] et al when used
1628 in a buffer that doesn't have a local value of `python-buffer'."
1629 (interactive)
1630 (if (local-variable-p 'python-buffer)
1631 (setq-default python-buffer python-buffer)
1632 (error "No local value of `python-buffer'")))
1633 \f
1634 ;;;; Context-sensitive help.
1635
1636 (defconst python-dotty-syntax-table
1637 (let ((table (make-syntax-table)))
1638 (set-char-table-parent table python-mode-syntax-table)
1639 (modify-syntax-entry ?. "_" table)
1640 table)
1641 "Syntax table giving `.' symbol syntax.
1642 Otherwise inherits from `python-mode-syntax-table'.")
1643
1644 (defvar view-return-to-alist)
1645 (eval-when-compile (autoload 'help-buffer "help-fns"))
1646
1647 (defvar python-imports) ; forward declaration
1648
1649 ;; Fixme: Should this actually be used instead of info-look, i.e. be
1650 ;; bound to C-h S? [Probably not, since info-look may work in cases
1651 ;; where this doesn't.]
1652 (defun python-describe-symbol (symbol)
1653 "Get help on SYMBOL using `help'.
1654 Interactively, prompt for symbol.
1655
1656 Symbol may be anything recognized by the interpreter's `help'
1657 command -- e.g. `CALLS' -- not just variables in scope in the
1658 interpreter. This only works for Python version 2.2 or newer
1659 since earlier interpreters don't support `help'.
1660
1661 In some cases where this doesn't find documentation, \\[info-lookup-symbol]
1662 will."
1663 ;; Note that we do this in the inferior process, not a separate one, to
1664 ;; ensure the environment is appropriate.
1665 (interactive
1666 (let ((symbol (with-syntax-table python-dotty-syntax-table
1667 (current-word)))
1668 (enable-recursive-minibuffers t))
1669 (list (read-string (if symbol
1670 (format "Describe symbol (default %s): " symbol)
1671 "Describe symbol: ")
1672 nil nil symbol))))
1673 (if (equal symbol "") (error "No symbol"))
1674 ;; Ensure we have a suitable help buffer.
1675 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1676 ;; allow C-c C-f in help buffer.
1677 (let ((temp-buffer-show-hook ; avoid xref stuff
1678 (lambda ()
1679 (toggle-read-only 1)
1680 (setq view-return-to-alist
1681 (list (cons (selected-window) help-return-method))))))
1682 (with-output-to-temp-buffer (help-buffer)
1683 (with-current-buffer standard-output
1684 ;; Fixme: Is this actually useful?
1685 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p))
1686 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1687 (print-help-return-message))))
1688 (comint-redirect-send-command-to-process (format "emacs.ehelp(%S, %s)"
1689 symbol python-imports)
1690 "*Help*" (python-proc) nil nil))
1691
1692 (add-to-list 'debug-ignored-errors "^No symbol")
1693
1694 (defun python-send-receive (string)
1695 "Send STRING to inferior Python (if any) and return result.
1696 The result is what follows `_emacs_out' in the output."
1697 (python-send-string string)
1698 (let ((proc (python-proc)))
1699 (with-current-buffer (process-buffer proc)
1700 (set (make-local-variable 'python-preoutput-result) nil)
1701 (while (progn
1702 (accept-process-output proc 5)
1703 (null python-preoutput-result)))
1704 (prog1 python-preoutput-result
1705 (kill-local-variable 'python-preoutput-result)))))
1706
1707 ;; Fixme: Is there anything reasonable we can do with random methods?
1708 ;; (Currently only works with functions.)
1709 (defun python-eldoc-function ()
1710 "`eldoc-documentation-function' for Python.
1711 Only works when point is in a function name, not its arg list, for
1712 instance. Assumes an inferior Python is running."
1713 (let ((symbol (with-syntax-table python-dotty-syntax-table
1714 (current-word))))
1715 ;; This is run from timers, so inhibit-quit tends to be set.
1716 (with-local-quit
1717 ;; First try the symbol we're on.
1718 (or (and symbol
1719 (python-send-receive (format "emacs.eargs(%S, %s)"
1720 symbol python-imports)))
1721 ;; Try moving to symbol before enclosing parens.
1722 (let ((s (syntax-ppss)))
1723 (unless (zerop (car s))
1724 (when (eq ?\( (char-after (nth 1 s)))
1725 (save-excursion
1726 (goto-char (nth 1 s))
1727 (skip-syntax-backward "-")
1728 (let ((point (point)))
1729 (skip-chars-backward "a-zA-Z._")
1730 (if (< (point) point)
1731 (python-send-receive
1732 (format "emacs.eargs(%S, %s)"
1733 (buffer-substring-no-properties (point) point)
1734 python-imports))))))))))))
1735 \f
1736 ;;;; Info-look functionality.
1737
1738 (declare-function info-lookup-maybe-add-help "info-look" (&rest arg))
1739
1740 (defun python-after-info-look ()
1741 "Set up info-look for Python.
1742 Used with `eval-after-load'."
1743 (let* ((version (let ((s (shell-command-to-string (concat python-command
1744 " -V"))))
1745 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1746 (match-string 1 s)))
1747 ;; Whether info files have a Python version suffix, e.g. in Debian.
1748 (versioned
1749 (with-temp-buffer
1750 (with-no-warnings (Info-mode))
1751 (condition-case ()
1752 ;; Don't use `info' because it would pop-up a *info* buffer.
1753 (with-no-warnings
1754 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
1755 version))
1756 t)
1757 (error nil)))))
1758 (info-lookup-maybe-add-help
1759 :mode 'python-mode
1760 :regexp "[[:alnum:]_]+"
1761 :doc-spec
1762 ;; Fixme: Can this reasonably be made specific to indices with
1763 ;; different rules? Is the order of indices optimal?
1764 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1765 ;; instance.)
1766 (if versioned
1767 ;; The empty prefix just gets us highlighted terms.
1768 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1769 (,(concat "(python" version "-ref)Module Index" nil ""))
1770 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1771 nil ""))
1772 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1773 nil ""))
1774 (,(concat "(python" version "-lib)Module Index" nil ""))
1775 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1776 nil ""))
1777 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1778 nil ""))
1779 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1780 '(("(python-ref)Miscellaneous Index" nil "")
1781 ("(python-ref)Module Index" nil "")
1782 ("(python-ref)Function-Method-Variable Index" nil "")
1783 ("(python-ref)Class-Exception-Object Index" nil "")
1784 ("(python-lib)Module Index" nil "")
1785 ("(python-lib)Class-Exception-Object Index" nil "")
1786 ("(python-lib)Function-Method-Variable Index" nil "")
1787 ("(python-lib)Miscellaneous Index" nil ""))))))
1788 (eval-after-load "info-look" '(python-after-info-look))
1789 \f
1790 ;;;; Miscellany.
1791
1792 (defcustom python-jython-packages '("java" "javax" "org" "com")
1793 "Packages implying `jython-mode'.
1794 If these are imported near the beginning of the buffer, `python-mode'
1795 actually punts to `jython-mode'."
1796 :type '(repeat string)
1797 :group 'python)
1798
1799 ;; Called from `python-mode', this causes a recursive call of the
1800 ;; mode. See logic there to break out of the recursion.
1801 (defun python-maybe-jython ()
1802 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1803 The criterion is either a match for `jython-mode' via
1804 `interpreter-mode-alist' or an import of a module from the list
1805 `python-jython-packages'."
1806 ;; The logic is taken from python-mode.el.
1807 (save-excursion
1808 (save-restriction
1809 (widen)
1810 (goto-char (point-min))
1811 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1812 (match-string 2))))
1813 (if (and interpreter (eq 'jython-mode
1814 (cdr (assoc (file-name-nondirectory
1815 interpreter)
1816 interpreter-mode-alist))))
1817 (jython-mode)
1818 (if (catch 'done
1819 (while (re-search-forward
1820 (rx line-start (or "import" "from") (1+ space)
1821 (group (1+ (not (any " \t\n.")))))
1822 (+ (point-min) 10000) ; Probably not worth customizing.
1823 t)
1824 (if (member (match-string 1) python-jython-packages)
1825 (throw 'done t))))
1826 (jython-mode)))))))
1827
1828 (defun python-fill-paragraph (&optional justify)
1829 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1830 If any of the current line is in or at the end of a multi-line string,
1831 fill the string or the paragraph of it that point is in, preserving
1832 the strings's indentation."
1833 (interactive "P")
1834 (or (fill-comment-paragraph justify)
1835 (save-excursion
1836 (end-of-line)
1837 (let* ((syntax (syntax-ppss))
1838 (orig (point))
1839 start end)
1840 (cond ((nth 4 syntax) ; comment. fixme: loses with trailing one
1841 (let (fill-paragraph-function)
1842 (fill-paragraph justify)))
1843 ;; The `paragraph-start' and `paragraph-separate'
1844 ;; variables don't allow us to delimit the last
1845 ;; paragraph in a multi-line string properly, so narrow
1846 ;; to the string and then fill around (the end of) the
1847 ;; current line.
1848 ((eq t (nth 3 syntax)) ; in fenced string
1849 (goto-char (nth 8 syntax)) ; string start
1850 (setq start (line-beginning-position))
1851 (setq end (condition-case () ; for unbalanced quotes
1852 (progn (forward-sexp)
1853 (- (point) 3))
1854 (error (point-max)))))
1855 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced string
1856 (forward-char)
1857 (setq end (point))
1858 (condition-case ()
1859 (progn (backward-sexp)
1860 (setq start (line-beginning-position)))
1861 (error nil))))
1862 (when end
1863 (save-restriction
1864 (narrow-to-region start end)
1865 (goto-char orig)
1866 ;; Avoid losing leading and trailing newlines in doc
1867 ;; strings written like:
1868 ;; """
1869 ;; ...
1870 ;; """
1871 (let* ((paragraph-separate
1872 (concat ".*\\s|\"\"$" ; newline after opening quotes
1873 "\\|\\(?:" paragraph-separate "\\)"))
1874 (paragraph-start
1875 (concat ".*\\s|\"\"[ \t]*[^ \t].*" ; not newline after
1876 ; opening quotes
1877 "\\|\\(?:" paragraph-separate "\\)"))
1878 (fill-paragraph-function))
1879 (fill-paragraph justify))))))) t)
1880
1881 (defun python-shift-left (start end &optional count)
1882 "Shift lines in region COUNT (the prefix arg) columns to the left.
1883 COUNT defaults to `python-indent'. If region isn't active, just shift
1884 current line. The region shifted includes the lines in which START and
1885 END lie. It is an error if any lines in the region are indented less than
1886 COUNT columns."
1887 (interactive (if mark-active
1888 (list (region-beginning) (region-end) current-prefix-arg)
1889 (list (point) (point) current-prefix-arg)))
1890 (if count
1891 (setq count (prefix-numeric-value count))
1892 (setq count python-indent))
1893 (when (> count 0)
1894 (save-excursion
1895 (goto-char start)
1896 (while (< (point) end)
1897 (if (and (< (current-indentation) count)
1898 (not (looking-at "[ \t]*$")))
1899 (error "Can't shift all lines enough"))
1900 (forward-line))
1901 (indent-rigidly start end (- count)))))
1902
1903 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1904
1905 (defun python-shift-right (start end &optional count)
1906 "Shift lines in region COUNT (the prefix arg) columns to the right.
1907 COUNT defaults to `python-indent'. If region isn't active, just shift
1908 current line. The region shifted includes the lines in which START and
1909 END lie."
1910 (interactive (if mark-active
1911 (list (region-beginning) (region-end) current-prefix-arg)
1912 (list (point) (point) current-prefix-arg)))
1913 (if count
1914 (setq count (prefix-numeric-value count))
1915 (setq count python-indent))
1916 (indent-rigidly start end count))
1917
1918 (defun python-outline-level ()
1919 "`outline-level' function for Python mode.
1920 The level is the number of `python-indent' steps of indentation
1921 of current line."
1922 (1+ (/ (current-indentation) python-indent)))
1923
1924 ;; Fixme: Consider top-level assignments, imports, &c.
1925 (defun python-current-defun (&optional length-limit)
1926 "`add-log-current-defun-function' for Python."
1927 (save-excursion
1928 ;; Move up the tree of nested `class' and `def' blocks until we
1929 ;; get to zero indentation, accumulating the defined names.
1930 (let ((accum)
1931 (length -1))
1932 (catch 'done
1933 (while (or (null length-limit)
1934 (null (cdr accum))
1935 (< length length-limit))
1936 (let ((started-from (point)))
1937 (python-beginning-of-block)
1938 (end-of-line)
1939 (beginning-of-defun)
1940 (when (= (point) started-from)
1941 (throw 'done nil)))
1942 (when (looking-at (rx (0+ space) (or "def" "class") (1+ space)
1943 (group (1+ (or word (syntax symbol))))))
1944 (push (match-string 1) accum)
1945 (setq length (+ length 1 (length (car accum)))))
1946 (when (= (current-indentation) 0)
1947 (throw 'done nil))))
1948 (when accum
1949 (when (and length-limit (> length length-limit))
1950 (setcar accum ".."))
1951 (mapconcat 'identity accum ".")))))
1952
1953 (defun python-mark-block ()
1954 "Mark the block around point.
1955 Uses `python-beginning-of-block', `python-end-of-block'."
1956 (interactive)
1957 (push-mark)
1958 (python-beginning-of-block)
1959 (push-mark (point) nil t)
1960 (python-end-of-block)
1961 (exchange-point-and-mark))
1962
1963 ;; Fixme: Provide a find-function-like command to find source of a
1964 ;; definition (separate from BicycleRepairMan). Complicated by
1965 ;; finding the right qualified name.
1966 \f
1967 ;;;; Completion.
1968
1969 ;; http://lists.gnu.org/archive/html/bug-gnu-emacs/2008-01/msg00076.html
1970 (defvar python-imports "None"
1971 "String of top-level import statements updated by `python-find-imports'.")
1972 (make-variable-buffer-local 'python-imports)
1973
1974 ;; Fixme: Should font-lock try to run this when it deals with an import?
1975 ;; Maybe not a good idea if it gets run multiple times when the
1976 ;; statement is being edited, and is more likely to end up with
1977 ;; something syntactically incorrect.
1978 ;; However, what we should do is to trundle up the block tree from point
1979 ;; to extract imports that appear to be in scope, and add those.
1980 (defun python-find-imports ()
1981 "Find top-level imports, updating `python-imports'."
1982 (interactive)
1983 (save-excursion
1984 (let (lines)
1985 (goto-char (point-min))
1986 (while (re-search-forward "^import\\>\\|^from\\>" nil t)
1987 (unless (syntax-ppss-context (syntax-ppss))
1988 (let ((start (line-beginning-position)))
1989 ;; Skip over continued lines.
1990 (while (and (eq ?\\ (char-before (line-end-position)))
1991 (= 0 (forward-line 1))))
1992 (push (buffer-substring start (line-beginning-position 2))
1993 lines))))
1994 (setq python-imports
1995 (if lines
1996 (apply #'concat
1997 ;; This is probably best left out since you're unlikely to need the
1998 ;; doc for a function in the buffer and the import will lose if the
1999 ;; Python sub-process' working directory isn't the same as the
2000 ;; buffer's.
2001 ;; (if buffer-file-name
2002 ;; (concat
2003 ;; "import "
2004 ;; (file-name-sans-extension
2005 ;; (file-name-nondirectory buffer-file-name))))
2006 (nreverse lines))
2007 "None"))
2008 (when lines
2009 (set-text-properties 0 (length python-imports) nil python-imports)
2010 ;; The output ends up in the wrong place if the string we
2011 ;; send contains newlines (from the imports).
2012 (setq python-imports
2013 (replace-regexp-in-string "\n" "\\n"
2014 (format "%S" python-imports) t t))))))
2015
2016 ;; Fixme: This fails the first time if the sub-process isn't already
2017 ;; running. Presumably a timing issue with i/o to the process.
2018 (defun python-symbol-completions (symbol)
2019 "Return a list of completions of the string SYMBOL from Python process.
2020 The list is sorted.
2021 Uses `python-imports' to load modules against which to complete."
2022 (when symbol
2023 (let ((completions
2024 (condition-case ()
2025 (car (read-from-string
2026 (python-send-receive
2027 (format "emacs.complete(%S,%s)" symbol python-imports))))
2028 (error nil))))
2029 (sort
2030 ;; We can get duplicates from the above -- don't know why.
2031 (delete-dups completions)
2032 #'string<))))
2033
2034 (defun python-partial-symbol ()
2035 "Return the partial symbol before point (for completion)."
2036 (let ((end (point))
2037 (start (save-excursion
2038 (and (re-search-backward
2039 (rx (or buffer-start (regexp "[^[:alnum:]._]"))
2040 (group (1+ (regexp "[[:alnum:]._]"))) point)
2041 nil t)
2042 (match-beginning 1)))))
2043 (if start (buffer-substring-no-properties start end))))
2044
2045 (defun python-complete-symbol ()
2046 "Perform completion on the Python symbol preceding point.
2047 Repeating the command scrolls the completion window."
2048 (interactive)
2049 (let ((window (get-buffer-window "*Completions*")))
2050 (if (and (eq last-command this-command)
2051 (window-live-p window) (window-buffer window)
2052 (buffer-name (window-buffer window)))
2053 (with-current-buffer (window-buffer window)
2054 (if (pos-visible-in-window-p (point-max) window)
2055 (set-window-start window (point-min))
2056 (save-selected-window
2057 (select-window window)
2058 (scroll-up))))
2059 ;; Do completion.
2060 (let* ((end (point))
2061 (symbol (python-partial-symbol))
2062 (completions (python-symbol-completions symbol))
2063 (completion (if completions
2064 (try-completion symbol completions))))
2065 (when symbol
2066 (cond ((eq completion t))
2067 ((null completion)
2068 (message "Can't find completion for \"%s\"" symbol)
2069 (ding))
2070 ((not (string= symbol completion))
2071 (delete-region (- end (length symbol)) end)
2072 (insert completion))
2073 (t
2074 (message "Making completion list...")
2075 (with-output-to-temp-buffer "*Completions*"
2076 (display-completion-list completions symbol))
2077 (message "Making completion list...%s" "done"))))))))
2078
2079 (defun python-try-complete (old)
2080 "Completion function for Python for use with `hippie-expand'."
2081 (when (derived-mode-p 'python-mode) ; though we only add it locally
2082 (unless old
2083 (let ((symbol (python-partial-symbol)))
2084 (he-init-string (- (point) (length symbol)) (point))
2085 (if (not (he-string-member he-search-string he-tried-table))
2086 (push he-search-string he-tried-table))
2087 (setq he-expand-list
2088 (and symbol (python-symbol-completions symbol)))))
2089 (while (and he-expand-list
2090 (he-string-member (car he-expand-list) he-tried-table))
2091 (pop he-expand-list))
2092 (if he-expand-list
2093 (progn
2094 (he-substitute-string (pop he-expand-list))
2095 t)
2096 (if old (he-reset-string))
2097 nil)))
2098 \f
2099 ;;;; FFAP support
2100
2101 (defun python-module-path (module)
2102 "Function for `ffap-alist' to return path to MODULE."
2103 (python-send-receive (format "emacs.modpath (%S)" module)))
2104
2105 (eval-after-load "ffap"
2106 '(push '(python-mode . python-module-path) ffap-alist))
2107 \f
2108 ;;;; Skeletons
2109
2110 (defcustom python-use-skeletons nil
2111 "Non-nil means template skeletons will be automagically inserted.
2112 This happens when pressing \"if<SPACE>\", for example, to prompt for
2113 the if condition."
2114 :type 'boolean
2115 :group 'python)
2116
2117 (defvar python-skeletons nil
2118 "Alist of named skeletons for Python mode.
2119 Elements are of the form (NAME . EXPANDER-FUNCTION).")
2120
2121 (define-abbrev-table 'python-mode-abbrev-table ()
2122 "Abbrev table for Python mode.
2123 The default contents correspond to the elements of `python-skeletons'."
2124 ;; Allow / in abbrevs.
2125 :regexp "\\<\\([[:word:]/]+\\)\\W*")
2126
2127 (eval-when-compile
2128 ;; Define a user-level skeleton and add it to `python-skeletons' and
2129 ;; the abbrev table.
2130 (defmacro def-python-skeleton (name &rest elements)
2131 (let* ((name (symbol-name name))
2132 (function (intern (concat "python-insert-" name))))
2133 `(progn
2134 (add-to-list 'python-skeletons ',(cons name function))
2135 (define-abbrev python-mode-abbrev-table ,name "" ',function
2136 :system t :case-fixed t
2137 :enable-function (lambda () python-use-skeletons))
2138 (define-skeleton ,function
2139 ,(format "Insert Python \"%s\" template." name)
2140 ,@elements)))))
2141 (put 'def-python-skeleton 'lisp-indent-function 2)
2142
2143 ;; From `skeleton-further-elements':
2144 ;; `<': outdent a level;
2145 ;; `^': delete indentation on current line and also previous newline.
2146 ;; Not quote like `delete-indentation'. Assumes point is at
2147 ;; beginning of indentation.
2148
2149 (def-python-skeleton if
2150 "Condition: "
2151 "if " str ":" \n
2152 > _ \n
2153 ("other condition, %s: "
2154 < ; Avoid wrong indentation after block opening.
2155 "elif " str ":" \n
2156 > _ \n nil)
2157 '(python-else) | ^)
2158
2159 (define-skeleton python-else
2160 "Auxiliary skeleton."
2161 nil
2162 (unless (eq ?y (read-char "Add `else' clause? (y for yes or RET for no) "))
2163 (signal 'quit t))
2164 < "else:" \n
2165 > _ \n)
2166
2167 (def-python-skeleton while
2168 "Condition: "
2169 "while " str ":" \n
2170 > _ \n
2171 '(python-else) | ^)
2172
2173 (def-python-skeleton for
2174 "Target, %s: "
2175 "for " str " in " (skeleton-read "Expression, %s: ") ":" \n
2176 > _ \n
2177 '(python-else) | ^)
2178
2179 (def-python-skeleton try/except
2180 nil
2181 "try:" \n
2182 > _ \n
2183 ("Exception, %s: "
2184 < "except " str '(python-target) ":" \n
2185 > _ \n nil)
2186 < "except:" \n
2187 > _ \n
2188 '(python-else) | ^)
2189
2190 (define-skeleton python-target
2191 "Auxiliary skeleton."
2192 "Target, %s: " ", " str | -2)
2193
2194 (def-python-skeleton try/finally
2195 nil
2196 "try:" \n
2197 > _ \n
2198 < "finally:" \n
2199 > _ \n)
2200
2201 (def-python-skeleton def
2202 "Name: "
2203 "def " str " (" ("Parameter, %s: " (unless (equal ?\( (char-before)) ", ")
2204 str) "):" \n
2205 "\"\"\"" @ " \"\"\"" \n ; Fixme: syntaxification wrong for """"""
2206 > _ \n)
2207
2208 (def-python-skeleton class
2209 "Name: "
2210 "class " str " (" ("Inheritance, %s: "
2211 (unless (equal ?\( (char-before)) ", ")
2212 str)
2213 & ")" | -2 ; close list or remove opening
2214 ":" \n
2215 "\"\"\"" @ " \"\"\"" \n
2216 > _ \n)
2217
2218 (defvar python-default-template "if"
2219 "Default template to expand by `python-expand-template'.
2220 Updated on each expansion.")
2221
2222 (defun python-expand-template (name)
2223 "Expand template named NAME.
2224 Interactively, prompt for the name with completion."
2225 (interactive
2226 (list (completing-read (format "Template to expand (default %s): "
2227 python-default-template)
2228 python-skeletons nil t)))
2229 (if (equal "" name)
2230 (setq name python-default-template)
2231 (setq python-default-template name))
2232 (let ((func (cdr (assoc name python-skeletons))))
2233 (if func
2234 (funcall func)
2235 (error "Undefined template: %s" name))))
2236 \f
2237 ;;;; Bicycle Repair Man support
2238
2239 (autoload 'pymacs-load "pymacs" nil t)
2240 (autoload 'brm-init "bikemacs")
2241
2242 ;; I'm not sure how useful BRM really is, and it's certainly dangerous
2243 ;; the way it modifies files outside Emacs... Also note that the
2244 ;; current BRM loses with tabs used for indentation -- I submitted a
2245 ;; fix <URL:http://www.loveshack.ukfsn.org/emacs/bikeemacs.py.diff>.
2246 (defun python-setup-brm ()
2247 "Set up Bicycle Repair Man refactoring tool (if available).
2248
2249 Note that the `refactoring' features change files independently of
2250 Emacs and may modify and save the contents of the current buffer
2251 without confirmation."
2252 (interactive)
2253 (condition-case data
2254 (unless (fboundp 'brm-rename)
2255 (pymacs-load "bikeemacs" "brm-") ; first line of normal recipe
2256 (let ((py-mode-map (make-sparse-keymap)) ; it assumes this
2257 (features (cons 'python-mode features))) ; and requires this
2258 (brm-init)) ; second line of normal recipe
2259 (remove-hook 'python-mode-hook ; undo this from `brm-init'
2260 '(lambda () (easy-menu-add brm-menu)))
2261 (easy-menu-define
2262 python-brm-menu python-mode-map
2263 "Bicycle Repair Man"
2264 '("BicycleRepairMan"
2265 :help "Interface to navigation and refactoring tool"
2266 "Queries"
2267 ["Find References" brm-find-references
2268 :help "Find references to name at point in compilation buffer"]
2269 ["Find Definition" brm-find-definition
2270 :help "Find definition of name at point"]
2271 "-"
2272 "Refactoring"
2273 ["Rename" brm-rename
2274 :help "Replace name at point with a new name everywhere"]
2275 ["Extract Method" brm-extract-method
2276 :active (and mark-active (not buffer-read-only))
2277 :help "Replace statements in region with a method"]
2278 ["Extract Local Variable" brm-extract-local-variable
2279 :active (and mark-active (not buffer-read-only))
2280 :help "Replace expression in region with an assignment"]
2281 ["Inline Local Variable" brm-inline-local-variable
2282 :help
2283 "Substitute uses of variable at point with its definition"]
2284 ;; Fixme: Should check for anything to revert.
2285 ["Undo Last Refactoring" brm-undo :help ""])))
2286 (error (error "Bicyclerepairman setup failed: %s" data))))
2287 \f
2288 ;;;; Modes.
2289
2290 (defvar outline-heading-end-regexp)
2291 (defvar eldoc-documentation-function)
2292 (defvar python-mode-running) ;Dynamically scoped var.
2293
2294 ;;;###autoload
2295 (define-derived-mode python-mode fundamental-mode "Python"
2296 "Major mode for editing Python files.
2297 Font Lock mode is currently required for correct parsing of the source.
2298 See also `jython-mode', which is actually invoked if the buffer appears to
2299 contain Jython code. See also `run-python' and associated Python mode
2300 commands for running Python under Emacs.
2301
2302 The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
2303 with nested `def' and `class' blocks. They take the innermost one as
2304 current without distinguishing method and class definitions. Used multiple
2305 times, they move over others at the same indentation level until they reach
2306 the end of definitions at that level, when they move up a level.
2307 \\<python-mode-map>
2308 Colon is electric: it outdents the line if appropriate, e.g. for
2309 an else statement. \\[python-backspace] at the beginning of an indented statement
2310 deletes a level of indentation to close the current block; otherwise it
2311 deletes a character backward. TAB indents the current line relative to
2312 the preceding code. Successive TABs, with no intervening command, cycle
2313 through the possibilities for indentation on the basis of enclosing blocks.
2314
2315 \\[fill-paragraph] fills comments and multi-line strings appropriately, but has no
2316 effect outside them.
2317
2318 Supports Eldoc mode (only for functions, using a Python process),
2319 Info-Look and Imenu. In Outline minor mode, `class' and `def'
2320 lines count as headers. Symbol completion is available in the
2321 same way as in the Python shell using the `rlcompleter' module
2322 and this is added to the Hippie Expand functions locally if
2323 Hippie Expand mode is turned on. Completion of symbols of the
2324 form x.y only works if the components are literal
2325 module/attribute names, not variables. An abbrev table is set up
2326 with skeleton expansions for compound statement templates.
2327
2328 \\{python-mode-map}"
2329 :group 'python
2330 (set (make-local-variable 'font-lock-defaults)
2331 '(python-font-lock-keywords nil nil nil nil
2332 (font-lock-syntactic-keywords
2333 . python-font-lock-syntactic-keywords)
2334 ;; This probably isn't worth it.
2335 ;; (font-lock-syntactic-face-function
2336 ;; . python-font-lock-syntactic-face-function)
2337 ))
2338 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2339 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2340 (set (make-local-variable 'comment-start) "# ")
2341 (set (make-local-variable 'indent-line-function) #'python-indent-line)
2342 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2343 (set (make-local-variable 'paragraph-start) "\\s-*$")
2344 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
2345 (set (make-local-variable 'require-final-newline) mode-require-final-newline)
2346 (set (make-local-variable 'add-log-current-defun-function)
2347 #'python-current-defun)
2348 (set (make-local-variable 'outline-regexp)
2349 (rx (* space) (or "class" "def" "elif" "else" "except" "finally"
2350 "for" "if" "try" "while" "with")
2351 symbol-end))
2352 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2353 (set (make-local-variable 'outline-level) #'python-outline-level)
2354 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
2355 (make-local-variable 'python-saved-check-command)
2356 (set (make-local-variable 'beginning-of-defun-function)
2357 'python-beginning-of-defun)
2358 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
2359 (add-hook 'which-func-functions 'python-which-func nil t)
2360 (setq imenu-create-index-function #'python-imenu-create-index)
2361 (set (make-local-variable 'eldoc-documentation-function)
2362 #'python-eldoc-function)
2363 (add-hook 'eldoc-mode-hook
2364 (lambda () (run-python nil t)) ; need it running
2365 nil t)
2366 ;; Fixme: should be in hideshow. This seems to be of limited use
2367 ;; since it isn't (can't be) indentation-based. Also hide-level
2368 ;; doesn't seem to work properly.
2369 (add-to-list 'hs-special-modes-alist
2370 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2371 ,(lambda (arg)
2372 (python-end-of-defun)
2373 (skip-chars-backward " \t\n"))
2374 nil))
2375 (set (make-local-variable 'skeleton-further-elements)
2376 '((< '(backward-delete-char-untabify (min python-indent
2377 (current-column))))
2378 (^ '(- (1+ (current-indentation))))))
2379 (if (featurep 'hippie-exp)
2380 (set (make-local-variable 'hippie-expand-try-functions-list)
2381 (cons 'python-try-complete hippie-expand-try-functions-list)))
2382 ;; Python defines TABs as being 8-char wide.
2383 (set (make-local-variable 'tab-width) 8)
2384 (when python-guess-indent (python-guess-indent))
2385 ;; Let's make it harder for the user to shoot himself in the foot.
2386 (unless (= tab-width python-indent)
2387 (setq indent-tabs-mode nil))
2388 (set (make-local-variable 'python-command) python-python-command)
2389 (python-find-imports)
2390 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
2391 (let ((python-mode-running t))
2392 (python-maybe-jython))))
2393
2394 (custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
2395 (custom-add-option 'python-mode-hook
2396 (lambda ()
2397 "Turn off Indent Tabs mode."
2398 (set (make-local-variable 'indent-tabs-mode) nil)))
2399 (custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
2400 (custom-add-option 'python-mode-hook 'abbrev-mode)
2401 (custom-add-option 'python-mode-hook 'python-setup-brm)
2402
2403 ;;;###autoload
2404 (define-derived-mode jython-mode python-mode "Jython"
2405 "Major mode for editing Jython files.
2406 Like `python-mode', but sets up parameters for Jython subprocesses.
2407 Runs `jython-mode-hook' after `python-mode-hook'."
2408 :group 'python
2409 (set (make-local-variable 'python-command) python-jython-command))
2410
2411 \f
2412
2413 ;; pdbtrack features
2414
2415 (defsubst python-point (position)
2416 "Returns the value of point at certain commonly referenced POSITIONs.
2417 POSITION can be one of the following symbols:
2418
2419 bol -- beginning of line
2420 eol -- end of line
2421 bod -- beginning of def or class
2422 eod -- end of def or class
2423 bob -- beginning of buffer
2424 eob -- end of buffer
2425 boi -- back to indentation
2426 bos -- beginning of statement
2427
2428 This function does not modify point or mark."
2429 (let ((here (point)))
2430 (cond
2431 ((eq position 'bol) (beginning-of-line))
2432 ((eq position 'eol) (end-of-line))
2433 ((eq position 'bod) (python-beginning-of-def-or-class))
2434 ((eq position 'eod) (python-end-of-def-or-class))
2435 ;; Kind of funny, I know, but useful for python-up-exception.
2436 ((eq position 'bob) (goto-char (point-min)))
2437 ((eq position 'eob) (goto-char (point-max)))
2438 ((eq position 'boi) (back-to-indentation))
2439 ((eq position 'bos) (python-goto-initial-line))
2440 (t (error "Unknown buffer position requested: %s" position)))
2441 (prog1
2442 (point)
2443 (goto-char here))))
2444
2445 (defun python-end-of-def-or-class (&optional class count)
2446 "Move point beyond end of `def' or `class' body.
2447
2448 By default, looks for an appropriate `def'. If you supply a prefix
2449 arg, looks for a `class' instead. The docs below assume the `def'
2450 case; just substitute `class' for `def' for the other case.
2451 Programmatically, if CLASS is `either', then moves to either `class'
2452 or `def'.
2453
2454 When second optional argument is given programmatically, move to the
2455 COUNTth end of `def'.
2456
2457 If point is in a `def' statement already, this is the `def' we use.
2458
2459 Else, if the `def' found by `\\[python-beginning-of-def-or-class]'
2460 contains the statement you started on, that's the `def' we use.
2461
2462 Otherwise, we search forward for the closest following `def', and use that.
2463
2464 If a `def' can be found by these rules, point is moved to the start of
2465 the line immediately following the `def' block, and the position of the
2466 start of the `def' is returned.
2467
2468 Else point is moved to the end of the buffer, and nil is returned.
2469
2470 Note that doing this command repeatedly will take you closer to the
2471 end of the buffer each time.
2472
2473 To mark the current `def', see `\\[python-mark-def-or-class]'."
2474 (interactive "P") ; raw prefix arg
2475 (if (and count (/= count 1))
2476 (python-beginning-of-def-or-class (- 1 count)))
2477 (let ((start (progn (python-goto-initial-line) (point)))
2478 (which (cond ((eq class 'either) "\\(class\\|def\\)")
2479 (class "class")
2480 (t "def")))
2481 (state 'not-found))
2482 ;; move point to start of appropriate def/class
2483 (if (looking-at (concat "[ \t]*" which "\\>")) ; already on one
2484 (setq state 'at-beginning)
2485 ;; else see if python-beginning-of-def-or-class hits container
2486 (if (and (python-beginning-of-def-or-class class)
2487 (progn (python-goto-beyond-block)
2488 (> (point) start)))
2489 (setq state 'at-end)
2490 ;; else search forward
2491 (goto-char start)
2492 (if (re-search-forward (concat "^[ \t]*" which "\\>") nil 'move)
2493 (progn (setq state 'at-beginning)
2494 (beginning-of-line)))))
2495 (cond
2496 ((eq state 'at-beginning) (python-goto-beyond-block) t)
2497 ((eq state 'at-end) t)
2498 ((eq state 'not-found) nil)
2499 (t (error "Internal error in `python-end-of-def-or-class'")))))
2500
2501 (defun python-beginning-of-def-or-class (&optional class count)
2502 "Move point to start of `def' or `class'.
2503
2504 Searches back for the closest preceding `def'. If you supply a prefix
2505 arg, looks for a `class' instead. The docs below assume the `def'
2506 case; just substitute `class' for `def' for the other case.
2507 Programmatically, if CLASS is `either', then moves to either `class'
2508 or `def'.
2509
2510 When second optional argument is given programmatically, move to the
2511 COUNTth start of `def'.
2512
2513 If point is in a `def' statement already, and after the `d', simply
2514 moves point to the start of the statement.
2515
2516 Otherwise (i.e. when point is not in a `def' statement, or at or
2517 before the `d' of a `def' statement), searches for the closest
2518 preceding `def' statement, and leaves point at its start. If no such
2519 statement can be found, leaves point at the start of the buffer.
2520
2521 Returns t iff a `def' statement is found by these rules.
2522
2523 Note that doing this command repeatedly will take you closer to the
2524 start of the buffer each time.
2525
2526 To mark the current `def', see `\\[python-mark-def-or-class]'."
2527 (interactive "P") ; raw prefix arg
2528 (setq count (or count 1))
2529 (let ((at-or-before-p (<= (current-column) (current-indentation)))
2530 (start-of-line (goto-char (python-point 'bol)))
2531 (start-of-stmt (goto-char (python-point 'bos)))
2532 (start-re (cond ((eq class 'either) "^[ \t]*\\(class\\|def\\)\\>")
2533 (class "^[ \t]*class\\>")
2534 (t "^[ \t]*def\\>"))))
2535 ;; searching backward
2536 (if (and (< 0 count)
2537 (or (/= start-of-stmt start-of-line)
2538 (not at-or-before-p)))
2539 (end-of-line))
2540 ;; search forward
2541 (if (and (> 0 count)
2542 (zerop (current-column))
2543 (looking-at start-re))
2544 (end-of-line))
2545 (if (re-search-backward start-re nil 'move count)
2546 (goto-char (match-beginning 0)))))
2547
2548 (defun python-goto-initial-line ()
2549 "Go to the initial line of the current statement.
2550 Usually this is the line we're on, but if we're on the 2nd or
2551 following lines of a continuation block, we need to go up to the first
2552 line of the block."
2553 ;; Tricky: We want to avoid quadratic-time behavior for long
2554 ;; continued blocks, whether of the backslash or open-bracket
2555 ;; varieties, or a mix of the two. The following manages to do that
2556 ;; in the usual cases.
2557 ;;
2558 ;; Also, if we're sitting inside a triple quoted string, this will
2559 ;; drop us at the line that begins the string.
2560 (let (open-bracket-pos)
2561 (while (python-continuation-line-p)
2562 (beginning-of-line)
2563 (if (python-backslash-continuation-line-p)
2564 (while (python-backslash-continuation-line-p)
2565 (forward-line -1))
2566 ;; else zip out of nested brackets/braces/parens
2567 (while (setq open-bracket-pos (python-nesting-level))
2568 (goto-char open-bracket-pos)))))
2569 (beginning-of-line))
2570
2571 (defun python-comint-output-filter-function (string)
2572 "Watch output for Python prompt and exec next file waiting in queue.
2573 This function is appropriate for `comint-output-filter-functions'."
2574 ;; TBD: this should probably use split-string
2575 (when (and (or (string-equal string ">>> ")
2576 (and (>= (length string) 5)
2577 (string-equal (substring string -5) "\n>>> ")))
2578 python-file-queue)
2579 (python-safe (delete-file (car python-file-queue)))
2580 (setq python-file-queue (cdr python-file-queue))
2581 (if python-file-queue
2582 (let ((pyproc (get-buffer-process (current-buffer))))
2583 (python-execute-file pyproc (car python-file-queue))))))
2584
2585 (defun python-pdbtrack-overlay-arrow (activation)
2586 "Activate or de arrow at beginning-of-line in current buffer."
2587 ;; This was derived/simplified from edebug-overlay-arrow
2588 (cond (activation
2589 (setq overlay-arrow-position (make-marker))
2590 (setq overlay-arrow-string "=>")
2591 (set-marker overlay-arrow-position
2592 (python-point 'bol) (current-buffer))
2593 (setq python-pdbtrack-is-tracking-p t))
2594 (python-pdbtrack-is-tracking-p
2595 (setq overlay-arrow-position nil)
2596 (setq python-pdbtrack-is-tracking-p nil))))
2597
2598 (defun python-pdbtrack-track-stack-file (text)
2599 "Show the file indicated by the pdb stack entry line, in a separate window.
2600
2601 Activity is disabled if the buffer-local variable
2602 `python-pdbtrack-do-tracking-p' is nil.
2603
2604 We depend on the pdb input prompt matching `python-pdbtrack-input-prompt'
2605 at the beginning of the line."
2606 ;; Instead of trying to piece things together from partial text
2607 ;; (which can be almost useless depending on Emacs version), we
2608 ;; monitor to the point where we have the next pdb prompt, and then
2609 ;; check all text from comint-last-input-end to process-mark.
2610 ;;
2611 ;; KLM: It might be nice to provide an optional override, so this
2612 ;; routine could be fed debugger output strings as the text
2613 ;; argument, for deliberate application elsewhere.
2614 ;;
2615 ;; KLM: We're very conservative about clearing the overlay arrow, to
2616 ;; minimize residue. This means, for instance, that executing other
2617 ;; pdb commands wipes out the highlight.
2618 (let* ((origbuf (current-buffer))
2619 (currproc (get-buffer-process origbuf)))
2620 (if (not (and currproc python-pdbtrack-do-tracking-p))
2621 (python-pdbtrack-overlay-arrow nil)
2622 (let* (;(origdir default-directory)
2623 (procmark (process-mark currproc))
2624 (block (buffer-substring (max comint-last-input-end
2625 (- procmark
2626 python-pdbtrack-track-range))
2627 procmark))
2628 fname lineno)
2629 (if (not (string-match (concat python-pdbtrack-input-prompt "$") block))
2630 (python-pdbtrack-overlay-arrow nil)
2631 (if (not (string-match
2632 (concat ".*" python-pdbtrack-stack-entry-regexp ".*")
2633 block))
2634 (python-pdbtrack-overlay-arrow nil)
2635 (setq fname (match-string 1 block)
2636 lineno (match-string 2 block))
2637 (if (file-exists-p fname)
2638 (progn
2639 (find-file-other-window fname)
2640 (goto-line (string-to-number lineno))
2641 (message "pdbtrack: line %s, file %s" lineno fname)
2642 (python-pdbtrack-overlay-arrow t)
2643 (pop-to-buffer origbuf t) )
2644 (if (= (elt fname 0) ?\<)
2645 (message "pdbtrack: (Non-file source: '%s')" fname)
2646 (message "pdbtrack: File not found: %s" fname)))))))))
2647
2648 (defun python-toggle-shells (arg)
2649 "Toggles between the CPython and JPython shells.
2650
2651 With positive argument ARG (interactively \\[universal-argument]),
2652 uses the CPython shell, with negative ARG uses the JPython shell, and
2653 with a zero argument, toggles the shell.
2654
2655 Programmatically, ARG can also be one of the symbols `cpython' or
2656 `jpython', equivalent to positive arg and negative arg respectively."
2657 (interactive "P")
2658 ;; default is to toggle
2659 (if (null arg)
2660 (setq arg 0))
2661 ;; preprocess arg
2662 (cond
2663 ((equal arg 0)
2664 ;; toggle
2665 (if (string-equal python-which-bufname "Python")
2666 (setq arg -1)
2667 (setq arg 1)))
2668 ((equal arg 'cpython) (setq arg 1))
2669 ((equal arg 'jpython) (setq arg -1)))
2670 (let (msg)
2671 (cond
2672 ((< 0 arg)
2673 ;; set to CPython
2674 (setq python-which-shell python-python-command
2675 python-which-args python-python-command-args
2676 python-which-bufname "Python"
2677 msg "CPython"
2678 mode-name "Python"))
2679 ((> 0 arg)
2680 (setq python-which-shell python-jython-command
2681 python-which-args python-jython-command-args
2682 python-which-bufname "JPython"
2683 msg "JPython"
2684 mode-name "JPython")))
2685 (message "Using the %s shell" msg)))
2686
2687 ;;;###autoload
2688 (defun python-shell (&optional argprompt)
2689 "Start an interactive Python interpreter in another window.
2690 This is like Shell mode, except that Python is running in the window
2691 instead of a shell. See the `Interactive Shell' and `Shell Mode'
2692 sections of the Emacs manual for details, especially for the key
2693 bindings active in the `*Python*' buffer.
2694
2695 With optional \\[universal-argument], the user is prompted for the
2696 flags to pass to the Python interpreter. This has no effect when this
2697 command is used to switch to an existing process, only when a new
2698 process is started. If you use this, you will probably want to ensure
2699 that the current arguments are retained (they will be included in the
2700 prompt). This argument is ignored when this function is called
2701 programmatically, or when running in Emacs 19.34 or older.
2702
2703 Note: You can toggle between using the CPython interpreter and the
2704 JPython interpreter by hitting \\[python-toggle-shells]. This toggles
2705 buffer local variables which control whether all your subshell
2706 interactions happen to the `*JPython*' or `*Python*' buffers (the
2707 latter is the name used for the CPython buffer).
2708
2709 Warning: Don't use an interactive Python if you change sys.ps1 or
2710 sys.ps2 from their default values, or if you're running code that
2711 prints `>>> ' or `... ' at the start of a line. `python-mode' can't
2712 distinguish your output from Python's output, and assumes that `>>> '
2713 at the start of a line is a prompt from Python. Similarly, the Emacs
2714 Shell mode code assumes that both `>>> ' and `... ' at the start of a
2715 line are Python prompts. Bad things can happen if you fool either
2716 mode.
2717
2718 Warning: If you do any editing *in* the process buffer *while* the
2719 buffer is accepting output from Python, do NOT attempt to `undo' the
2720 changes. Some of the output (nowhere near the parts you changed!) may
2721 be lost if you do. This appears to be an Emacs bug, an unfortunate
2722 interaction between undo and process filters; the same problem exists in
2723 non-Python process buffers using the default (Emacs-supplied) process
2724 filter."
2725 (interactive "P")
2726 ;; Set the default shell if not already set
2727 (when (null python-which-shell)
2728 (python-toggle-shells python-default-interpreter))
2729 (let ((args python-which-args))
2730 (when (and argprompt
2731 (interactive-p)
2732 (fboundp 'split-string))
2733 ;; TBD: Perhaps force "-i" in the final list?
2734 (setq args (split-string
2735 (read-string (concat python-which-bufname
2736 " arguments: ")
2737 (concat
2738 (mapconcat 'identity python-which-args " ") " ")
2739 ))))
2740 (switch-to-buffer-other-window
2741 (apply 'make-comint python-which-bufname python-which-shell nil args))
2742 (make-local-variable 'comint-prompt-regexp)
2743 (set-process-sentinel (get-buffer-process (current-buffer)) 'python-sentinel)
2744 (setq comint-prompt-regexp "^>>> \\|^[.][.][.] \\|^(pdb) ")
2745 (add-hook 'comint-output-filter-functions
2746 'python-comint-output-filter-function nil t)
2747 ;; pdbtrack
2748 (add-hook 'comint-output-filter-functions
2749 'python-pdbtrack-track-stack-file nil t)
2750 (setq python-pdbtrack-do-tracking-p t)
2751 (set-syntax-table python-mode-syntax-table)
2752 (use-local-map python-shell-map)))
2753
2754 (defun python-pdbtrack-toggle-stack-tracking (arg)
2755 (interactive "P")
2756 (if (not (get-buffer-process (current-buffer)))
2757 (error "No process associated with buffer '%s'" (current-buffer)))
2758 ;; missing or 0 is toggle, >0 turn on, <0 turn off
2759 (if (or (not arg)
2760 (zerop (setq arg (prefix-numeric-value arg))))
2761 (setq python-pdbtrack-do-tracking-p (not python-pdbtrack-do-tracking-p))
2762 (setq python-pdbtrack-do-tracking-p (> arg 0)))
2763 (message "%sabled Python's pdbtrack"
2764 (if python-pdbtrack-do-tracking-p "En" "Dis")))
2765
2766 (defun turn-on-pdbtrack ()
2767 (interactive)
2768 (python-pdbtrack-toggle-stack-tracking 1))
2769
2770 (defun turn-off-pdbtrack ()
2771 (interactive)
2772 (python-pdbtrack-toggle-stack-tracking 0))
2773
2774 (defun python-sentinel (proc msg)
2775 (setq overlay-arrow-position nil))
2776
2777 (provide 'python)
2778 (provide 'python-21)
2779 ;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
2780 ;;; python.el ends here