* lisp/progmodes/python.el (auto-mode-alist): Add .pyi. (Bug#27847)
[emacs.git] / lisp / progmodes / python.el
blob6f169123b95fba9dfc76fbea9b94ca22969610bb
1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2017 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fgallina@gnu.org>
6 ;; URL: https://github.com/fgallina/python.el
7 ;; Version: 0.25.2
8 ;; Package-Requires: ((emacs "24.1") (cl-lib "1.0"))
9 ;; Maintainer: emacs-devel@gnu.org
10 ;; Created: Jul 2010
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 <http://www.gnu.org/licenses/>.
28 ;;; Commentary:
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 `http://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
92 ;; your system):
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 `http://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/
154 ;; virtualenv:
156 ;; (setq python-shell-process-environment
157 ;; (list
158 ;; (format "PATH=%s" (mapconcat
159 ;; 'identity
160 ;; (reverse
161 ;; (cons (getenv "PATH")
162 ;; '("/path/to/env/bin/")))
163 ;; ":"))
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
214 ;; running.
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
235 ;; options:
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
244 ;; #'(lambda ()
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.
250 ;;; Installation:
252 ;; Add this to your .emacs:
254 ;; (add-to-list 'load-path "/folder/containing/file")
255 ;; (require 'python)
257 ;;; TODO:
259 ;;; Code:
261 (require 'ansi-color)
262 (require 'cl-lib)
263 (require 'comint)
264 (require 'json)
265 (require 'tramp-sh)
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")
275 ;;;###autoload
276 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py[iw]?\\'") 'python-mode))
277 ;;;###autoload
278 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
280 (defgroup python nil
281 "Python Language's flying circus support for Emacs."
282 :group 'languages
283 :version "24.3"
284 :link '(emacs-commentary-link "python"))
287 ;;; 24.x Compat
290 (unless (fboundp 'prog-widen)
291 (defun prog-widen ()
292 (widen)))
294 (unless (fboundp 'prog-first-column)
295 (defun prog-first-column ()
299 ;;; Bindings
301 (defvar python-mode-map
302 (let ((map (make-sparse-keymap)))
303 ;; Movement
304 (define-key map [remap backward-sentence] 'python-nav-backward-block)
305 (define-key map [remap forward-sentence] 'python-nav-forward-block)
306 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
307 (define-key map [remap mark-defun] 'python-mark-defun)
308 (define-key map "\C-c\C-j" 'imenu)
309 ;; Indent specific
310 (define-key map "\177" 'python-indent-dedent-line-backspace)
311 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
312 (define-key map "\C-c<" 'python-indent-shift-left)
313 (define-key map "\C-c>" 'python-indent-shift-right)
314 ;; Skeletons
315 (define-key map "\C-c\C-tc" 'python-skeleton-class)
316 (define-key map "\C-c\C-td" 'python-skeleton-def)
317 (define-key map "\C-c\C-tf" 'python-skeleton-for)
318 (define-key map "\C-c\C-ti" 'python-skeleton-if)
319 (define-key map "\C-c\C-tm" 'python-skeleton-import)
320 (define-key map "\C-c\C-tt" 'python-skeleton-try)
321 (define-key map "\C-c\C-tw" 'python-skeleton-while)
322 ;; Shell interaction
323 (define-key map "\C-c\C-p" 'run-python)
324 (define-key map "\C-c\C-s" 'python-shell-send-string)
325 (define-key map "\C-c\C-r" 'python-shell-send-region)
326 (define-key map "\C-\M-x" 'python-shell-send-defun)
327 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
328 (define-key map "\C-c\C-l" 'python-shell-send-file)
329 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
330 ;; Some util commands
331 (define-key map "\C-c\C-v" 'python-check)
332 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
333 (define-key map "\C-c\C-d" 'python-describe-at-point)
334 ;; Utilities
335 (substitute-key-definition 'complete-symbol 'completion-at-point
336 map global-map)
337 (easy-menu-define python-menu map "Python Mode menu"
338 `("Python"
339 :help "Python-specific Features"
340 ["Shift region left" python-indent-shift-left :active mark-active
341 :help "Shift region left by a single indentation step"]
342 ["Shift region right" python-indent-shift-right :active mark-active
343 :help "Shift region right by a single indentation step"]
345 ["Start of def/class" beginning-of-defun
346 :help "Go to start of outermost definition around point"]
347 ["End of def/class" end-of-defun
348 :help "Go to end of definition around point"]
349 ["Mark def/class" mark-defun
350 :help "Mark outermost definition around point"]
351 ["Jump to def/class" imenu
352 :help "Jump to a class or function definition"]
353 "--"
354 ("Skeletons")
355 "---"
356 ["Start interpreter" run-python
357 :help "Run inferior Python process in a separate buffer"]
358 ["Switch to shell" python-shell-switch-to-shell
359 :help "Switch to running inferior Python process"]
360 ["Eval string" python-shell-send-string
361 :help "Eval string in inferior Python session"]
362 ["Eval buffer" python-shell-send-buffer
363 :help "Eval buffer in inferior Python session"]
364 ["Eval region" python-shell-send-region
365 :help "Eval region in inferior Python session"]
366 ["Eval defun" python-shell-send-defun
367 :help "Eval defun in inferior Python session"]
368 ["Eval file" python-shell-send-file
369 :help "Eval file in inferior Python session"]
370 ["Debugger" pdb :help "Run pdb under GUD"]
371 "----"
372 ["Check file" python-check
373 :help "Check file for errors"]
374 ["Help on symbol" python-eldoc-at-point
375 :help "Get help on symbol at point"]
376 ["Complete symbol" completion-at-point
377 :help "Complete symbol before point"]))
378 map)
379 "Keymap for `python-mode'.")
382 ;;; Python specialized rx
384 (eval-and-compile
385 (defconst python-rx-constituents
386 `((block-start . ,(rx symbol-start
387 (or "def" "class" "if" "elif" "else" "try"
388 "except" "finally" "for" "while" "with"
389 ;; Python 3.5+ PEP492
390 (and "async" (+ space)
391 (or "def" "for" "with")))
392 symbol-end))
393 (dedenter . ,(rx symbol-start
394 (or "elif" "else" "except" "finally")
395 symbol-end))
396 (block-ender . ,(rx symbol-start
398 "break" "continue" "pass" "raise" "return")
399 symbol-end))
400 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
401 (* (any word ?_))))
402 (defun . ,(rx symbol-start
403 (or "def" "class"
404 ;; Python 3.5+ PEP492
405 (and "async" (+ space) "def"))
406 symbol-end))
407 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
408 (+ space) "==" (+ space)
409 (any ?' ?\") "__main__" (any ?' ?\")
410 (* space) ?:))
411 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
412 (open-paren . ,(rx (or "{" "[" "(")))
413 (close-paren . ,(rx (or "}" "]" ")")))
414 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
415 ;; FIXME: rx should support (not simple-operator).
416 (not-simple-operator . ,(rx
417 (not
418 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
419 ;; FIXME: Use regexp-opt.
420 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
421 "=" "%" "**" "//" "<<" ">>" "<=" "!="
422 "==" ">=" "is" "not")))
423 ;; FIXME: Use regexp-opt.
424 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
425 ">>=" "<<=" "&=" "^=" "|=")))
426 (string-delimiter . ,(rx (and
427 ;; Match even number of backslashes.
428 (or (not (any ?\\ ?\' ?\")) point
429 ;; Quotes might be preceded by a escaped quote.
430 (and (or (not (any ?\\)) point) ?\\
431 (* ?\\ ?\\) (any ?\' ?\")))
432 (* ?\\ ?\\)
433 ;; Match single or triple quotes of any kind.
434 (group (or "\"" "\"\"\"" "'" "'''")))))
435 (coding-cookie . ,(rx line-start ?# (* space)
437 ;; # coding=<encoding name>
438 (: "coding" (or ?: ?=) (* space) (group-n 1 (+ (or word ?-))))
439 ;; # -*- coding: <encoding name> -*-
440 (: "-*-" (* space) "coding:" (* space)
441 (group-n 1 (+ (or word ?-))) (* space) "-*-")
442 ;; # vim: set fileencoding=<encoding name> :
443 (: "vim:" (* space) "set" (+ space)
444 "fileencoding" (* space) ?= (* space)
445 (group-n 1 (+ (or word ?-))) (* space) ":")))))
446 "Additional Python specific sexps for `python-rx'")
448 (defmacro python-rx (&rest regexps)
449 "Python mode specialized rx macro.
450 This variant of `rx' supports common Python named REGEXPS."
451 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
452 (cond ((null regexps)
453 (error "No regexp"))
454 ((cdr regexps)
455 (rx-to-string `(and ,@regexps) t))
457 (rx-to-string (car regexps) t))))))
460 ;;; Font-lock and syntax
462 (eval-and-compile
463 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
464 (pcase type
465 (`'comment
466 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
467 (and (nth 4 ppss) (nth 8 ppss))))
468 (`'string
469 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
470 (and (nth 3 ppss) (nth 8 ppss))))
471 (`'paren
472 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
473 (_ form))))
475 (defun python-syntax-context (type &optional syntax-ppss)
476 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
477 TYPE can be `comment', `string' or `paren'. It returns the start
478 character address of the specified TYPE."
479 (declare (compiler-macro python-syntax--context-compiler-macro))
480 (let ((ppss (or syntax-ppss (syntax-ppss))))
481 (pcase type
482 (`comment (and (nth 4 ppss) (nth 8 ppss)))
483 (`string (and (nth 3 ppss) (nth 8 ppss)))
484 (`paren (nth 1 ppss))
485 (_ nil))))
487 (defun python-syntax-context-type (&optional syntax-ppss)
488 "Return the context type using SYNTAX-PPSS.
489 The type returned can be `comment', `string' or `paren'."
490 (let ((ppss (or syntax-ppss (syntax-ppss))))
491 (cond
492 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
493 ((nth 1 ppss) 'paren))))
495 (defsubst python-syntax-comment-or-string-p (&optional ppss)
496 "Return non-nil if PPSS is inside comment or string."
497 (nth 8 (or ppss (syntax-ppss))))
499 (defsubst python-syntax-closing-paren-p ()
500 "Return non-nil if char after point is a closing paren."
501 (eql (syntax-class (syntax-after (point)))
502 (syntax-class (string-to-syntax ")"))))
504 (define-obsolete-function-alias
505 'python-info-ppss-context #'python-syntax-context "24.3")
507 (define-obsolete-function-alias
508 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
510 (define-obsolete-function-alias
511 'python-info-ppss-comment-or-string-p
512 #'python-syntax-comment-or-string-p "24.3")
514 (defun python-font-lock-syntactic-face-function (state)
515 "Return syntactic face given STATE."
516 (if (nth 3 state)
517 (if (python-info-docstring-p state)
518 font-lock-doc-face
519 font-lock-string-face)
520 font-lock-comment-face))
522 (defvar python-font-lock-keywords
523 ;; Keywords
524 `(,(rx symbol-start
526 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
527 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
528 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
529 "try"
530 ;; Python 2:
531 "print" "exec"
532 ;; Python 3:
533 ;; False, None, and True are listed as keywords on the Python 3
534 ;; documentation, but since they also qualify as constants they are
535 ;; fontified like that in order to keep font-lock consistent between
536 ;; Python versions.
537 "nonlocal"
538 ;; Python 3.5+ PEP492
539 (and "async" (+ space) (or "def" "for" "with"))
540 "await"
541 ;; Extra:
542 "self")
543 symbol-end)
544 ;; functions
545 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
546 (1 font-lock-function-name-face))
547 ;; classes
548 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
549 (1 font-lock-type-face))
550 ;; Constants
551 (,(rx symbol-start
553 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
554 ;; copyright, license, credits, quit and exit are added by the site
555 ;; module and they are not intended to be used in programs
556 "copyright" "credits" "exit" "license" "quit")
557 symbol-end) . font-lock-constant-face)
558 ;; Decorators.
559 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
560 (0+ "." (1+ (or word ?_)))))
561 (1 font-lock-type-face))
562 ;; Builtin Exceptions
563 (,(rx symbol-start
565 ;; Python 2 and 3:
566 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
567 "BufferError" "BytesWarning" "DeprecationWarning" "EOFError"
568 "EnvironmentError" "Exception" "FloatingPointError" "FutureWarning"
569 "GeneratorExit" "IOError" "ImportError" "ImportWarning"
570 "IndentationError" "IndexError" "KeyError" "KeyboardInterrupt"
571 "LookupError" "MemoryError" "NameError" "NotImplementedError"
572 "OSError" "OverflowError" "PendingDeprecationWarning"
573 "ReferenceError" "RuntimeError" "RuntimeWarning" "StopIteration"
574 "SyntaxError" "SyntaxWarning" "SystemError" "SystemExit" "TabError"
575 "TypeError" "UnboundLocalError" "UnicodeDecodeError"
576 "UnicodeEncodeError" "UnicodeError" "UnicodeTranslateError"
577 "UnicodeWarning" "UserWarning" "ValueError" "Warning"
578 "ZeroDivisionError"
579 ;; Python 2:
580 "StandardError"
581 ;; Python 3:
582 "BlockingIOError" "BrokenPipeError" "ChildProcessError"
583 "ConnectionAbortedError" "ConnectionError" "ConnectionRefusedError"
584 "ConnectionResetError" "FileExistsError" "FileNotFoundError"
585 "InterruptedError" "IsADirectoryError" "NotADirectoryError"
586 "PermissionError" "ProcessLookupError" "RecursionError"
587 "ResourceWarning" "StopAsyncIteration" "TimeoutError"
588 ;; OS specific
589 "VMSError" "WindowsError"
591 symbol-end) . font-lock-type-face)
592 ;; Builtins
593 (,(rx symbol-start
595 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
596 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
597 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
598 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
599 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
600 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
601 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
602 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
603 "__import__"
604 ;; Python 2:
605 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
606 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
607 "intern"
608 ;; Python 3:
609 "ascii" "bytearray" "bytes" "exec"
610 ;; Extra:
611 "__all__" "__doc__" "__name__" "__package__")
612 symbol-end) . font-lock-builtin-face)
613 ;; assignments
614 ;; support for a = b = c = 5
615 (,(lambda (limit)
616 (let ((re (python-rx (group (+ (any word ?. ?_)))
617 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
618 assignment-operator))
619 (res nil))
620 (while (and (setq res (re-search-forward re limit t))
621 (or (python-syntax-context 'paren)
622 (equal (char-after (point)) ?=))))
623 res))
624 (1 font-lock-variable-name-face nil nil))
625 ;; support for a, b, c = (1, 2, 3)
626 (,(lambda (limit)
627 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
628 (* ?, (* space) (+ (any word ?. ?_)) (* space))
629 ?, (* space) (+ (any word ?. ?_)) (* space)
630 assignment-operator))
631 (res nil))
632 (while (and (setq res (re-search-forward re limit t))
633 (goto-char (match-end 1))
634 (python-syntax-context 'paren)))
635 res))
636 (1 font-lock-variable-name-face nil nil))))
638 (defconst python-syntax-propertize-function
639 (syntax-propertize-rules
640 ((python-rx string-delimiter)
641 (0 (ignore (python-syntax-stringify))))))
643 (defconst python--prettify-symbols-alist
644 '(("lambda" . ?λ)
645 ("and" . ?∧)
646 ("or" . ?∨)))
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."
653 (let ((i 0))
654 (while (and (< i 3)
655 (or (not limit) (< (+ point i) limit))
656 (eq (char-after (+ point i)) quote-char))
657 (setq i (1+ i)))
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)))
663 (ppss (prog2
664 (backward-char num-quotes)
665 (syntax-ppss)
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))
670 (num-closing-quotes
671 (and string-start
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
676 ;; kind. Do nothing.
677 nil)
678 ((not string-start)
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
689 ;; all three quotes.
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)))
699 (dotimes (i 128)
700 (unless (= i ?_)
701 (if (equal symbol (aref sst i))
702 (modify-syntax-entry i "." table)))))
703 (modify-syntax-entry ?$ "." table)
704 (modify-syntax-entry ?% "." table)
705 ;; exceptions
706 (modify-syntax-entry ?# "<" table)
707 (modify-syntax-entry ?\n ">" table)
708 (modify-syntax-entry ?' "\"" table)
709 (modify-syntax-entry ?` "$" table)
710 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)
717 table)
718 "Dotty syntax table for Python files.
719 It makes underscores and dots word constituent chars.")
722 ;;; Indentation
724 (defcustom python-indent-offset 4
725 "Default indentation offset for Python."
726 :group 'python
727 :type 'integer
728 :safe 'integerp)
730 (defcustom python-indent-guess-indent-offset t
731 "Non-nil tells Python mode to guess `python-indent-offset' value."
732 :type 'boolean
733 :group 'python
734 :safe 'booleanp)
736 (defcustom python-indent-guess-indent-offset-verbose t
737 "Non-nil means to emit a warning when indentation guessing fails."
738 :version "25.1"
739 :type 'boolean
740 :group 'python
741 :safe' booleanp)
743 (defcustom python-indent-trigger-commands
744 '(indent-for-tab-command yas-expand yas/expand)
745 "Commands that might trigger a `python-indent-line' call."
746 :type '(repeat symbol)
747 :group 'python)
749 (define-obsolete-variable-alias
750 'python-indent 'python-indent-offset "24.3")
752 (define-obsolete-variable-alias
753 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
755 (defvar python-indent-current-level 0
756 "Deprecated var available for compatibility.")
758 (defvar python-indent-levels '(0)
759 "Deprecated var available for compatibility.")
761 (make-obsolete-variable
762 'python-indent-current-level
763 "The indentation API changed to avoid global state.
764 The function `python-indent-calculate-levels' does not use it
765 anymore. If you were defadvising it and or depended on this
766 variable for indentation customizations, refactor your code to
767 work on `python-indent-calculate-indentation' instead."
768 "24.5")
770 (make-obsolete-variable
771 'python-indent-levels
772 "The indentation API changed to avoid global state.
773 The function `python-indent-calculate-levels' does not use it
774 anymore. If you were defadvising it and or depended on this
775 variable for indentation customizations, refactor your code to
776 work on `python-indent-calculate-indentation' instead."
777 "24.5")
779 (defun python-indent-guess-indent-offset ()
780 "Guess and set `python-indent-offset' for the current buffer."
781 (interactive)
782 (save-excursion
783 (save-restriction
784 (prog-widen)
785 (goto-char (point-min))
786 (let ((block-end))
787 (while (and (not block-end)
788 (re-search-forward
789 (python-rx line-start block-start) nil t))
790 (when (and
791 (not (python-syntax-context-type))
792 (progn
793 (goto-char (line-end-position))
794 (python-util-forward-comment -1)
795 (if (equal (char-before) ?:)
797 (forward-line 1)
798 (when (python-info-block-continuation-line-p)
799 (while (and (python-info-continuation-line-p)
800 (not (eobp)))
801 (forward-line 1))
802 (python-util-forward-comment -1)
803 (when (equal (char-before) ?:)
804 t)))))
805 (setq block-end (point-marker))))
806 (let ((indentation
807 (when block-end
808 (goto-char block-end)
809 (python-util-forward-comment)
810 (current-indentation))))
811 (if (and indentation (not (zerop indentation)))
812 (set (make-local-variable 'python-indent-offset) indentation)
813 (when python-indent-guess-indent-offset-verbose
814 (message "Can't guess python-indent-offset, using defaults: %s"
815 python-indent-offset))))))))
817 (defun python-indent-context ()
818 "Get information about the current indentation context.
819 Context is returned in a cons with the form (STATUS . START).
821 STATUS can be one of the following:
823 keyword
824 -------
826 :after-comment
827 - Point is after a comment line.
828 - START is the position of the \"#\" character.
829 :inside-string
830 - Point is inside string.
831 - START is the position of the first quote that starts it.
832 :no-indent
833 - No possible indentation case matches.
834 - START is always zero.
836 :inside-paren
837 - Fallback case when point is inside paren.
838 - START is the first non space char position *after* the open paren.
839 :inside-paren-at-closing-nested-paren
840 - Point is on a line that contains a nested paren closer.
841 - START is the position of the open paren it closes.
842 :inside-paren-at-closing-paren
843 - Point is on a line that contains a paren closer.
844 - START is the position of the open paren.
845 :inside-paren-newline-start
846 - Point is inside a paren with items starting in their own line.
847 - START is the position of the open paren.
848 :inside-paren-newline-start-from-block
849 - Point is inside a paren with items starting in their own line
850 from a block start.
851 - START is the position of the open paren.
853 :after-backslash
854 - Fallback case when point is after backslash.
855 - START is the char after the position of the backslash.
856 :after-backslash-assignment-continuation
857 - Point is after a backslashed assignment.
858 - START is the char after the position of the backslash.
859 :after-backslash-block-continuation
860 - Point is after a backslashed block continuation.
861 - START is the char after the position of the backslash.
862 :after-backslash-dotted-continuation
863 - Point is after a backslashed dotted continuation. Previous
864 line must contain a dot to align with.
865 - START is the char after the position of the backslash.
866 :after-backslash-first-line
867 - First line following a backslashed continuation.
868 - START is the char after the position of the backslash.
870 :after-block-end
871 - Point is after a line containing a block ender.
872 - START is the position where the ender starts.
873 :after-block-start
874 - Point is after a line starting a block.
875 - START is the position where the block starts.
876 :after-line
877 - Point is after a simple line.
878 - START is the position where the previous line starts.
879 :at-dedenter-block-start
880 - Point is on a line starting a dedenter block.
881 - START is the position where the dedenter block starts."
882 (save-restriction
883 (prog-widen)
884 (let ((ppss (save-excursion
885 (beginning-of-line)
886 (syntax-ppss))))
887 (cond
888 ;; Beginning of buffer.
889 ((= (line-number-at-pos) 1)
890 (cons :no-indent 0))
891 ;; Inside a string.
892 ((let ((start (python-syntax-context 'string ppss)))
893 (when start
894 (cons (if (python-info-docstring-p)
895 :inside-docstring
896 :inside-string) start))))
897 ;; Inside a paren.
898 ((let* ((start (python-syntax-context 'paren ppss))
899 (starts-in-newline
900 (when start
901 (save-excursion
902 (goto-char start)
903 (forward-char)
904 (not
905 (= (line-number-at-pos)
906 (progn
907 (python-util-forward-comment)
908 (line-number-at-pos))))))))
909 (when start
910 (cond
911 ;; Current line only holds the closing paren.
912 ((save-excursion
913 (skip-syntax-forward " ")
914 (when (and (python-syntax-closing-paren-p)
915 (progn
916 (forward-char 1)
917 (not (python-syntax-context 'paren))))
918 (cons :inside-paren-at-closing-paren start))))
919 ;; Current line only holds a closing paren for nested.
920 ((save-excursion
921 (back-to-indentation)
922 (python-syntax-closing-paren-p))
923 (cons :inside-paren-at-closing-nested-paren start))
924 ;; This line starts from a opening block in its own line.
925 ((save-excursion
926 (goto-char start)
927 (when (and
928 starts-in-newline
929 (save-excursion
930 (back-to-indentation)
931 (looking-at (python-rx block-start))))
932 (cons
933 :inside-paren-newline-start-from-block start))))
934 (starts-in-newline
935 (cons :inside-paren-newline-start start))
936 ;; General case.
937 (t (cons :inside-paren
938 (save-excursion
939 (goto-char (1+ start))
940 (skip-syntax-forward "(" 1)
941 (skip-syntax-forward " ")
942 (point))))))))
943 ;; After backslash.
944 ((let ((start (when (not (python-syntax-comment-or-string-p ppss))
945 (python-info-line-ends-backslash-p
946 (1- (line-number-at-pos))))))
947 (when start
948 (cond
949 ;; Continuation of dotted expression.
950 ((save-excursion
951 (back-to-indentation)
952 (when (eq (char-after) ?\.)
953 ;; Move point back until it's not inside a paren.
954 (while (prog2
955 (forward-line -1)
956 (and (not (bobp))
957 (python-syntax-context 'paren))))
958 (goto-char (line-end-position))
959 (while (and (search-backward
960 "." (line-beginning-position) t)
961 (python-syntax-context-type)))
962 ;; Ensure previous statement has dot to align with.
963 (when (and (eq (char-after) ?\.)
964 (not (python-syntax-context-type)))
965 (cons :after-backslash-dotted-continuation (point))))))
966 ;; Continuation of block definition.
967 ((let ((block-continuation-start
968 (python-info-block-continuation-line-p)))
969 (when block-continuation-start
970 (save-excursion
971 (goto-char block-continuation-start)
972 (re-search-forward
973 (python-rx block-start (* space))
974 (line-end-position) t)
975 (cons :after-backslash-block-continuation (point))))))
976 ;; Continuation of assignment.
977 ((let ((assignment-continuation-start
978 (python-info-assignment-continuation-line-p)))
979 (when assignment-continuation-start
980 (save-excursion
981 (goto-char assignment-continuation-start)
982 (cons :after-backslash-assignment-continuation (point))))))
983 ;; First line after backslash continuation start.
984 ((save-excursion
985 (goto-char start)
986 (when (or (= (line-number-at-pos) 1)
987 (not (python-info-beginning-of-backslash
988 (1- (line-number-at-pos)))))
989 (cons :after-backslash-first-line start))))
990 ;; General case.
991 (t (cons :after-backslash start))))))
992 ;; After beginning of block.
993 ((let ((start (save-excursion
994 (back-to-indentation)
995 (python-util-forward-comment -1)
996 (when (equal (char-before) ?:)
997 (python-nav-beginning-of-block)))))
998 (when start
999 (cons :after-block-start start))))
1000 ;; At dedenter statement.
1001 ((let ((start (python-info-dedenter-statement-p)))
1002 (when start
1003 (cons :at-dedenter-block-start start))))
1004 ;; After normal line, comment or ender (default case).
1005 ((save-excursion
1006 (back-to-indentation)
1007 (skip-chars-backward " \t\n")
1008 (if (bobp)
1009 (cons :no-indent 0)
1010 (python-nav-beginning-of-statement)
1011 (cons
1012 (cond ((python-info-current-line-comment-p)
1013 :after-comment)
1014 ((save-excursion
1015 (goto-char (line-end-position))
1016 (python-util-forward-comment -1)
1017 (python-nav-beginning-of-statement)
1018 (looking-at (python-rx block-ender)))
1019 :after-block-end)
1020 (t :after-line))
1021 (point)))))))))
1023 (defun python-indent--calculate-indentation ()
1024 "Internal implementation of `python-indent-calculate-indentation'.
1025 May return an integer for the maximum possible indentation at
1026 current context or a list of integers. The latter case is only
1027 happening for :at-dedenter-block-start context since the
1028 possibilities can be narrowed to specific indentation points."
1029 (save-restriction
1030 (prog-widen)
1031 (save-excursion
1032 (pcase (python-indent-context)
1033 (`(:no-indent . ,_) (prog-first-column)) ; usually 0
1034 (`(,(or :after-line
1035 :after-comment
1036 :inside-string
1037 :after-backslash
1038 :inside-paren-at-closing-paren
1039 :inside-paren-at-closing-nested-paren) . ,start)
1040 ;; Copy previous indentation.
1041 (goto-char start)
1042 (current-indentation))
1043 (`(:inside-docstring . ,start)
1044 (let* ((line-indentation (current-indentation))
1045 (base-indent (progn
1046 (goto-char start)
1047 (current-indentation))))
1048 (max line-indentation base-indent)))
1049 (`(,(or :after-block-start
1050 :after-backslash-first-line
1051 :after-backslash-assignment-continuation
1052 :inside-paren-newline-start) . ,start)
1053 ;; Add one indentation level.
1054 (goto-char start)
1055 (+ (current-indentation) python-indent-offset))
1056 (`(,(or :inside-paren
1057 :after-backslash-block-continuation
1058 :after-backslash-dotted-continuation) . ,start)
1059 ;; Use the column given by the context.
1060 (goto-char start)
1061 (current-column))
1062 (`(:after-block-end . ,start)
1063 ;; Subtract one indentation level.
1064 (goto-char start)
1065 (- (current-indentation) python-indent-offset))
1066 (`(:at-dedenter-block-start . ,_)
1067 ;; List all possible indentation levels from opening blocks.
1068 (let ((opening-block-start-points
1069 (python-info-dedenter-opening-block-positions)))
1070 (if (not opening-block-start-points)
1071 (prog-first-column) ; if not found default to first column
1072 (mapcar (lambda (pos)
1073 (save-excursion
1074 (goto-char pos)
1075 (current-indentation)))
1076 opening-block-start-points))))
1077 (`(,(or :inside-paren-newline-start-from-block) . ,start)
1078 ;; Add two indentation levels to make the suite stand out.
1079 (goto-char start)
1080 (+ (current-indentation) (* python-indent-offset 2)))))))
1082 (defun python-indent--calculate-levels (indentation)
1083 "Calculate levels list given INDENTATION.
1084 Argument INDENTATION can either be an integer or a list of
1085 integers. Levels are returned in ascending order, and in the
1086 case INDENTATION is a list, this order is enforced."
1087 (if (listp indentation)
1088 (sort (copy-sequence indentation) #'<)
1089 (nconc (number-sequence (prog-first-column) (1- indentation)
1090 python-indent-offset)
1091 (list indentation))))
1093 (defun python-indent--previous-level (levels indentation)
1094 "Return previous level from LEVELS relative to INDENTATION."
1095 (let* ((levels (sort (copy-sequence levels) #'>))
1096 (default (car levels)))
1097 (catch 'return
1098 (dolist (level levels)
1099 (when (funcall #'< level indentation)
1100 (throw 'return level)))
1101 default)))
1103 (defun python-indent-calculate-indentation (&optional previous)
1104 "Calculate indentation.
1105 Get indentation of PREVIOUS level when argument is non-nil.
1106 Return the max level of the cycle when indentation reaches the
1107 minimum."
1108 (let* ((indentation (python-indent--calculate-indentation))
1109 (levels (python-indent--calculate-levels indentation)))
1110 (if previous
1111 (python-indent--previous-level levels (current-indentation))
1112 (if levels
1113 (apply #'max levels)
1114 (prog-first-column)))))
1116 (defun python-indent-line (&optional previous)
1117 "Internal implementation of `python-indent-line-function'.
1118 Use the PREVIOUS level when argument is non-nil, otherwise indent
1119 to the maximum available level. When indentation is the minimum
1120 possible and PREVIOUS is non-nil, cycle back to the maximum
1121 level."
1122 (let ((follow-indentation-p
1123 ;; Check if point is within indentation.
1124 (and (<= (line-beginning-position) (point))
1125 (>= (+ (line-beginning-position)
1126 (current-indentation))
1127 (point)))))
1128 (save-excursion
1129 (indent-line-to
1130 (python-indent-calculate-indentation previous))
1131 (python-info-dedenter-opening-block-message))
1132 (when follow-indentation-p
1133 (back-to-indentation))))
1135 (defun python-indent-calculate-levels ()
1136 "Return possible indentation levels."
1137 (python-indent--calculate-levels
1138 (python-indent--calculate-indentation)))
1140 (defun python-indent-line-function ()
1141 "`indent-line-function' for Python mode.
1142 When the variable `last-command' is equal to one of the symbols
1143 inside `python-indent-trigger-commands' it cycles possible
1144 indentation levels from right to left."
1145 (python-indent-line
1146 (and (memq this-command python-indent-trigger-commands)
1147 (eq last-command this-command))))
1149 (defun python-indent-dedent-line ()
1150 "De-indent current line."
1151 (interactive "*")
1152 (when (and (not (bolp))
1153 (not (python-syntax-comment-or-string-p))
1154 (= (current-indentation) (current-column)))
1155 (python-indent-line t)
1158 (defun python-indent-dedent-line-backspace (arg)
1159 "De-indent current line.
1160 Argument ARG is passed to `backward-delete-char-untabify' when
1161 point is not in between the indentation."
1162 (interactive "*p")
1163 (unless (python-indent-dedent-line)
1164 (backward-delete-char-untabify arg)))
1166 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1168 (defun python-indent-region (start end)
1169 "Indent a Python region automagically.
1171 Called from a program, START and END specify the region to indent."
1172 (let ((deactivate-mark nil))
1173 (save-excursion
1174 (goto-char end)
1175 (setq end (point-marker))
1176 (goto-char start)
1177 (or (bolp) (forward-line 1))
1178 (while (< (point) end)
1179 (or (and (bolp) (eolp))
1180 (when (and
1181 ;; Skip if previous line is empty or a comment.
1182 (save-excursion
1183 (let ((line-is-comment-p
1184 (python-info-current-line-comment-p)))
1185 (forward-line -1)
1186 (not
1187 (or (and (python-info-current-line-comment-p)
1188 ;; Unless this line is a comment too.
1189 (not line-is-comment-p))
1190 (python-info-current-line-empty-p)))))
1191 ;; Don't mess with strings, unless it's the
1192 ;; enclosing set of quotes or a docstring.
1193 (or (not (python-syntax-context 'string))
1195 (syntax-after
1196 (+ (1- (point))
1197 (current-indentation)
1198 (python-syntax-count-quotes (char-after) (point))))
1199 (string-to-syntax "|"))
1200 (python-info-docstring-p))
1201 ;; Skip if current line is a block start, a
1202 ;; dedenter or block ender.
1203 (save-excursion
1204 (back-to-indentation)
1205 (not (looking-at
1206 (python-rx
1207 (or block-start dedenter block-ender))))))
1208 (python-indent-line)))
1209 (forward-line 1))
1210 (move-marker end nil))))
1212 (defun python-indent-shift-left (start end &optional count)
1213 "Shift lines contained in region START END by COUNT columns to the left.
1214 COUNT defaults to `python-indent-offset'. If region isn't
1215 active, the current line is shifted. The shifted region includes
1216 the lines in which START and END lie. An error is signaled if
1217 any lines in the region are indented less than COUNT columns."
1218 (interactive
1219 (if mark-active
1220 (list (region-beginning) (region-end) current-prefix-arg)
1221 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1222 (if count
1223 (setq count (prefix-numeric-value count))
1224 (setq count python-indent-offset))
1225 (when (> count 0)
1226 (let ((deactivate-mark nil))
1227 (save-excursion
1228 (goto-char start)
1229 (while (< (point) end)
1230 (if (and (< (current-indentation) count)
1231 (not (looking-at "[ \t]*$")))
1232 (user-error "Can't shift all lines enough"))
1233 (forward-line))
1234 (indent-rigidly start end (- count))))))
1236 (defun python-indent-shift-right (start end &optional count)
1237 "Shift lines contained in region START END by COUNT columns to the right.
1238 COUNT defaults to `python-indent-offset'. If region isn't
1239 active, the current line is shifted. The shifted region includes
1240 the lines in which START and END lie."
1241 (interactive
1242 (if mark-active
1243 (list (region-beginning) (region-end) current-prefix-arg)
1244 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1245 (let ((deactivate-mark nil))
1246 (setq count (if count (prefix-numeric-value count)
1247 python-indent-offset))
1248 (indent-rigidly start end count)))
1250 (defun python-indent-post-self-insert-function ()
1251 "Adjust indentation after insertion of some characters.
1252 This function is intended to be added to `post-self-insert-hook.'
1253 If a line renders a paren alone, after adding a char before it,
1254 the line will be re-indented automatically if needed."
1255 (when (and electric-indent-mode
1256 (eq (char-before) last-command-event))
1257 (cond
1258 ;; Electric indent inside parens
1259 ((and
1260 (not (bolp))
1261 (let ((paren-start (python-syntax-context 'paren)))
1262 ;; Check that point is inside parens.
1263 (when paren-start
1264 (not
1265 ;; Filter the case where input is happening in the same
1266 ;; line where the open paren is.
1267 (= (line-number-at-pos)
1268 (line-number-at-pos paren-start)))))
1269 ;; When content has been added before the closing paren or a
1270 ;; comma has been inserted, it's ok to do the trick.
1272 (memq (char-after) '(?\) ?\] ?\}))
1273 (eq (char-before) ?,)))
1274 (save-excursion
1275 (goto-char (line-beginning-position))
1276 (let ((indentation (python-indent-calculate-indentation)))
1277 (when (and (numberp indentation) (< (current-indentation) indentation))
1278 (indent-line-to indentation)))))
1279 ;; Electric colon
1280 ((and (eq ?: last-command-event)
1281 (memq ?: electric-indent-chars)
1282 (not current-prefix-arg)
1283 ;; Trigger electric colon only at end of line
1284 (eolp)
1285 ;; Avoid re-indenting on extra colon
1286 (not (equal ?: (char-before (1- (point)))))
1287 (not (python-syntax-comment-or-string-p)))
1288 ;; Just re-indent dedenters
1289 (let ((dedenter-pos (python-info-dedenter-statement-p))
1290 (current-pos (point)))
1291 (when dedenter-pos
1292 (save-excursion
1293 (goto-char dedenter-pos)
1294 (python-indent-line)
1295 (unless (= (line-number-at-pos dedenter-pos)
1296 (line-number-at-pos current-pos))
1297 ;; Reindent region if this is a multiline statement
1298 (python-indent-region dedenter-pos current-pos)))))))))
1301 ;;; Mark
1303 (defun python-mark-defun (&optional allow-extend)
1304 "Put mark at end of this defun, point at beginning.
1305 The defun marked is the one that contains point or follows point.
1307 Interactively (or with ALLOW-EXTEND non-nil), if this command is
1308 repeated or (in Transient Mark mode) if the mark is active, it
1309 marks the next defun after the ones already marked."
1310 (interactive "p")
1311 (when (python-info-looking-at-beginning-of-defun)
1312 (end-of-line 1))
1313 (mark-defun allow-extend))
1316 ;;; Navigation
1318 (defvar python-nav-beginning-of-defun-regexp
1319 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1320 "Regexp matching class or function definition.
1321 The name of the defun should be grouped so it can be retrieved
1322 via `match-string'.")
1324 (defun python-nav--beginning-of-defun (&optional arg)
1325 "Internal implementation of `python-nav-beginning-of-defun'.
1326 With positive ARG search backwards, else search forwards."
1327 (when (or (null arg) (= arg 0)) (setq arg 1))
1328 (let* ((re-search-fn (if (> arg 0)
1329 #'re-search-backward
1330 #'re-search-forward))
1331 (line-beg-pos (line-beginning-position))
1332 (line-content-start (+ line-beg-pos (current-indentation)))
1333 (pos (point-marker))
1334 (beg-indentation
1335 (and (> arg 0)
1336 (save-excursion
1337 (while (and
1338 (not (python-info-looking-at-beginning-of-defun))
1339 (python-nav-backward-block)))
1340 (or (and (python-info-looking-at-beginning-of-defun)
1341 (+ (current-indentation) python-indent-offset))
1342 0))))
1343 (found
1344 (progn
1345 (when (and (< arg 0)
1346 (python-info-looking-at-beginning-of-defun))
1347 (end-of-line 1))
1348 (while (and (funcall re-search-fn
1349 python-nav-beginning-of-defun-regexp nil t)
1350 (or (python-syntax-context-type)
1351 ;; Handle nested defuns when moving
1352 ;; backwards by checking indentation.
1353 (and (> arg 0)
1354 (not (= (current-indentation) 0))
1355 (>= (current-indentation) beg-indentation)))))
1356 (and (python-info-looking-at-beginning-of-defun)
1357 (or (not (= (line-number-at-pos pos)
1358 (line-number-at-pos)))
1359 (and (>= (point) line-beg-pos)
1360 (<= (point) line-content-start)
1361 (> pos line-content-start)))))))
1362 (if found
1363 (or (beginning-of-line 1) t)
1364 (and (goto-char pos) nil))))
1366 (defun python-nav-beginning-of-defun (&optional arg)
1367 "Move point to `beginning-of-defun'.
1368 With positive ARG search backwards else search forward.
1369 ARG nil or 0 defaults to 1. When searching backwards,
1370 nested defuns are handled with care depending on current
1371 point position. Return non-nil if point is moved to
1372 `beginning-of-defun'."
1373 (when (or (null arg) (= arg 0)) (setq arg 1))
1374 (let ((found))
1375 (while (and (not (= arg 0))
1376 (let ((keep-searching-p
1377 (python-nav--beginning-of-defun arg)))
1378 (when (and keep-searching-p (null found))
1379 (setq found t))
1380 keep-searching-p))
1381 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1382 found))
1384 (defun python-nav-end-of-defun ()
1385 "Move point to the end of def or class.
1386 Returns nil if point is not in a def or class."
1387 (interactive)
1388 (let ((beg-defun-indent)
1389 (beg-pos (point)))
1390 (when (or (python-info-looking-at-beginning-of-defun)
1391 (python-nav-beginning-of-defun 1)
1392 (python-nav-beginning-of-defun -1))
1393 (setq beg-defun-indent (current-indentation))
1394 (while (progn
1395 (python-nav-end-of-statement)
1396 (python-util-forward-comment 1)
1397 (and (> (current-indentation) beg-defun-indent)
1398 (not (eobp)))))
1399 (python-util-forward-comment -1)
1400 (forward-line 1)
1401 ;; Ensure point moves forward.
1402 (and (> beg-pos (point)) (goto-char beg-pos)))))
1404 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1405 "Move point using FN avoiding places with specific context.
1406 FN must take no arguments. POSCOMPFN is a two arguments function
1407 used to compare current and previous point after it is moved
1408 using FN, this is normally a less-than or greater-than
1409 comparison. Optional argument CONTEXTFN defaults to
1410 `python-syntax-context-type' and is used for checking current
1411 point context, it must return a non-nil value if this point must
1412 be skipped."
1413 (let ((contextfn (or contextfn 'python-syntax-context-type))
1414 (start-pos (point-marker))
1415 (prev-pos))
1416 (catch 'found
1417 (while t
1418 (let* ((newpos
1419 (and (funcall fn) (point-marker)))
1420 (context (funcall contextfn)))
1421 (cond ((and (not context) newpos
1422 (or (and (not prev-pos) newpos)
1423 (and prev-pos newpos
1424 (funcall poscompfn newpos prev-pos))))
1425 (throw 'found (point-marker)))
1426 ((and newpos context)
1427 (setq prev-pos (point)))
1428 (t (when (not newpos) (goto-char start-pos))
1429 (throw 'found nil))))))))
1431 (defun python-nav--forward-defun (arg)
1432 "Internal implementation of python-nav-{backward,forward}-defun.
1433 Uses ARG to define which function to call, and how many times
1434 repeat it."
1435 (let ((found))
1436 (while (and (> arg 0)
1437 (setq found
1438 (python-nav--syntactically
1439 (lambda ()
1440 (re-search-forward
1441 python-nav-beginning-of-defun-regexp nil t))
1442 '>)))
1443 (setq arg (1- arg)))
1444 (while (and (< arg 0)
1445 (setq found
1446 (python-nav--syntactically
1447 (lambda ()
1448 (re-search-backward
1449 python-nav-beginning-of-defun-regexp nil t))
1450 '<)))
1451 (setq arg (1+ arg)))
1452 found))
1454 (defun python-nav-backward-defun (&optional arg)
1455 "Navigate to closer defun backward ARG times.
1456 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1457 nested definitions."
1458 (interactive "^p")
1459 (python-nav--forward-defun (- (or arg 1))))
1461 (defun python-nav-forward-defun (&optional arg)
1462 "Navigate to closer defun forward ARG times.
1463 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1464 nested definitions."
1465 (interactive "^p")
1466 (python-nav--forward-defun (or arg 1)))
1468 (defun python-nav-beginning-of-statement ()
1469 "Move to start of current statement."
1470 (interactive "^")
1471 (back-to-indentation)
1472 (let* ((ppss (syntax-ppss))
1473 (context-point
1475 (python-syntax-context 'paren ppss)
1476 (python-syntax-context 'string ppss))))
1477 (cond ((bobp))
1478 (context-point
1479 (goto-char context-point)
1480 (python-nav-beginning-of-statement))
1481 ((save-excursion
1482 (forward-line -1)
1483 (python-info-line-ends-backslash-p))
1484 (forward-line -1)
1485 (python-nav-beginning-of-statement))))
1486 (point-marker))
1488 (defun python-nav-end-of-statement (&optional noend)
1489 "Move to end of current statement.
1490 Optional argument NOEND is internal and makes the logic to not
1491 jump to the end of line when moving forward searching for the end
1492 of the statement."
1493 (interactive "^")
1494 (let (string-start bs-pos (last-string-end 0))
1495 (while (and (or noend (goto-char (line-end-position)))
1496 (not (eobp))
1497 (cond ((setq string-start (python-syntax-context 'string))
1498 ;; The assertion can only fail if syntax table
1499 ;; text properties and the `syntax-ppss' cache
1500 ;; are somehow out of whack. This has been
1501 ;; observed when using `syntax-ppss' during
1502 ;; narrowing.
1503 (cl-assert (> string-start last-string-end)
1504 :show-args
1505 "Overlapping strings detected")
1506 (goto-char string-start)
1507 (if (python-syntax-context 'paren)
1508 ;; Ended up inside a paren, roll again.
1509 (python-nav-end-of-statement t)
1510 ;; This is not inside a paren, move to the
1511 ;; end of this string.
1512 (goto-char (+ (point)
1513 (python-syntax-count-quotes
1514 (char-after (point)) (point))))
1515 (setq last-string-end
1516 (or (re-search-forward
1517 (rx (syntax string-delimiter)) nil t)
1518 (goto-char (point-max))))))
1519 ((python-syntax-context 'paren)
1520 ;; The statement won't end before we've escaped
1521 ;; at least one level of parenthesis.
1522 (condition-case err
1523 (goto-char (scan-lists (point) 1 -1))
1524 (scan-error (goto-char (nth 3 err)))))
1525 ((setq bs-pos (python-info-line-ends-backslash-p))
1526 (goto-char bs-pos)
1527 (forward-line 1))))))
1528 (point-marker))
1530 (defun python-nav-backward-statement (&optional arg)
1531 "Move backward to previous statement.
1532 With ARG, repeat. See `python-nav-forward-statement'."
1533 (interactive "^p")
1534 (or arg (setq arg 1))
1535 (python-nav-forward-statement (- arg)))
1537 (defun python-nav-forward-statement (&optional arg)
1538 "Move forward to next statement.
1539 With ARG, repeat. With negative argument, move ARG times
1540 backward to previous statement."
1541 (interactive "^p")
1542 (or arg (setq arg 1))
1543 (while (> arg 0)
1544 (python-nav-end-of-statement)
1545 (python-util-forward-comment)
1546 (python-nav-beginning-of-statement)
1547 (setq arg (1- arg)))
1548 (while (< arg 0)
1549 (python-nav-beginning-of-statement)
1550 (python-util-forward-comment -1)
1551 (python-nav-beginning-of-statement)
1552 (setq arg (1+ arg))))
1554 (defun python-nav-beginning-of-block ()
1555 "Move to start of current block."
1556 (interactive "^")
1557 (let ((starting-pos (point)))
1558 (if (progn
1559 (python-nav-beginning-of-statement)
1560 (looking-at (python-rx block-start)))
1561 (point-marker)
1562 ;; Go to first line beginning a statement
1563 (while (and (not (bobp))
1564 (or (and (python-nav-beginning-of-statement) nil)
1565 (python-info-current-line-comment-p)
1566 (python-info-current-line-empty-p)))
1567 (forward-line -1))
1568 (let ((block-matching-indent
1569 (- (current-indentation) python-indent-offset)))
1570 (while
1571 (and (python-nav-backward-block)
1572 (> (current-indentation) block-matching-indent)))
1573 (if (and (looking-at (python-rx block-start))
1574 (= (current-indentation) block-matching-indent))
1575 (point-marker)
1576 (and (goto-char starting-pos) nil))))))
1578 (defun python-nav-end-of-block ()
1579 "Move to end of current block."
1580 (interactive "^")
1581 (when (python-nav-beginning-of-block)
1582 (let ((block-indentation (current-indentation)))
1583 (python-nav-end-of-statement)
1584 (while (and (forward-line 1)
1585 (not (eobp))
1586 (or (and (> (current-indentation) block-indentation)
1587 (or (python-nav-end-of-statement) t))
1588 (python-info-current-line-comment-p)
1589 (python-info-current-line-empty-p))))
1590 (python-util-forward-comment -1)
1591 (point-marker))))
1593 (defun python-nav-backward-block (&optional arg)
1594 "Move backward to previous block of code.
1595 With ARG, repeat. See `python-nav-forward-block'."
1596 (interactive "^p")
1597 (or arg (setq arg 1))
1598 (python-nav-forward-block (- arg)))
1600 (defun python-nav-forward-block (&optional arg)
1601 "Move forward to next block of code.
1602 With ARG, repeat. With negative argument, move ARG times
1603 backward to previous block."
1604 (interactive "^p")
1605 (or arg (setq arg 1))
1606 (let ((block-start-regexp
1607 (python-rx line-start (* whitespace) block-start))
1608 (starting-pos (point)))
1609 (while (> arg 0)
1610 (python-nav-end-of-statement)
1611 (while (and
1612 (re-search-forward block-start-regexp nil t)
1613 (python-syntax-context-type)))
1614 (setq arg (1- arg)))
1615 (while (< arg 0)
1616 (python-nav-beginning-of-statement)
1617 (while (and
1618 (re-search-backward block-start-regexp nil t)
1619 (python-syntax-context-type)))
1620 (setq arg (1+ arg)))
1621 (python-nav-beginning-of-statement)
1622 (if (not (looking-at (python-rx block-start)))
1623 (and (goto-char starting-pos) nil)
1624 (and (not (= (point) starting-pos)) (point-marker)))))
1626 (defun python-nav--lisp-forward-sexp (&optional arg)
1627 "Standard version `forward-sexp'.
1628 It ignores completely the value of `forward-sexp-function' by
1629 setting it to nil before calling `forward-sexp'. With positive
1630 ARG move forward only one sexp, else move backwards."
1631 (let ((forward-sexp-function)
1632 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1633 (forward-sexp arg)))
1635 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1636 "Safe version of standard `forward-sexp'.
1637 When at end of sexp (i.e. looking at a opening/closing paren)
1638 skips it instead of throwing an error. With positive ARG move
1639 forward only one sexp, else move backwards."
1640 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1641 (paren-regexp
1642 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1643 (search-fn
1644 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1645 (condition-case nil
1646 (python-nav--lisp-forward-sexp arg)
1647 (error
1648 (while (and (funcall search-fn paren-regexp nil t)
1649 (python-syntax-context 'paren)))))))
1651 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p)
1652 "Move to forward sexp.
1653 With positive optional argument DIR direction move forward, else
1654 backwards. When optional argument SAFE is non-nil do not throw
1655 errors when at end of sexp, skip it instead. With optional
1656 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1657 expressions when looking at them in either direction."
1658 (setq dir (or dir 1))
1659 (unless (= dir 0)
1660 (let* ((forward-p (if (> dir 0)
1661 (and (setq dir 1) t)
1662 (and (setq dir -1) nil)))
1663 (context-type (python-syntax-context-type)))
1664 (cond
1665 ((memq context-type '(string comment))
1666 ;; Inside of a string, get out of it.
1667 (let ((forward-sexp-function))
1668 (forward-sexp dir)))
1669 ((and (not skip-parens-p)
1670 (or (eq context-type 'paren)
1671 (if forward-p
1672 (eq (syntax-class (syntax-after (point)))
1673 (car (string-to-syntax "(")))
1674 (eq (syntax-class (syntax-after (1- (point))))
1675 (car (string-to-syntax ")"))))))
1676 ;; Inside a paren or looking at it, lisp knows what to do.
1677 (if safe
1678 (python-nav--lisp-forward-sexp-safe dir)
1679 (python-nav--lisp-forward-sexp dir)))
1681 ;; This part handles the lispy feel of
1682 ;; `python-nav-forward-sexp'. Knowing everything about the
1683 ;; current context and the context of the next sexp tries to
1684 ;; follow the lisp sexp motion commands in a symmetric manner.
1685 (let* ((context
1686 (cond
1687 ((python-info-beginning-of-block-p) 'block-start)
1688 ((python-info-end-of-block-p) 'block-end)
1689 ((python-info-beginning-of-statement-p) 'statement-start)
1690 ((python-info-end-of-statement-p) 'statement-end)))
1691 (next-sexp-pos
1692 (save-excursion
1693 (if safe
1694 (python-nav--lisp-forward-sexp-safe dir)
1695 (python-nav--lisp-forward-sexp dir))
1696 (point)))
1697 (next-sexp-context
1698 (save-excursion
1699 (goto-char next-sexp-pos)
1700 (cond
1701 ((python-info-beginning-of-block-p) 'block-start)
1702 ((python-info-end-of-block-p) 'block-end)
1703 ((python-info-beginning-of-statement-p) 'statement-start)
1704 ((python-info-end-of-statement-p) 'statement-end)
1705 ((python-info-statement-starts-block-p) 'starts-block)
1706 ((python-info-statement-ends-block-p) 'ends-block)))))
1707 (if forward-p
1708 (cond ((and (not (eobp))
1709 (python-info-current-line-empty-p))
1710 (python-util-forward-comment dir)
1711 (python-nav--forward-sexp dir safe skip-parens-p))
1712 ((eq context 'block-start)
1713 (python-nav-end-of-block))
1714 ((eq context 'statement-start)
1715 (python-nav-end-of-statement))
1716 ((and (memq context '(statement-end block-end))
1717 (eq next-sexp-context 'ends-block))
1718 (goto-char next-sexp-pos)
1719 (python-nav-end-of-block))
1720 ((and (memq context '(statement-end block-end))
1721 (eq next-sexp-context 'starts-block))
1722 (goto-char next-sexp-pos)
1723 (python-nav-end-of-block))
1724 ((memq context '(statement-end block-end))
1725 (goto-char next-sexp-pos)
1726 (python-nav-end-of-statement))
1727 (t (goto-char next-sexp-pos)))
1728 (cond ((and (not (bobp))
1729 (python-info-current-line-empty-p))
1730 (python-util-forward-comment dir)
1731 (python-nav--forward-sexp dir safe skip-parens-p))
1732 ((eq context 'block-end)
1733 (python-nav-beginning-of-block))
1734 ((eq context 'statement-end)
1735 (python-nav-beginning-of-statement))
1736 ((and (memq context '(statement-start block-start))
1737 (eq next-sexp-context 'starts-block))
1738 (goto-char next-sexp-pos)
1739 (python-nav-beginning-of-block))
1740 ((and (memq context '(statement-start block-start))
1741 (eq next-sexp-context 'ends-block))
1742 (goto-char next-sexp-pos)
1743 (python-nav-beginning-of-block))
1744 ((memq context '(statement-start block-start))
1745 (goto-char next-sexp-pos)
1746 (python-nav-beginning-of-statement))
1747 (t (goto-char next-sexp-pos))))))))))
1749 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p)
1750 "Move forward across expressions.
1751 With ARG, do it that many times. Negative arg -N means move
1752 backward N times. When optional argument SAFE is non-nil do not
1753 throw errors when at end of sexp, skip it instead. With optional
1754 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1755 expressions when looking at them in either direction (forced to t
1756 in interactive calls)."
1757 (interactive "^p")
1758 (or arg (setq arg 1))
1759 ;; Do not follow parens on interactive calls. This hack to detect
1760 ;; if the function was called interactively copes with the way
1761 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1762 ;; interactive detection by checking `current-prefix-arg'. The
1763 ;; reason to make this distinction is that lisp functions like
1764 ;; `blink-matching-open' get confused causing issues like the one in
1765 ;; Bug#16191. With this approach the user gets a symmetric behavior
1766 ;; when working interactively while called functions expecting
1767 ;; paren-based sexp motion work just fine.
1769 skip-parens-p
1770 (setq skip-parens-p
1771 (memq real-this-command
1772 (list
1773 #'forward-sexp #'backward-sexp
1774 #'python-nav-forward-sexp #'python-nav-backward-sexp
1775 #'python-nav-forward-sexp-safe #'python-nav-backward-sexp))))
1776 (while (> arg 0)
1777 (python-nav--forward-sexp 1 safe skip-parens-p)
1778 (setq arg (1- arg)))
1779 (while (< arg 0)
1780 (python-nav--forward-sexp -1 safe skip-parens-p)
1781 (setq arg (1+ arg))))
1783 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p)
1784 "Move backward across expressions.
1785 With ARG, do it that many times. Negative arg -N means move
1786 forward N times. When optional argument SAFE is non-nil do not
1787 throw errors when at end of sexp, skip it instead. With optional
1788 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1789 expressions when looking at them in either direction (forced to t
1790 in interactive calls)."
1791 (interactive "^p")
1792 (or arg (setq arg 1))
1793 (python-nav-forward-sexp (- arg) safe skip-parens-p))
1795 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p)
1796 "Move forward safely across expressions.
1797 With ARG, do it that many times. Negative arg -N means move
1798 backward N times. With optional argument SKIP-PARENS-P force
1799 sexp motion to ignore parenthesized expressions when looking at
1800 them in either direction (forced to t in interactive calls)."
1801 (interactive "^p")
1802 (python-nav-forward-sexp arg t skip-parens-p))
1804 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p)
1805 "Move backward safely across expressions.
1806 With ARG, do it that many times. Negative arg -N means move
1807 forward N times. With optional argument SKIP-PARENS-P force sexp
1808 motion to ignore parenthesized expressions when looking at them in
1809 either direction (forced to t in interactive calls)."
1810 (interactive "^p")
1811 (python-nav-backward-sexp arg t skip-parens-p))
1813 (defun python-nav--up-list (&optional dir)
1814 "Internal implementation of `python-nav-up-list'.
1815 DIR is always 1 or -1 and comes sanitized from
1816 `python-nav-up-list' calls."
1817 (let ((context (python-syntax-context-type))
1818 (forward-p (> dir 0)))
1819 (cond
1820 ((memq context '(string comment)))
1821 ((eq context 'paren)
1822 (let ((forward-sexp-function))
1823 (up-list dir)))
1824 ((and forward-p (python-info-end-of-block-p))
1825 (let ((parent-end-pos
1826 (save-excursion
1827 (let ((indentation (and
1828 (python-nav-beginning-of-block)
1829 (current-indentation))))
1830 (while (and indentation
1831 (> indentation 0)
1832 (>= (current-indentation) indentation)
1833 (python-nav-backward-block)))
1834 (python-nav-end-of-block)))))
1835 (and (> (or parent-end-pos (point)) (point))
1836 (goto-char parent-end-pos))))
1837 (forward-p (python-nav-end-of-block))
1838 ((and (not forward-p)
1839 (> (current-indentation) 0)
1840 (python-info-beginning-of-block-p))
1841 (let ((prev-block-pos
1842 (save-excursion
1843 (let ((indentation (current-indentation)))
1844 (while (and (python-nav-backward-block)
1845 (>= (current-indentation) indentation))))
1846 (point))))
1847 (and (> (point) prev-block-pos)
1848 (goto-char prev-block-pos))))
1849 ((not forward-p) (python-nav-beginning-of-block)))))
1851 (defun python-nav-up-list (&optional arg)
1852 "Move forward out of one level of parentheses (or blocks).
1853 With ARG, do this that many times.
1854 A negative argument means move backward but still to a less deep spot.
1855 This command assumes point is not in a string or comment."
1856 (interactive "^p")
1857 (or arg (setq arg 1))
1858 (while (> arg 0)
1859 (python-nav--up-list 1)
1860 (setq arg (1- arg)))
1861 (while (< arg 0)
1862 (python-nav--up-list -1)
1863 (setq arg (1+ arg))))
1865 (defun python-nav-backward-up-list (&optional arg)
1866 "Move backward out of one level of parentheses (or blocks).
1867 With ARG, do this that many times.
1868 A negative argument means move forward but still to a less deep spot.
1869 This command assumes point is not in a string or comment."
1870 (interactive "^p")
1871 (or arg (setq arg 1))
1872 (python-nav-up-list (- arg)))
1874 (defun python-nav-if-name-main ()
1875 "Move point at the beginning the __main__ block.
1876 When \"if __name__ == \\='__main__\\=':\" is found returns its
1877 position, else returns nil."
1878 (interactive)
1879 (let ((point (point))
1880 (found (catch 'found
1881 (goto-char (point-min))
1882 (while (re-search-forward
1883 (python-rx line-start
1884 "if" (+ space)
1885 "__name__" (+ space)
1886 "==" (+ space)
1887 (group-n 1 (or ?\" ?\'))
1888 "__main__" (backref 1) (* space) ":")
1889 nil t)
1890 (when (not (python-syntax-context-type))
1891 (beginning-of-line)
1892 (throw 'found t))))))
1893 (if found
1894 (point)
1895 (ignore (goto-char point)))))
1898 ;;; Shell integration
1900 (defcustom python-shell-buffer-name "Python"
1901 "Default buffer name for Python interpreter."
1902 :type 'string
1903 :group 'python
1904 :safe 'stringp)
1906 (defcustom python-shell-interpreter "python"
1907 "Default Python interpreter for shell."
1908 :type 'string
1909 :group 'python)
1911 (defcustom python-shell-internal-buffer-name "Python Internal"
1912 "Default buffer name for the Internal Python interpreter."
1913 :type 'string
1914 :group 'python
1915 :safe 'stringp)
1917 (defcustom python-shell-interpreter-args "-i"
1918 "Default arguments for the Python interpreter."
1919 :type 'string
1920 :group 'python)
1922 (defcustom python-shell-interpreter-interactive-arg "-i"
1923 "Interpreter argument to force it to run interactively."
1924 :type 'string
1925 :version "24.4")
1927 (defcustom python-shell-prompt-detect-enabled t
1928 "Non-nil enables autodetection of interpreter prompts."
1929 :type 'boolean
1930 :safe 'booleanp
1931 :version "24.4")
1933 (defcustom python-shell-prompt-detect-failure-warning t
1934 "Non-nil enables warnings when detection of prompts fail."
1935 :type 'boolean
1936 :safe 'booleanp
1937 :version "24.4")
1939 (defcustom python-shell-prompt-input-regexps
1940 '(">>> " "\\.\\.\\. " ; Python
1941 "In \\[[0-9]+\\]: " ; IPython
1942 " \\.\\.\\.: " ; IPython
1943 ;; Using ipdb outside IPython may fail to cleanup and leave static
1944 ;; IPython prompts activated, this adds some safeguard for that.
1945 "In : " "\\.\\.\\.: ")
1946 "List of regular expressions matching input prompts."
1947 :type '(repeat string)
1948 :version "24.4")
1950 (defcustom python-shell-prompt-output-regexps
1951 '("" ; Python
1952 "Out\\[[0-9]+\\]: " ; IPython
1953 "Out :") ; ipdb safeguard
1954 "List of regular expressions matching output prompts."
1955 :type '(repeat string)
1956 :version "24.4")
1958 (defcustom python-shell-prompt-regexp ">>> "
1959 "Regular expression matching top level input prompt of Python shell.
1960 It should not contain a caret (^) at the beginning."
1961 :type 'string)
1963 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1964 "Regular expression matching block input prompt of Python shell.
1965 It should not contain a caret (^) at the beginning."
1966 :type 'string)
1968 (defcustom python-shell-prompt-output-regexp ""
1969 "Regular expression matching output prompt of Python shell.
1970 It should not contain a caret (^) at the beginning."
1971 :type 'string)
1973 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1974 "Regular expression matching pdb input prompt of Python shell.
1975 It should not contain a caret (^) at the beginning."
1976 :type 'string)
1978 (define-obsolete-variable-alias
1979 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1981 (defcustom python-shell-font-lock-enable t
1982 "Should syntax highlighting be enabled in the Python shell buffer?
1983 Restart the Python shell after changing this variable for it to take effect."
1984 :type 'boolean
1985 :group 'python
1986 :safe 'booleanp)
1988 (defcustom python-shell-unbuffered t
1989 "Should shell output be unbuffered?.
1990 When non-nil, this may prevent delayed and missing output in the
1991 Python shell. See commentary for details."
1992 :type 'boolean
1993 :group 'python
1994 :safe 'booleanp)
1996 (defcustom python-shell-process-environment nil
1997 "List of overridden environment variables for subprocesses to inherit.
1998 Each element should be a string of the form ENVVARNAME=VALUE.
1999 When this variable is non-nil, values are exported into the
2000 process environment before starting it. Any variables already
2001 present in the current environment are superseded by variables
2002 set here."
2003 :type '(repeat string)
2004 :group 'python)
2006 (defcustom python-shell-extra-pythonpaths nil
2007 "List of extra pythonpaths for Python shell.
2008 When this variable is non-nil, values added at the beginning of
2009 the PYTHONPATH before starting processes. Any values present
2010 here that already exists in PYTHONPATH are moved to the beginning
2011 of the list so that they are prioritized when looking for
2012 modules."
2013 :type '(repeat string)
2014 :group 'python)
2016 (defcustom python-shell-exec-path nil
2017 "List of paths for searching executables.
2018 When this variable is non-nil, values added at the beginning of
2019 the PATH before starting processes. Any values present here that
2020 already exists in PATH are moved to the beginning of the list so
2021 that they are prioritized when looking for executables."
2022 :type '(repeat string)
2023 :group 'python)
2025 (defcustom python-shell-remote-exec-path nil
2026 "List of paths to be ensured remotely for searching executables.
2027 When this variable is non-nil, values are exported into remote
2028 hosts PATH before starting processes. Values defined in
2029 `python-shell-exec-path' will take precedence to paths defined
2030 here. Normally you wont use this variable directly unless you
2031 plan to ensure a particular set of paths to all Python shell
2032 executed through tramp connections."
2033 :version "25.1"
2034 :type '(repeat string)
2035 :group 'python)
2037 (defcustom python-shell-virtualenv-root nil
2038 "Path to virtualenv root.
2039 This variable, when set to a string, makes the environment to be
2040 modified such that shells are started within the specified
2041 virtualenv."
2042 :type '(choice (const nil) string)
2043 :group 'python)
2045 (define-obsolete-variable-alias
2046 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
2048 (defcustom python-shell-setup-codes nil
2049 "List of code run by `python-shell-send-setup-codes'."
2050 :type '(repeat symbol)
2051 :group 'python)
2053 (defcustom python-shell-compilation-regexp-alist
2054 `((,(rx line-start (1+ (any " \t")) "File \""
2055 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
2056 "\", line " (group (1+ digit)))
2057 1 2)
2058 (,(rx " in file " (group (1+ not-newline)) " on line "
2059 (group (1+ digit)))
2060 1 2)
2061 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
2062 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
2063 1 2))
2064 "`compilation-error-regexp-alist' for inferior Python."
2065 :type '(alist string)
2066 :group 'python)
2068 (defmacro python-shell--add-to-path-with-priority (pathvar paths)
2069 "Modify PATHVAR and ensure PATHS are added only once at beginning."
2070 `(dolist (path (reverse ,paths))
2071 (cl-delete path ,pathvar :test #'string=)
2072 (cl-pushnew path ,pathvar :test #'string=)))
2074 (defun python-shell-calculate-pythonpath ()
2075 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2076 (let ((pythonpath
2077 (split-string
2078 (or (getenv "PYTHONPATH") "") path-separator 'omit)))
2079 (python-shell--add-to-path-with-priority
2080 pythonpath python-shell-extra-pythonpaths)
2081 (mapconcat 'identity pythonpath path-separator)))
2083 (defun python-shell-calculate-process-environment ()
2084 "Calculate `process-environment' or `tramp-remote-process-environment'.
2085 Prepends `python-shell-process-environment', sets extra
2086 pythonpaths from `python-shell-extra-pythonpaths' and sets a few
2087 virtualenv related vars. If `default-directory' points to a
2088 remote host, the returned value is intended for
2089 `tramp-remote-process-environment'."
2090 (let* ((remote-p (file-remote-p default-directory))
2091 (process-environment (if remote-p
2092 tramp-remote-process-environment
2093 process-environment))
2094 (virtualenv (when python-shell-virtualenv-root
2095 (directory-file-name python-shell-virtualenv-root))))
2096 (dolist (env python-shell-process-environment)
2097 (pcase-let ((`(,key ,value) (split-string env "=")))
2098 (setenv key value)))
2099 (when python-shell-unbuffered
2100 (setenv "PYTHONUNBUFFERED" "1"))
2101 (when python-shell-extra-pythonpaths
2102 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2103 (if (not virtualenv)
2104 process-environment
2105 (setenv "PYTHONHOME" nil)
2106 (setenv "VIRTUAL_ENV" virtualenv))
2107 process-environment))
2109 (defun python-shell-calculate-exec-path ()
2110 "Calculate `exec-path'.
2111 Prepends `python-shell-exec-path' and adds the binary directory
2112 for virtualenv if `python-shell-virtualenv-root' is set. If
2113 `default-directory' points to a remote host, the returned value
2114 appends `python-shell-remote-exec-path' instead of `exec-path'."
2115 (let ((new-path (copy-sequence
2116 (if (file-remote-p default-directory)
2117 python-shell-remote-exec-path
2118 exec-path))))
2119 (python-shell--add-to-path-with-priority
2120 new-path python-shell-exec-path)
2121 (if (not python-shell-virtualenv-root)
2122 new-path
2123 (python-shell--add-to-path-with-priority
2124 new-path
2125 (list (expand-file-name "bin" python-shell-virtualenv-root)))
2126 new-path)))
2128 (defun python-shell-tramp-refresh-remote-path (vec paths)
2129 "Update VEC's remote-path giving PATHS priority."
2130 (let ((remote-path (tramp-get-connection-property vec "remote-path" nil)))
2131 (when remote-path
2132 (python-shell--add-to-path-with-priority remote-path paths)
2133 (tramp-set-connection-property vec "remote-path" remote-path)
2134 (tramp-set-remote-path vec))))
2136 (defun python-shell-tramp-refresh-process-environment (vec env)
2137 "Update VEC's process environment with ENV."
2138 ;; Stolen from `tramp-open-connection-setup-interactive-shell'.
2139 (let ((env (append (when (fboundp #'tramp-get-remote-locale)
2140 ;; Emacs<24.4 compat.
2141 (list (tramp-get-remote-locale vec)))
2142 (copy-sequence env)))
2143 (tramp-end-of-heredoc
2144 (if (boundp 'tramp-end-of-heredoc)
2145 tramp-end-of-heredoc
2146 (md5 tramp-end-of-output)))
2147 unset vars item)
2148 (while env
2149 (setq item (split-string (car env) "=" 'omit))
2150 (setcdr item (mapconcat 'identity (cdr item) "="))
2151 (if (and (stringp (cdr item)) (not (string-equal (cdr item) "")))
2152 (push (format "%s %s" (car item) (cdr item)) vars)
2153 (push (car item) unset))
2154 (setq env (cdr env)))
2155 (when vars
2156 (tramp-send-command
2158 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
2159 tramp-end-of-heredoc
2160 (mapconcat 'identity vars "\n")
2161 tramp-end-of-heredoc)
2163 (when unset
2164 (tramp-send-command
2165 vec (format "unset %s" (mapconcat 'identity unset " ")) t))))
2167 (defmacro python-shell-with-environment (&rest body)
2168 "Modify shell environment during execution of BODY.
2169 Temporarily sets `process-environment' and `exec-path' during
2170 execution of body. If `default-directory' points to a remote
2171 machine then modifies `tramp-remote-process-environment' and
2172 `python-shell-remote-exec-path' instead."
2173 (declare (indent 0) (debug (body)))
2174 (let ((vec (make-symbol "vec")))
2175 `(progn
2176 (let* ((,vec
2177 (when (file-remote-p default-directory)
2178 (ignore-errors
2179 (tramp-dissect-file-name default-directory 'noexpand))))
2180 (process-environment
2181 (if ,vec
2182 process-environment
2183 (python-shell-calculate-process-environment)))
2184 (exec-path
2185 (if ,vec
2186 exec-path
2187 (python-shell-calculate-exec-path)))
2188 (tramp-remote-process-environment
2189 (if ,vec
2190 (python-shell-calculate-process-environment)
2191 tramp-remote-process-environment)))
2192 (when (tramp-get-connection-process ,vec)
2193 ;; For already existing connections, the new exec path must
2194 ;; be re-set, otherwise it won't take effect. One example
2195 ;; of such case is when remote dir-locals are read and
2196 ;; *then* subprocesses are triggered within the same
2197 ;; connection.
2198 (python-shell-tramp-refresh-remote-path
2199 ,vec (python-shell-calculate-exec-path))
2200 ;; The `tramp-remote-process-environment' variable is only
2201 ;; effective when the started process is an interactive
2202 ;; shell, otherwise (like in the case of processes started
2203 ;; with `process-file') the environment is not changed.
2204 ;; This makes environment modifications effective
2205 ;; unconditionally.
2206 (python-shell-tramp-refresh-process-environment
2207 ,vec tramp-remote-process-environment))
2208 ,(macroexp-progn body)))))
2210 (defvar python-shell--prompt-calculated-input-regexp nil
2211 "Calculated input prompt regexp for inferior python shell.
2212 Do not set this variable directly, instead use
2213 `python-shell-prompt-set-calculated-regexps'.")
2215 (defvar python-shell--prompt-calculated-output-regexp nil
2216 "Calculated output prompt regexp for inferior python shell.
2217 Do not set this variable directly, instead use
2218 `python-shell-set-prompt-regexp'.")
2220 (defun python-shell-prompt-detect ()
2221 "Detect prompts for the current `python-shell-interpreter'.
2222 When prompts can be retrieved successfully from the
2223 `python-shell-interpreter' run with
2224 `python-shell-interpreter-interactive-arg', returns a list of
2225 three elements, where the first two are input prompts and the
2226 last one is an output prompt. When no prompts can be detected
2227 and `python-shell-prompt-detect-failure-warning' is non-nil,
2228 shows a warning with instructions to avoid hangs and returns nil.
2229 When `python-shell-prompt-detect-enabled' is nil avoids any
2230 detection and just returns nil."
2231 (when python-shell-prompt-detect-enabled
2232 (python-shell-with-environment
2233 (let* ((code (concat
2234 "import sys\n"
2235 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2236 ;; JSON is built manually for compatibility
2237 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2238 "print (ps_json)\n"
2239 "sys.exit(0)\n"))
2240 (interpreter python-shell-interpreter)
2241 (interpreter-arg python-shell-interpreter-interactive-arg)
2242 (output
2243 (with-temp-buffer
2244 ;; TODO: improve error handling by using
2245 ;; `condition-case' and displaying the error message to
2246 ;; the user in the no-prompts warning.
2247 (ignore-errors
2248 (let ((code-file (python-shell--save-temp-file code)))
2249 ;; Use `process-file' as it is remote-host friendly.
2250 (process-file
2251 interpreter
2252 code-file
2253 '(t nil)
2255 interpreter-arg)
2256 ;; Try to cleanup
2257 (delete-file code-file)))
2258 (buffer-string)))
2259 (prompts
2260 (catch 'prompts
2261 (dolist (line (split-string output "\n" t))
2262 (let ((res
2263 ;; Check if current line is a valid JSON array
2264 (and (string= (substring line 0 2) "[\"")
2265 (ignore-errors
2266 ;; Return prompts as a list, not vector
2267 (append (json-read-from-string line) nil)))))
2268 ;; The list must contain 3 strings, where the first
2269 ;; is the input prompt, the second is the block
2270 ;; prompt and the last one is the output prompt. The
2271 ;; input prompt is the only one that can't be empty.
2272 (when (and (= (length res) 3)
2273 (cl-every #'stringp res)
2274 (not (string= (car res) "")))
2275 (throw 'prompts res))))
2276 nil)))
2277 (when (and (not prompts)
2278 python-shell-prompt-detect-failure-warning)
2279 (lwarn
2280 '(python python-shell-prompt-regexp)
2281 :warning
2282 (concat
2283 "Python shell prompts cannot be detected.\n"
2284 "If your emacs session hangs when starting python shells\n"
2285 "recover with `keyboard-quit' and then try fixing the\n"
2286 "interactive flag for your interpreter by adjusting the\n"
2287 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2288 "matching shell prompts in the directory-local friendly vars:\n"
2289 " + `python-shell-prompt-regexp'\n"
2290 " + `python-shell-prompt-block-regexp'\n"
2291 " + `python-shell-prompt-output-regexp'\n"
2292 "Or alternatively in:\n"
2293 " + `python-shell-prompt-input-regexps'\n"
2294 " + `python-shell-prompt-output-regexps'")))
2295 prompts))))
2297 (defun python-shell-prompt-validate-regexps ()
2298 "Validate all user provided regexps for prompts.
2299 Signals `user-error' if any of these vars contain invalid
2300 regexps: `python-shell-prompt-regexp',
2301 `python-shell-prompt-block-regexp',
2302 `python-shell-prompt-pdb-regexp',
2303 `python-shell-prompt-output-regexp',
2304 `python-shell-prompt-input-regexps',
2305 `python-shell-prompt-output-regexps'."
2306 (dolist (symbol (list 'python-shell-prompt-input-regexps
2307 'python-shell-prompt-output-regexps
2308 'python-shell-prompt-regexp
2309 'python-shell-prompt-block-regexp
2310 'python-shell-prompt-pdb-regexp
2311 'python-shell-prompt-output-regexp))
2312 (dolist (regexp (let ((regexps (symbol-value symbol)))
2313 (if (listp regexps)
2314 regexps
2315 (list regexps))))
2316 (when (not (python-util-valid-regexp-p regexp))
2317 (user-error "Invalid regexp %s in `%s'"
2318 regexp symbol)))))
2320 (defun python-shell-prompt-set-calculated-regexps ()
2321 "Detect and set input and output prompt regexps.
2322 Build and set the values for `python-shell-input-prompt-regexp'
2323 and `python-shell-output-prompt-regexp' using the values from
2324 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2325 `python-shell-prompt-pdb-regexp',
2326 `python-shell-prompt-output-regexp',
2327 `python-shell-prompt-input-regexps',
2328 `python-shell-prompt-output-regexps' and detected prompts from
2329 `python-shell-prompt-detect'."
2330 (when (not (and python-shell--prompt-calculated-input-regexp
2331 python-shell--prompt-calculated-output-regexp))
2332 (let* ((detected-prompts (python-shell-prompt-detect))
2333 (input-prompts nil)
2334 (output-prompts nil)
2335 (build-regexp
2336 (lambda (prompts)
2337 (concat "^\\("
2338 (mapconcat #'identity
2339 (sort prompts
2340 (lambda (a b)
2341 (let ((length-a (length a))
2342 (length-b (length b)))
2343 (if (= length-a length-b)
2344 (string< a b)
2345 (> (length a) (length b))))))
2346 "\\|")
2347 "\\)"))))
2348 ;; Validate ALL regexps
2349 (python-shell-prompt-validate-regexps)
2350 ;; Collect all user defined input prompts
2351 (dolist (prompt (append python-shell-prompt-input-regexps
2352 (list python-shell-prompt-regexp
2353 python-shell-prompt-block-regexp
2354 python-shell-prompt-pdb-regexp)))
2355 (cl-pushnew prompt input-prompts :test #'string=))
2356 ;; Collect all user defined output prompts
2357 (dolist (prompt (cons python-shell-prompt-output-regexp
2358 python-shell-prompt-output-regexps))
2359 (cl-pushnew prompt output-prompts :test #'string=))
2360 ;; Collect detected prompts if any
2361 (when detected-prompts
2362 (dolist (prompt (butlast detected-prompts))
2363 (setq prompt (regexp-quote prompt))
2364 (cl-pushnew prompt input-prompts :test #'string=))
2365 (cl-pushnew (regexp-quote
2366 (car (last detected-prompts)))
2367 output-prompts :test #'string=))
2368 ;; Set input and output prompt regexps from collected prompts
2369 (setq python-shell--prompt-calculated-input-regexp
2370 (funcall build-regexp input-prompts)
2371 python-shell--prompt-calculated-output-regexp
2372 (funcall build-regexp output-prompts)))))
2374 (defun python-shell-get-process-name (dedicated)
2375 "Calculate the appropriate process name for inferior Python process.
2376 If DEDICATED is t returns a string with the form
2377 `python-shell-buffer-name'[`buffer-name'] else returns the value
2378 of `python-shell-buffer-name'."
2379 (if dedicated
2380 (format "%s[%s]" python-shell-buffer-name (buffer-name))
2381 python-shell-buffer-name))
2383 (defun python-shell-internal-get-process-name ()
2384 "Calculate the appropriate process name for Internal Python process.
2385 The name is calculated from `python-shell-global-buffer-name' and
2386 the `buffer-name'."
2387 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
2389 (defun python-shell-calculate-command ()
2390 "Calculate the string used to execute the inferior Python process."
2391 (format "%s %s"
2392 ;; `python-shell-make-comint' expects to be able to
2393 ;; `split-string-and-unquote' the result of this function.
2394 (combine-and-quote-strings (list python-shell-interpreter))
2395 python-shell-interpreter-args))
2397 (define-obsolete-function-alias
2398 'python-shell-parse-command
2399 #'python-shell-calculate-command "25.1")
2401 (defvar python-shell--package-depth 10)
2403 (defun python-shell-package-enable (directory package)
2404 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2405 (interactive
2406 (let* ((dir (expand-file-name
2407 (read-directory-name
2408 "Package root: "
2409 (file-name-directory
2410 (or (buffer-file-name) default-directory)))))
2411 (name (completing-read
2412 "Package: "
2413 (python-util-list-packages
2414 dir python-shell--package-depth))))
2415 (list dir name)))
2416 (python-shell-send-string
2417 (format
2418 (concat
2419 "import os.path;import sys;"
2420 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2421 "__package__ = '''%s''';"
2422 "import %s")
2423 directory package package)
2424 (python-shell-get-process)))
2426 (defun python-shell-accept-process-output (process &optional timeout regexp)
2427 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2428 Optional argument TIMEOUT is the timeout argument to
2429 `accept-process-output' calls. Optional argument REGEXP
2430 overrides the regexp to match the end of output, defaults to
2431 `comint-prompt-regexp.'. Returns non-nil when output was
2432 properly captured.
2434 This utility is useful in situations where the output may be
2435 received in chunks, since `accept-process-output' gives no
2436 guarantees they will be grabbed in a single call. An example use
2437 case for this would be the CPython shell start-up, where the
2438 banner and the initial prompt are received separately."
2439 (let ((regexp (or regexp comint-prompt-regexp)))
2440 (catch 'found
2441 (while t
2442 (when (not (accept-process-output process timeout))
2443 (throw 'found nil))
2444 (when (looking-back
2445 regexp (car (python-util-comint-last-prompt)))
2446 (throw 'found t))))))
2448 (defun python-shell-comint-end-of-output-p (output)
2449 "Return non-nil if OUTPUT is ends with input prompt."
2450 (string-match
2451 ;; XXX: It seems on macOS an extra carriage return is attached
2452 ;; at the end of output, this handles that too.
2453 (concat
2454 "\r?\n?"
2455 ;; Remove initial caret from calculated regexp
2456 (replace-regexp-in-string
2457 (rx string-start ?^) ""
2458 python-shell--prompt-calculated-input-regexp)
2459 (rx eos))
2460 output))
2462 (define-obsolete-function-alias
2463 'python-comint-output-filter-function
2464 'ansi-color-filter-apply
2465 "25.1")
2467 (defun python-comint-postoutput-scroll-to-bottom (output)
2468 "Faster version of `comint-postoutput-scroll-to-bottom'.
2469 Avoids `recenter' calls until OUTPUT is completely sent."
2470 (when (and (not (string= "" output))
2471 (python-shell-comint-end-of-output-p
2472 (ansi-color-filter-apply output)))
2473 (comint-postoutput-scroll-to-bottom output))
2474 output)
2476 (defvar python-shell--parent-buffer nil)
2478 (defmacro python-shell-with-shell-buffer (&rest body)
2479 "Execute the forms in BODY with the shell buffer temporarily current.
2480 Signals an error if no shell buffer is available for current buffer."
2481 (declare (indent 0) (debug t))
2482 (let ((shell-process (make-symbol "shell-process")))
2483 `(let ((,shell-process (python-shell-get-process-or-error)))
2484 (with-current-buffer (process-buffer ,shell-process)
2485 ,@body))))
2487 (defvar python-shell--font-lock-buffer nil)
2489 (defun python-shell-font-lock-get-or-create-buffer ()
2490 "Get or create a font-lock buffer for current inferior process."
2491 (python-shell-with-shell-buffer
2492 (if python-shell--font-lock-buffer
2493 python-shell--font-lock-buffer
2494 (let ((process-name
2495 (process-name (get-buffer-process (current-buffer)))))
2496 (generate-new-buffer
2497 (format " *%s-font-lock*" process-name))))))
2499 (defun python-shell-font-lock-kill-buffer ()
2500 "Kill the font-lock buffer safely."
2501 (when (and python-shell--font-lock-buffer
2502 (buffer-live-p python-shell--font-lock-buffer))
2503 (kill-buffer python-shell--font-lock-buffer)
2504 (when (derived-mode-p 'inferior-python-mode)
2505 (setq python-shell--font-lock-buffer nil))))
2507 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2508 "Execute the forms in BODY in the font-lock buffer.
2509 The value returned is the value of the last form in BODY. See
2510 also `with-current-buffer'."
2511 (declare (indent 0) (debug t))
2512 `(python-shell-with-shell-buffer
2513 (save-current-buffer
2514 (when (not (and python-shell--font-lock-buffer
2515 (get-buffer python-shell--font-lock-buffer)))
2516 (setq python-shell--font-lock-buffer
2517 (python-shell-font-lock-get-or-create-buffer)))
2518 (set-buffer python-shell--font-lock-buffer)
2519 (when (not font-lock-mode)
2520 (font-lock-mode 1))
2521 (set (make-local-variable 'delay-mode-hooks) t)
2522 (let ((python-indent-guess-indent-offset nil))
2523 (when (not (derived-mode-p 'python-mode))
2524 (python-mode))
2525 ,@body))))
2527 (defun python-shell-font-lock-cleanup-buffer ()
2528 "Cleanup the font-lock buffer.
2529 Provided as a command because this might be handy if something
2530 goes wrong and syntax highlighting in the shell gets messed up."
2531 (interactive)
2532 (python-shell-with-shell-buffer
2533 (python-shell-font-lock-with-font-lock-buffer
2534 (erase-buffer))))
2536 (defun python-shell-font-lock-comint-output-filter-function (output)
2537 "Clean up the font-lock buffer after any OUTPUT."
2538 (if (and (not (string= "" output))
2539 ;; Is end of output and is not just a prompt.
2540 (not (member
2541 (python-shell-comint-end-of-output-p
2542 (ansi-color-filter-apply output))
2543 '(nil 0))))
2544 ;; If output is other than an input prompt then "real" output has
2545 ;; been received and the font-lock buffer must be cleaned up.
2546 (python-shell-font-lock-cleanup-buffer)
2547 ;; Otherwise just add a newline.
2548 (python-shell-font-lock-with-font-lock-buffer
2549 (goto-char (point-max))
2550 (newline)))
2551 output)
2553 (defun python-shell-font-lock-post-command-hook ()
2554 "Fontifies current line in shell buffer."
2555 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2556 (when (and prompt-end (> (point) prompt-end)
2557 (process-live-p (get-buffer-process (current-buffer))))
2558 (let* ((input (buffer-substring-no-properties
2559 prompt-end (point-max)))
2560 (deactivate-mark nil)
2561 (start-pos prompt-end)
2562 (buffer-undo-list t)
2563 (font-lock-buffer-pos nil)
2564 (replacement
2565 (python-shell-font-lock-with-font-lock-buffer
2566 (delete-region (line-beginning-position)
2567 (point-max))
2568 (setq font-lock-buffer-pos (point))
2569 (insert input)
2570 ;; Ensure buffer is fontified, keeping it
2571 ;; compatible with Emacs < 24.4.
2572 (if (fboundp 'font-lock-ensure)
2573 (funcall 'font-lock-ensure)
2574 (font-lock-default-fontify-buffer))
2575 (buffer-substring font-lock-buffer-pos
2576 (point-max))))
2577 (replacement-length (length replacement))
2578 (i 0))
2579 ;; Inject text properties to get input fontified.
2580 (while (not (= i replacement-length))
2581 (let* ((plist (text-properties-at i replacement))
2582 (next-change (or (next-property-change i replacement)
2583 replacement-length))
2584 (plist (let ((face (plist-get plist 'face)))
2585 (if (not face)
2586 plist
2587 ;; Replace FACE text properties with
2588 ;; FONT-LOCK-FACE so input is fontified.
2589 (plist-put plist 'face nil)
2590 (plist-put plist 'font-lock-face face)))))
2591 (set-text-properties
2592 (+ start-pos i) (+ start-pos next-change) plist)
2593 (setq i next-change)))))))
2595 (defun python-shell-font-lock-turn-on (&optional msg)
2596 "Turn on shell font-lock.
2597 With argument MSG show activation message."
2598 (interactive "p")
2599 (python-shell-with-shell-buffer
2600 (python-shell-font-lock-kill-buffer)
2601 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2602 (add-hook 'post-command-hook
2603 #'python-shell-font-lock-post-command-hook nil 'local)
2604 (add-hook 'kill-buffer-hook
2605 #'python-shell-font-lock-kill-buffer nil 'local)
2606 (add-hook 'comint-output-filter-functions
2607 #'python-shell-font-lock-comint-output-filter-function
2608 'append 'local)
2609 (when msg
2610 (message "Shell font-lock is enabled"))))
2612 (defun python-shell-font-lock-turn-off (&optional msg)
2613 "Turn off shell font-lock.
2614 With argument MSG show deactivation message."
2615 (interactive "p")
2616 (python-shell-with-shell-buffer
2617 (python-shell-font-lock-kill-buffer)
2618 (when (python-util-comint-last-prompt)
2619 ;; Cleanup current fontification
2620 (remove-text-properties
2621 (cdr (python-util-comint-last-prompt))
2622 (line-end-position)
2623 '(face nil font-lock-face nil)))
2624 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2625 (remove-hook 'post-command-hook
2626 #'python-shell-font-lock-post-command-hook 'local)
2627 (remove-hook 'kill-buffer-hook
2628 #'python-shell-font-lock-kill-buffer 'local)
2629 (remove-hook 'comint-output-filter-functions
2630 #'python-shell-font-lock-comint-output-filter-function
2631 'local)
2632 (when msg
2633 (message "Shell font-lock is disabled"))))
2635 (defun python-shell-font-lock-toggle (&optional msg)
2636 "Toggle font-lock for shell.
2637 With argument MSG show activation/deactivation message."
2638 (interactive "p")
2639 (python-shell-with-shell-buffer
2640 (set (make-local-variable 'python-shell-font-lock-enable)
2641 (not python-shell-font-lock-enable))
2642 (if python-shell-font-lock-enable
2643 (python-shell-font-lock-turn-on msg)
2644 (python-shell-font-lock-turn-off msg))
2645 python-shell-font-lock-enable))
2647 (defvar python-shell--first-prompt-received-output-buffer nil)
2648 (defvar python-shell--first-prompt-received nil)
2650 (defcustom python-shell-first-prompt-hook nil
2651 "Hook run upon first (non-pdb) shell prompt detection.
2652 This is the place for shell setup functions that need to wait for
2653 output. Since the first prompt is ensured, this helps the
2654 current process to not hang waiting for output by safeguarding
2655 interactive actions can be performed. This is useful to safely
2656 attach setup code for long-running processes that eventually
2657 provide a shell."
2658 :version "25.1"
2659 :type 'hook
2660 :group 'python)
2662 (defun python-shell-comint-watch-for-first-prompt-output-filter (output)
2663 "Run `python-shell-first-prompt-hook' when first prompt is found in OUTPUT."
2664 (when (not python-shell--first-prompt-received)
2665 (set (make-local-variable 'python-shell--first-prompt-received-output-buffer)
2666 (concat python-shell--first-prompt-received-output-buffer
2667 (ansi-color-filter-apply output)))
2668 (when (python-shell-comint-end-of-output-p
2669 python-shell--first-prompt-received-output-buffer)
2670 (if (string-match-p
2671 (concat python-shell-prompt-pdb-regexp (rx eos))
2672 (or python-shell--first-prompt-received-output-buffer ""))
2673 ;; Skip pdb prompts and reset the buffer.
2674 (setq python-shell--first-prompt-received-output-buffer nil)
2675 (set (make-local-variable 'python-shell--first-prompt-received) t)
2676 (setq python-shell--first-prompt-received-output-buffer nil)
2677 (with-current-buffer (current-buffer)
2678 (let ((inhibit-quit nil))
2679 (run-hooks 'python-shell-first-prompt-hook))))))
2680 output)
2682 ;; Used to hold user interactive overrides to
2683 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2684 ;; will be made buffer-local by `inferior-python-mode':
2685 (defvar python-shell--interpreter)
2686 (defvar python-shell--interpreter-args)
2688 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2689 "Major mode for Python inferior process.
2690 Runs a Python interpreter as a subprocess of Emacs, with Python
2691 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2692 and `python-shell-interpreter-args' control which Python
2693 interpreter is run. Variables
2694 `python-shell-prompt-regexp',
2695 `python-shell-prompt-output-regexp',
2696 `python-shell-prompt-block-regexp',
2697 `python-shell-font-lock-enable',
2698 `python-shell-completion-setup-code',
2699 `python-shell-completion-string-code',
2700 `python-eldoc-setup-code', `python-eldoc-string-code',
2701 `python-ffap-setup-code' and `python-ffap-string-code' can
2702 customize this mode for different Python interpreters.
2704 This mode resets `comint-output-filter-functions' locally, so you
2705 may want to re-add custom functions to it using the
2706 `inferior-python-mode-hook'.
2708 You can also add additional setup code to be run at
2709 initialization of the interpreter via `python-shell-setup-codes'
2710 variable.
2712 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2713 (when python-shell--parent-buffer
2714 (python-util-clone-local-variables python-shell--parent-buffer))
2715 (set (make-local-variable 'indent-tabs-mode) nil)
2716 ;; Users can interactively override default values for
2717 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2718 ;; when calling `run-python'. This ensures values let-bound in
2719 ;; `python-shell-make-comint' are locally set if needed.
2720 (set (make-local-variable 'python-shell-interpreter)
2721 (or python-shell--interpreter python-shell-interpreter))
2722 (set (make-local-variable 'python-shell-interpreter-args)
2723 (or python-shell--interpreter-args python-shell-interpreter-args))
2724 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2725 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2726 (python-shell-prompt-set-calculated-regexps)
2727 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2728 (set (make-local-variable 'comint-prompt-read-only) t)
2729 (setq mode-line-process '(":%s"))
2730 (set (make-local-variable 'comint-output-filter-functions)
2731 '(ansi-color-process-output
2732 python-shell-comint-watch-for-first-prompt-output-filter
2733 python-pdbtrack-comint-output-filter-function
2734 python-comint-postoutput-scroll-to-bottom
2735 comint-watch-for-password-prompt))
2736 (set (make-local-variable 'compilation-error-regexp-alist)
2737 python-shell-compilation-regexp-alist)
2738 (add-hook 'completion-at-point-functions
2739 #'python-shell-completion-at-point nil 'local)
2740 (define-key inferior-python-mode-map "\t"
2741 'python-shell-completion-complete-or-indent)
2742 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2743 (make-local-variable 'python-pdbtrack-tracked-buffer)
2744 (make-local-variable 'python-shell-internal-last-output)
2745 (when python-shell-font-lock-enable
2746 (python-shell-font-lock-turn-on))
2747 (compilation-shell-minor-mode 1))
2749 (defun python-shell-make-comint (cmd proc-name &optional show internal)
2750 "Create a Python shell comint buffer.
2751 CMD is the Python command to be executed and PROC-NAME is the
2752 process name the comint buffer will get. After the comint buffer
2753 is created the `inferior-python-mode' is activated. When
2754 optional argument SHOW is non-nil the buffer is shown. When
2755 optional argument INTERNAL is non-nil this process is run on a
2756 buffer with a name that starts with a space, following the Emacs
2757 convention for temporary/internal buffers, and also makes sure
2758 the user is not queried for confirmation when the process is
2759 killed."
2760 (save-excursion
2761 (python-shell-with-environment
2762 (let* ((proc-buffer-name
2763 (format (if (not internal) "*%s*" " *%s*") proc-name)))
2764 (when (not (comint-check-proc proc-buffer-name))
2765 (let* ((cmdlist (split-string-and-unquote cmd))
2766 (interpreter (car cmdlist))
2767 (args (cdr cmdlist))
2768 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2769 interpreter nil args))
2770 (python-shell--parent-buffer (current-buffer))
2771 (process (get-buffer-process buffer))
2772 ;; Users can override the interpreter and args
2773 ;; interactively when calling `run-python', let-binding
2774 ;; these allows having the new right values in all
2775 ;; setup code that is done in `inferior-python-mode',
2776 ;; which is important, especially for prompt detection.
2777 (python-shell--interpreter interpreter)
2778 (python-shell--interpreter-args
2779 (mapconcat #'identity args " ")))
2780 (with-current-buffer buffer
2781 (inferior-python-mode))
2782 (when show (display-buffer buffer))
2783 (and internal (set-process-query-on-exit-flag process nil))))
2784 proc-buffer-name))))
2786 ;;;###autoload
2787 (defun run-python (&optional cmd dedicated show)
2788 "Run an inferior Python process.
2790 Argument CMD defaults to `python-shell-calculate-command' return
2791 value. When called interactively with `prefix-arg', it allows
2792 the user to edit such value and choose whether the interpreter
2793 should be DEDICATED for the current buffer. When numeric prefix
2794 arg is other than 0 or 4 do not SHOW.
2796 For a given buffer and same values of DEDICATED, if a process is
2797 already running for it, it will do nothing. This means that if
2798 the current buffer is using a global process, the user is still
2799 able to switch it to use a dedicated one.
2801 Runs the hook `inferior-python-mode-hook' after
2802 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2803 process buffer for a list of commands.)"
2804 (interactive
2805 (if current-prefix-arg
2806 (list
2807 (read-shell-command "Run Python: " (python-shell-calculate-command))
2808 (y-or-n-p "Make dedicated process? ")
2809 (= (prefix-numeric-value current-prefix-arg) 4))
2810 (list (python-shell-calculate-command) nil t)))
2811 (get-buffer-process
2812 (python-shell-make-comint
2813 (or cmd (python-shell-calculate-command))
2814 (python-shell-get-process-name dedicated) show)))
2816 (defun run-python-internal ()
2817 "Run an inferior Internal Python process.
2818 Input and output via buffer named after
2819 `python-shell-internal-buffer-name' and what
2820 `python-shell-internal-get-process-name' returns.
2822 This new kind of shell is intended to be used for generic
2823 communication related to defined configurations; the main
2824 difference with global or dedicated shells is that these ones are
2825 attached to a configuration, not a buffer. This means that can
2826 be used for example to retrieve the sys.path and other stuff,
2827 without messing with user shells. Note that
2828 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2829 are set to nil for these shells, so setup codes are not sent at
2830 startup."
2831 (let ((python-shell-font-lock-enable nil)
2832 (inferior-python-mode-hook nil))
2833 (get-buffer-process
2834 (python-shell-make-comint
2835 (python-shell-calculate-command)
2836 (python-shell-internal-get-process-name) nil t))))
2838 (defun python-shell-get-buffer ()
2839 "Return inferior Python buffer for current buffer.
2840 If current buffer is in `inferior-python-mode', return it."
2841 (if (derived-mode-p 'inferior-python-mode)
2842 (current-buffer)
2843 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2844 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2845 (global-proc-name (python-shell-get-process-name nil))
2846 (global-proc-buffer-name (format "*%s*" global-proc-name))
2847 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2848 (global-running (comint-check-proc global-proc-buffer-name)))
2849 ;; Always prefer dedicated
2850 (or (and dedicated-running dedicated-proc-buffer-name)
2851 (and global-running global-proc-buffer-name)))))
2853 (defun python-shell-get-process ()
2854 "Return inferior Python process for current buffer."
2855 (get-buffer-process (python-shell-get-buffer)))
2857 (defun python-shell-get-process-or-error (&optional interactivep)
2858 "Return inferior Python process for current buffer or signal error.
2859 When argument INTERACTIVEP is non-nil, use `user-error' instead
2860 of `error' with a user-friendly message."
2861 (or (python-shell-get-process)
2862 (if interactivep
2863 (user-error
2864 "Start a Python process first with `M-x run-python' or `%s'."
2865 ;; Get the binding.
2866 (key-description
2867 (where-is-internal
2868 #'run-python overriding-local-map t)))
2869 (error
2870 "No inferior Python process running."))))
2872 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2873 "Get or create an inferior Python process for current buffer and return it.
2874 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2875 are used to start the shell. If those arguments are not
2876 provided, `run-python' is called interactively and the user will
2877 be asked for their values."
2878 (let ((shell-process (python-shell-get-process)))
2879 (when (not shell-process)
2880 (if (not cmd)
2881 ;; XXX: Refactor code such that calling `run-python'
2882 ;; interactively is not needed anymore.
2883 (call-interactively 'run-python)
2884 (run-python cmd dedicated show)))
2885 (or shell-process (python-shell-get-process))))
2887 (make-obsolete
2888 #'python-shell-get-or-create-process
2889 "Instead call `python-shell-get-process' and create one if returns nil."
2890 "25.1")
2892 (defvar python-shell-internal-buffer nil
2893 "Current internal shell buffer for the current buffer.
2894 This is really not necessary at all for the code to work but it's
2895 there for compatibility with CEDET.")
2897 (defvar python-shell-internal-last-output nil
2898 "Last output captured by the internal shell.
2899 This is really not necessary at all for the code to work but it's
2900 there for compatibility with CEDET.")
2902 (defun python-shell-internal-get-or-create-process ()
2903 "Get or create an inferior Internal Python process."
2904 (let ((proc-name (python-shell-internal-get-process-name)))
2905 (if (process-live-p proc-name)
2906 (get-process proc-name)
2907 (run-python-internal))))
2909 (define-obsolete-function-alias
2910 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2912 (define-obsolete-variable-alias
2913 'python-buffer 'python-shell-internal-buffer "24.3")
2915 (define-obsolete-variable-alias
2916 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2918 (defun python-shell--save-temp-file (string)
2919 (let* ((temporary-file-directory
2920 (if (file-remote-p default-directory)
2921 (concat (file-remote-p default-directory) "/tmp")
2922 temporary-file-directory))
2923 (temp-file-name (make-temp-file "py"))
2924 (coding-system-for-write (python-info-encoding)))
2925 (with-temp-file temp-file-name
2926 (insert string)
2927 (delete-trailing-whitespace))
2928 temp-file-name))
2930 (defun python-shell-send-string (string &optional process msg)
2931 "Send STRING to inferior Python PROCESS.
2932 When optional argument MSG is non-nil, forces display of a
2933 user-friendly message if there's no process running; defaults to
2934 t when called interactively."
2935 (interactive
2936 (list (read-string "Python command: ") nil t))
2937 (let ((process (or process (python-shell-get-process-or-error msg))))
2938 (if (string-match ".\n+." string) ;Multiline.
2939 (let* ((temp-file-name (python-shell--save-temp-file string))
2940 (file-name (or (buffer-file-name) temp-file-name)))
2941 (python-shell-send-file file-name process temp-file-name t))
2942 (comint-send-string process string)
2943 (when (or (not (string-match "\n\\'" string))
2944 (string-match "\n[ \t].*\n?\\'" string))
2945 (comint-send-string process "\n")))))
2947 (defvar python-shell-output-filter-in-progress nil)
2948 (defvar python-shell-output-filter-buffer nil)
2950 (defun python-shell-output-filter (string)
2951 "Filter used in `python-shell-send-string-no-output' to grab output.
2952 STRING is the output received to this point from the process.
2953 This filter saves received output from the process in
2954 `python-shell-output-filter-buffer' and stops receiving it after
2955 detecting a prompt at the end of the buffer."
2956 (setq
2957 string (ansi-color-filter-apply string)
2958 python-shell-output-filter-buffer
2959 (concat python-shell-output-filter-buffer string))
2960 (when (python-shell-comint-end-of-output-p
2961 python-shell-output-filter-buffer)
2962 ;; Output ends when `python-shell-output-filter-buffer' contains
2963 ;; the prompt attached at the end of it.
2964 (setq python-shell-output-filter-in-progress nil
2965 python-shell-output-filter-buffer
2966 (substring python-shell-output-filter-buffer
2967 0 (match-beginning 0)))
2968 (when (string-match
2969 python-shell--prompt-calculated-output-regexp
2970 python-shell-output-filter-buffer)
2971 ;; Some shells, like IPython might append a prompt before the
2972 ;; output, clean that.
2973 (setq python-shell-output-filter-buffer
2974 (substring python-shell-output-filter-buffer (match-end 0)))))
2977 (defun python-shell-send-string-no-output (string &optional process)
2978 "Send STRING to PROCESS and inhibit output.
2979 Return the output."
2980 (let ((process (or process (python-shell-get-process-or-error)))
2981 (comint-preoutput-filter-functions
2982 '(python-shell-output-filter))
2983 (python-shell-output-filter-in-progress t)
2984 (inhibit-quit t))
2986 (with-local-quit
2987 (python-shell-send-string string process)
2988 (while python-shell-output-filter-in-progress
2989 ;; `python-shell-output-filter' takes care of setting
2990 ;; `python-shell-output-filter-in-progress' to NIL after it
2991 ;; detects end of output.
2992 (accept-process-output process))
2993 (prog1
2994 python-shell-output-filter-buffer
2995 (setq python-shell-output-filter-buffer nil)))
2996 (with-current-buffer (process-buffer process)
2997 (comint-interrupt-subjob)))))
2999 (defun python-shell-internal-send-string (string)
3000 "Send STRING to the Internal Python interpreter.
3001 Returns the output. See `python-shell-send-string-no-output'."
3002 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
3003 ;; updated to support this new mode.
3004 (setq python-shell-internal-last-output
3005 (python-shell-send-string-no-output
3006 ;; Makes this function compatible with the old
3007 ;; python-send-receive. (At least for CEDET).
3008 (replace-regexp-in-string "_emacs_out +" "" string)
3009 (python-shell-internal-get-or-create-process))))
3011 (define-obsolete-function-alias
3012 'python-send-receive 'python-shell-internal-send-string "24.3")
3014 (define-obsolete-function-alias
3015 'python-send-string 'python-shell-internal-send-string "24.3")
3017 (defun python-shell-buffer-substring (start end &optional nomain)
3018 "Send buffer substring from START to END formatted for shell.
3019 This is a wrapper over `buffer-substring' that takes care of
3020 different transformations for the code sent to be evaluated in
3021 the python shell:
3022 1. When optional argument NOMAIN is non-nil everything under an
3023 \"if __name__ == \\='__main__\\='\" block will be removed.
3024 2. When a subregion of the buffer is sent, it takes care of
3025 appending extra empty lines so tracebacks are correct.
3026 3. When the region sent is a substring of the current buffer, a
3027 coding cookie is added.
3028 4. Wraps indented regions under an \"if True:\" block so the
3029 interpreter evaluates them correctly."
3030 (let* ((start (save-excursion
3031 ;; Normalize start to the line beginning position.
3032 (goto-char start)
3033 (line-beginning-position)))
3034 (substring (buffer-substring-no-properties start end))
3035 (starts-at-point-min-p (save-restriction
3036 (widen)
3037 (= (point-min) start)))
3038 (encoding (python-info-encoding))
3039 (toplevel-p (zerop (save-excursion
3040 (goto-char start)
3041 (python-util-forward-comment 1)
3042 (current-indentation))))
3043 (fillstr (when (not starts-at-point-min-p)
3044 (concat
3045 (format "# -*- coding: %s -*-\n" encoding)
3046 (make-string
3047 ;; Subtract 2 because of the coding cookie.
3048 (- (line-number-at-pos start) 2) ?\n)))))
3049 (with-temp-buffer
3050 (python-mode)
3051 (when fillstr
3052 (insert fillstr))
3053 (insert substring)
3054 (goto-char (point-min))
3055 (when (not toplevel-p)
3056 (insert "if True:")
3057 (delete-region (point) (line-end-position)))
3058 (when nomain
3059 (let* ((if-name-main-start-end
3060 (and nomain
3061 (save-excursion
3062 (when (python-nav-if-name-main)
3063 (cons (point)
3064 (progn (python-nav-forward-sexp-safe)
3065 ;; Include ending newline
3066 (forward-line 1)
3067 (point)))))))
3068 ;; Oh destructuring bind, how I miss you.
3069 (if-name-main-start (car if-name-main-start-end))
3070 (if-name-main-end (cdr if-name-main-start-end))
3071 (fillstr (make-string
3072 (- (line-number-at-pos if-name-main-end)
3073 (line-number-at-pos if-name-main-start)) ?\n)))
3074 (when if-name-main-start-end
3075 (goto-char if-name-main-start)
3076 (delete-region if-name-main-start if-name-main-end)
3077 (insert fillstr))))
3078 ;; Ensure there's only one coding cookie in the generated string.
3079 (goto-char (point-min))
3080 (when (looking-at-p (python-rx coding-cookie))
3081 (forward-line 1)
3082 (when (looking-at-p (python-rx coding-cookie))
3083 (delete-region
3084 (line-beginning-position) (line-end-position))))
3085 (buffer-substring-no-properties (point-min) (point-max)))))
3087 (defun python-shell-send-region (start end &optional send-main msg)
3088 "Send the region delimited by START and END to inferior Python process.
3089 When optional argument SEND-MAIN is non-nil, allow execution of
3090 code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
3091 When called interactively SEND-MAIN defaults to nil, unless it's
3092 called with prefix argument. When optional argument MSG is
3093 non-nil, forces display of a user-friendly message if there's no
3094 process running; defaults to t when called interactively."
3095 (interactive
3096 (list (region-beginning) (region-end) current-prefix-arg t))
3097 (let* ((string (python-shell-buffer-substring start end (not send-main)))
3098 (process (python-shell-get-process-or-error msg))
3099 (original-string (buffer-substring-no-properties start end))
3100 (_ (string-match "\\`\n*\\(.*\\)" original-string)))
3101 (message "Sent: %s..." (match-string 1 original-string))
3102 (python-shell-send-string string process)))
3104 (defun python-shell-send-buffer (&optional send-main msg)
3105 "Send the entire buffer to inferior Python process.
3106 When optional argument SEND-MAIN is non-nil, allow execution of
3107 code inside blocks delimited by \"if __name__== \\='__main__\\=':\".
3108 When called interactively SEND-MAIN defaults to nil, unless it's
3109 called with prefix argument. When optional argument MSG is
3110 non-nil, forces display of a user-friendly message if there's no
3111 process running; defaults to t when called interactively."
3112 (interactive (list current-prefix-arg t))
3113 (save-restriction
3114 (widen)
3115 (python-shell-send-region (point-min) (point-max) send-main msg)))
3117 (defun python-shell-send-defun (&optional arg msg)
3118 "Send the current defun to inferior Python process.
3119 When argument ARG is non-nil do not include decorators. When
3120 optional argument MSG is non-nil, forces display of a
3121 user-friendly message if there's no process running; defaults to
3122 t when called interactively."
3123 (interactive (list current-prefix-arg t))
3124 (save-excursion
3125 (python-shell-send-region
3126 (progn
3127 (end-of-line 1)
3128 (while (and (or (python-nav-beginning-of-defun)
3129 (beginning-of-line 1))
3130 (> (current-indentation) 0)))
3131 (when (not arg)
3132 (while (and (forward-line -1)
3133 (looking-at (python-rx decorator))))
3134 (forward-line 1))
3135 (point-marker))
3136 (progn
3137 (or (python-nav-end-of-defun)
3138 (end-of-line 1))
3139 (point-marker))
3140 nil ;; noop
3141 msg)))
3143 (defun python-shell-send-file (file-name &optional process temp-file-name
3144 delete msg)
3145 "Send FILE-NAME to inferior Python PROCESS.
3146 If TEMP-FILE-NAME is passed then that file is used for processing
3147 instead, while internally the shell will continue to use
3148 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
3149 TEMP-FILE-NAME is deleted after evaluation is performed. When
3150 optional argument MSG is non-nil, forces display of a
3151 user-friendly message if there's no process running; defaults to
3152 t when called interactively."
3153 (interactive
3154 (list
3155 (read-file-name "File to send: ") ; file-name
3156 nil ; process
3157 nil ; temp-file-name
3158 nil ; delete
3159 t)) ; msg
3160 (let* ((process (or process (python-shell-get-process-or-error msg)))
3161 (encoding (with-temp-buffer
3162 (insert-file-contents
3163 (or temp-file-name file-name))
3164 (python-info-encoding)))
3165 (file-name (expand-file-name (file-local-name file-name)))
3166 (temp-file-name (when temp-file-name
3167 (expand-file-name
3168 (file-local-name temp-file-name)))))
3169 (python-shell-send-string
3170 (format
3171 (concat
3172 "import codecs, os;"
3173 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
3174 "__code = __pyfile.read().encode('''%s''');"
3175 "__pyfile.close();"
3176 (when (and delete temp-file-name)
3177 (format "os.remove('''%s''');" temp-file-name))
3178 "exec(compile(__code, '''%s''', 'exec'));")
3179 (or temp-file-name file-name) encoding encoding file-name)
3180 process)))
3182 (defun python-shell-switch-to-shell (&optional msg)
3183 "Switch to inferior Python process buffer.
3184 When optional argument MSG is non-nil, forces display of a
3185 user-friendly message if there's no process running; defaults to
3186 t when called interactively."
3187 (interactive "p")
3188 (pop-to-buffer
3189 (process-buffer (python-shell-get-process-or-error msg)) nil t))
3191 (defun python-shell-send-setup-code ()
3192 "Send all setup code for shell.
3193 This function takes the list of setup code to send from the
3194 `python-shell-setup-codes' list."
3195 (when python-shell-setup-codes
3196 (let ((process (python-shell-get-process))
3197 (code (concat
3198 (mapconcat
3199 (lambda (elt)
3200 (cond ((stringp elt) elt)
3201 ((symbolp elt) (symbol-value elt))
3202 (t "")))
3203 python-shell-setup-codes
3204 "\n\nprint ('python.el: sent setup code')"))))
3205 (python-shell-send-string code process)
3206 (python-shell-accept-process-output process))))
3208 (add-hook 'python-shell-first-prompt-hook
3209 #'python-shell-send-setup-code)
3212 ;;; Shell completion
3214 (defcustom python-shell-completion-setup-code
3216 def __PYTHON_EL_get_completions(text):
3217 completions = []
3218 completer = None
3220 try:
3221 import readline
3223 try:
3224 import __builtin__
3225 except ImportError:
3226 # Python 3
3227 import builtins as __builtin__
3228 builtins = dir(__builtin__)
3230 is_ipython = ('__IPYTHON__' in builtins or
3231 '__IPYTHON__active' in builtins)
3232 splits = text.split()
3233 is_module = splits and splits[0] in ('from', 'import')
3235 if is_ipython and is_module:
3236 from IPython.core.completerlib import module_completion
3237 completions = module_completion(text.strip())
3238 elif is_ipython and '__IP' in builtins:
3239 completions = __IP.complete(text)
3240 elif is_ipython and 'get_ipython' in builtins:
3241 completions = get_ipython().Completer.all_completions(text)
3242 else:
3243 # Try to reuse current completer.
3244 completer = readline.get_completer()
3245 if not completer:
3246 # importing rlcompleter sets the completer, use it as a
3247 # last resort to avoid breaking customizations.
3248 import rlcompleter
3249 completer = readline.get_completer()
3250 if getattr(completer, 'PYTHON_EL_WRAPPED', False):
3251 completer.print_mode = False
3252 i = 0
3253 while True:
3254 completion = completer(text, i)
3255 if not completion:
3256 break
3257 i += 1
3258 completions.append(completion)
3259 except:
3260 pass
3261 finally:
3262 if getattr(completer, 'PYTHON_EL_WRAPPED', False):
3263 completer.print_mode = True
3264 return completions"
3265 "Code used to setup completion in inferior Python processes."
3266 :type 'string
3267 :group 'python)
3269 (defcustom python-shell-completion-string-code
3270 "';'.join(__PYTHON_EL_get_completions('''%s'''))"
3271 "Python code used to get a string of completions separated by semicolons.
3272 The string passed to the function is the current python name or
3273 the full statement in the case of imports."
3274 :type 'string
3275 :group 'python)
3277 (define-obsolete-variable-alias
3278 'python-shell-completion-module-string-code
3279 'python-shell-completion-string-code
3280 "24.4"
3281 "Completion string code must also autocomplete modules.")
3283 (define-obsolete-variable-alias
3284 'python-shell-completion-pdb-string-code
3285 'python-shell-completion-string-code
3286 "25.1"
3287 "Completion string code must work for (i)pdb.")
3289 (defcustom python-shell-completion-native-disabled-interpreters
3290 ;; PyPy's readline cannot handle some escape sequences yet. Native
3291 ;; completion was found to be non-functional for IPython (see
3292 ;; Bug#25067).
3293 (list "pypy" "ipython")
3294 "List of disabled interpreters.
3295 When a match is found, native completion is disabled."
3296 :version "25.1"
3297 :type '(repeat string))
3299 (defcustom python-shell-completion-native-enable t
3300 "Enable readline based native completion."
3301 :version "25.1"
3302 :type 'boolean)
3304 (defcustom python-shell-completion-native-output-timeout 5.0
3305 "Time in seconds to wait for completion output before giving up."
3306 :version "25.1"
3307 :type 'float)
3309 (defcustom python-shell-completion-native-try-output-timeout 1.0
3310 "Time in seconds to wait for *trying* native completion output."
3311 :version "25.1"
3312 :type 'float)
3314 (defvar python-shell-completion-native-redirect-buffer
3315 " *Python completions redirect*"
3316 "Buffer to be used to redirect output of readline commands.")
3318 (defun python-shell-completion-native-interpreter-disabled-p ()
3319 "Return non-nil if interpreter has native completion disabled."
3320 (when python-shell-completion-native-disabled-interpreters
3321 (string-match
3322 (regexp-opt python-shell-completion-native-disabled-interpreters)
3323 (file-name-nondirectory python-shell-interpreter))))
3325 (defun python-shell-completion-native-try ()
3326 "Return non-nil if can trigger native completion."
3327 (let ((python-shell-completion-native-enable t)
3328 (python-shell-completion-native-output-timeout
3329 python-shell-completion-native-try-output-timeout))
3330 (python-shell-completion-native-get-completions
3331 (get-buffer-process (current-buffer))
3332 nil "_")))
3334 (defun python-shell-completion-native-setup ()
3335 "Try to setup native completion, return non-nil on success."
3336 (let ((process (python-shell-get-process)))
3337 (with-current-buffer (process-buffer process)
3338 (python-shell-send-string "
3339 def __PYTHON_EL_native_completion_setup():
3340 try:
3341 import readline
3343 try:
3344 import __builtin__
3345 except ImportError:
3346 # Python 3
3347 import builtins as __builtin__
3349 builtins = dir(__builtin__)
3350 is_ipython = ('__IPYTHON__' in builtins or
3351 '__IPYTHON__active' in builtins)
3353 class __PYTHON_EL_Completer:
3354 '''Completer wrapper that prints candidates to stdout.
3356 It wraps an existing completer function and changes its behavior so
3357 that the user input is unchanged and real candidates are printed to
3358 stdout.
3360 Returned candidates are '0__dummy_completion__' and
3361 '1__dummy_completion__' in that order ('0__dummy_completion__' is
3362 returned repeatedly until all possible candidates are consumed).
3364 The real candidates are printed to stdout so that they can be
3365 easily retrieved through comint output redirect trickery.
3368 PYTHON_EL_WRAPPED = True
3370 def __init__(self, completer):
3371 self.completer = completer
3372 self.last_completion = None
3373 self.print_mode = True
3375 def __call__(self, text, state):
3376 if state == 0:
3377 # Set the first dummy completion.
3378 self.last_completion = None
3379 completion = '0__dummy_completion__'
3380 else:
3381 completion = self.completer(text, state - 1)
3383 if not completion:
3384 if self.last_completion != '1__dummy_completion__':
3385 # When no more completions are available, returning a
3386 # dummy with non-sharing prefix allow ensuring output
3387 # while preventing changes to current input.
3388 # Coincidentally it's also the end of output.
3389 completion = '1__dummy_completion__'
3390 elif completion.endswith('('):
3391 # Remove parens on callables as it breaks completion on
3392 # arguments (e.g. str(Ari<tab>)).
3393 completion = completion[:-1]
3394 self.last_completion = completion
3396 if completion in (
3397 '0__dummy_completion__', '1__dummy_completion__'):
3398 return completion
3399 elif completion:
3400 # For every non-dummy completion, return a repeated dummy
3401 # one and print the real candidate so it can be retrieved
3402 # by comint output filters.
3403 if self.print_mode:
3404 print (completion)
3405 return '0__dummy_completion__'
3406 else:
3407 return completion
3408 else:
3409 return completion
3411 completer = readline.get_completer()
3413 if not completer:
3414 # Used as last resort to avoid breaking customizations.
3415 import rlcompleter
3416 completer = readline.get_completer()
3418 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3419 # Wrap the existing completer function only once.
3420 new_completer = __PYTHON_EL_Completer(completer)
3421 if not is_ipython:
3422 readline.set_completer(new_completer)
3423 else:
3424 # Try both initializations to cope with all IPython versions.
3425 # This works fine for IPython 3.x but not for earlier:
3426 readline.set_completer(new_completer)
3427 # IPython<3 hacks readline such that `readline.set_completer`
3428 # won't work. This workaround injects the new completer
3429 # function into the existing instance directly:
3430 instance = getattr(completer, 'im_self', completer.__self__)
3431 instance.rlcomplete = new_completer
3433 if readline.__doc__ and 'libedit' in readline.__doc__:
3434 readline.parse_and_bind('bind ^I rl_complete')
3435 else:
3436 readline.parse_and_bind('tab: complete')
3437 # Require just one tab to send output.
3438 readline.parse_and_bind('set show-all-if-ambiguous on')
3440 print ('python.el: native completion setup loaded')
3441 except:
3442 print ('python.el: native completion setup failed')
3444 __PYTHON_EL_native_completion_setup()" process)
3445 (when (and
3446 (python-shell-accept-process-output
3447 process python-shell-completion-native-try-output-timeout)
3448 (save-excursion
3449 (re-search-backward
3450 (regexp-quote "python.el: native completion setup loaded") nil t 1)))
3451 (python-shell-completion-native-try)))))
3453 (defun python-shell-completion-native-turn-off (&optional msg)
3454 "Turn off shell native completions.
3455 With argument MSG show deactivation message."
3456 (interactive "p")
3457 (python-shell-with-shell-buffer
3458 (set (make-local-variable 'python-shell-completion-native-enable) nil)
3459 (when msg
3460 (message "Shell native completion is disabled, using fallback"))))
3462 (defun python-shell-completion-native-turn-on (&optional msg)
3463 "Turn on shell native completions.
3464 With argument MSG show deactivation message."
3465 (interactive "p")
3466 (python-shell-with-shell-buffer
3467 (set (make-local-variable 'python-shell-completion-native-enable) t)
3468 (python-shell-completion-native-turn-on-maybe msg)))
3470 (defun python-shell-completion-native-turn-on-maybe (&optional msg)
3471 "Turn on native completions if enabled and available.
3472 With argument MSG show activation/deactivation message."
3473 (interactive "p")
3474 (python-shell-with-shell-buffer
3475 (when python-shell-completion-native-enable
3476 (cond
3477 ((python-shell-completion-native-interpreter-disabled-p)
3478 (python-shell-completion-native-turn-off msg))
3479 ((python-shell-completion-native-setup)
3480 (when msg
3481 (message "Shell native completion is enabled.")))
3482 (t (lwarn
3483 '(python python-shell-completion-native-turn-on-maybe)
3484 :warning
3485 (concat
3486 "Your `python-shell-interpreter' doesn't seem to "
3487 "support readline, yet `python-shell-completion-native-enable' "
3488 (format "was t and %S is not part of the "
3489 (file-name-nondirectory python-shell-interpreter))
3490 "`python-shell-completion-native-disabled-interpreters' "
3491 "list. Native completions have been disabled locally. "))
3492 (python-shell-completion-native-turn-off msg))))))
3494 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3495 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3496 (python-shell-completion-native-turn-on-maybe t))
3498 (add-hook 'python-shell-first-prompt-hook
3499 #'python-shell-completion-native-turn-on-maybe-with-msg)
3501 (defun python-shell-completion-native-toggle (&optional msg)
3502 "Toggle shell native completion.
3503 With argument MSG show activation/deactivation message."
3504 (interactive "p")
3505 (python-shell-with-shell-buffer
3506 (if python-shell-completion-native-enable
3507 (python-shell-completion-native-turn-off msg)
3508 (python-shell-completion-native-turn-on msg))
3509 python-shell-completion-native-enable))
3511 (defun python-shell-completion-native-get-completions (process import input)
3512 "Get completions using native readline for PROCESS.
3513 When IMPORT is non-nil takes precedence over INPUT for
3514 completion."
3515 (with-current-buffer (process-buffer process)
3516 (let* ((input (or import input))
3517 (original-filter-fn (process-filter process))
3518 (redirect-buffer (get-buffer-create
3519 python-shell-completion-native-redirect-buffer))
3520 (trigger "\t")
3521 (new-input (concat input trigger))
3522 (input-length
3523 (save-excursion
3524 (+ (- (point-max) (comint-bol)) (length new-input))))
3525 (delete-line-command (make-string input-length ?\b))
3526 (input-to-send (concat new-input delete-line-command)))
3527 ;; Ensure restoring the process filter, even if the user quits
3528 ;; or there's some other error.
3529 (unwind-protect
3530 (with-current-buffer redirect-buffer
3531 ;; Cleanup the redirect buffer
3532 (erase-buffer)
3533 ;; Mimic `comint-redirect-send-command', unfortunately it
3534 ;; can't be used here because it expects a newline in the
3535 ;; command and that's exactly what we are trying to avoid.
3536 (let ((comint-redirect-echo-input nil)
3537 (comint-redirect-completed nil)
3538 (comint-redirect-perform-sanity-check nil)
3539 (comint-redirect-insert-matching-regexp t)
3540 (comint-redirect-finished-regexp
3541 "1__dummy_completion__[[:space:]]*\n")
3542 (comint-redirect-output-buffer redirect-buffer))
3543 ;; Compatibility with Emacs 24.x. Comint changed and
3544 ;; now `comint-redirect-filter' gets 3 args. This
3545 ;; checks which version of `comint-redirect-filter' is
3546 ;; in use based on its args and uses `apply-partially'
3547 ;; to make it up for the 3 args case.
3548 (if (= (length
3549 (help-function-arglist 'comint-redirect-filter)) 3)
3550 (set-process-filter
3551 process (apply-partially
3552 #'comint-redirect-filter original-filter-fn))
3553 (set-process-filter process #'comint-redirect-filter))
3554 (process-send-string process input-to-send)
3555 ;; Grab output until our dummy completion used as
3556 ;; output end marker is found.
3557 (when (python-shell-accept-process-output
3558 process python-shell-completion-native-output-timeout
3559 comint-redirect-finished-regexp)
3560 (re-search-backward "0__dummy_completion__" nil t)
3561 (cl-remove-duplicates
3562 (split-string
3563 (buffer-substring-no-properties
3564 (line-beginning-position) (point-min))
3565 "[ \f\t\n\r\v()]+" t)
3566 :test #'string=))))
3567 (set-process-filter process original-filter-fn)))))
3569 (defun python-shell-completion-get-completions (process import input)
3570 "Do completion at point using PROCESS for IMPORT or INPUT.
3571 When IMPORT is non-nil takes precedence over INPUT for
3572 completion."
3573 (setq input (or import input))
3574 (with-current-buffer (process-buffer process)
3575 (let ((completions
3576 (python-util-strip-string
3577 (python-shell-send-string-no-output
3578 (format
3579 (concat python-shell-completion-setup-code
3580 "\nprint (" python-shell-completion-string-code ")")
3581 input) process))))
3582 (when (> (length completions) 2)
3583 (split-string completions
3584 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
3586 (defun python-shell-completion-at-point (&optional process)
3587 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3588 Optional argument PROCESS forces completions to be retrieved
3589 using that one instead of current buffer's process."
3590 (setq process (or process (get-buffer-process (current-buffer))))
3591 (let* ((line-start (if (derived-mode-p 'inferior-python-mode)
3592 ;; Working on a shell buffer: use prompt end.
3593 (cdr (python-util-comint-last-prompt))
3594 (line-beginning-position)))
3595 (import-statement
3596 (when (string-match-p
3597 (rx (* space) word-start (or "from" "import") word-end space)
3598 (buffer-substring-no-properties line-start (point)))
3599 (buffer-substring-no-properties line-start (point))))
3600 (start
3601 (save-excursion
3602 (if (not (re-search-backward
3603 (python-rx
3604 (or whitespace open-paren close-paren string-delimiter))
3605 line-start
3606 t 1))
3607 line-start
3608 (forward-char (length (match-string-no-properties 0)))
3609 (point))))
3610 (end (point))
3611 (prompt-boundaries
3612 (with-current-buffer (process-buffer process)
3613 (python-util-comint-last-prompt)))
3614 (prompt
3615 (with-current-buffer (process-buffer process)
3616 (when prompt-boundaries
3617 (buffer-substring-no-properties
3618 (car prompt-boundaries) (cdr prompt-boundaries)))))
3619 (completion-fn
3620 (with-current-buffer (process-buffer process)
3621 (cond ((or (null prompt)
3622 (< (point) (cdr prompt-boundaries)))
3623 #'ignore)
3624 ((or (not python-shell-completion-native-enable)
3625 ;; Even if native completion is enabled, for
3626 ;; pdb interaction always use the fallback
3627 ;; mechanism since the completer is changed.
3628 ;; Also, since pdb interaction is single-line
3629 ;; based, this is enough.
3630 (string-match-p python-shell-prompt-pdb-regexp prompt))
3631 #'python-shell-completion-get-completions)
3632 (t #'python-shell-completion-native-get-completions)))))
3633 (list start end
3634 (completion-table-dynamic
3635 (apply-partially
3636 completion-fn
3637 process import-statement)))))
3639 (define-obsolete-function-alias
3640 'python-shell-completion-complete-at-point
3641 'python-shell-completion-at-point
3642 "25.1")
3644 (defun python-shell-completion-complete-or-indent ()
3645 "Complete or indent depending on the context.
3646 If content before pointer is all whitespace, indent.
3647 If not try to complete."
3648 (interactive)
3649 (if (string-match "^[[:space:]]*$"
3650 (buffer-substring (comint-line-beginning-position)
3651 (point)))
3652 (indent-for-tab-command)
3653 (completion-at-point)))
3656 ;;; PDB Track integration
3658 (defcustom python-pdbtrack-activate t
3659 "Non-nil makes Python shell enable pdbtracking."
3660 :type 'boolean
3661 :group 'python
3662 :safe 'booleanp)
3664 (defcustom python-pdbtrack-stacktrace-info-regexp
3665 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3666 "Regular expression matching stacktrace information.
3667 Used to extract the current line and module being inspected."
3668 :type 'string
3669 :group 'python
3670 :safe 'stringp)
3672 (defvar python-pdbtrack-tracked-buffer nil
3673 "Variable containing the value of the current tracked buffer.
3674 Never set this variable directly, use
3675 `python-pdbtrack-set-tracked-buffer' instead.")
3677 (defvar python-pdbtrack-buffers-to-kill nil
3678 "List of buffers to be deleted after tracking finishes.")
3680 (defun python-pdbtrack-set-tracked-buffer (file-name)
3681 "Set the buffer for FILE-NAME as the tracked buffer.
3682 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3683 Returns the tracked buffer."
3684 (let* ((file-name-prospect (concat (file-remote-p default-directory)
3685 file-name))
3686 (file-buffer (get-file-buffer file-name-prospect)))
3687 (if file-buffer
3688 (setq python-pdbtrack-tracked-buffer file-buffer)
3689 (cond
3690 ((file-exists-p file-name-prospect)
3691 (setq file-buffer (find-file-noselect file-name-prospect)))
3692 ((and (not (equal file-name file-name-prospect))
3693 (file-exists-p file-name))
3694 ;; Fallback to a locally available copy of the file.
3695 (setq file-buffer (find-file-noselect file-name-prospect))))
3696 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3697 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3698 file-buffer))
3700 (defun python-pdbtrack-comint-output-filter-function (output)
3701 "Move overlay arrow to current pdb line in tracked buffer.
3702 Argument OUTPUT is a string with the output from the comint process."
3703 (when (and python-pdbtrack-activate (not (string= output "")))
3704 (let* ((full-output (ansi-color-filter-apply
3705 (buffer-substring comint-last-input-end (point-max))))
3706 (line-number)
3707 (file-name
3708 (with-temp-buffer
3709 (insert full-output)
3710 ;; When the debugger encounters a pdb.set_trace()
3711 ;; command, it prints a single stack frame. Sometimes
3712 ;; it prints a bit of extra information about the
3713 ;; arguments of the present function. When ipdb
3714 ;; encounters an exception, it prints the _entire_ stack
3715 ;; trace. To handle all of these cases, we want to find
3716 ;; the _last_ stack frame printed in the most recent
3717 ;; batch of output, then jump to the corresponding
3718 ;; file/line number.
3719 (goto-char (point-max))
3720 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3721 (setq line-number (string-to-number
3722 (match-string-no-properties 2)))
3723 (match-string-no-properties 1)))))
3724 (if (and file-name line-number)
3725 (let* ((tracked-buffer
3726 (python-pdbtrack-set-tracked-buffer file-name))
3727 (shell-buffer (current-buffer))
3728 (tracked-buffer-window (get-buffer-window tracked-buffer))
3729 (tracked-buffer-line-pos))
3730 (with-current-buffer tracked-buffer
3731 (set (make-local-variable 'overlay-arrow-string) "=>")
3732 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3733 (setq tracked-buffer-line-pos (progn
3734 (goto-char (point-min))
3735 (forward-line (1- line-number))
3736 (point-marker)))
3737 (when tracked-buffer-window
3738 (set-window-point
3739 tracked-buffer-window tracked-buffer-line-pos))
3740 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3741 (pop-to-buffer tracked-buffer)
3742 (switch-to-buffer-other-window shell-buffer))
3743 (when python-pdbtrack-tracked-buffer
3744 (with-current-buffer python-pdbtrack-tracked-buffer
3745 (set-marker overlay-arrow-position nil))
3746 (mapc #'(lambda (buffer)
3747 (ignore-errors (kill-buffer buffer)))
3748 python-pdbtrack-buffers-to-kill)
3749 (setq python-pdbtrack-tracked-buffer nil
3750 python-pdbtrack-buffers-to-kill nil)))))
3751 output)
3754 ;;; Symbol completion
3756 (defun python-completion-at-point ()
3757 "Function for `completion-at-point-functions' in `python-mode'.
3758 For this to work as best as possible you should call
3759 `python-shell-send-buffer' from time to time so context in
3760 inferior Python process is updated properly."
3761 (let ((process (python-shell-get-process)))
3762 (when process
3763 (python-shell-completion-at-point process))))
3765 (define-obsolete-function-alias
3766 'python-completion-complete-at-point
3767 'python-completion-at-point
3768 "25.1")
3771 ;;; Fill paragraph
3773 (defcustom python-fill-comment-function 'python-fill-comment
3774 "Function to fill comments.
3775 This is the function used by `python-fill-paragraph' to
3776 fill comments."
3777 :type 'symbol
3778 :group 'python)
3780 (defcustom python-fill-string-function 'python-fill-string
3781 "Function to fill strings.
3782 This is the function used by `python-fill-paragraph' to
3783 fill strings."
3784 :type 'symbol
3785 :group 'python)
3787 (defcustom python-fill-decorator-function 'python-fill-decorator
3788 "Function to fill decorators.
3789 This is the function used by `python-fill-paragraph' to
3790 fill decorators."
3791 :type 'symbol
3792 :group 'python)
3794 (defcustom python-fill-paren-function 'python-fill-paren
3795 "Function to fill parens.
3796 This is the function used by `python-fill-paragraph' to
3797 fill parens."
3798 :type 'symbol
3799 :group 'python)
3801 (defcustom python-fill-docstring-style 'pep-257
3802 "Style used to fill docstrings.
3803 This affects `python-fill-string' behavior with regards to
3804 triple quotes positioning.
3806 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3807 `symmetric', and nil. A value of nil won't care about quotes
3808 position and will treat docstrings a normal string, any other
3809 value may result in one of the following docstring styles:
3811 `django':
3813 \"\"\"
3814 Process foo, return bar.
3815 \"\"\"
3817 \"\"\"
3818 Process foo, return bar.
3820 If processing fails throw ProcessingError.
3821 \"\"\"
3823 `onetwo':
3825 \"\"\"Process foo, return bar.\"\"\"
3827 \"\"\"
3828 Process foo, return bar.
3830 If processing fails throw ProcessingError.
3832 \"\"\"
3834 `pep-257':
3836 \"\"\"Process foo, return bar.\"\"\"
3838 \"\"\"Process foo, return bar.
3840 If processing fails throw ProcessingError.
3842 \"\"\"
3844 `pep-257-nn':
3846 \"\"\"Process foo, return bar.\"\"\"
3848 \"\"\"Process foo, return bar.
3850 If processing fails throw ProcessingError.
3851 \"\"\"
3853 `symmetric':
3855 \"\"\"Process foo, return bar.\"\"\"
3857 \"\"\"
3858 Process foo, return bar.
3860 If processing fails throw ProcessingError.
3861 \"\"\""
3862 :type '(choice
3863 (const :tag "Don't format docstrings" nil)
3864 (const :tag "Django's coding standards style." django)
3865 (const :tag "One newline and start and Two at end style." onetwo)
3866 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3867 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3868 (const :tag "Symmetric style." symmetric))
3869 :group 'python
3870 :safe (lambda (val)
3871 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3873 (defun python-fill-paragraph (&optional justify)
3874 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3875 If any of the current line is in or at the end of a multi-line string,
3876 fill the string or the paragraph of it that point is in, preserving
3877 the string's indentation.
3878 Optional argument JUSTIFY defines if the paragraph should be justified."
3879 (interactive "P")
3880 (save-excursion
3881 (cond
3882 ;; Comments
3883 ((python-syntax-context 'comment)
3884 (funcall python-fill-comment-function justify))
3885 ;; Strings/Docstrings
3886 ((save-excursion (or (python-syntax-context 'string)
3887 (equal (string-to-syntax "|")
3888 (syntax-after (point)))))
3889 (funcall python-fill-string-function justify))
3890 ;; Decorators
3891 ((equal (char-after (save-excursion
3892 (python-nav-beginning-of-statement))) ?@)
3893 (funcall python-fill-decorator-function justify))
3894 ;; Parens
3895 ((or (python-syntax-context 'paren)
3896 (looking-at (python-rx open-paren))
3897 (save-excursion
3898 (skip-syntax-forward "^(" (line-end-position))
3899 (looking-at (python-rx open-paren))))
3900 (funcall python-fill-paren-function justify))
3901 (t t))))
3903 (defun python-fill-comment (&optional justify)
3904 "Comment fill function for `python-fill-paragraph'.
3905 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3906 (fill-comment-paragraph justify))
3908 (defun python-fill-string (&optional justify)
3909 "String fill function for `python-fill-paragraph'.
3910 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3911 (let* ((str-start-pos
3912 (set-marker
3913 (make-marker)
3914 (or (python-syntax-context 'string)
3915 (and (equal (string-to-syntax "|")
3916 (syntax-after (point)))
3917 (point)))))
3918 (num-quotes (python-syntax-count-quotes
3919 (char-after str-start-pos) str-start-pos))
3920 (str-end-pos
3921 (save-excursion
3922 (goto-char (+ str-start-pos num-quotes))
3923 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3924 (goto-char (point-max)))
3925 (point-marker)))
3926 (multi-line-p
3927 ;; Docstring styles may vary for oneliners and multi-liners.
3928 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3929 (delimiters-style
3930 (pcase python-fill-docstring-style
3931 ;; delimiters-style is a cons cell with the form
3932 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3933 ;; is NIL means to not add any newlines for start or end
3934 ;; of docstring. See `python-fill-docstring-style' for a
3935 ;; graphic idea of each style.
3936 (`django (cons 1 1))
3937 (`onetwo (and multi-line-p (cons 1 2)))
3938 (`pep-257 (and multi-line-p (cons nil 2)))
3939 (`pep-257-nn (and multi-line-p (cons nil 1)))
3940 (`symmetric (and multi-line-p (cons 1 1)))))
3941 (fill-paragraph-function))
3942 (save-restriction
3943 (narrow-to-region str-start-pos str-end-pos)
3944 (fill-paragraph justify))
3945 (save-excursion
3946 (when (and (python-info-docstring-p) python-fill-docstring-style)
3947 ;; Add the number of newlines indicated by the selected style
3948 ;; at the start of the docstring.
3949 (goto-char (+ str-start-pos num-quotes))
3950 (delete-region (point) (progn
3951 (skip-syntax-forward "> ")
3952 (point)))
3953 (and (car delimiters-style)
3954 (or (newline (car delimiters-style)) t)
3955 ;; Indent only if a newline is added.
3956 (indent-according-to-mode))
3957 ;; Add the number of newlines indicated by the selected style
3958 ;; at the end of the docstring.
3959 (goto-char (if (not (= str-end-pos (point-max)))
3960 (- str-end-pos num-quotes)
3961 str-end-pos))
3962 (delete-region (point) (progn
3963 (skip-syntax-backward "> ")
3964 (point)))
3965 (and (cdr delimiters-style)
3966 ;; Add newlines only if string ends.
3967 (not (= str-end-pos (point-max)))
3968 (or (newline (cdr delimiters-style)) t)
3969 ;; Again indent only if a newline is added.
3970 (indent-according-to-mode))))) t)
3972 (defun python-fill-decorator (&optional _justify)
3973 "Decorator fill function for `python-fill-paragraph'.
3974 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3977 (defun python-fill-paren (&optional justify)
3978 "Paren fill function for `python-fill-paragraph'.
3979 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3980 (save-restriction
3981 (narrow-to-region (progn
3982 (while (python-syntax-context 'paren)
3983 (goto-char (1- (point))))
3984 (line-beginning-position))
3985 (progn
3986 (when (not (python-syntax-context 'paren))
3987 (end-of-line)
3988 (when (not (python-syntax-context 'paren))
3989 (skip-syntax-backward "^)")))
3990 (while (and (python-syntax-context 'paren)
3991 (not (eobp)))
3992 (goto-char (1+ (point))))
3993 (point)))
3994 (let ((paragraph-start "\f\\|[ \t]*$")
3995 (paragraph-separate ",")
3996 (fill-paragraph-function))
3997 (goto-char (point-min))
3998 (fill-paragraph justify))
3999 (while (not (eobp))
4000 (forward-line 1)
4001 (python-indent-line)
4002 (goto-char (line-end-position))))
4006 ;;; Skeletons
4008 (defcustom python-skeleton-autoinsert nil
4009 "Non-nil means template skeletons will be automagically inserted.
4010 This happens when pressing \"if<SPACE>\", for example, to prompt for
4011 the if condition."
4012 :type 'boolean
4013 :group 'python
4014 :safe 'booleanp)
4016 (define-obsolete-variable-alias
4017 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
4019 (defvar python-skeleton-available '()
4020 "Internal list of available skeletons.")
4022 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
4023 "Abbrev table for Python mode skeletons."
4024 :case-fixed t
4025 ;; Allow / inside abbrevs.
4026 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
4027 ;; Only expand in code.
4028 :enable-function (lambda ()
4029 (and
4030 (not (python-syntax-comment-or-string-p))
4031 python-skeleton-autoinsert)))
4033 (defmacro python-skeleton-define (name doc &rest skel)
4034 "Define a `python-mode' skeleton using NAME DOC and SKEL.
4035 The skeleton will be bound to python-skeleton-NAME and will
4036 be added to `python-mode-skeleton-abbrev-table'."
4037 (declare (indent 2))
4038 (let* ((name (symbol-name name))
4039 (function-name (intern (concat "python-skeleton-" name))))
4040 `(progn
4041 (define-abbrev python-mode-skeleton-abbrev-table
4042 ,name "" ',function-name :system t)
4043 (setq python-skeleton-available
4044 (cons ',function-name python-skeleton-available))
4045 (define-skeleton ,function-name
4046 ,(or doc
4047 (format "Insert %s statement." name))
4048 ,@skel))))
4050 (define-abbrev-table 'python-mode-abbrev-table ()
4051 "Abbrev table for Python mode."
4052 :parents (list python-mode-skeleton-abbrev-table))
4054 (defmacro python-define-auxiliary-skeleton (name &optional doc &rest skel)
4055 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
4056 The skeleton will be bound to python-skeleton-NAME."
4057 (declare (indent 2))
4058 (let* ((name (symbol-name name))
4059 (function-name (intern (concat "python-skeleton--" name)))
4060 (msg (funcall (if (fboundp 'format-message) #'format-message #'format)
4061 "Add `%s' clause? " name)))
4062 (when (not skel)
4063 (setq skel
4064 `(< ,(format "%s:" name) \n \n
4065 > _ \n)))
4066 `(define-skeleton ,function-name
4067 ,(or doc
4068 (format "Auxiliary skeleton for %s statement." name))
4070 (unless (y-or-n-p ,msg)
4071 (signal 'quit t))
4072 ,@skel)))
4074 (python-define-auxiliary-skeleton else)
4076 (python-define-auxiliary-skeleton except)
4078 (python-define-auxiliary-skeleton finally)
4080 (python-skeleton-define if nil
4081 "Condition: "
4082 "if " str ":" \n
4083 _ \n
4084 ("other condition, %s: "
4086 "elif " str ":" \n
4087 > _ \n nil)
4088 '(python-skeleton--else) | ^)
4090 (python-skeleton-define while nil
4091 "Condition: "
4092 "while " str ":" \n
4093 > _ \n
4094 '(python-skeleton--else) | ^)
4096 (python-skeleton-define for nil
4097 "Iteration spec: "
4098 "for " str ":" \n
4099 > _ \n
4100 '(python-skeleton--else) | ^)
4102 (python-skeleton-define import nil
4103 "Import from module: "
4104 "from " str & " " | -5
4105 "import "
4106 ("Identifier: " str ", ") -2 \n _)
4108 (python-skeleton-define try nil
4110 "try:" \n
4111 > _ \n
4112 ("Exception, %s: "
4114 "except " str ":" \n
4115 > _ \n nil)
4116 resume:
4117 '(python-skeleton--except)
4118 '(python-skeleton--else)
4119 '(python-skeleton--finally) | ^)
4121 (python-skeleton-define def nil
4122 "Function name: "
4123 "def " str "(" ("Parameter, %s: "
4124 (unless (equal ?\( (char-before)) ", ")
4125 str) "):" \n
4126 "\"\"\"" - "\"\"\"" \n
4127 > _ \n)
4129 (python-skeleton-define class nil
4130 "Class name: "
4131 "class " str "(" ("Inheritance, %s: "
4132 (unless (equal ?\( (char-before)) ", ")
4133 str)
4134 & ")" | -1
4135 ":" \n
4136 "\"\"\"" - "\"\"\"" \n
4137 > _ \n)
4139 (defun python-skeleton-add-menu-items ()
4140 "Add menu items to Python->Skeletons menu."
4141 (let ((skeletons (sort python-skeleton-available 'string<)))
4142 (dolist (skeleton skeletons)
4143 (easy-menu-add-item
4144 nil '("Python" "Skeletons")
4145 `[,(format
4146 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
4147 ,skeleton t]))))
4149 ;;; FFAP
4151 (defcustom python-ffap-setup-code
4153 def __FFAP_get_module_path(objstr):
4154 try:
4155 import inspect
4156 import os.path
4157 # NameError exceptions are delayed until this point.
4158 obj = eval(objstr)
4159 module = inspect.getmodule(obj)
4160 filename = module.__file__
4161 ext = os.path.splitext(filename)[1]
4162 if ext in ('.pyc', '.pyo'):
4163 # Point to the source file.
4164 filename = filename[:-1]
4165 if os.path.exists(filename):
4166 return filename
4167 return ''
4168 except:
4169 return ''"
4170 "Python code to get a module path."
4171 :type 'string
4172 :group 'python)
4174 (defcustom python-ffap-string-code
4175 "__FFAP_get_module_path('''%s''')"
4176 "Python code used to get a string with the path of a module."
4177 :type 'string
4178 :group 'python)
4180 (defun python-ffap-module-path (module)
4181 "Function for `ffap-alist' to return path for MODULE."
4182 (let ((process (or
4183 (and (derived-mode-p 'inferior-python-mode)
4184 (get-buffer-process (current-buffer)))
4185 (python-shell-get-process))))
4186 (if (not process)
4188 (let ((module-file
4189 (python-shell-send-string-no-output
4190 (concat
4191 python-ffap-setup-code
4192 "\nprint (" (format python-ffap-string-code module) ")")
4193 process)))
4194 (unless (zerop (length module-file))
4195 (python-util-strip-string module-file))))))
4197 (defvar ffap-alist)
4199 (eval-after-load "ffap"
4200 '(progn
4201 (push '(python-mode . python-ffap-module-path) ffap-alist)
4202 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
4205 ;;; Code check
4207 (defcustom python-check-command
4208 (or (executable-find "pyflakes")
4209 (executable-find "epylint")
4210 "install pyflakes, pylint or something else")
4211 "Command used to check a Python file."
4212 :type 'string
4213 :group 'python)
4215 (defcustom python-check-buffer-name
4216 "*Python check: %s*"
4217 "Buffer name used for check commands."
4218 :type 'string
4219 :group 'python)
4221 (defvar python-check-custom-command nil
4222 "Internal use.")
4223 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
4224 (make-variable-buffer-local 'python-check-custom-command)
4226 (defun python-check (command)
4227 "Check a Python file (default current buffer's file).
4228 Runs COMMAND, a shell command, as if by `compile'.
4229 See `python-check-command' for the default."
4230 (interactive
4231 (list (read-string "Check command: "
4232 (or python-check-custom-command
4233 (concat python-check-command " "
4234 (shell-quote-argument
4236 (let ((name (buffer-file-name)))
4237 (and name
4238 (file-name-nondirectory name)))
4239 "")))))))
4240 (setq python-check-custom-command command)
4241 (save-some-buffers (not compilation-ask-about-save) nil)
4242 (python-shell-with-environment
4243 (compilation-start command nil
4244 (lambda (_modename)
4245 (format python-check-buffer-name command)))))
4248 ;;; Eldoc
4250 (defcustom python-eldoc-setup-code
4251 "def __PYDOC_get_help(obj):
4252 try:
4253 import inspect
4254 try:
4255 str_type = basestring
4256 except NameError:
4257 str_type = str
4258 if isinstance(obj, str_type):
4259 obj = eval(obj, globals())
4260 doc = inspect.getdoc(obj)
4261 if not doc and callable(obj):
4262 target = None
4263 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4264 target = obj.__init__
4265 objtype = 'class'
4266 else:
4267 target = obj
4268 objtype = 'def'
4269 if target:
4270 args = inspect.formatargspec(
4271 *inspect.getargspec(target)
4273 name = obj.__name__
4274 doc = '{objtype} {name}{args}'.format(
4275 objtype=objtype, name=name, args=args
4277 else:
4278 doc = doc.splitlines()[0]
4279 except:
4280 doc = ''
4281 return doc"
4282 "Python code to setup documentation retrieval."
4283 :type 'string
4284 :group 'python)
4286 (defcustom python-eldoc-string-code
4287 "__PYDOC_get_help('''%s''')"
4288 "Python code used to get a string with the documentation of an object."
4289 :type 'string
4290 :group 'python)
4292 (defun python-eldoc--get-symbol-at-point ()
4293 "Get the current symbol for eldoc.
4294 Returns the current symbol handling point within arguments."
4295 (save-excursion
4296 (let ((start (python-syntax-context 'paren)))
4297 (when start
4298 (goto-char start))
4299 (when (or start
4300 (eobp)
4301 (memq (char-syntax (char-after)) '(?\ ?-)))
4302 ;; Try to adjust to closest symbol if not in one.
4303 (python-util-forward-comment -1)))
4304 (python-info-current-symbol t)))
4306 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
4307 "Internal implementation to get documentation at point.
4308 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4309 returns will be used. If not FORCE-PROCESS is passed what
4310 `python-shell-get-process' returns is used."
4311 (let ((process (or force-process (python-shell-get-process))))
4312 (when process
4313 (let* ((input (or force-input
4314 (python-eldoc--get-symbol-at-point)))
4315 (docstring
4316 (when input
4317 ;; Prevent resizing the echo area when iPython is
4318 ;; enabled. Bug#18794.
4319 (python-util-strip-string
4320 (python-shell-send-string-no-output
4321 (concat
4322 python-eldoc-setup-code
4323 "\nprint(" (format python-eldoc-string-code input) ")")
4324 process)))))
4325 (unless (zerop (length docstring))
4326 docstring)))))
4328 (defvar-local python-eldoc-get-doc t
4329 "Non-nil means eldoc should fetch the documentation
4330 automatically. Set to nil by `python-eldoc-function' if
4331 `python-eldoc-function-timeout-permanent' is non-nil and
4332 `python-eldoc-function' times out.")
4334 (defcustom python-eldoc-function-timeout 1
4335 "Timeout for `python-eldoc-function' in seconds."
4336 :group 'python
4337 :type 'integer
4338 :version "25.1")
4340 (defcustom python-eldoc-function-timeout-permanent t
4341 "Non-nil means that when `python-eldoc-function' times out
4342 `python-eldoc-get-doc' will be set to nil"
4343 :group 'python
4344 :type 'boolean
4345 :version "25.1")
4347 (defun python-eldoc-function ()
4348 "`eldoc-documentation-function' for Python.
4349 For this to work as best as possible you should call
4350 `python-shell-send-buffer' from time to time so context in
4351 inferior Python process is updated properly.
4353 If `python-eldoc-function-timeout' seconds elapse before this
4354 function returns then if
4355 `python-eldoc-function-timeout-permanent' is non-nil
4356 `python-eldoc-get-doc' will be set to nil and eldoc will no
4357 longer return the documentation at the point automatically.
4359 Set `python-eldoc-get-doc' to t to reenable eldoc documentation
4360 fetching"
4361 (when python-eldoc-get-doc
4362 (with-timeout (python-eldoc-function-timeout
4363 (if python-eldoc-function-timeout-permanent
4364 (progn
4365 (message "Eldoc echo-area display muted in this buffer, see `python-eldoc-function'")
4366 (setq python-eldoc-get-doc nil))
4367 (message "`python-eldoc-function' timed out, see `python-eldoc-function-timeout'")))
4368 (python-eldoc--get-doc-at-point))))
4370 (defun python-eldoc-at-point (symbol)
4371 "Get help on SYMBOL using `help'.
4372 Interactively, prompt for symbol."
4373 (interactive
4374 (let ((symbol (python-eldoc--get-symbol-at-point))
4375 (enable-recursive-minibuffers t))
4376 (list (read-string (if symbol
4377 (format "Describe symbol (default %s): " symbol)
4378 "Describe symbol: ")
4379 nil nil symbol))))
4380 (message (python-eldoc--get-doc-at-point symbol)))
4382 (defun python-describe-at-point (symbol process)
4383 (interactive (list (python-info-current-symbol)
4384 (python-shell-get-process)))
4385 (comint-send-string process (concat "help('" symbol "')\n")))
4388 ;;; Hideshow
4390 (defun python-hideshow-forward-sexp-function (arg)
4391 "Python specific `forward-sexp' function for `hs-minor-mode'.
4392 Argument ARG is ignored."
4393 arg ; Shut up, byte compiler.
4394 (python-nav-end-of-defun)
4395 (unless (python-info-current-line-empty-p)
4396 (backward-char)))
4399 ;;; Imenu
4401 (defvar python-imenu-format-item-label-function
4402 'python-imenu-format-item-label
4403 "Imenu function used to format an item label.
4404 It must be a function with two arguments: TYPE and NAME.")
4406 (defvar python-imenu-format-parent-item-label-function
4407 'python-imenu-format-parent-item-label
4408 "Imenu function used to format a parent item label.
4409 It must be a function with two arguments: TYPE and NAME.")
4411 (defvar python-imenu-format-parent-item-jump-label-function
4412 'python-imenu-format-parent-item-jump-label
4413 "Imenu function used to format a parent jump item label.
4414 It must be a function with two arguments: TYPE and NAME.")
4416 (defun python-imenu-format-item-label (type name)
4417 "Return Imenu label for single node using TYPE and NAME."
4418 (format "%s (%s)" name type))
4420 (defun python-imenu-format-parent-item-label (type name)
4421 "Return Imenu label for parent node using TYPE and NAME."
4422 (format "%s..." (python-imenu-format-item-label type name)))
4424 (defun python-imenu-format-parent-item-jump-label (type _name)
4425 "Return Imenu label for parent node jump using TYPE and NAME."
4426 (if (string= type "class")
4427 "*class definition*"
4428 "*function definition*"))
4430 (defun python-imenu--get-defun-type-name ()
4431 "Return defun type and name at current position."
4432 (when (looking-at python-nav-beginning-of-defun-regexp)
4433 (let ((split (split-string (match-string-no-properties 0))))
4434 (if (= (length split) 2)
4435 split
4436 (list (concat (car split) " " (cadr split))
4437 (car (last split)))))))
4439 (defun python-imenu--put-parent (type name pos tree)
4440 "Add the parent with TYPE, NAME and POS to TREE."
4441 (let ((label
4442 (funcall python-imenu-format-item-label-function type name))
4443 (jump-label
4444 (funcall python-imenu-format-parent-item-jump-label-function type name)))
4445 (if (not tree)
4446 (cons label pos)
4447 (cons label (cons (cons jump-label pos) tree)))))
4449 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
4450 "Recursively build the tree of nested definitions of a node.
4451 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4452 not be passed explicitly unless you know what you are doing."
4453 (setq min-indent (or min-indent 0)
4454 prev-indent (or prev-indent python-indent-offset))
4455 (let* ((pos (python-nav-backward-defun))
4456 (defun-type-name (and pos (python-imenu--get-defun-type-name)))
4457 (type (car defun-type-name))
4458 (name (cadr defun-type-name))
4459 (label (when name
4460 (funcall python-imenu-format-item-label-function type name)))
4461 (indent (current-indentation))
4462 (children-indent-limit (+ python-indent-offset min-indent)))
4463 (cond ((not pos)
4464 ;; Nothing found, probably near to bobp.
4465 nil)
4466 ((<= indent min-indent)
4467 ;; The current indentation points that this is a parent
4468 ;; node, add it to the tree and stop recursing.
4469 (python-imenu--put-parent type name pos tree))
4471 (python-imenu--build-tree
4472 min-indent
4473 indent
4474 (if (<= indent children-indent-limit)
4475 ;; This lies within the children indent offset range,
4476 ;; so it's a normal child of its parent (i.e., not
4477 ;; a child of a child).
4478 (cons (cons label pos) tree)
4479 ;; Oh no, a child of a child?! Fear not, we
4480 ;; know how to roll. We recursively parse these by
4481 ;; swapping prev-indent and min-indent plus adding this
4482 ;; newly found item to a fresh subtree. This works, I
4483 ;; promise.
4484 (cons
4485 (python-imenu--build-tree
4486 prev-indent indent (list (cons label pos)))
4487 tree)))))))
4489 (defun python-imenu-create-index ()
4490 "Return tree Imenu alist for the current Python buffer.
4491 Change `python-imenu-format-item-label-function',
4492 `python-imenu-format-parent-item-label-function',
4493 `python-imenu-format-parent-item-jump-label-function' to
4494 customize how labels are formatted."
4495 (goto-char (point-max))
4496 (let ((index)
4497 (tree))
4498 (while (setq tree (python-imenu--build-tree))
4499 (setq index (cons tree index)))
4500 index))
4502 (defun python-imenu-create-flat-index (&optional alist prefix)
4503 "Return flat outline of the current Python buffer for Imenu.
4504 Optional argument ALIST is the tree to be flattened; when nil
4505 `python-imenu-build-index' is used with
4506 `python-imenu-format-parent-item-jump-label-function'
4507 `python-imenu-format-parent-item-label-function'
4508 `python-imenu-format-item-label-function' set to
4509 (lambda (type name) name)
4510 Optional argument PREFIX is used in recursive calls and should
4511 not be passed explicitly.
4513 Converts this:
4515 ((\"Foo\" . 103)
4516 (\"Bar\" . 138)
4517 (\"decorator\"
4518 (\"decorator\" . 173)
4519 (\"wrap\"
4520 (\"wrap\" . 353)
4521 (\"wrapped_f\" . 393))))
4523 To this:
4525 ((\"Foo\" . 103)
4526 (\"Bar\" . 138)
4527 (\"decorator\" . 173)
4528 (\"decorator.wrap\" . 353)
4529 (\"decorator.wrapped_f\" . 393))"
4530 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4531 (apply
4532 'nconc
4533 (mapcar
4534 (lambda (item)
4535 (let ((name (if prefix
4536 (concat prefix "." (car item))
4537 (car item)))
4538 (pos (cdr item)))
4539 (cond ((or (numberp pos) (markerp pos))
4540 (list (cons name pos)))
4541 ((listp pos)
4542 (cons
4543 (cons name (cdar pos))
4544 (python-imenu-create-flat-index (cddr item) name))))))
4545 (or alist
4546 (let* ((fn (lambda (_type name) name))
4547 (python-imenu-format-item-label-function fn)
4548 (python-imenu-format-parent-item-label-function fn)
4549 (python-imenu-format-parent-item-jump-label-function fn))
4550 (python-imenu-create-index))))))
4553 ;;; Misc helpers
4555 (defun python-info-current-defun (&optional include-type)
4556 "Return name of surrounding function with Python compatible dotty syntax.
4557 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4558 This function can be used as the value of `add-log-current-defun-function'
4559 since it returns nil if point is not inside a defun."
4560 (save-restriction
4561 (prog-widen)
4562 (save-excursion
4563 (end-of-line 1)
4564 (let ((names)
4565 (starting-indentation (current-indentation))
4566 (starting-pos (point))
4567 (first-run t)
4568 (last-indent)
4569 (type))
4570 (catch 'exit
4571 (while (python-nav-beginning-of-defun 1)
4572 (when (save-match-data
4573 (and
4574 (or (not last-indent)
4575 (< (current-indentation) last-indent))
4577 (and first-run
4578 (save-excursion
4579 ;; If this is the first run, we may add
4580 ;; the current defun at point.
4581 (setq first-run nil)
4582 (goto-char starting-pos)
4583 (python-nav-beginning-of-statement)
4584 (beginning-of-line 1)
4585 (looking-at-p
4586 python-nav-beginning-of-defun-regexp)))
4587 (< starting-pos
4588 (save-excursion
4589 (let ((min-indent
4590 (+ (current-indentation)
4591 python-indent-offset)))
4592 (if (< starting-indentation min-indent)
4593 ;; If the starting indentation is not
4594 ;; within the min defun indent make the
4595 ;; check fail.
4596 starting-pos
4597 ;; Else go to the end of defun and add
4598 ;; up the current indentation to the
4599 ;; ending position.
4600 (python-nav-end-of-defun)
4601 (+ (point)
4602 (if (>= (current-indentation) min-indent)
4603 (1+ (current-indentation))
4604 0)))))))))
4605 (save-match-data (setq last-indent (current-indentation)))
4606 (if (or (not include-type) type)
4607 (setq names (cons (match-string-no-properties 1) names))
4608 (let ((match (split-string (match-string-no-properties 0))))
4609 (setq type (car match))
4610 (setq names (cons (cadr match) names)))))
4611 ;; Stop searching ASAP.
4612 (and (= (current-indentation) 0) (throw 'exit t))))
4613 (and names
4614 (concat (and type (format "%s " type))
4615 (mapconcat 'identity names ".")))))))
4617 (defun python-info-current-symbol (&optional replace-self)
4618 "Return current symbol using dotty syntax.
4619 With optional argument REPLACE-SELF convert \"self\" to current
4620 parent defun name."
4621 (let ((name
4622 (and (not (python-syntax-comment-or-string-p))
4623 (with-syntax-table python-dotty-syntax-table
4624 (let ((sym (symbol-at-point)))
4625 (and sym
4626 (substring-no-properties (symbol-name sym))))))))
4627 (when name
4628 (if (not replace-self)
4629 name
4630 (let ((current-defun (python-info-current-defun)))
4631 (if (not current-defun)
4632 name
4633 (replace-regexp-in-string
4634 (python-rx line-start word-start "self" word-end ?.)
4635 (concat
4636 (mapconcat 'identity
4637 (butlast (split-string current-defun "\\."))
4638 ".") ".")
4639 name)))))))
4641 (defun python-info-statement-starts-block-p ()
4642 "Return non-nil if current statement opens a block."
4643 (save-excursion
4644 (python-nav-beginning-of-statement)
4645 (looking-at (python-rx block-start))))
4647 (defun python-info-statement-ends-block-p ()
4648 "Return non-nil if point is at end of block."
4649 (let ((end-of-block-pos (save-excursion
4650 (python-nav-end-of-block)))
4651 (end-of-statement-pos (save-excursion
4652 (python-nav-end-of-statement))))
4653 (and end-of-block-pos end-of-statement-pos
4654 (= end-of-block-pos end-of-statement-pos))))
4656 (defun python-info-beginning-of-statement-p ()
4657 "Return non-nil if point is at beginning of statement."
4658 (= (point) (save-excursion
4659 (python-nav-beginning-of-statement)
4660 (point))))
4662 (defun python-info-end-of-statement-p ()
4663 "Return non-nil if point is at end of statement."
4664 (= (point) (save-excursion
4665 (python-nav-end-of-statement)
4666 (point))))
4668 (defun python-info-beginning-of-block-p ()
4669 "Return non-nil if point is at beginning of block."
4670 (and (python-info-beginning-of-statement-p)
4671 (python-info-statement-starts-block-p)))
4673 (defun python-info-end-of-block-p ()
4674 "Return non-nil if point is at end of block."
4675 (and (python-info-end-of-statement-p)
4676 (python-info-statement-ends-block-p)))
4678 (define-obsolete-function-alias
4679 'python-info-closing-block
4680 'python-info-dedenter-opening-block-position "24.4")
4682 (defun python-info-dedenter-opening-block-position ()
4683 "Return the point of the closest block the current line closes.
4684 Returns nil if point is not on a dedenter statement or no opening
4685 block can be detected. The latter case meaning current file is
4686 likely an invalid python file."
4687 (let ((positions (python-info-dedenter-opening-block-positions))
4688 (indentation (current-indentation))
4689 (position))
4690 (while (and (not position)
4691 positions)
4692 (save-excursion
4693 (goto-char (car positions))
4694 (if (<= (current-indentation) indentation)
4695 (setq position (car positions))
4696 (setq positions (cdr positions)))))
4697 position))
4699 (defun python-info-dedenter-opening-block-positions ()
4700 "Return points of blocks the current line may close sorted by closer.
4701 Returns nil if point is not on a dedenter statement or no opening
4702 block can be detected. The latter case meaning current file is
4703 likely an invalid python file."
4704 (save-excursion
4705 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4706 (when dedenter-pos
4707 (goto-char dedenter-pos)
4708 (let* ((cur-line (line-beginning-position))
4709 (pairs '(("elif" "elif" "if")
4710 ("else" "if" "elif" "except" "for" "while")
4711 ("except" "except" "try")
4712 ("finally" "else" "except" "try")))
4713 (dedenter (match-string-no-properties 0))
4714 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
4715 (collected-indentations)
4716 (opening-blocks))
4717 (catch 'exit
4718 (while (python-nav--syntactically
4719 (lambda ()
4720 (re-search-backward (python-rx block-start) nil t))
4721 #'<)
4722 (let ((indentation (current-indentation)))
4723 (when (and (not (memq indentation collected-indentations))
4724 (or (not collected-indentations)
4725 (< indentation (apply #'min collected-indentations)))
4726 ;; There must be no line with indentation
4727 ;; smaller than `indentation' (except for
4728 ;; blank lines) between the found opening
4729 ;; block and the current line, otherwise it
4730 ;; is not an opening block.
4731 (save-excursion
4732 (forward-line)
4733 (let ((no-back-indent t))
4734 (save-match-data
4735 (while (and (< (point) cur-line)
4736 (setq no-back-indent
4737 (or (> (current-indentation) indentation)
4738 (python-info-current-line-empty-p))))
4739 (forward-line)))
4740 no-back-indent)))
4741 (setq collected-indentations
4742 (cons indentation collected-indentations))
4743 (when (member (match-string-no-properties 0)
4744 possible-opening-blocks)
4745 (setq opening-blocks (cons (point) opening-blocks))))
4746 (when (zerop indentation)
4747 (throw 'exit nil)))))
4748 ;; sort by closer
4749 (nreverse opening-blocks))))))
4751 (define-obsolete-function-alias
4752 'python-info-closing-block-message
4753 'python-info-dedenter-opening-block-message "24.4")
4755 (defun python-info-dedenter-opening-block-message ()
4756 "Message the first line of the block the current statement closes."
4757 (let ((point (python-info-dedenter-opening-block-position)))
4758 (when point
4759 (save-restriction
4760 (prog-widen)
4761 (message "Closes %s" (save-excursion
4762 (goto-char point)
4763 (buffer-substring
4764 (point) (line-end-position))))))))
4766 (defun python-info-dedenter-statement-p ()
4767 "Return point if current statement is a dedenter.
4768 Sets `match-data' to the keyword that starts the dedenter
4769 statement."
4770 (save-excursion
4771 (python-nav-beginning-of-statement)
4772 (when (and (not (python-syntax-context-type))
4773 (looking-at (python-rx dedenter)))
4774 (point))))
4776 (defun python-info-line-ends-backslash-p (&optional line-number)
4777 "Return non-nil if current line ends with backslash.
4778 With optional argument LINE-NUMBER, check that line instead."
4779 (save-excursion
4780 (save-restriction
4781 (prog-widen)
4782 (when line-number
4783 (python-util-goto-line line-number))
4784 (while (and (not (eobp))
4785 (goto-char (line-end-position))
4786 (python-syntax-context 'paren)
4787 (not (equal (char-before (point)) ?\\)))
4788 (forward-line 1))
4789 (when (equal (char-before) ?\\)
4790 (point-marker)))))
4792 (defun python-info-beginning-of-backslash (&optional line-number)
4793 "Return the point where the backslashed line start.
4794 Optional argument LINE-NUMBER forces the line number to check against."
4795 (save-excursion
4796 (save-restriction
4797 (prog-widen)
4798 (when line-number
4799 (python-util-goto-line line-number))
4800 (when (python-info-line-ends-backslash-p)
4801 (while (save-excursion
4802 (goto-char (line-beginning-position))
4803 (python-syntax-context 'paren))
4804 (forward-line -1))
4805 (back-to-indentation)
4806 (point-marker)))))
4808 (defun python-info-continuation-line-p ()
4809 "Check if current line is continuation of another.
4810 When current line is continuation of another return the point
4811 where the continued line ends."
4812 (save-excursion
4813 (save-restriction
4814 (prog-widen)
4815 (let* ((context-type (progn
4816 (back-to-indentation)
4817 (python-syntax-context-type)))
4818 (line-start (line-number-at-pos))
4819 (context-start (when context-type
4820 (python-syntax-context context-type))))
4821 (cond ((equal context-type 'paren)
4822 ;; Lines inside a paren are always a continuation line
4823 ;; (except the first one).
4824 (python-util-forward-comment -1)
4825 (point-marker))
4826 ((member context-type '(string comment))
4827 ;; move forward an roll again
4828 (goto-char context-start)
4829 (python-util-forward-comment)
4830 (python-info-continuation-line-p))
4832 ;; Not within a paren, string or comment, the only way
4833 ;; we are dealing with a continuation line is that
4834 ;; previous line contains a backslash, and this can
4835 ;; only be the previous line from current
4836 (back-to-indentation)
4837 (python-util-forward-comment -1)
4838 (when (and (equal (1- line-start) (line-number-at-pos))
4839 (python-info-line-ends-backslash-p))
4840 (point-marker))))))))
4842 (defun python-info-block-continuation-line-p ()
4843 "Return non-nil if current line is a continuation of a block."
4844 (save-excursion
4845 (when (python-info-continuation-line-p)
4846 (forward-line -1)
4847 (back-to-indentation)
4848 (when (looking-at (python-rx block-start))
4849 (point-marker)))))
4851 (defun python-info-assignment-statement-p (&optional current-line-only)
4852 "Check if current line is an assignment.
4853 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4854 continuations, just check the if current line is an assignment."
4855 (save-excursion
4856 (let ((found nil))
4857 (if current-line-only
4858 (back-to-indentation)
4859 (python-nav-beginning-of-statement))
4860 (while (and
4861 (re-search-forward (python-rx not-simple-operator
4862 assignment-operator
4863 (group not-simple-operator))
4864 (line-end-position) t)
4865 (not found))
4866 (save-excursion
4867 ;; The assignment operator should not be inside a string.
4868 (backward-char (length (match-string-no-properties 1)))
4869 (setq found (not (python-syntax-context-type)))))
4870 (when found
4871 (skip-syntax-forward " ")
4872 (point-marker)))))
4874 ;; TODO: rename to clarify this is only for the first continuation
4875 ;; line or remove it and move its body to `python-indent-context'.
4876 (defun python-info-assignment-continuation-line-p ()
4877 "Check if current line is the first continuation of an assignment.
4878 When current line is continuation of another with an assignment
4879 return the point of the first non-blank character after the
4880 operator."
4881 (save-excursion
4882 (when (python-info-continuation-line-p)
4883 (forward-line -1)
4884 (python-info-assignment-statement-p t))))
4886 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4887 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4888 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4889 (save-excursion
4890 (beginning-of-line 1)
4891 (looking-at python-nav-beginning-of-defun-regexp))))
4893 (defun python-info-current-line-comment-p ()
4894 "Return non-nil if current line is a comment line."
4895 (char-equal
4896 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4897 ?#))
4899 (defun python-info-current-line-empty-p ()
4900 "Return non-nil if current line is empty, ignoring whitespace."
4901 (save-excursion
4902 (beginning-of-line 1)
4903 (looking-at
4904 (python-rx line-start (* whitespace)
4905 (group (* not-newline))
4906 (* whitespace) line-end))
4907 (string-equal "" (match-string-no-properties 1))))
4909 (defun python-info-docstring-p (&optional syntax-ppss)
4910 "Return non-nil if point is in a docstring.
4911 When optional argument SYNTAX-PPSS is given, use that instead of
4912 point's current `syntax-ppss'."
4913 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4914 (save-excursion
4915 (when (and syntax-ppss (python-syntax-context 'string syntax-ppss))
4916 (goto-char (nth 8 syntax-ppss)))
4917 (python-nav-beginning-of-statement)
4918 (let ((counter 1)
4919 (indentation (current-indentation))
4920 (backward-sexp-point)
4921 (re (concat "[uU]?[rR]?"
4922 (python-rx string-delimiter))))
4923 (when (and
4924 (not (python-info-assignment-statement-p))
4925 (looking-at-p re)
4926 ;; Allow up to two consecutive docstrings only.
4929 (let (last-backward-sexp-point)
4930 (while (save-excursion
4931 (python-nav-backward-sexp)
4932 (setq backward-sexp-point (point))
4933 (and (= indentation (current-indentation))
4934 ;; Make sure we're always moving point.
4935 ;; If we get stuck in the same position
4936 ;; on consecutive loop iterations,
4937 ;; bail out.
4938 (prog1 (not (eql last-backward-sexp-point
4939 backward-sexp-point))
4940 (setq last-backward-sexp-point
4941 backward-sexp-point))
4942 (looking-at-p
4943 (concat "[uU]?[rR]?"
4944 (python-rx string-delimiter)))))
4945 ;; Previous sexp was a string, restore point.
4946 (goto-char backward-sexp-point)
4947 (cl-incf counter))
4948 counter)))
4949 (python-util-forward-comment -1)
4950 (python-nav-beginning-of-statement)
4951 (cond ((bobp))
4952 ((python-info-assignment-statement-p) t)
4953 ((python-info-looking-at-beginning-of-defun))
4954 (t nil))))))
4956 (defun python-info-encoding-from-cookie ()
4957 "Detect current buffer's encoding from its coding cookie.
4958 Returns the encoding as a symbol."
4959 (let ((first-two-lines
4960 (save-excursion
4961 (save-restriction
4962 (widen)
4963 (goto-char (point-min))
4964 (forward-line 2)
4965 (buffer-substring-no-properties
4966 (point)
4967 (point-min))))))
4968 (when (string-match (python-rx coding-cookie) first-two-lines)
4969 (intern (match-string-no-properties 1 first-two-lines)))))
4971 (defun python-info-encoding ()
4972 "Return encoding for file.
4973 Try `python-info-encoding-from-cookie', if none is found then
4974 default to utf-8."
4975 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4976 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4977 ;; in the worst case scenario python.el will make things work for
4978 ;; Python 2 files with unicode data and no encoding defined.
4979 (or (python-info-encoding-from-cookie)
4980 'utf-8))
4983 ;;; Utility functions
4985 (defun python-util-goto-line (line-number)
4986 "Move point to LINE-NUMBER."
4987 (goto-char (point-min))
4988 (forward-line (1- line-number)))
4990 ;; Stolen from org-mode
4991 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4992 "Clone local variables from FROM-BUFFER.
4993 Optional argument REGEXP selects variables to clone and defaults
4994 to \"^python-\"."
4995 (mapc
4996 (lambda (pair)
4997 (and (symbolp (car pair))
4998 (string-match (or regexp "^python-")
4999 (symbol-name (car pair)))
5000 (set (make-local-variable (car pair))
5001 (cdr pair))))
5002 (buffer-local-variables from-buffer)))
5004 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
5006 (defun python-util-comint-last-prompt ()
5007 "Return comint last prompt overlay start and end.
5008 This is for compatibility with Emacs < 24.4."
5009 (cond ((bound-and-true-p comint-last-prompt-overlay)
5010 (cons (overlay-start comint-last-prompt-overlay)
5011 (overlay-end comint-last-prompt-overlay)))
5012 ((bound-and-true-p comint-last-prompt)
5013 comint-last-prompt)
5014 (t nil)))
5016 (defun python-util-forward-comment (&optional direction)
5017 "Python mode specific version of `forward-comment'.
5018 Optional argument DIRECTION defines the direction to move to."
5019 (let ((comment-start (python-syntax-context 'comment))
5020 (factor (if (< (or direction 0) 0)
5021 -99999
5022 99999)))
5023 (when comment-start
5024 (goto-char comment-start))
5025 (forward-comment factor)))
5027 (defun python-util-list-directories (directory &optional predicate max-depth)
5028 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
5029 Argument PREDICATE defaults to `identity' and must be a function
5030 that takes one argument (a full path) and returns non-nil for
5031 allowed files. When optional argument MAX-DEPTH is non-nil, stop
5032 searching when depth is reached, else don't limit."
5033 (let* ((dir (expand-file-name directory))
5034 (dir-length (length dir))
5035 (predicate (or predicate #'identity))
5036 (to-scan (list dir))
5037 (tally nil))
5038 (while to-scan
5039 (let ((current-dir (car to-scan)))
5040 (when (funcall predicate current-dir)
5041 (setq tally (cons current-dir tally)))
5042 (setq to-scan (append (cdr to-scan)
5043 (python-util-list-files
5044 current-dir #'file-directory-p)
5045 nil))
5046 (when (and max-depth
5047 (<= max-depth
5048 (length (split-string
5049 (substring current-dir dir-length)
5050 "/\\|\\\\" t))))
5051 (setq to-scan nil))))
5052 (nreverse tally)))
5054 (defun python-util-list-files (dir &optional predicate)
5055 "List files in DIR, filtering with PREDICATE.
5056 Argument PREDICATE defaults to `identity' and must be a function
5057 that takes one argument (a full path) and returns non-nil for
5058 allowed files."
5059 (let ((dir-name (file-name-as-directory dir)))
5060 (apply #'nconc
5061 (mapcar (lambda (file-name)
5062 (let ((full-file-name (expand-file-name file-name dir-name)))
5063 (when (and
5064 (not (member file-name '("." "..")))
5065 (funcall (or predicate #'identity) full-file-name))
5066 (list full-file-name))))
5067 (directory-files dir-name)))))
5069 (defun python-util-list-packages (dir &optional max-depth)
5070 "List packages in DIR, limited by MAX-DEPTH.
5071 When optional argument MAX-DEPTH is non-nil, stop searching when
5072 depth is reached, else don't limit."
5073 (let* ((dir (expand-file-name dir))
5074 (parent-dir (file-name-directory
5075 (directory-file-name
5076 (file-name-directory
5077 (file-name-as-directory dir)))))
5078 (subpath-length (length parent-dir)))
5079 (mapcar
5080 (lambda (file-name)
5081 (replace-regexp-in-string
5082 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
5083 (python-util-list-directories
5084 (directory-file-name dir)
5085 (lambda (dir)
5086 (file-exists-p (expand-file-name "__init__.py" dir)))
5087 max-depth))))
5089 (defun python-util-popn (lst n)
5090 "Return LST first N elements.
5091 N should be an integer, when negative its opposite is used.
5092 When N is bigger than the length of LST, the list is
5093 returned as is."
5094 (let* ((n (min (abs n)))
5095 (len (length lst))
5096 (acc))
5097 (if (> n len)
5099 (while (< 0 n)
5100 (setq acc (cons (car lst) acc)
5101 lst (cdr lst)
5102 n (1- n)))
5103 (reverse acc))))
5105 (defun python-util-strip-string (string)
5106 "Strip STRING whitespace and newlines from end and beginning."
5107 (replace-regexp-in-string
5108 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
5109 (: (* (any whitespace ?\r ?\n)) string-end)))
5111 string))
5113 (defun python-util-valid-regexp-p (regexp)
5114 "Return non-nil if REGEXP is valid."
5115 (ignore-errors (string-match regexp "") t))
5118 (defun python-electric-pair-string-delimiter ()
5119 (when (and electric-pair-mode
5120 (memq last-command-event '(?\" ?\'))
5121 (let ((count 0))
5122 (while (eq (char-before (- (point) count)) last-command-event)
5123 (cl-incf count))
5124 (= count 3))
5125 (eq (char-after) last-command-event))
5126 (save-excursion (insert (make-string 2 last-command-event)))))
5128 (defvar electric-indent-inhibit)
5130 ;;;###autoload
5131 (define-derived-mode python-mode prog-mode "Python"
5132 "Major mode for editing Python files.
5134 \\{python-mode-map}"
5135 (set (make-local-variable 'tab-width) 8)
5136 (set (make-local-variable 'indent-tabs-mode) nil)
5138 (set (make-local-variable 'comment-start) "# ")
5139 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
5141 (set (make-local-variable 'parse-sexp-lookup-properties) t)
5142 (set (make-local-variable 'parse-sexp-ignore-comments) t)
5144 (set (make-local-variable 'forward-sexp-function)
5145 'python-nav-forward-sexp)
5147 (set (make-local-variable 'font-lock-defaults)
5148 '(python-font-lock-keywords
5149 nil nil nil nil
5150 (font-lock-syntactic-face-function
5151 . python-font-lock-syntactic-face-function)))
5153 (set (make-local-variable 'syntax-propertize-function)
5154 python-syntax-propertize-function)
5156 (set (make-local-variable 'indent-line-function)
5157 #'python-indent-line-function)
5158 (set (make-local-variable 'indent-region-function) #'python-indent-region)
5159 ;; Because indentation is not redundant, we cannot safely reindent code.
5160 (set (make-local-variable 'electric-indent-inhibit) t)
5161 (set (make-local-variable 'electric-indent-chars)
5162 (cons ?: electric-indent-chars))
5164 ;; Add """ ... """ pairing to electric-pair-mode.
5165 (add-hook 'post-self-insert-hook
5166 #'python-electric-pair-string-delimiter 'append t)
5168 (set (make-local-variable 'paragraph-start) "\\s-*$")
5169 (set (make-local-variable 'fill-paragraph-function)
5170 #'python-fill-paragraph)
5172 (set (make-local-variable 'beginning-of-defun-function)
5173 #'python-nav-beginning-of-defun)
5174 (set (make-local-variable 'end-of-defun-function)
5175 #'python-nav-end-of-defun)
5177 (add-hook 'completion-at-point-functions
5178 #'python-completion-at-point nil 'local)
5180 (add-hook 'post-self-insert-hook
5181 #'python-indent-post-self-insert-function 'append 'local)
5183 (set (make-local-variable 'imenu-create-index-function)
5184 #'python-imenu-create-index)
5186 (set (make-local-variable 'add-log-current-defun-function)
5187 #'python-info-current-defun)
5189 (add-hook 'which-func-functions #'python-info-current-defun nil t)
5191 (set (make-local-variable 'skeleton-further-elements)
5192 '((abbrev-mode nil)
5193 (< '(backward-delete-char-untabify (min python-indent-offset
5194 (current-column))))
5195 (^ '(- (1+ (current-indentation))))))
5197 (if (null eldoc-documentation-function)
5198 ;; Emacs<25
5199 (set (make-local-variable 'eldoc-documentation-function)
5200 #'python-eldoc-function)
5201 (add-function :before-until (local 'eldoc-documentation-function)
5202 #'python-eldoc-function))
5204 (add-to-list
5205 'hs-special-modes-alist
5206 `(python-mode
5207 "\\s-*\\_<\\(?:def\\|class\\)\\_>"
5208 ;; Use the empty string as end regexp so it doesn't default to
5209 ;; "\\s)". This way parens at end of defun are properly hidden.
5212 python-hideshow-forward-sexp-function
5213 nil))
5215 (set (make-local-variable 'outline-regexp)
5216 (python-rx (* space) block-start))
5217 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
5218 (set (make-local-variable 'outline-level)
5219 #'(lambda ()
5220 "`outline-level' function for Python mode."
5221 (1+ (/ (current-indentation) python-indent-offset))))
5223 (set (make-local-variable 'prettify-symbols-alist)
5224 python--prettify-symbols-alist)
5226 (python-skeleton-add-menu-items)
5228 (make-local-variable 'python-shell-internal-buffer)
5230 (when python-indent-guess-indent-offset
5231 (python-indent-guess-indent-offset)))
5234 (provide 'python)
5236 ;; Local Variables:
5237 ;; indent-tabs-mode: nil
5238 ;; End:
5240 ;;; python.el ends here