Documentation fixes
[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
4e531f7a 54;; word. Shell completion is implemented in a manner that if you
45c138ac
FEG
55;; change the `python-shell-interpreter' to any other (for example
56;; IPython) it should be easy to integrate another way to calculate
4e531f7a 57;; completions. You just need to especify your custom
45c138ac
FEG
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
4e531f7a 65;; Symbol completion: you can complete the symbol at point. It uses
45c138ac
FEG
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
4e531f7a 70;; inferior python subprocess to inspect its documentation. As you
45c138ac
FEG
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)
4e531f7a 196 "Python mode especialized rx macro which supports common python named REGEXPS."
45c138ac
FEG
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 ()
954aa7bd 404 "Guess and set `python-indent-offset' for the current buffer."
bbac1eb8
FEG
405 (save-excursion
406 (save-restriction
407 (widen)
408 (goto-char (point-min))
409 (let ((found-block))
410 (while (and (not found-block)
411 (re-search-forward
412 (python-rx line-start block-start) nil t))
413 (when (and (not (syntax-ppss-context (syntax-ppss)))
414 (progn
415 (goto-char (line-end-position))
416 (forward-comment -1)
417 (eq ?: (char-before))))
418 (setq found-block t)))
419 (if (not found-block)
420 (message "Can't guess python-indent-offset, using defaults: %s"
421 python-indent-offset)
422 (while (and (progn
423 (goto-char (line-end-position))
424 (python-info-continuation-line-p))
425 (not (eobp)))
426 (forward-line 1))
427 (forward-line 1)
428 (forward-comment 1)
429 (setq python-indent-offset (current-indentation)))))))
45c138ac
FEG
430
431(defun python-indent-context (&optional stop)
432 "Return information on indentation context.
433Optional argument STOP serves to stop recursive calls.
434
435Returns a cons with the form:
436
437\(STATUS . START)
438
439Where status can be any of the following symbols:
440
441 * inside-paren: If point in between (), {} or []
442 * inside-string: If point is inside a string
443 * after-backslash: Previous line ends in a backslash
444 * after-beginning-of-block: Point is after beginning of block
445 * after-line: Point is after normal line
446 * no-indent: Point is at beginning of buffer or other special case
447
448START is the buffer position where the sexp starts."
449 (save-restriction
450 (widen)
451 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
452 (start))
453 (cons
454 (cond
69bab1de 455 ;; Beginning of buffer
19b122e4
FEG
456 ((save-excursion
457 (goto-char (line-beginning-position))
458 (bobp))
69bab1de 459 'no-indent)
45c138ac
FEG
460 ;; Inside a paren
461 ((setq start (nth 1 ppss))
462 'inside-paren)
463 ;; Inside string
464 ((setq start (when (and (nth 3 ppss))
465 (nth 8 ppss)))
466 'inside-string)
467 ;; After backslash
468 ((setq start (when (not (syntax-ppss-context ppss))
469 (let ((line-beg-pos (line-beginning-position)))
470 (when (eq ?\\ (char-before (1- line-beg-pos)))
471 (- line-beg-pos 2)))))
472 'after-backslash)
473 ;; After beginning of block
474 ((setq start (save-excursion
475 (let ((block-regexp (python-rx block-start))
476 (block-start-line-end ":[[:space:]]*$"))
477 (back-to-indentation)
478 (while (and (forward-comment -1) (not (bobp))))
479 (back-to-indentation)
480 (when (or (python-info-continuation-line-p)
481 (and (not (looking-at block-regexp))
482 (save-excursion
483 (re-search-forward
484 block-start-line-end
485 (line-end-position) t))))
486 (while (and (forward-line -1)
487 (python-info-continuation-line-p)
488 (not (bobp))))
489 (when (not (looking-at block-regexp))
490 (forward-line 1)))
491 (back-to-indentation)
492 (when (and (looking-at block-regexp)
493 (or (re-search-forward
494 block-start-line-end
495 (line-end-position) t)
496 (python-info-continuation-line-p)))
497 (point-marker)))))
498 'after-beginning-of-block)
499 ;; After normal line
500 ((setq start (save-excursion
501 (while (and (forward-comment -1) (not (bobp))))
502 (while (and (not (back-to-indentation))
503 (not (bobp))
504 (if (> (nth 0 (syntax-ppss)) 0)
505 (forward-line -1)
506 (if (save-excursion
507 (forward-line -1)
508 (python-info-line-ends-backslash-p))
509 (forward-line -1)))))
510 (point-marker)))
511 'after-line)
512 ;; Do not indent
513 (t 'no-indent))
514 start))))
515
516(defun python-indent-calculate-indentation ()
517 "Calculate correct indentation offset for the current line."
518 (let* ((indentation-context (python-indent-context))
519 (context-status (car indentation-context))
520 (context-start (cdr indentation-context)))
521 (save-restriction
522 (widen)
523 (save-excursion
524 (case context-status
525 ('no-indent 0)
526 ('after-beginning-of-block
527 (goto-char context-start)
528 (+ (current-indentation) python-indent-offset))
529 ('after-line
530 (-
531 (save-excursion
532 (goto-char context-start)
533 (current-indentation))
534 (if (progn
535 (back-to-indentation)
536 (looking-at (regexp-opt python-indent-dedenters)))
537 python-indent-offset
538 0)))
539 ('inside-string
540 (goto-char context-start)
541 (current-indentation))
542 ('after-backslash
543 (let* ((block-continuation
544 (save-excursion
545 (forward-line -1)
546 (python-info-block-continuation-line-p)))
547 (assignment-continuation
548 (save-excursion
549 (forward-line -1)
550 (python-info-assignment-continuation-line-p)))
551 (indentation (cond (block-continuation
552 (goto-char block-continuation)
553 (re-search-forward
554 (python-rx block-start (* space))
555 (line-end-position) t)
556 (current-column))
557 (assignment-continuation
558 (goto-char assignment-continuation)
559 (re-search-forward
560 (python-rx simple-operator)
561 (line-end-position) t)
562 (forward-char 1)
563 (re-search-forward
564 (python-rx (* space))
565 (line-end-position) t)
566 (current-column))
567 (t
568 (goto-char context-start)
569 (current-indentation)))))
570 indentation))
571 ('inside-paren
572 (-
573 (save-excursion
574 (goto-char context-start)
575 (forward-char)
13d1a42e
FEG
576 (save-restriction
577 (narrow-to-region
578 (line-beginning-position)
579 (line-end-position))
580 (forward-comment 1))
581 (if (looking-at "$")
45c138ac
FEG
582 (+ (current-indentation) python-indent-offset)
583 (forward-comment 1)
584 (current-column)))
585 (if (progn
586 (back-to-indentation)
587 (looking-at (regexp-opt '(")" "]" "}"))))
588 python-indent-offset
589 0))))))))
590
591(defun python-indent-calculate-levels ()
592 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
593 (let* ((indentation (python-indent-calculate-indentation))
594 (remainder (% indentation python-indent-offset))
595 (steps (/ (- indentation remainder) python-indent-offset)))
596 (setq python-indent-levels '())
597 (setq python-indent-levels (cons 0 python-indent-levels))
598 (dotimes (step steps)
599 (setq python-indent-levels
600 (cons (* python-indent-offset (1+ step)) python-indent-levels)))
601 (when (not (eq 0 remainder))
602 (setq python-indent-levels
603 (cons (+ (* python-indent-offset steps) remainder)
604 python-indent-levels)))
605 (setq python-indent-levels (nreverse python-indent-levels))
606 (setq python-indent-current-level (1- (length python-indent-levels)))))
607
608(defun python-indent-toggle-levels ()
609 "Toggle `python-indent-current-level' over `python-indent-levels'."
610 (setq python-indent-current-level (1- python-indent-current-level))
611 (when (< python-indent-current-level 0)
612 (setq python-indent-current-level (1- (length python-indent-levels)))))
613
614(defun python-indent-line (&optional force-toggle)
615 "Internal implementation of `python-indent-line-function'.
616
617Uses the offset calculated in
618`python-indent-calculate-indentation' and available levels
619indicated by the variable `python-indent-levels'.
620
621When the variable `last-command' is equal to
622`indent-for-tab-command' or FORCE-TOGGLE is non-nil:
623
624* Cycles levels indicated in the variable `python-indent-levels'
625 by setting the current level in the variable
626 `python-indent-current-level'.
627
628When the variable `last-command' is not equal to
629`indent-for-tab-command' and FORCE-TOGGLE is nil:
630
631* calculates possible indentation levels and saves it in the
632 variable `python-indent-levels'.
633
634* sets the variable `python-indent-current-level' correctly so
635 offset is equal to (`nth' `python-indent-current-level'
636 `python-indent-levels')"
637 (if (or (and (eq this-command 'indent-for-tab-command)
638 (eq last-command this-command))
639 force-toggle)
640 (python-indent-toggle-levels)
641 (python-indent-calculate-levels))
642 (beginning-of-line)
643 (delete-horizontal-space)
644 (indent-to (nth python-indent-current-level python-indent-levels))
645 (save-restriction
646 (widen)
647 (let ((closing-block-point (python-info-closing-block)))
648 (when closing-block-point
649 (message "Closes %s" (buffer-substring
650 closing-block-point
651 (save-excursion
652 (goto-char closing-block-point)
653 (line-end-position))))))))
654
655(defun python-indent-line-function ()
656 "`indent-line-function' for Python mode.
657Internally just calls `python-indent-line'."
658 (python-indent-line))
659
660(defun python-indent-dedent-line ()
661 "Dedent current line."
662 (interactive "*")
663 (when (and (not (syntax-ppss-context (syntax-ppss)))
664 (<= (point-marker) (save-excursion
665 (back-to-indentation)
666 (point-marker)))
667 (> (current-column) 0))
668 (python-indent-line t)
669 t))
670
671(defun python-indent-dedent-line-backspace (arg)
672 "Dedent current line.
673Argument ARG is passed to `backward-delete-char-untabify' when
674point is not in between the indentation."
675 (interactive "*p")
676 (when (not (python-indent-dedent-line))
677 (backward-delete-char-untabify arg)))
183f9296 678(put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
45c138ac
FEG
679
680(defun python-indent-region (start end)
681 "Indent a python region automagically.
682
683Called from a program, START and END specify the region to indent."
684 (save-excursion
685 (goto-char end)
686 (setq end (point-marker))
687 (goto-char start)
688 (or (bolp) (forward-line 1))
689 (while (< (point) end)
690 (or (and (bolp) (eolp))
691 (let (word)
692 (forward-line -1)
693 (back-to-indentation)
694 (setq word (current-word))
695 (forward-line 1)
696 (when word
697 (beginning-of-line)
698 (delete-horizontal-space)
699 (indent-to (python-indent-calculate-indentation)))))
700 (forward-line 1))
701 (move-marker end nil)))
702
703(defun python-indent-shift-left (start end &optional count)
704 "Shift lines contained in region START END by COUNT columns to the left.
705
706COUNT defaults to `python-indent-offset'.
707
708If region isn't active, the current line is shifted.
709
710The shifted region includes the lines in which START and END lie.
711
712An error is signaled if any lines in the region are indented less
713than COUNT columns."
714 (interactive
715 (if mark-active
716 (list (region-beginning) (region-end) current-prefix-arg)
717 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
718 (if count
719 (setq count (prefix-numeric-value count))
720 (setq count python-indent-offset))
721 (when (> count 0)
722 (save-excursion
723 (goto-char start)
724 (while (< (point) end)
725 (if (and (< (current-indentation) count)
726 (not (looking-at "[ \t]*$")))
727 (error "Can't shift all lines enough"))
728 (forward-line))
729 (indent-rigidly start end (- count)))))
730
731(add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
732
733(defun python-indent-shift-right (start end &optional count)
734 "Shift lines contained in region START END by COUNT columns to the left.
735
736COUNT defaults to `python-indent-offset'.
737
738If region isn't active, the current line is shifted.
739
740The shifted region includes the lines in which START and END
741lie."
742 (interactive
743 (if mark-active
744 (list (region-beginning) (region-end) current-prefix-arg)
745 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
746 (if count
747 (setq count (prefix-numeric-value count))
748 (setq count python-indent-offset))
749 (indent-rigidly start end count))
750
751\f
752;;; Navigation
753
754(defvar python-beginning-of-defun-regexp
755 "^\\(def\\|class\\)[[:space:]]+[[:word:]]+"
756 "Regular expresion matching beginning of outermost class or function.")
757
758(defvar python-beginning-of-innermost-defun-regexp
759 "^[[:space:]]*\\(def\\|class\\)[[:space:]]+[[:word:]]+"
760 "Regular expresion matching beginning of innermost class or function.")
761
762(defun python-beginning-of-defun (&optional innermost)
763 "Move point to the beginning of innermost/outermost def or class.
764If INNERMOST is non-nil then move to the beginning of the
765innermost definition."
766 (let ((starting-point (point-marker))
767 (nonblank-line-indent)
768 (defun-indent)
769 (defun-point)
770 (regexp (if innermost
771 python-beginning-of-innermost-defun-regexp
772 python-beginning-of-defun-regexp)))
773 (back-to-indentation)
774 (if (and (not (looking-at "@"))
775 (not (looking-at regexp)))
776 (forward-comment -1)
777 (while (and (not (eobp))
778 (forward-line 1)
779 (not (back-to-indentation))
780 (looking-at "@"))))
781 (when (not (looking-at regexp))
782 (re-search-backward regexp nil t))
783 (setq nonblank-line-indent (+ (current-indentation) python-indent-offset))
784 (setq defun-indent (current-indentation))
785 (setq defun-point (point-marker))
786 (if (> nonblank-line-indent defun-indent)
787 (progn
788 (goto-char defun-point)
789 (forward-line -1)
790 (while (and (looking-at "@")
791 (forward-line -1)
792 (not (bobp))
793 (not (back-to-indentation))))
df700cc9
FEG
794 (unless (bobp)
795 (forward-line 1))
45c138ac
FEG
796 (point-marker))
797 (if innermost
798 (python-beginning-of-defun)
799 (goto-char starting-point)
800 nil))))
801
802(defun python-beginning-of-defun-function ()
803 "Move point to the beginning of outermost def or class.
804Returns nil if point is not in a def or class."
805 (python-beginning-of-defun nil))
806
807(defun python-beginning-of-innermost-defun ()
808 "Move point to the beginning of innermost def or class.
809Returns nil if point is not in a def or class."
810 (interactive)
811 (python-beginning-of-defun t))
812
813(defun python-end-of-defun-function ()
814 "Move point to the end of def or class.
815Returns nil if point is not in a def or class."
816 (let ((starting-point (point-marker))
817 (defun-regexp (python-rx defun))
818 (beg-defun-indent))
819 (back-to-indentation)
820 (if (looking-at "@")
821 (while (and (not (eobp))
822 (forward-line 1)
823 (not (back-to-indentation))
824 (looking-at "@")))
825 (while (and (not (bobp))
826 (not (progn (back-to-indentation) (current-word)))
827 (forward-line -1))))
828 (when (or (not (equal (current-indentation) 0))
829 (string-match defun-regexp (current-word)))
830 (setq beg-defun-indent (save-excursion
831 (or (looking-at defun-regexp)
832 (python-beginning-of-innermost-defun))
833 (current-indentation)))
834 (while (and (forward-line 1)
835 (not (eobp))
836 (or (not (current-word))
837 (> (current-indentation) beg-defun-indent))))
838 (while (and (forward-comment -1)
839 (not (bobp))))
840 (forward-line 1)
841 (point-marker))))
842
843\f
844;;; Shell integration
845
846(defvar python-shell-buffer-name "Python"
847 "Default buffer name for Python interpreter.")
848
849(defcustom python-shell-interpreter "python"
850 "Default Python interpreter for shell."
851 :group 'python
852 :type 'string
853 :safe 'stringp)
854
855(defcustom python-shell-interpreter-args "-i"
856 "Default arguments for the Python interpreter."
857 :group 'python
858 :type 'string
859 :safe 'stringp)
860
861(defcustom python-shell-prompt-regexp ">>> "
862 "Regex matching top\-level input prompt of python shell.
863The regex should not contain a caret (^) at the beginning."
864 :type 'string
865 :group 'python
866 :safe 'stringp)
867
868(defcustom python-shell-prompt-block-regexp "[.][.][.] "
869 "Regex matching block input prompt of python shell.
870The regex should not contain a caret (^) at the beginning."
871 :type 'string
872 :group 'python
873 :safe 'stringp)
874
875(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
876 "Regex matching pdb input prompt of python shell.
877The regex should not contain a caret (^) at the beginning."
878 :type 'string
879 :group 'python
880 :safe 'stringp)
881
882(defcustom python-shell-compilation-regexp-alist
883 `((,(rx line-start (1+ (any " \t")) "File \""
884 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
885 "\", line " (group (1+ digit)))
886 1 2)
887 (,(rx " in file " (group (1+ not-newline)) " on line "
888 (group (1+ digit)))
889 1 2)
890 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
891 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
892 1 2))
893 "`compilation-error-regexp-alist' for inferior Python."
894 :type '(alist string)
895 :group 'python)
896
897(defun python-shell-get-process-name (dedicated)
898 "Calculate the appropiate process name for inferior Python process.
899
900If DEDICATED is t and the variable `buffer-file-name' is non-nil
901returns a string with the form
902`python-shell-buffer-name'[variable `buffer-file-name'] else
903returns the value of `python-shell-buffer-name'.
904
905After calculating the process name add the buffer name for the
906process in the `same-window-buffer-names' list"
907 (let ((process-name
908 (if (and dedicated
909 buffer-file-name)
910 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
911 (format "%s" python-shell-buffer-name))))
912 (add-to-list 'same-window-buffer-names (purecopy
913 (format "*%s*" process-name)))
914 process-name))
915
916(defun python-shell-parse-command ()
917 "Calculates the string used to execute the inferior Python process."
918 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
919
920(defun python-comint-output-filter-function (output)
921 "Hook run after content is put into comint buffer.
922OUTPUT is a string with the contents of the buffer."
923 (ansi-color-filter-apply output))
924
925(defvar inferior-python-mode-current-file nil
926 "Current file from which a region was sent.")
927(make-variable-buffer-local 'inferior-python-mode-current-file)
928
929(defvar inferior-python-mode-current-temp-file nil
930 "Current temp file sent to process.")
931(make-variable-buffer-local 'inferior-python-mode-current-file)
932
933(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
934 "Major mode for Python inferior process."
935 (set-syntax-table python-mode-syntax-table)
936 (setq mode-line-process '(":%s"))
937 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
938 python-shell-prompt-regexp
939 python-shell-prompt-block-regexp
940 python-shell-prompt-pdb-regexp))
941 (make-local-variable 'comint-output-filter-functions)
942 (add-hook 'comint-output-filter-functions
943 'python-comint-output-filter-function)
944 (add-hook 'comint-output-filter-functions
945 'python-pdbtrack-comint-output-filter-function)
946 (set (make-local-variable 'compilation-error-regexp-alist)
947 python-shell-compilation-regexp-alist)
948 (compilation-shell-minor-mode 1))
949
950(defun run-python (dedicated cmd)
951 "Run an inferior Python process.
952
953Input and output via buffer *\\[python-shell-buffer-name]*.
954
955If there is a process already running in
956*\\[python-shell-buffer-name]*, switch to that buffer.
957
958With argument, allows you to:
959
960 * Define DEDICATED so a dedicated process for the current buffer
961 is open.
962
963 * Define CMD so you can edit the command used to call the
964interpreter (default is value of `python-shell-interpreter' and
965arguments defined in `python-shell-interpreter-args').
966
967Runs the hook `inferior-python-mode-hook' (after the
968`comint-mode-hook' is run).
969
970\(Type \\[describe-mode] in the process buffer for a list of
971commands.)"
972 (interactive
973 (if current-prefix-arg
974 (list
975 (y-or-n-p "Make dedicated process? ")
976 (read-string "Run Python: " (python-shell-parse-command)))
977 (list nil (python-shell-parse-command))))
978 (let* ((proc-name (python-shell-get-process-name dedicated))
979 (proc-buffer-name (format "*%s*" proc-name)))
980 (when (not (comint-check-proc proc-buffer-name))
981 (let ((cmdlist (split-string-and-unquote cmd)))
982 (set-buffer
983 (apply 'make-comint proc-name (car cmdlist) nil
984 (cdr cmdlist)))
985 (inferior-python-mode)))
986 (pop-to-buffer proc-buffer-name))
987 dedicated)
988
989(defun python-shell-get-process ()
990 "Get inferior Python process for current buffer and return it."
991 (let* ((dedicated-proc-name (python-shell-get-process-name t))
992 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
993 (global-proc-name (python-shell-get-process-name nil))
994 (global-proc-buffer-name (format "*%s*" global-proc-name))
995 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
996 (global-running (comint-check-proc global-proc-buffer-name)))
997 ;; Always prefer dedicated
998 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
999 (and global-running global-proc-buffer-name)))))
1000
1001(defun python-shell-get-or-create-process ()
1002 "Get or create an inferior Python process for current buffer and return it."
79dafa51
FEG
1003 (let* ((old-buffer (current-buffer))
1004 (dedicated-proc-name (python-shell-get-process-name t))
45c138ac
FEG
1005 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1006 (global-proc-name (python-shell-get-process-name nil))
1007 (global-proc-buffer-name (format "*%s*" global-proc-name))
1008 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1009 (global-running (comint-check-proc global-proc-buffer-name))
1010 (current-prefix-arg 4))
1011 (when (and (not dedicated-running) (not global-running))
1012 (if (call-interactively 'run-python)
1013 (setq dedicated-running t)
1014 (setq global-running t)))
1015 ;; Always prefer dedicated
79dafa51 1016 (switch-to-buffer old-buffer)
45c138ac
FEG
1017 (get-buffer-process (if dedicated-running
1018 dedicated-proc-buffer-name
1019 global-proc-buffer-name))))
1020
1021(defun python-shell-send-string (string)
1022 "Send STRING to inferior Python process."
1023 (interactive "sPython command: ")
1024 (let ((process (python-shell-get-or-create-process)))
1025 (message (format "Sent: %s..." string))
1026 (comint-send-string process string)
1027 (when (or (not (string-match "\n$" string))
1028 (string-match "\n[ \t].*\n?$" string))
1029 (comint-send-string process "\n"))))
1030
1031(defun python-shell-send-region (start end)
1032 "Send the region delimited by START and END to inferior Python process."
1033 (interactive "r")
1034 (let* ((contents (buffer-substring start end))
1035 (current-file (buffer-file-name))
1036 (process (python-shell-get-or-create-process))
66b0b492 1037 (temp-file (make-temp-file "py")))
45c138ac
FEG
1038 (with-temp-file temp-file
1039 (insert contents)
1040 (delete-trailing-whitespace)
1041 (goto-char (point-min))
1042 (message (format "Sent: %s..."
1043 (buffer-substring (point-min)
1044 (line-end-position)))))
1045 (with-current-buffer (process-buffer process)
1046 (setq inferior-python-mode-current-file current-file)
66b0b492
FEG
1047 (setq inferior-python-mode-current-temp-file temp-file))
1048 (python-shell-send-file temp-file process)))
45c138ac
FEG
1049
1050(defun python-shell-send-buffer ()
1051 "Send the entire buffer to inferior Python process."
1052 (interactive)
1053 (save-restriction
1054 (widen)
1055 (python-shell-send-region (point-min) (point-max))))
1056
1057(defun python-shell-send-defun (arg)
1058 "Send the (inner|outer)most def or class to inferior Python process.
1059When argument ARG is non-nil sends the innermost defun."
1060 (interactive "P")
1061 (save-excursion
1062 (python-shell-send-region (progn
1063 (or (if arg
1064 (python-beginning-of-innermost-defun)
1065 (python-beginning-of-defun-function))
1066 (progn (beginning-of-line) (point-marker))))
1067 (progn
1068 (or (python-end-of-defun-function)
1069 (progn (end-of-line) (point-marker)))))))
1070
66b0b492 1071(defun python-shell-send-file (file-name &optional process)
4e531f7a 1072 "Send FILE-NAME to inferior Python PROCESS."
45c138ac 1073 (interactive "fFile to send: ")
b962ebad
FEG
1074 (let ((process (or process (python-shell-get-or-create-process)))
1075 (full-file-name (expand-file-name file-name)))
66b0b492
FEG
1076 (accept-process-output process)
1077 (with-current-buffer (process-buffer process)
1078 (delete-region (save-excursion
1079 (move-to-column 0)
1080 (point-marker))
1081 (line-end-position)))
1082 (comint-send-string
1083 process
b962ebad
FEG
1084 (format
1085 "with open('%s') as __pyfile: exec(compile(__pyfile.read(), '%s', 'exec'))\n\n"
1086 full-file-name full-file-name))))
45c138ac
FEG
1087
1088(defun python-shell-switch-to-shell ()
1089 "Switch to inferior Python process buffer."
1090 (interactive)
1091 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1092
1093\f
1094;;; Shell completion
1095
1096(defvar python-shell-completion-setup-code
1097 "try:
1098 import readline
1099except ImportError:
1100 def __COMPLETER_all_completions(text): []
1101else:
1102 import rlcompleter
1103 readline.set_completer(rlcompleter.Completer().complete)
1104 def __COMPLETER_all_completions(text):
1105 import sys
1106 completions = []
1107 try:
1108 i = 0
1109 while True:
1110 res = readline.get_completer()(text, i)
1111 if not res: break
1112 i += 1
1113 completions.append(res)
1114 except NameError:
1115 pass
1116 return completions"
1117 "Code used to setup completion in inferior Python processes.")
1118
1119(defvar python-shell-completion-strings-code
1120 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1121 "Python code used to get a string of completions separated by semicolons.")
1122
1123(defun python-shell-completion-setup ()
1124 "Send `python-shell-completion-setup-code' to inferior Python process.
1125Also binds <tab> to `python-shell-complete-or-indent' in the
1126`inferior-python-mode-map' and adds
1127`python-shell-completion-complete-at-point' to the
1128`comint-dynamic-complete-functions' list.
1129It is specially designed to be added to the
1130`inferior-python-mode-hook'."
1131 (when python-shell-completion-setup-code
1132 (let ((temp-file (make-temp-file "py"))
1133 (process (get-buffer-process (current-buffer))))
1134 (with-temp-file temp-file
1135 (insert python-shell-completion-setup-code)
1136 (delete-trailing-whitespace)
1137 (goto-char (point-min)))
66b0b492 1138 (python-shell-send-file temp-file process)
45c138ac
FEG
1139 (message (format "Completion setup code sent.")))
1140 (add-to-list (make-local-variable
1141 'comint-dynamic-complete-functions)
1142 'python-shell-completion-complete-at-point)
1143 (define-key inferior-python-mode-map (kbd "<tab>")
1144 'python-shell-completion-complete-or-indent)))
1145
1146(defun python-shell-completion-complete-at-point ()
1147 "Perform completion at point in inferior Python process."
1148 (interactive)
1149 (when (and comint-last-prompt-overlay
1150 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1151 (let* ((process (get-buffer-process (current-buffer)))
1152 (input (comint-word (current-word)))
1153 (completions (when input
1154 (delete-region (point-marker)
1155 (progn
1156 (forward-char (- (length input)))
1157 (point-marker)))
1158 (process-send-string
1159 process
1160 (format
1161 python-shell-completion-strings-code input))
1162 (accept-process-output process)
1163 (save-excursion
1164 (re-search-backward comint-prompt-regexp
1165 comint-last-input-end t)
1166 (split-string
1167 (buffer-substring-no-properties
1168 (point-marker) comint-last-input-end)
1169 ";\\|\"\\|'\\|(" t))))
1170 (completion (when completions (try-completion input completions))))
1171 (when completions
1172 (save-excursion
1173 (forward-line -1)
1174 (kill-line 1)))
1175 (cond ((eq completion t)
1176 (when input (insert input)))
1177 ((null completion)
1178 (when input (insert input))
1179 (message "Can't find completion for \"%s\"" input)
1180 (ding))
1181 ((not (string= input completion))
1182 (insert completion))
1183 (t
1184 (message "Making completion list...")
1185 (when input (insert input))
1186 (with-output-to-temp-buffer "*Python Completions*"
1187 (display-completion-list
1188 (all-completions input completions))))))))
1189
45c138ac
FEG
1190(defun python-shell-completion-complete-or-indent ()
1191 "Complete or indent depending on the context.
1192If content before pointer is all whitespace indent. If not try to
1193complete."
1194 (interactive)
1195 (if (string-match "^[[:space:]]*$"
1196 (buffer-substring (comint-line-beginning-position)
1197 (point-marker)))
1198 (indent-for-tab-command)
1199 (comint-dynamic-complete)))
1200
1201(add-hook 'inferior-python-mode-hook
1202 #'python-shell-completion-setup)
1203
1204\f
1205;;; PDB Track integration
1206
1207(defvar python-pdbtrack-stacktrace-info-regexp
1208 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1209 "Regexp matching stacktrace information.
1210It is used to extract the current line and module beign
1211inspected.
1212The regexp should not start with a caret (^) and can contain a
1213string placeholder (\%s) which is replaced with the filename
1214beign inspected (so other files in the debugging process are not
1215opened)")
1216
1217(defvar python-pdbtrack-tracking-buffers '()
1218 "Alist containing elements of form (#<buffer> . #<buffer>).
1219The car of each element of the alist is the tracking buffer and
1220the cdr is the tracked buffer.")
1221
1222(defun python-pdbtrack-get-or-add-tracking-buffers ()
1223 "Get/Add a tracked buffer for the current buffer.
1224Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1225Returns a cons with the form:
1226 * (#<tracking buffer> . #< tracked buffer>)."
1227 (or
1228 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1229 (let* ((file (with-current-buffer (current-buffer)
1230 (or inferior-python-mode-current-file
1231 inferior-python-mode-current-temp-file)))
1232 (tracking-buffers
1233 `(,(current-buffer) .
1234 ,(or (get-file-buffer file)
1235 (find-file-noselect file)))))
1236 (set-buffer (cdr tracking-buffers))
1237 (python-mode)
1238 (set-buffer (car tracking-buffers))
1239 (setq python-pdbtrack-tracking-buffers
1240 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1241 tracking-buffers)))
1242
1243(defun python-pdbtrack-comint-output-filter-function (output)
1244 "Move overlay arrow to current pdb line in tracked buffer.
1245Argument OUTPUT is a string with the output from the comint process."
1246 (when (not (string= output ""))
1247 (let ((full-output (ansi-color-filter-apply
1248 (buffer-substring comint-last-input-end
1249 (point-max)))))
1250 (if (string-match python-shell-prompt-pdb-regexp full-output)
1251 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1252 (line-num
1253 (save-excursion
1254 (string-match
1255 (format python-pdbtrack-stacktrace-info-regexp
1256 (regexp-quote
1257 inferior-python-mode-current-temp-file))
1258 full-output)
1259 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1260 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1261 (tracked-buffer-line-pos))
1262 (when line-num
1263 (with-current-buffer (cdr tracking-buffers)
1264 (set (make-local-variable 'overlay-arrow-string) "=>")
1265 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1266 (setq tracked-buffer-line-pos (progn
1267 (goto-char (point-min))
1268 (forward-line (1- line-num))
1269 (point-marker)))
1270 (when tracked-buffer-window
1271 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1272 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1273 (pop-to-buffer (cdr tracking-buffers))
1274 (switch-to-buffer-other-window (car tracking-buffers)))
1275 (let ((tracking-buffers (assq (current-buffer)
1276 python-pdbtrack-tracking-buffers)))
1277 (when tracking-buffers
1278 (if inferior-python-mode-current-file
1279 (with-current-buffer (cdr tracking-buffers)
1280 (set-marker overlay-arrow-position nil))
1281 (kill-buffer (cdr tracking-buffers)))
1282 (setq python-pdbtrack-tracking-buffers
1283 (assq-delete-all (current-buffer)
1284 python-pdbtrack-tracking-buffers)))))))
1285 output)
1286
1287\f
1288;;; Symbol completion
1289
1290(defun python-completion-complete-at-point ()
1291 "Complete current symbol at point.
1292For this to work the best as possible you should call
1293`python-shell-send-buffer' from time to time so context in
1294inferior python process is updated properly."
1295 (interactive)
1296 (let ((process (python-shell-get-process)))
1297 (if (not process)
4e531f7a 1298 (error "Completion needs an inferior Python process running")
45c138ac
FEG
1299 (let* ((input (when (comint-word (current-word))
1300 (with-syntax-table python-dotty-syntax-table
1301 (buffer-substring (point-marker)
1302 (save-excursion
1303 (forward-word -1)
1304 (point-marker))))))
1305 (completions (when input
1306 (delete-region (point-marker)
1307 (progn
1308 (forward-char (- (length input)))
1309 (point-marker)))
1310 (process-send-string
1311 process
1312 (format
1313 python-shell-completion-strings-code input))
1314 (accept-process-output process)
1315 (with-current-buffer (process-buffer process)
1316 (save-excursion
1317 (re-search-backward comint-prompt-regexp
1318 comint-last-input-end t)
1319 (split-string
1320 (buffer-substring-no-properties
1321 (point-marker) comint-last-input-end)
1322 ";\\|\"\\|'\\|(" t)))))
1323 (completion (when completions
1324 (try-completion input completions))))
1325 (with-current-buffer (process-buffer process)
1326 (save-excursion
1327 (forward-line -1)
1328 (kill-line 1)))
1329 (when completions
1330 (cond ((eq completion t)
1331 (insert input))
1332 ((null completion)
1333 (insert input)
1334 (message "Can't find completion for \"%s\"" input)
1335 (ding))
1336 ((not (string= input completion))
1337 (insert completion))
1338 (t
1339 (message "Making completion list...")
1340 (insert input)
1341 (with-output-to-temp-buffer "*Python Completions*"
1342 (display-completion-list
1343 (all-completions input completions))))))))))
1344
1345(add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1346
1347\f
1348;;; Fill paragraph
1349
1350(defun python-fill-paragraph-function (&optional justify)
1351 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1352If any of the current line is in or at the end of a multi-line string,
1353fill the string or the paragraph of it that point is in, preserving
4e531f7a
FEG
1354the string's indentation.
1355Optional argument JUSTIFY defines if the paragraph should be justified."
45c138ac
FEG
1356 (interactive "P")
1357 (save-excursion
1358 (back-to-indentation)
1359 (cond
1360 ;; Comments
1361 ((fill-comment-paragraph justify))
1362 ;; Docstrings
1363 ((save-excursion (skip-chars-forward "\"'uUrR")
1364 (nth 3 (syntax-ppss)))
1365 (let ((marker (point-marker))
1366 (string-start-marker
1367 (progn
1368 (skip-chars-forward "\"'uUrR")
1369 (goto-char (nth 8 (syntax-ppss)))
1370 (skip-chars-forward "\"'uUrR")
1371 (point-marker)))
1372 (reg-start (line-beginning-position))
1373 (string-end-marker
1374 (progn
1375 (while (nth 3 (syntax-ppss)) (goto-char (1+ (point-marker))))
1376 (skip-chars-backward "\"'")
1377 (point-marker)))
1378 (reg-end (line-end-position))
1379 (fill-paragraph-function))
1380 (save-restriction
1381 (narrow-to-region reg-start reg-end)
1382 (save-excursion
1383 (goto-char string-start-marker)
1384 (delete-region (point-marker) (progn
1385 (skip-syntax-forward "> ")
1386 (point-marker)))
1387 (goto-char string-end-marker)
1388 (delete-region (point-marker) (progn
1389 (skip-syntax-backward "> ")
1390 (point-marker)))
1391 (save-excursion
1392 (goto-char marker)
1393 (fill-paragraph justify))
1394 ;; If there is a newline in the docstring lets put triple
1395 ;; quote in it's own line to follow pep 8
1396 (when (save-excursion
1397 (re-search-backward "\n" string-start-marker t))
1398 (newline)
1399 (newline-and-indent))
1400 (fill-paragraph justify)))) t)
1401 ;; Decorators
1402 ((equal (char-after (save-excursion
1403 (back-to-indentation)
1404 (point-marker))) ?@) t)
1405 ;; Parens
1406 ((or (> (nth 0 (syntax-ppss)) 0)
1407 (looking-at (python-rx open-paren))
1408 (save-excursion
1409 (skip-syntax-forward "^(" (line-end-position))
1410 (looking-at (python-rx open-paren))))
1411 (save-restriction
1412 (narrow-to-region (progn
1413 (while (> (nth 0 (syntax-ppss)) 0)
1414 (goto-char (1- (point-marker))))
1415 (point-marker)
1416 (line-beginning-position))
1417 (progn
1418 (when (not (> (nth 0 (syntax-ppss)) 0))
1419 (end-of-line)
1420 (when (not (> (nth 0 (syntax-ppss)) 0))
1421 (skip-syntax-backward "^)")))
1422 (while (> (nth 0 (syntax-ppss)) 0)
1423 (goto-char (1+ (point-marker))))
1424 (point-marker)))
1425 (let ((paragraph-start "\f\\|[ \t]*$")
1426 (paragraph-separate ",")
1427 (fill-paragraph-function))
1428 (goto-char (point-min))
1429 (fill-paragraph justify))
1430 (while (not (eobp))
1431 (forward-line 1)
1432 (python-indent-line)
1433 (goto-char (line-end-position)))) t)
1434 (t t))))
1435
1436\f
1437;;; Eldoc
1438
1439(defvar python-eldoc-setup-code
1440 "def __PYDOC_get_help(obj):
1441 try:
1442 import pydoc
1443 obj = eval(obj, globals())
1444 return pydoc.getdoc(obj)
1445 except:
1446 return ''"
1447 "Python code to setup documentation retrieval.")
1448
1449(defvar python-eldoc-string-code
1450 "print __PYDOC_get_help('''%s''')\n"
1451 "Python code used to get a string with the documentation of an object.")
1452
1453(defun python-eldoc-setup ()
1454 "Send `python-eldoc-setup-code' to inferior Python process.
1455It is specially designed to be added to the
1456`inferior-python-mode-hook'."
1457 (when python-eldoc-setup-code
1458 (let ((temp-file (make-temp-file "py")))
1459 (with-temp-file temp-file
1460 (insert python-eldoc-setup-code)
1461 (delete-trailing-whitespace)
1462 (goto-char (point-min)))
66b0b492 1463 (python-shell-send-file temp-file (get-buffer-process (current-buffer)))
45c138ac
FEG
1464 (message (format "Completion setup code sent.")))))
1465
1466(defun python-eldoc-function ()
1467 "`eldoc-documentation-function' for Python.
1468For this to work the best as possible you should call
1469`python-shell-send-buffer' from time to time so context in
1470inferior python process is updated properly."
1471 (interactive)
1472 (let ((process (python-shell-get-process)))
1473 (if (not process)
1474 "Eldoc needs an inferior Python process running."
1475 (let* ((current-defun (python-info-current-defun))
1476 (input (with-syntax-table python-dotty-syntax-table
1477 (if (not current-defun)
1478 (current-word)
1479 (concat current-defun "." (current-word)))))
1480 (ppss (syntax-ppss))
1481 (help (when (and input
1482 (not (string= input (concat current-defun ".")))
1483 (eq nil (nth 3 ppss))
1484 (eq nil (nth 4 ppss)))
1485 (when (string-match (concat
1486 (regexp-quote (concat current-defun "."))
1487 "self\\.") input)
1488 (with-temp-buffer
1489 (insert input)
1490 (goto-char (point-min))
1491 (forward-word)
1492 (forward-char)
1493 (delete-region (point-marker) (search-forward "self."))
1494 (setq input (buffer-substring (point-min) (point-max)))))
1495 (process-send-string
1496 process (format python-eldoc-string-code input))
1497 (accept-process-output process)
1498 (with-current-buffer (process-buffer process)
1499 (when comint-last-prompt-overlay
1500 (save-excursion
1501 (goto-char comint-last-input-end)
1502 (re-search-forward comint-prompt-regexp
1503 (line-end-position) t)
1504 (buffer-substring-no-properties
1505 (point-marker)
1506 (overlay-start comint-last-prompt-overlay))))))))
1507 (with-current-buffer (process-buffer process)
1508 (when comint-last-prompt-overlay
1509 (delete-region comint-last-input-end
1510 (overlay-start comint-last-prompt-overlay))))
1511 (when (and help
1512 (not (string= help "\n")))
1513 help)))))
1514
1515(add-hook 'inferior-python-mode-hook
1516 #'python-eldoc-setup)
1517
1518\f
1519;;; Misc helpers
1520
1521(defun python-info-current-defun ()
1522 "Return name of surrounding function with Python compatible dotty syntax.
1523This function is compatible to be used as
1524`add-log-current-defun-function' since it returns nil if point is
1525not inside a defun."
1526 (let ((names '()))
1527 (save-restriction
1528 (widen)
1529 (save-excursion
1530 (beginning-of-line)
1531 (when (not (>= (current-indentation) python-indent-offset))
1532 (while (and (not (eobp)) (forward-comment 1))))
1533 (while (and (not (equal 0 (current-indentation)))
1534 (python-beginning-of-innermost-defun))
1535 (back-to-indentation)
1536 (looking-at "\\(?:def\\|class\\) +\\([^(]+\\)[^:]+:\\s-*\n")
1537 (setq names (cons (match-string-no-properties 1) names)))))
1538 (when names
1539 (mapconcat (lambda (string) string) names "."))))
1540
1541(defun python-info-closing-block ()
1542 "Return the point of the block that the current line closes."
1543 (let ((closing-word (save-excursion
1544 (back-to-indentation)
1545 (current-word)))
1546 (indentation (current-indentation)))
1547 (when (member closing-word python-indent-dedenters)
1548 (save-excursion
1549 (forward-line -1)
1550 (while (and (> (current-indentation) indentation)
1551 (not (bobp))
1552 (not (back-to-indentation))
1553 (forward-line -1)))
1554 (back-to-indentation)
1555 (cond
1556 ((not (equal indentation (current-indentation))) nil)
1557 ((string= closing-word "elif")
1558 (when (member (current-word) '("if" "elif"))
1559 (point-marker)))
1560 ((string= closing-word "else")
1561 (when (member (current-word) '("if" "elif" "except" "for" "while"))
1562 (point-marker)))
1563 ((string= closing-word "except")
1564 (when (member (current-word) '("try"))
1565 (point-marker)))
1566 ((string= closing-word "finally")
1567 (when (member (current-word) '("except" "else"))
1568 (point-marker))))))))
1569
1570(defun python-info-line-ends-backslash-p ()
1571 "Return non-nil if current line ends with backslash."
1572 (string= (or (ignore-errors
1573 (buffer-substring
1574 (line-end-position)
1575 (- (line-end-position) 1))) "") "\\"))
1576
1577(defun python-info-continuation-line-p ()
1578 "Return non-nil if current line is continuation of another."
1579 (or (python-info-line-ends-backslash-p)
1580 (string-match ",[[:space:]]*$" (buffer-substring
1581 (line-beginning-position)
1582 (line-end-position)))
1583 (save-excursion
1584 (let ((innermost-paren (progn
1585 (goto-char (line-end-position))
1586 (nth 1 (syntax-ppss)))))
1587 (when (and innermost-paren
1588 (and (<= (line-beginning-position) innermost-paren)
1589 (>= (line-end-position) innermost-paren)))
1590 (goto-char innermost-paren)
1591 (looking-at (python-rx open-paren (* space) line-end)))))
1592 (save-excursion
1593 (back-to-indentation)
1594 (nth 1 (syntax-ppss)))))
1595
1596(defun python-info-block-continuation-line-p ()
1597 "Return non-nil if current line is a continuation of a block."
1598 (save-excursion
1599 (while (and (not (bobp))
1600 (python-info-continuation-line-p))
1601 (forward-line -1))
1602 (forward-line 1)
1603 (back-to-indentation)
1604 (when (looking-at (python-rx block-start))
1605 (point-marker))))
1606
1607(defun python-info-assignment-continuation-line-p ()
1608 "Return non-nil if current line is a continuation of an assignment."
1609 (save-excursion
1610 (while (and (not (bobp))
1611 (python-info-continuation-line-p))
1612 (forward-line -1))
1613 (forward-line 1)
1614 (back-to-indentation)
1615 (when (and (not (looking-at (python-rx block-start)))
1616 (save-excursion
1617 (and (re-search-forward (python-rx not-simple-operator
1618 assignment-operator
1619 not-simple-operator)
1620 (line-end-position) t)
1621 (not (syntax-ppss-context (syntax-ppss))))))
1622 (point-marker))))
1623
1624\f
1625;;;###autoload
1626(define-derived-mode python-mode fundamental-mode "Python"
1627 "A major mode for editing Python files."
1628 (set (make-local-variable 'tab-width) 8)
1629 (set (make-local-variable 'indent-tabs-mode) nil)
1630
1631 (set (make-local-variable 'comment-start) "# ")
1632 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
1633
1634 (set (make-local-variable 'parse-sexp-lookup-properties) t)
1635 (set (make-local-variable 'parse-sexp-ignore-comments) t)
1636
1637 (set (make-local-variable 'font-lock-defaults)
1638 '(python-font-lock-keywords
1639 nil nil nil nil
1640 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
1641
1642 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
1643 (set (make-local-variable 'indent-region-function) #'python-indent-region)
1644
1645 (set (make-local-variable 'paragraph-start) "\\s-*$")
1646 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
1647
1648 (set (make-local-variable 'beginning-of-defun-function)
1649 #'python-beginning-of-defun-function)
1650 (set (make-local-variable 'end-of-defun-function)
1651 #'python-end-of-defun-function)
1652
1653 (add-hook 'completion-at-point-functions
1654 'python-completion-complete-at-point nil 'local)
1655
1656 (set (make-local-variable 'add-log-current-defun-function)
1657 #'python-info-current-defun)
1658
1659 (set (make-local-variable 'eldoc-documentation-function)
1660 #'python-eldoc-function)
1661
1662 (add-to-list 'hs-special-modes-alist
1663 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
1664 ,(lambda (arg)
1665 (python-end-of-defun-function)) nil))
1666
1667 (set (make-local-variable 'outline-regexp)
1668 (python-rx (* space) block-start))
1669 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
1670 (set (make-local-variable 'outline-level)
1671 #'(lambda ()
1672 "`outline-level' function for Python mode."
1673 (1+ (/ (current-indentation) python-indent-offset))))
1674
1675 (when python-indent-guess-indent-offset
1676 (python-indent-guess-indent-offset)))
1677
1678
1679(provide 'python)
1680;;; python.el ends here