python-shell-get-or-create-process preserves current buffer.
[bpt/emacs.git] / lisp / progmodes / python.el
CommitLineData
45c138ac
FEG
1;;; python.el -- Python's flying circus support for Emacs
2
3;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5;; Author: Fabián E. Gallina <fabian@anue.biz>
6;; Maintainer: FSF
7;; Created: Jul 2010
8;; Keywords: languages
9
10;; This file is NOT part of GNU Emacs.
11
12;; python.el 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 of the License, or
15;; (at your option) any later version.
16
17;; python.el 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 python.el. If not, see <http://www.gnu.org/licenses/>.
24
25;;; Commentary:
26
27;; Major mode for editing Python files with some fontification and
28;; indentation bits extracted from original Dave Love's python.el
29;; found in GNU/Emacs.
30
31;; While it probably has less features than Dave Love's python.el and
32;; PSF's python-mode.el it provides the main stuff you'll need while
33;; keeping it simple :)
34
35;; Implements Syntax highlighting, Indentation, Movement, Shell
36;; interaction, Shell completion, Pdb tracking, Symbol completion,
37;; Eldoc.
38
39;; Syntax highlighting: Fontification of code is provided and supports
40;; python's triple quoted strings properly.
41
42;; Indentation: Automatic indentation with indentation cycling is
43;; provided, it allows you to navigate different available levels of
44;; indentation by hitting <tab> several times.
45
46;; Movement: `beginning-of-defun' and `end-of-defun' functions are
47;; properly implemented. A `beginning-of-innermost-defun' is defined
48;; to navigate nested defuns.
49
50;; Shell interaction: is provided and allows you easily execute any
51;; block of code of your current buffer in an inferior Python process.
52
53;; Shell completion: hitting tab will try to complete the current
54;; word. Shell completion is implemented in a manner that if you
55;; change the `python-shell-interpreter' to any other (for example
56;; IPython) it should be easy to integrate another way to calculate
57;; completions. You just need to especify your custom
58;; `python-shell-completion-setup-code' and
59;; `python-shell-completion-strings-code'
60
61;; Pdb tracking: when you execute a block of code that contains some
62;; call to pdb (or ipdb) it will prompt the block of code and will
63;; follow the execution of pdb marking the current line with an arrow.
64
65;; Symbol completion: you can complete the symbol at point. It uses
66;; the shell completion in background so you should run
67;; `python-shell-send-buffer' from time to time to get better results.
68
69;; Eldoc: returns documentation for object at point by using the
70;; inferior python subprocess to inspect its documentation. As you
71;; might guessed you should run `python-shell-send-buffer' from time
72;; to time to get better results too.
73
74;;; Installation:
75
76;; Add this to your .emacs:
77
78;; (add-to-list 'load-path "/folder/containing/file")
79;; (require 'python)
80
81;;; TODO:
82
83;; Ordered by priority:
84
85;; Better decorator support for beginning of defun
86
87;; Fix shell autocompletion when: obj.<tab>
88
89;; Remove garbage prompts left from calls to `comint-send-string' and
90;; other comint related cleanups.
91
92;; Review code and cleanup
93
94;;; Code:
95
96(require 'comint)
97(require 'ansi-color)
98(require 'outline)
99
100(eval-when-compile
101 (require 'cl))
102
103(autoload 'comint-mode "comint")
104
105;;;###autoload
106(add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
107;;;###autoload
108(add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
109
110(defgroup python nil
111 "Python Language's flying circus support for Emacs."
112 :group 'languages
113 :version "23.2"
114 :link '(emacs-commentary-link "python"))
115
116\f
117;;; Bindings
118
119(defvar python-mode-map
120 (let ((map (make-sparse-keymap)))
121 ;; Indent specific
122 (define-key map "\177" 'python-indent-dedent-line-backspace)
123 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
124 (define-key map "\C-c<" 'python-indent-shift-left)
125 (define-key map "\C-c>" 'python-indent-shift-right)
126 ;; Shell interaction
127 (define-key map "\C-c\C-s" 'python-shell-send-string)
128 (define-key map "\C-c\C-r" 'python-shell-send-region)
129 (define-key map "\C-\M-x" 'python-shell-send-defun)
130 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
131 (define-key map "\C-c\C-l" 'python-shell-send-file)
132 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
133 ;; Utilities
134 (substitute-key-definition 'complete-symbol 'completion-at-point
135 map global-map)
136 (easy-menu-define python-menu map "Python Mode menu"
137 `("Python"
138 :help "Python-specific Features"
139 ["Shift region left" python-indent-shift-left :active mark-active
140 :help "Shift region left by a single indentation step"]
141 ["Shift region right" python-indent-shift-right :active mark-active
142 :help "Shift region right by a single indentation step"]
143 "-"
144 ["Mark def/class" mark-defun
145 :help "Mark outermost definition around point"]
146 "-"
147 ["Start of def/class" beginning-of-defun
148 :help "Go to start of outermost definition around point"]
149 ["Start of def/class" python-beginning-of-innermost-defun
150 :help "Go to start of innermost definition around point"]
151 ["End of def/class" end-of-defun
152 :help "Go to end of definition around point"]
153 "-"
154 ["Start interpreter" run-python
155 :help "Run inferior Python process in a separate buffer"]
156 ["Switch to shell" python-shell-switch-to-shell
157 :help "Switch to running inferior Python process"]
158 ["Eval string" python-shell-send-string
159 :help "Eval string in inferior Python session"]
160 ["Eval buffer" python-shell-send-buffer
161 :help "Eval buffer in inferior Python session"]
162 ["Eval region" python-shell-send-region
163 :help "Eval region in inferior Python session"]
164 ["Eval defun" python-shell-send-defun
165 :help "Eval defun in inferior Python session"]
166 ["Eval file" python-shell-send-file
167 :help "Eval file in inferior Python session"]
168 ["Debugger" pdb :help "Run pdb under GUD"]
169 "-"
170 ["Complete symbol" completion-at-point
171 :help "Complete symbol before point"]))
172 map)
173 "Keymap for `python-mode'.")
174
175\f
176;;; Python specialized rx
177
178(defconst python-rx-constituents
179 (list
180 `(block-start . ,(rx symbol-start
181 (or "def" "class" "if" "elif" "else" "try"
182 "except" "finally" "for" "while" "with")
183 symbol-end))
184 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
185 `(open-paren . ,(rx (or "{" "[" "(")))
186 `(close-paren . ,(rx (or "}" "]" ")")))
187 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
188 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
189 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
190 "=" "%" "**" "//" "<<" ">>" "<=" "!="
191 "==" ">=" "is" "not")))
192 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
193 ">>=" "<<=" "&=" "^=" "|=")))))
194
195(defmacro python-rx (&rest regexps)
196 "Python mode especialized rx macro which supports common python named regexps."
197 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
198 (cond ((null regexps)
199 (error "No regexp"))
200 ((cdr regexps)
201 (rx-to-string `(and ,@regexps) t))
202 (t
203 (rx-to-string (car regexps) t)))))
204
205\f
206;;; Font-lock and syntax
207
208(defvar python-font-lock-keywords
209 ;; Keywords
210 `(,(rx symbol-start
211 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
212 "assert" "else" "if" "pass" "yield" "break" "except" "import"
213 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
214 "return" "def" "for" "lambda" "try" "self")
215 symbol-end)
216 ;; functions
217 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
218 (1 font-lock-function-name-face))
219 ;; classes
220 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
221 (1 font-lock-type-face))
222 ;; Constants
223 (,(rx symbol-start (group "None" symbol-end))
224 (1 font-lock-constant-face))
225 ;; Decorators.
226 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
227 (0+ "." (1+ (or word ?_)))))
228 (1 font-lock-type-face))
229 ;; Builtin Exceptions
230 (,(rx symbol-start
231 (or "ArithmeticError" "AssertionError" "AttributeError"
232 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
233 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
234 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
235 "ImportWarning" "IndentationError" "IndexError" "KeyError"
236 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
237 "NotImplemented" "NotImplementedError" "OSError" "OverflowError"
238 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
239 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
240 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
241 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
242 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
243 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
244 symbol-end) . font-lock-type-face)
245 ;; Builtins
246 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
247 (group
248 (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
249 "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer"
250 "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce"
251 "compile" "complex" "copyright" "credits" "delattr" "dict" "dir"
252 "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter"
253 "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash"
254 "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
255 "iter" "len" "license" "list" "locals" "long" "map" "max" "min"
256 "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit"
257 "range" "raw_input" "reduce" "reload" "repr" "reversed" "round"
258 "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum"
259 "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip"
260 "True" "False" "Ellipsis")) symbol-end)
261 (1 font-lock-builtin-face))
262 ;; asignations
263 ;; support for a = b = c = 5
264 (,(lambda (limit)
265 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
266 assignment-operator)))
267 (when (re-search-forward re limit t)
268 (while (and (not (equal (nth 0 (syntax-ppss)) 0))
269 (re-search-forward re limit t)))
270 (if (equal (nth 0 (syntax-ppss)) 0)
271 t
272 (set-match-data nil)))))
273 (1 font-lock-variable-name-face nil nil))
274 ;; support for a, b, c = (1, 2, 3)
275 (,(lambda (limit)
276 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
277 (* ?, (* space) (+ (any word ?. ?_)) (* space))
278 ?, (* space) (+ (any word ?. ?_)) (* space)
279 assignment-operator)))
280 (when (and (re-search-forward re limit t)
281 (goto-char (nth 3 (match-data))))
282 (while (and (not (equal (nth 0 (syntax-ppss)) 0))
283 (re-search-forward re limit t))
284 (goto-char (nth 3 (match-data))))
285 (if (equal (nth 0 (syntax-ppss)) 0)
286 t
287 (set-match-data nil)))))
288 (1 font-lock-variable-name-face nil nil))))
289
290;; Fixme: Is there a better way?
291(defconst python-font-lock-syntactic-keywords
292 ;; First avoid a sequence preceded by an odd number of backslashes.
293 `((,(rx (not (any ?\\))
294 ?\\ (* (and ?\\ ?\\))
295 (group (syntax string-quote))
296 (backref 1)
297 (group (backref 1)))
298 (2 ,(string-to-syntax "\""))) ; dummy
299 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
300 (optional (any "rR")) ; possible second prefix
301 (group (syntax string-quote)) ; maybe gets property
302 (backref 2) ; per first quote
303 (group (backref 2))) ; maybe gets property
304 (1 (python-quote-syntax 1))
305 (2 (python-quote-syntax 2))
306 (3 (python-quote-syntax 3))))
307 "Make outer chars of triple-quote strings into generic string delimiters.")
308
309(defun python-quote-syntax (n)
310 "Put `syntax-table' property correctly on triple quote.
311Used for syntactic keywords. N is the match number (1, 2 or 3)."
312 ;; Given a triple quote, we have to check the context to know
313 ;; whether this is an opening or closing triple or whether it's
314 ;; quoted anyhow, and should be ignored. (For that we need to do
315 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
316 ;; to use it here despite initial worries.) We also have to sort
317 ;; out a possible prefix -- well, we don't _have_ to, but I think it
318 ;; should be treated as part of the string.
319
320 ;; Test cases:
321 ;; ur"""ar""" x='"' # """
322 ;; x = ''' """ ' a
323 ;; '''
324 ;; x '"""' x """ \"""" x
325 (save-excursion
326 (goto-char (match-beginning 0))
327 (cond
328 ;; Consider property for the last char if in a fenced string.
329 ((= n 3)
330 (let* ((font-lock-syntactic-keywords nil)
331 (syntax (syntax-ppss)))
332 (when (eq t (nth 3 syntax)) ; after unclosed fence
333 (goto-char (nth 8 syntax)) ; fence position
334 (skip-chars-forward "uUrR") ; skip any prefix
335 ;; Is it a matching sequence?
336 (if (eq (char-after) (char-after (match-beginning 2)))
337 (eval-when-compile (string-to-syntax "|"))))))
338 ;; Consider property for initial char, accounting for prefixes.
339 ((or (and (= n 2) ; leading quote (not prefix)
340 (= (match-beginning 1) (match-end 1))) ; prefix is null
341 (and (= n 1) ; prefix
342 (/= (match-beginning 1) (match-end 1)))) ; non-empty
343 (let ((font-lock-syntactic-keywords nil))
344 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
345 (eval-when-compile (string-to-syntax "|")))))
346 ;; Otherwise (we're in a non-matching string) the property is
347 ;; nil, which is OK.
348 )))
349
350(defvar python-mode-syntax-table
351 (let ((table (make-syntax-table)))
352 ;; Give punctuation syntax to ASCII that normally has symbol
353 ;; syntax or has word syntax and isn't a letter.
354 (let ((symbol (string-to-syntax "_"))
355 (sst (standard-syntax-table)))
356 (dotimes (i 128)
357 (unless (= i ?_)
358 (if (equal symbol (aref sst i))
359 (modify-syntax-entry i "." table)))))
360 (modify-syntax-entry ?$ "." table)
361 (modify-syntax-entry ?% "." table)
362 ;; exceptions
363 (modify-syntax-entry ?# "<" table)
364 (modify-syntax-entry ?\n ">" table)
365 (modify-syntax-entry ?' "\"" table)
366 (modify-syntax-entry ?` "$" table)
367 table)
368 "Syntax table for Python files.")
369
370(defvar python-dotty-syntax-table
371 (let ((table (make-syntax-table python-mode-syntax-table)))
372 (modify-syntax-entry ?. "w" table)
373 (modify-syntax-entry ?_ "w" table)
374 table)
375 "Dotty syntax table for Python files.
376It makes underscores and dots word constituent chars.")
377
378\f
379;;; Indentation
380
381(defcustom python-indent-offset 4
382 "Default indentation offset for Python."
383 :group 'python
384 :type 'integer
385 :safe 'integerp)
386
387(defcustom python-indent-guess-indent-offset t
388 "Non-nil tells Python mode to guess `python-indent-offset' value."
389 :type 'boolean
390 :group 'python)
391
392(defvar python-indent-current-level 0
393 "Current indentation level `python-indent-line-function' is using.")
394
395(defvar python-indent-levels '(0)
396 "Levels of indentation available for `python-indent-line-function'.")
397
398(defvar python-indent-dedenters '("else" "elif" "except" "finally")
399 "List of words that should be dedented.
400These make `python-indent-calculate-indentation' subtract the value of
401`python-indent-offset'.")
402
403(defun python-indent-guess-indent-offset ()
404 "Guess and set the value for `python-indent-offset' given the current buffer."
405 (let ((guessed-indentation (save-excursion
406 (goto-char (point-min))
407 (re-search-forward ":\\s-*\n" nil t)
408 (while (and (not (eobp)) (forward-comment 1)))
409 (current-indentation))))
410 (when (not (equal guessed-indentation 0))
411 (setq python-indent-offset guessed-indentation))))
412
413(defun python-indent-context (&optional stop)
414 "Return information on indentation context.
415Optional argument STOP serves to stop recursive calls.
416
417Returns a cons with the form:
418
419\(STATUS . START)
420
421Where status can be any of the following symbols:
422
423 * inside-paren: If point in between (), {} or []
424 * inside-string: If point is inside a string
425 * after-backslash: Previous line ends in a backslash
426 * after-beginning-of-block: Point is after beginning of block
427 * after-line: Point is after normal line
428 * no-indent: Point is at beginning of buffer or other special case
429
430START is the buffer position where the sexp starts."
431 (save-restriction
432 (widen)
433 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
434 (start))
435 (cons
436 (cond
437 ;; Inside a paren
438 ((setq start (nth 1 ppss))
439 'inside-paren)
440 ;; Inside string
441 ((setq start (when (and (nth 3 ppss))
442 (nth 8 ppss)))
443 'inside-string)
444 ;; After backslash
445 ((setq start (when (not (syntax-ppss-context ppss))
446 (let ((line-beg-pos (line-beginning-position)))
447 (when (eq ?\\ (char-before (1- line-beg-pos)))
448 (- line-beg-pos 2)))))
449 'after-backslash)
450 ;; After beginning of block
451 ((setq start (save-excursion
452 (let ((block-regexp (python-rx block-start))
453 (block-start-line-end ":[[:space:]]*$"))
454 (back-to-indentation)
455 (while (and (forward-comment -1) (not (bobp))))
456 (back-to-indentation)
457 (when (or (python-info-continuation-line-p)
458 (and (not (looking-at block-regexp))
459 (save-excursion
460 (re-search-forward
461 block-start-line-end
462 (line-end-position) t))))
463 (while (and (forward-line -1)
464 (python-info-continuation-line-p)
465 (not (bobp))))
466 (when (not (looking-at block-regexp))
467 (forward-line 1)))
468 (back-to-indentation)
469 (when (and (looking-at block-regexp)
470 (or (re-search-forward
471 block-start-line-end
472 (line-end-position) t)
473 (python-info-continuation-line-p)))
474 (point-marker)))))
475 'after-beginning-of-block)
476 ;; After normal line
477 ((setq start (save-excursion
478 (while (and (forward-comment -1) (not (bobp))))
479 (while (and (not (back-to-indentation))
480 (not (bobp))
481 (if (> (nth 0 (syntax-ppss)) 0)
482 (forward-line -1)
483 (if (save-excursion
484 (forward-line -1)
485 (python-info-line-ends-backslash-p))
486 (forward-line -1)))))
487 (point-marker)))
488 'after-line)
489 ;; Do not indent
490 (t 'no-indent))
491 start))))
492
493(defun python-indent-calculate-indentation ()
494 "Calculate correct indentation offset for the current line."
495 (let* ((indentation-context (python-indent-context))
496 (context-status (car indentation-context))
497 (context-start (cdr indentation-context)))
498 (save-restriction
499 (widen)
500 (save-excursion
501 (case context-status
502 ('no-indent 0)
503 ('after-beginning-of-block
504 (goto-char context-start)
505 (+ (current-indentation) python-indent-offset))
506 ('after-line
507 (-
508 (save-excursion
509 (goto-char context-start)
510 (current-indentation))
511 (if (progn
512 (back-to-indentation)
513 (looking-at (regexp-opt python-indent-dedenters)))
514 python-indent-offset
515 0)))
516 ('inside-string
517 (goto-char context-start)
518 (current-indentation))
519 ('after-backslash
520 (let* ((block-continuation
521 (save-excursion
522 (forward-line -1)
523 (python-info-block-continuation-line-p)))
524 (assignment-continuation
525 (save-excursion
526 (forward-line -1)
527 (python-info-assignment-continuation-line-p)))
528 (indentation (cond (block-continuation
529 (goto-char block-continuation)
530 (re-search-forward
531 (python-rx block-start (* space))
532 (line-end-position) t)
533 (current-column))
534 (assignment-continuation
535 (goto-char assignment-continuation)
536 (re-search-forward
537 (python-rx simple-operator)
538 (line-end-position) t)
539 (forward-char 1)
540 (re-search-forward
541 (python-rx (* space))
542 (line-end-position) t)
543 (current-column))
544 (t
545 (goto-char context-start)
546 (current-indentation)))))
547 indentation))
548 ('inside-paren
549 (-
550 (save-excursion
551 (goto-char context-start)
552 (forward-char)
553 (if (looking-at "[[:space:]]*$")
554 (+ (current-indentation) python-indent-offset)
555 (forward-comment 1)
556 (current-column)))
557 (if (progn
558 (back-to-indentation)
559 (looking-at (regexp-opt '(")" "]" "}"))))
560 python-indent-offset
561 0))))))))
562
563(defun python-indent-calculate-levels ()
564 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
565 (let* ((indentation (python-indent-calculate-indentation))
566 (remainder (% indentation python-indent-offset))
567 (steps (/ (- indentation remainder) python-indent-offset)))
568 (setq python-indent-levels '())
569 (setq python-indent-levels (cons 0 python-indent-levels))
570 (dotimes (step steps)
571 (setq python-indent-levels
572 (cons (* python-indent-offset (1+ step)) python-indent-levels)))
573 (when (not (eq 0 remainder))
574 (setq python-indent-levels
575 (cons (+ (* python-indent-offset steps) remainder)
576 python-indent-levels)))
577 (setq python-indent-levels (nreverse python-indent-levels))
578 (setq python-indent-current-level (1- (length python-indent-levels)))))
579
580(defun python-indent-toggle-levels ()
581 "Toggle `python-indent-current-level' over `python-indent-levels'."
582 (setq python-indent-current-level (1- python-indent-current-level))
583 (when (< python-indent-current-level 0)
584 (setq python-indent-current-level (1- (length python-indent-levels)))))
585
586(defun python-indent-line (&optional force-toggle)
587 "Internal implementation of `python-indent-line-function'.
588
589Uses the offset calculated in
590`python-indent-calculate-indentation' and available levels
591indicated by the variable `python-indent-levels'.
592
593When the variable `last-command' is equal to
594`indent-for-tab-command' or FORCE-TOGGLE is non-nil:
595
596* Cycles levels indicated in the variable `python-indent-levels'
597 by setting the current level in the variable
598 `python-indent-current-level'.
599
600When the variable `last-command' is not equal to
601`indent-for-tab-command' and FORCE-TOGGLE is nil:
602
603* calculates possible indentation levels and saves it in the
604 variable `python-indent-levels'.
605
606* sets the variable `python-indent-current-level' correctly so
607 offset is equal to (`nth' `python-indent-current-level'
608 `python-indent-levels')"
609 (if (or (and (eq this-command 'indent-for-tab-command)
610 (eq last-command this-command))
611 force-toggle)
612 (python-indent-toggle-levels)
613 (python-indent-calculate-levels))
614 (beginning-of-line)
615 (delete-horizontal-space)
616 (indent-to (nth python-indent-current-level python-indent-levels))
617 (save-restriction
618 (widen)
619 (let ((closing-block-point (python-info-closing-block)))
620 (when closing-block-point
621 (message "Closes %s" (buffer-substring
622 closing-block-point
623 (save-excursion
624 (goto-char closing-block-point)
625 (line-end-position))))))))
626
627(defun python-indent-line-function ()
628 "`indent-line-function' for Python mode.
629Internally just calls `python-indent-line'."
630 (python-indent-line))
631
632(defun python-indent-dedent-line ()
633 "Dedent current line."
634 (interactive "*")
635 (when (and (not (syntax-ppss-context (syntax-ppss)))
636 (<= (point-marker) (save-excursion
637 (back-to-indentation)
638 (point-marker)))
639 (> (current-column) 0))
640 (python-indent-line t)
641 t))
642
643(defun python-indent-dedent-line-backspace (arg)
644 "Dedent current line.
645Argument ARG is passed to `backward-delete-char-untabify' when
646point is not in between the indentation."
647 (interactive "*p")
648 (when (not (python-indent-dedent-line))
649 (backward-delete-char-untabify arg)))
650
651(defun python-indent-region (start end)
652 "Indent a python region automagically.
653
654Called from a program, START and END specify the region to indent."
655 (save-excursion
656 (goto-char end)
657 (setq end (point-marker))
658 (goto-char start)
659 (or (bolp) (forward-line 1))
660 (while (< (point) end)
661 (or (and (bolp) (eolp))
662 (let (word)
663 (forward-line -1)
664 (back-to-indentation)
665 (setq word (current-word))
666 (forward-line 1)
667 (when word
668 (beginning-of-line)
669 (delete-horizontal-space)
670 (indent-to (python-indent-calculate-indentation)))))
671 (forward-line 1))
672 (move-marker end nil)))
673
674(defun python-indent-shift-left (start end &optional count)
675 "Shift lines contained in region START END by COUNT columns to the left.
676
677COUNT defaults to `python-indent-offset'.
678
679If region isn't active, the current line is shifted.
680
681The shifted region includes the lines in which START and END lie.
682
683An error is signaled if any lines in the region are indented less
684than COUNT columns."
685 (interactive
686 (if mark-active
687 (list (region-beginning) (region-end) current-prefix-arg)
688 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
689 (if count
690 (setq count (prefix-numeric-value count))
691 (setq count python-indent-offset))
692 (when (> count 0)
693 (save-excursion
694 (goto-char start)
695 (while (< (point) end)
696 (if (and (< (current-indentation) count)
697 (not (looking-at "[ \t]*$")))
698 (error "Can't shift all lines enough"))
699 (forward-line))
700 (indent-rigidly start end (- count)))))
701
702(add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
703
704(defun python-indent-shift-right (start end &optional count)
705 "Shift lines contained in region START END by COUNT columns to the left.
706
707COUNT defaults to `python-indent-offset'.
708
709If region isn't active, the current line is shifted.
710
711The shifted region includes the lines in which START and END
712lie."
713 (interactive
714 (if mark-active
715 (list (region-beginning) (region-end) current-prefix-arg)
716 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
717 (if count
718 (setq count (prefix-numeric-value count))
719 (setq count python-indent-offset))
720 (indent-rigidly start end count))
721
722\f
723;;; Navigation
724
725(defvar python-beginning-of-defun-regexp
726 "^\\(def\\|class\\)[[:space:]]+[[:word:]]+"
727 "Regular expresion matching beginning of outermost class or function.")
728
729(defvar python-beginning-of-innermost-defun-regexp
730 "^[[:space:]]*\\(def\\|class\\)[[:space:]]+[[:word:]]+"
731 "Regular expresion matching beginning of innermost class or function.")
732
733(defun python-beginning-of-defun (&optional innermost)
734 "Move point to the beginning of innermost/outermost def or class.
735If INNERMOST is non-nil then move to the beginning of the
736innermost definition."
737 (let ((starting-point (point-marker))
738 (nonblank-line-indent)
739 (defun-indent)
740 (defun-point)
741 (regexp (if innermost
742 python-beginning-of-innermost-defun-regexp
743 python-beginning-of-defun-regexp)))
744 (back-to-indentation)
745 (if (and (not (looking-at "@"))
746 (not (looking-at regexp)))
747 (forward-comment -1)
748 (while (and (not (eobp))
749 (forward-line 1)
750 (not (back-to-indentation))
751 (looking-at "@"))))
752 (when (not (looking-at regexp))
753 (re-search-backward regexp nil t))
754 (setq nonblank-line-indent (+ (current-indentation) python-indent-offset))
755 (setq defun-indent (current-indentation))
756 (setq defun-point (point-marker))
757 (if (> nonblank-line-indent defun-indent)
758 (progn
759 (goto-char defun-point)
760 (forward-line -1)
761 (while (and (looking-at "@")
762 (forward-line -1)
763 (not (bobp))
764 (not (back-to-indentation))))
765 (forward-line 1)
766 (point-marker))
767 (if innermost
768 (python-beginning-of-defun)
769 (goto-char starting-point)
770 nil))))
771
772(defun python-beginning-of-defun-function ()
773 "Move point to the beginning of outermost def or class.
774Returns nil if point is not in a def or class."
775 (python-beginning-of-defun nil))
776
777(defun python-beginning-of-innermost-defun ()
778 "Move point to the beginning of innermost def or class.
779Returns nil if point is not in a def or class."
780 (interactive)
781 (python-beginning-of-defun t))
782
783(defun python-end-of-defun-function ()
784 "Move point to the end of def or class.
785Returns nil if point is not in a def or class."
786 (let ((starting-point (point-marker))
787 (defun-regexp (python-rx defun))
788 (beg-defun-indent))
789 (back-to-indentation)
790 (if (looking-at "@")
791 (while (and (not (eobp))
792 (forward-line 1)
793 (not (back-to-indentation))
794 (looking-at "@")))
795 (while (and (not (bobp))
796 (not (progn (back-to-indentation) (current-word)))
797 (forward-line -1))))
798 (when (or (not (equal (current-indentation) 0))
799 (string-match defun-regexp (current-word)))
800 (setq beg-defun-indent (save-excursion
801 (or (looking-at defun-regexp)
802 (python-beginning-of-innermost-defun))
803 (current-indentation)))
804 (while (and (forward-line 1)
805 (not (eobp))
806 (or (not (current-word))
807 (> (current-indentation) beg-defun-indent))))
808 (while (and (forward-comment -1)
809 (not (bobp))))
810 (forward-line 1)
811 (point-marker))))
812
813\f
814;;; Shell integration
815
816(defvar python-shell-buffer-name "Python"
817 "Default buffer name for Python interpreter.")
818
819(defcustom python-shell-interpreter "python"
820 "Default Python interpreter for shell."
821 :group 'python
822 :type 'string
823 :safe 'stringp)
824
825(defcustom python-shell-interpreter-args "-i"
826 "Default arguments for the Python interpreter."
827 :group 'python
828 :type 'string
829 :safe 'stringp)
830
831(defcustom python-shell-prompt-regexp ">>> "
832 "Regex matching top\-level input prompt of python shell.
833The regex should not contain a caret (^) at the beginning."
834 :type 'string
835 :group 'python
836 :safe 'stringp)
837
838(defcustom python-shell-prompt-block-regexp "[.][.][.] "
839 "Regex matching block input prompt of python shell.
840The regex should not contain a caret (^) at the beginning."
841 :type 'string
842 :group 'python
843 :safe 'stringp)
844
845(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
846 "Regex matching pdb input prompt of python shell.
847The regex should not contain a caret (^) at the beginning."
848 :type 'string
849 :group 'python
850 :safe 'stringp)
851
852(defcustom python-shell-compilation-regexp-alist
853 `((,(rx line-start (1+ (any " \t")) "File \""
854 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
855 "\", line " (group (1+ digit)))
856 1 2)
857 (,(rx " in file " (group (1+ not-newline)) " on line "
858 (group (1+ digit)))
859 1 2)
860 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
861 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
862 1 2))
863 "`compilation-error-regexp-alist' for inferior Python."
864 :type '(alist string)
865 :group 'python)
866
867(defun python-shell-get-process-name (dedicated)
868 "Calculate the appropiate process name for inferior Python process.
869
870If DEDICATED is t and the variable `buffer-file-name' is non-nil
871returns a string with the form
872`python-shell-buffer-name'[variable `buffer-file-name'] else
873returns the value of `python-shell-buffer-name'.
874
875After calculating the process name add the buffer name for the
876process in the `same-window-buffer-names' list"
877 (let ((process-name
878 (if (and dedicated
879 buffer-file-name)
880 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
881 (format "%s" python-shell-buffer-name))))
882 (add-to-list 'same-window-buffer-names (purecopy
883 (format "*%s*" process-name)))
884 process-name))
885
886(defun python-shell-parse-command ()
887 "Calculates the string used to execute the inferior Python process."
888 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
889
890(defun python-comint-output-filter-function (output)
891 "Hook run after content is put into comint buffer.
892OUTPUT is a string with the contents of the buffer."
893 (ansi-color-filter-apply output))
894
895(defvar inferior-python-mode-current-file nil
896 "Current file from which a region was sent.")
897(make-variable-buffer-local 'inferior-python-mode-current-file)
898
899(defvar inferior-python-mode-current-temp-file nil
900 "Current temp file sent to process.")
901(make-variable-buffer-local 'inferior-python-mode-current-file)
902
903(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
904 "Major mode for Python inferior process."
905 (set-syntax-table python-mode-syntax-table)
906 (setq mode-line-process '(":%s"))
907 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
908 python-shell-prompt-regexp
909 python-shell-prompt-block-regexp
910 python-shell-prompt-pdb-regexp))
911 (make-local-variable 'comint-output-filter-functions)
912 (add-hook 'comint-output-filter-functions
913 'python-comint-output-filter-function)
914 (add-hook 'comint-output-filter-functions
915 'python-pdbtrack-comint-output-filter-function)
916 (set (make-local-variable 'compilation-error-regexp-alist)
917 python-shell-compilation-regexp-alist)
918 (compilation-shell-minor-mode 1))
919
920(defun run-python (dedicated cmd)
921 "Run an inferior Python process.
922
923Input and output via buffer *\\[python-shell-buffer-name]*.
924
925If there is a process already running in
926*\\[python-shell-buffer-name]*, switch to that buffer.
927
928With argument, allows you to:
929
930 * Define DEDICATED so a dedicated process for the current buffer
931 is open.
932
933 * Define CMD so you can edit the command used to call the
934interpreter (default is value of `python-shell-interpreter' and
935arguments defined in `python-shell-interpreter-args').
936
937Runs the hook `inferior-python-mode-hook' (after the
938`comint-mode-hook' is run).
939
940\(Type \\[describe-mode] in the process buffer for a list of
941commands.)"
942 (interactive
943 (if current-prefix-arg
944 (list
945 (y-or-n-p "Make dedicated process? ")
946 (read-string "Run Python: " (python-shell-parse-command)))
947 (list nil (python-shell-parse-command))))
948 (let* ((proc-name (python-shell-get-process-name dedicated))
949 (proc-buffer-name (format "*%s*" proc-name)))
950 (when (not (comint-check-proc proc-buffer-name))
951 (let ((cmdlist (split-string-and-unquote cmd)))
952 (set-buffer
953 (apply 'make-comint proc-name (car cmdlist) nil
954 (cdr cmdlist)))
955 (inferior-python-mode)))
956 (pop-to-buffer proc-buffer-name))
957 dedicated)
958
959(defun python-shell-get-process ()
960 "Get inferior Python process for current buffer and return it."
961 (let* ((dedicated-proc-name (python-shell-get-process-name t))
962 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
963 (global-proc-name (python-shell-get-process-name nil))
964 (global-proc-buffer-name (format "*%s*" global-proc-name))
965 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
966 (global-running (comint-check-proc global-proc-buffer-name)))
967 ;; Always prefer dedicated
968 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
969 (and global-running global-proc-buffer-name)))))
970
971(defun python-shell-get-or-create-process ()
972 "Get or create an inferior Python process for current buffer and return it."
79dafa51
FEG
973 (let* ((old-buffer (current-buffer))
974 (dedicated-proc-name (python-shell-get-process-name t))
45c138ac
FEG
975 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
976 (global-proc-name (python-shell-get-process-name nil))
977 (global-proc-buffer-name (format "*%s*" global-proc-name))
978 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
979 (global-running (comint-check-proc global-proc-buffer-name))
980 (current-prefix-arg 4))
981 (when (and (not dedicated-running) (not global-running))
982 (if (call-interactively 'run-python)
983 (setq dedicated-running t)
984 (setq global-running t)))
985 ;; Always prefer dedicated
79dafa51 986 (switch-to-buffer old-buffer)
45c138ac
FEG
987 (get-buffer-process (if dedicated-running
988 dedicated-proc-buffer-name
989 global-proc-buffer-name))))
990
991(defun python-shell-send-string (string)
992 "Send STRING to inferior Python process."
993 (interactive "sPython command: ")
994 (let ((process (python-shell-get-or-create-process)))
995 (message (format "Sent: %s..." string))
996 (comint-send-string process string)
997 (when (or (not (string-match "\n$" string))
998 (string-match "\n[ \t].*\n?$" string))
999 (comint-send-string process "\n"))))
1000
1001(defun python-shell-send-region (start end)
1002 "Send the region delimited by START and END to inferior Python process."
1003 (interactive "r")
1004 (let* ((contents (buffer-substring start end))
1005 (current-file (buffer-file-name))
1006 (process (python-shell-get-or-create-process))
66b0b492 1007 (temp-file (make-temp-file "py")))
45c138ac
FEG
1008 (with-temp-file temp-file
1009 (insert contents)
1010 (delete-trailing-whitespace)
1011 (goto-char (point-min))
1012 (message (format "Sent: %s..."
1013 (buffer-substring (point-min)
1014 (line-end-position)))))
1015 (with-current-buffer (process-buffer process)
1016 (setq inferior-python-mode-current-file current-file)
66b0b492
FEG
1017 (setq inferior-python-mode-current-temp-file temp-file))
1018 (python-shell-send-file temp-file process)))
45c138ac
FEG
1019
1020(defun python-shell-send-buffer ()
1021 "Send the entire buffer to inferior Python process."
1022 (interactive)
1023 (save-restriction
1024 (widen)
1025 (python-shell-send-region (point-min) (point-max))))
1026
1027(defun python-shell-send-defun (arg)
1028 "Send the (inner|outer)most def or class to inferior Python process.
1029When argument ARG is non-nil sends the innermost defun."
1030 (interactive "P")
1031 (save-excursion
1032 (python-shell-send-region (progn
1033 (or (if arg
1034 (python-beginning-of-innermost-defun)
1035 (python-beginning-of-defun-function))
1036 (progn (beginning-of-line) (point-marker))))
1037 (progn
1038 (or (python-end-of-defun-function)
1039 (progn (end-of-line) (point-marker)))))))
1040
66b0b492 1041(defun python-shell-send-file (file-name &optional process)
45c138ac
FEG
1042 "Send FILE-NAME to inferior Python process."
1043 (interactive "fFile to send: ")
66b0b492
FEG
1044 (let ((process (or process (python-shell-get-or-create-process))))
1045 (accept-process-output process)
1046 (with-current-buffer (process-buffer process)
1047 (delete-region (save-excursion
1048 (move-to-column 0)
1049 (point-marker))
1050 (line-end-position)))
1051 (comint-send-string
1052 process
1053 (format "execfile('%s')\n" (expand-file-name file-name)))))
45c138ac
FEG
1054
1055(defun python-shell-switch-to-shell ()
1056 "Switch to inferior Python process buffer."
1057 (interactive)
1058 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1059
1060\f
1061;;; Shell completion
1062
1063(defvar python-shell-completion-setup-code
1064 "try:
1065 import readline
1066except ImportError:
1067 def __COMPLETER_all_completions(text): []
1068else:
1069 import rlcompleter
1070 readline.set_completer(rlcompleter.Completer().complete)
1071 def __COMPLETER_all_completions(text):
1072 import sys
1073 completions = []
1074 try:
1075 i = 0
1076 while True:
1077 res = readline.get_completer()(text, i)
1078 if not res: break
1079 i += 1
1080 completions.append(res)
1081 except NameError:
1082 pass
1083 return completions"
1084 "Code used to setup completion in inferior Python processes.")
1085
1086(defvar python-shell-completion-strings-code
1087 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1088 "Python code used to get a string of completions separated by semicolons.")
1089
1090(defun python-shell-completion-setup ()
1091 "Send `python-shell-completion-setup-code' to inferior Python process.
1092Also binds <tab> to `python-shell-complete-or-indent' in the
1093`inferior-python-mode-map' and adds
1094`python-shell-completion-complete-at-point' to the
1095`comint-dynamic-complete-functions' list.
1096It is specially designed to be added to the
1097`inferior-python-mode-hook'."
1098 (when python-shell-completion-setup-code
1099 (let ((temp-file (make-temp-file "py"))
1100 (process (get-buffer-process (current-buffer))))
1101 (with-temp-file temp-file
1102 (insert python-shell-completion-setup-code)
1103 (delete-trailing-whitespace)
1104 (goto-char (point-min)))
66b0b492 1105 (python-shell-send-file temp-file process)
45c138ac
FEG
1106 (message (format "Completion setup code sent.")))
1107 (add-to-list (make-local-variable
1108 'comint-dynamic-complete-functions)
1109 'python-shell-completion-complete-at-point)
1110 (define-key inferior-python-mode-map (kbd "<tab>")
1111 'python-shell-completion-complete-or-indent)))
1112
1113(defun python-shell-completion-complete-at-point ()
1114 "Perform completion at point in inferior Python process."
1115 (interactive)
1116 (when (and comint-last-prompt-overlay
1117 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1118 (let* ((process (get-buffer-process (current-buffer)))
1119 (input (comint-word (current-word)))
1120 (completions (when input
1121 (delete-region (point-marker)
1122 (progn
1123 (forward-char (- (length input)))
1124 (point-marker)))
1125 (process-send-string
1126 process
1127 (format
1128 python-shell-completion-strings-code input))
1129 (accept-process-output process)
1130 (save-excursion
1131 (re-search-backward comint-prompt-regexp
1132 comint-last-input-end t)
1133 (split-string
1134 (buffer-substring-no-properties
1135 (point-marker) comint-last-input-end)
1136 ";\\|\"\\|'\\|(" t))))
1137 (completion (when completions (try-completion input completions))))
1138 (when completions
1139 (save-excursion
1140 (forward-line -1)
1141 (kill-line 1)))
1142 (cond ((eq completion t)
1143 (when input (insert input)))
1144 ((null completion)
1145 (when input (insert input))
1146 (message "Can't find completion for \"%s\"" input)
1147 (ding))
1148 ((not (string= input completion))
1149 (insert completion))
1150 (t
1151 (message "Making completion list...")
1152 (when input (insert input))
1153 (with-output-to-temp-buffer "*Python Completions*"
1154 (display-completion-list
1155 (all-completions input completions))))))))
1156
45c138ac
FEG
1157(defun python-shell-completion-complete-or-indent ()
1158 "Complete or indent depending on the context.
1159If content before pointer is all whitespace indent. If not try to
1160complete."
1161 (interactive)
1162 (if (string-match "^[[:space:]]*$"
1163 (buffer-substring (comint-line-beginning-position)
1164 (point-marker)))
1165 (indent-for-tab-command)
1166 (comint-dynamic-complete)))
1167
1168(add-hook 'inferior-python-mode-hook
1169 #'python-shell-completion-setup)
1170
1171\f
1172;;; PDB Track integration
1173
1174(defvar python-pdbtrack-stacktrace-info-regexp
1175 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1176 "Regexp matching stacktrace information.
1177It is used to extract the current line and module beign
1178inspected.
1179The regexp should not start with a caret (^) and can contain a
1180string placeholder (\%s) which is replaced with the filename
1181beign inspected (so other files in the debugging process are not
1182opened)")
1183
1184(defvar python-pdbtrack-tracking-buffers '()
1185 "Alist containing elements of form (#<buffer> . #<buffer>).
1186The car of each element of the alist is the tracking buffer and
1187the cdr is the tracked buffer.")
1188
1189(defun python-pdbtrack-get-or-add-tracking-buffers ()
1190 "Get/Add a tracked buffer for the current buffer.
1191Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1192Returns a cons with the form:
1193 * (#<tracking buffer> . #< tracked buffer>)."
1194 (or
1195 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1196 (let* ((file (with-current-buffer (current-buffer)
1197 (or inferior-python-mode-current-file
1198 inferior-python-mode-current-temp-file)))
1199 (tracking-buffers
1200 `(,(current-buffer) .
1201 ,(or (get-file-buffer file)
1202 (find-file-noselect file)))))
1203 (set-buffer (cdr tracking-buffers))
1204 (python-mode)
1205 (set-buffer (car tracking-buffers))
1206 (setq python-pdbtrack-tracking-buffers
1207 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1208 tracking-buffers)))
1209
1210(defun python-pdbtrack-comint-output-filter-function (output)
1211 "Move overlay arrow to current pdb line in tracked buffer.
1212Argument OUTPUT is a string with the output from the comint process."
1213 (when (not (string= output ""))
1214 (let ((full-output (ansi-color-filter-apply
1215 (buffer-substring comint-last-input-end
1216 (point-max)))))
1217 (if (string-match python-shell-prompt-pdb-regexp full-output)
1218 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1219 (line-num
1220 (save-excursion
1221 (string-match
1222 (format python-pdbtrack-stacktrace-info-regexp
1223 (regexp-quote
1224 inferior-python-mode-current-temp-file))
1225 full-output)
1226 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1227 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1228 (tracked-buffer-line-pos))
1229 (when line-num
1230 (with-current-buffer (cdr tracking-buffers)
1231 (set (make-local-variable 'overlay-arrow-string) "=>")
1232 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1233 (setq tracked-buffer-line-pos (progn
1234 (goto-char (point-min))
1235 (forward-line (1- line-num))
1236 (point-marker)))
1237 (when tracked-buffer-window
1238 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1239 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1240 (pop-to-buffer (cdr tracking-buffers))
1241 (switch-to-buffer-other-window (car tracking-buffers)))
1242 (let ((tracking-buffers (assq (current-buffer)
1243 python-pdbtrack-tracking-buffers)))
1244 (when tracking-buffers
1245 (if inferior-python-mode-current-file
1246 (with-current-buffer (cdr tracking-buffers)
1247 (set-marker overlay-arrow-position nil))
1248 (kill-buffer (cdr tracking-buffers)))
1249 (setq python-pdbtrack-tracking-buffers
1250 (assq-delete-all (current-buffer)
1251 python-pdbtrack-tracking-buffers)))))))
1252 output)
1253
1254\f
1255;;; Symbol completion
1256
1257(defun python-completion-complete-at-point ()
1258 "Complete current symbol at point.
1259For this to work the best as possible you should call
1260`python-shell-send-buffer' from time to time so context in
1261inferior python process is updated properly."
1262 (interactive)
1263 (let ((process (python-shell-get-process)))
1264 (if (not process)
1265 (error "Completion needs an inferior Python process running.")
1266 (let* ((input (when (comint-word (current-word))
1267 (with-syntax-table python-dotty-syntax-table
1268 (buffer-substring (point-marker)
1269 (save-excursion
1270 (forward-word -1)
1271 (point-marker))))))
1272 (completions (when input
1273 (delete-region (point-marker)
1274 (progn
1275 (forward-char (- (length input)))
1276 (point-marker)))
1277 (process-send-string
1278 process
1279 (format
1280 python-shell-completion-strings-code input))
1281 (accept-process-output process)
1282 (with-current-buffer (process-buffer process)
1283 (save-excursion
1284 (re-search-backward comint-prompt-regexp
1285 comint-last-input-end t)
1286 (split-string
1287 (buffer-substring-no-properties
1288 (point-marker) comint-last-input-end)
1289 ";\\|\"\\|'\\|(" t)))))
1290 (completion (when completions
1291 (try-completion input completions))))
1292 (with-current-buffer (process-buffer process)
1293 (save-excursion
1294 (forward-line -1)
1295 (kill-line 1)))
1296 (when completions
1297 (cond ((eq completion t)
1298 (insert input))
1299 ((null completion)
1300 (insert input)
1301 (message "Can't find completion for \"%s\"" input)
1302 (ding))
1303 ((not (string= input completion))
1304 (insert completion))
1305 (t
1306 (message "Making completion list...")
1307 (insert input)
1308 (with-output-to-temp-buffer "*Python Completions*"
1309 (display-completion-list
1310 (all-completions input completions))))))))))
1311
1312(add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1313
1314\f
1315;;; Fill paragraph
1316
1317(defun python-fill-paragraph-function (&optional justify)
1318 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1319If any of the current line is in or at the end of a multi-line string,
1320fill the string or the paragraph of it that point is in, preserving
1321the string's indentation."
1322 (interactive "P")
1323 (save-excursion
1324 (back-to-indentation)
1325 (cond
1326 ;; Comments
1327 ((fill-comment-paragraph justify))
1328 ;; Docstrings
1329 ((save-excursion (skip-chars-forward "\"'uUrR")
1330 (nth 3 (syntax-ppss)))
1331 (let ((marker (point-marker))
1332 (string-start-marker
1333 (progn
1334 (skip-chars-forward "\"'uUrR")
1335 (goto-char (nth 8 (syntax-ppss)))
1336 (skip-chars-forward "\"'uUrR")
1337 (point-marker)))
1338 (reg-start (line-beginning-position))
1339 (string-end-marker
1340 (progn
1341 (while (nth 3 (syntax-ppss)) (goto-char (1+ (point-marker))))
1342 (skip-chars-backward "\"'")
1343 (point-marker)))
1344 (reg-end (line-end-position))
1345 (fill-paragraph-function))
1346 (save-restriction
1347 (narrow-to-region reg-start reg-end)
1348 (save-excursion
1349 (goto-char string-start-marker)
1350 (delete-region (point-marker) (progn
1351 (skip-syntax-forward "> ")
1352 (point-marker)))
1353 (goto-char string-end-marker)
1354 (delete-region (point-marker) (progn
1355 (skip-syntax-backward "> ")
1356 (point-marker)))
1357 (save-excursion
1358 (goto-char marker)
1359 (fill-paragraph justify))
1360 ;; If there is a newline in the docstring lets put triple
1361 ;; quote in it's own line to follow pep 8
1362 (when (save-excursion
1363 (re-search-backward "\n" string-start-marker t))
1364 (newline)
1365 (newline-and-indent))
1366 (fill-paragraph justify)))) t)
1367 ;; Decorators
1368 ((equal (char-after (save-excursion
1369 (back-to-indentation)
1370 (point-marker))) ?@) t)
1371 ;; Parens
1372 ((or (> (nth 0 (syntax-ppss)) 0)
1373 (looking-at (python-rx open-paren))
1374 (save-excursion
1375 (skip-syntax-forward "^(" (line-end-position))
1376 (looking-at (python-rx open-paren))))
1377 (save-restriction
1378 (narrow-to-region (progn
1379 (while (> (nth 0 (syntax-ppss)) 0)
1380 (goto-char (1- (point-marker))))
1381 (point-marker)
1382 (line-beginning-position))
1383 (progn
1384 (when (not (> (nth 0 (syntax-ppss)) 0))
1385 (end-of-line)
1386 (when (not (> (nth 0 (syntax-ppss)) 0))
1387 (skip-syntax-backward "^)")))
1388 (while (> (nth 0 (syntax-ppss)) 0)
1389 (goto-char (1+ (point-marker))))
1390 (point-marker)))
1391 (let ((paragraph-start "\f\\|[ \t]*$")
1392 (paragraph-separate ",")
1393 (fill-paragraph-function))
1394 (goto-char (point-min))
1395 (fill-paragraph justify))
1396 (while (not (eobp))
1397 (forward-line 1)
1398 (python-indent-line)
1399 (goto-char (line-end-position)))) t)
1400 (t t))))
1401
1402\f
1403;;; Eldoc
1404
1405(defvar python-eldoc-setup-code
1406 "def __PYDOC_get_help(obj):
1407 try:
1408 import pydoc
1409 obj = eval(obj, globals())
1410 return pydoc.getdoc(obj)
1411 except:
1412 return ''"
1413 "Python code to setup documentation retrieval.")
1414
1415(defvar python-eldoc-string-code
1416 "print __PYDOC_get_help('''%s''')\n"
1417 "Python code used to get a string with the documentation of an object.")
1418
1419(defun python-eldoc-setup ()
1420 "Send `python-eldoc-setup-code' to inferior Python process.
1421It is specially designed to be added to the
1422`inferior-python-mode-hook'."
1423 (when python-eldoc-setup-code
1424 (let ((temp-file (make-temp-file "py")))
1425 (with-temp-file temp-file
1426 (insert python-eldoc-setup-code)
1427 (delete-trailing-whitespace)
1428 (goto-char (point-min)))
66b0b492 1429 (python-shell-send-file temp-file (get-buffer-process (current-buffer)))
45c138ac
FEG
1430 (message (format "Completion setup code sent.")))))
1431
1432(defun python-eldoc-function ()
1433 "`eldoc-documentation-function' for Python.
1434For this to work the best as possible you should call
1435`python-shell-send-buffer' from time to time so context in
1436inferior python process is updated properly."
1437 (interactive)
1438 (let ((process (python-shell-get-process)))
1439 (if (not process)
1440 "Eldoc needs an inferior Python process running."
1441 (let* ((current-defun (python-info-current-defun))
1442 (input (with-syntax-table python-dotty-syntax-table
1443 (if (not current-defun)
1444 (current-word)
1445 (concat current-defun "." (current-word)))))
1446 (ppss (syntax-ppss))
1447 (help (when (and input
1448 (not (string= input (concat current-defun ".")))
1449 (eq nil (nth 3 ppss))
1450 (eq nil (nth 4 ppss)))
1451 (when (string-match (concat
1452 (regexp-quote (concat current-defun "."))
1453 "self\\.") input)
1454 (with-temp-buffer
1455 (insert input)
1456 (goto-char (point-min))
1457 (forward-word)
1458 (forward-char)
1459 (delete-region (point-marker) (search-forward "self."))
1460 (setq input (buffer-substring (point-min) (point-max)))))
1461 (process-send-string
1462 process (format python-eldoc-string-code input))
1463 (accept-process-output process)
1464 (with-current-buffer (process-buffer process)
1465 (when comint-last-prompt-overlay
1466 (save-excursion
1467 (goto-char comint-last-input-end)
1468 (re-search-forward comint-prompt-regexp
1469 (line-end-position) t)
1470 (buffer-substring-no-properties
1471 (point-marker)
1472 (overlay-start comint-last-prompt-overlay))))))))
1473 (with-current-buffer (process-buffer process)
1474 (when comint-last-prompt-overlay
1475 (delete-region comint-last-input-end
1476 (overlay-start comint-last-prompt-overlay))))
1477 (when (and help
1478 (not (string= help "\n")))
1479 help)))))
1480
1481(add-hook 'inferior-python-mode-hook
1482 #'python-eldoc-setup)
1483
1484\f
1485;;; Misc helpers
1486
1487(defun python-info-current-defun ()
1488 "Return name of surrounding function with Python compatible dotty syntax.
1489This function is compatible to be used as
1490`add-log-current-defun-function' since it returns nil if point is
1491not inside a defun."
1492 (let ((names '()))
1493 (save-restriction
1494 (widen)
1495 (save-excursion
1496 (beginning-of-line)
1497 (when (not (>= (current-indentation) python-indent-offset))
1498 (while (and (not (eobp)) (forward-comment 1))))
1499 (while (and (not (equal 0 (current-indentation)))
1500 (python-beginning-of-innermost-defun))
1501 (back-to-indentation)
1502 (looking-at "\\(?:def\\|class\\) +\\([^(]+\\)[^:]+:\\s-*\n")
1503 (setq names (cons (match-string-no-properties 1) names)))))
1504 (when names
1505 (mapconcat (lambda (string) string) names "."))))
1506
1507(defun python-info-closing-block ()
1508 "Return the point of the block that the current line closes."
1509 (let ((closing-word (save-excursion
1510 (back-to-indentation)
1511 (current-word)))
1512 (indentation (current-indentation)))
1513 (when (member closing-word python-indent-dedenters)
1514 (save-excursion
1515 (forward-line -1)
1516 (while (and (> (current-indentation) indentation)
1517 (not (bobp))
1518 (not (back-to-indentation))
1519 (forward-line -1)))
1520 (back-to-indentation)
1521 (cond
1522 ((not (equal indentation (current-indentation))) nil)
1523 ((string= closing-word "elif")
1524 (when (member (current-word) '("if" "elif"))
1525 (point-marker)))
1526 ((string= closing-word "else")
1527 (when (member (current-word) '("if" "elif" "except" "for" "while"))
1528 (point-marker)))
1529 ((string= closing-word "except")
1530 (when (member (current-word) '("try"))
1531 (point-marker)))
1532 ((string= closing-word "finally")
1533 (when (member (current-word) '("except" "else"))
1534 (point-marker))))))))
1535
1536(defun python-info-line-ends-backslash-p ()
1537 "Return non-nil if current line ends with backslash."
1538 (string= (or (ignore-errors
1539 (buffer-substring
1540 (line-end-position)
1541 (- (line-end-position) 1))) "") "\\"))
1542
1543(defun python-info-continuation-line-p ()
1544 "Return non-nil if current line is continuation of another."
1545 (or (python-info-line-ends-backslash-p)
1546 (string-match ",[[:space:]]*$" (buffer-substring
1547 (line-beginning-position)
1548 (line-end-position)))
1549 (save-excursion
1550 (let ((innermost-paren (progn
1551 (goto-char (line-end-position))
1552 (nth 1 (syntax-ppss)))))
1553 (when (and innermost-paren
1554 (and (<= (line-beginning-position) innermost-paren)
1555 (>= (line-end-position) innermost-paren)))
1556 (goto-char innermost-paren)
1557 (looking-at (python-rx open-paren (* space) line-end)))))
1558 (save-excursion
1559 (back-to-indentation)
1560 (nth 1 (syntax-ppss)))))
1561
1562(defun python-info-block-continuation-line-p ()
1563 "Return non-nil if current line is a continuation of a block."
1564 (save-excursion
1565 (while (and (not (bobp))
1566 (python-info-continuation-line-p))
1567 (forward-line -1))
1568 (forward-line 1)
1569 (back-to-indentation)
1570 (when (looking-at (python-rx block-start))
1571 (point-marker))))
1572
1573(defun python-info-assignment-continuation-line-p ()
1574 "Return non-nil if current line is a continuation of an assignment."
1575 (save-excursion
1576 (while (and (not (bobp))
1577 (python-info-continuation-line-p))
1578 (forward-line -1))
1579 (forward-line 1)
1580 (back-to-indentation)
1581 (when (and (not (looking-at (python-rx block-start)))
1582 (save-excursion
1583 (and (re-search-forward (python-rx not-simple-operator
1584 assignment-operator
1585 not-simple-operator)
1586 (line-end-position) t)
1587 (not (syntax-ppss-context (syntax-ppss))))))
1588 (point-marker))))
1589
1590\f
1591;;;###autoload
1592(define-derived-mode python-mode fundamental-mode "Python"
1593 "A major mode for editing Python files."
1594 (set (make-local-variable 'tab-width) 8)
1595 (set (make-local-variable 'indent-tabs-mode) nil)
1596
1597 (set (make-local-variable 'comment-start) "# ")
1598 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
1599
1600 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1601 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1602
1603 (set (make-local-variable 'font-lock-defaults)
1604 '(python-font-lock-keywords
1605 nil nil nil nil
1606 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
1607
1608 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
1609 (set (make-local-variable 'indent-region-function) #'python-indent-region)
1610
1611 (set (make-local-variable 'paragraph-start) "\\s-*$")
1612 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
1613
1614 (set (make-local-variable 'beginning-of-defun-function)
1615 #'python-beginning-of-defun-function)
1616 (set (make-local-variable 'end-of-defun-function)
1617 #'python-end-of-defun-function)
1618
1619 (add-hook 'completion-at-point-functions
1620 'python-completion-complete-at-point nil 'local)
1621
1622 (set (make-local-variable 'add-log-current-defun-function)
1623 #'python-info-current-defun)
1624
1625 (set (make-local-variable 'eldoc-documentation-function)
1626 #'python-eldoc-function)
1627
1628 (add-to-list 'hs-special-modes-alist
1629 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
1630 ,(lambda (arg)
1631 (python-end-of-defun-function)) nil))
1632
1633 (set (make-local-variable 'outline-regexp)
1634 (python-rx (* space) block-start))
1635 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
1636 (set (make-local-variable 'outline-level)
1637 #'(lambda ()
1638 "`outline-level' function for Python mode."
1639 (1+ (/ (current-indentation) python-indent-offset))))
1640
1641 (when python-indent-guess-indent-offset
1642 (python-indent-guess-indent-offset)))
1643
1644
1645(provide 'python)
1646;;; python.el ends here