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