(python-beginning-of-statement): Exit the loop if backward-up-list gets error.
[bpt/emacs.git] / lisp / progmodes / python.el
CommitLineData
6f480c7a
SM
1;;; python.el --- silly walks for Python
2
3;; Copyright (C) 2003, 04 Free Software Foundation, Inc.
4
5;; Author: Dave Love <fx@gnu.org>
c02484a0 6;; Maintainer: FSF
6f480c7a
SM
7;; Created: Nov 2003
8;; Keywords: languages
9
10;; This file is part of GNU Emacs.
11
12;; This file is free software; you can redistribute it and/or modify
13;; it under the terms of the GNU General Public License as published by
14;; the Free Software Foundation; either version 2, or (at your option)
15;; any later version.
16
17;; This file 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
24;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25;; Boston, MA 02111-1307, 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, perhaps, better in other ways. In particular,
36;; using the syntax functions with text properties maintained by
37;; font-lock should make it more correct with arbitrary string and
38;; comment contents.
39
40;; This doesn't implement all the facilities of python-mode.el. Some
41;; just need doing, e.g. catching exceptions in the inferior Python
0578dead 42;; buffer (but see M-x pdb for debugging). [Actually, the use of
6f480c7a
SM
43;; `compilation-minor-mode' now is probably enough for that.] Others
44;; don't seem appropriate. For instance, `forward-into-nomenclature'
45;; should be done separately, since it's not specific to Python, and
46;; I've installed a minor mode to do the job properly in Emacs 22.
47;; Other things seem more natural or canonical here, e.g. the
48;; {beginning,end}-of-defun implementation dealing with nested
24d5055c
SM
49;; definitions, and the inferior mode following `cmuscheme'. The
50;; inferior mode can find the source of errors from
51;; `python-send-region' & al via `compilation-minor-mode'. Successive
52;; TABs cycle between possible indentations for the line. There is
53;; symbol completion using lookup in Python.
6f480c7a
SM
54
55;; Even where it has similar facilities, this is incompatible with
56;; python-mode.el in various respects. For instance, various key
57;; bindings are changed to obey Emacs conventions, and things like
58;; marking blocks and `beginning-of-defun' behave differently.
59
24d5055c 60;; TODO: See various Fixmes below.
0578dead 61
6f480c7a
SM
62;;; Code:
63
6f480c7a
SM
64;; It's messy to autoload the relevant comint functions so that comint
65;; is only required when inferior Python is used.
66(require 'comint)
0578dead
SM
67(eval-when-compile
68 (require 'compile)
0578dead 69 (autoload 'info-lookup-maybe-add-help "info-look"))
b6ea7940 70(autoload 'compilation-start "compile")
6f480c7a
SM
71
72(defgroup python nil
73 "Silly walks in the Python language"
74 :group 'languages
0578dead 75 :version "21.4"
6f480c7a
SM
76 :link '(emacs-commentary-link "python"))
77\f
78;;;###autoload
79(add-to-list 'interpreter-mode-alist '("jython" . jython-mode))
80;;;###autoload
81(add-to-list 'interpreter-mode-alist '("python" . python-mode))
82;;;###autoload
83(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
84\f
85;;;; Font lock
86
87(defvar python-font-lock-keywords
88 `(,(rx (and word-start
89 ;; From v 2.3 reference.
90 ;; def and class dealt with separately below
91 (or "and" "assert" "break" "continue" "del" "elif" "else"
92 "except" "exec" "finally" "for" "from" "global" "if"
93 "import" "in" "is" "lambda" "not" "or" "pass" "print"
94 "raise" "return" "try" "while" "yield"
95 ;; Future keywords
96 "as" "None")
97 word-end))
98 (,(rx (and word-start (group "class") (1+ space) (group (1+ word))))
99 (1 font-lock-keyword-face) (2 font-lock-type-face))
100 (,(rx (and word-start (group "def") (1+ space) (group (1+ word))))
101 (1 font-lock-keyword-face) (2 font-lock-function-name-face))))
102
103(defconst python-font-lock-syntactic-keywords
104 ;; Make outer chars of matching triple-quote sequences into generic
105 ;; string delimiters. Fixme: Is there a better way?
106 `((,(rx (and (group (optional (any "uUrR"))) ; prefix gets syntax property
107 (optional (any "rR")) ; possible second prefix
108 (group (syntax string-quote)) ; maybe gets property
109 (backref 2) ; per first quote
110 (group (backref 2)))) ; maybe gets property
0578dead
SM
111 (1 (python-quote-syntax 1))
112 (2 (python-quote-syntax 2))
6f480c7a
SM
113 (3 (python-quote-syntax 3)))
114 ;; This doesn't really help.
115;;; (,(rx (and ?\\ (group ?\n))) (1 " "))
116 ))
117
118(defun python-quote-syntax (n)
119 "Put `syntax-table' property correctly on triple quote.
120Used for syntactic keywords. N is the match number (1, 2 or 3)."
0578dead
SM
121 ;; Given a triple quote, we have to check the context to know
122 ;; whether this is an opening or closing triple or whether it's
123 ;; quoted anyhow, and should be ignored. (For that we need to do
124 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
125 ;; to use it here despite initial worries.) We also have to sort
126 ;; out a possible prefix -- well, we don't _have_ to, but I think it
127 ;; should be treated as part of the string.
128
129 ;; Test cases:
130 ;; ur"""ar""" x='"' # """
131 ;; x = ''' """ ' a
132 ;; '''
133 ;; x '"""' x
134 (save-excursion
135 (goto-char (match-beginning 0))
136 (unless (eq ?\\ (char-before))
137 (cond
138 ;; Consider property for the last char if in a fenced string.
139 ((= n 3)
140 (let ((syntax (syntax-ppss)))
141 (when (eq t (nth 3 syntax)) ; after unclosed fence
142 (goto-char (nth 8 syntax)) ; fence position
143 ;; Skip any prefix.
144 (if (memq (char-after) '(?u ?U ?R ?r))
145 (skip-chars-forward "uUrR"))
146 ;; Is it a matching sequence?
147 (if (eq (char-after) (char-after (match-beginning 2)))
148 (eval-when-compile (string-to-syntax "|"))))))
149 ;; Consider property for initial char, accounting for prefixes.
150 ((or (and (= n 2) ; not prefix
151 (= (match-beginning 1) (match-end 1))) ; prefix is null
152 (and (= n 1) ; prefix
153 (/= (match-beginning 1) (match-end 1)))) ; non-empty
154 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
155 (eval-when-compile (string-to-syntax "|")))))
156 ;; Otherwise (we're in a non-matching string) the property is
157 ;; nil, which is OK.
6f480c7a
SM
158 )))
159
160;; This isn't currently in `font-lock-defaults' as probably not worth
161;; it -- we basically only mess with a few normally-symbol characters.
162
163;; (defun python-font-lock-syntactic-face-function (state)
164;; "`font-lock-syntactic-face-function' for Python mode.
165;; Returns the string or comment face as usual, with side effect of putting
166;; a `syntax-table' property on the inside of the string or comment which is
167;; the standard syntax table."
168;; (if (nth 3 state)
169;; (save-excursion
170;; (goto-char (nth 8 state))
171;; (condition-case nil
172;; (forward-sexp)
173;; (error nil))
174;; (put-text-property (1+ (nth 8 state)) (1- (point))
175;; 'syntax-table (standard-syntax-table))
176;; 'font-lock-string-face)
177;; (put-text-property (1+ (nth 8 state)) (line-end-position)
178;; 'syntax-table (standard-syntax-table))
179;; 'font-lock-comment-face))
180\f
181;;;; Keymap and syntax
182
183(defvar python-mode-map
184 (let ((map (make-sparse-keymap)))
185 ;; Mostly taken from python-mode.el.
186 (define-key map ":" 'python-electric-colon)
187 (define-key map "\177" 'python-backspace)
188 (define-key map "\C-c<" 'python-shift-left)
189 (define-key map "\C-c>" 'python-shift-right)
190 (define-key map "\C-c\C-k" 'python-mark-block)
191 (define-key map "\C-c\C-n" 'python-next-statement)
192 (define-key map "\C-c\C-p" 'python-previous-statement)
193 (define-key map "\C-c\C-u" 'python-beginning-of-block)
194 (define-key map "\C-c\C-f" 'python-describe-symbol)
195 (define-key map "\C-c\C-w" 'python-check)
196 (define-key map "\C-c\C-v" 'python-check) ; a la sgml-mode
197 (define-key map "\C-c\C-s" 'python-send-string)
198 (define-key map [?\C-\M-x] 'python-send-defun)
199 (define-key map "\C-c\C-r" 'python-send-region)
200 (define-key map "\C-c\M-r" 'python-send-region-and-go)
201 (define-key map "\C-c\C-c" 'python-send-buffer)
202 (define-key map "\C-c\C-z" 'python-switch-to-python)
203 (define-key map "\C-c\C-m" 'python-load-file)
204 (define-key map "\C-c\C-l" 'python-load-file) ; a la cmuscheme
24d5055c
SM
205 (substitute-key-definition 'complete-symbol 'python-complete-symbol
206 map global-map)
6f480c7a
SM
207 ;; Fixme: Add :help to menu.
208 (easy-menu-define python-menu map "Python Mode menu"
209 '("Python"
210 ["Shift region left" python-shift-left :active mark-active]
211 ["Shift region right" python-shift-right :active mark-active]
212 "-"
213 ["Mark block" python-mark-block]
214 ["Mark def/class" mark-defun
215 :help "Mark innermost definition around point"]
216 "-"
217 ["Start of block" python-beginning-of-block]
218 ["End of block" python-end-of-block]
219 ["Start of def/class" beginning-of-defun
220 :help "Go to start of innermost definition around point"]
221 ["End of def/class" end-of-defun
222 :help "Go to end of innermost definition around point"]
223 "-"
224 ["Start interpreter" run-python
225 :help "Run `inferior' Python in separate buffer"]
226 ["Import/reload file" python-load-file
227 :help "Load into inferior Python session"]
228 ["Eval buffer" python-send-buffer
229 :help "Evaluate buffer en bloc in inferior Python session"]
230 ["Eval region" python-send-region :active mark-active
231 :help "Evaluate region en bloc in inferior Python session"]
232 ["Eval def/class" python-send-defun
233 :help "Evaluate current definition in inferior Python session"]
234 ["Switch to interpreter" python-switch-to-python
235 :help "Switch to inferior Python buffer"]
236 ["Check file" python-check :help "Run pychecker"]
237 ["Debugger" pdb :help "Run pdb under GUD"]
238 "-"
239 ["Help on symbol" python-describe-symbol
240 :help "Use pydoc on symbol at point"]))
241 map))
242
243(defvar python-mode-syntax-table
244 (let ((table (make-syntax-table)))
245 ;; Give punctuation syntax to ASCII that normally has symbol
246 ;; syntax or has word syntax and isn't a letter.
247 (let ((symbol (string-to-syntax "_"))
248 (sst (standard-syntax-table)))
249 (dotimes (i 128)
250 (unless (= i ?_)
251 (if (equal symbol (aref sst i))
252 (modify-syntax-entry i "." table)))))
253 (modify-syntax-entry ?$ "." table)
254 (modify-syntax-entry ?% "." table)
255 ;; exceptions
256 (modify-syntax-entry ?# "<" table)
257 (modify-syntax-entry ?\n ">" table)
258 (modify-syntax-entry ?' "\"" table)
259 (modify-syntax-entry ?` "$" table)
260 table))
261\f
262;;;; Utility stuff
263
264(defsubst python-in-string/comment ()
24d5055c 265 "Return non-nil if point is in a Python literal (a comment or string)."
6f480c7a
SM
266 (syntax-ppss-context (syntax-ppss)))
267
268(defconst python-space-backslash-table
269 (let ((table (copy-syntax-table python-mode-syntax-table)))
270 (modify-syntax-entry ?\\ " " table)
271 table)
272 "`python-mode-syntax-table' with backslash given whitespace syntax.")
273
274(defun python-skip-comments/blanks (&optional backward)
275 "Skip comments and blank lines.
276BACKWARD non-nil means go backwards, otherwise go forwards. Backslash is
277treated as whitespace so that continued blank lines are skipped.
278Doesn't move out of comments -- should be outside or at end of line."
279 (with-syntax-table python-space-backslash-table
280 (forward-comment (if backward
281 most-negative-fixnum
282 most-positive-fixnum))))
283
284(defun python-backslash-continuation-line-p ()
285 "Non-nil if preceding line ends with backslash that is not in a comment."
286 (and (eq ?\\ (char-before (line-end-position 0)))
287 (not (syntax-ppss-context (syntax-ppss)))))
288
289(defun python-continuation-line-p ()
290 "Return non-nil if current line continues a previous one.
291The criteria are that the previous line ends in a backslash outside
292comments and strings, or that the bracket/paren nesting depth is nonzero."
293 (or (and (eq ?\\ (char-before (line-end-position 0)))
294 (not (syntax-ppss-context (syntax-ppss))))
295 (/= 0 (syntax-ppss-depth
296 (save-excursion ; syntax-ppss with arg changes point
297 (syntax-ppss (line-beginning-position)))))))
298
299(defun python-comment-line-p ()
07c7712f 300 "Return non-nil iff current line has only a comment."
6f480c7a 301 (save-excursion
24d5055c 302 (end-of-line)
24d5055c
SM
303 (when (eq 'comment (syntax-ppss-context (syntax-ppss)))
304 (back-to-indentation)
305 (looking-at (rx (or (syntax comment-start) line-end))))))
6f480c7a
SM
306
307(defun python-beginning-of-string ()
308 "Go to beginning of string around point.
309Do nothing if not in string."
310 (let ((state (syntax-ppss)))
24d5055c 311 (when (eq 'string (syntax-ppss-context state))
6f480c7a
SM
312 (goto-char (nth 8 state)))))
313
314(defun python-open-block-statement-p (&optional bos)
315 "Return non-nil if statement at point opens a block.
316BOS non-nil means point is known to be at beginning of statement."
317 (save-excursion
318 (unless bos (python-beginning-of-statement))
319 (and (not (python-comment-line-p))
320 (re-search-forward (rx (and ?: (0+ space)
321 (optional (and (syntax comment-start)
322 (0+ not-newline)))
323 line-end))
324 (save-excursion (python-end-of-statement))
325 t)
cebe0988
EZ
326 (not (progn (goto-char (match-beginning 0))
327 (python-in-string/comment))))))
6f480c7a
SM
328
329(defun python-close-block-statement-p (&optional bos)
330 "Return non-nil if current line is a statement closing a block.
331BOS non-nil means point is at beginning of statement.
332The criteria are that the line isn't a comment or in string and starts with
333keyword `raise', `break', `continue' or `pass'."
334 (save-excursion
335 (unless bos (python-beginning-of-statement))
336 (back-to-indentation)
337 (looking-at (rx (and (or "return" "raise" "break" "continue" "pass")
338 word-end)))))
339
340(defun python-outdent-p ()
341 "Return non-nil if current line should outdent a level."
342 (save-excursion
343 (back-to-indentation)
344 (and (looking-at (rx (and (or (and (or "else" "finally") word-end)
345 (and (or "except" "elif") word-end
346 (1+ (not (any ?:)))))
347 (optional space) ":" (optional space)
348 (or (syntax comment-start) line-end))))
349 (progn (end-of-line)
350 (not (python-in-string/comment)))
351 ;; Ensure there's a previous statement and move to it.
352 (zerop (python-previous-statement))
353 (not (python-close-block-statement-p t))
354 ;; Fixme: check this
355 (not (looking-at (rx (and (or (and (or "if" "elif" "except"
356 "for" "while")
357 word-end (1+ (not (any ?:))))
358 (and "try" word-end))
359 (optional space) ":" (optional space)
360 (or (syntax comment-start) line-end)))))
361 (progn (end-of-line)
362 (not (python-in-string/comment))))))
363\f
364;;;; Indentation.
365
366(defcustom python-indent 4
367 "*Number of columns for a unit of indentation in Python mode.
368See also `\\[python-guess-indent]'"
369 :group 'python
370 :type 'integer)
371
372(defcustom python-guess-indent t
373 "*Non-nil means Python mode guesses `python-indent' for the buffer."
374 :type 'boolean
375 :group 'python)
376
377(defcustom python-indent-string-contents t
378 "*Non-nil means indent contents of multi-line strings together.
379This means indent them the same as the preceding non-blank line.
380Otherwise indent them to column zero."
381 :type '(choice (const :tag "Align with preceding" t)
382 (const :tag "Indent to column 0" nil))
383 :group 'python)
384
385(defcustom python-honour-comment-indentation nil
386 "Non-nil means indent relative to preceding comment line.
387Only do this for comments where the leading comment character is followed
24d5055c
SM
388by space. This doesn't apply to comment lines, which are always indented
389in lines with preceding comments."
6f480c7a
SM
390 :type 'boolean
391 :group 'python)
392
393(defcustom python-continuation-offset 4
394 "*Number of columns of additional indentation for continuation lines.
395Continuation lines follow a backslash-terminated line starting a statement."
396 :group 'python
397 :type 'integer)
398
399(defun python-guess-indent ()
400 "Guess step for indentation of current buffer.
401Set `python-indent' locally to the value guessed."
402 (interactive)
403 (save-excursion
0578dead
SM
404 (save-restriction
405 (widen)
406 (goto-char (point-min))
407 (let (done indent)
408 (while (and (not done) (not (eobp)))
409 (when (and (re-search-forward (rx (and ?: (0+ space)
410 (or (syntax comment-start)
411 line-end)))
412 nil 'move)
413 (python-open-block-statement-p))
414 (save-excursion
415 (python-beginning-of-statement)
416 (let ((initial (current-indentation)))
417 (if (zerop (python-next-statement))
418 (setq indent (- (current-indentation) initial)))
419 (if (and (>= indent 2) (<= indent 8)) ; sanity check
420 (setq done t))))))
421 (when done
422 (when (/= indent (default-value 'python-indent))
423 (set (make-local-variable 'python-indent) indent)
424 (unless (= tab-width python-indent)
425 (setq indent-tabs-mode nil)))
426 indent)))))
6f480c7a
SM
427
428(defun python-calculate-indentation ()
429 "Calculate Python indentation for line at point."
430 (save-excursion
431 (beginning-of-line)
432 (let ((syntax (syntax-ppss))
433 start)
434 (cond
435 ((eq 'string (syntax-ppss-context syntax)) ; multi-line string
436 (if (not python-indent-string-contents)
437 0
438 (save-excursion
439 ;; Find indentation of preceding non-blank line within string.
440 (setq start (nth 8 syntax))
441 (forward-line -1)
442 (while (and (< start (point)) (looking-at "\\s-*$"))
443 (forward-line -1))
444 (current-indentation))))
445 ((python-continuation-line-p)
446 (let ((point (point))
447 (open-start (cadr syntax)))
448 (if open-start
449 ;; Inside bracketed expression.
450 (progn
451 (goto-char (1+ open-start))
452 ;; Look for first item in list (preceding point) and
453 ;; align with it, if found.
454 (if (with-syntax-table python-space-backslash-table
455 (let ((parse-sexp-ignore-comments t))
456 (condition-case ()
457 (progn (forward-sexp)
458 (backward-sexp)
459 (< (point) point))
460 (error nil))))
461 (current-column)
462 ;; Otherwise indent relative to statement start, one
463 ;; level per bracketing level.
464 (goto-char (1+ open-start))
465 (python-beginning-of-statement)
466 (+ (current-indentation) (* (car syntax) python-indent))))
467 ;; Otherwise backslash-continued.
468 (forward-line -1)
469 (if (python-continuation-line-p)
470 ;; We're past first continuation line. Align with
471 ;; previous line.
472 (current-indentation)
473 ;; First continuation line. Indent one step, with an
474 ;; extra one if statement opens a block.
475 (save-excursion
476 (python-beginning-of-statement)
477 (+ (current-indentation) python-continuation-offset
478 (if (python-open-block-statement-p t)
479 python-indent
480 0)))))))
481 ((bobp) 0)
482 ;; Fixme: Like python-mode.el; not convinced by this.
483 ((looking-at (rx (and (0+ space) (syntax comment-start)
484 (not (any " \t\n"))))) ; non-indentable comment
485 (current-indentation))
486 (t (let ((point (point)))
487 (if python-honour-comment-indentation
488 ;; Back over whitespace, newlines, non-indentable comments.
489 (catch 'done
490 (while t
491 (if (cond ((bobp))
492 ;; not at comment start
493 ((not (forward-comment -1))
494 (python-beginning-of-statement)
495 t)
496 ;; trailing comment
497 ((/= (current-column) (current-indentation))
498 (python-beginning-of-statement)
499 t)
500 ;; indentable comment like python-mode.el
501 ((and (looking-at (rx (and (syntax comment-start)
502 (or space line-end))))
503 (/= 0 (current-column)))))
504 (throw 'done t))))
505 ;; Else back over all comments.
506 (python-skip-comments/blanks t)
507 (python-beginning-of-statement))
508 ;; don't lose on bogus outdent
509 (max 0 (+ (current-indentation)
510 (or (cond ((python-open-block-statement-p t)
511 python-indent)
512 ((python-close-block-statement-p t)
513 (- python-indent)))
514 (progn (goto-char point)
515 (if (python-outdent-p)
516 (- python-indent)))
517 0)))))))))
518
24d5055c
SM
519(defun python-comment-indent ()
520 "`comment-indent-function' for Python."
521 ;; If previous non-blank line was a comment, use its indentation.
522 ;; FIXME: This seems unnecessary since the default code delegates to
523 ;; indent-according-to-mode. --Stef
524 (unless (bobp)
525 (save-excursion
526 (forward-comment -1)
527 (if (eq ?# (char-after)) (current-column)))))
528
6f480c7a
SM
529;;;; Cycling through the possible indentations with successive TABs.
530
531;; These don't need to be buffer-local since they're only relevant
532;; during a cycle.
533
534;; Alist of possible indentations and start of statement they would close.
535(defvar python-indent-list nil
536 "Internal use.")
537;; Length of the above
538(defvar python-indent-list-length nil
539 "Internal use.")
540;; Current index into the alist.
541(defvar python-indent-index nil
542 "Internal use.")
543
544(defun python-initial-text ()
545 "Text of line following indentation and ignoring any trailing comment."
546 (buffer-substring (+ (line-beginning-position) (current-indentation))
547 (save-excursion
548 (end-of-line)
549 (forward-comment -1)
550 (point))))
551
552(defun python-indentation-levels ()
24d5055c 553 "Return a list of possible indentations for this line.
6f480c7a 554Includes the default indentation and those which would close all
24d5055c
SM
555enclosing blocks. Assumes the line has already been indented per
556`python-indent-line'. Elements of the list are actually pairs:
557\(INDENTATION . TEXT), where TEXT is the initial text of the
558corresponding block opening (or nil)."
6f480c7a 559 (save-excursion
24d5055c
SM
560 (let ((levels (list (cons (current-indentation)
561 (save-excursion
562 (if (python-beginning-of-block)
563 (python-initial-text)))))))
6f480c7a
SM
564 ;; Only one possibility if we immediately follow a block open or
565 ;; are in a continuation line.
566 (unless (or (python-continuation-line-p)
567 (save-excursion (and (python-previous-statement)
568 (python-open-block-statement-p t))))
569 (while (python-beginning-of-block)
570 (push (cons (current-indentation) (python-initial-text))
571 levels)))
572 levels)))
573
574;; This is basically what `python-indent-line' would be if we didn't
575;; do the cycling.
576(defun python-indent-line-1 ()
577 "Subroutine of `python-indent-line'."
578 (let ((target (python-calculate-indentation))
579 (pos (- (point-max) (point))))
580 (if (= target (current-indentation))
581 (if (< (current-column) (current-indentation))
582 (back-to-indentation))
583 (beginning-of-line)
584 (delete-horizontal-space)
585 (indent-to target)
586 (if (> (- (point-max) pos) (point))
587 (goto-char (- (point-max) pos))))))
588
24d5055c 589(defun python-indent-line ()
6f480c7a
SM
590 "Indent current line as Python code.
591When invoked via `indent-for-tab-command', cycle through possible
592indentations for current line. The cycle is broken by a command different
593from `indent-for-tab-command', i.e. successive TABs do the cycling."
594 (interactive)
595 ;; Don't do extra work if invoked via `indent-region', for instance.
596 (if (not (eq this-command 'indent-for-tab-command))
597 (python-indent-line-1)
598 (if (eq last-command this-command)
599 (if (= 1 python-indent-list-length)
600 (message "Sole indentation")
601 (progn (setq python-indent-index (% (1+ python-indent-index)
602 python-indent-list-length))
603 (beginning-of-line)
604 (delete-horizontal-space)
605 (indent-to (car (nth python-indent-index python-indent-list)))
24d5055c
SM
606 (if (python-block-end-p)
607 (let ((text (cdr (nth python-indent-index
608 python-indent-list))))
609 (if text
610 (message "Closes: %s" text))))))
6f480c7a
SM
611 (python-indent-line-1)
612 (setq python-indent-list (python-indentation-levels)
613 python-indent-list-length (length python-indent-list)
614 python-indent-index (1- python-indent-list-length)))))
24d5055c
SM
615
616(defun python-block-end-p ()
617 "Non-nil if this is a line in a statement closing a block,
618or a blank line indented to where it would close a block."
619 (and (not (python-comment-line-p))
620 (or (python-close-block-statement-p t)
621 (< (current-indentation)
622 (save-excursion
623 (python-previous-statement)
624 (current-indentation))))))
625
626;; Fixme: Define an indent-region-function. It should probably leave
627;; lines alone if the indentation is already at one of the allowed
628;; levels. Otherwise, M-C-\ typically keeps indenting more deeply
629;; down a function.
6f480c7a
SM
630\f
631;;;; Movement.
632
633(defun python-beginning-of-defun ()
634 "`beginning-of-defun-function' for Python.
635Finds beginning of innermost nested class or method definition.
636Returns the name of the definition found at the end, or nil if reached
637start of buffer."
638 (let ((ci (current-indentation))
639 (def-re (rx (and line-start (0+ space) (or "def" "class")
640 (1+ space)
641 (group (1+ (or word (syntax symbol)))))))
a1ae0e9c 642 found lep def-line)
6f480c7a
SM
643 (if (python-comment-line-p)
644 (setq ci most-positive-fixnum))
645 (while (and (not (bobp)) (not found))
646 ;; Treat bol at beginning of function as outside function so
647 ;; that successive C-M-a makes progress backwards.
648 (setq def-line (looking-at def-re))
649 (unless (bolp) (end-of-line))
650 (setq lep (line-end-position))
651 (if (and (re-search-backward def-re nil 'move)
652 ;; Must be less indented or matching top level, or
653 ;; equally indented if we started on a definition line.
654 (let ((in (current-indentation)))
655 (or (and (zerop ci) (zerop in))
656 (= lep (line-end-position)) ; on initial line
657 (and def-line (= in ci))
658 (< in ci)))
659 (not (python-in-string/comment)))
660 (setq found t)))))
661
662(defun python-end-of-defun ()
663 "`end-of-defun-function' for Python.
664Finds end of innermost nested class or method definition."
665 (let ((orig (point))
24d5055c 666 (pattern (rx (and line-start (0+ space) (or "def" "class") space))))
6f480c7a
SM
667 ;; Go to start of current block and check whether it's at top
668 ;; level. If it is, and not a block start, look forward for
669 ;; definition statement.
670 (when (python-comment-line-p)
671 (end-of-line)
672 (forward-comment most-positive-fixnum))
673 (if (not (python-open-block-statement-p))
674 (python-beginning-of-block))
675 (if (zerop (current-indentation))
676 (unless (python-open-block-statement-p)
677 (while (and (re-search-forward pattern nil 'move)
678 (python-in-string/comment))) ; just loop
679 (unless (eobp)
680 (beginning-of-line)))
681 ;; Don't move before top-level statement that would end defun.
682 (end-of-line)
683 (python-beginning-of-defun))
684 ;; If we got to the start of buffer, look forward for
685 ;; definition statement.
686 (if (and (bobp) (not (looking-at "def\\|class")))
687 (while (and (not (eobp))
688 (re-search-forward pattern nil 'move)
689 (python-in-string/comment)))) ; just loop
690 ;; We're at a definition statement (or end-of-buffer).
691 (unless (eobp)
692 (python-end-of-block)
693 ;; Count trailing space in defun (but not trailing comments).
694 (skip-syntax-forward " >")
695 (beginning-of-line))
696 ;; Catch pathological case like this, where the beginning-of-defun
697 ;; skips to a definition we're not in:
698 ;; if ...:
699 ;; ...
700 ;; else:
701 ;; ... # point here
702 ;; ...
703 ;; def ...
704 (if (< (point) orig)
705 (goto-char (point-max)))))
706
707(defun python-beginning-of-statement ()
708 "Go to start of current statement.
709Accounts for continuation lines, multi-line strings, and multi-line bracketed
710expressions."
711 (beginning-of-line)
712 (python-beginning-of-string)
b830b63b
RS
713 (catch 'foo
714 (while (python-continuation-line-p)
715 (beginning-of-line)
716 (if (python-backslash-continuation-line-p)
717 (while (python-backslash-continuation-line-p)
718 (forward-line -1))
719 (python-beginning-of-string)
720 ;; Skip forward out of nested brackets.
721 (condition-case () ; beware invalid syntax
722 (progn (backward-up-list (syntax-ppss-depth (syntax-ppss))) t)
723 (error (throw 'foo nil))))))
6f480c7a
SM
724 (back-to-indentation))
725
726(defun python-end-of-statement ()
727 "Go to the end of the current statement and return point.
728Usually this is the start of the next line, but if this is a
729multi-line statement we need to skip over the continuation lines.
730On a comment line, go to end of line."
731 (end-of-line)
732 (while (let (comment)
733 ;; Move past any enclosing strings and sexps, or stop if
734 ;; we're in a comment.
735 (while (let ((s (syntax-ppss)))
736 (cond ((eq 'comment (syntax-ppss-context s))
737 (setq comment t)
738 nil)
739 ((eq 'string (syntax-ppss-context s))
740 ;; Go to start of string and skip it.
741 (goto-char (nth 8 s))
742 (condition-case () ; beware invalid syntax
743 (progn (forward-sexp) t)
744 (error (end-of-line))))
745 ((> (syntax-ppss-depth s) 0)
746 ;; Skip forward out of nested brackets.
747 (condition-case () ; beware invalid syntax
748 (progn (backward-up-list
749 (- (syntax-ppss-depth s)))
750 t)
751 (error (end-of-line))))))
752 (end-of-line))
753 (unless comment
754 (eq ?\\ (char-before)))) ; Line continued?
755 (end-of-line 2)) ; Try next line.
756 (point))
757
758(defun python-previous-statement (&optional count)
759 "Go to start of previous statement.
760With argument COUNT, do it COUNT times. Stop at beginning of buffer.
761Return count of statements left to move."
762 (interactive "p")
763 (unless count (setq count 1))
764 (if (< count 0)
765 (python-next-statement (- count))
766 (python-beginning-of-statement)
767 (while (and (> count 0) (not (bobp)))
768 (python-skip-comments/blanks t)
769 (python-beginning-of-statement)
770 (unless (bobp) (setq count (1- count))))
771 count))
772
773(defun python-next-statement (&optional count)
774 "Go to start of next statement.
775With argument COUNT, do it COUNT times. Stop at end of buffer.
776Return count of statements left to move."
777 (interactive "p")
778 (unless count (setq count 1))
779 (if (< count 0)
780 (python-previous-statement (- count))
781 (beginning-of-line)
782 (while (and (> count 0) (not (eobp)))
783 (python-end-of-statement)
784 (python-skip-comments/blanks)
785 (setq count (1- count)))
786 count))
787
788(defun python-beginning-of-block (&optional arg)
789 "Go to start of current block.
790With numeric arg, do it that many times. If ARG is negative, call
791`python-end-of-block' instead.
792If point is on the first line of a block, use its outer block.
793If current statement is in column zero, don't move and return nil.
794Otherwise return non-nil."
795 (interactive "p")
796 (unless arg (setq arg 1))
797 (cond
798 ((zerop arg))
799 ((< arg 0) (python-end-of-block (- arg)))
800 (t
801 (let ((point (point)))
802 (if (python-comment-line-p)
803 (python-skip-comments/blanks t))
804 (python-beginning-of-statement)
805 (let ((ci (current-indentation)))
806 (if (zerop ci)
807 (not (goto-char point)) ; return nil
808 ;; Look upwards for less indented statement.
809 (if (catch 'done
810;;; This is slower than the below.
811;;; (while (zerop (python-previous-statement))
812;;; (when (and (< (current-indentation) ci)
813;;; (python-open-block-statement-p t))
814;;; (beginning-of-line)
815;;; (throw 'done t)))
816 (while (and (zerop (forward-line -1)))
817 (when (and (< (current-indentation) ci)
818 (not (python-comment-line-p))
819 ;; Move to beginning to save effort in case
820 ;; this is in string.
821 (progn (python-beginning-of-statement) t)
822 (python-open-block-statement-p t))
823 (beginning-of-line)
824 (throw 'done t)))
825 (not (goto-char point))) ; Failed -- return nil
826 (python-beginning-of-block (1- arg)))))))))
827
828(defun python-end-of-block (&optional arg)
829 "Go to end of current block.
830With numeric arg, do it that many times. If ARG is negative, call
831`python-beginning-of-block' instead.
832If current statement is in column zero and doesn't open a block, don't
833move and return nil. Otherwise return t."
834 (interactive "p")
835 (unless arg (setq arg 1))
836 (if (< arg 0)
837 (python-beginning-of-block (- arg)))
838 (while (and (> arg 0)
839 (let* ((point (point))
840 (_ (if (python-comment-line-p)
841 (python-skip-comments/blanks t)))
842 (ci (current-indentation))
843 (open (python-open-block-statement-p)))
844 (if (and (zerop ci) (not open))
845 (not (goto-char point))
846 (catch 'done
847 (while (zerop (python-next-statement))
848 (when (or (and open (<= (current-indentation) ci))
849 (< (current-indentation) ci))
850 (python-skip-comments/blanks t)
851 (beginning-of-line 2)
852 (throw 'done t)))
853 (not (goto-char point))))))
854 (setq arg (1- arg)))
855 (zerop arg))
856\f
857;;;; Imenu.
858
a1ae0e9c 859(defvar python-recursing)
6f480c7a
SM
860(defun python-imenu-create-index ()
861 "`imenu-create-index-function' for Python.
862
863Makes nested Imenu menus from nested `class' and `def' statements.
864The nested menus are headed by an item referencing the outer
865definition; it has a space prepended to the name so that it sorts
b6ea7940
SM
866first with `imenu--sort-by-name' (though, unfortunately, sub-menus
867precede it)."
a1ae0e9c 868 (unless (boundp 'python-recursing) ; dynamically bound below
6f480c7a
SM
869 (goto-char (point-min))) ; normal call from Imenu
870 (let (index-alist ; accumulated value to return
a1ae0e9c 871 name)
6f480c7a
SM
872 (while (re-search-forward
873 (rx (and line-start (0+ space) ; leading space
874 (or (group "def") (group "class")) ; type
875 (1+ space) (group (1+ (or word ?_))))) ; name
876 nil t)
877 (unless (python-in-string/comment)
878 (let ((pos (match-beginning 0))
879 (name (match-string-no-properties 3)))
880 (if (match-beginning 2) ; def or class?
881 (setq name (concat "class " name)))
882 (save-restriction
883 (narrow-to-defun)
a1ae0e9c 884 (let* ((python-recursing t)
6f480c7a
SM
885 (sublist (python-imenu-create-index)))
886 (if sublist
887 (progn (push (cons (concat " " name) pos) sublist)
888 (push (cons name sublist) index-alist))
889 (push (cons name pos) index-alist)))))))
890 (nreverse index-alist)))
891\f
892;;;; `Electric' commands.
893
894(defun python-electric-colon (arg)
895 "Insert a colon and maybe outdent the line if it is a statement like `else'.
896With numeric ARG, just insert that many colons. With \\[universal-argument],
897just insert a single colon."
898 (interactive "*P")
899 (self-insert-command (if (not (integerp arg)) 1 arg))
900 (and (not arg)
901 (eolp)
902 (python-outdent-p)
903 (not (python-in-string/comment))
904 (> (current-indentation) (python-calculate-indentation))
905 (python-indent-line))) ; OK, do it
906(put 'python-electric-colon 'delete-selection t)
907
908(defun python-backspace (arg)
909 "Maybe delete a level of indentation on the current line.
910If not at the end of line's indentation, or on a comment line, just call
911`backward-delete-char-untabify'. With ARG, repeat that many times."
912 (interactive "*p")
913 (if (or (/= (current-indentation) (current-column))
914 (bolp)
915 (python-continuation-line-p))
916 (backward-delete-char-untabify arg)
917 (let ((indent 0))
918 (save-excursion
919 (while (and (> arg 0) (python-beginning-of-block))
920 (setq arg (1- arg)))
921 (when (zerop arg)
922 (setq indent (current-indentation))
923 (message "Closes %s" (python-initial-text))))
924 (delete-horizontal-space)
925 (indent-to indent))))
926(put 'python-backspace 'delete-selection 'supersede)
927\f
928;;;; pychecker
929
930(defcustom python-check-command "pychecker --stdlib"
931 "*Command used to check a Python file."
932 :type 'string
933 :group 'python)
934
935(defvar python-saved-check-command nil
936 "Internal use.")
937
6f480c7a
SM
938;; After `sgml-validate-command'.
939(defun python-check (command)
940 "Check a Python file (default current buffer's file).
941Runs COMMAND, a shell command, as if by `compile'.
942See `python-check-command' for the default."
943 (interactive
944 (list (read-string "Checker command: "
945 (or python-saved-check-command
946 (concat python-check-command " "
947 (let ((name (buffer-file-name)))
948 (if name
949 (file-name-nondirectory name))))))))
950 (setq python-saved-check-command command)
951 (save-some-buffers (not compilation-ask-about-save) nil)
24d5055c
SM
952 (let ((compilation-error-regexp-alist
953 (cons '("(\\([^,]+\\), line \\([0-9]+\\))" 1 2)
954 compilation-error-regexp-alist)))
955 (compilation-start command)))
6f480c7a
SM
956\f
957;;;; Inferior mode stuff (following cmuscheme).
958
24d5055c
SM
959;; Fixme: Make sure we can work with IPython.
960
6f480c7a
SM
961(defcustom python-python-command "python"
962 "*Shell command to run Python interpreter.
24d5055c
SM
963Any arguments can't contain whitespace.
964Note that IPython may not work properly; it must at least be used with the
965`-cl' flag, i.e. use `ipython -cl'."
6f480c7a
SM
966 :group 'python
967 :type 'string)
968
969(defcustom python-jython-command "jython"
970 "*Shell command to run Jython interpreter.
971Any arguments can't contain whitespace."
972 :group 'python
973 :type 'string)
974
975(defvar python-command python-python-command
976 "Actual command used to run Python.
977May be `python-python-command' or `python-jython-command'.
978Additional arguments are added when the command is used by `run-python'
979et al.")
980
981(defvar python-buffer nil
b6ea7940
SM
982 "The current python process buffer."
983 ;; Fixme: a single process is currently assumed, so that this doc
984 ;; is misleading.
985
986;; "*The current python process buffer.
987;; To run multiple Python processes, start the first with \\[run-python].
988;; It will be in a buffer named *Python*. Rename that with
989;; \\[rename-buffer]. Now start a new process with \\[run-python]. It
990;; will be in a new buffer, named *Python*. Switch between the different
991;; process buffers with \\[switch-to-buffer].
992
993;; Commands that send text from source buffers to Python processes have
994;; to choose a process to send to. This is determined by global variable
995;; `python-buffer'. Suppose you have three inferior Pythons running:
996;; Buffer Process
997;; foo python
998;; bar python<2>
999;; *Python* python<3>
1000;; If you do a \\[python-send-region-and-go] command on some Python source
1001;; code, what process does it go to?
1002
1003;; - In a process buffer (foo, bar, or *Python*), send it to that process.
1004;; - In some other buffer (e.g. a source file), send it to the process
1005;; attached to `python-buffer'.
1006;; Process selection is done by function `python-proc'.
1007
1008;; Whenever \\[run-python] starts a new process, it resets `python-buffer'
1009;; to be the new process's buffer. If you only run one process, this will
1010;; do the right thing. If you run multiple processes, you can change
1011;; `python-buffer' to another process buffer with \\[set-variable]."
1012 )
6f480c7a 1013
0578dead 1014(defconst python-compilation-regexp-alist
24d5055c 1015 ;; FIXME: maybe these should move to compilation-error-regexp-alist-alist.
0578dead
SM
1016 `((,(rx (and line-start (1+ (any " \t")) "File \""
1017 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1018 "\", line " (group (1+ digit))))
24d5055c
SM
1019 1 2)
1020 (,(rx (and " in file " (group (1+ not-newline)) " on line "
1021 (group (1+ digit))))
ee99b45b 1022 1 2))
0578dead
SM
1023 "`compilation-error-regexp-alist' for inferior Python.")
1024
24d5055c
SM
1025(defvar inferior-python-mode-map
1026 (let ((map (make-sparse-keymap)))
1027 ;; This will inherit from comint-mode-map.
1028 (define-key map "\C-c\C-l" 'python-load-file)
24d5055c
SM
1029 (define-key map "\C-c\C-v" 'python-check)
1030 ;; Note that we _can_ still use these commands which send to the
1031 ;; Python process even at the prompt iff we have a normal prompt,
1032 ;; i.e. '>>> ' and not '... '. See the comment before
1033 ;; python-send-region. Fixme: uncomment these if we address that.
1034
1035 ;; (define-key map [(meta ?\t)] 'python-complete-symbol)
1036 ;; (define-key map "\C-c\C-f" 'python-describe-symbol)
1037 map))
1038
b6ea7940
SM
1039;; Fixme: This should inherit some stuff from python-mode, but I'm not
1040;; sure how much: at least some keybindings, like C-c C-f; syntax?;
1041;; font-locking, e.g. for triple-quoted strings?
6f480c7a
SM
1042(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1043 "Major mode for interacting with an inferior Python process.
1044A Python process can be started with \\[run-python].
1045
1046Hooks `comint-mode-hook' and `inferior-python-mode-hook' are run in
1047that order.
1048
1049You can send text to the inferior Python process from other buffers containing
1050Python source.
1051 * `python-switch-to-python' switches the current buffer to the Python
1052 process buffer.
1053 * `python-send-region' sends the current region to the Python process.
1054 * `python-send-region-and-go' switches to the Python process buffer
1055 after sending the text.
1056For running multiple processes in multiple buffers, see `python-buffer'.
1057
1058\\{inferior-python-mode-map}"
1059 :group 'python
1060 (set-syntax-table python-mode-syntax-table)
1061 (setq mode-line-process '(":%s"))
24d5055c 1062 (set (make-local-variable 'comint-input-filter) 'python-input-filter)
0578dead
SM
1063 (add-hook 'comint-preoutput-filter-functions #'python-preoutput-filter
1064 nil t)
b6ea7940
SM
1065 ;; Still required by `comint-redirect-send-command', for instance
1066 ;; (and we need to match things like `>>> ... >>> '):
24d5055c
SM
1067 (set (make-local-variable 'comint-prompt-regexp)
1068 (rx (and line-start (1+ (and (repeat 3 (any ">.")) ?\ )))))
0578dead
SM
1069 (set (make-local-variable 'compilation-error-regexp-alist)
1070 python-compilation-regexp-alist)
1071 (compilation-shell-minor-mode 1))
6f480c7a
SM
1072
1073(defcustom inferior-python-filter-regexp "\\`\\s-*\\S-?\\S-?\\s-*\\'"
1074 "*Input matching this regexp is not saved on the history list.
1075Default ignores all inputs of 0, 1, or 2 non-blank characters."
1076 :type 'regexp
1077 :group 'python)
1078
24d5055c
SM
1079(defun python-input-filter (str)
1080 "`comint-input-filter' function for inferior Python.
1081Don't save anything for STR matching `inferior-python-filter-regexp'."
1082 (not (string-match inferior-python-filter-regexp str)))
1083
6f480c7a
SM
1084;; Fixme: Loses with quoted whitespace.
1085(defun python-args-to-list (string)
1086 (let ((where (string-match "[ \t]" string)))
1087 (cond ((null where) (list string))
1088 ((not (= where 0))
1089 (cons (substring string 0 where)
1090 (python-args-to-list (substring string (+ 1 where)))))
1091 (t (let ((pos (string-match "[^ \t]" string)))
1092 (if pos (python-args-to-list (substring string pos))))))))
1093
0578dead 1094(defvar python-preoutput-result nil
24d5055c 1095 "Data from last `_emacs_out' line seen by the preoutput filter.")
0578dead
SM
1096
1097(defvar python-preoutput-continuation nil
1098 "If non-nil, funcall this when `python-preoutput-filter' sees `_emacs_ok'.")
1099
1100;; Using this stops us getting lines in the buffer like
1101;; >>> ... ... >>>
1102;; Also look for (and delete) an `_emacs_ok' string and call
1103;; `python-preoutput-continuation' if we get it.
1104(defun python-preoutput-filter (s)
1105 "`comint-preoutput-filter-functions' function: ignore prompts not at bol."
24d5055c
SM
1106 (cond ((and (string-match (rx (and string-start (repeat 3 (any ".>"))
1107 " " string-end))
1108 s)
0578dead
SM
1109 (/= (let ((inhibit-field-text-motion t))
1110 (line-beginning-position))
1111 (point)))
1112 "")
1113 ((string= s "_emacs_ok\n")
1114 (when python-preoutput-continuation
1115 (funcall python-preoutput-continuation)
1116 (setq python-preoutput-continuation nil))
1117 "")
1118 ((string-match "_emacs_out \\(.*\\)\n" s)
1119 (setq python-preoutput-result (match-string 1 s))
1120 "")
1121 (t s)))
1122
6f480c7a 1123;;;###autoload
0578dead 1124(defun run-python (&optional cmd noshow)
6f480c7a 1125 "Run an inferior Python process, input and output via buffer *Python*.
0578dead
SM
1126CMD is the Python command to run. NOSHOW non-nil means don't show the
1127buffer automatically.
6f480c7a 1128If there is a process already running in `*Python*', switch to
24d5055c
SM
1129that buffer. Interactively, a prefix arg allows you to edit the initial
1130command line (default is `python-command'); `-i' etc. args will be added
1131to this as appropriate. Runs the hook `inferior-python-mode-hook'
1132\(after the `comint-mode-hook' is run).
0578dead 1133\(Type \\[describe-mode] in the process buffer for a list of commands.)"
6f480c7a
SM
1134 (interactive (list (if current-prefix-arg
1135 (read-string "Run Python: " python-command)
1136 python-command)))
0578dead
SM
1137 (unless cmd (setq cmd python-python-command))
1138 (setq python-command cmd)
6f480c7a
SM
1139 ;; Fixme: Consider making `python-buffer' buffer-local as a buffer
1140 ;; (not a name) in Python buffers from which `run-python' &c is
1141 ;; invoked. Would support multiple processes better.
24d5055c 1142 (unless (comint-check-proc python-buffer)
522067b2
SM
1143 (let* ((cmdlist (append (python-args-to-list cmd) '("-i")))
1144 (path (getenv "PYTHONPATH"))
1145 (process-environment ; to import emacs.py
1146 (push (concat "PYTHONPATH=" data-directory
1147 (if path (concat ":" path)))
1148 process-environment)))
0578dead 1149 (set-buffer (apply 'make-comint "Python" (car cmdlist) nil
24d5055c
SM
1150 (cdr cmdlist)))
1151 (setq python-buffer "*Python*"))
0578dead
SM
1152 (inferior-python-mode)
1153 ;; Load function defintions we need.
1154 ;; Before the preoutput function was used, this was done via -c in
1155 ;; cmdlist, but that loses the banner and doesn't run the startup
24d5055c
SM
1156 ;; file. The code might be inline here, but there's enough that it
1157 ;; seems worth putting in a separate file, and it's probably cleaner
1158 ;; to put it in a module.
1159 (python-send-string "import emacs"))
1160 (unless noshow (pop-to-buffer python-buffer)))
1161
1162;; Fixme: We typically lose if the inferior isn't in the normal REPL,
1163;; e.g. prompt is `help> '. Probably raise an error if the form of
1164;; the prompt is unexpected; actually, it needs to be `>>> ', not
1165;; `... ', i.e. we're not inputting a block &c. However, this may not
1166;; be the place to do it, e.g. we might actually want to send commands
1167;; having set up such a state.
6f480c7a 1168
56e6d6fe
SM
1169(defun python-send-command (command)
1170 "Like `python-send-string' but resets `compilation-minor-mode'."
24d5055c 1171 (goto-char (point-max))
56e6d6fe
SM
1172 (let ((end (marker-position (process-mark (python-proc)))))
1173 (compilation-forget-errors)
1174 (python-send-string command)
1175 (set-marker compilation-parsing-end end)
1176 (setq compilation-last-buffer (current-buffer))))
1177
6f480c7a
SM
1178(defun python-send-region (start end)
1179 "Send the region to the inferior Python process."
1180 ;; The region is evaluated from a temporary file. This avoids
1181 ;; problems with blank lines, which have different semantics
1182 ;; interactively and in files. It also saves the inferior process
24d5055c
SM
1183 ;; buffer filling up with interpreter prompts. We need a Python
1184 ;; function to remove the temporary file when it has been evaluated
1185 ;; (though we could probably do it in Lisp with a Comint output
1186 ;; filter). This function also catches exceptions and truncates
1187 ;; tracebacks not to mention the frame of the function itself.
6f480c7a
SM
1188 ;;
1189 ;; The compilation-minor-mode parsing takes care of relating the
24d5055c
SM
1190 ;; reference to the temporary file to the source.
1191 ;;
1192 ;; Fixme: Write a `coding' header to the temp file if the region is
1193 ;; non-ASCII.
6f480c7a
SM
1194 (interactive "r")
1195 (let* ((f (make-temp-file "py"))
24d5055c 1196 (command (format "emacs.eexecfile(%S)" f))
a1ae0e9c 1197 (orig-start (copy-marker start)))
24d5055c
SM
1198 (when (save-excursion
1199 (goto-char start)
1200 (/= 0 (current-indentation))) ; need dummy block
1201 (save-excursion
1202 (goto-char orig-start)
1203 ;; Wrong if we had indented code at buffer start.
1204 (set-marker orig-start (line-beginning-position 0)))
1205 (write-region "if True:\n" nil f nil 'nomsg))
6f480c7a 1206 (write-region start end f t 'nomsg)
24d5055c 1207 (let ((proc (python-proc))) ;Make sure we're running a process.
6f480c7a 1208 (with-current-buffer python-buffer
ee99b45b
SM
1209 (python-send-command command)
1210 ;; Tell compile.el to redirect error locations in file `f' to
1211 ;; positions past marker `orig-start'. It has to be done *after*
1212 ;; python-send-command's call to compilation-forget-errors.
1213 (compilation-fake-loc orig-start f)))))
6f480c7a
SM
1214
1215(defun python-send-string (string)
1216 "Evaluate STRING in inferior Python process."
1217 (interactive "sPython command: ")
0578dead
SM
1218 (comint-send-string (python-proc) string)
1219 (comint-send-string (python-proc) "\n\n"))
6f480c7a
SM
1220
1221(defun python-send-buffer ()
1222 "Send the current buffer to the inferior Python process."
1223 (interactive)
1224 (python-send-region (point-min) (point-max)))
1225
24d5055c
SM
1226;; Fixme: Try to define the function or class within the relevant
1227;; module, not just at top level.
6f480c7a
SM
1228(defun python-send-defun ()
1229 "Send the current defun (class or method) to the inferior Python process."
1230 (interactive)
1231 (save-excursion (python-send-region (progn (beginning-of-defun) (point))
1232 (progn (end-of-defun) (point)))))
1233
1234(defun python-switch-to-python (eob-p)
1235 "Switch to the Python process buffer.
1236With prefix arg, position cursor at end of buffer."
1237 (interactive "P")
1238 (if (get-buffer python-buffer)
1239 (pop-to-buffer python-buffer)
1240 (error "No current process buffer. See variable `python-buffer'"))
1241 (when eob-p
1242 (push-mark)
1243 (goto-char (point-max))))
1244
1245(add-to-list 'debug-ignored-errors "^No current process buffer.")
1246
1247(defun python-send-region-and-go (start end)
1248 "Send the region to the inferior Python process.
1249Then switch to the process buffer."
1250 (interactive "r")
1251 (python-send-region start end)
1252 (python-switch-to-python t))
1253
1254(defcustom python-source-modes '(python-mode jython-mode)
1255 "*Used to determine if a buffer contains Python source code.
1256If it's loaded into a buffer that is in one of these major modes, it's
1257considered a Python source file by `python-load-file'.
1258Used by these commands to determine defaults."
1259 :type '(repeat function)
1260 :group 'python)
1261
1262(defvar python-prev-dir/file nil
1263 "Caches (directory . file) pair used in the last `python-load-file' command.
1264Used for determining the default in the next one.")
1265
1266(defun python-load-file (file-name)
1267 "Load a Python file FILE-NAME into the inferior Python process.
1268If the file has extension `.py' import or reload it as a module.
1269Treating it as a module keeps the global namespace clean, provides
1270function location information for debugging, and supports users of
1271module-qualified names."
1272 (interactive (comint-get-source "Load Python file: " python-prev-dir/file
1273 python-source-modes
24d5055c
SM
1274 t)) ; because execfile needs exact name
1275 (comint-check-source file-name) ; Check to see if buffer needs saving.
6f480c7a
SM
1276 (setq python-prev-dir/file (cons (file-name-directory file-name)
1277 (file-name-nondirectory file-name)))
24d5055c 1278 (let ((proc (python-proc))) ;Make sure we have a process.
0578dead 1279 (with-current-buffer python-buffer
56e6d6fe
SM
1280 ;; Fixme: I'm not convinced by this logic from python-mode.el.
1281 (python-send-command
1282 (if (string-match "\\.py\\'" file-name)
56e6d6fe
SM
1283 (let ((module (file-name-sans-extension
1284 (file-name-nondirectory file-name))))
24d5055c
SM
1285 (format "emacs.eimport(%S,%S)"
1286 module (file-name-directory file-name)))
1287 (format "execfile(%S)" file-name)))
1288 (message "%s loaded" file-name))))
6f480c7a 1289
24d5055c
SM
1290;; Fixme: If we need to start the process, wait until we've got the OK
1291;; from the startup.
6f480c7a 1292(defun python-proc ()
24d5055c
SM
1293 "Return the current Python process.
1294See variable `python-buffer'. Starts a new process if necessary."
1295 (or (if python-buffer
1296 (get-buffer-process (if (eq major-mode 'inferior-python-mode)
1297 (current-buffer)
1298 python-buffer)))
1299 (progn (run-python nil t)
1300 (python-proc))))
6f480c7a
SM
1301\f
1302;;;; Context-sensitive help.
1303
0578dead
SM
1304(defconst python-dotty-syntax-table
1305 (let ((table (make-syntax-table)))
1306 (set-char-table-parent table python-mode-syntax-table)
1307 (modify-syntax-entry ?. "_" table)
1308 table)
1309 "Syntax table giving `.' symbol syntax.
1310Otherwise inherits from `python-mode-syntax-table'.")
6f480c7a 1311
24d5055c 1312(defvar view-return-to-alist)
522067b2 1313(eval-when-compile (autoload 'help-buffer "help-fns"))
24d5055c 1314
0578dead 1315;; Fixme: Should this actually be used instead of info-look, i.e. be
24d5055c 1316;; bound to C-h S? Can we use other pydoc stuff before python 2.2?
6f480c7a 1317(defun python-describe-symbol (symbol)
24d5055c
SM
1318 "Get help on SYMBOL using `help'.
1319Interactively, prompt for symbol.
1320
1321Symbol may be anything recognized by the interpreter's `help' command --
1322e.g. `CALLS' -- not just variables in scope.
1323This only works for Python version 2.2 or newer since earlier interpreters
1324don't support `help'."
1325 ;; Note that we do this in the inferior process, not a separate one, to
0578dead 1326 ;; ensure the environment is appropriate.
6f480c7a 1327 (interactive
0578dead
SM
1328 (let ((symbol (with-syntax-table python-dotty-syntax-table
1329 (current-word)))
24d5055c
SM
1330 (enable-recursive-minibuffers t))
1331 (list (read-string (if symbol
1332 (format "Describe symbol (default %s): " symbol)
1333 "Describe symbol: ")
1334 nil nil symbol))))
6f480c7a 1335 (if (equal symbol "") (error "No symbol"))
0578dead 1336 (let* ((func `(lambda ()
24d5055c
SM
1337 (comint-redirect-send-command (format "emacs.ehelp(%S)\n"
1338 ,symbol)
0578dead
SM
1339 "*Help*" nil))))
1340 ;; Ensure we have a suitable help buffer.
24d5055c
SM
1341 ;; Fixme: Maybe process `Related help topics' a la help xrefs and
1342 ;; allow C-c C-f in help buffer.
1343 (let ((temp-buffer-show-hook ; avoid xref stuff
1344 (lambda ()
1345 (toggle-read-only 1)
1346 (setq view-return-to-alist
1347 (list (cons (selected-window) help-return-method))))))
3299a03a 1348 (help-setup-xref (list 'python-describe-symbol symbol) (interactive-p))
24d5055c 1349 (with-output-to-temp-buffer (help-buffer)
0578dead 1350 (with-current-buffer standard-output
24d5055c
SM
1351 (set (make-local-variable 'comint-redirect-subvert-readonly) t)
1352 (print-help-return-message))))
0578dead
SM
1353 (if (and python-buffer (get-buffer python-buffer))
1354 (with-current-buffer python-buffer
1355 (funcall func))
1356 (setq python-preoutput-continuation func)
1357 (run-python nil t))))
6f480c7a
SM
1358
1359(add-to-list 'debug-ignored-errors "^No symbol")
0578dead 1360
24d5055c
SM
1361(defun python-send-receive (string)
1362 "Send STRING to inferior Python (if any) and return result.
1363The result is what follows `_emacs_out' in the output (or nil)."
1364 (let ((proc (python-proc)))
1365 (python-send-string string)
1366 (setq python-preoutput-result nil)
1367 (accept-process-output proc 5)
1368 python-preoutput-result))
1369
0578dead
SM
1370;; Fixme: try to make it work with point in the arglist. Also, is
1371;; there anything reasonable we can do with random methods?
1372;; (Currently only works with functions.)
1373(defun python-eldoc-function ()
1374 "`eldoc-print-current-symbol-info' for Python.
1375Only works when point is in a function name, not its arglist, for instance.
1376Assumes an inferior Python is running."
1377 (let ((symbol (with-syntax-table python-dotty-syntax-table
24d5055c
SM
1378 (current-word))))
1379 (when symbol
1380 (python-send-receive (format "emacs.eargs(%S)" symbol)))))
6f480c7a
SM
1381\f
1382;;;; Info-look functionality.
1383
0578dead
SM
1384(defun python-after-info-look ()
1385 "Set up info-look for Python.
1386Used with `eval-after-load'."
1387 (let* ((version (let ((s (shell-command-to-string (concat python-command
1388 " -V"))))
1389 (string-match "^Python \\([0-9]+\\.[0-9]+\\>\\)" s)
1390 (match-string 1 s)))
1391 ;; Whether info files have a Python version suffix, e.g. in Debian.
3299a03a 1392 (versioned
0578dead 1393 (with-temp-buffer
b6ea7940 1394 (with-no-warnings (Info-mode))
0578dead 1395 (condition-case ()
a1ae0e9c 1396 ;; Don't use `info' because it would pop-up a *info* buffer.
b6ea7940
SM
1397 (with-no-warnings
1398 (Info-goto-node (format "(python%s-lib)Miscellaneous Index"
522067b2
SM
1399 version))
1400 t)
0578dead
SM
1401 (error nil)))))
1402 (info-lookup-maybe-add-help
1403 :mode 'python-mode
1404 :regexp "[[:alnum:]_]+"
1405 :doc-spec
1406 ;; Fixme: Can this reasonably be made specific to indices with
1407 ;; different rules? Is the order of indices optimal?
1408 ;; (Miscellaneous in -ref first prefers lookup of keywords, for
1409 ;; instance.)
1410 (if versioned
1411 ;; The empty prefix just gets us highlighted terms.
1412 `((,(concat "(python" version "-ref)Miscellaneous Index") nil "")
1413 (,(concat "(python" version "-ref)Module Index" nil ""))
1414 (,(concat "(python" version "-ref)Function-Method-Variable Index"
1415 nil ""))
1416 (,(concat "(python" version "-ref)Class-Exception-Object Index"
1417 nil ""))
1418 (,(concat "(python" version "-lib)Module Index" nil ""))
1419 (,(concat "(python" version "-lib)Class-Exception-Object Index"
1420 nil ""))
1421 (,(concat "(python" version "-lib)Function-Method-Variable Index"
1422 nil ""))
1423 (,(concat "(python" version "-lib)Miscellaneous Index" nil "")))
1424 '(("(python-ref)Miscellaneous Index" nil "")
1425 ("(python-ref)Module Index" nil "")
1426 ("(python-ref)Function-Method-Variable Index" nil "")
1427 ("(python-ref)Class-Exception-Object Index" nil "")
1428 ("(python-lib)Module Index" nil "")
1429 ("(python-lib)Class-Exception-Object Index" nil "")
1430 ("(python-lib)Function-Method-Variable Index" nil "")
1431 ("(python-lib)Miscellaneous Index" nil ""))))))
1432(eval-after-load "info-look" '(python-after-info-look))
6f480c7a
SM
1433\f
1434;;;; Miscellancy.
1435
1436(defcustom python-jython-packages '("java" "javax" "org" "com")
1437 "Packages implying `jython-mode'.
1438If these are imported near the beginning of the buffer, `python-mode'
1439actually punts to `jython-mode'."
1440 :type '(repeat string)
1441 :group 'python)
1442
1443;; Called from `python-mode', this causes a recursive call of the
1444;; mode. See logic there to break out of the recursion.
1445(defun python-maybe-jython ()
1446 "Invoke `jython-mode' if the buffer appears to contain Jython code.
1447The criterion is either a match for `jython-mode' via
1448`interpreter-mode-alist' or an import of a module from the list
1449`python-jython-packages'."
1450 ;; The logic is taken from python-mode.el.
1451 (save-excursion
0578dead
SM
1452 (save-restriction
1453 (widen)
1454 (goto-char (point-min))
1455 (let ((interpreter (if (looking-at auto-mode-interpreter-regexp)
1456 (match-string 2))))
1457 (if (and interpreter (eq 'jython-mode
1458 (cdr (assoc (file-name-nondirectory
1459 interpreter)
1460 interpreter-mode-alist))))
1461 (jython-mode)
1462 (if (catch 'done
1463 (while (re-search-forward
1464 (rx (and line-start (or "import" "from") (1+ space)
1465 (group (1+ (not (any " \t\n."))))))
c3f85d95 1466 (+ (point-min) 10000) ; Probably not worth customizing.
0578dead
SM
1467 t)
1468 (if (member (match-string 1) python-jython-packages)
1469 (throw 'done t))))
1470 (jython-mode)))))))
6f480c7a
SM
1471
1472(defun python-fill-paragraph (&optional justify)
0578dead 1473 "`fill-paragraph-function' handling comments and multi-line strings.
6f480c7a 1474If any of the current line is a comment, fill the comment or the
0578dead
SM
1475paragraph of it that point is in, preserving the comment's
1476indentation and initial comment characters. Similarly if the end
1477of the current line is in or at the end of a multi-line string.
1478Otherwise, do nothing."
6f480c7a
SM
1479 (interactive "P")
1480 (or (fill-comment-paragraph justify)
0578dead
SM
1481 ;; The `paragraph-start' and `paragraph-separate' variables
1482 ;; don't allow us to delimit the last paragraph in a multi-line
1483 ;; string properly, so narrow to the string and then fill around
1484 ;; (the end of) the current line.
1485 (save-excursion
1486 (end-of-line)
1487 (let* ((syntax (syntax-ppss))
1488 (orig (point))
1489 (start (nth 8 syntax))
1490 end)
1491 (cond ((eq t (nth 3 syntax)) ; in fenced string
1492 (goto-char (nth 8 syntax)) ; string start
1493 (condition-case () ; for unbalanced quotes
1494 (progn (forward-sexp)
1495 (setq end (point)))
1496 (error (setq end (point-max)))))
1497 ((re-search-backward "\\s|\\s-*\\=" nil t) ; end of fenced
1498 ; string
1499 (forward-char)
1500 (setq end (point))
1501 (condition-case ()
1502 (progn (backward-sexp)
1503 (setq start (point)))
1504 (error nil))))
1505 (when end
1506 (save-restriction
1507 (narrow-to-region start end)
1508 (goto-char orig)
1509 (fill-paragraph justify))))))
1510 t)
6f480c7a
SM
1511
1512(defun python-shift-left (start end &optional count)
1513 "Shift lines in region COUNT (the prefix arg) columns to the left.
1514COUNT defaults to `python-indent'. If region isn't active, just shift
1515current line. The region shifted includes the lines in which START and
1516END lie. It is an error if any lines in the region are indented less than
1517COUNT columns."
1518 (interactive (if mark-active
1519 (list (region-beginning) (region-end) current-prefix-arg)
1520 (list (point) (point) current-prefix-arg)))
1521 (if count
1522 (setq count (prefix-numeric-value count))
1523 (setq count python-indent))
1524 (when (> count 0)
1525 (save-excursion
1526 (goto-char start)
1527 (while (< (point) end)
1528 (if (and (< (current-indentation) count)
1529 (not (looking-at "[ \t]*$")))
1530 (error "Can't shift all lines enough"))
1531 (forward-line))
1532 (indent-rigidly start end (- count)))))
1533
1534(add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1535
1536(defun python-shift-right (start end &optional count)
1537 "Shift lines in region COUNT (the prefix arg) columns to the right.
1538COUNT defaults to `python-indent'. If region isn't active, just shift
1539current line. The region shifted includes the lines in which START and
1540END lie."
1541 (interactive (if mark-active
1542 (list (region-beginning) (region-end) current-prefix-arg)
1543 (list (point) (point) current-prefix-arg)))
1544 (if count
1545 (setq count (prefix-numeric-value count))
1546 (setq count python-indent))
1547 (indent-rigidly start end count))
1548
1549(defun python-outline-level ()
1550 "`outline-level' function for Python mode.
0578dead
SM
1551The level is the number of `python-indent' steps of indentation
1552of current line."
6f480c7a
SM
1553 (/ (current-indentation) python-indent))
1554
1555;; Fixme: Consider top-level assignments, imports, &c.
1556(defun python-current-defun ()
1557 "`add-log-current-defun-function' for Python."
1558 (save-excursion
1559 ;; Move up the tree of nested `class' and `def' blocks until we
1560 ;; get to zero indentation, accumulating the defined names.
1561 (let ((start t)
1562 accum)
1563 (while (or start (> (current-indentation) 0))
1564 (setq start nil)
1565 (python-beginning-of-block)
1566 (end-of-line)
1567 (beginning-of-defun)
1568 (if (looking-at (rx (and (0+ space) (or "def" "class") (1+ space)
1569 (group (1+ (or word (syntax symbol))))
1570 word-end)))
1571 (push (match-string 1) accum)))
1572 (if accum (mapconcat 'identity accum ".")))))
1573
1574(defun python-mark-block ()
1575 "Mark the block around point.
1576Uses `python-beginning-of-block', `python-end-of-block'."
1577 (interactive)
1578 (push-mark)
1579 (python-beginning-of-block)
1580 (push-mark (point) nil t)
1581 (python-end-of-block)
1582 (exchange-point-and-mark))
1583\f
24d5055c
SM
1584;;;; Completion.
1585
1586(defun python-symbol-completions (symbol)
1587 "Return a list of completions of the string SYMBOL from Python process.
1588The list is sorted."
1589 (when symbol
1590 (let ((completions
1591 (condition-case ()
1592 (car (read-from-string (python-send-receive
1593 (format "emacs.complete(%S)" symbol))))
1594 (error nil))))
1595 (sort
1596 ;; We can get duplicates from the above -- don't know why.
1597 (delete-dups completions)
1598 #'string<))))
1599
1600(defun python-partial-symbol ()
1601 "Return the partial symbol before point (for completion)."
1602 (let ((end (point))
1603 (start (save-excursion
1604 (and (re-search-backward
1605 (rx (and (or buffer-start (regexp "[^[:alnum:]._]"))
1606 (group (1+ (regexp "[[:alnum:]._]")))
1607 point))
1608 nil t)
1609 (match-beginning 1)))))
1610 (if start (buffer-substring-no-properties start end))))
1611
1612;; Fixme: We should have an abstraction of this sort of thing in the
1613;; core.
1614(defun python-complete-symbol ()
1615 "Perform completion on the Python symbol preceding point.
1616Repeating the command scrolls the completion window."
1617 (interactive)
1618 (let ((window (get-buffer-window "*Completions*")))
1619 (if (and (eq last-command this-command)
1620 window (window-live-p window) (window-buffer window)
1621 (buffer-name (window-buffer window)))
1622 (with-current-buffer (window-buffer window)
1623 (if (pos-visible-in-window-p (point-max) window)
1624 (set-window-start window (point-min))
1625 (save-selected-window
1626 (select-window window)
1627 (scroll-up))))
1628 ;; Do completion.
1629 (let* ((end (point))
1630 (symbol (python-partial-symbol))
1631 (completions (python-symbol-completions symbol))
1632 (completion (if completions
1633 (try-completion symbol completions))))
1634 (when symbol
1635 (cond ((eq completion t))
1636 ((null completion)
1637 (message "Can't find completion for \"%s\"" symbol)
1638 (ding))
1639 ((not (string= symbol completion))
1640 (delete-region (- end (length symbol)) end)
1641 (insert completion))
1642 (t
1643 (message "Making completion list...")
1644 (with-output-to-temp-buffer "*Completions*"
1645 (display-completion-list completions))
1646 (message "Making completion list...%s" "done"))))))))
1647
1648(eval-when-compile (require 'hippie-exp))
1649
1650(defun python-try-complete (old)
1651 "Completion function for Python for use with `hippie-expand'."
1652 (when (eq major-mode 'python-mode) ; though we only add it locally
1653 (unless old
1654 (let ((symbol (python-partial-symbol)))
1655 (he-init-string (- (point) (length symbol)) (point))
1656 (if (not (he-string-member he-search-string he-tried-table))
1657 (push he-search-string he-tried-table))
1658 (setq he-expand-list
1659 (and symbol (python-symbol-completions symbol)))))
1660 (while (and he-expand-list
1661 (he-string-member (car he-expand-list) he-tried-table))
1662 (pop he-expand-list))
1663 (if he-expand-list
1664 (progn
1665 (he-substitute-string (pop he-expand-list))
1666 t)
1667 (if old (he-reset-string))
1668 nil)))
1669\f
6f480c7a
SM
1670;;;; Modes.
1671
0578dead
SM
1672(defvar outline-heading-end-regexp)
1673(defvar eldoc-print-current-symbol-info-function)
24d5055c 1674
6f480c7a
SM
1675;;;###autoload
1676(define-derived-mode python-mode fundamental-mode "Python"
1677 "Major mode for editing Python files.
1678Turns on Font Lock mode unconditionally since it is required for correct
1679parsing of the source.
1680See also `jython-mode', which is actually invoked if the buffer appears to
0578dead
SM
1681contain Jython code. See also `run-python' and associated Python mode
1682commands for running Python under Emacs.
6f480c7a
SM
1683
1684The Emacs commands which work with `defun's, e.g. \\[beginning-of-defun], deal
1685with nested `def' and `class' blocks. They take the innermost one as
0578dead
SM
1686current without distinguishing method and class definitions. Used multiple
1687times, they move over others at the same indentation level until they reach
1688the end of definitions at that level, when they move up a level.
6f480c7a
SM
1689\\<python-mode-map>
1690Colon is electric: it outdents the line if appropriate, e.g. for
1691an else statement. \\[python-backspace] at the beginning of an indented statement
1692deletes a level of indentation to close the current block; otherwise it
1693deletes a charcter backward. TAB indents the current line relative to
1694the preceding code. Successive TABs, with no intervening command, cycle
1695through the possibilities for indentation on the basis of enclosing blocks.
1696
0578dead
SM
1697\\[fill-paragraph] fills comments and multiline strings appropriately, but has no
1698effect outside them.
1699
1700Supports Eldoc mode (only for functions, using a Python process),
1701Info-Look and Imenu. In Outline minor mode, `class' and `def'
1702lines count as headers.
1703
6f480c7a
SM
1704\\{python-mode-map}"
1705 :group 'python
1706 (set (make-local-variable 'font-lock-defaults)
1707 '(python-font-lock-keywords nil nil ((?_ . "w")) nil
1708 (font-lock-syntactic-keywords
1709 . python-font-lock-syntactic-keywords)
1710;;; This probably isn't worth it.
1711;;; (font-lock-syntactic-face-function
1712;;; . python-font-lock-syntactic-face-function)
1713 ))
1714 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1715 (set (make-local-variable 'comment-start) "# ")
24d5055c 1716 (set (make-local-variable 'comment-indent-function) #'python-comment-indent)
6f480c7a
SM
1717 (set (make-local-variable 'indent-line-function) #'python-indent-line)
1718 (set (make-local-variable 'paragraph-start) "\\s-*$")
24d5055c 1719 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph)
6f480c7a
SM
1720 (set (make-local-variable 'require-final-newline) t)
1721 (set (make-local-variable 'add-log-current-defun-function)
1722 #'python-current-defun)
1723 ;; Fixme: Generalize to do all blocks?
0578dead
SM
1724 (set (make-local-variable 'outline-regexp) "\\s-*\\(def\\|class\\)\\>")
1725 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
6f480c7a
SM
1726 (set (make-local-variable 'outline-level) #'python-outline-level)
1727 (set (make-local-variable 'open-paren-in-column-0-is-defun-start) nil)
1728 (make-local-variable 'python-saved-check-command)
1729 (set (make-local-variable 'beginning-of-defun-function)
1730 'python-beginning-of-defun)
1731 (set (make-local-variable 'end-of-defun-function) 'python-end-of-defun)
1732 (setq imenu-create-index-function #'python-imenu-create-index)
0578dead
SM
1733 (set (make-local-variable 'eldoc-print-current-symbol-info-function)
1734 #'python-eldoc-function)
1735 (add-hook 'eldoc-mode-hook
1736 '(lambda () (run-python 0 t)) nil t) ; need it running
24d5055c
SM
1737 (if (featurep 'hippie-exp)
1738 (set (make-local-variable 'hippie-expand-try-functions-list)
1739 (cons 'python-try-complete hippie-expand-try-functions-list)))
6f480c7a
SM
1740 (unless font-lock-mode (font-lock-mode 1))
1741 (when python-guess-indent (python-guess-indent))
1742 (set (make-local-variable 'python-command) python-python-command)
1743 (unless (boundp 'python-mode-running) ; kill the recursion from jython-mode
1744 (let ((python-mode-running t))
1745 (python-maybe-jython))))
1746
1747(custom-add-option 'python-mode-hook 'imenu-add-menubar-index)
1748(custom-add-option 'python-mode-hook
1749 '(lambda ()
1750 "Turn on Indent Tabs mode."
1751 (set (make-local-variable 'indent-tabs-mode) t)))
0578dead 1752(custom-add-option 'python-mode-hook 'turn-on-eldoc-mode)
6f480c7a
SM
1753
1754;;;###autoload
1755(define-derived-mode jython-mode python-mode "Jython"
1756 "Major mode for editing Jython files.
1757Like `python-mode', but sets up parameters for Jython subprocesses.
1758Runs `jython-mode-hook' after `python-mode-hook'."
1759 :group 'python
1760 (set (make-local-variable 'python-command) python-jython-command))
1761
1762(provide 'python)
1763;; arch-tag: 6fce1d99-a704-4de9-ba19-c6e4912b0554
1764;;; python.el ends here