1 ;;; python.el -- Python's flying circus support for Emacs
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
10 ;; This file is NOT part of GNU Emacs.
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.
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.
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/>.
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.
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 :)
35 ;; Implements Syntax highlighting, Indentation, Movement, Shell
36 ;; interaction, Shell completion, Pdb tracking, Symbol completion,
39 ;; Syntax highlighting: Fontification of code is provided and supports
40 ;; python's triple quoted strings properly.
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. Also when inserting a
45 ;; colon the `python-indent-electric-colon' command is invoked and
46 ;; causes the current line to be dedented automatically if needed.
48 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
49 ;; properly implemented. A `beginning-of-innermost-defun' is defined
50 ;; to navigate nested defuns.
52 ;; Shell interaction: is provided and allows you easily execute any
53 ;; block of code of your current buffer in an inferior Python process.
55 ;; Shell completion: hitting tab will try to complete the current
56 ;; word. Shell completion is implemented in a manner that if you
57 ;; change the `python-shell-interpreter' to any other (for example
58 ;; IPython) it should be easy to integrate another way to calculate
59 ;; completions. You just need to specify your custom
60 ;; `python-shell-completion-setup-code' and
61 ;; `python-shell-completion-string-code'
63 ;; Here is a complete example of the settings you would use for
67 ;; python-shell-interpreter "ipython"
68 ;; python-shell-interpreter-args ""
69 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
70 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
71 ;; python-shell-completion-setup-code ""
72 ;; python-shell-completion-string-code
73 ;; "';'.join(__IP.complete('''%s'''))\n")
75 ;; Please note that the default completion system depends on the
76 ;; readline module, so if you are using some Operating System that
77 ;; bundles Python without it (like Windows) just install the
78 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
79 ;; you should be good to go.
81 ;; Pdb tracking: when you execute a block of code that contains some
82 ;; call to pdb (or ipdb) it will prompt the block of code and will
83 ;; follow the execution of pdb marking the current line with an arrow.
85 ;; Symbol completion: you can complete the symbol at point. It uses
86 ;; the shell completion in background so you should run
87 ;; `python-shell-send-buffer' from time to time to get better results.
89 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
90 ;; def, for, if, try and while. These skeletons are integrated with
91 ;; dabbrev. If you have `dabbrev-mode' activated and
92 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
93 ;; the name of any of those defined and hit SPC, they will be
94 ;; automatically expanded.
96 ;; FFAP: You can find the filename for a given module when using ffap
97 ;; out of the box. This feature needs an inferior python shell
100 ;; Code check: Check the current file for errors using
101 ;; `python-check-command'
103 ;; Eldoc: returns documentation for object at point by using the
104 ;; inferior python subprocess to inspect its documentation. As you
105 ;; might guessed you should run `python-shell-send-buffer' from time
106 ;; to time to get better results too.
108 ;; If you used python-mode.el you probably will miss auto-indentation
109 ;; when inserting newlines. To achieve the same behavior you have
112 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
114 ;; 2) Add the following hook in your .emacs:
116 ;; (add-hook 'python-mode-hook
118 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
120 ;; I'd recommend the first one since you'll get the same behavior for
121 ;; all modes out-of-the-box.
125 ;; Add this to your .emacs:
127 ;; (add-to-list 'load-path "/folder/containing/file")
132 ;; Ordered by priority:
134 ;; Better decorator support for beginning of defun
136 ;; Review code and cleanup
140 (require 'ansi-color
)
145 ;; Avoid compiler warnings
146 (defvar view-return-to-alist
)
147 (defvar compilation-error-regexp-alist
)
148 (defvar outline-heading-end-regexp
))
150 (autoload 'comint-mode
"comint")
153 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
155 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
158 "Python Language's flying circus support for Emacs."
161 :link
'(emacs-commentary-link "python"))
166 (defvar python-mode-map
167 (let ((map (make-sparse-keymap)))
169 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
170 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
171 (define-key map
"\C-c<" 'python-indent-shift-left
)
172 (define-key map
"\C-c>" 'python-indent-shift-right
)
173 (define-key map
":" 'python-indent-electric-colon
)
175 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
176 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
177 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
178 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
179 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
180 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
182 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
183 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
184 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
185 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
186 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
187 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
188 ;; Some util commands
189 (define-key map
"\C-c\C-v" 'python-check
)
190 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
192 (substitute-key-definition 'complete-symbol
'completion-at-point
194 (easy-menu-define python-menu map
"Python Mode menu"
196 :help
"Python-specific Features"
197 ["Shift region left" python-indent-shift-left
:active mark-active
198 :help
"Shift region left by a single indentation step"]
199 ["Shift region right" python-indent-shift-right
:active mark-active
200 :help
"Shift region right by a single indentation step"]
202 ["Mark def/class" mark-defun
203 :help
"Mark outermost definition around point"]
205 ["Start of def/class" beginning-of-defun
206 :help
"Go to start of outermost definition around point"]
207 ["Start of def/class" python-beginning-of-innermost-defun
208 :help
"Go to start of innermost definition around point"]
209 ["End of def/class" end-of-defun
210 :help
"Go to end of definition around point"]
214 ["Start interpreter" run-python
215 :help
"Run inferior Python process in a separate buffer"]
216 ["Switch to shell" python-shell-switch-to-shell
217 :help
"Switch to running inferior Python process"]
218 ["Eval string" python-shell-send-string
219 :help
"Eval string in inferior Python session"]
220 ["Eval buffer" python-shell-send-buffer
221 :help
"Eval buffer in inferior Python session"]
222 ["Eval region" python-shell-send-region
223 :help
"Eval region in inferior Python session"]
224 ["Eval defun" python-shell-send-defun
225 :help
"Eval defun in inferior Python session"]
226 ["Eval file" python-shell-send-file
227 :help
"Eval file in inferior Python session"]
228 ["Debugger" pdb
:help
"Run pdb under GUD"]
230 ["Check file" python-check
231 :help
"Check file for errors"]
232 ["Help on symbol" python-eldoc-at-point
233 :help
"Get help on symbol at point"]
234 ["Complete symbol" completion-at-point
235 :help
"Complete symbol before point"]))
237 "Keymap for `python-mode'.")
240 ;;; Python specialized rx
243 (defconst python-rx-constituents
245 `(block-start .
,(rx symbol-start
246 (or "def" "class" "if" "elif" "else" "try"
247 "except" "finally" "for" "while" "with")
249 `(defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
250 `(open-paren .
,(rx (or "{" "[" "(")))
251 `(close-paren .
,(rx (or "}" "]" ")")))
252 `(simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
253 `(not-simple-operator .
,(rx (not (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
254 `(operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
255 "=" "%" "**" "//" "<<" ">>" "<=" "!="
256 "==" ">=" "is" "not")))
257 `(assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
258 ">>=" "<<=" "&=" "^=" "|="))))))
260 (defmacro python-rx
(&rest regexps
)
261 "Python mode especialized rx macro which supports common python named REGEXPS."
262 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
263 (cond ((null regexps
)
266 (rx-to-string `(and ,@regexps
) t
))
268 (rx-to-string (car regexps
) t
)))))
271 ;;; Font-lock and syntax
273 (defvar python-font-lock-keywords
276 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
277 "assert" "else" "if" "pass" "yield" "break" "except" "import"
278 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
279 "return" "def" "for" "lambda" "try" "self")
282 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
283 (1 font-lock-function-name-face
))
285 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
286 (1 font-lock-type-face
))
288 (,(rx symbol-start
(group "None" symbol-end
))
289 (1 font-lock-constant-face
))
291 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
292 (0+ "." (1+ (or word ?_
)))))
293 (1 font-lock-type-face
))
294 ;; Builtin Exceptions
296 (or "ArithmeticError" "AssertionError" "AttributeError"
297 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
298 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
299 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
300 "ImportWarning" "IndentationError" "IndexError" "KeyError"
301 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
302 "NotImplemented" "NotImplementedError" "OSError" "OverflowError"
303 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
304 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
305 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
306 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
307 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
308 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
309 symbol-end
) . font-lock-type-face
)
311 (,(rx (or line-start
(not (any ". \t"))) (* (any " \t")) symbol-start
313 (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
314 "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer"
315 "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce"
316 "compile" "complex" "copyright" "credits" "delattr" "dict" "dir"
317 "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter"
318 "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash"
319 "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
320 "iter" "len" "license" "list" "locals" "long" "map" "max" "min"
321 "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit"
322 "range" "raw_input" "reduce" "reload" "repr" "reversed" "round"
323 "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum"
324 "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip"
325 "True" "False" "Ellipsis")) symbol-end
)
326 (1 font-lock-builtin-face
))
328 ;; support for a = b = c = 5
330 (let ((re (python-rx (group (+ (any word ?. ?_
)))
331 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
332 assignment-operator
)))
333 (when (re-search-forward re limit t
)
334 (while (and (python-info-ppss-context 'paren
)
335 (re-search-forward re limit t
)))
336 (if (and (not (python-info-ppss-context 'paren
))
337 (not (equal (char-after (point-marker)) ?
=)))
339 (set-match-data nil
)))))
340 (1 font-lock-variable-name-face nil nil
))
341 ;; support for a, b, c = (1, 2, 3)
343 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
344 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
345 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
346 assignment-operator
)))
347 (when (and (re-search-forward re limit t
)
348 (goto-char (nth 3 (match-data))))
349 (while (and (python-info-ppss-context 'paren
)
350 (re-search-forward re limit t
))
351 (goto-char (nth 3 (match-data))))
352 (if (not (python-info-ppss-context 'paren
))
354 (set-match-data nil
)))))
355 (1 font-lock-variable-name-face nil nil
))))
357 ;; Fixme: Is there a better way?
358 (defconst python-font-lock-syntactic-keywords
359 ;; First avoid a sequence preceded by an odd number of backslashes.
360 `((,(rx (not (any ?
\\))
361 ?
\\ (* (and ?
\\ ?
\\))
362 (group (syntax string-quote
))
365 (2 ,(string-to-syntax "\""))) ; dummy
366 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
367 (optional (any "rR")) ; possible second prefix
368 (group (syntax string-quote
)) ; maybe gets property
369 (backref 2) ; per first quote
370 (group (backref 2))) ; maybe gets property
371 (1 (python-quote-syntax 1))
372 (2 (python-quote-syntax 2))
373 (3 (python-quote-syntax 3))))
374 "Make outer chars of triple-quote strings into generic string delimiters.")
376 (defun python-quote-syntax (n)
377 "Put `syntax-table' property correctly on triple quote.
378 Used for syntactic keywords. N is the match number (1, 2 or 3)."
379 ;; Given a triple quote, we have to check the context to know
380 ;; whether this is an opening or closing triple or whether it's
381 ;; quoted anyhow, and should be ignored. (For that we need to do
382 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
383 ;; to use it here despite initial worries.) We also have to sort
384 ;; out a possible prefix -- well, we don't _have_ to, but I think it
385 ;; should be treated as part of the string.
388 ;; ur"""ar""" x='"' # """
391 ;; x '"""' x """ \"""" x
393 (goto-char (match-beginning 0))
395 ;; Consider property for the last char if in a fenced string.
397 (let* ((font-lock-syntactic-keywords nil
)
398 (syntax (syntax-ppss)))
399 (when (eq t
(nth 3 syntax
)) ; after unclosed fence
400 (goto-char (nth 8 syntax
)) ; fence position
401 (skip-chars-forward "uUrR") ; skip any prefix
402 ;; Is it a matching sequence?
403 (if (eq (char-after) (char-after (match-beginning 2)))
404 (eval-when-compile (string-to-syntax "|"))))))
405 ;; Consider property for initial char, accounting for prefixes.
406 ((or (and (= n
2) ; leading quote (not prefix)
407 (= (match-beginning 1) (match-end 1))) ; prefix is null
408 (and (= n
1) ; prefix
409 (/= (match-beginning 1) (match-end 1)))) ; non-empty
410 (let ((font-lock-syntactic-keywords nil
))
411 (unless (eq 'string
(syntax-ppss-context (syntax-ppss)))
412 (eval-when-compile (string-to-syntax "|")))))
413 ;; Otherwise (we're in a non-matching string) the property is
417 (defvar python-mode-syntax-table
418 (let ((table (make-syntax-table)))
419 ;; Give punctuation syntax to ASCII that normally has symbol
420 ;; syntax or has word syntax and isn't a letter.
421 (let ((symbol (string-to-syntax "_"))
422 (sst (standard-syntax-table)))
425 (if (equal symbol
(aref sst i
))
426 (modify-syntax-entry i
"." table
)))))
427 (modify-syntax-entry ?$
"." table
)
428 (modify-syntax-entry ?%
"." table
)
430 (modify-syntax-entry ?
# "<" table
)
431 (modify-syntax-entry ?
\n ">" table
)
432 (modify-syntax-entry ?
' "\"" table
)
433 (modify-syntax-entry ?
` "$" table
)
435 "Syntax table for Python files.")
437 (defvar python-dotty-syntax-table
438 (let ((table (make-syntax-table python-mode-syntax-table
)))
439 (modify-syntax-entry ?.
"w" table
)
440 (modify-syntax-entry ?_
"w" table
)
442 "Dotty syntax table for Python files.
443 It makes underscores and dots word constituent chars.")
448 (defcustom python-indent-offset
4
449 "Default indentation offset for Python."
454 (defcustom python-indent-guess-indent-offset t
455 "Non-nil tells Python mode to guess `python-indent-offset' value."
459 (defvar python-indent-current-level
0
460 "Current indentation level `python-indent-line-function' is using.")
462 (defvar python-indent-levels
'(0)
463 "Levels of indentation available for `python-indent-line-function'.")
465 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
466 "List of words that should be dedented.
467 These make `python-indent-calculate-indentation' subtract the value of
468 `python-indent-offset'.")
470 (defun python-indent-guess-indent-offset ()
471 "Guess and set `python-indent-offset' for the current buffer."
475 (goto-char (point-min))
477 (while (and (not found-block
)
479 (python-rx line-start block-start
) nil t
))
480 (when (and (not (python-info-ppss-context 'string
))
481 (not (python-info-ppss-context 'comment
))
483 (goto-char (line-end-position))
485 (eq ?
: (char-before))))
486 (setq found-block t
)))
487 (if (not found-block
)
488 (message "Can't guess python-indent-offset, using defaults: %s"
489 python-indent-offset
)
491 (goto-char (line-end-position))
492 (python-info-continuation-line-p))
497 (let ((indent-offset (current-indentation)))
498 (when (> indent-offset
0)
499 (setq python-indent-offset indent-offset
))))))))
501 (defun python-indent-context (&optional stop
)
502 "Return information on indentation context.
503 Optional argument STOP serves to stop recursive calls.
505 Returns a cons with the form:
509 Where status can be any of the following symbols:
511 * inside-paren: If point in between (), {} or []
512 * inside-string: If point is inside a string
513 * after-backslash: Previous line ends in a backslash
514 * after-beginning-of-block: Point is after beginning of block
515 * after-line: Point is after normal line
516 * no-indent: Point is at beginning of buffer or other special case
518 START is the buffer position where the sexp starts."
521 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
525 ;; Beginning of buffer
527 (goto-char (line-beginning-position))
531 ((setq start
(python-info-ppss-context 'paren ppss
))
534 ((setq start
(python-info-ppss-context 'string ppss
))
537 ((setq start
(when (not (or (python-info-ppss-context 'string ppss
)
538 (python-info-ppss-context 'comment ppss
)))
539 (let ((line-beg-pos (line-beginning-position)))
540 (when (eq ?
\\ (char-before (1- line-beg-pos
)))
541 (- line-beg-pos
2)))))
543 ;; After beginning of block
544 ((setq start
(save-excursion
545 (let ((block-regexp (python-rx block-start
))
546 (block-start-line-end ":[[:space:]]*$"))
547 (back-to-indentation)
548 (while (and (forward-comment -
1) (not (bobp))))
549 (back-to-indentation)
550 (when (or (python-info-continuation-line-p)
551 (and (not (looking-at block-regexp
))
555 (line-end-position) t
))))
556 (while (and (forward-line -
1)
557 (python-info-continuation-line-p)
559 (when (not (looking-at block-regexp
))
561 (back-to-indentation)
562 (when (and (looking-at block-regexp
)
563 (or (re-search-forward
565 (line-end-position) t
)
566 (python-info-continuation-line-p)))
568 'after-beginning-of-block
)
570 ((setq start
(save-excursion
571 (while (and (forward-comment -
1) (not (bobp))))
572 (while (and (not (back-to-indentation))
574 (if (python-info-ppss-context 'paren
)
578 (python-info-line-ends-backslash-p))
579 (forward-line -
1)))))
586 (defun python-indent-calculate-indentation ()
587 "Calculate correct indentation offset for the current line."
588 (let* ((indentation-context (python-indent-context))
589 (context-status (car indentation-context
))
590 (context-start (cdr indentation-context
)))
596 ('after-beginning-of-block
597 (goto-char context-start
)
598 (+ (current-indentation) python-indent-offset
))
602 (goto-char context-start
)
603 (current-indentation))
605 (back-to-indentation)
606 (looking-at (regexp-opt python-indent-dedenters
)))
610 (goto-char context-start
)
611 (current-indentation))
613 (let* ((block-continuation
616 (python-info-block-continuation-line-p)))
617 (assignment-continuation
620 (python-info-assignment-continuation-line-p)))
623 (back-to-indentation)
624 (when (looking-at "\\.")
626 (back-to-indentation)
627 (forward-char (length
628 (with-syntax-table python-dotty-syntax-table
630 (re-search-backward "\\." (line-beginning-position) t
1)
632 (indentation (cond (block-continuation
633 (goto-char block-continuation
)
635 (python-rx block-start
(* space
))
636 (line-end-position) t
)
638 (assignment-continuation
639 (goto-char assignment-continuation
)
641 (python-rx simple-operator
)
642 (line-end-position) t
)
645 (python-rx (* space
))
646 (line-end-position) t
)
651 (goto-char context-start
)
652 (current-indentation)))))
657 (looking-at (regexp-opt '(")" "]" "}")))
659 (when (not (python-info-ppss-context 'paren
))
660 (goto-char context-start
)
661 (back-to-indentation)
665 (goto-char context-start
)
669 (line-beginning-position)
673 (+ (current-indentation) python-indent-offset
)
677 (back-to-indentation)
678 (looking-at (regexp-opt '(")" "]" "}"))))
682 (defun python-indent-calculate-levels ()
683 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
684 (let* ((indentation (python-indent-calculate-indentation))
685 (remainder (% indentation python-indent-offset
))
686 (steps (/ (- indentation remainder
) python-indent-offset
)))
687 (setq python-indent-levels
'())
688 (setq python-indent-levels
(cons 0 python-indent-levels
))
689 (dotimes (step steps
)
690 (setq python-indent-levels
691 (cons (* python-indent-offset
(1+ step
)) python-indent-levels
)))
692 (when (not (eq 0 remainder
))
693 (setq python-indent-levels
694 (cons (+ (* python-indent-offset steps
) remainder
)
695 python-indent-levels
)))
696 (setq python-indent-levels
(nreverse python-indent-levels
))
697 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
699 (defun python-indent-toggle-levels ()
700 "Toggle `python-indent-current-level' over `python-indent-levels'."
701 (setq python-indent-current-level
(1- python-indent-current-level
))
702 (when (< python-indent-current-level
0)
703 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
705 (defun python-indent-line (&optional force-toggle
)
706 "Internal implementation of `python-indent-line-function'.
708 Uses the offset calculated in
709 `python-indent-calculate-indentation' and available levels
710 indicated by the variable `python-indent-levels'.
712 When the variable `last-command' is equal to
713 `indent-for-tab-command' or FORCE-TOGGLE is non-nil:
715 * Cycles levels indicated in the variable `python-indent-levels'
716 by setting the current level in the variable
717 `python-indent-current-level'.
719 When the variable `last-command' is not equal to
720 `indent-for-tab-command' and FORCE-TOGGLE is nil:
722 * calculates possible indentation levels and saves it in the
723 variable `python-indent-levels'.
725 * sets the variable `python-indent-current-level' correctly so
726 offset is equal to (`nth' `python-indent-current-level'
727 `python-indent-levels')"
728 (if (or (and (eq this-command
'indent-for-tab-command
)
729 (eq last-command this-command
))
731 (python-indent-toggle-levels)
732 (python-indent-calculate-levels))
734 (delete-horizontal-space)
735 (indent-to (nth python-indent-current-level python-indent-levels
))
738 (let ((closing-block-point (python-info-closing-block)))
739 (when closing-block-point
740 (message "Closes %s" (buffer-substring
743 (goto-char closing-block-point
)
744 (line-end-position))))))))
746 (defun python-indent-line-function ()
747 "`indent-line-function' for Python mode.
748 Internally just calls `python-indent-line'."
749 (python-indent-line))
751 (defun python-indent-dedent-line ()
752 "Dedent current line."
754 (when (and (not (or (python-info-ppss-context 'string
)
755 (python-info-ppss-context 'comment
)))
756 (<= (point-marker) (save-excursion
757 (back-to-indentation)
759 (> (current-column) 0))
760 (python-indent-line t
)
763 (defun python-indent-dedent-line-backspace (arg)
764 "Dedent current line.
765 Argument ARG is passed to `backward-delete-char-untabify' when
766 point is not in between the indentation."
768 (when (not (python-indent-dedent-line))
769 (backward-delete-char-untabify arg
)))
770 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
772 (defun python-indent-region (start end
)
773 "Indent a python region automagically.
775 Called from a program, START and END specify the region to indent."
776 (let ((deactivate-mark nil
))
779 (setq end
(point-marker))
781 (or (bolp) (forward-line 1))
782 (while (< (point) end
)
783 (or (and (bolp) (eolp))
786 (back-to-indentation)
787 (setq word
(current-word))
791 (delete-horizontal-space)
792 (indent-to (python-indent-calculate-indentation)))))
794 (move-marker end nil
))))
796 (defun python-indent-shift-left (start end
&optional count
)
797 "Shift lines contained in region START END by COUNT columns to the left.
799 COUNT defaults to `python-indent-offset'.
801 If region isn't active, the current line is shifted.
803 The shifted region includes the lines in which START and END lie.
805 An error is signaled if any lines in the region are indented less
809 (list (region-beginning) (region-end) current-prefix-arg
)
810 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
812 (setq count
(prefix-numeric-value count
))
813 (setq count python-indent-offset
))
815 (let ((deactivate-mark nil
))
818 (while (< (point) end
)
819 (if (and (< (current-indentation) count
)
820 (not (looking-at "[ \t]*$")))
821 (error "Can't shift all lines enough"))
823 (indent-rigidly start end
(- count
))))))
825 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
827 (defun python-indent-shift-right (start end
&optional count
)
828 "Shift lines contained in region START END by COUNT columns to the left.
830 COUNT defaults to `python-indent-offset'.
832 If region isn't active, the current line is shifted.
834 The shifted region includes the lines in which START and END
838 (list (region-beginning) (region-end) current-prefix-arg
)
839 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
840 (let ((deactivate-mark nil
))
842 (setq count
(prefix-numeric-value count
))
843 (setq count python-indent-offset
))
844 (indent-rigidly start end count
)))
846 (defun python-indent-electric-colon (arg)
847 "Insert a colon and maybe outdent the line if it is a statement like `else'.
848 With numeric ARG, just insert that many colons. With \\[universal-argument],
849 just insert a single colon."
851 (self-insert-command (if (not (integerp arg
)) 1 arg
))
854 (not (equal ?
: (char-after (- (point-marker) 2))))
855 (not (or (python-info-ppss-context 'string
)
856 (python-info-ppss-context 'comment
))))
857 (let ((indentation (current-indentation))
858 (calculated-indentation (python-indent-calculate-indentation)))
859 (when (> indentation calculated-indentation
)
861 (indent-line-to calculated-indentation
)
862 (when (not (python-info-closing-block))
863 (indent-line-to indentation
)))))))
864 (put 'python-indent-electric-colon
'delete-selection t
)
869 (defvar python-beginning-of-defun-regexp
870 "^\\(def\\|class\\)[[:space:]]+[[:word:]]+"
871 "Regular expresion matching beginning of outermost class or function.")
873 (defvar python-beginning-of-innermost-defun-regexp
874 "^[[:space:]]*\\(def\\|class\\)[[:space:]]+[[:word:]]+"
875 "Regular expresion matching beginning of innermost class or function.")
877 (defun python-beginning-of-defun (&optional innermost
)
878 "Move point to the beginning of innermost/outermost def or class.
879 If INNERMOST is non-nil then move to the beginning of the
880 innermost definition."
881 (let ((starting-point (point-marker))
882 (nonblank-line-indent)
885 (regexp (if innermost
886 python-beginning-of-innermost-defun-regexp
887 python-beginning-of-defun-regexp
)))
888 (back-to-indentation)
889 (if (and (not (looking-at "@"))
890 (not (looking-at regexp
)))
892 (while (and (not (eobp))
894 (not (back-to-indentation))
896 (when (not (looking-at regexp
))
897 (re-search-backward regexp nil t
))
898 (setq nonblank-line-indent
(+ (current-indentation) python-indent-offset
))
899 (setq defun-indent
(current-indentation))
900 (setq defun-point
(point-marker))
901 (if (> nonblank-line-indent defun-indent
)
903 (goto-char defun-point
)
905 (while (and (looking-at "@")
908 (not (back-to-indentation))))
913 (python-beginning-of-defun)
914 (goto-char starting-point
)
917 (defun python-beginning-of-defun-function ()
918 "Move point to the beginning of outermost def or class.
919 Returns nil if point is not in a def or class."
920 (python-beginning-of-defun nil))
922 (defun python-beginning-of-innermost-defun ()
923 "Move point to the beginning of innermost def or class.
924 Returns nil if point is not in a def or class."
926 (python-beginning-of-defun t))
928 (defun python-end-of-defun-function ()
929 "Move point to the end of def or class.
930 Returns nil if point is not in a def or class."
931 (let ((starting-point (point-marker))
932 (defun-regexp (python-rx defun
))
934 (back-to-indentation)
936 (while (and (not (eobp))
938 (not (back-to-indentation))
940 (while (and (not (bobp))
941 (not (progn (back-to-indentation) (current-word)))
943 (when (or (not (equal (current-indentation) 0))
944 (string-match defun-regexp
(current-word)))
945 (setq beg-defun-indent
(save-excursion
946 (or (looking-at defun-regexp
)
947 (python-beginning-of-innermost-defun))
948 (current-indentation)))
949 (while (and (forward-line 1)
951 (or (not (current-word))
952 (> (current-indentation) beg-defun-indent
))))
953 (while (and (forward-comment -
1)
959 ;;; Shell integration
961 (defvar python-shell-buffer-name
"Python"
962 "Default buffer name for Python interpreter.")
964 (defcustom python-shell-interpreter
"python"
965 "Default Python interpreter for shell."
970 (defcustom python-shell-interpreter-args
"-i"
971 "Default arguments for the Python interpreter."
976 (defcustom python-shell-prompt-regexp
">>> "
977 "Regex matching top\-level input prompt of python shell.
978 The regex should not contain a caret (^) at the beginning."
983 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
984 "Regex matching block input prompt of python shell.
985 The regex should not contain a caret (^) at the beginning."
990 (defcustom python-shell-prompt-output-regexp nil
991 "Regex matching output prompt of python shell.
992 The regex should not contain a caret (^) at the beginning."
997 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
998 "Regex matching pdb input prompt of python shell.
999 The regex should not contain a caret (^) at the beginning."
1004 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1005 python-ffap-setup-code
1006 python-eldoc-setup-code
)
1007 "List of code run by `python-shell-send-setup-codes'.
1008 Each variable can be either a simple string with the code to
1009 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1010 is a string with the code to execute and DESCRIPTION is the
1012 :type
'(repeat symbol
)
1016 (defcustom python-shell-compilation-regexp-alist
1017 `((,(rx line-start
(1+ (any " \t")) "File \""
1018 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1019 "\", line " (group (1+ digit
)))
1021 (,(rx " in file " (group (1+ not-newline
)) " on line "
1024 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1025 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1027 "`compilation-error-regexp-alist' for inferior Python."
1028 :type
'(alist string
)
1031 (defun python-shell-get-process-name (dedicated)
1032 "Calculate the appropiate process name for inferior Python process.
1034 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1035 returns a string with the form
1036 `python-shell-buffer-name'[variable `buffer-file-name'] else
1037 returns the value of `python-shell-buffer-name'.
1039 After calculating the process name add the buffer name for the
1040 process in the `same-window-buffer-names' list"
1044 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1045 (format "%s" python-shell-buffer-name
))))
1046 (add-to-list 'same-window-buffer-names
(purecopy
1047 (format "*%s*" process-name
)))
1050 (defun python-shell-parse-command ()
1051 "Calculates the string used to execute the inferior Python process."
1052 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1054 (defun python-comint-output-filter-function (output)
1055 "Hook run after content is put into comint buffer.
1056 OUTPUT is a string with the contents of the buffer."
1057 (ansi-color-filter-apply output
))
1059 (defvar inferior-python-mode-current-file nil
1060 "Current file from which a region was sent.")
1061 (make-variable-buffer-local 'inferior-python-mode-current-file
)
1063 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1064 "Major mode for Python inferior process.
1065 Adds `python-shell-completion-complete-at-point' to the
1066 `comint-dynamic-complete-functions' list. Also binds <tab> to
1067 `python-shell-complete-or-indent' in the
1068 `inferior-python-mode-map'."
1069 (set-syntax-table python-mode-syntax-table
)
1070 (setq mode-line-process
'(":%s"))
1071 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1072 python-shell-prompt-regexp
1073 python-shell-prompt-block-regexp
1074 python-shell-prompt-pdb-regexp
))
1075 (make-local-variable 'comint-output-filter-functions
)
1076 (add-hook 'comint-output-filter-functions
1077 'python-comint-output-filter-function
)
1078 (add-hook 'comint-output-filter-functions
1079 'python-pdbtrack-comint-output-filter-function
)
1080 (set (make-local-variable 'compilation-error-regexp-alist
)
1081 python-shell-compilation-regexp-alist
)
1082 (define-key inferior-python-mode-map
[remap complete-symbol
]
1083 'completion-at-point
)
1084 (add-hook 'completion-at-point-functions
1085 'python-shell-completion-complete-at-point nil
'local
)
1086 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1087 'python-shell-completion-complete-at-point
)
1088 (define-key inferior-python-mode-map
(kbd "<tab>")
1089 'python-shell-completion-complete-or-indent
)
1090 (compilation-shell-minor-mode 1))
1092 (defun run-python (dedicated cmd
)
1093 "Run an inferior Python process.
1095 Input and output via buffer *\\[python-shell-buffer-name]*.
1097 If there is a process already running in
1098 *\\[python-shell-buffer-name]*, switch to that buffer.
1100 With argument, allows you to:
1102 * Define DEDICATED so a dedicated process for the current buffer
1105 * Define CMD so you can edit the command used to call the
1106 interpreter (default is value of `python-shell-interpreter' and
1107 arguments defined in `python-shell-interpreter-args').
1109 Runs the hook `inferior-python-mode-hook' (after the
1110 `comint-mode-hook' is run).
1112 \(Type \\[describe-mode] in the process buffer for a list of
1115 (if current-prefix-arg
1117 (y-or-n-p "Make dedicated process? ")
1118 (read-string "Run Python: " (python-shell-parse-command)))
1119 (list nil
(python-shell-parse-command))))
1120 (let* ((proc-name (python-shell-get-process-name dedicated
))
1121 (proc-buffer-name (format "*%s*" proc-name
)))
1122 (when (not (comint-check-proc proc-buffer-name
))
1123 (let ((cmdlist (split-string-and-unquote cmd
)))
1125 (apply 'make-comint proc-name
(car cmdlist
) nil
1127 (inferior-python-mode)))
1128 (pop-to-buffer proc-buffer-name
))
1131 (defun python-shell-get-process ()
1132 "Get inferior Python process for current buffer and return it."
1133 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1134 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1135 (global-proc-name (python-shell-get-process-name nil
))
1136 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1137 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1138 (global-running (comint-check-proc global-proc-buffer-name
)))
1139 ;; Always prefer dedicated
1140 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1141 (and global-running global-proc-buffer-name
)))))
1143 (defun python-shell-get-or-create-process ()
1144 "Get or create an inferior Python process for current buffer and return it."
1145 (let* ((old-buffer (current-buffer))
1146 (dedicated-proc-name (python-shell-get-process-name t
))
1147 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1148 (global-proc-name (python-shell-get-process-name nil
))
1149 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1150 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1151 (global-running (comint-check-proc global-proc-buffer-name
))
1152 (current-prefix-arg 4))
1153 (when (and (not dedicated-running
) (not global-running
))
1154 (if (call-interactively 'run-python
)
1155 (setq dedicated-running t
)
1156 (setq global-running t
)))
1157 ;; Always prefer dedicated
1158 (switch-to-buffer old-buffer
)
1159 (get-buffer-process (if dedicated-running
1160 dedicated-proc-buffer-name
1161 global-proc-buffer-name
))))
1163 (defun python-shell-send-string (string &optional process msg
)
1164 "Send STRING to inferior Python PROCESS.
1165 When MSG is non-nil messages the first line of STRING."
1166 (interactive "sPython command: ")
1167 (let ((process (or process
(python-shell-get-or-create-process)))
1168 (lines (split-string string
"\n" t
)))
1170 (message (format "Sent: %s..." (nth 0 lines
))))
1171 (if (> (length lines
) 1)
1172 (let* ((temp-file-name (make-temp-file "py"))
1173 (file-name (or (buffer-file-name) temp-file-name
)))
1174 (with-temp-file temp-file-name
1176 (delete-trailing-whitespace))
1177 (python-shell-send-file file-name process temp-file-name
))
1178 (comint-send-string process string
)
1179 (when (or (not (string-match "\n$" string
))
1180 (string-match "\n[ \t].*\n?$" string
))
1181 (comint-send-string process
"\n")))))
1183 (defun python-shell-send-string-no-output (string &optional process msg
)
1184 "Send STRING to PROCESS and inhibit output.
1185 When MSG is non-nil messages the first line of STRING.
1187 (let* ((output-buffer)
1188 (process (or process
(python-shell-get-or-create-process)))
1189 (comint-preoutput-filter-functions
1190 (append comint-preoutput-filter-functions
1191 '(ansi-color-filter-apply
1193 (setq output-buffer
(concat output-buffer string
))
1195 (python-shell-send-string string process msg
)
1196 (accept-process-output process
)
1197 ;; Cleanup output prompt regexp
1198 (when (and (not (string= "" output-buffer
))
1199 (> (length python-shell-prompt-output-regexp
) 0))
1202 (insert output-buffer
)
1203 (goto-char (point-min))
1205 (buffer-substring-no-properties
1207 (and (looking-at python-shell-prompt-output-regexp
)
1209 python-shell-prompt-output-regexp nil t
1))
1213 (lambda (string) string
)
1214 (butlast (split-string output-buffer
"\n")) "\n")))
1216 (defun python-shell-send-region (start end
)
1217 "Send the region delimited by START and END to inferior Python process."
1219 (let ((deactivate-mark nil
))
1220 (python-shell-send-string (buffer-substring start end
) nil t
)))
1222 (defun python-shell-send-buffer ()
1223 "Send the entire buffer to inferior Python process."
1227 (python-shell-send-region (point-min) (point-max))))
1229 (defun python-shell-send-defun (arg)
1230 "Send the (inner|outer)most def or class to inferior Python process.
1231 When argument ARG is non-nil sends the innermost defun."
1234 (python-shell-send-region (progn
1236 (python-beginning-of-innermost-defun)
1237 (python-beginning-of-defun-function))
1238 (progn (beginning-of-line) (point-marker))))
1240 (or (python-end-of-defun-function)
1241 (progn (end-of-line) (point-marker)))))))
1243 (defun python-shell-send-file (file-name &optional process temp-file-name
)
1244 "Send FILE-NAME to inferior Python PROCESS.
1245 If TEMP-FILE-NAME is passed then that file is used for processing
1246 instead, while internally the shell will continue to use
1248 (interactive "fFile to send: ")
1249 (let* ((process (or process
(python-shell-get-or-create-process)))
1250 (temp-file-name (when temp-file-name
1251 (expand-file-name temp-file-name
)))
1252 (file-name (or (expand-file-name file-name
) temp-file-name
)))
1253 (when (not file-name
)
1254 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1255 (with-current-buffer (process-buffer process
)
1256 (setq inferior-python-mode-current-file
1257 (convert-standard-filename file-name
)))
1258 (python-shell-send-string
1260 (concat "__pyfile = open('''%s''');"
1261 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1263 (or temp-file-name file-name
) file-name
)
1266 (defun python-shell-switch-to-shell ()
1267 "Switch to inferior Python process buffer."
1269 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
1271 (defun python-shell-send-setup-code ()
1272 "Send all setup code for shell.
1273 This function takes the list of setup code to send from the
1274 `python-shell-setup-codes' list."
1275 (let ((msg "Sent %s")
1276 (process (get-buffer-process (current-buffer))))
1277 (accept-process-output process
1)
1278 (dolist (code python-shell-setup-codes
)
1281 (setq msg
(cdr code
)))
1282 (message (format msg code
))
1283 (python-shell-send-string-no-output
1284 (symbol-value code
) process
)))))
1286 (add-hook 'inferior-python-mode-hook
1287 #'python-shell-send-setup-code
)
1290 ;;; Shell completion
1292 (defvar python-shell-completion-setup-code
1296 def __COMPLETER_all_completions(text): []
1299 readline.set_completer(rlcompleter.Completer().complete)
1300 def __COMPLETER_all_completions(text):
1306 res = readline.get_completer()(text, i)
1309 completions.append(res)
1313 "Code used to setup completion in inferior Python processes.")
1315 (defvar python-shell-completion-string-code
1316 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1317 "Python code used to get a string of completions separated by semicolons.")
1319 (defun python-shell-completion--get-completions (input process
)
1320 "Retrieve available completions for INPUT using PROCESS."
1321 (with-current-buffer (process-buffer process
)
1322 (let ((completions (python-shell-send-string-no-output
1323 (format python-shell-completion-string-code input
)
1325 (when (> (length completions
) 2)
1326 (split-string completions
"^'\\|^\"\\|;\\|'$\\|\"$" t
)))))
1328 (defun python-shell-completion--get-completion (input completions
)
1329 "Get completion for INPUT using COMPLETIONS."
1330 (let ((completion (when completions
1331 (try-completion input completions
))))
1332 (cond ((eq completion t
)
1335 (message "Can't find completion for \"%s\"" input
)
1338 ((not (string= input completion
))
1341 (message "Making completion list...")
1342 (with-output-to-temp-buffer "*Python Completions*"
1343 (display-completion-list
1344 (all-completions input completions
)))
1347 (defun python-shell-completion-complete-at-point ()
1348 "Perform completion at point in inferior Python process."
1350 (with-syntax-table python-dotty-syntax-table
1351 (when (and comint-last-prompt-overlay
1352 (> (point-marker) (overlay-end comint-last-prompt-overlay
)))
1353 (let* ((process (get-buffer-process (current-buffer)))
1354 (input (substring-no-properties
1355 (or (comint-word (current-word)) "") nil nil
)))
1356 (delete-char (- (length input
)))
1358 (python-shell-completion--get-completion
1359 input
(python-shell-completion--get-completions input process
)))))))
1361 (defun python-shell-completion-complete-or-indent ()
1362 "Complete or indent depending on the context.
1363 If content before pointer is all whitespace indent. If not try to
1366 (if (string-match "^[[:space:]]*$"
1367 (buffer-substring (comint-line-beginning-position)
1369 (indent-for-tab-command)
1370 (comint-dynamic-complete)))
1373 ;;; PDB Track integration
1375 (defvar python-pdbtrack-stacktrace-info-regexp
1376 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1377 "Regexp matching stacktrace information.
1378 It is used to extract the current line and module beign
1380 The regexp should not start with a caret (^) and can contain a
1381 string placeholder (\%s) which is replaced with the filename
1382 beign inspected (so other files in the debugging process are not
1385 (defvar python-pdbtrack-tracking-buffers
'()
1386 "Alist containing elements of form (#<buffer> . #<buffer>).
1387 The car of each element of the alist is the tracking buffer and
1388 the cdr is the tracked buffer.")
1390 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1391 "Get/Add a tracked buffer for the current buffer.
1392 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1393 Returns a cons with the form:
1394 * (#<tracking buffer> . #< tracked buffer>)."
1396 (assq (current-buffer) python-pdbtrack-tracking-buffers
)
1397 (let* ((file (with-current-buffer (current-buffer)
1398 inferior-python-mode-current-file
))
1400 `(,(current-buffer) .
1401 ,(or (get-file-buffer file
)
1402 (find-file-noselect file
)))))
1403 (set-buffer (cdr tracking-buffers
))
1405 (set-buffer (car tracking-buffers
))
1406 (setq python-pdbtrack-tracking-buffers
1407 (cons tracking-buffers python-pdbtrack-tracking-buffers
))
1410 (defun python-pdbtrack-comint-output-filter-function (output)
1411 "Move overlay arrow to current pdb line in tracked buffer.
1412 Argument OUTPUT is a string with the output from the comint process."
1413 (when (not (string= output
""))
1414 (let ((full-output (ansi-color-filter-apply
1415 (buffer-substring comint-last-input-end
1417 (if (string-match python-shell-prompt-pdb-regexp full-output
)
1418 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1422 (format python-pdbtrack-stacktrace-info-regexp
1424 inferior-python-mode-current-file
))
1426 (string-to-number (or (match-string-no-properties 1 full-output
) ""))))
1427 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers
)))
1428 (tracked-buffer-line-pos))
1430 (with-current-buffer (cdr tracking-buffers
)
1431 (set (make-local-variable 'overlay-arrow-string
) "=>")
1432 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
1433 (setq tracked-buffer-line-pos
(progn
1434 (goto-char (point-min))
1435 (forward-line (1- line-num
))
1437 (when tracked-buffer-window
1438 (set-window-point tracked-buffer-window tracked-buffer-line-pos
))
1439 (set-marker overlay-arrow-position tracked-buffer-line-pos
)))
1440 (pop-to-buffer (cdr tracking-buffers
))
1441 (switch-to-buffer-other-window (car tracking-buffers
)))
1442 (let ((tracking-buffers (assq (current-buffer)
1443 python-pdbtrack-tracking-buffers
)))
1444 (when tracking-buffers
1445 (if inferior-python-mode-current-file
1446 (with-current-buffer (cdr tracking-buffers
)
1447 (set-marker overlay-arrow-position nil
))
1448 (kill-buffer (cdr tracking-buffers
)))
1449 (setq python-pdbtrack-tracking-buffers
1450 (assq-delete-all (current-buffer)
1451 python-pdbtrack-tracking-buffers
)))))))
1455 ;;; Symbol completion
1457 (defun python-completion-complete-at-point ()
1458 "Complete current symbol at point.
1459 For this to work the best as possible you should call
1460 `python-shell-send-buffer' from time to time so context in
1461 inferior python process is updated properly."
1463 (let ((process (python-shell-get-process)))
1465 (error "Completion needs an inferior Python process running")
1466 (with-syntax-table python-dotty-syntax-table
1467 (let* ((input (substring-no-properties
1468 (or (comint-word (current-word)) "") nil nil
))
1469 (completions (python-shell-completion--get-completions
1471 (delete-char (- (length input
)))
1473 (python-shell-completion--get-completion
1474 input completions
)))))))
1476 (add-to-list 'debug-ignored-errors
"^Completion needs an inferior Python process running.")
1481 (defun python-fill-paragraph-function (&optional justify
)
1482 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1483 If any of the current line is in or at the end of a multi-line string,
1484 fill the string or the paragraph of it that point is in, preserving
1485 the string's indentation.
1486 Optional argument JUSTIFY defines if the paragraph should be justified."
1489 (back-to-indentation)
1492 ((fill-comment-paragraph justify
))
1494 ((save-excursion (skip-chars-forward "\"'uUrR")
1495 (python-info-ppss-context 'string
))
1496 (let ((marker (point-marker))
1497 (string-start-marker
1499 (skip-chars-forward "\"'uUrR")
1500 (goto-char (python-info-ppss-context 'string
))
1501 (skip-chars-forward "\"'uUrR")
1503 (reg-start (line-beginning-position))
1506 (while (python-info-ppss-context 'string
)
1507 (goto-char (1+ (point-marker))))
1508 (skip-chars-backward "\"'")
1510 (reg-end (line-end-position))
1511 (fill-paragraph-function))
1513 (narrow-to-region reg-start reg-end
)
1515 (goto-char string-start-marker
)
1516 (delete-region (point-marker) (progn
1517 (skip-syntax-forward "> ")
1519 (goto-char string-end-marker
)
1520 (delete-region (point-marker) (progn
1521 (skip-syntax-backward "> ")
1525 (fill-paragraph justify
))
1526 ;; If there is a newline in the docstring lets put triple
1527 ;; quote in it's own line to follow pep 8
1528 (when (save-excursion
1529 (re-search-backward "\n" string-start-marker t
))
1531 (newline-and-indent))
1532 (fill-paragraph justify
)))) t
)
1534 ((equal (char-after (save-excursion
1535 (back-to-indentation)
1536 (point-marker))) ?
@) t
)
1538 ((or (python-info-ppss-context 'paren
)
1539 (looking-at (python-rx open-paren
))
1541 (skip-syntax-forward "^(" (line-end-position))
1542 (looking-at (python-rx open-paren
))))
1544 (narrow-to-region (progn
1545 (while (python-info-ppss-context 'paren
)
1546 (goto-char (1- (point-marker))))
1548 (line-beginning-position))
1550 (when (not (python-info-ppss-context 'paren
))
1552 (when (not (python-info-ppss-context 'paren
))
1553 (skip-syntax-backward "^)")))
1554 (while (python-info-ppss-context 'paren
)
1555 (goto-char (1+ (point-marker))))
1557 (let ((paragraph-start "\f\\|[ \t]*$")
1558 (paragraph-separate ",")
1559 (fill-paragraph-function))
1560 (goto-char (point-min))
1561 (fill-paragraph justify
))
1564 (python-indent-line)
1565 (goto-char (line-end-position)))) t
)
1571 (defcustom python-skeleton-autoinsert nil
1572 "Non-nil means template skeletons will be automagically inserted.
1573 This happens when pressing \"if<SPACE>\", for example, to prompt for
1578 (defvar python-skeleton-available
'()
1579 "Internal list of available skeletons.")
1580 (make-variable-buffer-local 'inferior-python-mode-current-file
)
1582 (define-abbrev-table 'python-mode-abbrev-table
()
1583 "Abbrev table for Python mode."
1585 ;; Allow / inside abbrevs.
1586 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1587 ;; Only expand in code.
1588 :enable-function
(lambda ()
1590 (not (or (python-info-ppss-context 'string
)
1591 (python-info-ppss-context 'comment
)))
1592 python-skeleton-autoinsert
)))
1594 (defmacro python-skeleton-define
(name doc
&rest skel
)
1595 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1596 The skeleton will be bound to python-skeleton-NAME and will
1597 be added to `python-mode-abbrev-table'."
1598 (let* ((name (symbol-name name
))
1599 (function-name (intern (concat "python-skeleton-" name
))))
1601 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
)
1602 (setq python-skeleton-available
1603 (cons ',function-name python-skeleton-available
))
1604 (define-skeleton ,function-name
1606 (format "Insert %s statement." name
))
1608 (put 'python-skeleton-define
'lisp-indent-function
2)
1610 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
1611 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1612 The skeleton will be bound to python-skeleton-NAME."
1613 (let* ((name (symbol-name name
))
1614 (function-name (intern (concat "python-skeleton--" name
)))
1616 "Add '%s' clause? " name
)))
1619 `(< ,(format "%s:" name
) \n \n
1621 `(define-skeleton ,function-name
1623 (format "Auxiliary skeleton for %s statement." name
))
1625 (unless (y-or-n-p ,msg
)
1628 (put 'python-define-auxiliary-skeleton
'lisp-indent-function
2)
1630 (python-define-auxiliary-skeleton else nil
)
1632 (python-define-auxiliary-skeleton except nil
)
1634 (python-define-auxiliary-skeleton finally nil
)
1636 (python-skeleton-define if nil
1640 ("other condition, %s: "
1644 '(python-skeleton--else) | ^
)
1646 (python-skeleton-define while nil
1650 '(python-skeleton--else) | ^
)
1652 (python-skeleton-define for nil
1656 '(python-skeleton--else) | ^
)
1658 (python-skeleton-define try nil
1664 "except " str
":" \n
1667 '(python-skeleton--except)
1668 '(python-skeleton--else)
1669 '(python-skeleton--finally) | ^
)
1671 (python-skeleton-define def nil
1673 "def " str
" (" ("Parameter, %s: "
1674 (unless (equal ?\
( (char-before)) ", ")
1676 "\"\"\"" -
"\"\"\"" \n
1679 (python-skeleton-define class nil
1681 "class " str
" (" ("Inheritance, %s: "
1682 (unless (equal ?\
( (char-before)) ", ")
1686 "\"\"\"" -
"\"\"\"" \n
1689 (defun python-skeleton-add-menu-items ()
1690 "Add menu items to Python->Skeletons menu."
1691 (let ((skeletons (sort python-skeleton-available
'string
<))
1693 (dolist (skeleton skeletons
)
1695 nil
'("Python" "Skeletons")
1697 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
1702 (defvar python-ffap-setup-code
1703 "def __FFAP_get_module_path(module):
1706 path = __import__(module).__file__
1707 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1712 "Python code to get a module path.")
1714 (defvar python-ffap-string-code
1715 "__FFAP_get_module_path('''%s''')\n"
1716 "Python code used to get a string with the path of a module.")
1718 (defun python-ffap-module-path (module)
1719 "Function for `ffap-alist' to return path for MODULE."
1721 (and (eq major-mode
'inferior-python-mode
)
1722 (get-buffer-process (current-buffer)))
1723 (python-shell-get-process))))
1727 (python-shell-send-string-no-output
1728 (format python-ffap-string-code module
) process
)))
1730 (substring-no-properties module-file
1 -
1))))))
1732 (eval-after-load "ffap"
1734 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
1735 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
1740 (defvar python-check-command
1741 "pychecker --stdlib"
1742 "Command used to check a Python file.")
1744 (defvar python-check-custom-command nil
1747 (defun python-check (command)
1748 "Check a Python file (default current buffer's file).
1749 Runs COMMAND, a shell command, as if by `compile'. See
1750 `python-check-command' for the default."
1752 (list (read-string "Check command: "
1753 (or python-check-custom-command
1754 (concat python-check-command
" "
1755 (shell-quote-argument
1757 (let ((name (buffer-file-name)))
1759 (file-name-nondirectory name
)))
1761 (setq python-check-custom-command command
)
1762 (save-some-buffers (not compilation-ask-about-save
) nil
)
1763 (compilation-start command
))
1768 (defvar python-eldoc-setup-code
1769 "def __PYDOC_get_help(obj):
1772 if hasattr(obj, 'startswith'):
1773 obj = eval(obj, globals())
1774 doc = pydoc.getdoc(obj)
1781 "Python code to setup documentation retrieval.")
1783 (defvar python-eldoc-string-code
1784 "__PYDOC_get_help('''%s''')\n"
1785 "Python code used to get a string with the documentation of an object.")
1787 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
1788 "Internal implementation to get documentation at point.
1789 If not FORCE-INPUT is passed then what `current-word' returns
1790 will be used. If not FORCE-PROCESS is passed what
1791 `python-shell-get-process' returns is used."
1792 (let ((process (or force-process
(python-shell-get-process))))
1794 "Eldoc needs an inferior Python process running."
1795 (let* ((current-defun (python-info-current-defun))
1796 (input (or force-input
1797 (with-syntax-table python-dotty-syntax-table
1798 (if (not current-defun
)
1800 (concat current-defun
"." (current-word))))))
1801 (ppss (syntax-ppss))
1802 (help (when (and input
1803 (not (string= input
(concat current-defun
".")))
1804 (not (or (python-info-ppss-context 'string ppss
)
1805 (python-info-ppss-context 'comment ppss
))))
1806 (when (string-match (concat
1807 (regexp-quote (concat current-defun
"."))
1811 (goto-char (point-min))
1814 (delete-region (point-marker) (search-forward "self."))
1815 (setq input
(buffer-substring (point-min) (point-max)))))
1816 (python-shell-send-string-no-output
1817 (format python-eldoc-string-code input
) process
))))
1818 (with-current-buffer (process-buffer process
)
1819 (when comint-last-prompt-overlay
1820 (delete-region comint-last-input-end
1821 (overlay-start comint-last-prompt-overlay
))))
1823 (not (string= help
"\n")))
1826 (defun python-eldoc-function ()
1827 "`eldoc-documentation-function' for Python.
1828 For this to work the best as possible you should call
1829 `python-shell-send-buffer' from time to time so context in
1830 inferior python process is updated properly."
1831 (python-eldoc--get-doc-at-point))
1833 (defun python-eldoc-at-point (symbol)
1834 "Get help on SYMBOL using `help'.
1835 Interactively, prompt for symbol."
1837 (let ((symbol (with-syntax-table python-dotty-syntax-table
1839 (enable-recursive-minibuffers t
))
1840 (list (read-string (if symbol
1841 (format "Describe symbol (default %s): " symbol
)
1842 "Describe symbol: ")
1844 (let ((process (python-shell-get-process)))
1846 (message "Eldoc needs an inferior Python process running.")
1847 (let ((temp-buffer-show-hook
1849 (toggle-read-only 1)
1850 (setq view-return-to-alist
1851 (list (cons (selected-window) help-return-method
))))))
1852 (with-output-to-temp-buffer (help-buffer)
1853 (with-current-buffer standard-output
1855 (python-eldoc--get-doc-at-point symbol process
))
1856 (help-print-return-message)))))))
1861 (defun python-info-current-defun ()
1862 "Return name of surrounding function with Python compatible dotty syntax.
1863 This function is compatible to be used as
1864 `add-log-current-defun-function' since it returns nil if point is
1865 not inside a defun."
1871 (when (not (>= (current-indentation) python-indent-offset
))
1872 (while (and (not (eobp)) (forward-comment 1))))
1873 (while (and (not (equal 0 (current-indentation)))
1874 (python-beginning-of-innermost-defun))
1875 (back-to-indentation)
1876 (looking-at "\\(?:def\\|class\\) +\\([^(]+\\)[^:]+:\\s-*\n")
1877 (setq names
(cons (match-string-no-properties 1) names
)))))
1879 (mapconcat (lambda (string) string
) names
"."))))
1881 (defun python-info-closing-block ()
1882 "Return the point of the block that the current line closes."
1883 (let ((closing-word (save-excursion
1884 (back-to-indentation)
1886 (indentation (current-indentation)))
1887 (when (member closing-word python-indent-dedenters
)
1890 (while (and (> (current-indentation) indentation
)
1892 (not (back-to-indentation))
1894 (back-to-indentation)
1896 ((not (equal indentation
(current-indentation))) nil
)
1897 ((string= closing-word
"elif")
1898 (when (member (current-word) '("if" "elif"))
1900 ((string= closing-word
"else")
1901 (when (member (current-word) '("if" "elif" "except" "for" "while"))
1903 ((string= closing-word
"except")
1904 (when (member (current-word) '("try"))
1906 ((string= closing-word
"finally")
1907 (when (member (current-word) '("except" "else"))
1908 (point-marker))))))))
1910 (defun python-info-line-ends-backslash-p ()
1911 "Return non-nil if current line ends with backslash."
1912 (string= (or (ignore-errors
1915 (- (line-end-position) 1))) "") "\\"))
1917 (defun python-info-continuation-line-p ()
1918 "Return non-nil if current line is continuation of another."
1919 (or (python-info-line-ends-backslash-p)
1920 (string-match ",[[:space:]]*$" (buffer-substring
1921 (line-beginning-position)
1922 (line-end-position)))
1924 (let ((innermost-paren (progn
1925 (goto-char (line-end-position))
1926 (python-info-ppss-context 'paren
))))
1927 (when (and innermost-paren
1928 (and (<= (line-beginning-position) innermost-paren
)
1929 (>= (line-end-position) innermost-paren
)))
1930 (goto-char innermost-paren
)
1931 (looking-at (python-rx open-paren
(* space
) line-end
)))))
1933 (back-to-indentation)
1934 (python-info-ppss-context 'paren
))))
1936 (defun python-info-block-continuation-line-p ()
1937 "Return non-nil if current line is a continuation of a block."
1939 (while (and (not (bobp))
1940 (python-info-continuation-line-p))
1943 (back-to-indentation)
1944 (when (looking-at (python-rx block-start
))
1947 (defun python-info-assignment-continuation-line-p ()
1948 "Return non-nil if current line is a continuation of an assignment."
1950 (while (and (not (bobp))
1951 (python-info-continuation-line-p))
1954 (back-to-indentation)
1955 (when (and (not (looking-at (python-rx block-start
)))
1957 (and (re-search-forward (python-rx not-simple-operator
1959 not-simple-operator
)
1960 (line-end-position) t
)
1961 (not (or (python-info-ppss-context 'string
)
1962 (python-info-ppss-context 'paren
)
1963 (python-info-ppss-context 'comment
))))))
1966 (defun python-info-ppss-context (type &optional syntax-ppss
)
1967 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
1968 TYPE can be 'comment, 'string or 'parent. It returns the start
1969 character address of the specified TYPE."
1970 (let ((ppss (or syntax-ppss
(syntax-ppss))))
1983 (define-derived-mode python-mode fundamental-mode
"Python"
1984 "A major mode for editing Python files."
1985 (set (make-local-variable 'tab-width
) 8)
1986 (set (make-local-variable 'indent-tabs-mode
) nil
)
1988 (set (make-local-variable 'comment-start
) "# ")
1989 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
1991 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1992 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1994 (set (make-local-variable 'font-lock-defaults
)
1995 '(python-font-lock-keywords
1997 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords
)))
1999 (set (make-local-variable 'indent-line-function
) #'python-indent-line-function
)
2000 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2002 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2003 (set (make-local-variable 'fill-paragraph-function
) 'python-fill-paragraph-function
)
2005 (set (make-local-variable 'beginning-of-defun-function
)
2006 #'python-beginning-of-defun-function
)
2007 (set (make-local-variable 'end-of-defun-function
)
2008 #'python-end-of-defun-function
)
2010 (add-hook 'completion-at-point-functions
2011 'python-completion-complete-at-point nil
'local
)
2013 (set (make-local-variable 'add-log-current-defun-function
)
2014 #'python-info-current-defun
)
2016 (set (make-local-variable 'skeleton-further-elements
)
2018 (< '(backward-delete-char-untabify (min python-indent-offset
2020 (^
'(- (1+ (current-indentation))))))
2022 (set (make-local-variable 'eldoc-documentation-function
)
2023 #'python-eldoc-function
)
2025 (add-to-list 'hs-special-modes-alist
2026 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
2028 (python-end-of-defun-function)) nil
))
2030 (set (make-local-variable 'outline-regexp
)
2031 (python-rx (* space
) block-start
))
2032 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
2033 (set (make-local-variable 'outline-level
)
2035 "`outline-level' function for Python mode."
2036 (1+ (/ (current-indentation) python-indent-offset
))))
2038 (python-skeleton-add-menu-items)
2040 (when python-indent-guess-indent-offset
2041 (python-indent-guess-indent-offset)))
2045 ;;; python.el ends here