1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2018 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fgallina@gnu.org>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Package-Requires: ((emacs "24.1") (cl-lib "1.0"))
9 ;; Maintainer: emacs-devel@gnu.org
11 ;; Keywords: languages
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published
17 ;; by the Free Software Foundation, either version 3 of the License,
18 ;; or (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful, but
21 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 ;; General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
30 ;; Major mode for editing Python files with some fontification and
31 ;; indentation bits extracted from original Dave Love's python.el
32 ;; found in GNU/Emacs.
34 ;; Implements Syntax highlighting, Indentation, Movement, Shell
35 ;; interaction, Shell completion, Shell virtualenv support, Shell
36 ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
37 ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
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 electric-indent-mode
45 ;; is supported such that when inserting a colon the current line is
46 ;; dedented automatically if needed.
48 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
49 ;; properly implemented. There are also specialized
50 ;; `forward-sentence' and `backward-sentence' replacements called
51 ;; `python-nav-forward-block', `python-nav-backward-block'
52 ;; respectively which navigate between beginning of blocks of code.
53 ;; Extra functions `python-nav-forward-statement',
54 ;; `python-nav-backward-statement',
55 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
56 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
57 ;; `python-nav-if-name-main' are included but no bound to any key. At
58 ;; last but not least the specialized `python-nav-forward-sexp' allows
59 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
60 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
61 ;; enough, You can do that using the `python-mode-hook':
63 ;; (add-hook 'python-mode-hook
64 ;; (lambda () (setq forward-sexp-function nil)))
66 ;; Shell interaction: is provided and allows opening Python shells
67 ;; inside Emacs and executing any block of code of your current buffer
68 ;; in that inferior Python process.
70 ;; Besides that only the standard CPython (2.x and 3.x) shell and
71 ;; IPython are officially supported out of the box, the interaction
72 ;; should support any other readline based Python shells as well
73 ;; (e.g. Jython and PyPy have been reported to work). You can change
74 ;; your default interpreter and commandline arguments by setting the
75 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
76 ;; variables. This example enables IPython globally:
78 ;; (setq python-shell-interpreter "ipython"
79 ;; python-shell-interpreter-args "-i")
81 ;; Using the "console" subcommand to start IPython in server-client
82 ;; mode is known to fail intermittently due a bug on IPython itself
83 ;; (see URL `https://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
84 ;; There seems to be a race condition in the IPython server (A.K.A
85 ;; kernel) when code is sent while it is still initializing, sometimes
86 ;; causing the shell to get stalled. With that said, if an IPython
87 ;; kernel is already running, "console --existing" seems to work fine.
89 ;; Running IPython on Windows needs more tweaking. The way you should
90 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
91 ;; is as follows (of course you need to modify the paths according to
94 ;; (setq python-shell-interpreter "C:/Python27/python.exe"
95 ;; python-shell-interpreter-args
96 ;; "-i C:/Python27/Scripts/ipython-script.py")
98 ;; Missing or delayed output used to happen due to differences between
99 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
100 ;; See URL `https://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
102 ;; controls whether `python-shell-calculate-process-environment'
103 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
104 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
106 ;; The interaction relies upon having prompts for input (e.g. ">>> "
107 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
108 ;; IPython) detected properly. Failing that Emacs may hang but, in
109 ;; the case that happens, you can recover with \\[keyboard-quit]. To
110 ;; avoid this issue, a two-step prompt autodetection mechanism is
111 ;; provided: the first step is manual and consists of a collection of
112 ;; regular expressions matching common prompts for Python shells
113 ;; stored in `python-shell-prompt-input-regexps' and
114 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
115 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
116 ;; `python-shell-prompt-output-regexp' which are appended to the
117 ;; former automatically when a shell spawns; the second step is
118 ;; automatic and depends on the `python-shell-prompt-detect' helper
119 ;; function. See its docstring for details on global variables that
120 ;; modify its behavior.
122 ;; Shell completion: hitting tab will try to complete the current
123 ;; word. The two built-in mechanisms depend on Python's readline
124 ;; module: the "native" completion is tried first and is activated
125 ;; when `python-shell-completion-native-enable' is non-nil, the
126 ;; current `python-shell-interpreter' is not a member of the
127 ;; `python-shell-completion-native-disabled-interpreters' variable and
128 ;; `python-shell-completion-native-setup' succeeds; the "fallback" or
129 ;; "legacy" mechanism works by executing Python code in the background
130 ;; and enables auto-completion for shells that do not support
131 ;; receiving escape sequences (with some limitations, i.e. completion
132 ;; in blocks does not work). The code executed for the "fallback"
133 ;; completion can be found in `python-shell-completion-setup-code' and
134 ;; `python-shell-completion-string-code' variables. Their default
135 ;; values enable completion for both CPython and IPython, and probably
136 ;; any readline based shell (it's known to work with PyPy). If your
137 ;; Python installation lacks readline (like CPython for Windows),
138 ;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
139 ;; should suffice. To troubleshoot why you are not getting any
140 ;; completions, you can try the following in your Python shell:
142 ;; >>> import readline, rlcompleter
144 ;; If you see an error, then you need to either install pyreadline or
145 ;; setup custom code that avoids that dependency.
147 ;; Shell virtualenv support: The shell also contains support for
148 ;; virtualenvs and other special environment modifications thanks to
149 ;; `python-shell-process-environment' and `python-shell-exec-path'.
150 ;; These two variables allows you to modify execution paths and
151 ;; environment variables to make easy for you to setup virtualenv rules
152 ;; or behavior modifications when running shells. Here is an example
153 ;; of how to make shell processes to be run using the /path/to/env/
156 ;; (setq python-shell-process-environment
158 ;; (format "PATH=%s" (mapconcat
161 ;; (cons (getenv "PATH")
162 ;; '("/path/to/env/bin/")))
164 ;; "VIRTUAL_ENV=/path/to/env/"))
165 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
167 ;; Since the above is cumbersome and can be programmatically
168 ;; calculated, the variable `python-shell-virtualenv-root' is
169 ;; provided. When this variable is set with the path of the
170 ;; virtualenv to use, `process-environment' and `exec-path' get proper
171 ;; values in order to run shells inside the specified virtualenv. So
172 ;; the following will achieve the same as the previous example:
174 ;; (setq python-shell-virtualenv-root "/path/to/env/")
176 ;; Also the `python-shell-extra-pythonpaths' variable have been
177 ;; introduced as simple way of adding paths to the PYTHONPATH without
178 ;; affecting existing values.
180 ;; Shell package support: you can enable a package in the current
181 ;; shell so that relative imports work properly using the
182 ;; `python-shell-package-enable' command.
184 ;; Shell remote support: remote Python shells are started with the
185 ;; correct environment for files opened remotely through tramp, also
186 ;; respecting dir-local variables provided `enable-remote-dir-locals'
187 ;; is non-nil. The logic for this is transparently handled by the
188 ;; `python-shell-with-environment' macro.
190 ;; Shell syntax highlighting: when enabled current input in shell is
191 ;; highlighted. The variable `python-shell-font-lock-enable' controls
192 ;; activation of this feature globally when shells are started.
193 ;; Activation/deactivation can be also controlled on the fly via the
194 ;; `python-shell-font-lock-toggle' command.
196 ;; Pdb tracking: when you execute a block of code that contains some
197 ;; call to pdb (or ipdb) it will prompt the block of code and will
198 ;; follow the execution of pdb marking the current line with an arrow.
200 ;; Symbol completion: you can complete the symbol at point. It uses
201 ;; the shell completion in background so you should run
202 ;; `python-shell-send-buffer' from time to time to get better results.
204 ;; Skeletons: skeletons are provided for simple inserting of things like class,
205 ;; def, for, import, if, try, and while. These skeletons are
206 ;; integrated with abbrev. If you have `abbrev-mode' activated and
207 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
208 ;; the name of any of those defined and hit SPC, they will be
209 ;; automatically expanded. As an alternative you can use the defined
210 ;; skeleton commands: `python-skeleton-<foo>'.
212 ;; FFAP: You can find the filename for a given module when using ffap
213 ;; out of the box. This feature needs an inferior python shell
216 ;; Code check: Check the current file for errors with `python-check'
217 ;; using the program defined in `python-check-command'.
219 ;; Eldoc: returns documentation for object at point by using the
220 ;; inferior python subprocess to inspect its documentation. As you
221 ;; might guessed you should run `python-shell-send-buffer' from time
222 ;; to time to get better results too.
224 ;; Imenu: There are two index building functions to be used as
225 ;; `imenu-create-index-function': `python-imenu-create-index' (the
226 ;; default one, builds the alist in form of a tree) and
227 ;; `python-imenu-create-flat-index'. See also
228 ;; `python-imenu-format-item-label-function',
229 ;; `python-imenu-format-parent-item-label-function',
230 ;; `python-imenu-format-parent-item-jump-label-function' variables for
231 ;; changing the way labels are formatted in the tree version.
233 ;; If you used python-mode.el you may miss auto-indentation when
234 ;; inserting newlines. To achieve the same behavior you have two
237 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
238 ;; default) and use RET. If this mode is disabled use
239 ;; `newline-and-indent', bound to C-j.
241 ;; 2) Add the following hook in your .emacs:
243 ;; (add-hook 'python-mode-hook
245 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
247 ;; I'd recommend the first one since you'll get the same behavior for
248 ;; all modes out-of-the-box.
252 ;; Add this to your .emacs:
254 ;; (add-to-list 'load-path "/folder/containing/file")
261 (require 'ansi-color
)
267 ;; Avoid compiler warnings
268 (defvar view-return-to-alist
)
269 (defvar compilation-error-regexp-alist
)
270 (defvar outline-heading-end-regexp
)
272 (autoload 'comint-mode
"comint")
273 (autoload 'help-function-arglist
"help-fns")
276 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py[iw]?\\'") 'python-mode
))
278 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
281 "Python Language's flying circus support for Emacs."
284 :link
'(emacs-commentary-link "python"))
290 (unless (fboundp 'prog-first-column
)
291 (defun prog-first-column ()
297 (defvar python-mode-map
298 (let ((map (make-sparse-keymap)))
300 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
301 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
302 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
303 (define-key map
[remap mark-defun
] 'python-mark-defun
)
304 (define-key map
"\C-c\C-j" 'imenu
)
306 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
307 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
308 (define-key map
"\C-c<" 'python-indent-shift-left
)
309 (define-key map
"\C-c>" 'python-indent-shift-right
)
311 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
312 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
313 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
314 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
315 (define-key map
"\C-c\C-tm" 'python-skeleton-import
)
316 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
317 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
319 (define-key map
"\C-c\C-p" 'run-python
)
320 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
321 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
322 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
323 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
324 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
325 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
326 ;; Some util commands
327 (define-key map
"\C-c\C-v" 'python-check
)
328 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
329 (define-key map
"\C-c\C-d" 'python-describe-at-point
)
331 (substitute-key-definition 'complete-symbol
'completion-at-point
333 (easy-menu-define python-menu map
"Python Mode menu"
335 :help
"Python-specific Features"
336 ["Shift region left" python-indent-shift-left
:active mark-active
337 :help
"Shift region left by a single indentation step"]
338 ["Shift region right" python-indent-shift-right
:active mark-active
339 :help
"Shift region right by a single indentation step"]
341 ["Start of def/class" beginning-of-defun
342 :help
"Go to start of outermost definition around point"]
343 ["End of def/class" end-of-defun
344 :help
"Go to end of definition around point"]
345 ["Mark def/class" mark-defun
346 :help
"Mark outermost definition around point"]
347 ["Jump to def/class" imenu
348 :help
"Jump to a class or function definition"]
352 ["Start interpreter" run-python
353 :help
"Run inferior Python process in a separate buffer"]
354 ["Switch to shell" python-shell-switch-to-shell
355 :help
"Switch to running inferior Python process"]
356 ["Eval string" python-shell-send-string
357 :help
"Eval string in inferior Python session"]
358 ["Eval buffer" python-shell-send-buffer
359 :help
"Eval buffer in inferior Python session"]
360 ["Eval region" python-shell-send-region
361 :help
"Eval region in inferior Python session"]
362 ["Eval defun" python-shell-send-defun
363 :help
"Eval defun in inferior Python session"]
364 ["Eval file" python-shell-send-file
365 :help
"Eval file in inferior Python session"]
366 ["Debugger" pdb
:help
"Run pdb under GUD"]
368 ["Check file" python-check
369 :help
"Check file for errors"]
370 ["Help on symbol" python-eldoc-at-point
371 :help
"Get help on symbol at point"]
372 ["Complete symbol" completion-at-point
373 :help
"Complete symbol before point"]))
375 "Keymap for `python-mode'.")
378 ;;; Python specialized rx
381 (defconst python-rx-constituents
382 `((block-start .
,(rx symbol-start
383 (or "def" "class" "if" "elif" "else" "try"
384 "except" "finally" "for" "while" "with"
385 ;; Python 3.5+ PEP492
386 (and "async" (+ space
)
387 (or "def" "for" "with")))
389 (dedenter .
,(rx symbol-start
390 (or "elif" "else" "except" "finally")
392 (block-ender .
,(rx symbol-start
394 "break" "continue" "pass" "raise" "return")
396 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
398 (defun .
,(rx symbol-start
400 ;; Python 3.5+ PEP492
401 (and "async" (+ space
) "def"))
403 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
404 (+ space
) "==" (+ space
)
405 (any ?
' ?
\") "__main__" (any ?
' ?
\")
407 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
408 (open-paren .
,(rx (or "{" "[" "(")))
409 (close-paren .
,(rx (or "}" "]" ")")))
410 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
411 ;; FIXME: rx should support (not simple-operator).
412 (not-simple-operator .
,(rx
414 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
415 ;; FIXME: Use regexp-opt.
416 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
417 "=" "%" "**" "//" "<<" ">>" "<=" "!="
418 "==" ">=" "is" "not")))
419 ;; FIXME: Use regexp-opt.
420 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
421 ">>=" "<<=" "&=" "^=" "|=")))
422 (string-delimiter .
,(rx (and
423 ;; Match even number of backslashes.
424 (or (not (any ?
\\ ?
\' ?
\")) point
425 ;; Quotes might be preceded by a escaped quote.
426 (and (or (not (any ?
\\)) point
) ?
\\
427 (* ?
\\ ?
\\) (any ?
\' ?
\")))
429 ;; Match single or triple quotes of any kind.
430 (group (or "\"" "\"\"\"" "'" "'''")))))
431 (coding-cookie .
,(rx line-start ?
# (* space
)
433 ;; # coding=<encoding name>
434 (: "coding" (or ?
: ?
=) (* space
) (group-n 1 (+ (or word ?-
))))
435 ;; # -*- coding: <encoding name> -*-
436 (: "-*-" (* space
) "coding:" (* space
)
437 (group-n 1 (+ (or word ?-
))) (* space
) "-*-")
438 ;; # vim: set fileencoding=<encoding name> :
439 (: "vim:" (* space
) "set" (+ space
)
440 "fileencoding" (* space
) ?
= (* space
)
441 (group-n 1 (+ (or word ?-
))) (* space
) ":")))))
442 "Additional Python specific sexps for `python-rx'")
444 (defmacro python-rx
(&rest regexps
)
445 "Python mode specialized rx macro.
446 This variant of `rx' supports common Python named REGEXPS."
447 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
448 (cond ((null regexps
)
451 (rx-to-string `(and ,@regexps
) t
))
453 (rx-to-string (car regexps
) t
))))))
456 ;;; Font-lock and syntax
459 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
462 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
463 (and (nth 4 ppss
) (nth 8 ppss
))))
465 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
466 (and (nth 3 ppss
) (nth 8 ppss
))))
468 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
471 (defun python-syntax-context (type &optional syntax-ppss
)
472 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
473 TYPE can be `comment', `string' or `paren'. It returns the start
474 character address of the specified TYPE."
475 (declare (compiler-macro python-syntax--context-compiler-macro
))
476 (let ((ppss (or syntax-ppss
(syntax-ppss))))
478 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
479 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
480 (`paren
(nth 1 ppss
))
483 (defun python-syntax-context-type (&optional syntax-ppss
)
484 "Return the context type using SYNTAX-PPSS.
485 The type returned can be `comment', `string' or `paren'."
486 (let ((ppss (or syntax-ppss
(syntax-ppss))))
488 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
489 ((nth 1 ppss
) 'paren
))))
491 (defsubst python-syntax-comment-or-string-p
(&optional ppss
)
492 "Return non-nil if PPSS is inside comment or string."
493 (nth 8 (or ppss
(syntax-ppss))))
495 (defsubst python-syntax-closing-paren-p
()
496 "Return non-nil if char after point is a closing paren."
497 (eql (syntax-class (syntax-after (point)))
498 (syntax-class (string-to-syntax ")"))))
500 (define-obsolete-function-alias
501 'python-info-ppss-context
#'python-syntax-context
"24.3")
503 (define-obsolete-function-alias
504 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
506 (define-obsolete-function-alias
507 'python-info-ppss-comment-or-string-p
508 #'python-syntax-comment-or-string-p
"24.3")
510 (defun python-font-lock-syntactic-face-function (state)
511 "Return syntactic face given STATE."
513 (if (python-info-docstring-p state
)
515 font-lock-string-face
)
516 font-lock-comment-face
))
518 (defvar python-font-lock-keywords
522 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
523 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
524 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
529 ;; False, None, and True are listed as keywords on the Python 3
530 ;; documentation, but since they also qualify as constants they are
531 ;; fontified like that in order to keep font-lock consistent between
534 ;; Python 3.5+ PEP492
535 (and "async" (+ space
) (or "def" "for" "with"))
541 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
542 (1 font-lock-function-name-face
))
544 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
545 (1 font-lock-type-face
))
549 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
550 ;; copyright, license, credits, quit and exit are added by the site
551 ;; module and they are not intended to be used in programs
552 "copyright" "credits" "exit" "license" "quit")
553 symbol-end
) . font-lock-constant-face
)
555 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
556 (0+ "." (1+ (or word ?_
)))))
557 (1 font-lock-type-face
))
558 ;; Builtin Exceptions
562 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
563 "BufferError" "BytesWarning" "DeprecationWarning" "EOFError"
564 "EnvironmentError" "Exception" "FloatingPointError" "FutureWarning"
565 "GeneratorExit" "IOError" "ImportError" "ImportWarning"
566 "IndentationError" "IndexError" "KeyError" "KeyboardInterrupt"
567 "LookupError" "MemoryError" "NameError" "NotImplementedError"
568 "OSError" "OverflowError" "PendingDeprecationWarning"
569 "ReferenceError" "RuntimeError" "RuntimeWarning" "StopIteration"
570 "SyntaxError" "SyntaxWarning" "SystemError" "SystemExit" "TabError"
571 "TypeError" "UnboundLocalError" "UnicodeDecodeError"
572 "UnicodeEncodeError" "UnicodeError" "UnicodeTranslateError"
573 "UnicodeWarning" "UserWarning" "ValueError" "Warning"
578 "BlockingIOError" "BrokenPipeError" "ChildProcessError"
579 "ConnectionAbortedError" "ConnectionError" "ConnectionRefusedError"
580 "ConnectionResetError" "FileExistsError" "FileNotFoundError"
581 "InterruptedError" "IsADirectoryError" "NotADirectoryError"
582 "PermissionError" "ProcessLookupError" "RecursionError"
583 "ResourceWarning" "StopAsyncIteration" "TimeoutError"
585 "VMSError" "WindowsError"
587 symbol-end
) . font-lock-type-face
)
591 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
592 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
593 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
594 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
595 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
596 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
597 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
598 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
601 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
602 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
605 "ascii" "bytearray" "bytes" "exec"
607 "__all__" "__doc__" "__name__" "__package__")
608 symbol-end
) . font-lock-builtin-face
)
610 ;; support for a = b = c = 5
612 (let ((re (python-rx (group (+ (any word ?. ?_
)))
613 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
614 assignment-operator
))
616 (while (and (setq res
(re-search-forward re limit t
))
617 (or (python-syntax-context 'paren
)
618 (equal (char-after (point)) ?
=))))
620 (1 font-lock-variable-name-face nil nil
))
621 ;; support for a, b, c = (1, 2, 3)
623 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
624 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
625 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
626 assignment-operator
))
628 (while (and (setq res
(re-search-forward re limit t
))
629 (goto-char (match-end 1))
630 (python-syntax-context 'paren
)))
632 (1 font-lock-variable-name-face nil nil
))))
634 (defconst python-syntax-propertize-function
635 (syntax-propertize-rules
636 ((python-rx string-delimiter
)
637 (0 (ignore (python-syntax-stringify))))))
639 (defvar python-prettify-symbols-alist
643 "Value for `prettify-symbols-alist' in `python-mode'.")
645 (define-obsolete-variable-alias 'python--prettify-symbols-alist
646 'python-prettify-symbols-alist
"26.1")
648 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
649 "Count number of quotes around point (max is 3).
650 QUOTE-CHAR is the quote char to count. Optional argument POINT is
651 the point where scan starts (defaults to current point), and LIMIT
652 is used to limit the scan."
655 (or (not limit
) (< (+ point i
) limit
))
656 (eq (char-after (+ point i
)) quote-char
))
660 (defun python-syntax-stringify ()
661 "Put `syntax-table' property correctly on single/triple quotes."
662 (let* ((num-quotes (length (match-string-no-properties 1)))
664 (backward-char num-quotes
)
666 (forward-char num-quotes
)))
667 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
668 (quote-starting-pos (- (point) num-quotes
))
669 (quote-ending-pos (point))
672 (python-syntax-count-quotes
673 (char-before) string-start quote-starting-pos
))))
674 (cond ((and string-start
(= num-closing-quotes
0))
675 ;; This set of quotes doesn't match the string starting
679 ;; This set of quotes delimit the start of a string.
680 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
681 'syntax-table
(string-to-syntax "|")))
682 ((= num-quotes num-closing-quotes
)
683 ;; This set of quotes delimit the end of a string.
684 (put-text-property (1- quote-ending-pos
) quote-ending-pos
685 'syntax-table
(string-to-syntax "|")))
686 ((> num-quotes num-closing-quotes
)
687 ;; This may only happen whenever a triple quote is closing
688 ;; a single quoted string. Add string delimiter syntax to
690 (put-text-property quote-starting-pos quote-ending-pos
691 'syntax-table
(string-to-syntax "|"))))))
693 (defvar python-mode-syntax-table
694 (let ((table (make-syntax-table)))
695 ;; Give punctuation syntax to ASCII that normally has symbol
696 ;; syntax or has word syntax and isn't a letter.
697 (let ((symbol (string-to-syntax "_"))
698 (sst (standard-syntax-table)))
701 (if (equal symbol
(aref sst i
))
702 (modify-syntax-entry i
"." table
)))))
703 (modify-syntax-entry ?$
"." table
)
704 (modify-syntax-entry ?%
"." table
)
706 (modify-syntax-entry ?
# "<" table
)
707 (modify-syntax-entry ?
\n ">" table
)
708 (modify-syntax-entry ?
' "\"" table
)
709 (modify-syntax-entry ?
` "$" table
)
711 "Syntax table for Python files.")
713 (defvar python-dotty-syntax-table
714 (let ((table (make-syntax-table python-mode-syntax-table
)))
715 (modify-syntax-entry ?.
"w" table
)
716 (modify-syntax-entry ?_
"w" table
)
718 "Dotty syntax table for Python files.
719 It makes underscores and dots word constituent chars.")
724 (define-obsolete-variable-alias
725 'python-indent
'python-indent-offset
"24.3")
727 (defcustom python-indent-offset
4
728 "Default indentation offset for Python."
733 (define-obsolete-variable-alias
734 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
736 (defcustom python-indent-guess-indent-offset t
737 "Non-nil tells Python mode to guess `python-indent-offset' value."
742 (defcustom python-indent-guess-indent-offset-verbose t
743 "Non-nil means to emit a warning when indentation guessing fails."
749 (defcustom python-indent-trigger-commands
750 '(indent-for-tab-command yas-expand yas
/expand
)
751 "Commands that might trigger a `python-indent-line' call."
752 :type
'(repeat symbol
)
755 (defcustom python-indent-def-block-scale
2
756 "Multiplier applied to indentation inside multi-line def blocks."
761 (defvar python-indent-current-level
0
762 "Deprecated var available for compatibility.")
764 (defvar python-indent-levels
'(0)
765 "Deprecated var available for compatibility.")
767 (make-obsolete-variable
768 'python-indent-current-level
769 "The indentation API changed to avoid global state.
770 The function `python-indent-calculate-levels' does not use it
771 anymore. If you were defadvising it and or depended on this
772 variable for indentation customizations, refactor your code to
773 work on `python-indent-calculate-indentation' instead."
776 (make-obsolete-variable
777 'python-indent-levels
778 "The indentation API changed to avoid global state.
779 The function `python-indent-calculate-levels' does not use it
780 anymore. If you were defadvising it and or depended on this
781 variable for indentation customizations, refactor your code to
782 work on `python-indent-calculate-indentation' instead."
785 (defun python-indent-guess-indent-offset ()
786 "Guess and set `python-indent-offset' for the current buffer."
791 (goto-char (point-min))
793 (while (and (not block-end
)
795 (python-rx line-start block-start
) nil t
))
797 (not (python-syntax-context-type))
799 (goto-char (line-end-position))
800 (python-util-forward-comment -
1)
801 (if (equal (char-before) ?
:)
804 (when (python-info-block-continuation-line-p)
805 (while (and (python-info-continuation-line-p)
808 (python-util-forward-comment -
1)
809 (when (equal (char-before) ?
:)
811 (setq block-end
(point-marker))))
814 (goto-char block-end
)
815 (python-util-forward-comment)
816 (current-indentation))))
817 (if (and indentation
(not (zerop indentation
)))
818 (set (make-local-variable 'python-indent-offset
) indentation
)
819 (when python-indent-guess-indent-offset-verbose
820 (message "Can't guess python-indent-offset, using defaults: %s"
821 python-indent-offset
))))))))
823 (defun python-indent-context ()
824 "Get information about the current indentation context.
825 Context is returned in a cons with the form (STATUS . START).
827 STATUS can be one of the following:
833 - Point is after a comment line.
834 - START is the position of the \"#\" character.
836 - Point is inside string.
837 - START is the position of the first quote that starts it.
839 - No possible indentation case matches.
840 - START is always zero.
843 - Fallback case when point is inside paren.
844 - START is the first non space char position *after* the open paren.
845 :inside-paren-at-closing-nested-paren
846 - Point is on a line that contains a nested paren closer.
847 - START is the position of the open paren it closes.
848 :inside-paren-at-closing-paren
849 - Point is on a line that contains a paren closer.
850 - START is the position of the open paren.
851 :inside-paren-newline-start
852 - Point is inside a paren with items starting in their own line.
853 - START is the position of the open paren.
854 :inside-paren-newline-start-from-block
855 - Point is inside a paren with items starting in their own line
857 - START is the position of the open paren.
860 - Fallback case when point is after backslash.
861 - START is the char after the position of the backslash.
862 :after-backslash-assignment-continuation
863 - Point is after a backslashed assignment.
864 - START is the char after the position of the backslash.
865 :after-backslash-block-continuation
866 - Point is after a backslashed block continuation.
867 - START is the char after the position of the backslash.
868 :after-backslash-dotted-continuation
869 - Point is after a backslashed dotted continuation. Previous
870 line must contain a dot to align with.
871 - START is the char after the position of the backslash.
872 :after-backslash-first-line
873 - First line following a backslashed continuation.
874 - START is the char after the position of the backslash.
877 - Point is after a line containing a block ender.
878 - START is the position where the ender starts.
880 - Point is after a line starting a block.
881 - START is the position where the block starts.
883 - Point is after a simple line.
884 - START is the position where the previous line starts.
885 :at-dedenter-block-start
886 - Point is on a line starting a dedenter block.
887 - START is the position where the dedenter block starts."
888 (let ((ppss (save-excursion
892 ;; Beginning of buffer.
893 ((= (line-number-at-pos) 1)
896 ((let ((start (python-syntax-context 'string ppss
)))
898 (cons (if (python-info-docstring-p)
900 :inside-string
) start
))))
902 ((let* ((start (python-syntax-context 'paren ppss
))
909 (= (line-number-at-pos)
911 (python-util-forward-comment)
912 (line-number-at-pos))))))))
915 ;; Current line only holds the closing paren.
917 (skip-syntax-forward " ")
918 (when (and (python-syntax-closing-paren-p)
921 (not (python-syntax-context 'paren
))))
922 (cons :inside-paren-at-closing-paren start
))))
923 ;; Current line only holds a closing paren for nested.
925 (back-to-indentation)
926 (python-syntax-closing-paren-p))
927 (cons :inside-paren-at-closing-nested-paren start
))
928 ;; This line starts from a opening block in its own line.
934 (back-to-indentation)
935 (looking-at (python-rx block-start
))))
937 :inside-paren-newline-start-from-block start
))))
939 (cons :inside-paren-newline-start start
))
941 (t (cons :inside-paren
943 (goto-char (1+ start
))
944 (skip-syntax-forward "(" 1)
945 (skip-syntax-forward " ")
948 ((let ((start (when (not (python-syntax-comment-or-string-p ppss
))
949 (python-info-line-ends-backslash-p
950 (1- (line-number-at-pos))))))
953 ;; Continuation of dotted expression.
955 (back-to-indentation)
956 (when (eq (char-after) ?\.
)
957 ;; Move point back until it's not inside a paren.
961 (python-syntax-context 'paren
))))
962 (goto-char (line-end-position))
963 (while (and (search-backward
964 "." (line-beginning-position) t
)
965 (python-syntax-context-type)))
966 ;; Ensure previous statement has dot to align with.
967 (when (and (eq (char-after) ?\.
)
968 (not (python-syntax-context-type)))
969 (cons :after-backslash-dotted-continuation
(point))))))
970 ;; Continuation of block definition.
971 ((let ((block-continuation-start
972 (python-info-block-continuation-line-p)))
973 (when block-continuation-start
975 (goto-char block-continuation-start
)
977 (python-rx block-start
(* space
))
978 (line-end-position) t
)
979 (cons :after-backslash-block-continuation
(point))))))
980 ;; Continuation of assignment.
981 ((let ((assignment-continuation-start
982 (python-info-assignment-continuation-line-p)))
983 (when assignment-continuation-start
985 (goto-char assignment-continuation-start
)
986 (cons :after-backslash-assignment-continuation
(point))))))
987 ;; First line after backslash continuation start.
990 (when (or (= (line-number-at-pos) 1)
991 (not (python-info-beginning-of-backslash
992 (1- (line-number-at-pos)))))
993 (cons :after-backslash-first-line start
))))
995 (t (cons :after-backslash start
))))))
996 ;; After beginning of block.
997 ((let ((start (save-excursion
998 (back-to-indentation)
999 (python-util-forward-comment -
1)
1000 (when (equal (char-before) ?
:)
1001 (python-nav-beginning-of-block)))))
1003 (cons :after-block-start start
))))
1004 ;; At dedenter statement.
1005 ((let ((start (python-info-dedenter-statement-p)))
1007 (cons :at-dedenter-block-start start
))))
1008 ;; After normal line, comment or ender (default case).
1010 (back-to-indentation)
1011 (skip-chars-backward " \t\n")
1014 (python-nav-beginning-of-statement)
1016 (cond ((python-info-current-line-comment-p)
1019 (goto-char (line-end-position))
1020 (python-util-forward-comment -
1)
1021 (python-nav-beginning-of-statement)
1022 (looking-at (python-rx block-ender
)))
1027 (defun python-indent--calculate-indentation ()
1028 "Internal implementation of `python-indent-calculate-indentation'.
1029 May return an integer for the maximum possible indentation at
1030 current context or a list of integers. The latter case is only
1031 happening for :at-dedenter-block-start context since the
1032 possibilities can be narrowed to specific indentation points."
1034 (pcase (python-indent-context)
1035 (`(:no-indent .
,_
) (prog-first-column)) ; usually 0
1040 :inside-paren-at-closing-paren
1041 :inside-paren-at-closing-nested-paren
) .
,start
)
1042 ;; Copy previous indentation.
1044 (current-indentation))
1045 (`(:inside-docstring .
,start
)
1046 (let* ((line-indentation (current-indentation))
1049 (current-indentation))))
1050 (max line-indentation base-indent
)))
1051 (`(,(or :after-block-start
1052 :after-backslash-first-line
1053 :after-backslash-assignment-continuation
1054 :inside-paren-newline-start
) .
,start
)
1055 ;; Add one indentation level.
1057 (+ (current-indentation) python-indent-offset
))
1058 (`(,(or :inside-paren
1059 :after-backslash-block-continuation
1060 :after-backslash-dotted-continuation
) .
,start
)
1061 ;; Use the column given by the context.
1064 (`(:after-block-end .
,start
)
1065 ;; Subtract one indentation level.
1067 (- (current-indentation) python-indent-offset
))
1068 (`(:at-dedenter-block-start .
,_
)
1069 ;; List all possible indentation levels from opening blocks.
1070 (let ((opening-block-start-points
1071 (python-info-dedenter-opening-block-positions)))
1072 (if (not opening-block-start-points
)
1073 (prog-first-column) ; if not found default to first column
1074 (mapcar (lambda (pos)
1077 (current-indentation)))
1078 opening-block-start-points
))))
1079 (`(,(or :inside-paren-newline-start-from-block
) .
,start
)
1081 (+ (current-indentation)
1082 (* python-indent-offset python-indent-def-block-scale
))))))
1084 (defun python-indent--calculate-levels (indentation)
1085 "Calculate levels list given INDENTATION.
1086 Argument INDENTATION can either be an integer or a list of
1087 integers. Levels are returned in ascending order, and in the
1088 case INDENTATION is a list, this order is enforced."
1089 (if (listp indentation
)
1090 (sort (copy-sequence indentation
) #'<)
1091 (nconc (number-sequence (prog-first-column) (1- indentation
)
1092 python-indent-offset
)
1093 (list indentation
))))
1095 (defun python-indent--previous-level (levels indentation
)
1096 "Return previous level from LEVELS relative to INDENTATION."
1097 (let* ((levels (sort (copy-sequence levels
) #'>))
1098 (default (car levels
)))
1100 (dolist (level levels
)
1101 (when (funcall #'< level indentation
)
1102 (throw 'return level
)))
1105 (defun python-indent-calculate-indentation (&optional previous
)
1106 "Calculate indentation.
1107 Get indentation of PREVIOUS level when argument is non-nil.
1108 Return the max level of the cycle when indentation reaches the
1110 (let* ((indentation (python-indent--calculate-indentation))
1111 (levels (python-indent--calculate-levels indentation
)))
1113 (python-indent--previous-level levels
(current-indentation))
1115 (apply #'max levels
)
1116 (prog-first-column)))))
1118 (defun python-indent-line (&optional previous
)
1119 "Internal implementation of `python-indent-line-function'.
1120 Use the PREVIOUS level when argument is non-nil, otherwise indent
1121 to the maximum available level. When indentation is the minimum
1122 possible and PREVIOUS is non-nil, cycle back to the maximum
1124 (let ((follow-indentation-p
1125 ;; Check if point is within indentation.
1126 (and (<= (line-beginning-position) (point))
1127 (>= (+ (line-beginning-position)
1128 (current-indentation))
1132 (python-indent-calculate-indentation previous
))
1133 (python-info-dedenter-opening-block-message))
1134 (when follow-indentation-p
1135 (back-to-indentation))))
1137 (defun python-indent-calculate-levels ()
1138 "Return possible indentation levels."
1139 (python-indent--calculate-levels
1140 (python-indent--calculate-indentation)))
1142 (defun python-indent-line-function ()
1143 "`indent-line-function' for Python mode.
1144 When the variable `last-command' is equal to one of the symbols
1145 inside `python-indent-trigger-commands' it cycles possible
1146 indentation levels from right to left."
1148 (and (memq this-command python-indent-trigger-commands
)
1149 (eq last-command this-command
))))
1151 (defun python-indent-dedent-line ()
1152 "De-indent current line."
1154 (when (and (not (bolp))
1155 (not (python-syntax-comment-or-string-p))
1156 (= (current-indentation) (current-column)))
1157 (python-indent-line t
)
1160 (defun python-indent-dedent-line-backspace (arg)
1161 "De-indent current line.
1162 Argument ARG is passed to `backward-delete-char-untabify' when
1163 point is not in between the indentation."
1165 (unless (python-indent-dedent-line)
1166 (backward-delete-char-untabify arg
)))
1168 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1170 (defun python-indent-region (start end
)
1171 "Indent a Python region automagically.
1173 Called from a program, START and END specify the region to indent."
1174 (let ((deactivate-mark nil
))
1177 (setq end
(point-marker))
1179 (or (bolp) (forward-line 1))
1180 (while (< (point) end
)
1181 (or (and (bolp) (eolp))
1183 ;; Skip if previous line is empty or a comment.
1185 (let ((line-is-comment-p
1186 (python-info-current-line-comment-p)))
1189 (or (and (python-info-current-line-comment-p)
1190 ;; Unless this line is a comment too.
1191 (not line-is-comment-p
))
1192 (python-info-current-line-empty-p)))))
1193 ;; Don't mess with strings, unless it's the
1194 ;; enclosing set of quotes or a docstring.
1195 (or (not (python-syntax-context 'string
))
1199 (current-indentation)
1200 (python-syntax-count-quotes (char-after) (point))))
1201 (string-to-syntax "|"))
1202 (python-info-docstring-p))
1203 ;; Skip if current line is a block start, a
1204 ;; dedenter or block ender.
1206 (back-to-indentation)
1209 (or block-start dedenter block-ender
))))))
1210 (python-indent-line)))
1212 (move-marker end nil
))))
1214 (defun python-indent-shift-left (start end
&optional count
)
1215 "Shift lines contained in region START END by COUNT columns to the left.
1216 COUNT defaults to `python-indent-offset'. If region isn't
1217 active, the current line is shifted. The shifted region includes
1218 the lines in which START and END lie. An error is signaled if
1219 any lines in the region are indented less than COUNT columns."
1222 (list (region-beginning) (region-end) current-prefix-arg
)
1223 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1225 (setq count
(prefix-numeric-value count
))
1226 (setq count python-indent-offset
))
1228 (let ((deactivate-mark nil
))
1231 (while (< (point) end
)
1232 (if (and (< (current-indentation) count
)
1233 (not (looking-at "[ \t]*$")))
1234 (user-error "Can't shift all lines enough"))
1236 (indent-rigidly start end
(- count
))))))
1238 (defun python-indent-shift-right (start end
&optional count
)
1239 "Shift lines contained in region START END by COUNT columns to the right.
1240 COUNT defaults to `python-indent-offset'. If region isn't
1241 active, the current line is shifted. The shifted region includes
1242 the lines in which START and END lie."
1245 (list (region-beginning) (region-end) current-prefix-arg
)
1246 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1247 (let ((deactivate-mark nil
))
1248 (setq count
(if count
(prefix-numeric-value count
)
1249 python-indent-offset
))
1250 (indent-rigidly start end count
)))
1252 (defun python-indent-post-self-insert-function ()
1253 "Adjust indentation after insertion of some characters.
1254 This function is intended to be added to `post-self-insert-hook.'
1255 If a line renders a paren alone, after adding a char before it,
1256 the line will be re-indented automatically if needed."
1257 (when (and electric-indent-mode
1258 (eq (char-before) last-command-event
)
1259 (not (python-syntax-context 'string
))
1262 (not (python-syntax-context 'string
(syntax-ppss)))))
1264 ;; Electric indent inside parens
1267 (let ((paren-start (python-syntax-context 'paren
)))
1268 ;; Check that point is inside parens.
1271 ;; Filter the case where input is happening in the same
1272 ;; line where the open paren is.
1273 (= (line-number-at-pos)
1274 (line-number-at-pos paren-start
)))))
1275 ;; When content has been added before the closing paren or a
1276 ;; comma has been inserted, it's ok to do the trick.
1278 (memq (char-after) '(?\
) ?\
] ?\
}))
1279 (eq (char-before) ?
,)))
1281 (goto-char (line-beginning-position))
1282 (let ((indentation (python-indent-calculate-indentation)))
1283 (when (and (numberp indentation
) (< (current-indentation) indentation
))
1284 (indent-line-to indentation
)))))
1286 ((and (eq ?
: last-command-event
)
1287 (memq ?
: electric-indent-chars
)
1288 (not current-prefix-arg
)
1289 ;; Trigger electric colon only at end of line
1291 ;; Avoid re-indenting on extra colon
1292 (not (equal ?
: (char-before (1- (point)))))
1293 (not (python-syntax-comment-or-string-p)))
1294 ;; Just re-indent dedenters
1295 (let ((dedenter-pos (python-info-dedenter-statement-p))
1296 (current-pos (point)))
1299 (goto-char dedenter-pos
)
1300 (python-indent-line)
1301 (unless (= (line-number-at-pos dedenter-pos
)
1302 (line-number-at-pos current-pos
))
1303 ;; Reindent region if this is a multiline statement
1304 (python-indent-region dedenter-pos current-pos
)))))))))
1309 (defun python-mark-defun (&optional allow-extend
)
1310 "Put mark at end of this defun, point at beginning.
1311 The defun marked is the one that contains point or follows point.
1313 Interactively (or with ALLOW-EXTEND non-nil), if this command is
1314 repeated or (in Transient Mark mode) if the mark is active, it
1315 marks the next defun after the ones already marked."
1317 (when (python-info-looking-at-beginning-of-defun)
1319 (mark-defun allow-extend))
1324 (defvar python-nav-beginning-of-defun-regexp
1325 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1326 "Regexp matching class or function definition.
1327 The name of the defun should be grouped so it can be retrieved
1328 via `match-string'.")
1330 (defun python-nav--beginning-of-defun (&optional arg
)
1331 "Internal implementation of `python-nav-beginning-of-defun'.
1332 With positive ARG search backwards, else search forwards."
1333 (when (or (null arg
) (= arg
0)) (setq arg
1))
1334 (let* ((re-search-fn (if (> arg
0)
1335 #'re-search-backward
1336 #'re-search-forward
))
1337 (line-beg-pos (line-beginning-position))
1338 (line-content-start (+ line-beg-pos
(current-indentation)))
1339 (pos (point-marker))
1344 (not (python-info-looking-at-beginning-of-defun))
1345 (python-nav-backward-block)))
1346 (or (and (python-info-looking-at-beginning-of-defun)
1347 (+ (current-indentation) python-indent-offset
))
1351 (when (and (< arg
0)
1352 (python-info-looking-at-beginning-of-defun))
1354 (while (and (funcall re-search-fn
1355 python-nav-beginning-of-defun-regexp nil t
)
1356 (or (python-syntax-context-type)
1357 ;; Handle nested defuns when moving
1358 ;; backwards by checking indentation.
1360 (not (= (current-indentation) 0))
1361 (>= (current-indentation) beg-indentation
)))))
1362 (and (python-info-looking-at-beginning-of-defun)
1363 (or (not (= (line-number-at-pos pos
)
1364 (line-number-at-pos)))
1365 (and (>= (point) line-beg-pos
)
1366 (<= (point) line-content-start
)
1367 (> pos line-content-start
)))))))
1369 (or (beginning-of-line 1) t
)
1370 (and (goto-char pos
) nil
))))
1372 (defun python-nav-beginning-of-defun (&optional arg
)
1373 "Move point to `beginning-of-defun'.
1374 With positive ARG search backwards else search forward.
1375 ARG nil or 0 defaults to 1. When searching backwards,
1376 nested defuns are handled with care depending on current
1377 point position. Return non-nil if point is moved to
1378 `beginning-of-defun'."
1379 (when (or (null arg
) (= arg
0)) (setq arg
1))
1381 (while (and (not (= arg
0))
1382 (let ((keep-searching-p
1383 (python-nav--beginning-of-defun arg)))
1384 (when (and keep-searching-p
(null found
))
1387 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1390 (defun python-nav-end-of-defun ()
1391 "Move point to the end of def or class.
1392 Returns nil if point is not in a def or class."
1394 (let ((beg-defun-indent)
1396 (when (or (python-info-looking-at-beginning-of-defun)
1397 (python-nav-beginning-of-defun 1)
1398 (python-nav-beginning-of-defun -1))
1399 (setq beg-defun-indent
(current-indentation))
1401 (python-nav-end-of-statement)
1402 (python-util-forward-comment 1)
1403 (and (> (current-indentation) beg-defun-indent
)
1405 (python-util-forward-comment -
1)
1407 ;; Ensure point moves forward.
1408 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1410 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1411 "Move point using FN avoiding places with specific context.
1412 FN must take no arguments. POSCOMPFN is a two arguments function
1413 used to compare current and previous point after it is moved
1414 using FN, this is normally a less-than or greater-than
1415 comparison. Optional argument CONTEXTFN defaults to
1416 `python-syntax-context-type' and is used for checking current
1417 point context, it must return a non-nil value if this point must
1419 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1420 (start-pos (point-marker))
1425 (and (funcall fn
) (point-marker)))
1426 (context (funcall contextfn
)))
1427 (cond ((and (not context
) newpos
1428 (or (and (not prev-pos
) newpos
)
1429 (and prev-pos newpos
1430 (funcall poscompfn newpos prev-pos
))))
1431 (throw 'found
(point-marker)))
1432 ((and newpos context
)
1433 (setq prev-pos
(point)))
1434 (t (when (not newpos
) (goto-char start-pos
))
1435 (throw 'found nil
))))))))
1437 (defun python-nav--forward-defun (arg)
1438 "Internal implementation of python-nav-{backward,forward}-defun.
1439 Uses ARG to define which function to call, and how many times
1442 (while (and (> arg
0)
1444 (python-nav--syntactically
1447 python-nav-beginning-of-defun-regexp nil t
))
1449 (setq arg
(1- arg
)))
1450 (while (and (< arg
0)
1452 (python-nav--syntactically
1455 python-nav-beginning-of-defun-regexp nil t
))
1457 (setq arg
(1+ arg
)))
1460 (defun python-nav-backward-defun (&optional arg
)
1461 "Navigate to closer defun backward ARG times.
1462 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1463 nested definitions."
1465 (python-nav--forward-defun (- (or arg
1))))
1467 (defun python-nav-forward-defun (&optional arg
)
1468 "Navigate to closer defun forward ARG times.
1469 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1470 nested definitions."
1472 (python-nav--forward-defun (or arg
1)))
1474 (defun python-nav-beginning-of-statement ()
1475 "Move to start of current statement."
1478 (let* ((ppss (syntax-ppss))
1481 (python-syntax-context 'paren ppss
)
1482 (python-syntax-context 'string ppss
))))
1485 (goto-char context-point
)
1486 (python-nav-beginning-of-statement))
1489 (python-info-line-ends-backslash-p))
1491 (python-nav-beginning-of-statement))))
1492 (back-to-indentation)
1495 (defun python-nav-end-of-statement (&optional noend
)
1496 "Move to end of current statement.
1497 Optional argument NOEND is internal and makes the logic to not
1498 jump to the end of line when moving forward searching for the end
1501 (let (string-start bs-pos
(last-string-end 0))
1502 (while (and (or noend
(goto-char (line-end-position)))
1504 (cond ((setq string-start
(python-syntax-context 'string
))
1505 ;; The assertion can only fail if syntax table
1506 ;; text properties and the `syntax-ppss' cache
1507 ;; are somehow out of whack. This has been
1508 ;; observed when using `syntax-ppss' during
1510 (cl-assert (> string-start last-string-end
)
1512 "Overlapping strings detected")
1513 (goto-char string-start
)
1514 (if (python-syntax-context 'paren
)
1515 ;; Ended up inside a paren, roll again.
1516 (python-nav-end-of-statement t
)
1517 ;; This is not inside a paren, move to the
1518 ;; end of this string.
1519 (goto-char (+ (point)
1520 (python-syntax-count-quotes
1521 (char-after (point)) (point))))
1522 (setq last-string-end
1523 (or (re-search-forward
1524 (rx (syntax string-delimiter
)) nil t
)
1525 (goto-char (point-max))))))
1526 ((python-syntax-context 'paren
)
1527 ;; The statement won't end before we've escaped
1528 ;; at least one level of parenthesis.
1530 (goto-char (scan-lists (point) 1 -
1))
1531 (scan-error (goto-char (nth 3 err
)))))
1532 ((setq bs-pos
(python-info-line-ends-backslash-p))
1534 (forward-line 1))))))
1537 (defun python-nav-backward-statement (&optional arg
)
1538 "Move backward to previous statement.
1539 With ARG, repeat. See `python-nav-forward-statement'."
1541 (or arg
(setq arg
1))
1542 (python-nav-forward-statement (- arg
)))
1544 (defun python-nav-forward-statement (&optional arg
)
1545 "Move forward to next statement.
1546 With ARG, repeat. With negative argument, move ARG times
1547 backward to previous statement."
1549 (or arg
(setq arg
1))
1551 (python-nav-end-of-statement)
1552 (python-util-forward-comment)
1553 (python-nav-beginning-of-statement)
1554 (setq arg
(1- arg
)))
1556 (python-nav-beginning-of-statement)
1557 (python-util-forward-comment -
1)
1558 (python-nav-beginning-of-statement)
1559 (setq arg
(1+ arg
))))
1561 (defun python-nav-beginning-of-block ()
1562 "Move to start of current block."
1564 (let ((starting-pos (point)))
1566 (python-nav-beginning-of-statement)
1567 (looking-at (python-rx block-start
)))
1569 ;; Go to first line beginning a statement
1570 (while (and (not (bobp))
1571 (or (and (python-nav-beginning-of-statement) nil
)
1572 (python-info-current-line-comment-p)
1573 (python-info-current-line-empty-p)))
1575 (let ((block-matching-indent
1576 (- (current-indentation) python-indent-offset
)))
1578 (and (python-nav-backward-block)
1579 (> (current-indentation) block-matching-indent
)))
1580 (if (and (looking-at (python-rx block-start
))
1581 (= (current-indentation) block-matching-indent
))
1583 (and (goto-char starting-pos
) nil
))))))
1585 (defun python-nav-end-of-block ()
1586 "Move to end of current block."
1588 (when (python-nav-beginning-of-block)
1589 (let ((block-indentation (current-indentation)))
1590 (python-nav-end-of-statement)
1591 (while (and (forward-line 1)
1593 (or (and (> (current-indentation) block-indentation
)
1594 (or (python-nav-end-of-statement) t
))
1595 (python-info-current-line-comment-p)
1596 (python-info-current-line-empty-p))))
1597 (python-util-forward-comment -
1)
1600 (defun python-nav-backward-block (&optional arg
)
1601 "Move backward to previous block of code.
1602 With ARG, repeat. See `python-nav-forward-block'."
1604 (or arg
(setq arg
1))
1605 (python-nav-forward-block (- arg
)))
1607 (defun python-nav-forward-block (&optional arg
)
1608 "Move forward to next block of code.
1609 With ARG, repeat. With negative argument, move ARG times
1610 backward to previous block."
1612 (or arg
(setq arg
1))
1613 (let ((block-start-regexp
1614 (python-rx line-start
(* whitespace
) block-start
))
1615 (starting-pos (point)))
1617 (python-nav-end-of-statement)
1619 (re-search-forward block-start-regexp nil t
)
1620 (python-syntax-context-type)))
1621 (setq arg
(1- arg
)))
1623 (python-nav-beginning-of-statement)
1625 (re-search-backward block-start-regexp nil t
)
1626 (python-syntax-context-type)))
1627 (setq arg
(1+ arg
)))
1628 (python-nav-beginning-of-statement)
1629 (if (not (looking-at (python-rx block-start
)))
1630 (and (goto-char starting-pos
) nil
)
1631 (and (not (= (point) starting-pos
)) (point-marker)))))
1633 (defun python-nav--lisp-forward-sexp (&optional arg
)
1634 "Standard version `forward-sexp'.
1635 It ignores completely the value of `forward-sexp-function' by
1636 setting it to nil before calling `forward-sexp'. With positive
1637 ARG move forward only one sexp, else move backwards."
1638 (let ((forward-sexp-function)
1639 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1640 (forward-sexp arg
)))
1642 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1643 "Safe version of standard `forward-sexp'.
1644 When at end of sexp (i.e. looking at a opening/closing paren)
1645 skips it instead of throwing an error. With positive ARG move
1646 forward only one sexp, else move backwards."
1647 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1649 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1651 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1653 (python-nav--lisp-forward-sexp arg
)
1655 (while (and (funcall search-fn paren-regexp nil t
)
1656 (python-syntax-context 'paren
)))))))
1658 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p
)
1659 "Move to forward sexp.
1660 With positive optional argument DIR direction move forward, else
1661 backwards. When optional argument SAFE is non-nil do not throw
1662 errors when at end of sexp, skip it instead. With optional
1663 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1664 expressions when looking at them in either direction."
1665 (setq dir
(or dir
1))
1667 (let* ((forward-p (if (> dir
0)
1668 (and (setq dir
1) t
)
1669 (and (setq dir -
1) nil
)))
1670 (context-type (python-syntax-context-type)))
1672 ((memq context-type
'(string comment
))
1673 ;; Inside of a string, get out of it.
1674 (let ((forward-sexp-function))
1675 (forward-sexp dir
)))
1676 ((and (not skip-parens-p
)
1677 (or (eq context-type
'paren
)
1679 (eq (syntax-class (syntax-after (point)))
1680 (car (string-to-syntax "(")))
1681 (eq (syntax-class (syntax-after (1- (point))))
1682 (car (string-to-syntax ")"))))))
1683 ;; Inside a paren or looking at it, lisp knows what to do.
1685 (python-nav--lisp-forward-sexp-safe dir
)
1686 (python-nav--lisp-forward-sexp dir
)))
1688 ;; This part handles the lispy feel of
1689 ;; `python-nav-forward-sexp'. Knowing everything about the
1690 ;; current context and the context of the next sexp tries to
1691 ;; follow the lisp sexp motion commands in a symmetric manner.
1694 ((python-info-beginning-of-block-p) 'block-start
)
1695 ((python-info-end-of-block-p) 'block-end
)
1696 ((python-info-beginning-of-statement-p) 'statement-start
)
1697 ((python-info-end-of-statement-p) 'statement-end
)))
1701 (python-nav--lisp-forward-sexp-safe dir
)
1702 (python-nav--lisp-forward-sexp dir
))
1706 (goto-char next-sexp-pos
)
1708 ((python-info-beginning-of-block-p) 'block-start
)
1709 ((python-info-end-of-block-p) 'block-end
)
1710 ((python-info-beginning-of-statement-p) 'statement-start
)
1711 ((python-info-end-of-statement-p) 'statement-end
)
1712 ((python-info-statement-starts-block-p) 'starts-block
)
1713 ((python-info-statement-ends-block-p) 'ends-block
)))))
1715 (cond ((and (not (eobp))
1716 (python-info-current-line-empty-p))
1717 (python-util-forward-comment dir
)
1718 (python-nav--forward-sexp dir safe skip-parens-p
))
1719 ((eq context
'block-start
)
1720 (python-nav-end-of-block))
1721 ((eq context
'statement-start
)
1722 (python-nav-end-of-statement))
1723 ((and (memq context
'(statement-end block-end
))
1724 (eq next-sexp-context
'ends-block
))
1725 (goto-char next-sexp-pos
)
1726 (python-nav-end-of-block))
1727 ((and (memq context
'(statement-end block-end
))
1728 (eq next-sexp-context
'starts-block
))
1729 (goto-char next-sexp-pos
)
1730 (python-nav-end-of-block))
1731 ((memq context
'(statement-end block-end
))
1732 (goto-char next-sexp-pos
)
1733 (python-nav-end-of-statement))
1734 (t (goto-char next-sexp-pos
)))
1735 (cond ((and (not (bobp))
1736 (python-info-current-line-empty-p))
1737 (python-util-forward-comment dir
)
1738 (python-nav--forward-sexp dir safe skip-parens-p
))
1739 ((eq context
'block-end
)
1740 (python-nav-beginning-of-block))
1741 ((eq context
'statement-end
)
1742 (python-nav-beginning-of-statement))
1743 ((and (memq context
'(statement-start block-start
))
1744 (eq next-sexp-context
'starts-block
))
1745 (goto-char next-sexp-pos
)
1746 (python-nav-beginning-of-block))
1747 ((and (memq context
'(statement-start block-start
))
1748 (eq next-sexp-context
'ends-block
))
1749 (goto-char next-sexp-pos
)
1750 (python-nav-beginning-of-block))
1751 ((memq context
'(statement-start block-start
))
1752 (goto-char next-sexp-pos
)
1753 (python-nav-beginning-of-statement))
1754 (t (goto-char next-sexp-pos
))))))))))
1756 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p
)
1757 "Move forward across expressions.
1758 With ARG, do it that many times. Negative arg -N means move
1759 backward N times. When optional argument SAFE is non-nil do not
1760 throw errors when at end of sexp, skip it instead. With optional
1761 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1762 expressions when looking at them in either direction (forced to t
1763 in interactive calls)."
1765 (or arg
(setq arg
1))
1766 ;; Do not follow parens on interactive calls. This hack to detect
1767 ;; if the function was called interactively copes with the way
1768 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1769 ;; interactive detection by checking `current-prefix-arg'. The
1770 ;; reason to make this distinction is that lisp functions like
1771 ;; `blink-matching-open' get confused causing issues like the one in
1772 ;; Bug#16191. With this approach the user gets a symmetric behavior
1773 ;; when working interactively while called functions expecting
1774 ;; paren-based sexp motion work just fine.
1778 (memq real-this-command
1780 #'forward-sexp
#'backward-sexp
1781 #'python-nav-forward-sexp
#'python-nav-backward-sexp
1782 #'python-nav-forward-sexp-safe
#'python-nav-backward-sexp
))))
1784 (python-nav--forward-sexp 1 safe skip-parens-p
)
1785 (setq arg
(1- arg
)))
1787 (python-nav--forward-sexp -
1 safe skip-parens-p
)
1788 (setq arg
(1+ arg
))))
1790 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p
)
1791 "Move backward across expressions.
1792 With ARG, do it that many times. Negative arg -N means move
1793 forward N times. When optional argument SAFE is non-nil do not
1794 throw errors when at end of sexp, skip it instead. With optional
1795 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1796 expressions when looking at them in either direction (forced to t
1797 in interactive calls)."
1799 (or arg
(setq arg
1))
1800 (python-nav-forward-sexp (- arg
) safe skip-parens-p
))
1802 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p
)
1803 "Move forward safely across expressions.
1804 With ARG, do it that many times. Negative arg -N means move
1805 backward N times. With optional argument SKIP-PARENS-P force
1806 sexp motion to ignore parenthesized expressions when looking at
1807 them in either direction (forced to t in interactive calls)."
1809 (python-nav-forward-sexp arg t skip-parens-p
))
1811 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p
)
1812 "Move backward safely across expressions.
1813 With ARG, do it that many times. Negative arg -N means move
1814 forward N times. With optional argument SKIP-PARENS-P force sexp
1815 motion to ignore parenthesized expressions when looking at them in
1816 either direction (forced to t in interactive calls)."
1818 (python-nav-backward-sexp arg t skip-parens-p
))
1820 (defun python-nav--up-list (&optional dir
)
1821 "Internal implementation of `python-nav-up-list'.
1822 DIR is always 1 or -1 and comes sanitized from
1823 `python-nav-up-list' calls."
1824 (let ((context (python-syntax-context-type))
1825 (forward-p (> dir
0)))
1827 ((memq context
'(string comment
)))
1828 ((eq context
'paren
)
1829 (let ((forward-sexp-function))
1831 ((and forward-p
(python-info-end-of-block-p))
1832 (let ((parent-end-pos
1834 (let ((indentation (and
1835 (python-nav-beginning-of-block)
1836 (current-indentation))))
1837 (while (and indentation
1839 (>= (current-indentation) indentation
)
1840 (python-nav-backward-block)))
1841 (python-nav-end-of-block)))))
1842 (and (> (or parent-end-pos
(point)) (point))
1843 (goto-char parent-end-pos
))))
1844 (forward-p (python-nav-end-of-block))
1845 ((and (not forward-p
)
1846 (> (current-indentation) 0)
1847 (python-info-beginning-of-block-p))
1848 (let ((prev-block-pos
1850 (let ((indentation (current-indentation)))
1851 (while (and (python-nav-backward-block)
1852 (>= (current-indentation) indentation
))))
1854 (and (> (point) prev-block-pos
)
1855 (goto-char prev-block-pos
))))
1856 ((not forward-p
) (python-nav-beginning-of-block)))))
1858 (defun python-nav-up-list (&optional arg
)
1859 "Move forward out of one level of parentheses (or blocks).
1860 With ARG, do this that many times.
1861 A negative argument means move backward but still to a less deep spot.
1862 This command assumes point is not in a string or comment."
1864 (or arg
(setq arg
1))
1866 (python-nav--up-list 1)
1867 (setq arg
(1- arg
)))
1869 (python-nav--up-list -
1)
1870 (setq arg
(1+ arg
))))
1872 (defun python-nav-backward-up-list (&optional arg
)
1873 "Move backward out of one level of parentheses (or blocks).
1874 With ARG, do this that many times.
1875 A negative argument means move forward but still to a less deep spot.
1876 This command assumes point is not in a string or comment."
1878 (or arg
(setq arg
1))
1879 (python-nav-up-list (- arg
)))
1881 (defun python-nav-if-name-main ()
1882 "Move point at the beginning the __main__ block.
1883 When \"if __name__ == \\='__main__\\=':\" is found returns its
1884 position, else returns nil."
1886 (let ((point (point))
1887 (found (catch 'found
1888 (goto-char (point-min))
1889 (while (re-search-forward
1890 (python-rx line-start
1892 "__name__" (+ space
)
1894 (group-n 1 (or ?
\" ?
\'))
1895 "__main__" (backref 1) (* space
) ":")
1897 (when (not (python-syntax-context-type))
1899 (throw 'found t
))))))
1902 (ignore (goto-char point
)))))
1905 ;;; Shell integration
1907 (defcustom python-shell-buffer-name
"Python"
1908 "Default buffer name for Python interpreter."
1913 (defcustom python-shell-interpreter
"python"
1914 "Default Python interpreter for shell."
1918 (defcustom python-shell-internal-buffer-name
"Python Internal"
1919 "Default buffer name for the Internal Python interpreter."
1924 (defcustom python-shell-interpreter-args
"-i"
1925 "Default arguments for the Python interpreter."
1929 (defcustom python-shell-interpreter-interactive-arg
"-i"
1930 "Interpreter argument to force it to run interactively."
1934 (defcustom python-shell-prompt-detect-enabled t
1935 "Non-nil enables autodetection of interpreter prompts."
1940 (defcustom python-shell-prompt-detect-failure-warning t
1941 "Non-nil enables warnings when detection of prompts fail."
1946 (defcustom python-shell-prompt-input-regexps
1947 '(">>> " "\\.\\.\\. " ; Python
1948 "In \\[[0-9]+\\]: " ; IPython
1949 " \\.\\.\\.: " ; IPython
1950 ;; Using ipdb outside IPython may fail to cleanup and leave static
1951 ;; IPython prompts activated, this adds some safeguard for that.
1952 "In : " "\\.\\.\\.: ")
1953 "List of regular expressions matching input prompts."
1954 :type
'(repeat string
)
1957 (defcustom python-shell-prompt-output-regexps
1959 "Out\\[[0-9]+\\]: " ; IPython
1960 "Out :") ; ipdb safeguard
1961 "List of regular expressions matching output prompts."
1962 :type
'(repeat string
)
1965 (defcustom python-shell-prompt-regexp
">>> "
1966 "Regular expression matching top level input prompt of Python shell.
1967 It should not contain a caret (^) at the beginning."
1970 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1971 "Regular expression matching block input prompt of Python shell.
1972 It should not contain a caret (^) at the beginning."
1975 (defcustom python-shell-prompt-output-regexp
""
1976 "Regular expression matching output prompt of Python shell.
1977 It should not contain a caret (^) at the beginning."
1980 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1981 "Regular expression matching pdb input prompt of Python shell.
1982 It should not contain a caret (^) at the beginning."
1985 (define-obsolete-variable-alias
1986 'python-shell-enable-font-lock
'python-shell-font-lock-enable
"25.1")
1988 (defcustom python-shell-font-lock-enable t
1989 "Should syntax highlighting be enabled in the Python shell buffer?
1990 Restart the Python shell after changing this variable for it to take effect."
1995 (defcustom python-shell-unbuffered t
1996 "Should shell output be unbuffered?.
1997 When non-nil, this may prevent delayed and missing output in the
1998 Python shell. See commentary for details."
2003 (defcustom python-shell-process-environment nil
2004 "List of overridden environment variables for subprocesses to inherit.
2005 Each element should be a string of the form ENVVARNAME=VALUE.
2006 When this variable is non-nil, values are exported into the
2007 process environment before starting it. Any variables already
2008 present in the current environment are superseded by variables
2010 :type
'(repeat string
)
2013 (defcustom python-shell-extra-pythonpaths nil
2014 "List of extra pythonpaths for Python shell.
2015 When this variable is non-nil, values added at the beginning of
2016 the PYTHONPATH before starting processes. Any values present
2017 here that already exists in PYTHONPATH are moved to the beginning
2018 of the list so that they are prioritized when looking for
2020 :type
'(repeat string
)
2023 (defcustom python-shell-exec-path nil
2024 "List of paths for searching executables.
2025 When this variable is non-nil, values added at the beginning of
2026 the PATH before starting processes. Any values present here that
2027 already exists in PATH are moved to the beginning of the list so
2028 that they are prioritized when looking for executables."
2029 :type
'(repeat string
)
2032 (defcustom python-shell-remote-exec-path nil
2033 "List of paths to be ensured remotely for searching executables.
2034 When this variable is non-nil, values are exported into remote
2035 hosts PATH before starting processes. Values defined in
2036 `python-shell-exec-path' will take precedence to paths defined
2037 here. Normally you wont use this variable directly unless you
2038 plan to ensure a particular set of paths to all Python shell
2039 executed through tramp connections."
2041 :type
'(repeat string
)
2044 (define-obsolete-variable-alias
2045 'python-shell-virtualenv-path
'python-shell-virtualenv-root
"25.1")
2047 (defcustom python-shell-virtualenv-root nil
2048 "Path to virtualenv root.
2049 This variable, when set to a string, makes the environment to be
2050 modified such that shells are started within the specified
2052 :type
'(choice (const nil
) string
)
2055 (defcustom python-shell-setup-codes nil
2056 "List of code run by `python-shell-send-setup-codes'."
2057 :type
'(repeat symbol
)
2060 (defcustom python-shell-compilation-regexp-alist
2061 `((,(rx line-start
(1+ (any " \t")) "File \""
2062 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
2063 "\", line " (group (1+ digit
)))
2065 (,(rx " in file " (group (1+ not-newline
)) " on line "
2068 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
2069 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
2071 "`compilation-error-regexp-alist' for inferior Python."
2072 :type
'(alist string
)
2075 (defmacro python-shell--add-to-path-with-priority
(pathvar paths
)
2076 "Modify PATHVAR and ensure PATHS are added only once at beginning."
2077 `(dolist (path (reverse ,paths
))
2078 (cl-delete path
,pathvar
:test
#'string
=)
2079 (cl-pushnew path
,pathvar
:test
#'string
=)))
2081 (defun python-shell-calculate-pythonpath ()
2082 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2085 (or (getenv "PYTHONPATH") "") path-separator
'omit
)))
2086 (python-shell--add-to-path-with-priority
2087 pythonpath python-shell-extra-pythonpaths
)
2088 (mapconcat 'identity pythonpath path-separator
)))
2090 (defun python-shell-calculate-process-environment ()
2091 "Calculate `process-environment' or `tramp-remote-process-environment'.
2092 Prepends `python-shell-process-environment', sets extra
2093 pythonpaths from `python-shell-extra-pythonpaths' and sets a few
2094 virtualenv related vars. If `default-directory' points to a
2095 remote host, the returned value is intended for
2096 `tramp-remote-process-environment'."
2097 (let* ((remote-p (file-remote-p default-directory
))
2098 (process-environment (if remote-p
2099 tramp-remote-process-environment
2100 process-environment
))
2101 (virtualenv (when python-shell-virtualenv-root
2102 (directory-file-name python-shell-virtualenv-root
))))
2103 (dolist (env python-shell-process-environment
)
2104 (pcase-let ((`(,key
,value
) (split-string env
"=")))
2105 (setenv key value
)))
2106 (when python-shell-unbuffered
2107 (setenv "PYTHONUNBUFFERED" "1"))
2108 (when python-shell-extra-pythonpaths
2109 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2110 (if (not virtualenv
)
2112 (setenv "PYTHONHOME" nil
)
2113 (setenv "VIRTUAL_ENV" virtualenv
))
2114 process-environment
))
2116 (defun python-shell-calculate-exec-path ()
2117 "Calculate `exec-path'.
2118 Prepends `python-shell-exec-path' and adds the binary directory
2119 for virtualenv if `python-shell-virtualenv-root' is set - this
2120 will use the python interpreter from inside the virtualenv when
2121 starting the shell. If `default-directory' points to a remote host,
2122 the returned value appends `python-shell-remote-exec-path' instead
2124 (let ((new-path (copy-sequence
2125 (if (file-remote-p default-directory
)
2126 python-shell-remote-exec-path
2129 ;; Windows and POSIX systems use different venv directory structures
2130 (virtualenv-bin-dir (if (eq system-type
'windows-nt
) "Scripts" "bin")))
2131 (python-shell--add-to-path-with-priority
2132 new-path python-shell-exec-path
)
2133 (if (not python-shell-virtualenv-root
)
2135 (python-shell--add-to-path-with-priority
2137 (list (expand-file-name virtualenv-bin-dir python-shell-virtualenv-root
)))
2140 (defun python-shell-tramp-refresh-remote-path (vec paths
)
2141 "Update VEC's remote-path giving PATHS priority."
2142 (let ((remote-path (tramp-get-connection-property vec
"remote-path" nil
)))
2144 (python-shell--add-to-path-with-priority remote-path paths
)
2145 (tramp-set-connection-property vec
"remote-path" remote-path
)
2146 (tramp-set-remote-path vec
))))
2148 (defun python-shell-tramp-refresh-process-environment (vec env
)
2149 "Update VEC's process environment with ENV."
2150 ;; Stolen from `tramp-open-connection-setup-interactive-shell'.
2151 (let ((env (append (when (fboundp #'tramp-get-remote-locale
)
2152 ;; Emacs<24.4 compat.
2153 (list (tramp-get-remote-locale vec
)))
2154 (copy-sequence env
)))
2155 (tramp-end-of-heredoc
2156 (if (boundp 'tramp-end-of-heredoc
)
2157 tramp-end-of-heredoc
2158 (md5 tramp-end-of-output
)))
2161 (setq item
(split-string (car env
) "=" 'omit
))
2162 (setcdr item
(mapconcat 'identity
(cdr item
) "="))
2163 (if (and (stringp (cdr item
)) (not (string-equal (cdr item
) "")))
2164 (push (format "%s %s" (car item
) (cdr item
)) vars
)
2165 (push (car item
) unset
))
2166 (setq env
(cdr env
)))
2170 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
2171 tramp-end-of-heredoc
2172 (mapconcat 'identity vars
"\n")
2173 tramp-end-of-heredoc
)
2177 vec
(format "unset %s" (mapconcat 'identity unset
" ")) t
))))
2179 (defmacro python-shell-with-environment
(&rest body
)
2180 "Modify shell environment during execution of BODY.
2181 Temporarily sets `process-environment' and `exec-path' during
2182 execution of body. If `default-directory' points to a remote
2183 machine then modifies `tramp-remote-process-environment' and
2184 `python-shell-remote-exec-path' instead."
2185 (declare (indent 0) (debug (body)))
2186 (let ((vec (make-symbol "vec")))
2189 (when (file-remote-p default-directory
)
2191 (tramp-dissect-file-name default-directory
'noexpand
))))
2192 (process-environment
2195 (python-shell-calculate-process-environment)))
2199 (python-shell-calculate-exec-path)))
2200 (tramp-remote-process-environment
2202 (python-shell-calculate-process-environment)
2203 tramp-remote-process-environment
)))
2204 (when (tramp-get-connection-process ,vec
)
2205 ;; For already existing connections, the new exec path must
2206 ;; be re-set, otherwise it won't take effect. One example
2207 ;; of such case is when remote dir-locals are read and
2208 ;; *then* subprocesses are triggered within the same
2210 (python-shell-tramp-refresh-remote-path
2211 ,vec
(python-shell-calculate-exec-path))
2212 ;; The `tramp-remote-process-environment' variable is only
2213 ;; effective when the started process is an interactive
2214 ;; shell, otherwise (like in the case of processes started
2215 ;; with `process-file') the environment is not changed.
2216 ;; This makes environment modifications effective
2218 (python-shell-tramp-refresh-process-environment
2219 ,vec tramp-remote-process-environment
))
2220 ,(macroexp-progn body
)))))
2222 (defvar python-shell--prompt-calculated-input-regexp nil
2223 "Calculated input prompt regexp for inferior python shell.
2224 Do not set this variable directly, instead use
2225 `python-shell-prompt-set-calculated-regexps'.")
2227 (defvar python-shell--block-prompt nil
2228 "Input block prompt for inferior python shell.
2229 Do not set this variable directly, instead use
2230 `python-shell-prompt-set-calculated-regexps'.")
2232 (defvar python-shell--prompt-calculated-output-regexp nil
2233 "Calculated output prompt regexp for inferior python shell.
2234 Do not set this variable directly, instead use
2235 `python-shell-set-prompt-regexp'.")
2237 (defun python-shell-prompt-detect ()
2238 "Detect prompts for the current `python-shell-interpreter'.
2239 When prompts can be retrieved successfully from the
2240 `python-shell-interpreter' run with
2241 `python-shell-interpreter-interactive-arg', returns a list of
2242 three elements, where the first two are input prompts and the
2243 last one is an output prompt. When no prompts can be detected
2244 and `python-shell-prompt-detect-failure-warning' is non-nil,
2245 shows a warning with instructions to avoid hangs and returns nil.
2246 When `python-shell-prompt-detect-enabled' is nil avoids any
2247 detection and just returns nil."
2248 (when python-shell-prompt-detect-enabled
2249 (python-shell-with-environment
2250 (let* ((code (concat
2252 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2253 ;; JSON is built manually for compatibility
2254 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2257 (interpreter python-shell-interpreter
)
2258 (interpreter-arg python-shell-interpreter-interactive-arg
)
2261 ;; TODO: improve error handling by using
2262 ;; `condition-case' and displaying the error message to
2263 ;; the user in the no-prompts warning.
2266 ;; Python 2.x on Windows does not handle
2267 ;; carriage returns in unbuffered mode.
2268 (let ((inhibit-eol-conversion (getenv "PYTHONUNBUFFERED")))
2269 (python-shell--save-temp-file code
))))
2270 ;; Use `process-file' as it is remote-host friendly.
2278 (delete-file code-file
)))
2282 (dolist (line (split-string output
"\n" t
))
2284 ;; Check if current line is a valid JSON array
2285 (and (string= (substring line
0 2) "[\"")
2287 ;; Return prompts as a list, not vector
2288 (append (json-read-from-string line
) nil
)))))
2289 ;; The list must contain 3 strings, where the first
2290 ;; is the input prompt, the second is the block
2291 ;; prompt and the last one is the output prompt. The
2292 ;; input prompt is the only one that can't be empty.
2293 (when (and (= (length res
) 3)
2294 (cl-every #'stringp res
)
2295 (not (string= (car res
) "")))
2296 (throw 'prompts res
))))
2298 (when (and (not prompts
)
2299 python-shell-prompt-detect-failure-warning
)
2301 '(python python-shell-prompt-regexp
)
2304 "Python shell prompts cannot be detected.\n"
2305 "If your emacs session hangs when starting python shells\n"
2306 "recover with `keyboard-quit' and then try fixing the\n"
2307 "interactive flag for your interpreter by adjusting the\n"
2308 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2309 "matching shell prompts in the directory-local friendly vars:\n"
2310 " + `python-shell-prompt-regexp'\n"
2311 " + `python-shell-prompt-block-regexp'\n"
2312 " + `python-shell-prompt-output-regexp'\n"
2313 "Or alternatively in:\n"
2314 " + `python-shell-prompt-input-regexps'\n"
2315 " + `python-shell-prompt-output-regexps'")))
2318 (defun python-shell-prompt-validate-regexps ()
2319 "Validate all user provided regexps for prompts.
2320 Signals `user-error' if any of these vars contain invalid
2321 regexps: `python-shell-prompt-regexp',
2322 `python-shell-prompt-block-regexp',
2323 `python-shell-prompt-pdb-regexp',
2324 `python-shell-prompt-output-regexp',
2325 `python-shell-prompt-input-regexps',
2326 `python-shell-prompt-output-regexps'."
2327 (dolist (symbol (list 'python-shell-prompt-input-regexps
2328 'python-shell-prompt-output-regexps
2329 'python-shell-prompt-regexp
2330 'python-shell-prompt-block-regexp
2331 'python-shell-prompt-pdb-regexp
2332 'python-shell-prompt-output-regexp
))
2333 (dolist (regexp (let ((regexps (symbol-value symbol
)))
2337 (when (not (python-util-valid-regexp-p regexp
))
2338 (user-error "Invalid regexp %s in `%s'"
2341 (defun python-shell-prompt-set-calculated-regexps ()
2342 "Detect and set input and output prompt regexps.
2343 Build and set the values for `python-shell-input-prompt-regexp'
2344 and `python-shell-output-prompt-regexp' using the values from
2345 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2346 `python-shell-prompt-pdb-regexp',
2347 `python-shell-prompt-output-regexp',
2348 `python-shell-prompt-input-regexps',
2349 `python-shell-prompt-output-regexps' and detected prompts from
2350 `python-shell-prompt-detect'."
2351 (when (not (and python-shell--prompt-calculated-input-regexp
2352 python-shell--prompt-calculated-output-regexp
))
2353 (let* ((detected-prompts (python-shell-prompt-detect))
2355 (output-prompts nil
)
2359 (mapconcat #'identity
2362 (let ((length-a (length a
))
2363 (length-b (length b
)))
2364 (if (= length-a length-b
)
2366 (> (length a
) (length b
))))))
2369 ;; Validate ALL regexps
2370 (python-shell-prompt-validate-regexps)
2371 ;; Collect all user defined input prompts
2372 (dolist (prompt (append python-shell-prompt-input-regexps
2373 (list python-shell-prompt-regexp
2374 python-shell-prompt-block-regexp
2375 python-shell-prompt-pdb-regexp
)))
2376 (cl-pushnew prompt input-prompts
:test
#'string
=))
2377 ;; Collect all user defined output prompts
2378 (dolist (prompt (cons python-shell-prompt-output-regexp
2379 python-shell-prompt-output-regexps
))
2380 (cl-pushnew prompt output-prompts
:test
#'string
=))
2381 ;; Collect detected prompts if any
2382 (when detected-prompts
2383 (dolist (prompt (butlast detected-prompts
))
2384 (setq prompt
(regexp-quote prompt
))
2385 (cl-pushnew prompt input-prompts
:test
#'string
=))
2386 (setq python-shell--block-prompt
(nth 1 detected-prompts
))
2387 (cl-pushnew (regexp-quote
2388 (car (last detected-prompts
)))
2389 output-prompts
:test
#'string
=))
2390 ;; Set input and output prompt regexps from collected prompts
2391 (setq python-shell--prompt-calculated-input-regexp
2392 (funcall build-regexp input-prompts
)
2393 python-shell--prompt-calculated-output-regexp
2394 (funcall build-regexp output-prompts
)))))
2396 (defun python-shell-get-process-name (dedicated)
2397 "Calculate the appropriate process name for inferior Python process.
2398 If DEDICATED is t returns a string with the form
2399 `python-shell-buffer-name'[`buffer-name'] else returns the value
2400 of `python-shell-buffer-name'."
2402 (format "%s[%s]" python-shell-buffer-name
(buffer-name))
2403 python-shell-buffer-name
))
2405 (defun python-shell-internal-get-process-name ()
2406 "Calculate the appropriate process name for Internal Python process.
2407 The name is calculated from `python-shell-global-buffer-name' and
2409 (format "%s[%s]" python-shell-internal-buffer-name
(buffer-name)))
2411 (defun python-shell-calculate-command ()
2412 "Calculate the string used to execute the inferior Python process."
2414 ;; `python-shell-make-comint' expects to be able to
2415 ;; `split-string-and-unquote' the result of this function.
2416 (combine-and-quote-strings (list python-shell-interpreter
))
2417 python-shell-interpreter-args
))
2419 (define-obsolete-function-alias
2420 'python-shell-parse-command
2421 #'python-shell-calculate-command
"25.1")
2423 (defvar python-shell--package-depth
10)
2425 (defun python-shell-package-enable (directory package
)
2426 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2428 (let* ((dir (expand-file-name
2429 (read-directory-name
2431 (file-name-directory
2432 (or (buffer-file-name) default-directory
)))))
2433 (name (completing-read
2435 (python-util-list-packages
2436 dir python-shell--package-depth
))))
2438 (python-shell-send-string
2441 "import os.path;import sys;"
2442 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2443 "__package__ = '''%s''';"
2445 directory package package
)
2446 (python-shell-get-process)))
2448 (defun python-shell-accept-process-output (process &optional timeout regexp
)
2449 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2450 Optional argument TIMEOUT is the timeout argument to
2451 `accept-process-output' calls. Optional argument REGEXP
2452 overrides the regexp to match the end of output, defaults to
2453 `comint-prompt-regexp'. Returns non-nil when output was
2456 This utility is useful in situations where the output may be
2457 received in chunks, since `accept-process-output' gives no
2458 guarantees they will be grabbed in a single call. An example use
2459 case for this would be the CPython shell start-up, where the
2460 banner and the initial prompt are received separately."
2461 (let ((regexp (or regexp comint-prompt-regexp
)))
2464 (when (not (accept-process-output process timeout
))
2467 regexp
(car (python-util-comint-last-prompt)))
2468 (throw 'found t
))))))
2470 (defun python-shell-comint-end-of-output-p (output)
2471 "Return non-nil if OUTPUT ends with input prompt."
2473 ;; XXX: It seems on macOS an extra carriage return is attached
2474 ;; at the end of output, this handles that too.
2477 ;; Remove initial caret from calculated regexp
2478 (replace-regexp-in-string
2479 (rx string-start ?^
) ""
2480 python-shell--prompt-calculated-input-regexp
)
2484 (define-obsolete-function-alias
2485 'python-comint-output-filter-function
2486 'ansi-color-filter-apply
2489 (defun python-comint-postoutput-scroll-to-bottom (output)
2490 "Faster version of `comint-postoutput-scroll-to-bottom'.
2491 Avoids `recenter' calls until OUTPUT is completely sent."
2492 (when (and (not (string= "" output
))
2493 (python-shell-comint-end-of-output-p
2494 (ansi-color-filter-apply output
)))
2495 (comint-postoutput-scroll-to-bottom output
))
2498 (defvar python-shell--parent-buffer nil
)
2500 (defmacro python-shell-with-shell-buffer
(&rest body
)
2501 "Execute the forms in BODY with the shell buffer temporarily current.
2502 Signals an error if no shell buffer is available for current buffer."
2503 (declare (indent 0) (debug t
))
2504 (let ((shell-process (make-symbol "shell-process")))
2505 `(let ((,shell-process
(python-shell-get-process-or-error)))
2506 (with-current-buffer (process-buffer ,shell-process
)
2509 (defvar python-shell--font-lock-buffer nil
)
2511 (defun python-shell-font-lock-get-or-create-buffer ()
2512 "Get or create a font-lock buffer for current inferior process."
2513 (python-shell-with-shell-buffer
2514 (if python-shell--font-lock-buffer
2515 python-shell--font-lock-buffer
2517 (process-name (get-buffer-process (current-buffer)))))
2518 (generate-new-buffer
2519 (format " *%s-font-lock*" process-name
))))))
2521 (defun python-shell-font-lock-kill-buffer ()
2522 "Kill the font-lock buffer safely."
2523 (when (and python-shell--font-lock-buffer
2524 (buffer-live-p python-shell--font-lock-buffer
))
2525 (kill-buffer python-shell--font-lock-buffer
)
2526 (when (derived-mode-p 'inferior-python-mode
)
2527 (setq python-shell--font-lock-buffer nil
))))
2529 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2530 "Execute the forms in BODY in the font-lock buffer.
2531 The value returned is the value of the last form in BODY. See
2532 also `with-current-buffer'."
2533 (declare (indent 0) (debug t
))
2534 `(python-shell-with-shell-buffer
2535 (save-current-buffer
2536 (when (not (and python-shell--font-lock-buffer
2537 (get-buffer python-shell--font-lock-buffer
)))
2538 (setq python-shell--font-lock-buffer
2539 (python-shell-font-lock-get-or-create-buffer)))
2540 (set-buffer python-shell--font-lock-buffer
)
2541 (when (not font-lock-mode
)
2543 (set (make-local-variable 'delay-mode-hooks
) t
)
2544 (let ((python-indent-guess-indent-offset nil
))
2545 (when (not (derived-mode-p 'python-mode
))
2549 (defun python-shell-font-lock-cleanup-buffer ()
2550 "Cleanup the font-lock buffer.
2551 Provided as a command because this might be handy if something
2552 goes wrong and syntax highlighting in the shell gets messed up."
2554 (python-shell-with-shell-buffer
2555 (python-shell-font-lock-with-font-lock-buffer
2558 (defun python-shell-font-lock-comint-output-filter-function (output)
2559 "Clean up the font-lock buffer after any OUTPUT."
2560 (if (and (not (string= "" output
))
2561 ;; Is end of output and is not just a prompt.
2563 (python-shell-comint-end-of-output-p
2564 (ansi-color-filter-apply output
))
2566 ;; If output is other than an input prompt then "real" output has
2567 ;; been received and the font-lock buffer must be cleaned up.
2568 (python-shell-font-lock-cleanup-buffer)
2569 ;; Otherwise just add a newline.
2570 (python-shell-font-lock-with-font-lock-buffer
2571 (goto-char (point-max))
2575 (defun python-shell-font-lock-post-command-hook ()
2576 "Fontifies current line in shell buffer."
2577 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2578 (when (and prompt-end
(> (point) prompt-end
)
2579 (process-live-p (get-buffer-process (current-buffer))))
2580 (let* ((input (buffer-substring-no-properties
2581 prompt-end
(point-max)))
2582 (deactivate-mark nil
)
2583 (start-pos prompt-end
)
2584 (buffer-undo-list t
)
2585 (font-lock-buffer-pos nil
)
2587 (python-shell-font-lock-with-font-lock-buffer
2588 (delete-region (line-beginning-position)
2590 (setq font-lock-buffer-pos
(point))
2592 ;; Ensure buffer is fontified, keeping it
2593 ;; compatible with Emacs < 24.4.
2594 (if (fboundp 'font-lock-ensure
)
2595 (funcall 'font-lock-ensure
)
2596 (font-lock-default-fontify-buffer))
2597 (buffer-substring font-lock-buffer-pos
2599 (replacement-length (length replacement
))
2601 ;; Inject text properties to get input fontified.
2602 (while (not (= i replacement-length
))
2603 (let* ((plist (text-properties-at i replacement
))
2604 (next-change (or (next-property-change i replacement
)
2605 replacement-length
))
2606 (plist (let ((face (plist-get plist
'face
)))
2609 ;; Replace FACE text properties with
2610 ;; FONT-LOCK-FACE so input is fontified.
2611 (plist-put plist
'face nil
)
2612 (plist-put plist
'font-lock-face face
)))))
2613 (set-text-properties
2614 (+ start-pos i
) (+ start-pos next-change
) plist
)
2615 (setq i next-change
)))))))
2617 (defun python-shell-font-lock-turn-on (&optional msg
)
2618 "Turn on shell font-lock.
2619 With argument MSG show activation message."
2621 (python-shell-with-shell-buffer
2622 (python-shell-font-lock-kill-buffer)
2623 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2624 (add-hook 'post-command-hook
2625 #'python-shell-font-lock-post-command-hook nil
'local
)
2626 (add-hook 'kill-buffer-hook
2627 #'python-shell-font-lock-kill-buffer nil
'local
)
2628 (add-hook 'comint-output-filter-functions
2629 #'python-shell-font-lock-comint-output-filter-function
2632 (message "Shell font-lock is enabled"))))
2634 (defun python-shell-font-lock-turn-off (&optional msg
)
2635 "Turn off shell font-lock.
2636 With argument MSG show deactivation message."
2638 (python-shell-with-shell-buffer
2639 (python-shell-font-lock-kill-buffer)
2640 (when (python-util-comint-last-prompt)
2641 ;; Cleanup current fontification
2642 (remove-text-properties
2643 (cdr (python-util-comint-last-prompt))
2645 '(face nil font-lock-face nil
)))
2646 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2647 (remove-hook 'post-command-hook
2648 #'python-shell-font-lock-post-command-hook
'local
)
2649 (remove-hook 'kill-buffer-hook
2650 #'python-shell-font-lock-kill-buffer
'local
)
2651 (remove-hook 'comint-output-filter-functions
2652 #'python-shell-font-lock-comint-output-filter-function
2655 (message "Shell font-lock is disabled"))))
2657 (defun python-shell-font-lock-toggle (&optional msg
)
2658 "Toggle font-lock for shell.
2659 With argument MSG show activation/deactivation message."
2661 (python-shell-with-shell-buffer
2662 (set (make-local-variable 'python-shell-font-lock-enable
)
2663 (not python-shell-font-lock-enable
))
2664 (if python-shell-font-lock-enable
2665 (python-shell-font-lock-turn-on msg
)
2666 (python-shell-font-lock-turn-off msg
))
2667 python-shell-font-lock-enable
))
2669 (defvar python-shell--first-prompt-received-output-buffer nil
)
2670 (defvar python-shell--first-prompt-received nil
)
2672 (defcustom python-shell-first-prompt-hook nil
2673 "Hook run upon first (non-pdb) shell prompt detection.
2674 This is the place for shell setup functions that need to wait for
2675 output. Since the first prompt is ensured, this helps the
2676 current process to not hang while waiting. This is useful to
2677 safely attach setup code for long-running processes that
2678 eventually provide a shell."
2683 (defun python-shell-comint-watch-for-first-prompt-output-filter (output)
2684 "Run `python-shell-first-prompt-hook' when first prompt is found in OUTPUT."
2685 (when (not python-shell--first-prompt-received
)
2686 (set (make-local-variable 'python-shell--first-prompt-received-output-buffer
)
2687 (concat python-shell--first-prompt-received-output-buffer
2688 (ansi-color-filter-apply output
)))
2689 (when (python-shell-comint-end-of-output-p
2690 python-shell--first-prompt-received-output-buffer
)
2692 (concat python-shell-prompt-pdb-regexp
(rx eos
))
2693 (or python-shell--first-prompt-received-output-buffer
""))
2694 ;; Skip pdb prompts and reset the buffer.
2695 (setq python-shell--first-prompt-received-output-buffer nil
)
2696 (set (make-local-variable 'python-shell--first-prompt-received
) t
)
2697 (setq python-shell--first-prompt-received-output-buffer nil
)
2698 (with-current-buffer (current-buffer)
2699 (let ((inhibit-quit nil
))
2700 (run-hooks 'python-shell-first-prompt-hook
))))))
2703 ;; Used to hold user interactive overrides to
2704 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2705 ;; will be made buffer-local by `inferior-python-mode':
2706 (defvar python-shell--interpreter
)
2707 (defvar python-shell--interpreter-args
)
2709 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2710 "Major mode for Python inferior process.
2711 Runs a Python interpreter as a subprocess of Emacs, with Python
2712 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2713 and `python-shell-interpreter-args' control which Python
2714 interpreter is run. Variables
2715 `python-shell-prompt-regexp',
2716 `python-shell-prompt-output-regexp',
2717 `python-shell-prompt-block-regexp',
2718 `python-shell-font-lock-enable',
2719 `python-shell-completion-setup-code',
2720 `python-shell-completion-string-code',
2721 `python-eldoc-setup-code', `python-eldoc-string-code',
2722 `python-ffap-setup-code' and `python-ffap-string-code' can
2723 customize this mode for different Python interpreters.
2725 This mode resets `comint-output-filter-functions' locally, so you
2726 may want to re-add custom functions to it using the
2727 `inferior-python-mode-hook'.
2729 You can also add additional setup code to be run at
2730 initialization of the interpreter via `python-shell-setup-codes'
2733 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2734 (when python-shell--parent-buffer
2735 (python-util-clone-local-variables python-shell--parent-buffer
))
2736 (set (make-local-variable 'indent-tabs-mode
) nil
)
2737 ;; Users can interactively override default values for
2738 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2739 ;; when calling `run-python'. This ensures values let-bound in
2740 ;; `python-shell-make-comint' are locally set if needed.
2741 (set (make-local-variable 'python-shell-interpreter
)
2742 (or python-shell--interpreter python-shell-interpreter
))
2743 (set (make-local-variable 'python-shell-interpreter-args
)
2744 (or python-shell--interpreter-args python-shell-interpreter-args
))
2745 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2746 (set (make-local-variable 'python-shell--block-prompt
) nil
)
2747 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2748 (python-shell-prompt-set-calculated-regexps)
2749 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2750 (set (make-local-variable 'comint-prompt-read-only
) t
)
2751 (setq mode-line-process
'(":%s"))
2752 (set (make-local-variable 'comint-output-filter-functions
)
2753 '(ansi-color-process-output
2754 python-shell-comint-watch-for-first-prompt-output-filter
2755 python-pdbtrack-comint-output-filter-function
2756 python-comint-postoutput-scroll-to-bottom
2757 comint-watch-for-password-prompt
))
2758 (set (make-local-variable 'compilation-error-regexp-alist
)
2759 python-shell-compilation-regexp-alist
)
2760 (add-hook 'completion-at-point-functions
2761 #'python-shell-completion-at-point nil
'local
)
2762 (define-key inferior-python-mode-map
"\t"
2763 'python-shell-completion-complete-or-indent
)
2764 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2765 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2766 (make-local-variable 'python-shell-internal-last-output
)
2767 (when python-shell-font-lock-enable
2768 (python-shell-font-lock-turn-on))
2769 (compilation-shell-minor-mode 1))
2771 (defun python-shell-make-comint (cmd proc-name
&optional show internal
)
2772 "Create a Python shell comint buffer.
2773 CMD is the Python command to be executed and PROC-NAME is the
2774 process name the comint buffer will get. After the comint buffer
2775 is created the `inferior-python-mode' is activated. When
2776 optional argument SHOW is non-nil the buffer is shown. When
2777 optional argument INTERNAL is non-nil this process is run on a
2778 buffer with a name that starts with a space, following the Emacs
2779 convention for temporary/internal buffers, and also makes sure
2780 the user is not queried for confirmation when the process is
2783 (python-shell-with-environment
2784 (let* ((proc-buffer-name
2785 (format (if (not internal
) "*%s*" " *%s*") proc-name
)))
2786 (when (not (comint-check-proc proc-buffer-name
))
2787 (let* ((cmdlist (split-string-and-unquote cmd
))
2788 (interpreter (car cmdlist
))
2789 (args (cdr cmdlist
))
2790 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2791 interpreter nil args
))
2792 (python-shell--parent-buffer (current-buffer))
2793 (process (get-buffer-process buffer
))
2794 ;; Users can override the interpreter and args
2795 ;; interactively when calling `run-python', let-binding
2796 ;; these allows having the new right values in all
2797 ;; setup code that is done in `inferior-python-mode',
2798 ;; which is important, especially for prompt detection.
2799 (python-shell--interpreter interpreter
)
2800 (python-shell--interpreter-args
2801 (mapconcat #'identity args
" ")))
2802 (with-current-buffer buffer
2803 (inferior-python-mode))
2804 (when show
(display-buffer buffer
))
2805 (and internal
(set-process-query-on-exit-flag process nil
))))
2806 proc-buffer-name
))))
2809 (defun run-python (&optional cmd dedicated show
)
2810 "Run an inferior Python process.
2812 Argument CMD defaults to `python-shell-calculate-command' return
2813 value. When called interactively with `prefix-arg', it allows
2814 the user to edit such value and choose whether the interpreter
2815 should be DEDICATED for the current buffer. When numeric prefix
2816 arg is other than 0 or 4 do not SHOW.
2818 For a given buffer and same values of DEDICATED, if a process is
2819 already running for it, it will do nothing. This means that if
2820 the current buffer is using a global process, the user is still
2821 able to switch it to use a dedicated one.
2823 Runs the hook `inferior-python-mode-hook' after
2824 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2825 process buffer for a list of commands.)"
2827 (if current-prefix-arg
2829 (read-shell-command "Run Python: " (python-shell-calculate-command))
2830 (y-or-n-p "Make dedicated process? ")
2831 (= (prefix-numeric-value current-prefix-arg
) 4))
2832 (list (python-shell-calculate-command) nil t
)))
2834 (python-shell-make-comint
2835 (or cmd
(python-shell-calculate-command))
2836 (python-shell-get-process-name dedicated
) show
)))
2838 (defun run-python-internal ()
2839 "Run an inferior Internal Python process.
2840 Input and output via buffer named after
2841 `python-shell-internal-buffer-name' and what
2842 `python-shell-internal-get-process-name' returns.
2844 This new kind of shell is intended to be used for generic
2845 communication related to defined configurations; the main
2846 difference with global or dedicated shells is that these ones are
2847 attached to a configuration, not a buffer. This means that can
2848 be used for example to retrieve the sys.path and other stuff,
2849 without messing with user shells. Note that
2850 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2851 are set to nil for these shells, so setup codes are not sent at
2853 (let ((python-shell-font-lock-enable nil
)
2854 (inferior-python-mode-hook nil
))
2856 (python-shell-make-comint
2857 (python-shell-calculate-command)
2858 (python-shell-internal-get-process-name) nil t
))))
2860 (defun python-shell-get-buffer ()
2861 "Return inferior Python buffer for current buffer.
2862 If current buffer is in `inferior-python-mode', return it."
2863 (if (derived-mode-p 'inferior-python-mode
)
2865 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2866 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2867 (global-proc-name (python-shell-get-process-name nil
))
2868 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2869 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2870 (global-running (comint-check-proc global-proc-buffer-name
)))
2871 ;; Always prefer dedicated
2872 (or (and dedicated-running dedicated-proc-buffer-name
)
2873 (and global-running global-proc-buffer-name
)))))
2875 (defun python-shell-get-process ()
2876 "Return inferior Python process for current buffer."
2877 (get-buffer-process (python-shell-get-buffer)))
2879 (defun python-shell-get-process-or-error (&optional interactivep
)
2880 "Return inferior Python process for current buffer or signal error.
2881 When argument INTERACTIVEP is non-nil, use `user-error' instead
2882 of `error' with a user-friendly message."
2883 (or (python-shell-get-process)
2886 "Start a Python process first with `M-x run-python' or `%s'."
2890 #'run-python overriding-local-map t
)))
2892 "No inferior Python process running."))))
2894 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2895 "Get or create an inferior Python process for current buffer and return it.
2896 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2897 are used to start the shell. If those arguments are not
2898 provided, `run-python' is called interactively and the user will
2899 be asked for their values."
2900 (let ((shell-process (python-shell-get-process)))
2901 (when (not shell-process
)
2903 ;; XXX: Refactor code such that calling `run-python'
2904 ;; interactively is not needed anymore.
2905 (call-interactively 'run-python
)
2906 (run-python cmd dedicated show
)))
2907 (or shell-process
(python-shell-get-process))))
2910 #'python-shell-get-or-create-process
2911 "Instead call `python-shell-get-process' and create one if returns nil."
2914 (defvar python-shell-internal-buffer nil
2915 "Current internal shell buffer for the current buffer.
2916 This is really not necessary at all for the code to work but it's
2917 there for compatibility with CEDET.")
2919 (defvar python-shell-internal-last-output nil
2920 "Last output captured by the internal shell.
2921 This is really not necessary at all for the code to work but it's
2922 there for compatibility with CEDET.")
2924 (defun python-shell-internal-get-or-create-process ()
2925 "Get or create an inferior Internal Python process."
2926 (let ((proc-name (python-shell-internal-get-process-name)))
2927 (if (process-live-p proc-name
)
2928 (get-process proc-name
)
2929 (run-python-internal))))
2931 (define-obsolete-function-alias
2932 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2934 (define-obsolete-variable-alias
2935 'python-buffer
'python-shell-internal-buffer
"24.3")
2937 (define-obsolete-variable-alias
2938 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2940 (defun python-shell--save-temp-file (string)
2941 (let* ((temporary-file-directory
2942 (if (file-remote-p default-directory
)
2943 (concat (file-remote-p default-directory
) "/tmp")
2944 temporary-file-directory
))
2945 (temp-file-name (make-temp-file "py"))
2946 (coding-system-for-write (python-info-encoding)))
2947 (with-temp-file temp-file-name
2949 (delete-trailing-whitespace))
2952 (defun python-shell-send-string (string &optional process msg
)
2953 "Send STRING to inferior Python PROCESS.
2954 When optional argument MSG is non-nil, forces display of a
2955 user-friendly message if there's no process running; defaults to
2956 t when called interactively."
2958 (list (read-string "Python command: ") nil t
))
2959 (let ((process (or process
(python-shell-get-process-or-error msg
))))
2960 (if (string-match ".\n+." string
) ;Multiline.
2961 (let* ((temp-file-name (python-shell--save-temp-file string
))
2962 (file-name (or (buffer-file-name) temp-file-name
)))
2963 (python-shell-send-file file-name process temp-file-name t
))
2964 (comint-send-string process string
)
2965 (when (or (not (string-match "\n\\'" string
))
2966 (string-match "\n[ \t].*\n?\\'" string
))
2967 (comint-send-string process
"\n")))))
2969 (defvar python-shell-output-filter-in-progress nil
)
2970 (defvar python-shell-output-filter-buffer nil
)
2972 (defun python-shell-output-filter (string)
2973 "Filter used in `python-shell-send-string-no-output' to grab output.
2974 STRING is the output received to this point from the process.
2975 This filter saves received output from the process in
2976 `python-shell-output-filter-buffer' and stops receiving it after
2977 detecting a prompt at the end of the buffer."
2979 string
(ansi-color-filter-apply string
)
2980 python-shell-output-filter-buffer
2981 (concat python-shell-output-filter-buffer string
))
2982 (when (python-shell-comint-end-of-output-p
2983 python-shell-output-filter-buffer
)
2984 ;; Output ends when `python-shell-output-filter-buffer' contains
2985 ;; the prompt attached at the end of it.
2986 (setq python-shell-output-filter-in-progress nil
2987 python-shell-output-filter-buffer
2988 (substring python-shell-output-filter-buffer
2989 0 (match-beginning 0)))
2991 python-shell--prompt-calculated-output-regexp
2992 python-shell-output-filter-buffer
)
2993 ;; Some shells, like IPython might append a prompt before the
2994 ;; output, clean that.
2995 (setq python-shell-output-filter-buffer
2996 (substring python-shell-output-filter-buffer
(match-end 0)))))
2999 (defun python-shell-send-string-no-output (string &optional process
)
3000 "Send STRING to PROCESS and inhibit output.
3002 (let ((process (or process
(python-shell-get-process-or-error)))
3003 (comint-preoutput-filter-functions
3004 '(python-shell-output-filter))
3005 (python-shell-output-filter-in-progress t
)
3009 (python-shell-send-string string process
)
3010 (while python-shell-output-filter-in-progress
3011 ;; `python-shell-output-filter' takes care of setting
3012 ;; `python-shell-output-filter-in-progress' to NIL after it
3013 ;; detects end of output.
3014 (accept-process-output process
))
3016 python-shell-output-filter-buffer
3017 (setq python-shell-output-filter-buffer nil
)))
3018 (with-current-buffer (process-buffer process
)
3019 (comint-interrupt-subjob)))))
3021 (defun python-shell-internal-send-string (string)
3022 "Send STRING to the Internal Python interpreter.
3023 Returns the output. See `python-shell-send-string-no-output'."
3024 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
3025 ;; updated to support this new mode.
3026 (setq python-shell-internal-last-output
3027 (python-shell-send-string-no-output
3028 ;; Makes this function compatible with the old
3029 ;; python-send-receive. (At least for CEDET).
3030 (replace-regexp-in-string "_emacs_out +" "" string
)
3031 (python-shell-internal-get-or-create-process))))
3033 (define-obsolete-function-alias
3034 'python-send-receive
'python-shell-internal-send-string
"24.3")
3036 (define-obsolete-function-alias
3037 'python-send-string
'python-shell-internal-send-string
"24.3")
3039 (defun python-shell-buffer-substring (start end
&optional nomain
)
3040 "Send buffer substring from START to END formatted for shell.
3041 This is a wrapper over `buffer-substring' that takes care of
3042 different transformations for the code sent to be evaluated in
3044 1. When optional argument NOMAIN is non-nil everything under an
3045 \"if __name__ == \\='__main__\\='\" block will be removed.
3046 2. When a subregion of the buffer is sent, it takes care of
3047 appending extra empty lines so tracebacks are correct.
3048 3. When the region sent is a substring of the current buffer, a
3049 coding cookie is added.
3050 4. Wraps indented regions under an \"if True:\" block so the
3051 interpreter evaluates them correctly."
3052 (let* ((start (save-excursion
3053 ;; Normalize start to the line beginning position.
3055 (line-beginning-position)))
3056 (substring (buffer-substring-no-properties start end
))
3057 (starts-at-point-min-p (save-restriction
3059 (= (point-min) start
)))
3060 (encoding (python-info-encoding))
3061 (toplevel-p (zerop (save-excursion
3063 (python-util-forward-comment 1)
3064 (current-indentation))))
3065 (fillstr (when (not starts-at-point-min-p
)
3067 (format "# -*- coding: %s -*-\n" encoding
)
3069 ;; Subtract 2 because of the coding cookie.
3070 (- (line-number-at-pos start
) 2) ?
\n)))))
3076 (goto-char (point-min))
3077 (when (not toplevel-p
)
3079 (delete-region (point) (line-end-position)))
3081 (let* ((if-name-main-start-end
3084 (when (python-nav-if-name-main)
3086 (progn (python-nav-forward-sexp-safe)
3087 ;; Include ending newline
3090 ;; Oh destructuring bind, how I miss you.
3091 (if-name-main-start (car if-name-main-start-end
))
3092 (if-name-main-end (cdr if-name-main-start-end
))
3093 (fillstr (make-string
3094 (- (line-number-at-pos if-name-main-end
)
3095 (line-number-at-pos if-name-main-start
)) ?
\n)))
3096 (when if-name-main-start-end
3097 (goto-char if-name-main-start
)
3098 (delete-region if-name-main-start if-name-main-end
)
3100 ;; Ensure there's only one coding cookie in the generated string.
3101 (goto-char (point-min))
3102 (when (looking-at-p (python-rx coding-cookie
))
3104 (when (looking-at-p (python-rx coding-cookie
))
3106 (line-beginning-position) (line-end-position))))
3107 (buffer-substring-no-properties (point-min) (point-max)))))
3109 (defun python-shell-send-region (start end
&optional send-main msg
)
3110 "Send the region delimited by START and END to inferior Python process.
3111 When optional argument SEND-MAIN is non-nil, allow execution of
3112 code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
3113 When called interactively SEND-MAIN defaults to nil, unless it's
3114 called with prefix argument. When optional argument MSG is
3115 non-nil, forces display of a user-friendly message if there's no
3116 process running; defaults to t when called interactively."
3118 (list (region-beginning) (region-end) current-prefix-arg t
))
3119 (let* ((string (python-shell-buffer-substring start end
(not send-main
)))
3120 (process (python-shell-get-process-or-error msg
))
3121 (original-string (buffer-substring-no-properties start end
))
3122 (_ (string-match "\\`\n*\\(.*\\)" original-string
)))
3123 (message "Sent: %s..." (match-string 1 original-string
))
3124 (python-shell-send-string string process
)))
3126 (defun python-shell-send-buffer (&optional send-main msg
)
3127 "Send the entire buffer to inferior Python process.
3128 When optional argument SEND-MAIN is non-nil, allow execution of
3129 code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
3130 When called interactively SEND-MAIN defaults to nil, unless it's
3131 called with prefix argument. When optional argument MSG is
3132 non-nil, forces display of a user-friendly message if there's no
3133 process running; defaults to t when called interactively."
3134 (interactive (list current-prefix-arg t
))
3137 (python-shell-send-region (point-min) (point-max) send-main msg
)))
3139 (defun python-shell-send-defun (&optional arg msg
)
3140 "Send the current defun to inferior Python process.
3141 When argument ARG is non-nil do not include decorators. When
3142 optional argument MSG is non-nil, forces display of a
3143 user-friendly message if there's no process running; defaults to
3144 t when called interactively."
3145 (interactive (list current-prefix-arg t
))
3147 (python-shell-send-region
3150 (while (and (or (python-nav-beginning-of-defun)
3151 (beginning-of-line 1))
3152 (> (current-indentation) 0)))
3154 (while (and (forward-line -
1)
3155 (looking-at (python-rx decorator
))))
3159 (or (python-nav-end-of-defun)
3165 (defun python-shell-send-file (file-name &optional process temp-file-name
3167 "Send FILE-NAME to inferior Python PROCESS.
3168 If TEMP-FILE-NAME is passed then that file is used for processing
3169 instead, while internally the shell will continue to use
3170 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
3171 TEMP-FILE-NAME is deleted after evaluation is performed. When
3172 optional argument MSG is non-nil, forces display of a
3173 user-friendly message if there's no process running; defaults to
3174 t when called interactively."
3177 (read-file-name "File to send: ") ; file-name
3179 nil
; temp-file-name
3182 (let* ((process (or process
(python-shell-get-process-or-error msg
)))
3183 (encoding (with-temp-buffer
3184 (insert-file-contents
3185 (or temp-file-name file-name
))
3186 (python-info-encoding)))
3187 (file-name (expand-file-name (file-local-name file-name
)))
3188 (temp-file-name (when temp-file-name
3190 (file-local-name temp-file-name
)))))
3191 (python-shell-send-string
3194 "import codecs, os;"
3195 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
3196 "__code = __pyfile.read().encode('''%s''');"
3198 (when (and delete temp-file-name
)
3199 (format "os.remove('''%s''');" temp-file-name
))
3200 "exec(compile(__code, '''%s''', 'exec'));")
3201 (or temp-file-name file-name
) encoding encoding file-name
)
3204 (defun python-shell-switch-to-shell (&optional msg
)
3205 "Switch to inferior Python process buffer.
3206 When optional argument MSG is non-nil, forces display of a
3207 user-friendly message if there's no process running; defaults to
3208 t when called interactively."
3211 (process-buffer (python-shell-get-process-or-error msg
)) nil t
))
3213 (defun python-shell-send-setup-code ()
3214 "Send all setup code for shell.
3215 This function takes the list of setup code to send from the
3216 `python-shell-setup-codes' list."
3217 (when python-shell-setup-codes
3218 (let ((process (python-shell-get-process))
3222 (cond ((stringp elt
) elt
)
3223 ((symbolp elt
) (symbol-value elt
))
3225 python-shell-setup-codes
3226 "\n\nprint ('python.el: sent setup code')"))))
3227 (python-shell-send-string code process
)
3228 (python-shell-accept-process-output process
))))
3230 (add-hook 'python-shell-first-prompt-hook
3231 #'python-shell-send-setup-code
)
3234 ;;; Shell completion
3236 (defcustom python-shell-completion-setup-code
3238 def __PYTHON_EL_get_completions(text):
3249 import builtins as __builtin__
3250 builtins = dir(__builtin__)
3252 is_ipython = ('__IPYTHON__' in builtins or
3253 '__IPYTHON__active' in builtins)
3254 splits = text.split()
3255 is_module = splits and splits[0] in ('from', 'import')
3257 if is_ipython and is_module:
3258 from IPython.core.completerlib import module_completion
3259 completions = module_completion(text.strip())
3260 elif is_ipython and '__IP' in builtins:
3261 completions = __IP.complete(text)
3262 elif is_ipython and 'get_ipython' in builtins:
3263 completions = get_ipython().Completer.all_completions(text)
3265 # Try to reuse current completer.
3266 completer = readline.get_completer()
3268 # importing rlcompleter sets the completer, use it as a
3269 # last resort to avoid breaking customizations.
3271 completer = readline.get_completer()
3272 if getattr(completer, 'PYTHON_EL_WRAPPED', False):
3273 completer.print_mode = False
3276 completion = completer(text, i)
3280 completions.append(completion)
3284 if getattr(completer, 'PYTHON_EL_WRAPPED', False):
3285 completer.print_mode = True
3287 "Code used to setup completion in inferior Python processes."
3291 (define-obsolete-variable-alias
3292 'python-shell-completion-module-string-code
3293 'python-shell-completion-string-code
3295 "Completion string code must also autocomplete modules.")
3297 (define-obsolete-variable-alias
3298 'python-shell-completion-pdb-string-code
3299 'python-shell-completion-string-code
3301 "Completion string code must work for (i)pdb.")
3303 (defcustom python-shell-completion-string-code
3304 "';'.join(__PYTHON_EL_get_completions('''%s'''))"
3305 "Python code used to get a string of completions separated by semicolons.
3306 The string passed to the function is the current python name or
3307 the full statement in the case of imports."
3311 (defcustom python-shell-completion-native-disabled-interpreters
3312 ;; PyPy's readline cannot handle some escape sequences yet. Native
3313 ;; completion was found to be non-functional for IPython (see
3314 ;; Bug#25067). Native completion doesn't work on w32 (Bug#28580).
3315 (if (eq system-type
'windows-nt
) '("")
3316 '("pypy" "ipython"))
3317 "List of disabled interpreters.
3318 When a match is found, native completion is disabled."
3320 :type
'(repeat string
))
3322 (defcustom python-shell-completion-native-enable t
3323 "Enable readline based native completion."
3327 (defcustom python-shell-completion-native-output-timeout
5.0
3328 "Time in seconds to wait for completion output before giving up."
3332 (defcustom python-shell-completion-native-try-output-timeout
1.0
3333 "Time in seconds to wait for *trying* native completion output."
3337 (defvar python-shell-completion-native-redirect-buffer
3338 " *Python completions redirect*"
3339 "Buffer to be used to redirect output of readline commands.")
3341 (defun python-shell-completion-native-interpreter-disabled-p ()
3342 "Return non-nil if interpreter has native completion disabled."
3343 (when python-shell-completion-native-disabled-interpreters
3345 (regexp-opt python-shell-completion-native-disabled-interpreters
)
3346 (file-name-nondirectory python-shell-interpreter
))))
3348 (defun python-shell-completion-native-try ()
3349 "Return non-nil if can trigger native completion."
3350 (let ((python-shell-completion-native-enable t
)
3351 (python-shell-completion-native-output-timeout
3352 python-shell-completion-native-try-output-timeout
))
3353 (python-shell-completion-native-get-completions
3354 (get-buffer-process (current-buffer))
3357 (defun python-shell-completion-native-setup ()
3358 "Try to setup native completion, return non-nil on success."
3359 (let ((process (python-shell-get-process)))
3360 (with-current-buffer (process-buffer process
)
3361 (python-shell-send-string "
3362 def __PYTHON_EL_native_completion_setup():
3370 import builtins as __builtin__
3372 builtins = dir(__builtin__)
3373 is_ipython = ('__IPYTHON__' in builtins or
3374 '__IPYTHON__active' in builtins)
3376 class __PYTHON_EL_Completer:
3377 '''Completer wrapper that prints candidates to stdout.
3379 It wraps an existing completer function and changes its behavior so
3380 that the user input is unchanged and real candidates are printed to
3383 Returned candidates are '0__dummy_completion__' and
3384 '1__dummy_completion__' in that order ('0__dummy_completion__' is
3385 returned repeatedly until all possible candidates are consumed).
3387 The real candidates are printed to stdout so that they can be
3388 easily retrieved through comint output redirect trickery.
3391 PYTHON_EL_WRAPPED = True
3393 def __init__(self, completer):
3394 self.completer = completer
3395 self.last_completion = None
3396 self.print_mode = True
3398 def __call__(self, text, state):
3400 # Set the first dummy completion.
3401 self.last_completion = None
3402 completion = '0__dummy_completion__'
3404 completion = self.completer(text, state - 1)
3407 if self.last_completion != '1__dummy_completion__':
3408 # When no more completions are available, returning a
3409 # dummy with non-sharing prefix allow ensuring output
3410 # while preventing changes to current input.
3411 # Coincidentally it's also the end of output.
3412 completion = '1__dummy_completion__'
3413 elif completion.endswith('('):
3414 # Remove parens on callables as it breaks completion on
3415 # arguments (e.g. str(Ari<tab>)).
3416 completion = completion[:-1]
3417 self.last_completion = completion
3420 '0__dummy_completion__', '1__dummy_completion__'):
3423 # For every non-dummy completion, return a repeated dummy
3424 # one and print the real candidate so it can be retrieved
3425 # by comint output filters.
3428 return '0__dummy_completion__'
3434 completer = readline.get_completer()
3437 # Used as last resort to avoid breaking customizations.
3439 completer = readline.get_completer()
3441 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3442 # Wrap the existing completer function only once.
3443 new_completer = __PYTHON_EL_Completer(completer)
3445 readline.set_completer(new_completer)
3447 # Try both initializations to cope with all IPython versions.
3448 # This works fine for IPython 3.x but not for earlier:
3449 readline.set_completer(new_completer)
3450 # IPython<3 hacks readline such that `readline.set_completer`
3451 # won't work. This workaround injects the new completer
3452 # function into the existing instance directly:
3453 instance = getattr(completer, 'im_self', completer.__self__)
3454 instance.rlcomplete = new_completer
3456 if readline.__doc__ and 'libedit' in readline.__doc__:
3457 raise Exception('''libedit based readline is known not to work,
3458 see etc/PROBLEMS under \"In Inferior Python mode, input is echoed\".''')
3459 readline.parse_and_bind('bind ^I rl_complete')
3461 readline.parse_and_bind('tab: complete')
3462 # Require just one tab to send output.
3463 readline.parse_and_bind('set show-all-if-ambiguous on')
3465 print ('python.el: native completion setup loaded')
3468 print ('python.el: native completion setup failed, %s: %s'
3469 % sys.exc_info()[:2])
3471 __PYTHON_EL_native_completion_setup()" process
)
3473 (python-shell-accept-process-output
3474 process python-shell-completion-native-try-output-timeout
)
3477 (regexp-quote "python.el: native completion setup loaded") nil t
1)))
3478 (python-shell-completion-native-try)))))
3480 (defun python-shell-completion-native-turn-off (&optional msg
)
3481 "Turn off shell native completions.
3482 With argument MSG show deactivation message."
3484 (python-shell-with-shell-buffer
3485 (set (make-local-variable 'python-shell-completion-native-enable
) nil
)
3487 (message "Shell native completion is disabled, using fallback"))))
3489 (defun python-shell-completion-native-turn-on (&optional msg
)
3490 "Turn on shell native completions.
3491 With argument MSG show deactivation message."
3493 (python-shell-with-shell-buffer
3494 (set (make-local-variable 'python-shell-completion-native-enable
) t
)
3495 (python-shell-completion-native-turn-on-maybe msg
)))
3497 (defun python-shell-completion-native-turn-on-maybe (&optional msg
)
3498 "Turn on native completions if enabled and available.
3499 With argument MSG show activation/deactivation message."
3501 (python-shell-with-shell-buffer
3502 (when python-shell-completion-native-enable
3504 ((python-shell-completion-native-interpreter-disabled-p)
3505 (python-shell-completion-native-turn-off msg
))
3506 ((python-shell-completion-native-setup)
3508 (message "Shell native completion is enabled.")))
3510 '(python python-shell-completion-native-turn-on-maybe
)
3513 "Your `python-shell-interpreter' doesn't seem to "
3514 "support readline, yet `python-shell-completion-native-enable' "
3515 (format "was t and %S is not part of the "
3516 (file-name-nondirectory python-shell-interpreter
))
3517 "`python-shell-completion-native-disabled-interpreters' "
3518 "list. Native completions have been disabled locally. "))
3519 (python-shell-completion-native-turn-off msg
))))))
3521 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3522 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3523 (python-shell-completion-native-turn-on-maybe t
))
3525 (add-hook 'python-shell-first-prompt-hook
3526 #'python-shell-completion-native-turn-on-maybe-with-msg
)
3528 (defun python-shell-completion-native-toggle (&optional msg
)
3529 "Toggle shell native completion.
3530 With argument MSG show activation/deactivation message."
3532 (python-shell-with-shell-buffer
3533 (if python-shell-completion-native-enable
3534 (python-shell-completion-native-turn-off msg
)
3535 (python-shell-completion-native-turn-on msg
))
3536 python-shell-completion-native-enable
))
3538 (defun python-shell-completion-native-get-completions (process import input
)
3539 "Get completions using native readline for PROCESS.
3540 When IMPORT is non-nil takes precedence over INPUT for
3542 (with-current-buffer (process-buffer process
)
3543 (let* ((input (or import input
))
3544 (original-filter-fn (process-filter process
))
3545 (redirect-buffer (get-buffer-create
3546 python-shell-completion-native-redirect-buffer
))
3548 (new-input (concat input trigger
))
3551 (+ (- (point-max) (comint-bol)) (length new-input
))))
3552 (delete-line-command (make-string input-length ?
\b))
3553 (input-to-send (concat new-input delete-line-command
)))
3554 ;; Ensure restoring the process filter, even if the user quits
3555 ;; or there's some other error.
3557 (with-current-buffer redirect-buffer
3558 ;; Cleanup the redirect buffer
3560 ;; Mimic `comint-redirect-send-command', unfortunately it
3561 ;; can't be used here because it expects a newline in the
3562 ;; command and that's exactly what we are trying to avoid.
3563 (let ((comint-redirect-echo-input nil
)
3564 (comint-redirect-completed nil
)
3565 (comint-redirect-perform-sanity-check nil
)
3566 (comint-redirect-insert-matching-regexp t
)
3567 (comint-redirect-finished-regexp
3568 "1__dummy_completion__[[:space:]]*\n")
3569 (comint-redirect-output-buffer redirect-buffer
))
3570 ;; Compatibility with Emacs 24.x. Comint changed and
3571 ;; now `comint-redirect-filter' gets 3 args. This
3572 ;; checks which version of `comint-redirect-filter' is
3573 ;; in use based on its args and uses `apply-partially'
3574 ;; to make it up for the 3 args case.
3576 (help-function-arglist 'comint-redirect-filter
)) 3)
3578 process
(apply-partially
3579 #'comint-redirect-filter original-filter-fn
))
3580 (set-process-filter process
#'comint-redirect-filter
))
3581 (process-send-string process input-to-send
)
3582 ;; Grab output until our dummy completion used as
3583 ;; output end marker is found.
3584 (when (python-shell-accept-process-output
3585 process python-shell-completion-native-output-timeout
3586 comint-redirect-finished-regexp
)
3587 (re-search-backward "0__dummy_completion__" nil t
)
3588 (cl-remove-duplicates
3590 (buffer-substring-no-properties
3591 (line-beginning-position) (point-min))
3592 "[ \f\t\n\r\v()]+" t
)
3594 (set-process-filter process original-filter-fn
)))))
3596 (defun python-shell-completion-get-completions (process import input
)
3597 "Do completion at point using PROCESS for IMPORT or INPUT.
3598 When IMPORT is non-nil takes precedence over INPUT for
3600 (setq input
(or import input
))
3601 (with-current-buffer (process-buffer process
)
3603 (python-util-strip-string
3604 (python-shell-send-string-no-output
3606 (concat python-shell-completion-setup-code
3607 "\nprint (" python-shell-completion-string-code
")")
3609 (when (> (length completions
) 2)
3610 (split-string completions
3611 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))
3613 (defun python-shell-completion-at-point (&optional process
)
3614 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3615 Optional argument PROCESS forces completions to be retrieved
3616 using that one instead of current buffer's process."
3617 (setq process
(or process
(get-buffer-process (current-buffer))))
3618 (let* ((line-start (if (derived-mode-p 'inferior-python-mode
)
3619 ;; Working on a shell buffer: use prompt end.
3620 (cdr (python-util-comint-last-prompt))
3621 (line-beginning-position)))
3623 (when (string-match-p
3624 (rx (* space
) word-start
(or "from" "import") word-end space
)
3625 (buffer-substring-no-properties line-start
(point)))
3626 (buffer-substring-no-properties line-start
(point))))
3629 (if (not (re-search-backward
3631 (or whitespace open-paren close-paren string-delimiter
))
3635 (forward-char (length (match-string-no-properties 0)))
3639 (with-current-buffer (process-buffer process
)
3640 (python-util-comint-last-prompt)))
3642 (with-current-buffer (process-buffer process
)
3643 (when prompt-boundaries
3644 (buffer-substring-no-properties
3645 (car prompt-boundaries
) (cdr prompt-boundaries
)))))
3647 (with-current-buffer (process-buffer process
)
3648 (cond ((or (null prompt
)
3649 (< (point) (cdr prompt-boundaries
)))
3651 ((or (not python-shell-completion-native-enable
)
3652 ;; Even if native completion is enabled, for
3653 ;; pdb interaction always use the fallback
3654 ;; mechanism since the completer is changed.
3655 ;; Also, since pdb interaction is single-line
3656 ;; based, this is enough.
3657 (string-match-p python-shell-prompt-pdb-regexp prompt
))
3658 (if (or (equal python-shell--block-prompt prompt
)
3660 python-shell-prompt-block-regexp prompt
))
3661 ;; The non-native completion mechanism sends
3662 ;; newlines to the interpreter, so we can't use
3663 ;; it during a multiline statement (Bug#28051).
3665 #'python-shell-completion-get-completions
))
3666 (t #'python-shell-completion-native-get-completions
)))))
3668 (completion-table-dynamic
3671 process import-statement
)))))
3673 (define-obsolete-function-alias
3674 'python-shell-completion-complete-at-point
3675 'python-shell-completion-at-point
3678 (defun python-shell-completion-complete-or-indent ()
3679 "Complete or indent depending on the context.
3680 If content before pointer is all whitespace, indent.
3681 If not try to complete."
3683 (if (string-match "^[[:space:]]*$"
3684 (buffer-substring (comint-line-beginning-position)
3686 (indent-for-tab-command)
3687 (completion-at-point)))
3690 ;;; PDB Track integration
3692 (defcustom python-pdbtrack-activate t
3693 "Non-nil makes Python shell enable pdbtracking."
3698 (defcustom python-pdbtrack-stacktrace-info-regexp
3699 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3700 "Regular expression matching stacktrace information.
3701 Used to extract the current line and module being inspected."
3706 (defvar python-pdbtrack-tracked-buffer nil
3707 "Variable containing the value of the current tracked buffer.
3708 Never set this variable directly, use
3709 `python-pdbtrack-set-tracked-buffer' instead.")
3711 (defvar python-pdbtrack-buffers-to-kill nil
3712 "List of buffers to be deleted after tracking finishes.")
3714 (defun python-pdbtrack-set-tracked-buffer (file-name)
3715 "Set the buffer for FILE-NAME as the tracked buffer.
3716 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3717 Returns the tracked buffer."
3718 (let* ((file-name-prospect (concat (file-remote-p default-directory
)
3720 (file-buffer (get-file-buffer file-name-prospect
)))
3722 (setq python-pdbtrack-tracked-buffer file-buffer
)
3724 ((file-exists-p file-name-prospect
)
3725 (setq file-buffer
(find-file-noselect file-name-prospect
)))
3726 ((and (not (equal file-name file-name-prospect
))
3727 (file-exists-p file-name
))
3728 ;; Fallback to a locally available copy of the file.
3729 (setq file-buffer
(find-file-noselect file-name-prospect
))))
3730 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3731 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3734 (defun python-pdbtrack-comint-output-filter-function (output)
3735 "Move overlay arrow to current pdb line in tracked buffer.
3736 Argument OUTPUT is a string with the output from the comint process."
3737 (when (and python-pdbtrack-activate
(not (string= output
"")))
3738 (let* ((full-output (ansi-color-filter-apply
3739 (buffer-substring comint-last-input-end
(point-max))))
3743 (insert full-output
)
3744 ;; When the debugger encounters a pdb.set_trace()
3745 ;; command, it prints a single stack frame. Sometimes
3746 ;; it prints a bit of extra information about the
3747 ;; arguments of the present function. When ipdb
3748 ;; encounters an exception, it prints the _entire_ stack
3749 ;; trace. To handle all of these cases, we want to find
3750 ;; the _last_ stack frame printed in the most recent
3751 ;; batch of output, then jump to the corresponding
3752 ;; file/line number.
3753 (goto-char (point-max))
3754 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3755 (setq line-number
(string-to-number
3756 (match-string-no-properties 2)))
3757 (match-string-no-properties 1)))))
3758 (if (and file-name line-number
)
3759 (let* ((tracked-buffer
3760 (python-pdbtrack-set-tracked-buffer file-name
))
3761 (shell-buffer (current-buffer))
3762 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3763 (tracked-buffer-line-pos))
3764 (with-current-buffer tracked-buffer
3765 (set (make-local-variable 'overlay-arrow-string
) "=>")
3766 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3767 (setq tracked-buffer-line-pos
(progn
3768 (goto-char (point-min))
3769 (forward-line (1- line-number
))
3771 (when tracked-buffer-window
3773 tracked-buffer-window tracked-buffer-line-pos
))
3774 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3775 (pop-to-buffer tracked-buffer
)
3776 (switch-to-buffer-other-window shell-buffer
))
3777 (when python-pdbtrack-tracked-buffer
3778 (with-current-buffer python-pdbtrack-tracked-buffer
3779 (set-marker overlay-arrow-position nil
))
3780 (mapc #'(lambda (buffer)
3781 (ignore-errors (kill-buffer buffer
)))
3782 python-pdbtrack-buffers-to-kill
)
3783 (setq python-pdbtrack-tracked-buffer nil
3784 python-pdbtrack-buffers-to-kill nil
)))))
3788 ;;; Symbol completion
3790 (defun python-completion-at-point ()
3791 "Function for `completion-at-point-functions' in `python-mode'.
3792 For this to work as best as possible you should call
3793 `python-shell-send-buffer' from time to time so context in
3794 inferior Python process is updated properly."
3795 (let ((process (python-shell-get-process)))
3797 (python-shell-completion-at-point process
))))
3799 (define-obsolete-function-alias
3800 'python-completion-complete-at-point
3801 'python-completion-at-point
3807 (defcustom python-fill-comment-function
'python-fill-comment
3808 "Function to fill comments.
3809 This is the function used by `python-fill-paragraph' to
3814 (defcustom python-fill-string-function
'python-fill-string
3815 "Function to fill strings.
3816 This is the function used by `python-fill-paragraph' to
3821 (defcustom python-fill-decorator-function
'python-fill-decorator
3822 "Function to fill decorators.
3823 This is the function used by `python-fill-paragraph' to
3828 (defcustom python-fill-paren-function
'python-fill-paren
3829 "Function to fill parens.
3830 This is the function used by `python-fill-paragraph' to
3835 (defcustom python-fill-docstring-style
'pep-257
3836 "Style used to fill docstrings.
3837 This affects `python-fill-string' behavior with regards to
3838 triple quotes positioning.
3840 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3841 `symmetric', and nil. A value of nil won't care about quotes
3842 position and will treat docstrings a normal string, any other
3843 value may result in one of the following docstring styles:
3848 Process foo, return bar.
3852 Process foo, return bar.
3854 If processing fails throw ProcessingError.
3859 \"\"\"Process foo, return bar.\"\"\"
3862 Process foo, return bar.
3864 If processing fails throw ProcessingError.
3870 \"\"\"Process foo, return bar.\"\"\"
3872 \"\"\"Process foo, return bar.
3874 If processing fails throw ProcessingError.
3880 \"\"\"Process foo, return bar.\"\"\"
3882 \"\"\"Process foo, return bar.
3884 If processing fails throw ProcessingError.
3889 \"\"\"Process foo, return bar.\"\"\"
3892 Process foo, return bar.
3894 If processing fails throw ProcessingError.
3897 (const :tag
"Don't format docstrings" nil
)
3898 (const :tag
"Django's coding standards style." django
)
3899 (const :tag
"One newline and start and Two at end style." onetwo
)
3900 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3901 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3902 (const :tag
"Symmetric style." symmetric
))
3905 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3907 (defun python-fill-paragraph (&optional justify
)
3908 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3909 If any of the current line is in or at the end of a multi-line string,
3910 fill the string or the paragraph of it that point is in, preserving
3911 the string's indentation.
3912 Optional argument JUSTIFY defines if the paragraph should be justified."
3917 ((python-syntax-context 'comment
)
3918 (funcall python-fill-comment-function justify
))
3919 ;; Strings/Docstrings
3920 ((save-excursion (or (python-syntax-context 'string
)
3921 (equal (string-to-syntax "|")
3922 (syntax-after (point)))))
3923 (funcall python-fill-string-function justify
))
3925 ((equal (char-after (save-excursion
3926 (python-nav-beginning-of-statement))) ?
@)
3927 (funcall python-fill-decorator-function justify
))
3929 ((or (python-syntax-context 'paren
)
3930 (looking-at (python-rx open-paren
))
3932 (skip-syntax-forward "^(" (line-end-position))
3933 (looking-at (python-rx open-paren
))))
3934 (funcall python-fill-paren-function justify
))
3937 (defun python-fill-comment (&optional justify
)
3938 "Comment fill function for `python-fill-paragraph'.
3939 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3940 (fill-comment-paragraph justify
))
3942 (defun python-fill-string (&optional justify
)
3943 "String fill function for `python-fill-paragraph'.
3944 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3945 (let* ((str-start-pos
3948 (or (python-syntax-context 'string
)
3949 (and (equal (string-to-syntax "|")
3950 (syntax-after (point)))
3952 (num-quotes (python-syntax-count-quotes
3953 (char-after str-start-pos
) str-start-pos
))
3956 (goto-char (+ str-start-pos num-quotes
))
3957 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3958 (goto-char (point-max)))
3961 ;; Docstring styles may vary for oneliners and multi-liners.
3962 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3964 (pcase python-fill-docstring-style
3965 ;; delimiters-style is a cons cell with the form
3966 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3967 ;; is NIL means to not add any newlines for start or end
3968 ;; of docstring. See `python-fill-docstring-style' for a
3969 ;; graphic idea of each style.
3970 (`django
(cons 1 1))
3971 (`onetwo
(and multi-line-p
(cons 1 2)))
3972 (`pep-257
(and multi-line-p
(cons nil
2)))
3973 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3974 (`symmetric
(and multi-line-p
(cons 1 1)))))
3975 (fill-paragraph-function))
3977 (narrow-to-region str-start-pos str-end-pos
)
3978 (fill-paragraph justify
))
3980 (when (and (python-info-docstring-p) python-fill-docstring-style
)
3981 ;; Add the number of newlines indicated by the selected style
3982 ;; at the start of the docstring.
3983 (goto-char (+ str-start-pos num-quotes
))
3984 (delete-region (point) (progn
3985 (skip-syntax-forward "> ")
3987 (and (car delimiters-style
)
3988 (or (newline (car delimiters-style
)) t
)
3989 ;; Indent only if a newline is added.
3990 (indent-according-to-mode))
3991 ;; Add the number of newlines indicated by the selected style
3992 ;; at the end of the docstring.
3993 (goto-char (if (not (= str-end-pos
(point-max)))
3994 (- str-end-pos num-quotes
)
3996 (delete-region (point) (progn
3997 (skip-syntax-backward "> ")
3999 (and (cdr delimiters-style
)
4000 ;; Add newlines only if string ends.
4001 (not (= str-end-pos
(point-max)))
4002 (or (newline (cdr delimiters-style
)) t
)
4003 ;; Again indent only if a newline is added.
4004 (indent-according-to-mode))))) t
)
4006 (defun python-fill-decorator (&optional _justify
)
4007 "Decorator fill function for `python-fill-paragraph'.
4008 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
4011 (defun python-fill-paren (&optional justify
)
4012 "Paren fill function for `python-fill-paragraph'.
4013 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
4015 (narrow-to-region (progn
4016 (while (python-syntax-context 'paren
)
4017 (goto-char (1- (point))))
4018 (line-beginning-position))
4020 (when (not (python-syntax-context 'paren
))
4022 (when (not (python-syntax-context 'paren
))
4023 (skip-syntax-backward "^)")))
4024 (while (and (python-syntax-context 'paren
)
4026 (goto-char (1+ (point))))
4028 (let ((paragraph-start "\f\\|[ \t]*$")
4029 (paragraph-separate ",")
4030 (fill-paragraph-function))
4031 (goto-char (point-min))
4032 (fill-paragraph justify
))
4035 (python-indent-line)
4036 (goto-char (line-end-position))))
4042 (define-obsolete-variable-alias
4043 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
4045 (defcustom python-skeleton-autoinsert nil
4046 "Non-nil means template skeletons will be automagically inserted.
4047 This happens when pressing \"if<SPACE>\", for example, to prompt for
4053 (defvar python-skeleton-available
'()
4054 "Internal list of available skeletons.")
4056 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
4057 "Abbrev table for Python mode skeletons."
4059 ;; Allow / inside abbrevs.
4060 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
4061 ;; Only expand in code.
4062 :enable-function
(lambda ()
4064 (not (python-syntax-comment-or-string-p))
4065 python-skeleton-autoinsert
)))
4067 (defmacro python-skeleton-define
(name doc
&rest skel
)
4068 "Define a `python-mode' skeleton using NAME DOC and SKEL.
4069 The skeleton will be bound to python-skeleton-NAME and will
4070 be added to `python-mode-skeleton-abbrev-table'."
4071 (declare (indent 2))
4072 (let* ((name (symbol-name name
))
4073 (function-name (intern (concat "python-skeleton-" name
))))
4075 (define-abbrev python-mode-skeleton-abbrev-table
4076 ,name
"" ',function-name
:system t
)
4077 (setq python-skeleton-available
4078 (cons ',function-name python-skeleton-available
))
4079 (define-skeleton ,function-name
4081 (format "Insert %s statement." name
))
4084 (define-abbrev-table 'python-mode-abbrev-table
()
4085 "Abbrev table for Python mode."
4086 :parents
(list python-mode-skeleton-abbrev-table
))
4088 (defmacro python-define-auxiliary-skeleton
(name &optional doc
&rest skel
)
4089 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
4090 The skeleton will be bound to python-skeleton-NAME."
4091 (declare (indent 2))
4092 (let* ((name (symbol-name name
))
4093 (function-name (intern (concat "python-skeleton--" name
)))
4094 (msg (funcall (if (fboundp 'format-message
) #'format-message
#'format
)
4095 "Add `%s' clause? " name
)))
4098 `(< ,(format "%s:" name
) \n \n
4100 `(define-skeleton ,function-name
4102 (format "Auxiliary skeleton for %s statement." name
))
4104 (unless (y-or-n-p ,msg
)
4108 (python-define-auxiliary-skeleton else
)
4110 (python-define-auxiliary-skeleton except
)
4112 (python-define-auxiliary-skeleton finally
)
4114 (python-skeleton-define if nil
4118 ("other condition, %s: "
4122 '(python-skeleton--else) | ^
)
4124 (python-skeleton-define while nil
4128 '(python-skeleton--else) | ^
)
4130 (python-skeleton-define for nil
4134 '(python-skeleton--else) | ^
)
4136 (python-skeleton-define import nil
4137 "Import from module: "
4138 "from " str
& " " | -
5
4140 ("Identifier: " str
", ") -
2 \n _
)
4142 (python-skeleton-define try nil
4148 "except " str
":" \n
4151 '(python-skeleton--except)
4152 '(python-skeleton--else)
4153 '(python-skeleton--finally) | ^
)
4155 (python-skeleton-define def nil
4157 "def " str
"(" ("Parameter, %s: "
4158 (unless (equal ?\
( (char-before)) ", ")
4160 "\"\"\"" -
"\"\"\"" \n
4163 (python-skeleton-define class nil
4165 "class " str
"(" ("Inheritance, %s: "
4166 (unless (equal ?\
( (char-before)) ", ")
4170 "\"\"\"" -
"\"\"\"" \n
4173 (defun python-skeleton-add-menu-items ()
4174 "Add menu items to Python->Skeletons menu."
4175 (let ((skeletons (sort python-skeleton-available
'string
<)))
4176 (dolist (skeleton skeletons
)
4178 nil
'("Python" "Skeletons")
4180 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
4185 (defcustom python-ffap-setup-code
4187 def __FFAP_get_module_path(objstr):
4191 # NameError exceptions are delayed until this point.
4193 module = inspect.getmodule(obj)
4194 filename = module.__file__
4195 ext = os.path.splitext(filename)[1]
4196 if ext in ('.pyc', '.pyo'):
4197 # Point to the source file.
4198 filename = filename[:-1]
4199 if os.path.exists(filename):
4204 "Python code to get a module path."
4208 (defcustom python-ffap-string-code
4209 "__FFAP_get_module_path('''%s''')"
4210 "Python code used to get a string with the path of a module."
4214 (defun python-ffap-module-path (module)
4215 "Function for `ffap-alist' to return path for MODULE."
4217 (and (derived-mode-p 'inferior-python-mode
)
4218 (get-buffer-process (current-buffer)))
4219 (python-shell-get-process))))
4223 (python-shell-send-string-no-output
4225 python-ffap-setup-code
4226 "\nprint (" (format python-ffap-string-code module
) ")")
4228 (unless (zerop (length module-file
))
4229 (python-util-strip-string module-file
))))))
4233 (eval-after-load "ffap"
4235 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
4236 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
4241 (defcustom python-check-command
4242 (or (executable-find "pyflakes")
4243 (executable-find "epylint")
4244 "install pyflakes, pylint or something else")
4245 "Command used to check a Python file."
4249 (defcustom python-check-buffer-name
4250 "*Python check: %s*"
4251 "Buffer name used for check commands."
4255 (defvar python-check-custom-command nil
4257 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
4258 (make-variable-buffer-local 'python-check-custom-command
)
4260 (defun python-check (command)
4261 "Check a Python file (default current buffer's file).
4262 Runs COMMAND, a shell command, as if by `compile'.
4263 See `python-check-command' for the default."
4265 (list (read-string "Check command: "
4266 (or python-check-custom-command
4267 (concat python-check-command
" "
4268 (shell-quote-argument
4270 (let ((name (buffer-file-name)))
4272 (file-name-nondirectory name
)))
4274 (setq python-check-custom-command command
)
4275 (save-some-buffers (not compilation-ask-about-save
) nil
)
4276 (python-shell-with-environment
4277 (compilation-start command nil
4279 (format python-check-buffer-name command
)))))
4284 (defcustom python-eldoc-setup-code
4285 "def __PYDOC_get_help(obj):
4289 str_type = basestring
4290 argspec_function = inspect.getargspec
4293 argspec_function = inspect.getfullargspec
4294 if isinstance(obj, str_type):
4295 obj = eval(obj, globals())
4296 doc = inspect.getdoc(obj)
4297 if not doc and callable(obj):
4299 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4300 target = obj.__init__
4306 args = inspect.formatargspec(*argspec_function(target))
4308 doc = '{objtype} {name}{args}'.format(
4309 objtype=objtype, name=name, args=args
4312 doc = doc.splitlines()[0]
4316 "Python code to setup documentation retrieval."
4320 (defcustom python-eldoc-string-code
4321 "__PYDOC_get_help('''%s''')"
4322 "Python code used to get a string with the documentation of an object."
4326 (defun python-eldoc--get-symbol-at-point ()
4327 "Get the current symbol for eldoc.
4328 Returns the current symbol handling point within arguments."
4330 (let ((start (python-syntax-context 'paren
)))
4335 (memq (char-syntax (char-after)) '(?\ ?-
)))
4336 ;; Try to adjust to closest symbol if not in one.
4337 (python-util-forward-comment -
1)))
4338 (python-info-current-symbol t
)))
4340 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
4341 "Internal implementation to get documentation at point.
4342 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4343 returns will be used. If not FORCE-PROCESS is passed what
4344 `python-shell-get-process' returns is used."
4345 (let ((process (or force-process
(python-shell-get-process))))
4347 (let* ((input (or force-input
4348 (python-eldoc--get-symbol-at-point)))
4351 ;; Prevent resizing the echo area when iPython is
4352 ;; enabled. Bug#18794.
4353 (python-util-strip-string
4354 (python-shell-send-string-no-output
4356 python-eldoc-setup-code
4357 "\nprint(" (format python-eldoc-string-code input
) ")")
4359 (unless (zerop (length docstring
))
4362 (defvar-local python-eldoc-get-doc t
4363 "Non-nil means eldoc should fetch the documentation
4364 automatically. Set to nil by `python-eldoc-function' if
4365 `python-eldoc-function-timeout-permanent' is non-nil and
4366 `python-eldoc-function' times out.")
4368 (defcustom python-eldoc-function-timeout
1
4369 "Timeout for `python-eldoc-function' in seconds."
4374 (defcustom python-eldoc-function-timeout-permanent t
4375 "Non-nil means that when `python-eldoc-function' times out
4376 `python-eldoc-get-doc' will be set to nil"
4381 (defun python-eldoc-function ()
4382 "`eldoc-documentation-function' for Python.
4383 For this to work as best as possible you should call
4384 `python-shell-send-buffer' from time to time so context in
4385 inferior Python process is updated properly.
4387 If `python-eldoc-function-timeout' seconds elapse before this
4388 function returns then if
4389 `python-eldoc-function-timeout-permanent' is non-nil
4390 `python-eldoc-get-doc' will be set to nil and eldoc will no
4391 longer return the documentation at the point automatically.
4393 Set `python-eldoc-get-doc' to t to reenable eldoc documentation
4395 (when python-eldoc-get-doc
4396 (with-timeout (python-eldoc-function-timeout
4397 (if python-eldoc-function-timeout-permanent
4399 (message "Eldoc echo-area display muted in this buffer, see `python-eldoc-function'")
4400 (setq python-eldoc-get-doc nil
))
4401 (message "`python-eldoc-function' timed out, see `python-eldoc-function-timeout'")))
4402 (python-eldoc--get-doc-at-point))))
4404 (defun python-eldoc-at-point (symbol)
4405 "Get help on SYMBOL using `help'.
4406 Interactively, prompt for symbol."
4408 (let ((symbol (python-eldoc--get-symbol-at-point))
4409 (enable-recursive-minibuffers t
))
4410 (list (read-string (if symbol
4411 (format "Describe symbol (default %s): " symbol
)
4412 "Describe symbol: ")
4414 (message (python-eldoc--get-doc-at-point symbol
)))
4416 (defun python-describe-at-point (symbol process
)
4417 (interactive (list (python-info-current-symbol)
4418 (python-shell-get-process)))
4419 (comint-send-string process
(concat "help('" symbol
"')\n")))
4424 (defun python-hideshow-forward-sexp-function (arg)
4425 "Python specific `forward-sexp' function for `hs-minor-mode'.
4426 Argument ARG is ignored."
4427 arg
; Shut up, byte compiler.
4428 (python-nav-end-of-defun)
4429 (unless (python-info-current-line-empty-p)
4435 (defvar python-imenu-format-item-label-function
4436 'python-imenu-format-item-label
4437 "Imenu function used to format an item label.
4438 It must be a function with two arguments: TYPE and NAME.")
4440 (defvar python-imenu-format-parent-item-label-function
4441 'python-imenu-format-parent-item-label
4442 "Imenu function used to format a parent item label.
4443 It must be a function with two arguments: TYPE and NAME.")
4445 (defvar python-imenu-format-parent-item-jump-label-function
4446 'python-imenu-format-parent-item-jump-label
4447 "Imenu function used to format a parent jump item label.
4448 It must be a function with two arguments: TYPE and NAME.")
4450 (defun python-imenu-format-item-label (type name
)
4451 "Return Imenu label for single node using TYPE and NAME."
4452 (format "%s (%s)" name type
))
4454 (defun python-imenu-format-parent-item-label (type name
)
4455 "Return Imenu label for parent node using TYPE and NAME."
4456 (format "%s..." (python-imenu-format-item-label type name
)))
4458 (defun python-imenu-format-parent-item-jump-label (type _name
)
4459 "Return Imenu label for parent node jump using TYPE and NAME."
4460 (if (string= type
"class")
4461 "*class definition*"
4462 "*function definition*"))
4464 (defun python-imenu--get-defun-type-name ()
4465 "Return defun type and name at current position."
4466 (when (looking-at python-nav-beginning-of-defun-regexp
)
4467 (let ((split (split-string (match-string-no-properties 0))))
4468 (if (= (length split
) 2)
4470 (list (concat (car split
) " " (cadr split
))
4471 (car (last split
)))))))
4473 (defun python-imenu--put-parent (type name pos tree
)
4474 "Add the parent with TYPE, NAME and POS to TREE."
4476 (funcall python-imenu-format-item-label-function type name
))
4478 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
4481 (cons label
(cons (cons jump-label pos
) tree
)))))
4483 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
4484 "Recursively build the tree of nested definitions of a node.
4485 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4486 not be passed explicitly unless you know what you are doing."
4487 (setq min-indent
(or min-indent
0)
4488 prev-indent
(or prev-indent python-indent-offset
))
4489 (let* ((pos (python-nav-backward-defun))
4490 (defun-type-name (and pos
(python-imenu--get-defun-type-name)))
4491 (type (car defun-type-name
))
4492 (name (cadr defun-type-name
))
4494 (funcall python-imenu-format-item-label-function type name
)))
4495 (indent (current-indentation))
4496 (children-indent-limit (+ python-indent-offset min-indent
)))
4498 ;; Nothing found, probably near to bobp.
4500 ((<= indent min-indent
)
4501 ;; The current indentation points that this is a parent
4502 ;; node, add it to the tree and stop recursing.
4503 (python-imenu--put-parent type name pos tree
))
4505 (python-imenu--build-tree
4508 (if (<= indent children-indent-limit
)
4509 ;; This lies within the children indent offset range,
4510 ;; so it's a normal child of its parent (i.e., not
4511 ;; a child of a child).
4512 (cons (cons label pos
) tree
)
4513 ;; Oh no, a child of a child?! Fear not, we
4514 ;; know how to roll. We recursively parse these by
4515 ;; swapping prev-indent and min-indent plus adding this
4516 ;; newly found item to a fresh subtree. This works, I
4519 (python-imenu--build-tree
4520 prev-indent indent
(list (cons label pos
)))
4523 (defun python-imenu-create-index ()
4524 "Return tree Imenu alist for the current Python buffer.
4525 Change `python-imenu-format-item-label-function',
4526 `python-imenu-format-parent-item-label-function',
4527 `python-imenu-format-parent-item-jump-label-function' to
4528 customize how labels are formatted."
4529 (goto-char (point-max))
4532 (while (setq tree
(python-imenu--build-tree))
4533 (setq index
(cons tree index
)))
4536 (defun python-imenu-create-flat-index (&optional alist prefix
)
4537 "Return flat outline of the current Python buffer for Imenu.
4538 Optional argument ALIST is the tree to be flattened; when nil
4539 `python-imenu-build-index' is used with
4540 `python-imenu-format-parent-item-jump-label-function'
4541 `python-imenu-format-parent-item-label-function'
4542 `python-imenu-format-item-label-function' set to
4543 (lambda (type name) name)
4544 Optional argument PREFIX is used in recursive calls and should
4545 not be passed explicitly.
4552 (\"decorator\" . 173)
4555 (\"wrapped_f\" . 393))))
4561 (\"decorator\" . 173)
4562 (\"decorator.wrap\" . 353)
4563 (\"decorator.wrapped_f\" . 393))"
4564 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4569 (let ((name (if prefix
4570 (concat prefix
"." (car item
))
4573 (cond ((or (numberp pos
) (markerp pos
))
4574 (list (cons name pos
)))
4577 (cons name
(cdar pos
))
4578 (python-imenu-create-flat-index (cddr item
) name
))))))
4580 (let* ((fn (lambda (_type name
) name
))
4581 (python-imenu-format-item-label-function fn
)
4582 (python-imenu-format-parent-item-label-function fn
)
4583 (python-imenu-format-parent-item-jump-label-function fn
))
4584 (python-imenu-create-index))))))
4589 (defun python-info-current-defun (&optional include-type
)
4590 "Return name of surrounding function with Python compatible dotty syntax.
4591 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4592 This function can be used as the value of `add-log-current-defun-function'
4593 since it returns nil if point is not inside a defun."
4599 (starting-indentation (current-indentation))
4600 (starting-pos (point))
4605 (while (python-nav-beginning-of-defun 1)
4606 (when (save-match-data
4608 (or (not last-indent
)
4609 (< (current-indentation) last-indent
))
4613 ;; If this is the first run, we may add
4614 ;; the current defun at point.
4615 (setq first-run nil
)
4616 (goto-char starting-pos
)
4617 (python-nav-beginning-of-statement)
4618 (beginning-of-line 1)
4620 python-nav-beginning-of-defun-regexp
)))
4624 (+ (current-indentation)
4625 python-indent-offset
)))
4626 (if (< starting-indentation min-indent
)
4627 ;; If the starting indentation is not
4628 ;; within the min defun indent make the
4631 ;; Else go to the end of defun and add
4632 ;; up the current indentation to the
4634 (python-nav-end-of-defun)
4636 (if (>= (current-indentation) min-indent
)
4637 (1+ (current-indentation))
4639 (save-match-data (setq last-indent
(current-indentation)))
4640 (if (or (not include-type
) type
)
4641 (setq names
(cons (match-string-no-properties 1) names
))
4642 (let ((match (split-string (match-string-no-properties 0))))
4643 (setq type
(car match
))
4644 (setq names
(cons (cadr match
) names
)))))
4645 ;; Stop searching ASAP.
4646 (and (= (current-indentation) 0) (throw 'exit t
))))
4648 (concat (and type
(format "%s " type
))
4649 (mapconcat 'identity names
".")))))))
4651 (defun python-info-current-symbol (&optional replace-self
)
4652 "Return current symbol using dotty syntax.
4653 With optional argument REPLACE-SELF convert \"self\" to current
4656 (and (not (python-syntax-comment-or-string-p))
4657 (with-syntax-table python-dotty-syntax-table
4658 (let ((sym (symbol-at-point)))
4660 (substring-no-properties (symbol-name sym
))))))))
4662 (if (not replace-self
)
4664 (let ((current-defun (python-info-current-defun)))
4665 (if (not current-defun
)
4667 (replace-regexp-in-string
4668 (python-rx line-start word-start
"self" word-end ?.
)
4670 (mapconcat 'identity
4671 (butlast (split-string current-defun
"\\."))
4675 (defun python-info-statement-starts-block-p ()
4676 "Return non-nil if current statement opens a block."
4678 (python-nav-beginning-of-statement)
4679 (looking-at (python-rx block-start
))))
4681 (defun python-info-statement-ends-block-p ()
4682 "Return non-nil if point is at end of block."
4683 (let ((end-of-block-pos (save-excursion
4684 (python-nav-end-of-block)))
4685 (end-of-statement-pos (save-excursion
4686 (python-nav-end-of-statement))))
4687 (and end-of-block-pos end-of-statement-pos
4688 (= end-of-block-pos end-of-statement-pos
))))
4690 (defun python-info-beginning-of-statement-p ()
4691 "Return non-nil if point is at beginning of statement."
4692 (= (point) (save-excursion
4693 (python-nav-beginning-of-statement)
4696 (defun python-info-end-of-statement-p ()
4697 "Return non-nil if point is at end of statement."
4698 (= (point) (save-excursion
4699 (python-nav-end-of-statement)
4702 (defun python-info-beginning-of-block-p ()
4703 "Return non-nil if point is at beginning of block."
4704 (and (python-info-beginning-of-statement-p)
4705 (python-info-statement-starts-block-p)))
4707 (defun python-info-end-of-block-p ()
4708 "Return non-nil if point is at end of block."
4709 (and (python-info-end-of-statement-p)
4710 (python-info-statement-ends-block-p)))
4712 (define-obsolete-function-alias
4713 'python-info-closing-block
4714 'python-info-dedenter-opening-block-position
"24.4")
4716 (defun python-info-dedenter-opening-block-position ()
4717 "Return the point of the closest block the current line closes.
4718 Returns nil if point is not on a dedenter statement or no opening
4719 block can be detected. The latter case meaning current file is
4720 likely an invalid python file."
4721 (let ((positions (python-info-dedenter-opening-block-positions))
4722 (indentation (current-indentation))
4724 (while (and (not position
)
4727 (goto-char (car positions
))
4728 (if (<= (current-indentation) indentation
)
4729 (setq position
(car positions
))
4730 (setq positions
(cdr positions
)))))
4733 (defun python-info-dedenter-opening-block-positions ()
4734 "Return points of blocks the current line may close sorted by closer.
4735 Returns nil if point is not on a dedenter statement or no opening
4736 block can be detected. The latter case meaning current file is
4737 likely an invalid python file."
4739 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4741 (goto-char dedenter-pos
)
4742 (let* ((cur-line (line-beginning-position))
4743 (pairs '(("elif" "elif" "if")
4744 ("else" "if" "elif" "except" "for" "while")
4745 ("except" "except" "try")
4746 ("finally" "else" "except" "try")))
4747 (dedenter (match-string-no-properties 0))
4748 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
4749 (collected-indentations)
4752 (while (python-nav--syntactically
4754 (re-search-backward (python-rx block-start
) nil t
))
4756 (let ((indentation (current-indentation)))
4757 (when (and (not (memq indentation collected-indentations
))
4758 (or (not collected-indentations
)
4759 (< indentation
(apply #'min collected-indentations
)))
4760 ;; There must be no line with indentation
4761 ;; smaller than `indentation' (except for
4762 ;; blank lines) between the found opening
4763 ;; block and the current line, otherwise it
4764 ;; is not an opening block.
4767 (let ((no-back-indent t
))
4769 (while (and (< (point) cur-line
)
4770 (setq no-back-indent
4771 (or (> (current-indentation) indentation
)
4772 (python-info-current-line-empty-p))))
4775 (setq collected-indentations
4776 (cons indentation collected-indentations
))
4777 (when (member (match-string-no-properties 0)
4778 possible-opening-blocks
)
4779 (setq opening-blocks
(cons (point) opening-blocks
))))
4780 (when (zerop indentation
)
4781 (throw 'exit nil
)))))
4783 (nreverse opening-blocks
))))))
4785 (define-obsolete-function-alias
4786 'python-info-closing-block-message
4787 'python-info-dedenter-opening-block-message
"24.4")
4789 (defun python-info-dedenter-opening-block-message ()
4790 "Message the first line of the block the current statement closes."
4791 (let ((point (python-info-dedenter-opening-block-position)))
4793 (message "Closes %s" (save-excursion
4796 (point) (line-end-position)))))))
4798 (defun python-info-dedenter-statement-p ()
4799 "Return point if current statement is a dedenter.
4800 Sets `match-data' to the keyword that starts the dedenter
4803 (python-nav-beginning-of-statement)
4804 (when (and (not (python-syntax-context-type))
4805 (looking-at (python-rx dedenter
)))
4808 (defun python-info-line-ends-backslash-p (&optional line-number
)
4809 "Return non-nil if current line ends with backslash.
4810 With optional argument LINE-NUMBER, check that line instead."
4813 (python-util-goto-line line-number
))
4814 (while (and (not (eobp))
4815 (goto-char (line-end-position))
4816 (python-syntax-context 'paren
)
4817 (not (equal (char-before (point)) ?
\\)))
4819 (when (equal (char-before) ?
\\)
4822 (defun python-info-beginning-of-backslash (&optional line-number
)
4823 "Return the point where the backslashed line starts.
4824 Optional argument LINE-NUMBER forces the line number to check against."
4827 (python-util-goto-line line-number
))
4828 (when (python-info-line-ends-backslash-p)
4829 (while (save-excursion
4830 (goto-char (line-beginning-position))
4831 (python-syntax-context 'paren
))
4833 (back-to-indentation)
4836 (defun python-info-continuation-line-p ()
4837 "Check if current line is continuation of another.
4838 When current line is continuation of another return the point
4839 where the continued line ends."
4841 (let* ((context-type (progn
4842 (back-to-indentation)
4843 (python-syntax-context-type)))
4844 (line-start (line-number-at-pos))
4845 (context-start (when context-type
4846 (python-syntax-context context-type
))))
4847 (cond ((equal context-type
'paren
)
4848 ;; Lines inside a paren are always a continuation line
4849 ;; (except the first one).
4850 (python-util-forward-comment -
1)
4852 ((member context-type
'(string comment
))
4853 ;; move forward an roll again
4854 (goto-char context-start
)
4855 (python-util-forward-comment)
4856 (python-info-continuation-line-p))
4858 ;; Not within a paren, string or comment, the only way
4859 ;; we are dealing with a continuation line is that
4860 ;; previous line contains a backslash, and this can
4861 ;; only be the previous line from current
4862 (back-to-indentation)
4863 (python-util-forward-comment -
1)
4864 (when (and (equal (1- line-start
) (line-number-at-pos))
4865 (python-info-line-ends-backslash-p))
4866 (point-marker)))))))
4868 (defun python-info-block-continuation-line-p ()
4869 "Return non-nil if current line is a continuation of a block."
4871 (when (python-info-continuation-line-p)
4873 (back-to-indentation)
4874 (when (looking-at (python-rx block-start
))
4877 (defun python-info-assignment-statement-p (&optional current-line-only
)
4878 "Check if current line is an assignment.
4879 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4880 continuations, just check the if current line is an assignment."
4883 (if current-line-only
4884 (back-to-indentation)
4885 (python-nav-beginning-of-statement))
4887 (re-search-forward (python-rx not-simple-operator
4889 (group not-simple-operator
))
4890 (line-end-position) t
)
4893 ;; The assignment operator should not be inside a string.
4894 (backward-char (length (match-string-no-properties 1)))
4895 (setq found
(not (python-syntax-context-type)))))
4897 (skip-syntax-forward " ")
4900 ;; TODO: rename to clarify this is only for the first continuation
4901 ;; line or remove it and move its body to `python-indent-context'.
4902 (defun python-info-assignment-continuation-line-p ()
4903 "Check if current line is the first continuation of an assignment.
4904 When current line is continuation of another with an assignment
4905 return the point of the first non-blank character after the
4908 (when (python-info-continuation-line-p)
4910 (python-info-assignment-statement-p t
))))
4912 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4913 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4914 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4916 (beginning-of-line 1)
4917 (looking-at python-nav-beginning-of-defun-regexp
))))
4919 (defun python-info-current-line-comment-p ()
4920 "Return non-nil if current line is a comment line."
4922 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4925 (defun python-info-current-line-empty-p ()
4926 "Return non-nil if current line is empty, ignoring whitespace."
4928 (beginning-of-line 1)
4930 (python-rx line-start
(* whitespace
)
4931 (group (* not-newline
))
4932 (* whitespace
) line-end
))
4933 (string-equal "" (match-string-no-properties 1))))
4935 (defun python-info-docstring-p (&optional syntax-ppss
)
4936 "Return non-nil if point is in a docstring.
4937 When optional argument SYNTAX-PPSS is given, use that instead of
4938 point's current `syntax-ppss'."
4939 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4941 (when (and syntax-ppss
(python-syntax-context 'string syntax-ppss
))
4942 (goto-char (nth 8 syntax-ppss
)))
4943 (python-nav-beginning-of-statement)
4945 (indentation (current-indentation))
4946 (backward-sexp-point)
4947 (re (concat "[uU]?[rR]?"
4948 (python-rx string-delimiter
))))
4950 (not (python-info-assignment-statement-p))
4952 ;; Allow up to two consecutive docstrings only.
4955 (let (last-backward-sexp-point)
4956 (while (save-excursion
4957 (python-nav-backward-sexp)
4958 (setq backward-sexp-point
(point))
4959 (and (= indentation
(current-indentation))
4960 ;; Make sure we're always moving point.
4961 ;; If we get stuck in the same position
4962 ;; on consecutive loop iterations,
4964 (prog1 (not (eql last-backward-sexp-point
4965 backward-sexp-point
))
4966 (setq last-backward-sexp-point
4967 backward-sexp-point
))
4969 (concat "[uU]?[rR]?"
4970 (python-rx string-delimiter
)))))
4971 ;; Previous sexp was a string, restore point.
4972 (goto-char backward-sexp-point
)
4975 (python-util-forward-comment -
1)
4976 (python-nav-beginning-of-statement)
4978 ((python-info-assignment-statement-p) t
)
4979 ((python-info-looking-at-beginning-of-defun))
4982 (defun python-info-encoding-from-cookie ()
4983 "Detect current buffer's encoding from its coding cookie.
4984 Returns the encoding as a symbol."
4985 (let ((first-two-lines
4989 (goto-char (point-min))
4991 (buffer-substring-no-properties
4994 (when (string-match (python-rx coding-cookie
) first-two-lines
)
4995 (intern (match-string-no-properties 1 first-two-lines
)))))
4997 (defun python-info-encoding ()
4998 "Return encoding for file.
4999 Try `python-info-encoding-from-cookie', if none is found then
5001 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
5002 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
5003 ;; in the worst case scenario python.el will make things work for
5004 ;; Python 2 files with unicode data and no encoding defined.
5005 (or (python-info-encoding-from-cookie)
5009 ;;; Utility functions
5011 (defun python-util-goto-line (line-number)
5012 "Move point to LINE-NUMBER."
5013 (goto-char (point-min))
5014 (forward-line (1- line-number
)))
5016 ;; Stolen from org-mode
5017 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
5018 "Clone local variables from FROM-BUFFER.
5019 Optional argument REGEXP selects variables to clone and defaults
5023 (and (symbolp (car pair
))
5024 (string-match (or regexp
"^python-")
5025 (symbol-name (car pair
)))
5026 (set (make-local-variable (car pair
))
5028 (buffer-local-variables from-buffer
)))
5030 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
5032 (defun python-util-comint-last-prompt ()
5033 "Return comint last prompt overlay start and end.
5034 This is for compatibility with Emacs < 24.4."
5035 (cond ((bound-and-true-p comint-last-prompt-overlay
)
5036 (cons (overlay-start comint-last-prompt-overlay
)
5037 (overlay-end comint-last-prompt-overlay
)))
5038 ((bound-and-true-p comint-last-prompt
)
5042 (defun python-util-forward-comment (&optional direction
)
5043 "Python mode specific version of `forward-comment'.
5044 Optional argument DIRECTION defines the direction to move to."
5045 (let ((comment-start (python-syntax-context 'comment
))
5046 (factor (if (< (or direction
0) 0)
5050 (goto-char comment-start
))
5051 (forward-comment factor
)))
5053 (defun python-util-list-directories (directory &optional predicate max-depth
)
5054 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
5055 Argument PREDICATE defaults to `identity' and must be a function
5056 that takes one argument (a full path) and returns non-nil for
5057 allowed files. When optional argument MAX-DEPTH is non-nil, stop
5058 searching when depth is reached, else don't limit."
5059 (let* ((dir (expand-file-name directory
))
5060 (dir-length (length dir
))
5061 (predicate (or predicate
#'identity
))
5062 (to-scan (list dir
))
5065 (let ((current-dir (car to-scan
)))
5066 (when (funcall predicate current-dir
)
5067 (setq tally
(cons current-dir tally
)))
5068 (setq to-scan
(append (cdr to-scan
)
5069 (python-util-list-files
5070 current-dir
#'file-directory-p
)
5072 (when (and max-depth
5074 (length (split-string
5075 (substring current-dir dir-length
)
5077 (setq to-scan nil
))))
5080 (defun python-util-list-files (dir &optional predicate
)
5081 "List files in DIR, filtering with PREDICATE.
5082 Argument PREDICATE defaults to `identity' and must be a function
5083 that takes one argument (a full path) and returns non-nil for
5085 (let ((dir-name (file-name-as-directory dir
)))
5087 (mapcar (lambda (file-name)
5088 (let ((full-file-name (expand-file-name file-name dir-name
)))
5090 (not (member file-name
'("." "..")))
5091 (funcall (or predicate
#'identity
) full-file-name
))
5092 (list full-file-name
))))
5093 (directory-files dir-name
)))))
5095 (defun python-util-list-packages (dir &optional max-depth
)
5096 "List packages in DIR, limited by MAX-DEPTH.
5097 When optional argument MAX-DEPTH is non-nil, stop searching when
5098 depth is reached, else don't limit."
5099 (let* ((dir (expand-file-name dir
))
5100 (parent-dir (file-name-directory
5101 (directory-file-name
5102 (file-name-directory
5103 (file-name-as-directory dir
)))))
5104 (subpath-length (length parent-dir
)))
5107 (replace-regexp-in-string
5108 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
5109 (python-util-list-directories
5110 (directory-file-name dir
)
5112 (file-exists-p (expand-file-name "__init__.py" dir
)))
5115 (defun python-util-popn (lst n
)
5116 "Return LST first N elements.
5117 N should be an integer, when negative its opposite is used.
5118 When N is bigger than the length of LST, the list is
5120 (let* ((n (min (abs n
)))
5126 (setq acc
(cons (car lst
) acc
)
5131 (defun python-util-strip-string (string)
5132 "Strip STRING whitespace and newlines from end and beginning."
5133 (replace-regexp-in-string
5134 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
5135 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
5139 (defun python-util-valid-regexp-p (regexp)
5140 "Return non-nil if REGEXP is valid."
5141 (ignore-errors (string-match regexp
"") t
))
5144 ;;; Flymake integration
5146 (defgroup python-flymake nil
5147 "Integration between Python and Flymake."
5149 :link
'(custom-group-link :tag
"Flymake" flymake
)
5152 (defcustom python-flymake-command
'("pyflakes")
5153 "The external tool that will be used to perform the syntax check.
5154 This is a non empty list of strings, the checker tool possibly followed by
5155 required arguments. Once launched it will receive the Python source to be
5156 checked as its standard input.
5157 To use `flake8' you would set this to (\"flake8\" \"-\")."
5159 :group
'python-flymake
5160 :type
'(repeat string
))
5162 ;; The default regexp accomodates for older pyflakes, which did not
5163 ;; report the column number, and at the same time it's compatible with
5164 ;; flake8 output, although it may be redefined to explicitly match the
5166 (defcustom python-flymake-command-output-pattern
5168 "^\\(?:<?stdin>?\\):\\(?1:[0-9]+\\):\\(?:\\(?2:[0-9]+\\):\\)? \\(?3:.*\\)$"
5170 "Specify how to parse the output of `python-flymake-command'.
5171 The value has the form (REGEXP LINE COLUMN TYPE MESSAGE): if
5172 REGEXP matches, the LINE'th subexpression gives the line number,
5173 the COLUMN'th subexpression gives the column number on that line,
5174 the TYPE'th subexpression gives the type of the message and the
5175 MESSAGE'th gives the message text itself.
5177 If COLUMN or TYPE are nil or that index didn't match, that
5178 information is not present on the matched line and a default will
5181 :group
'python-flymake
5183 (integer :tag
"Line's index")
5185 (const :tag
"No column" nil
)
5186 (integer :tag
"Column's index"))
5188 (const :tag
"No type" nil
)
5189 (integer :tag
"Type's index"))
5190 (integer :tag
"Message's index")))
5192 (defcustom python-flymake-msg-alist
5193 '(("\\(^redefinition\\|.*unused.*\\|used$\\)" .
:warning
))
5194 "Alist used to associate messages to their types.
5195 Each element should be a cons-cell (REGEXP . TYPE), where TYPE must be
5196 one defined in the variable `flymake-diagnostic-types-alist'.
5197 For example, when using `flake8' a possible configuration could be:
5199 ((\"\\(^redefinition\\|.*unused.*\\|used$\\)\" . :warning)
5200 (\"^E999\" . :error)
5201 (\"^[EW][0-9]+\" . :note))
5203 By default messages are considered errors."
5205 :group
'python-flymake
5206 :type
`(alist :key-type
(regexp)
5207 :value-type
(symbol)))
5209 (defvar-local python--flymake-proc nil
)
5211 (defun python--flymake-parse-output (source proc report-fn
)
5212 "Collect diagnostics parsing checker tool's output line by line."
5213 (let ((rx (nth 0 python-flymake-command-output-pattern
))
5214 (lineidx (nth 1 python-flymake-command-output-pattern
))
5215 (colidx (nth 2 python-flymake-command-output-pattern
))
5216 (typeidx (nth 3 python-flymake-command-output-pattern
))
5217 (msgidx (nth 4 python-flymake-command-output-pattern
)))
5218 (with-current-buffer (process-buffer proc
)
5219 (goto-char (point-min))
5221 while
(search-forward-regexp rx nil t
)
5222 for msg
= (match-string msgidx
)
5223 for
(beg . end
) = (flymake-diag-region
5226 (match-string lineidx
))
5228 (match-string colidx
)
5230 (match-string colidx
))))
5231 for type
= (or (and typeidx
5232 (match-string typeidx
)
5234 (match-string typeidx
)
5235 python-flymake-msg-alist
5238 python-flymake-msg-alist
5241 collect
(flymake-make-diagnostic
5242 source beg end type msg
)
5244 finally
(funcall report-fn diags
)))))
5246 (defun python-flymake (report-fn &rest _args
)
5247 "Flymake backend for Python.
5248 This backend uses `python-flymake-command' (which see) to launch a process
5249 that is passed the current buffer's content via stdin.
5250 REPORT-FN is Flymake's callback function."
5251 (unless (executable-find (car python-flymake-command
))
5252 (error "Cannot find a suitable checker"))
5254 (when (process-live-p python--flymake-proc
)
5255 (kill-process python--flymake-proc
))
5257 (let ((source (current-buffer)))
5260 (setq python--flymake-proc
5262 :name
"python-flymake"
5264 :connection-type
'pipe
5265 :buffer
(generate-new-buffer " *python-flymake*")
5266 :command python-flymake-command
5268 (lambda (proc _event
)
5269 (when (eq 'exit
(process-status proc
))
5271 (when (with-current-buffer source
5272 (eq proc python--flymake-proc
))
5273 (python--flymake-parse-output source proc report-fn
))
5274 (kill-buffer (process-buffer proc
)))))))
5275 (process-send-region python--flymake-proc
(point-min) (point-max))
5276 (process-send-eof python--flymake-proc
))))
5279 (defun python-electric-pair-string-delimiter ()
5280 (when (and electric-pair-mode
5281 (memq last-command-event
'(?
\" ?
\'))
5283 (while (eq (char-before (- (point) count
)) last-command-event
)
5286 (eq (char-after) last-command-event
))
5287 (save-excursion (insert (make-string 2 last-command-event
)))))
5289 (defvar electric-indent-inhibit
)
5292 (define-derived-mode python-mode prog-mode
"Python"
5293 "Major mode for editing Python files.
5295 \\{python-mode-map}"
5296 (set (make-local-variable 'tab-width
) 8)
5297 (set (make-local-variable 'indent-tabs-mode
) nil
)
5299 (set (make-local-variable 'comment-start
) "# ")
5300 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
5302 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
5303 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
5305 (set (make-local-variable 'forward-sexp-function
)
5306 'python-nav-forward-sexp
)
5308 (set (make-local-variable 'font-lock-defaults
)
5309 '(python-font-lock-keywords
5311 (font-lock-syntactic-face-function
5312 . python-font-lock-syntactic-face-function
)))
5314 (set (make-local-variable 'syntax-propertize-function
)
5315 python-syntax-propertize-function
)
5317 (set (make-local-variable 'indent-line-function
)
5318 #'python-indent-line-function
)
5319 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
5320 ;; Because indentation is not redundant, we cannot safely reindent code.
5321 (set (make-local-variable 'electric-indent-inhibit
) t
)
5322 (set (make-local-variable 'electric-indent-chars
)
5323 (cons ?
: electric-indent-chars
))
5325 ;; Add """ ... """ pairing to electric-pair-mode.
5326 (add-hook 'post-self-insert-hook
5327 #'python-electric-pair-string-delimiter
'append t
)
5329 (set (make-local-variable 'paragraph-start
) "\\s-*$")
5330 (set (make-local-variable 'fill-paragraph-function
)
5331 #'python-fill-paragraph
)
5333 (set (make-local-variable 'beginning-of-defun-function
)
5334 #'python-nav-beginning-of-defun
)
5335 (set (make-local-variable 'end-of-defun-function
)
5336 #'python-nav-end-of-defun
)
5338 (add-hook 'completion-at-point-functions
5339 #'python-completion-at-point nil
'local
)
5341 (add-hook 'post-self-insert-hook
5342 #'python-indent-post-self-insert-function
'append
'local
)
5344 (set (make-local-variable 'imenu-create-index-function
)
5345 #'python-imenu-create-index
)
5347 (set (make-local-variable 'add-log-current-defun-function
)
5348 #'python-info-current-defun
)
5350 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
5352 (set (make-local-variable 'skeleton-further-elements
)
5354 (< '(backward-delete-char-untabify (min python-indent-offset
5356 (^
'(- (1+ (current-indentation))))))
5358 (if (null eldoc-documentation-function
)
5360 (set (make-local-variable 'eldoc-documentation-function
)
5361 #'python-eldoc-function
)
5362 (add-function :before-until
(local 'eldoc-documentation-function
)
5363 #'python-eldoc-function
))
5366 'hs-special-modes-alist
5368 "\\s-*\\_<\\(?:def\\|class\\)\\_>"
5369 ;; Use the empty string as end regexp so it doesn't default to
5370 ;; "\\s)". This way parens at end of defun are properly hidden.
5373 python-hideshow-forward-sexp-function
5376 (set (make-local-variable 'outline-regexp
)
5377 (python-rx (* space
) block-start
))
5378 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
5379 (set (make-local-variable 'outline-level
)
5381 "`outline-level' function for Python mode."
5382 (1+ (/ (current-indentation) python-indent-offset
))))
5384 (set (make-local-variable 'prettify-symbols-alist
)
5385 python--prettify-symbols-alist
)
5387 (python-skeleton-add-menu-items)
5389 (make-local-variable 'python-shell-internal-buffer
)
5391 (when python-indent-guess-indent-offset
5392 (python-indent-guess-indent-offset))
5394 (add-hook 'flymake-diagnostic-functions
#'python-flymake nil t
))
5400 ;; indent-tabs-mode: nil
5403 ;;; python.el ends here