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-strings-code'
63 ;; Pdb tracking: when you execute a block of code that contains some
64 ;; call to pdb (or ipdb) it will prompt the block of code and will
65 ;; follow the execution of pdb marking the current line with an arrow.
67 ;; Symbol completion: you can complete the symbol at point. It uses
68 ;; the shell completion in background so you should run
69 ;; `python-shell-send-buffer' from time to time to get better results.
71 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
72 ;; def, for, if, try and while. These skeletons are integrated with
73 ;; dabbrev. If you have `dabbrev-mode' activated and
74 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
75 ;; the name of any of those defined and hit SPC, they will be
76 ;; automatically expanded.
78 ;; FFAP: You can find the filename for a given module when using ffap
79 ;; out of the box. This feature needs an inferior python shell
82 ;; Code check: Check the current file for errors using
83 ;; `python-check-command'
85 ;; Eldoc: returns documentation for object at point by using the
86 ;; inferior python subprocess to inspect its documentation. As you
87 ;; might guessed you should run `python-shell-send-buffer' from time
88 ;; to time to get better results too.
90 ;; If you used python-mode.el you probably will miss auto-indentation
91 ;; when inserting newlines. To achieve the same behavior you have
94 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
96 ;; 2) Add the following hook in your .emacs:
98 ;; (add-hook 'python-mode-hook
100 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
102 ;; I'd recommend the first one since you'll get the same behavior for
103 ;; all modes out-of-the-box.
107 ;; Add this to your .emacs:
109 ;; (add-to-list 'load-path "/folder/containing/file")
114 ;; Ordered by priority:
116 ;; Better decorator support for beginning of defun
118 ;; Review code and cleanup
122 (require 'ansi-color
)
127 ;; Avoid compiler warnings
128 (defvar view-return-to-alist
)
129 (defvar compilation-error-regexp-alist
)
130 (defvar outline-heading-end-regexp
))
132 (autoload 'comint-mode
"comint")
135 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
137 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
140 "Python Language's flying circus support for Emacs."
143 :link
'(emacs-commentary-link "python"))
148 (defvar python-mode-map
149 (let ((map (make-sparse-keymap)))
151 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
152 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
153 (define-key map
"\C-c<" 'python-indent-shift-left
)
154 (define-key map
"\C-c>" 'python-indent-shift-right
)
155 (define-key map
":" 'python-indent-electric-colon
)
157 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
158 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
159 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
160 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
161 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
162 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
164 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
165 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
166 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
167 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
168 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
169 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
170 ;; Some util commands
171 (define-key map
"\C-c\C-v" 'python-check
)
172 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
174 (substitute-key-definition 'complete-symbol
'completion-at-point
176 (easy-menu-define python-menu map
"Python Mode menu"
178 :help
"Python-specific Features"
179 ["Shift region left" python-indent-shift-left
:active mark-active
180 :help
"Shift region left by a single indentation step"]
181 ["Shift region right" python-indent-shift-right
:active mark-active
182 :help
"Shift region right by a single indentation step"]
184 ["Mark def/class" mark-defun
185 :help
"Mark outermost definition around point"]
187 ["Start of def/class" beginning-of-defun
188 :help
"Go to start of outermost definition around point"]
189 ["Start of def/class" python-beginning-of-innermost-defun
190 :help
"Go to start of innermost definition around point"]
191 ["End of def/class" end-of-defun
192 :help
"Go to end of definition around point"]
196 ["Start interpreter" run-python
197 :help
"Run inferior Python process in a separate buffer"]
198 ["Switch to shell" python-shell-switch-to-shell
199 :help
"Switch to running inferior Python process"]
200 ["Eval string" python-shell-send-string
201 :help
"Eval string in inferior Python session"]
202 ["Eval buffer" python-shell-send-buffer
203 :help
"Eval buffer in inferior Python session"]
204 ["Eval region" python-shell-send-region
205 :help
"Eval region in inferior Python session"]
206 ["Eval defun" python-shell-send-defun
207 :help
"Eval defun in inferior Python session"]
208 ["Eval file" python-shell-send-file
209 :help
"Eval file in inferior Python session"]
210 ["Debugger" pdb
:help
"Run pdb under GUD"]
212 ["Check file" python-check
213 :help
"Check file for errors"]
214 ["Help on symbol" python-eldoc-at-point
215 :help
"Get help on symbol at point"]
216 ["Complete symbol" completion-at-point
217 :help
"Complete symbol before point"]))
219 "Keymap for `python-mode'.")
222 ;;; Python specialized rx
225 (defconst python-rx-constituents
227 `(block-start .
,(rx symbol-start
228 (or "def" "class" "if" "elif" "else" "try"
229 "except" "finally" "for" "while" "with")
231 `(defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
232 `(open-paren .
,(rx (or "{" "[" "(")))
233 `(close-paren .
,(rx (or "}" "]" ")")))
234 `(simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
235 `(not-simple-operator .
,(rx (not (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
236 `(operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
237 "=" "%" "**" "//" "<<" ">>" "<=" "!="
238 "==" ">=" "is" "not")))
239 `(assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
240 ">>=" "<<=" "&=" "^=" "|="))))))
242 (defmacro python-rx
(&rest regexps
)
243 "Python mode especialized rx macro which supports common python named REGEXPS."
244 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
245 (cond ((null regexps
)
248 (rx-to-string `(and ,@regexps
) t
))
250 (rx-to-string (car regexps
) t
)))))
253 ;;; Font-lock and syntax
255 (defvar python-font-lock-keywords
258 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
259 "assert" "else" "if" "pass" "yield" "break" "except" "import"
260 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
261 "return" "def" "for" "lambda" "try" "self")
264 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
265 (1 font-lock-function-name-face
))
267 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
268 (1 font-lock-type-face
))
270 (,(rx symbol-start
(group "None" symbol-end
))
271 (1 font-lock-constant-face
))
273 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
274 (0+ "." (1+ (or word ?_
)))))
275 (1 font-lock-type-face
))
276 ;; Builtin Exceptions
278 (or "ArithmeticError" "AssertionError" "AttributeError"
279 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
280 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
281 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
282 "ImportWarning" "IndentationError" "IndexError" "KeyError"
283 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
284 "NotImplemented" "NotImplementedError" "OSError" "OverflowError"
285 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
286 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
287 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
288 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
289 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
290 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
291 symbol-end
) . font-lock-type-face
)
293 (,(rx (or line-start
(not (any ". \t"))) (* (any " \t")) symbol-start
295 (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
296 "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer"
297 "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce"
298 "compile" "complex" "copyright" "credits" "delattr" "dict" "dir"
299 "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter"
300 "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash"
301 "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
302 "iter" "len" "license" "list" "locals" "long" "map" "max" "min"
303 "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit"
304 "range" "raw_input" "reduce" "reload" "repr" "reversed" "round"
305 "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum"
306 "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip"
307 "True" "False" "Ellipsis")) symbol-end
)
308 (1 font-lock-builtin-face
))
310 ;; support for a = b = c = 5
312 (let ((re (python-rx (group (+ (any word ?. ?_
)))
313 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
314 assignment-operator
)))
315 (when (re-search-forward re limit t
)
316 (while (and (not (equal (nth 0 (syntax-ppss)) 0))
317 (re-search-forward re limit t
)))
318 (if (and (equal (nth 0 (syntax-ppss)) 0)
319 (not (equal (char-after (point-marker)) ?
=)))
321 (set-match-data nil
)))))
322 (1 font-lock-variable-name-face nil nil
))
323 ;; support for a, b, c = (1, 2, 3)
325 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
326 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
327 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
328 assignment-operator
)))
329 (when (and (re-search-forward re limit t
)
330 (goto-char (nth 3 (match-data))))
331 (while (and (not (equal (nth 0 (syntax-ppss)) 0))
332 (re-search-forward re limit t
))
333 (goto-char (nth 3 (match-data))))
334 (if (equal (nth 0 (syntax-ppss)) 0)
336 (set-match-data nil
)))))
337 (1 font-lock-variable-name-face nil nil
))))
339 ;; Fixme: Is there a better way?
340 (defconst python-font-lock-syntactic-keywords
341 ;; First avoid a sequence preceded by an odd number of backslashes.
342 `((,(rx (not (any ?
\\))
343 ?
\\ (* (and ?
\\ ?
\\))
344 (group (syntax string-quote
))
347 (2 ,(string-to-syntax "\""))) ; dummy
348 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
349 (optional (any "rR")) ; possible second prefix
350 (group (syntax string-quote
)) ; maybe gets property
351 (backref 2) ; per first quote
352 (group (backref 2))) ; maybe gets property
353 (1 (python-quote-syntax 1))
354 (2 (python-quote-syntax 2))
355 (3 (python-quote-syntax 3))))
356 "Make outer chars of triple-quote strings into generic string delimiters.")
358 (defun python-quote-syntax (n)
359 "Put `syntax-table' property correctly on triple quote.
360 Used for syntactic keywords. N is the match number (1, 2 or 3)."
361 ;; Given a triple quote, we have to check the context to know
362 ;; whether this is an opening or closing triple or whether it's
363 ;; quoted anyhow, and should be ignored. (For that we need to do
364 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
365 ;; to use it here despite initial worries.) We also have to sort
366 ;; out a possible prefix -- well, we don't _have_ to, but I think it
367 ;; should be treated as part of the string.
370 ;; ur"""ar""" x='"' # """
373 ;; x '"""' x """ \"""" x
375 (goto-char (match-beginning 0))
377 ;; Consider property for the last char if in a fenced string.
379 (let* ((font-lock-syntactic-keywords nil
)
380 (syntax (syntax-ppss)))
381 (when (eq t
(nth 3 syntax
)) ; after unclosed fence
382 (goto-char (nth 8 syntax
)) ; fence position
383 (skip-chars-forward "uUrR") ; skip any prefix
384 ;; Is it a matching sequence?
385 (if (eq (char-after) (char-after (match-beginning 2)))
386 (eval-when-compile (string-to-syntax "|"))))))
387 ;; Consider property for initial char, accounting for prefixes.
388 ((or (and (= n
2) ; leading quote (not prefix)
389 (= (match-beginning 1) (match-end 1))) ; prefix is null
390 (and (= n
1) ; prefix
391 (/= (match-beginning 1) (match-end 1)))) ; non-empty
392 (let ((font-lock-syntactic-keywords nil
))
393 (unless (eq 'string
(syntax-ppss-context (syntax-ppss)))
394 (eval-when-compile (string-to-syntax "|")))))
395 ;; Otherwise (we're in a non-matching string) the property is
399 (defvar python-mode-syntax-table
400 (let ((table (make-syntax-table)))
401 ;; Give punctuation syntax to ASCII that normally has symbol
402 ;; syntax or has word syntax and isn't a letter.
403 (let ((symbol (string-to-syntax "_"))
404 (sst (standard-syntax-table)))
407 (if (equal symbol
(aref sst i
))
408 (modify-syntax-entry i
"." table
)))))
409 (modify-syntax-entry ?$
"." table
)
410 (modify-syntax-entry ?%
"." table
)
412 (modify-syntax-entry ?
# "<" table
)
413 (modify-syntax-entry ?
\n ">" table
)
414 (modify-syntax-entry ?
' "\"" table
)
415 (modify-syntax-entry ?
` "$" table
)
417 "Syntax table for Python files.")
419 (defvar python-dotty-syntax-table
420 (let ((table (make-syntax-table python-mode-syntax-table
)))
421 (modify-syntax-entry ?.
"w" table
)
422 (modify-syntax-entry ?_
"w" table
)
424 "Dotty syntax table for Python files.
425 It makes underscores and dots word constituent chars.")
430 (defcustom python-indent-offset
4
431 "Default indentation offset for Python."
436 (defcustom python-indent-guess-indent-offset t
437 "Non-nil tells Python mode to guess `python-indent-offset' value."
441 (defvar python-indent-current-level
0
442 "Current indentation level `python-indent-line-function' is using.")
444 (defvar python-indent-levels
'(0)
445 "Levels of indentation available for `python-indent-line-function'.")
447 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
448 "List of words that should be dedented.
449 These make `python-indent-calculate-indentation' subtract the value of
450 `python-indent-offset'.")
452 (defun python-indent-guess-indent-offset ()
453 "Guess and set `python-indent-offset' for the current buffer."
457 (goto-char (point-min))
459 (while (and (not found-block
)
461 (python-rx line-start block-start
) nil t
))
462 (when (and (not (syntax-ppss-context (syntax-ppss)))
464 (goto-char (line-end-position))
466 (eq ?
: (char-before))))
467 (setq found-block t
)))
468 (if (not found-block
)
469 (message "Can't guess python-indent-offset, using defaults: %s"
470 python-indent-offset
)
472 (goto-char (line-end-position))
473 (python-info-continuation-line-p))
478 (let ((indent-offset (current-indentation)))
479 (when (> indent-offset
0)
480 (setq python-indent-offset indent-offset
))))))))
482 (defun python-indent-context (&optional stop
)
483 "Return information on indentation context.
484 Optional argument STOP serves to stop recursive calls.
486 Returns a cons with the form:
490 Where status can be any of the following symbols:
492 * inside-paren: If point in between (), {} or []
493 * inside-string: If point is inside a string
494 * after-backslash: Previous line ends in a backslash
495 * after-beginning-of-block: Point is after beginning of block
496 * after-line: Point is after normal line
497 * no-indent: Point is at beginning of buffer or other special case
499 START is the buffer position where the sexp starts."
502 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
506 ;; Beginning of buffer
508 (goto-char (line-beginning-position))
512 ((setq start
(nth 1 ppss
))
515 ((setq start
(when (and (nth 3 ppss
))
519 ((setq start
(when (not (syntax-ppss-context ppss
))
520 (let ((line-beg-pos (line-beginning-position)))
521 (when (eq ?
\\ (char-before (1- line-beg-pos
)))
522 (- line-beg-pos
2)))))
524 ;; After beginning of block
525 ((setq start
(save-excursion
526 (let ((block-regexp (python-rx block-start
))
527 (block-start-line-end ":[[:space:]]*$"))
528 (back-to-indentation)
529 (while (and (forward-comment -
1) (not (bobp))))
530 (back-to-indentation)
531 (when (or (python-info-continuation-line-p)
532 (and (not (looking-at block-regexp
))
536 (line-end-position) t
))))
537 (while (and (forward-line -
1)
538 (python-info-continuation-line-p)
540 (when (not (looking-at block-regexp
))
542 (back-to-indentation)
543 (when (and (looking-at block-regexp
)
544 (or (re-search-forward
546 (line-end-position) t
)
547 (python-info-continuation-line-p)))
549 'after-beginning-of-block
)
551 ((setq start
(save-excursion
552 (while (and (forward-comment -
1) (not (bobp))))
553 (while (and (not (back-to-indentation))
555 (if (> (nth 0 (syntax-ppss)) 0)
559 (python-info-line-ends-backslash-p))
560 (forward-line -
1)))))
567 (defun python-indent-calculate-indentation ()
568 "Calculate correct indentation offset for the current line."
569 (let* ((indentation-context (python-indent-context))
570 (context-status (car indentation-context
))
571 (context-start (cdr indentation-context
)))
577 ('after-beginning-of-block
578 (goto-char context-start
)
579 (+ (current-indentation) python-indent-offset
))
583 (goto-char context-start
)
584 (current-indentation))
586 (back-to-indentation)
587 (looking-at (regexp-opt python-indent-dedenters
)))
591 (goto-char context-start
)
592 (current-indentation))
594 (let* ((block-continuation
597 (python-info-block-continuation-line-p)))
598 (assignment-continuation
601 (python-info-assignment-continuation-line-p)))
602 (indentation (cond (block-continuation
603 (goto-char block-continuation
)
605 (python-rx block-start
(* space
))
606 (line-end-position) t
)
608 (assignment-continuation
609 (goto-char assignment-continuation
)
611 (python-rx simple-operator
)
612 (line-end-position) t
)
615 (python-rx (* space
))
616 (line-end-position) t
)
619 (goto-char context-start
)
620 (current-indentation)))))
625 (looking-at (regexp-opt '(")" "]" "}")))
627 (when (not (nth 1 (syntax-ppss)))
628 (goto-char context-start
)
629 (back-to-indentation)
633 (goto-char context-start
)
637 (line-beginning-position)
641 (+ (current-indentation) python-indent-offset
)
645 (back-to-indentation)
646 (looking-at (regexp-opt '(")" "]" "}"))))
650 (defun python-indent-calculate-levels ()
651 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
652 (let* ((indentation (python-indent-calculate-indentation))
653 (remainder (% indentation python-indent-offset
))
654 (steps (/ (- indentation remainder
) python-indent-offset
)))
655 (setq python-indent-levels
'())
656 (setq python-indent-levels
(cons 0 python-indent-levels
))
657 (dotimes (step steps
)
658 (setq python-indent-levels
659 (cons (* python-indent-offset
(1+ step
)) python-indent-levels
)))
660 (when (not (eq 0 remainder
))
661 (setq python-indent-levels
662 (cons (+ (* python-indent-offset steps
) remainder
)
663 python-indent-levels
)))
664 (setq python-indent-levels
(nreverse python-indent-levels
))
665 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
667 (defun python-indent-toggle-levels ()
668 "Toggle `python-indent-current-level' over `python-indent-levels'."
669 (setq python-indent-current-level
(1- python-indent-current-level
))
670 (when (< python-indent-current-level
0)
671 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
673 (defun python-indent-line (&optional force-toggle
)
674 "Internal implementation of `python-indent-line-function'.
676 Uses the offset calculated in
677 `python-indent-calculate-indentation' and available levels
678 indicated by the variable `python-indent-levels'.
680 When the variable `last-command' is equal to
681 `indent-for-tab-command' or FORCE-TOGGLE is non-nil:
683 * Cycles levels indicated in the variable `python-indent-levels'
684 by setting the current level in the variable
685 `python-indent-current-level'.
687 When the variable `last-command' is not equal to
688 `indent-for-tab-command' and FORCE-TOGGLE is nil:
690 * calculates possible indentation levels and saves it in the
691 variable `python-indent-levels'.
693 * sets the variable `python-indent-current-level' correctly so
694 offset is equal to (`nth' `python-indent-current-level'
695 `python-indent-levels')"
696 (if (or (and (eq this-command
'indent-for-tab-command
)
697 (eq last-command this-command
))
699 (python-indent-toggle-levels)
700 (python-indent-calculate-levels))
702 (delete-horizontal-space)
703 (indent-to (nth python-indent-current-level python-indent-levels
))
706 (let ((closing-block-point (python-info-closing-block)))
707 (when closing-block-point
708 (message "Closes %s" (buffer-substring
711 (goto-char closing-block-point
)
712 (line-end-position))))))))
714 (defun python-indent-line-function ()
715 "`indent-line-function' for Python mode.
716 Internally just calls `python-indent-line'."
717 (python-indent-line))
719 (defun python-indent-dedent-line ()
720 "Dedent current line."
722 (when (and (not (syntax-ppss-context (syntax-ppss)))
723 (<= (point-marker) (save-excursion
724 (back-to-indentation)
726 (> (current-column) 0))
727 (python-indent-line t
)
730 (defun python-indent-dedent-line-backspace (arg)
731 "Dedent current line.
732 Argument ARG is passed to `backward-delete-char-untabify' when
733 point is not in between the indentation."
735 (when (not (python-indent-dedent-line))
736 (backward-delete-char-untabify arg
)))
737 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
739 (defun python-indent-region (start end
)
740 "Indent a python region automagically.
742 Called from a program, START and END specify the region to indent."
743 (let ((deactivate-mark nil
))
746 (setq end
(point-marker))
748 (or (bolp) (forward-line 1))
749 (while (< (point) end
)
750 (or (and (bolp) (eolp))
753 (back-to-indentation)
754 (setq word
(current-word))
758 (delete-horizontal-space)
759 (indent-to (python-indent-calculate-indentation)))))
761 (move-marker end nil
))))
763 (defun python-indent-shift-left (start end
&optional count
)
764 "Shift lines contained in region START END by COUNT columns to the left.
766 COUNT defaults to `python-indent-offset'.
768 If region isn't active, the current line is shifted.
770 The shifted region includes the lines in which START and END lie.
772 An error is signaled if any lines in the region are indented less
776 (list (region-beginning) (region-end) current-prefix-arg
)
777 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
779 (setq count
(prefix-numeric-value count
))
780 (setq count python-indent-offset
))
782 (let ((deactivate-mark nil
))
785 (while (< (point) end
)
786 (if (and (< (current-indentation) count
)
787 (not (looking-at "[ \t]*$")))
788 (error "Can't shift all lines enough"))
790 (indent-rigidly start end
(- count
))))))
792 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
794 (defun python-indent-shift-right (start end
&optional count
)
795 "Shift lines contained in region START END by COUNT columns to the left.
797 COUNT defaults to `python-indent-offset'.
799 If region isn't active, the current line is shifted.
801 The shifted region includes the lines in which START and END
805 (list (region-beginning) (region-end) current-prefix-arg
)
806 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
807 (let ((deactivate-mark nil
))
809 (setq count
(prefix-numeric-value count
))
810 (setq count python-indent-offset
))
811 (indent-rigidly start end count
)))
813 ;; Directly from Dave Love's python.el
814 (defun python-indent-electric-colon (arg)
815 "Insert a colon and maybe outdent the line if it is a statement like `else'.
816 With numeric ARG, just insert that many colons. With \\[universal-argument],
817 just insert a single colon."
819 (self-insert-command (if (not (integerp arg
)) 1 arg
))
822 (not (nth 8 (syntax-ppss)))
823 (> (current-indentation) (python-indent-calculate-indentation))
824 (save-excursion (python-indent-line))))
825 (put 'python-indent-electric-colon
'delete-selection t
)
830 (defvar python-beginning-of-defun-regexp
831 "^\\(def\\|class\\)[[:space:]]+[[:word:]]+"
832 "Regular expresion matching beginning of outermost class or function.")
834 (defvar python-beginning-of-innermost-defun-regexp
835 "^[[:space:]]*\\(def\\|class\\)[[:space:]]+[[:word:]]+"
836 "Regular expresion matching beginning of innermost class or function.")
838 (defun python-beginning-of-defun (&optional innermost
)
839 "Move point to the beginning of innermost/outermost def or class.
840 If INNERMOST is non-nil then move to the beginning of the
841 innermost definition."
842 (let ((starting-point (point-marker))
843 (nonblank-line-indent)
846 (regexp (if innermost
847 python-beginning-of-innermost-defun-regexp
848 python-beginning-of-defun-regexp
)))
849 (back-to-indentation)
850 (if (and (not (looking-at "@"))
851 (not (looking-at regexp
)))
853 (while (and (not (eobp))
855 (not (back-to-indentation))
857 (when (not (looking-at regexp
))
858 (re-search-backward regexp nil t
))
859 (setq nonblank-line-indent
(+ (current-indentation) python-indent-offset
))
860 (setq defun-indent
(current-indentation))
861 (setq defun-point
(point-marker))
862 (if (> nonblank-line-indent defun-indent
)
864 (goto-char defun-point
)
866 (while (and (looking-at "@")
869 (not (back-to-indentation))))
874 (python-beginning-of-defun)
875 (goto-char starting-point
)
878 (defun python-beginning-of-defun-function ()
879 "Move point to the beginning of outermost def or class.
880 Returns nil if point is not in a def or class."
881 (python-beginning-of-defun nil))
883 (defun python-beginning-of-innermost-defun ()
884 "Move point to the beginning of innermost def or class.
885 Returns nil if point is not in a def or class."
887 (python-beginning-of-defun t))
889 (defun python-end-of-defun-function ()
890 "Move point to the end of def or class.
891 Returns nil if point is not in a def or class."
892 (let ((starting-point (point-marker))
893 (defun-regexp (python-rx defun
))
895 (back-to-indentation)
897 (while (and (not (eobp))
899 (not (back-to-indentation))
901 (while (and (not (bobp))
902 (not (progn (back-to-indentation) (current-word)))
904 (when (or (not (equal (current-indentation) 0))
905 (string-match defun-regexp
(current-word)))
906 (setq beg-defun-indent
(save-excursion
907 (or (looking-at defun-regexp
)
908 (python-beginning-of-innermost-defun))
909 (current-indentation)))
910 (while (and (forward-line 1)
912 (or (not (current-word))
913 (> (current-indentation) beg-defun-indent
))))
914 (while (and (forward-comment -
1)
920 ;;; Shell integration
922 (defvar python-shell-buffer-name
"Python"
923 "Default buffer name for Python interpreter.")
925 (defcustom python-shell-interpreter
"python"
926 "Default Python interpreter for shell."
931 (defcustom python-shell-interpreter-args
"-i"
932 "Default arguments for the Python interpreter."
937 (defcustom python-shell-prompt-regexp
">>> "
938 "Regex matching top\-level input prompt of python shell.
939 The regex should not contain a caret (^) at the beginning."
944 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
945 "Regex matching block input prompt of python shell.
946 The regex should not contain a caret (^) at the beginning."
951 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
952 "Regex matching pdb input prompt of python shell.
953 The regex should not contain a caret (^) at the beginning."
958 (defcustom python-shell-compilation-regexp-alist
959 `((,(rx line-start
(1+ (any " \t")) "File \""
960 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
961 "\", line " (group (1+ digit
)))
963 (,(rx " in file " (group (1+ not-newline
)) " on line "
966 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
967 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
969 "`compilation-error-regexp-alist' for inferior Python."
970 :type
'(alist string
)
973 (defun python-shell-get-process-name (dedicated)
974 "Calculate the appropiate process name for inferior Python process.
976 If DEDICATED is t and the variable `buffer-file-name' is non-nil
977 returns a string with the form
978 `python-shell-buffer-name'[variable `buffer-file-name'] else
979 returns the value of `python-shell-buffer-name'.
981 After calculating the process name add the buffer name for the
982 process in the `same-window-buffer-names' list"
986 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
987 (format "%s" python-shell-buffer-name
))))
988 (add-to-list 'same-window-buffer-names
(purecopy
989 (format "*%s*" process-name
)))
992 (defun python-shell-parse-command ()
993 "Calculates the string used to execute the inferior Python process."
994 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
996 (defun python-comint-output-filter-function (output)
997 "Hook run after content is put into comint buffer.
998 OUTPUT is a string with the contents of the buffer."
999 (ansi-color-filter-apply output
))
1001 (defvar inferior-python-mode-current-file nil
1002 "Current file from which a region was sent.")
1003 (make-variable-buffer-local 'inferior-python-mode-current-file
)
1005 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1006 "Major mode for Python inferior process."
1007 (set-syntax-table python-mode-syntax-table
)
1008 (setq mode-line-process
'(":%s"))
1009 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1010 python-shell-prompt-regexp
1011 python-shell-prompt-block-regexp
1012 python-shell-prompt-pdb-regexp
))
1013 (make-local-variable 'comint-output-filter-functions
)
1014 (add-hook 'comint-output-filter-functions
1015 'python-comint-output-filter-function
)
1016 (add-hook 'comint-output-filter-functions
1017 'python-pdbtrack-comint-output-filter-function
)
1018 (set (make-local-variable 'compilation-error-regexp-alist
)
1019 python-shell-compilation-regexp-alist
)
1020 (define-key inferior-python-mode-map
[remap complete-symbol
]
1021 'completion-at-point
)
1022 (add-hook 'completion-at-point-functions
1023 'python-shell-completion-complete-at-point nil
'local
)
1024 (compilation-shell-minor-mode 1))
1026 (defun run-python (dedicated cmd
)
1027 "Run an inferior Python process.
1029 Input and output via buffer *\\[python-shell-buffer-name]*.
1031 If there is a process already running in
1032 *\\[python-shell-buffer-name]*, switch to that buffer.
1034 With argument, allows you to:
1036 * Define DEDICATED so a dedicated process for the current buffer
1039 * Define CMD so you can edit the command used to call the
1040 interpreter (default is value of `python-shell-interpreter' and
1041 arguments defined in `python-shell-interpreter-args').
1043 Runs the hook `inferior-python-mode-hook' (after the
1044 `comint-mode-hook' is run).
1046 \(Type \\[describe-mode] in the process buffer for a list of
1049 (if current-prefix-arg
1051 (y-or-n-p "Make dedicated process? ")
1052 (read-string "Run Python: " (python-shell-parse-command)))
1053 (list nil
(python-shell-parse-command))))
1054 (let* ((proc-name (python-shell-get-process-name dedicated
))
1055 (proc-buffer-name (format "*%s*" proc-name
)))
1056 (when (not (comint-check-proc proc-buffer-name
))
1057 (let ((cmdlist (split-string-and-unquote cmd
)))
1059 (apply 'make-comint proc-name
(car cmdlist
) nil
1061 (inferior-python-mode)))
1062 (pop-to-buffer proc-buffer-name
))
1065 (defun python-shell-get-process ()
1066 "Get inferior Python process for current buffer and return it."
1067 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1068 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1069 (global-proc-name (python-shell-get-process-name nil
))
1070 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1071 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1072 (global-running (comint-check-proc global-proc-buffer-name
)))
1073 ;; Always prefer dedicated
1074 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1075 (and global-running global-proc-buffer-name
)))))
1077 (defun python-shell-get-or-create-process ()
1078 "Get or create an inferior Python process for current buffer and return it."
1079 (let* ((old-buffer (current-buffer))
1080 (dedicated-proc-name (python-shell-get-process-name t
))
1081 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1082 (global-proc-name (python-shell-get-process-name nil
))
1083 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1084 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1085 (global-running (comint-check-proc global-proc-buffer-name
))
1086 (current-prefix-arg 4))
1087 (when (and (not dedicated-running
) (not global-running
))
1088 (if (call-interactively 'run-python
)
1089 (setq dedicated-running t
)
1090 (setq global-running t
)))
1091 ;; Always prefer dedicated
1092 (switch-to-buffer old-buffer
)
1093 (get-buffer-process (if dedicated-running
1094 dedicated-proc-buffer-name
1095 global-proc-buffer-name
))))
1097 (defun python-shell-send-string (string &optional process
)
1098 "Send STRING to inferior Python PROCESS."
1099 (interactive "sPython command: ")
1100 (let ((process (or process
(python-shell-get-or-create-process))))
1101 (when (called-interactively-p 'interactive
)
1102 (message (format "Sent: %s..." string
)))
1103 (comint-send-string process string
)
1104 (when (or (not (string-match "\n$" string
))
1105 (string-match "\n[ \t].*\n?$" string
))
1106 (comint-send-string process
"\n"))))
1108 (defun python-shell-send-region (start end
)
1109 "Send the region delimited by START and END to inferior Python process."
1111 (let* ((contents (buffer-substring start end
))
1112 (current-file (buffer-file-name))
1113 (process (python-shell-get-or-create-process))
1114 (temp-file (make-temp-file "py")))
1115 (with-temp-file temp-file
1117 (delete-trailing-whitespace)
1118 (goto-char (point-min))
1119 (message (format "Sent: %s..."
1120 (buffer-substring (point-min)
1121 (line-end-position)))))
1122 (python-shell-send-file current-file process temp-file
)))
1124 (defun python-shell-send-buffer ()
1125 "Send the entire buffer to inferior Python process."
1129 (python-shell-send-region (point-min) (point-max))))
1131 (defun python-shell-send-defun (arg)
1132 "Send the (inner|outer)most def or class to inferior Python process.
1133 When argument ARG is non-nil sends the innermost defun."
1136 (python-shell-send-region (progn
1138 (python-beginning-of-innermost-defun)
1139 (python-beginning-of-defun-function))
1140 (progn (beginning-of-line) (point-marker))))
1142 (or (python-end-of-defun-function)
1143 (progn (end-of-line) (point-marker)))))))
1145 (defun python-shell-send-file (file-name &optional process temp-file-name
)
1146 "Send FILE-NAME to inferior Python PROCESS.
1147 If TEMP-FILE-NAME is passed then that file is used for processing
1148 instead, while internally the shell will continue to use
1150 (interactive "fFile to send: ")
1151 (let ((process (or process
(python-shell-get-or-create-process)))
1152 (file-name (expand-file-name file-name
))
1153 (temp-file-name (when temp-file-name
1154 (expand-file-name temp-file-name
))))
1155 (find-file-noselect file-name
)
1156 (with-current-buffer (process-buffer process
)
1157 (setq inferior-python-mode-current-file
1158 (convert-standard-filename file-name
)))
1159 (python-shell-send-string
1161 (concat "__pyfile = open('''%s''');"
1162 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1164 (or temp-file-name file-name
) file-name
)
1167 (defun python-shell-clear-latest-output ()
1168 "Clear latest output from the Python shell.
1169 Return the cleaned output."
1171 (when (and comint-last-output-start
1172 comint-last-prompt-overlay
)
1174 (let* ((last-output-end
1177 (overlay-start comint-last-prompt-overlay
))
1178 (forward-comment -
1)
1181 (buffer-substring-no-properties
1182 comint-last-output-start last-output-end
)))
1183 (when (< 0 (length last-output
))
1184 (goto-char comint-last-output-start
)
1185 (delete-region comint-last-output-start last-output-end
)
1189 (defun python-shell-send-and-clear-output (string process
)
1190 "Send STRING to PROCESS and clear the output.
1191 Return the cleaned output."
1193 (python-shell-send-string string process
)
1194 (accept-process-output process
)
1195 (with-current-buffer (process-buffer process
)
1196 (let ((output (python-shell-clear-latest-output)))
1199 (goto-char (overlay-end comint-last-prompt-overlay
))
1202 (defun python-shell-switch-to-shell ()
1203 "Switch to inferior Python process buffer."
1205 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
1208 ;;; Shell completion
1210 (defvar python-shell-completion-setup-code
1214 def __COMPLETER_all_completions(text): []
1217 readline.set_completer(rlcompleter.Completer().complete)
1218 def __COMPLETER_all_completions(text):
1224 res = readline.get_completer()(text, i)
1227 completions.append(res)
1231 "Code used to setup completion in inferior Python processes.")
1233 (defvar python-shell-completion-strings-code
1234 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1235 "Python code used to get a string of completions separated by semicolons.")
1237 (defun python-shell-completion-setup ()
1238 "Send `python-shell-completion-setup-code' to inferior Python process.
1239 Also binds <tab> to `python-shell-complete-or-indent' in the
1240 `inferior-python-mode-map' and adds
1241 `python-shell-completion-complete-at-point' to the
1242 `comint-dynamic-complete-functions' list.
1243 It is specially designed to be added to the
1244 `inferior-python-mode-hook'."
1245 (when python-shell-completion-setup-code
1246 (let ((temp-file (make-temp-file "py"))
1247 (process (get-buffer-process (current-buffer))))
1248 (with-temp-file temp-file
1249 (insert python-shell-completion-setup-code
)
1250 (delete-trailing-whitespace)
1251 (goto-char (point-min)))
1252 (python-shell-send-file temp-file process
)
1253 (message (format "Completion setup code sent.")))
1254 (add-to-list (make-local-variable
1255 'comint-dynamic-complete-functions
)
1256 'python-shell-completion-complete-at-point
)
1257 (define-key inferior-python-mode-map
(kbd "<tab>")
1258 'python-shell-completion-complete-or-indent
)))
1260 (defun python-shell-completion--get-completions (input process
)
1261 "Retrieve available completions for INPUT using PROCESS."
1262 (with-current-buffer (process-buffer process
)
1264 (or (python-shell-send-and-clear-output
1265 (format python-shell-completion-strings-code input
)
1267 ";\\|\"\\|'\\|(" t
)))
1269 (defun python-shell-completion--get-completion (input completions
)
1270 "Get completion for INPUT using COMPLETIONS."
1271 (let ((completion (when completions
1272 (try-completion input completions
))))
1273 (cond ((eq completion t
)
1276 (message "Can't find completion for \"%s\"" input
)
1279 ((not (string= input completion
))
1282 (message "Making completion list...")
1283 (with-output-to-temp-buffer "*Python Completions*"
1284 (display-completion-list
1285 (all-completions input completions
)))
1288 (defun python-shell-completion-complete-at-point ()
1289 "Perform completion at point in inferior Python process."
1291 (with-syntax-table python-dotty-syntax-table
1292 (when (and comint-last-prompt-overlay
1293 (> (point-marker) (overlay-end comint-last-prompt-overlay
)))
1294 (let* ((process (get-buffer-process (current-buffer)))
1295 (input (substring-no-properties
1296 (or (comint-word (current-word)) "") nil nil
)))
1297 (delete-char (- (length input
)))
1299 (python-shell-completion--get-completion
1300 input
(python-shell-completion--get-completions input process
)))))))
1302 (defun python-shell-completion-complete-or-indent ()
1303 "Complete or indent depending on the context.
1304 If content before pointer is all whitespace indent. If not try to
1307 (if (string-match "^[[:space:]]*$"
1308 (buffer-substring (comint-line-beginning-position)
1310 (indent-for-tab-command)
1311 (comint-dynamic-complete)))
1313 (add-hook 'inferior-python-mode-hook
1314 #'python-shell-completion-setup
)
1317 ;;; PDB Track integration
1319 (defvar python-pdbtrack-stacktrace-info-regexp
1320 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1321 "Regexp matching stacktrace information.
1322 It is used to extract the current line and module beign
1324 The regexp should not start with a caret (^) and can contain a
1325 string placeholder (\%s) which is replaced with the filename
1326 beign inspected (so other files in the debugging process are not
1329 (defvar python-pdbtrack-tracking-buffers
'()
1330 "Alist containing elements of form (#<buffer> . #<buffer>).
1331 The car of each element of the alist is the tracking buffer and
1332 the cdr is the tracked buffer.")
1334 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1335 "Get/Add a tracked buffer for the current buffer.
1336 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1337 Returns a cons with the form:
1338 * (#<tracking buffer> . #< tracked buffer>)."
1340 (assq (current-buffer) python-pdbtrack-tracking-buffers
)
1341 (let* ((file (with-current-buffer (current-buffer)
1342 inferior-python-mode-current-file
))
1344 `(,(current-buffer) .
1345 ,(or (get-file-buffer file
)
1346 (find-file-noselect file
)))))
1347 (set-buffer (cdr tracking-buffers
))
1349 (set-buffer (car tracking-buffers
))
1350 (setq python-pdbtrack-tracking-buffers
1351 (cons tracking-buffers python-pdbtrack-tracking-buffers
))
1354 (defun python-pdbtrack-comint-output-filter-function (output)
1355 "Move overlay arrow to current pdb line in tracked buffer.
1356 Argument OUTPUT is a string with the output from the comint process."
1357 (when (not (string= output
""))
1358 (let ((full-output (ansi-color-filter-apply
1359 (buffer-substring comint-last-input-end
1361 (if (string-match python-shell-prompt-pdb-regexp full-output
)
1362 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1366 (format python-pdbtrack-stacktrace-info-regexp
1368 inferior-python-mode-current-file
))
1370 (string-to-number (or (match-string-no-properties 1 full-output
) ""))))
1371 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers
)))
1372 (tracked-buffer-line-pos))
1374 (with-current-buffer (cdr tracking-buffers
)
1375 (set (make-local-variable 'overlay-arrow-string
) "=>")
1376 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
1377 (setq tracked-buffer-line-pos
(progn
1378 (goto-char (point-min))
1379 (forward-line (1- line-num
))
1381 (when tracked-buffer-window
1382 (set-window-point tracked-buffer-window tracked-buffer-line-pos
))
1383 (set-marker overlay-arrow-position tracked-buffer-line-pos
)))
1384 (pop-to-buffer (cdr tracking-buffers
))
1385 (switch-to-buffer-other-window (car tracking-buffers
)))
1386 (let ((tracking-buffers (assq (current-buffer)
1387 python-pdbtrack-tracking-buffers
)))
1388 (when tracking-buffers
1389 (if inferior-python-mode-current-file
1390 (with-current-buffer (cdr tracking-buffers
)
1391 (set-marker overlay-arrow-position nil
))
1392 (kill-buffer (cdr tracking-buffers
)))
1393 (setq python-pdbtrack-tracking-buffers
1394 (assq-delete-all (current-buffer)
1395 python-pdbtrack-tracking-buffers
)))))))
1399 ;;; Symbol completion
1401 (defun python-completion-complete-at-point ()
1402 "Complete current symbol at point.
1403 For this to work the best as possible you should call
1404 `python-shell-send-buffer' from time to time so context in
1405 inferior python process is updated properly."
1407 (let ((process (python-shell-get-process)))
1409 (error "Completion needs an inferior Python process running")
1410 (with-syntax-table python-dotty-syntax-table
1411 (let* ((input (substring-no-properties
1412 (or (comint-word (current-word)) "") nil nil
))
1413 (completions (python-shell-completion--get-completions
1415 (delete-char (- (length input
)))
1417 (python-shell-completion--get-completion
1418 input completions
)))))))
1420 (add-to-list 'debug-ignored-errors
"^Completion needs an inferior Python process running.")
1425 (defun python-fill-paragraph-function (&optional justify
)
1426 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1427 If any of the current line is in or at the end of a multi-line string,
1428 fill the string or the paragraph of it that point is in, preserving
1429 the string's indentation.
1430 Optional argument JUSTIFY defines if the paragraph should be justified."
1433 (back-to-indentation)
1436 ((fill-comment-paragraph justify
))
1438 ((save-excursion (skip-chars-forward "\"'uUrR")
1439 (nth 3 (syntax-ppss)))
1440 (let ((marker (point-marker))
1441 (string-start-marker
1443 (skip-chars-forward "\"'uUrR")
1444 (goto-char (nth 8 (syntax-ppss)))
1445 (skip-chars-forward "\"'uUrR")
1447 (reg-start (line-beginning-position))
1450 (while (nth 3 (syntax-ppss)) (goto-char (1+ (point-marker))))
1451 (skip-chars-backward "\"'")
1453 (reg-end (line-end-position))
1454 (fill-paragraph-function))
1456 (narrow-to-region reg-start reg-end
)
1458 (goto-char string-start-marker
)
1459 (delete-region (point-marker) (progn
1460 (skip-syntax-forward "> ")
1462 (goto-char string-end-marker
)
1463 (delete-region (point-marker) (progn
1464 (skip-syntax-backward "> ")
1468 (fill-paragraph justify
))
1469 ;; If there is a newline in the docstring lets put triple
1470 ;; quote in it's own line to follow pep 8
1471 (when (save-excursion
1472 (re-search-backward "\n" string-start-marker t
))
1474 (newline-and-indent))
1475 (fill-paragraph justify
)))) t
)
1477 ((equal (char-after (save-excursion
1478 (back-to-indentation)
1479 (point-marker))) ?
@) t
)
1481 ((or (> (nth 0 (syntax-ppss)) 0)
1482 (looking-at (python-rx open-paren
))
1484 (skip-syntax-forward "^(" (line-end-position))
1485 (looking-at (python-rx open-paren
))))
1487 (narrow-to-region (progn
1488 (while (> (nth 0 (syntax-ppss)) 0)
1489 (goto-char (1- (point-marker))))
1491 (line-beginning-position))
1493 (when (not (> (nth 0 (syntax-ppss)) 0))
1495 (when (not (> (nth 0 (syntax-ppss)) 0))
1496 (skip-syntax-backward "^)")))
1497 (while (> (nth 0 (syntax-ppss)) 0)
1498 (goto-char (1+ (point-marker))))
1500 (let ((paragraph-start "\f\\|[ \t]*$")
1501 (paragraph-separate ",")
1502 (fill-paragraph-function))
1503 (goto-char (point-min))
1504 (fill-paragraph justify
))
1507 (python-indent-line)
1508 (goto-char (line-end-position)))) t
)
1514 (defcustom python-skeleton-autoinsert nil
1515 "Non-nil means template skeletons will be automagically inserted.
1516 This happens when pressing \"if<SPACE>\", for example, to prompt for
1521 (defvar python-skeleton-available
'()
1522 "Internal list of available skeletons.")
1523 (make-variable-buffer-local 'inferior-python-mode-current-file
)
1525 (define-abbrev-table 'python-mode-abbrev-table
()
1526 "Abbrev table for Python mode."
1528 ;; Allow / inside abbrevs.
1529 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1530 ;; Only expand in code.
1531 :enable-function
(lambda ()
1532 (message "ppss %s" (not (nth 8 (syntax-ppss))))
1533 (message "autoinsert %s" python-skeleton-autoinsert
)
1535 (not (nth 8 (syntax-ppss)))
1536 python-skeleton-autoinsert
)))
1538 (defmacro python-skeleton-define
(name doc
&rest skel
)
1539 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1540 The skeleton will be bound to python-skeleton-NAME and will
1541 be added to `python-mode-abbrev-table'."
1542 (let* ((name (symbol-name name
))
1543 (function-name (intern (concat "python-skeleton-" name
))))
1545 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
)
1546 (setq python-skeleton-available
1547 (cons ',function-name python-skeleton-available
))
1548 (define-skeleton ,function-name
1550 (format "Insert %s statement." name
))
1552 (put 'python-skeleton-define
'lisp-indent-function
2)
1554 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
1555 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1556 The skeleton will be bound to python-skeleton-NAME."
1557 (let* ((name (symbol-name name
))
1558 (function-name (intern (concat "python-skeleton--" name
)))
1560 "Add '%s' clause? " name
)))
1563 `(< ,(format "%s:" name
) \n \n
1565 `(define-skeleton ,function-name
1567 (format "Auxiliary skeleton for %s statement." name
))
1569 (unless (y-or-n-p ,msg
)
1572 (put 'python-define-auxiliary-skeleton
'lisp-indent-function
2)
1574 (python-define-auxiliary-skeleton else nil
)
1576 (python-define-auxiliary-skeleton except nil
)
1578 (python-define-auxiliary-skeleton finally nil
)
1580 (python-skeleton-define if nil
1584 ("other condition, %s: "
1588 '(python-skeleton--else) | ^
)
1590 (python-skeleton-define while nil
1594 '(python-skeleton--else) | ^
)
1596 (python-skeleton-define for nil
1600 '(python-skeleton--else) | ^
)
1602 (python-skeleton-define try nil
1608 "except " str
":" \n
1611 '(python-skeleton--except)
1612 '(python-skeleton--else)
1613 '(python-skeleton--finally) | ^
)
1615 (python-skeleton-define def nil
1617 "def " str
" (" ("Parameter, %s: "
1618 (unless (equal ?\
( (char-before)) ", ")
1620 "\"\"\"" -
"\"\"\"" \n
1623 (python-skeleton-define class nil
1625 "class " str
" (" ("Inheritance, %s: "
1626 (unless (equal ?\
( (char-before)) ", ")
1630 "\"\"\"" -
"\"\"\"" \n
1633 (defun python-skeleton-add-menu-items ()
1634 "Add menu items to Python->Skeletons menu."
1635 (let ((skeletons (sort python-skeleton-available
'string
<))
1637 (dolist (skeleton skeletons
)
1639 nil
'("Python" "Skeletons")
1641 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
1646 (defvar python-ffap-setup-code
1647 "def __FFAP_get_module_path(module):
1650 path = __import__(module).__file__
1651 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1656 "Python code to get a module path.")
1658 (defvar python-ffap-string-code
1659 "__FFAP_get_module_path('''%s''')\n"
1660 "Python code used to get a string with the path of a module.")
1662 (defun python-ffap-setup ()
1663 "Send `python-ffap-setup-code' to inferior Python process.
1664 It is specially designed to be added to the
1665 `inferior-python-mode-hook'."
1666 (when python-ffap-setup-code
1667 (let ((temp-file (make-temp-file "py")))
1668 (with-temp-file temp-file
1669 (insert python-ffap-setup-code
)
1670 (delete-trailing-whitespace)
1671 (goto-char (point-min)))
1672 (python-shell-send-file temp-file
(get-buffer-process (current-buffer)))
1673 (message (format "FFAP setup code sent.")))))
1675 (defun python-ffap-module-path (module)
1676 "Function for `ffap-alist' to return path for MODULE."
1678 (and (eq major-mode
'inferior-python-mode
)
1679 (get-buffer-process (current-buffer)))
1680 (python-shell-get-process))))
1684 (python-shell-send-and-clear-output
1685 (format python-ffap-string-code module
) process
)))
1687 (substring-no-properties module-file
1 -
1))))))
1689 (eval-after-load "ffap"
1691 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
1692 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
1694 (add-hook 'inferior-python-mode-hook
1695 #'python-ffap-setup
)
1700 (defvar python-check-command
1701 "pychecker --stdlib"
1702 "Command used to check a Python file.")
1704 (defvar python-check-custom-command nil
1707 (defun python-check (command)
1708 "Check a Python file (default current buffer's file).
1709 Runs COMMAND, a shell command, as if by `compile'. See
1710 `python-check-command' for the default."
1712 (list (read-string "Check command: "
1713 (or python-check-custom-command
1714 (concat python-check-command
" "
1715 (shell-quote-argument
1717 (let ((name (buffer-file-name)))
1719 (file-name-nondirectory name
)))
1721 (setq python-check-custom-command command
)
1722 (save-some-buffers (not compilation-ask-about-save
) nil
)
1723 (compilation-start command
))
1728 (defvar python-eldoc-setup-code
1729 "def __PYDOC_get_help(obj):
1732 if hasattr(obj, 'startswith'):
1733 obj = eval(obj, globals())
1734 doc = pydoc.getdoc(obj)
1741 "Python code to setup documentation retrieval.")
1743 (defvar python-eldoc-string-code
1744 "__PYDOC_get_help('''%s''')\n"
1745 "Python code used to get a string with the documentation of an object.")
1747 (defun python-eldoc-setup ()
1748 "Send `python-eldoc-setup-code' to inferior Python process.
1749 It is specially designed to be added to the
1750 `inferior-python-mode-hook'."
1751 (when python-eldoc-setup-code
1752 (let ((temp-file (make-temp-file "py")))
1753 (with-temp-file temp-file
1754 (insert python-eldoc-setup-code
)
1755 (delete-trailing-whitespace)
1756 (goto-char (point-min)))
1757 (python-shell-send-file temp-file
(get-buffer-process (current-buffer)))
1758 (message (format "Eldoc setup code sent.")))))
1760 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
1761 "Internal implementation to get documentation at point.
1762 If not FORCE-INPUT is passed then what `current-word' returns
1763 will be used. If not FORCE-PROCESS is passed what
1764 `python-shell-get-process' returns is used."
1765 (let ((process (or force-process
(python-shell-get-process))))
1767 "Eldoc needs an inferior Python process running."
1768 (let* ((current-defun (python-info-current-defun))
1769 (input (or force-input
1770 (with-syntax-table python-dotty-syntax-table
1771 (if (not current-defun
)
1773 (concat current-defun
"." (current-word))))))
1774 (ppss (syntax-ppss))
1775 (help (when (and input
1776 (not (string= input
(concat current-defun
".")))
1777 (eq nil
(nth 3 ppss
))
1778 (eq nil
(nth 4 ppss
)))
1779 (when (string-match (concat
1780 (regexp-quote (concat current-defun
"."))
1784 (goto-char (point-min))
1787 (delete-region (point-marker) (search-forward "self."))
1788 (setq input
(buffer-substring (point-min) (point-max)))))
1789 (python-shell-send-and-clear-output
1790 (format python-eldoc-string-code input
) process
))))
1791 (with-current-buffer (process-buffer process
)
1792 (when comint-last-prompt-overlay
1793 (delete-region comint-last-input-end
1794 (overlay-start comint-last-prompt-overlay
))))
1796 (not (string= help
"\n")))
1799 (defun python-eldoc-function ()
1800 "`eldoc-documentation-function' for Python.
1801 For this to work the best as possible you should call
1802 `python-shell-send-buffer' from time to time so context in
1803 inferior python process is updated properly."
1804 (python-eldoc--get-doc-at-point))
1806 (defun python-eldoc-at-point (symbol)
1807 "Get help on SYMBOL using `help'.
1808 Interactively, prompt for symbol."
1810 (let ((symbol (with-syntax-table python-dotty-syntax-table
1812 (enable-recursive-minibuffers t
))
1813 (list (read-string (if symbol
1814 (format "Describe symbol (default %s): " symbol
)
1815 "Describe symbol: ")
1817 (let ((process (python-shell-get-process)))
1819 (message "Eldoc needs an inferior Python process running.")
1820 (let ((temp-buffer-show-hook
1822 (toggle-read-only 1)
1823 (setq view-return-to-alist
1824 (list (cons (selected-window) help-return-method
))))))
1825 (with-output-to-temp-buffer (help-buffer)
1826 (with-current-buffer standard-output
1828 (python-eldoc--get-doc-at-point symbol process
))
1829 (help-print-return-message)))))))
1831 (add-hook 'inferior-python-mode-hook
1832 #'python-eldoc-setup
)
1837 (defun python-info-current-defun ()
1838 "Return name of surrounding function with Python compatible dotty syntax.
1839 This function is compatible to be used as
1840 `add-log-current-defun-function' since it returns nil if point is
1841 not inside a defun."
1847 (when (not (>= (current-indentation) python-indent-offset
))
1848 (while (and (not (eobp)) (forward-comment 1))))
1849 (while (and (not (equal 0 (current-indentation)))
1850 (python-beginning-of-innermost-defun))
1851 (back-to-indentation)
1852 (looking-at "\\(?:def\\|class\\) +\\([^(]+\\)[^:]+:\\s-*\n")
1853 (setq names
(cons (match-string-no-properties 1) names
)))))
1855 (mapconcat (lambda (string) string
) names
"."))))
1857 (defun python-info-closing-block ()
1858 "Return the point of the block that the current line closes."
1859 (let ((closing-word (save-excursion
1860 (back-to-indentation)
1862 (indentation (current-indentation)))
1863 (when (member closing-word python-indent-dedenters
)
1866 (while (and (> (current-indentation) indentation
)
1868 (not (back-to-indentation))
1870 (back-to-indentation)
1872 ((not (equal indentation
(current-indentation))) nil
)
1873 ((string= closing-word
"elif")
1874 (when (member (current-word) '("if" "elif"))
1876 ((string= closing-word
"else")
1877 (when (member (current-word) '("if" "elif" "except" "for" "while"))
1879 ((string= closing-word
"except")
1880 (when (member (current-word) '("try"))
1882 ((string= closing-word
"finally")
1883 (when (member (current-word) '("except" "else"))
1884 (point-marker))))))))
1886 (defun python-info-line-ends-backslash-p ()
1887 "Return non-nil if current line ends with backslash."
1888 (string= (or (ignore-errors
1891 (- (line-end-position) 1))) "") "\\"))
1893 (defun python-info-continuation-line-p ()
1894 "Return non-nil if current line is continuation of another."
1895 (or (python-info-line-ends-backslash-p)
1896 (string-match ",[[:space:]]*$" (buffer-substring
1897 (line-beginning-position)
1898 (line-end-position)))
1900 (let ((innermost-paren (progn
1901 (goto-char (line-end-position))
1902 (nth 1 (syntax-ppss)))))
1903 (when (and innermost-paren
1904 (and (<= (line-beginning-position) innermost-paren
)
1905 (>= (line-end-position) innermost-paren
)))
1906 (goto-char innermost-paren
)
1907 (looking-at (python-rx open-paren
(* space
) line-end
)))))
1909 (back-to-indentation)
1910 (nth 1 (syntax-ppss)))))
1912 (defun python-info-block-continuation-line-p ()
1913 "Return non-nil if current line is a continuation of a block."
1915 (while (and (not (bobp))
1916 (python-info-continuation-line-p))
1919 (back-to-indentation)
1920 (when (looking-at (python-rx block-start
))
1923 (defun python-info-assignment-continuation-line-p ()
1924 "Return non-nil if current line is a continuation of an assignment."
1926 (while (and (not (bobp))
1927 (python-info-continuation-line-p))
1930 (back-to-indentation)
1931 (when (and (not (looking-at (python-rx block-start
)))
1933 (and (re-search-forward (python-rx not-simple-operator
1935 not-simple-operator
)
1936 (line-end-position) t
)
1937 (not (syntax-ppss-context (syntax-ppss))))))
1942 (define-derived-mode python-mode fundamental-mode
"Python"
1943 "A major mode for editing Python files."
1944 (set (make-local-variable 'tab-width
) 8)
1945 (set (make-local-variable 'indent-tabs-mode
) nil
)
1947 (set (make-local-variable 'comment-start
) "# ")
1948 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
1950 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
1951 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
1953 (set (make-local-variable 'font-lock-defaults
)
1954 '(python-font-lock-keywords
1956 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords
)))
1958 (set (make-local-variable 'indent-line-function
) #'python-indent-line-function
)
1959 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
1961 (set (make-local-variable 'paragraph-start
) "\\s-*$")
1962 (set (make-local-variable 'fill-paragraph-function
) 'python-fill-paragraph-function
)
1964 (set (make-local-variable 'beginning-of-defun-function
)
1965 #'python-beginning-of-defun-function
)
1966 (set (make-local-variable 'end-of-defun-function
)
1967 #'python-end-of-defun-function
)
1969 (add-hook 'completion-at-point-functions
1970 'python-completion-complete-at-point nil
'local
)
1972 (set (make-local-variable 'add-log-current-defun-function
)
1973 #'python-info-current-defun
)
1975 (set (make-local-variable 'skeleton-further-elements
)
1977 (< '(backward-delete-char-untabify (min python-indent-offset
1979 (^
'(- (1+ (current-indentation))))))
1981 (set (make-local-variable 'eldoc-documentation-function
)
1982 #'python-eldoc-function
)
1984 (add-to-list 'hs-special-modes-alist
1985 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
1987 (python-end-of-defun-function)) nil
))
1989 (set (make-local-variable 'outline-regexp
)
1990 (python-rx (* space
) block-start
))
1991 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
1992 (set (make-local-variable 'outline-level
)
1994 "`outline-level' function for Python mode."
1995 (1+ (/ (current-indentation) python-indent-offset
))))
1997 (python-skeleton-add-menu-items)
1999 (when python-indent-guess-indent-offset
2000 (python-indent-guess-indent-offset)))
2004 ;;; python.el ends here