1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2015 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Maintainer: emacs-devel@gnu.org
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Shell
35 ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
36 ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows opening Python shells
66 ;; inside Emacs and executing any block of code of your current buffer
67 ;; in that inferior Python process.
69 ;; Besides that only the standard CPython (2.x and 3.x) shell and
70 ;; IPython are officially supported out of the box, the interaction
71 ;; should support any other readline based Python shells as well
72 ;; (e.g. Jython and PyPy have been reported to work). You can change
73 ;; your default interpreter and commandline arguments by setting the
74 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
75 ;; variables. This example enables IPython globally:
77 ;; (setq python-shell-interpreter "ipython"
78 ;; python-shell-interpreter-args "-i")
80 ;; Using the "console" subcommand to start IPython in server-client
81 ;; mode is known to fail intermittently due a bug on IPython itself
82 ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
83 ;; There seems to be a race condition in the IPython server (A.K.A
84 ;; kernel) when code is sent while it is still initializing, sometimes
85 ;; causing the shell to get stalled. With that said, if an IPython
86 ;; kernel is already running, "console --existing" seems to work fine.
88 ;; Running IPython on Windows needs more tweaking. The way you should
89 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
90 ;; is as follows (of course you need to modify the paths according to
93 ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
94 ;; python-shell-interpreter-args
95 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
97 ;; Missing or delayed output used to happen due to differences between
98 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
99 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
100 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
101 ;; controls whether `python-shell-calculate-process-environment'
102 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
103 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
105 ;; The interaction relies upon having prompts for input (e.g. ">>> "
106 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
107 ;; IPython) detected properly. Failing that Emacs may hang but, in
108 ;; the case that happens, you can recover with \\[keyboard-quit]. To
109 ;; avoid this issue, a two-step prompt autodetection mechanism is
110 ;; provided: the first step is manual and consists of a collection of
111 ;; regular expressions matching common prompts for Python shells
112 ;; stored in `python-shell-prompt-input-regexps' and
113 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
114 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
115 ;; `python-shell-prompt-output-regexp' which are appended to the
116 ;; former automatically when a shell spawns; the second step is
117 ;; automatic and depends on the `python-shell-prompt-detect' helper
118 ;; function. See its docstring for details on global variables that
119 ;; modify its behavior.
121 ;; Shell completion: hitting tab will try to complete the current
122 ;; word. The two built-in mechanisms depend on Python's readline
123 ;; module: the "native" completion is tried first and is activated
124 ;; when `python-shell-completion-native-enable' is non-nil, the
125 ;; current `python-shell-interpreter' is not a member of the
126 ;; `python-shell-completion-native-disabled-interpreters' variable and
127 ;; `python-shell-completion-native-setup' succeeds; the "fallback" or
128 ;; "legacy" mechanism works by executing Python code in the background
129 ;; and enables auto-completion for shells that do not support
130 ;; receiving escape sequences (with some limitations, i.e. completion
131 ;; in blocks does not work). The code executed for the "fallback"
132 ;; completion can be found in `python-shell-completion-setup-code' and
133 ;; `python-shell-completion-string-code' variables. Their default
134 ;; values enable completion for both CPython and IPython, and probably
135 ;; any readline based shell (it's known to work with PyPy). If your
136 ;; Python installation lacks readline (like CPython for Windows),
137 ;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
138 ;; should suffice. To troubleshoot why you are not getting any
139 ;; completions, you can try the following in your Python shell:
141 ;; >>> import readline, rlcompleter
143 ;; If you see an error, then you need to either install pyreadline or
144 ;; setup custom code that avoids that dependency.
146 ;; Shell virtualenv support: The shell also contains support for
147 ;; virtualenvs and other special environment modifications thanks to
148 ;; `python-shell-process-environment' and `python-shell-exec-path'.
149 ;; These two variables allows you to modify execution paths and
150 ;; environment variables to make easy for you to setup virtualenv rules
151 ;; or behavior modifications when running shells. Here is an example
152 ;; of how to make shell processes to be run using the /path/to/env/
155 ;; (setq python-shell-process-environment
157 ;; (format "PATH=%s" (mapconcat
160 ;; (cons (getenv "PATH")
161 ;; '("/path/to/env/bin/")))
163 ;; "VIRTUAL_ENV=/path/to/env/"))
164 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
166 ;; Since the above is cumbersome and can be programmatically
167 ;; calculated, the variable `python-shell-virtualenv-root' is
168 ;; provided. When this variable is set with the path of the
169 ;; virtualenv to use, `process-environment' and `exec-path' get proper
170 ;; values in order to run shells inside the specified virtualenv. So
171 ;; the following will achieve the same as the previous example:
173 ;; (setq python-shell-virtualenv-root "/path/to/env/")
175 ;; Also the `python-shell-extra-pythonpaths' variable have been
176 ;; introduced as simple way of adding paths to the PYTHONPATH without
177 ;; affecting existing values.
179 ;; Shell package support: you can enable a package in the current
180 ;; shell so that relative imports work properly using the
181 ;; `python-shell-package-enable' command.
183 ;; Shell remote support: remote Python shells are started with the
184 ;; correct environment for files opened remotely through tramp, also
185 ;; respecting dir-local variables provided `enable-remote-dir-locals'
186 ;; is non-nil. The logic for this is transparently handled by the
187 ;; `python-shell-with-environment' macro.
189 ;; Shell syntax highlighting: when enabled current input in shell is
190 ;; highlighted. The variable `python-shell-font-lock-enable' controls
191 ;; activation of this feature globally when shells are started.
192 ;; Activation/deactivation can be also controlled on the fly via the
193 ;; `python-shell-font-lock-toggle' command.
195 ;; Pdb tracking: when you execute a block of code that contains some
196 ;; call to pdb (or ipdb) it will prompt the block of code and will
197 ;; follow the execution of pdb marking the current line with an arrow.
199 ;; Symbol completion: you can complete the symbol at point. It uses
200 ;; the shell completion in background so you should run
201 ;; `python-shell-send-buffer' from time to time to get better results.
203 ;; Skeletons: skeletons are provided for simple inserting of things like class,
204 ;; def, for, import, if, try, and while. These skeletons are
205 ;; integrated with abbrev. If you have `abbrev-mode' activated and
206 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
207 ;; the name of any of those defined and hit SPC, they will be
208 ;; automatically expanded. As an alternative you can use the defined
209 ;; skeleton commands: `python-skeleton-<foo>'.
211 ;; FFAP: You can find the filename for a given module when using ffap
212 ;; out of the box. This feature needs an inferior python shell
215 ;; Code check: Check the current file for errors with `python-check'
216 ;; using the program defined in `python-check-command'.
218 ;; Eldoc: returns documentation for object at point by using the
219 ;; inferior python subprocess to inspect its documentation. As you
220 ;; might guessed you should run `python-shell-send-buffer' from time
221 ;; to time to get better results too.
223 ;; Imenu: There are two index building functions to be used as
224 ;; `imenu-create-index-function': `python-imenu-create-index' (the
225 ;; default one, builds the alist in form of a tree) and
226 ;; `python-imenu-create-flat-index'. See also
227 ;; `python-imenu-format-item-label-function',
228 ;; `python-imenu-format-parent-item-label-function',
229 ;; `python-imenu-format-parent-item-jump-label-function' variables for
230 ;; changing the way labels are formatted in the tree version.
232 ;; If you used python-mode.el you may miss auto-indentation when
233 ;; inserting newlines. To achieve the same behavior you have two
236 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
237 ;; default) and use RET. If this mode is disabled use
238 ;; `newline-and-indent', bound to C-j.
240 ;; 2) Add the following hook in your .emacs:
242 ;; (add-hook 'python-mode-hook
244 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
246 ;; I'd recommend the first one since you'll get the same behavior for
247 ;; all modes out-of-the-box.
251 ;; Add this to your .emacs:
253 ;; (add-to-list 'load-path "/folder/containing/file")
260 (require 'ansi-color)
266 ;; Avoid compiler warnings
267 (defvar view-return-to-alist)
268 (defvar compilation-error-regexp-alist)
269 (defvar outline-heading-end-regexp)
271 (autoload 'comint-mode "comint")
272 (autoload 'help-function-arglist "help-fns")
275 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
277 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
280 "Python Language's flying circus support for Emacs."
283 :link '(emacs-commentary-link "python"))
289 (unless (fboundp 'prog-widen)
293 (unless (fboundp 'prog-first-column)
294 (defun prog-first-column ()
300 (defvar python-mode-map
301 (let ((map (make-sparse-keymap)))
303 (define-key map [remap backward-sentence] 'python-nav-backward-block)
304 (define-key map [remap forward-sentence] 'python-nav-forward-block)
305 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
306 (define-key map [remap mark-defun] 'python-mark-defun)
307 (define-key map "\C-c\C-j" 'imenu)
309 (define-key map "\177" 'python-indent-dedent-line-backspace)
310 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
311 (define-key map "\C-c<" 'python-indent-shift-left)
312 (define-key map "\C-c>" 'python-indent-shift-right)
314 (define-key map "\C-c\C-tc" 'python-skeleton-class)
315 (define-key map "\C-c\C-td" 'python-skeleton-def)
316 (define-key map "\C-c\C-tf" 'python-skeleton-for)
317 (define-key map "\C-c\C-ti" 'python-skeleton-if)
318 (define-key map "\C-c\C-tm" 'python-skeleton-import)
319 (define-key map "\C-c\C-tt" 'python-skeleton-try)
320 (define-key map "\C-c\C-tw" 'python-skeleton-while)
322 (define-key map "\C-c\C-p" 'run-python)
323 (define-key map "\C-c\C-s" 'python-shell-send-string)
324 (define-key map "\C-c\C-r" 'python-shell-send-region)
325 (define-key map "\C-\M-x" 'python-shell-send-defun)
326 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
327 (define-key map "\C-c\C-l" 'python-shell-send-file)
328 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
329 ;; Some util commands
330 (define-key map "\C-c\C-v" 'python-check)
331 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
333 (substitute-key-definition 'complete-symbol 'completion-at-point
335 (easy-menu-define python-menu map "Python Mode menu"
337 :help "Python-specific Features"
338 ["Shift region left" python-indent-shift-left :active mark-active
339 :help "Shift region left by a single indentation step"]
340 ["Shift region right" python-indent-shift-right :active mark-active
341 :help "Shift region right by a single indentation step"]
343 ["Start of def/class" beginning-of-defun
344 :help "Go to start of outermost definition around point"]
345 ["End of def/class" end-of-defun
346 :help "Go to end of definition around point"]
347 ["Mark def/class" mark-defun
348 :help "Mark outermost definition around point"]
349 ["Jump to def/class" imenu
350 :help "Jump to a class or function definition"]
354 ["Start interpreter" run-python
355 :help "Run inferior Python process in a separate buffer"]
356 ["Switch to shell" python-shell-switch-to-shell
357 :help "Switch to running inferior Python process"]
358 ["Eval string" python-shell-send-string
359 :help "Eval string in inferior Python session"]
360 ["Eval buffer" python-shell-send-buffer
361 :help "Eval buffer in inferior Python session"]
362 ["Eval region" python-shell-send-region
363 :help "Eval region in inferior Python session"]
364 ["Eval defun" python-shell-send-defun
365 :help "Eval defun in inferior Python session"]
366 ["Eval file" python-shell-send-file
367 :help "Eval file in inferior Python session"]
368 ["Debugger" pdb :help "Run pdb under GUD"]
370 ["Check file" python-check
371 :help "Check file for errors"]
372 ["Help on symbol" python-eldoc-at-point
373 :help "Get help on symbol at point"]
374 ["Complete symbol" completion-at-point
375 :help "Complete symbol before point"]))
377 "Keymap for `python-mode'.")
380 ;;; Python specialized rx
383 (defconst python-rx-constituents
384 `((block-start . ,(rx symbol-start
385 (or "def" "class" "if" "elif" "else" "try"
386 "except" "finally" "for" "while" "with")
388 (dedenter . ,(rx symbol-start
389 (or "elif" "else" "except" "finally")
391 (block-ender . ,(rx symbol-start
393 "break" "continue" "pass" "raise" "return")
395 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
397 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
398 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
399 (+ space) "==" (+ space)
400 (any ?' ?\") "__main__" (any ?' ?\")
402 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
403 (open-paren . ,(rx (or "{" "[" "(")))
404 (close-paren . ,(rx (or "}" "]" ")")))
405 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
406 ;; FIXME: rx should support (not simple-operator).
407 (not-simple-operator . ,(rx
409 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
410 ;; FIXME: Use regexp-opt.
411 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
412 "=" "%" "**" "//" "<<" ">>" "<=" "!="
413 "==" ">=" "is" "not")))
414 ;; FIXME: Use regexp-opt.
415 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
416 ">>=" "<<=" "&=" "^=" "|=")))
417 (string-delimiter . ,(rx (and
418 ;; Match even number of backslashes.
419 (or (not (any ?\\ ?\' ?\")) point
420 ;; Quotes might be preceded by a escaped quote.
421 (and (or (not (any ?\\)) point) ?\\
422 (* ?\\ ?\\) (any ?\' ?\")))
424 ;; Match single or triple quotes of any kind.
425 (group (or "\"" "\"\"\"" "'" "'''")))))
426 (coding-cookie . ,(rx line-start ?# (* space)
428 ;; # coding=<encoding name>
429 (: "coding" (or ?: ?=) (* space) (group-n 1 (+ (or word ?-))))
430 ;; # -*- coding: <encoding name> -*-
431 (: "-*-" (* space) "coding:" (* space)
432 (group-n 1 (+ (or word ?-))) (* space) "-*-")
433 ;; # vim: set fileencoding=<encoding name> :
434 (: "vim:" (* space) "set" (+ space)
435 "fileencoding" (* space) ?= (* space)
436 (group-n 1 (+ (or word ?-))) (* space) ":")))))
437 "Additional Python specific sexps for `python-rx'")
439 (defmacro python-rx (&rest regexps)
440 "Python mode specialized rx macro.
441 This variant of `rx' supports common Python named REGEXPS."
442 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
443 (cond ((null regexps)
446 (rx-to-string `(and ,@regexps) t))
448 (rx-to-string (car regexps) t))))))
451 ;;; Font-lock and syntax
454 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
457 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
458 (and (nth 4 ppss) (nth 8 ppss))))
460 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
461 (and (nth 3 ppss) (nth 8 ppss))))
463 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
466 (defun python-syntax-context (type &optional syntax-ppss)
467 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
468 TYPE can be `comment', `string' or `paren'. It returns the start
469 character address of the specified TYPE."
470 (declare (compiler-macro python-syntax--context-compiler-macro))
471 (let ((ppss (or syntax-ppss (syntax-ppss))))
473 (`comment (and (nth 4 ppss) (nth 8 ppss)))
474 (`string (and (nth 3 ppss) (nth 8 ppss)))
475 (`paren (nth 1 ppss))
478 (defun python-syntax-context-type (&optional syntax-ppss)
479 "Return the context type using SYNTAX-PPSS.
480 The type returned can be `comment', `string' or `paren'."
481 (let ((ppss (or syntax-ppss (syntax-ppss))))
483 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
484 ((nth 1 ppss) 'paren))))
486 (defsubst python-syntax-comment-or-string-p (&optional ppss)
487 "Return non-nil if PPSS is inside 'comment or 'string."
488 (nth 8 (or ppss (syntax-ppss))))
490 (defsubst python-syntax-closing-paren-p ()
491 "Return non-nil if char after point is a closing paren."
492 (= (syntax-class (syntax-after (point)))
493 (syntax-class (string-to-syntax ")"))))
495 (define-obsolete-function-alias
496 'python-info-ppss-context #'python-syntax-context "24.3")
498 (define-obsolete-function-alias
499 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
501 (define-obsolete-function-alias
502 'python-info-ppss-comment-or-string-p
503 #'python-syntax-comment-or-string-p "24.3")
505 (defun python-font-lock-syntactic-face-function (state)
506 "Return syntactic face given STATE."
508 (if (python-info-docstring-p state)
510 font-lock-string-face)
511 font-lock-comment-face))
513 (defvar python-font-lock-keywords
517 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
518 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
519 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
524 ;; False, None, and True are listed as keywords on the Python 3
525 ;; documentation, but since they also qualify as constants they are
526 ;; fontified like that in order to keep font-lock consistent between
533 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
534 (1 font-lock-function-name-face))
536 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
537 (1 font-lock-type-face))
541 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
542 ;; copyright, license, credits, quit and exit are added by the site
543 ;; module and they are not intended to be used in programs
544 "copyright" "credits" "exit" "license" "quit")
545 symbol-end) . font-lock-constant-face)
547 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
548 (0+ "." (1+ (or word ?_)))))
549 (1 font-lock-type-face))
550 ;; Builtin Exceptions
553 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
554 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
555 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
556 "ImportError" "ImportWarning" "IndexError" "KeyError"
557 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
558 "NotImplementedError" "OSError" "OverflowError"
559 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
560 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
561 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
562 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
563 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
564 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
568 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
570 symbol-end) . font-lock-type-face)
574 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
575 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
576 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
577 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
578 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
579 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
580 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
581 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
584 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
585 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
588 "ascii" "bytearray" "bytes" "exec"
590 "__all__" "__doc__" "__name__" "__package__")
591 symbol-end) . font-lock-builtin-face)
593 ;; support for a = b = c = 5
595 (let ((re (python-rx (group (+ (any word ?. ?_)))
596 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
597 assignment-operator))
599 (while (and (setq res (re-search-forward re limit t))
600 (or (python-syntax-context 'paren)
601 (equal (char-after (point)) ?=))))
603 (1 font-lock-variable-name-face nil nil))
604 ;; support for a, b, c = (1, 2, 3)
606 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
607 (* ?, (* space) (+ (any word ?. ?_)) (* space))
608 ?, (* space) (+ (any word ?. ?_)) (* space)
609 assignment-operator))
611 (while (and (setq res (re-search-forward re limit t))
612 (goto-char (match-end 1))
613 (python-syntax-context 'paren)))
615 (1 font-lock-variable-name-face nil nil))))
617 (defconst python-syntax-propertize-function
618 (syntax-propertize-rules
619 ((python-rx string-delimiter)
620 (0 (ignore (python-syntax-stringify))))))
622 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
623 "Count number of quotes around point (max is 3).
624 QUOTE-CHAR is the quote char to count. Optional argument POINT is
625 the point where scan starts (defaults to current point), and LIMIT
626 is used to limit the scan."
629 (or (not limit) (< (+ point i) limit))
630 (eq (char-after (+ point i)) quote-char))
634 (defun python-syntax-stringify ()
635 "Put `syntax-table' property correctly on single/triple quotes."
636 (let* ((num-quotes (length (match-string-no-properties 1)))
638 (backward-char num-quotes)
640 (forward-char num-quotes)))
641 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
642 (quote-starting-pos (- (point) num-quotes))
643 (quote-ending-pos (point))
646 (python-syntax-count-quotes
647 (char-before) string-start quote-starting-pos))))
648 (cond ((and string-start (= num-closing-quotes 0))
649 ;; This set of quotes doesn't match the string starting
653 ;; This set of quotes delimit the start of a string.
654 (put-text-property quote-starting-pos (1+ quote-starting-pos)
655 'syntax-table (string-to-syntax "|")))
656 ((= num-quotes num-closing-quotes)
657 ;; This set of quotes delimit the end of a string.
658 (put-text-property (1- quote-ending-pos) quote-ending-pos
659 'syntax-table (string-to-syntax "|")))
660 ((> num-quotes num-closing-quotes)
661 ;; This may only happen whenever a triple quote is closing
662 ;; a single quoted string. Add string delimiter syntax to
664 (put-text-property quote-starting-pos quote-ending-pos
665 'syntax-table (string-to-syntax "|"))))))
667 (defvar python-mode-syntax-table
668 (let ((table (make-syntax-table)))
669 ;; Give punctuation syntax to ASCII that normally has symbol
670 ;; syntax or has word syntax and isn't a letter.
671 (let ((symbol (string-to-syntax "_"))
672 (sst (standard-syntax-table)))
675 (if (equal symbol (aref sst i))
676 (modify-syntax-entry i "." table)))))
677 (modify-syntax-entry ?$ "." table)
678 (modify-syntax-entry ?% "." table)
680 (modify-syntax-entry ?# "<" table)
681 (modify-syntax-entry ?\n ">" table)
682 (modify-syntax-entry ?' "\"" table)
683 (modify-syntax-entry ?` "$" table)
685 "Syntax table for Python files.")
687 (defvar python-dotty-syntax-table
688 (let ((table (make-syntax-table python-mode-syntax-table)))
689 (modify-syntax-entry ?. "w" table)
690 (modify-syntax-entry ?_ "w" table)
692 "Dotty syntax table for Python files.
693 It makes underscores and dots word constituent chars.")
698 (defcustom python-indent-offset 4
699 "Default indentation offset for Python."
704 (defcustom python-indent-guess-indent-offset t
705 "Non-nil tells Python mode to guess `python-indent-offset' value."
710 (defcustom python-indent-guess-indent-offset-verbose t
711 "Non-nil means to emit a warning when indentation guessing fails."
716 (defcustom python-indent-trigger-commands
717 '(indent-for-tab-command yas-expand yas/expand)
718 "Commands that might trigger a `python-indent-line' call."
719 :type '(repeat symbol)
722 (define-obsolete-variable-alias
723 'python-indent 'python-indent-offset "24.3")
725 (define-obsolete-variable-alias
726 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
728 (defvar python-indent-current-level 0
729 "Deprecated var available for compatibility.")
731 (defvar python-indent-levels '(0)
732 "Deprecated var available for compatibility.")
734 (make-obsolete-variable
735 'python-indent-current-level
736 "The indentation API changed to avoid global state.
737 The function `python-indent-calculate-levels' does not use it
738 anymore. If you were defadvising it and or depended on this
739 variable for indentation customizations, refactor your code to
740 work on `python-indent-calculate-indentation' instead."
743 (make-obsolete-variable
744 'python-indent-levels
745 "The indentation API changed to avoid global state.
746 The function `python-indent-calculate-levels' does not use it
747 anymore. If you were defadvising it and or depended on this
748 variable for indentation customizations, refactor your code to
749 work on `python-indent-calculate-indentation' instead."
752 (defun python-indent-guess-indent-offset ()
753 "Guess and set `python-indent-offset' for the current buffer."
758 (goto-char (point-min))
760 (while (and (not block-end)
762 (python-rx line-start block-start) nil t))
764 (not (python-syntax-context-type))
766 (goto-char (line-end-position))
767 (python-util-forward-comment -1)
768 (if (equal (char-before) ?:)
771 (when (python-info-block-continuation-line-p)
772 (while (and (python-info-continuation-line-p)
775 (python-util-forward-comment -1)
776 (when (equal (char-before) ?:)
778 (setq block-end (point-marker))))
781 (goto-char block-end)
782 (python-util-forward-comment)
783 (current-indentation))))
784 (if (and indentation (not (zerop indentation)))
785 (set (make-local-variable 'python-indent-offset) indentation)
786 (when python-indent-guess-indent-offset-verbose
787 (message "Can't guess python-indent-offset, using defaults: %s"
788 python-indent-offset))))))))
790 (defun python-indent-context ()
791 "Get information about the current indentation context.
792 Context is returned in a cons with the form (STATUS . START).
794 STATUS can be one of the following:
800 - Point is after a comment line.
801 - START is the position of the \"#\" character.
803 - Point is inside string.
804 - START is the position of the first quote that starts it.
806 - No possible indentation case matches.
807 - START is always zero.
810 - Fallback case when point is inside paren.
811 - START is the first non space char position *after* the open paren.
812 :inside-paren-at-closing-nested-paren
813 - Point is on a line that contains a nested paren closer.
814 - START is the position of the open paren it closes.
815 :inside-paren-at-closing-paren
816 - Point is on a line that contains a paren closer.
817 - START is the position of the open paren.
818 :inside-paren-newline-start
819 - Point is inside a paren with items starting in their own line.
820 - START is the position of the open paren.
821 :inside-paren-newline-start-from-block
822 - Point is inside a paren with items starting in their own line
824 - START is the position of the open paren.
827 - Fallback case when point is after backslash.
828 - START is the char after the position of the backslash.
829 :after-backslash-assignment-continuation
830 - Point is after a backslashed assignment.
831 - START is the char after the position of the backslash.
832 :after-backslash-block-continuation
833 - Point is after a backslashed block continuation.
834 - START is the char after the position of the backslash.
835 :after-backslash-dotted-continuation
836 - Point is after a backslashed dotted continuation. Previous
837 line must contain a dot to align with.
838 - START is the char after the position of the backslash.
839 :after-backslash-first-line
840 - First line following a backslashed continuation.
841 - START is the char after the position of the backslash.
844 - Point is after a line containing a block ender.
845 - START is the position where the ender starts.
847 - Point is after a line starting a block.
848 - START is the position where the block starts.
850 - Point is after a simple line.
851 - START is the position where the previous line starts.
852 :at-dedenter-block-start
853 - Point is on a line starting a dedenter block.
854 - START is the position where the dedenter block starts."
857 (let ((ppss (save-excursion
861 ;; Beginning of buffer.
862 ((= (line-number-at-pos) 1)
865 ((let ((start (python-syntax-context 'string ppss)))
867 (cons (if (python-info-docstring-p)
869 :inside-string) start))))
871 ((let* ((start (python-syntax-context 'paren ppss))
878 (= (line-number-at-pos)
880 (python-util-forward-comment)
881 (line-number-at-pos))))))))
884 ;; Current line only holds the closing paren.
886 (skip-syntax-forward " ")
887 (when (and (python-syntax-closing-paren-p)
890 (not (python-syntax-context 'paren))))
891 (cons :inside-paren-at-closing-paren start))))
892 ;; Current line only holds a closing paren for nested.
894 (back-to-indentation)
895 (python-syntax-closing-paren-p))
896 (cons :inside-paren-at-closing-nested-paren start))
897 ;; This line starts from a opening block in its own line.
903 (back-to-indentation)
904 (looking-at (python-rx block-start))))
906 :inside-paren-newline-start-from-block start))))
908 (cons :inside-paren-newline-start start))
910 (t (cons :inside-paren
912 (goto-char (1+ start))
913 (skip-syntax-forward "(" 1)
914 (skip-syntax-forward " ")
917 ((let ((start (when (not (python-syntax-comment-or-string-p ppss))
918 (python-info-line-ends-backslash-p
919 (1- (line-number-at-pos))))))
922 ;; Continuation of dotted expression.
924 (back-to-indentation)
925 (when (eq (char-after) ?\.)
926 ;; Move point back until it's not inside a paren.
930 (python-syntax-context 'paren))))
931 (goto-char (line-end-position))
932 (while (and (search-backward
933 "." (line-beginning-position) t)
934 (python-syntax-context-type)))
935 ;; Ensure previous statement has dot to align with.
936 (when (and (eq (char-after) ?\.)
937 (not (python-syntax-context-type)))
938 (cons :after-backslash-dotted-continuation (point))))))
939 ;; Continuation of block definition.
940 ((let ((block-continuation-start
941 (python-info-block-continuation-line-p)))
942 (when block-continuation-start
944 (goto-char block-continuation-start)
946 (python-rx block-start (* space))
947 (line-end-position) t)
948 (cons :after-backslash-block-continuation (point))))))
949 ;; Continuation of assignment.
950 ((let ((assignment-continuation-start
951 (python-info-assignment-continuation-line-p)))
952 (when assignment-continuation-start
954 (goto-char assignment-continuation-start)
955 (cons :after-backslash-assignment-continuation (point))))))
956 ;; First line after backslash continuation start.
959 (when (or (= (line-number-at-pos) 1)
960 (not (python-info-beginning-of-backslash
961 (1- (line-number-at-pos)))))
962 (cons :after-backslash-first-line start))))
964 (t (cons :after-backslash start))))))
965 ;; After beginning of block.
966 ((let ((start (save-excursion
967 (back-to-indentation)
968 (python-util-forward-comment -1)
969 (when (equal (char-before) ?:)
970 (python-nav-beginning-of-block)))))
972 (cons :after-block-start start))))
973 ;; At dedenter statement.
974 ((let ((start (python-info-dedenter-statement-p)))
976 (cons :at-dedenter-block-start start))))
977 ;; After normal line, comment or ender (default case).
979 (back-to-indentation)
980 (skip-chars-backward " \t\n")
983 (python-nav-beginning-of-statement)
985 (cond ((python-info-current-line-comment-p)
988 (goto-char (line-end-position))
989 (python-util-forward-comment -1)
990 (python-nav-beginning-of-statement)
991 (looking-at (python-rx block-ender)))
996 (defun python-indent--calculate-indentation ()
997 "Internal implementation of `python-indent-calculate-indentation'.
998 May return an integer for the maximum possible indentation at
999 current context or a list of integers. The latter case is only
1000 happening for :at-dedenter-block-start context since the
1001 possibilities can be narrowed to specific indentation points."
1005 (pcase (python-indent-context)
1006 (`(:no-indent . ,_) (prog-first-column)) ; usually 0
1011 :inside-paren-at-closing-paren
1012 :inside-paren-at-closing-nested-paren) . ,start)
1013 ;; Copy previous indentation.
1015 (current-indentation))
1016 (`(:inside-docstring . ,start)
1017 (let* ((line-indentation (current-indentation))
1020 (current-indentation))))
1021 (max line-indentation base-indent)))
1022 (`(,(or :after-block-start
1023 :after-backslash-first-line
1024 :inside-paren-newline-start) . ,start)
1025 ;; Add one indentation level.
1027 (+ (current-indentation) python-indent-offset))
1028 (`(,(or :inside-paren
1029 :after-backslash-block-continuation
1030 :after-backslash-assignment-continuation
1031 :after-backslash-dotted-continuation) . ,start)
1032 ;; Use the column given by the context.
1035 (`(:after-block-end . ,start)
1036 ;; Subtract one indentation level.
1038 (- (current-indentation) python-indent-offset))
1039 (`(:at-dedenter-block-start . ,_)
1040 ;; List all possible indentation levels from opening blocks.
1041 (let ((opening-block-start-points
1042 (python-info-dedenter-opening-block-positions)))
1043 (if (not opening-block-start-points)
1044 (prog-first-column) ; if not found default to first column
1045 (mapcar (lambda (pos)
1048 (current-indentation)))
1049 opening-block-start-points))))
1050 (`(,(or :inside-paren-newline-start-from-block) . ,start)
1051 ;; Add two indentation levels to make the suite stand out.
1053 (+ (current-indentation) (* python-indent-offset 2)))))))
1055 (defun python-indent--calculate-levels (indentation)
1056 "Calculate levels list given INDENTATION.
1057 Argument INDENTATION can either be an integer or a list of
1058 integers. Levels are returned in ascending order, and in the
1059 case INDENTATION is a list, this order is enforced."
1060 (if (listp indentation)
1061 (sort (copy-sequence indentation) #'<)
1062 (nconc (number-sequence (prog-first-column) (1- indentation)
1063 python-indent-offset)
1064 (list indentation))))
1066 (defun python-indent--previous-level (levels indentation)
1067 "Return previous level from LEVELS relative to INDENTATION."
1068 (let* ((levels (sort (copy-sequence levels) #'>))
1069 (default (car levels)))
1071 (dolist (level levels)
1072 (when (funcall #'< level indentation)
1073 (throw 'return level)))
1076 (defun python-indent-calculate-indentation (&optional previous)
1077 "Calculate indentation.
1078 Get indentation of PREVIOUS level when argument is non-nil.
1079 Return the max level of the cycle when indentation reaches the
1081 (let* ((indentation (python-indent--calculate-indentation))
1082 (levels (python-indent--calculate-levels indentation)))
1084 (python-indent--previous-level levels (current-indentation))
1086 (apply #'max levels)
1087 (prog-first-column)))))
1089 (defun python-indent-line (&optional previous)
1090 "Internal implementation of `python-indent-line-function'.
1091 Use the PREVIOUS level when argument is non-nil, otherwise indent
1092 to the maximum available level. When indentation is the minimum
1093 possible and PREVIOUS is non-nil, cycle back to the maximum
1095 (let ((follow-indentation-p
1096 ;; Check if point is within indentation.
1097 (and (<= (line-beginning-position) (point))
1098 (>= (+ (line-beginning-position)
1099 (current-indentation))
1103 (python-indent-calculate-indentation previous))
1104 (python-info-dedenter-opening-block-message))
1105 (when follow-indentation-p
1106 (back-to-indentation))))
1108 (defun python-indent-calculate-levels ()
1109 "Return possible indentation levels."
1110 (python-indent--calculate-levels
1111 (python-indent--calculate-indentation)))
1113 (defun python-indent-line-function ()
1114 "`indent-line-function' for Python mode.
1115 When the variable `last-command' is equal to one of the symbols
1116 inside `python-indent-trigger-commands' it cycles possible
1117 indentation levels from right to left."
1119 (and (memq this-command python-indent-trigger-commands)
1120 (eq last-command this-command))))
1122 (defun python-indent-dedent-line ()
1123 "De-indent current line."
1125 (when (and (not (bolp))
1126 (not (python-syntax-comment-or-string-p))
1127 (= (current-indentation) (current-column)))
1128 (python-indent-line t)
1131 (defun python-indent-dedent-line-backspace (arg)
1132 "De-indent current line.
1133 Argument ARG is passed to `backward-delete-char-untabify' when
1134 point is not in between the indentation."
1136 (unless (python-indent-dedent-line)
1137 (backward-delete-char-untabify arg)))
1139 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1141 (defun python-indent-region (start end)
1142 "Indent a Python region automagically.
1144 Called from a program, START and END specify the region to indent."
1145 (let ((deactivate-mark nil))
1148 (setq end (point-marker))
1150 (or (bolp) (forward-line 1))
1151 (while (< (point) end)
1152 (or (and (bolp) (eolp))
1154 ;; Skip if previous line is empty or a comment.
1156 (let ((line-is-comment-p
1157 (python-info-current-line-comment-p)))
1160 (or (and (python-info-current-line-comment-p)
1161 ;; Unless this line is a comment too.
1162 (not line-is-comment-p))
1163 (python-info-current-line-empty-p)))))
1164 ;; Don't mess with strings, unless it's the
1165 ;; enclosing set of quotes or a docstring.
1166 (or (not (python-syntax-context 'string))
1170 (current-indentation)
1171 (python-syntax-count-quotes (char-after) (point))))
1172 (string-to-syntax "|"))
1173 (python-info-docstring-p))
1174 ;; Skip if current line is a block start, a
1175 ;; dedenter or block ender.
1177 (back-to-indentation)
1180 (or block-start dedenter block-ender))))))
1181 (python-indent-line)))
1183 (move-marker end nil))))
1185 (defun python-indent-shift-left (start end &optional count)
1186 "Shift lines contained in region START END by COUNT columns to the left.
1187 COUNT defaults to `python-indent-offset'. If region isn't
1188 active, the current line is shifted. The shifted region includes
1189 the lines in which START and END lie. An error is signaled if
1190 any lines in the region are indented less than COUNT columns."
1193 (list (region-beginning) (region-end) current-prefix-arg)
1194 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1196 (setq count (prefix-numeric-value count))
1197 (setq count python-indent-offset))
1199 (let ((deactivate-mark nil))
1202 (while (< (point) end)
1203 (if (and (< (current-indentation) count)
1204 (not (looking-at "[ \t]*$")))
1205 (user-error "Can't shift all lines enough"))
1207 (indent-rigidly start end (- count))))))
1209 (defun python-indent-shift-right (start end &optional count)
1210 "Shift lines contained in region START END by COUNT columns to the right.
1211 COUNT defaults to `python-indent-offset'. If region isn't
1212 active, the current line is shifted. The shifted region includes
1213 the lines in which START and END lie."
1216 (list (region-beginning) (region-end) current-prefix-arg)
1217 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1218 (let ((deactivate-mark nil))
1219 (setq count (if count (prefix-numeric-value count)
1220 python-indent-offset))
1221 (indent-rigidly start end count)))
1223 (defun python-indent-post-self-insert-function ()
1224 "Adjust indentation after insertion of some characters.
1225 This function is intended to be added to `post-self-insert-hook.'
1226 If a line renders a paren alone, after adding a char before it,
1227 the line will be re-indented automatically if needed."
1228 (when (and electric-indent-mode
1229 (eq (char-before) last-command-event))
1231 ;; Electric indent inside parens
1234 (let ((paren-start (python-syntax-context 'paren)))
1235 ;; Check that point is inside parens.
1238 ;; Filter the case where input is happening in the same
1239 ;; line where the open paren is.
1240 (= (line-number-at-pos)
1241 (line-number-at-pos paren-start)))))
1242 ;; When content has been added before the closing paren or a
1243 ;; comma has been inserted, it's ok to do the trick.
1245 (memq (char-after) '(?\) ?\] ?\}))
1246 (eq (char-before) ?,)))
1248 (goto-char (line-beginning-position))
1249 (let ((indentation (python-indent-calculate-indentation)))
1250 (when (and (numberp indentation) (< (current-indentation) indentation))
1251 (indent-line-to indentation)))))
1253 ((and (eq ?: last-command-event)
1254 (memq ?: electric-indent-chars)
1255 (not current-prefix-arg)
1256 ;; Trigger electric colon only at end of line
1258 ;; Avoid re-indenting on extra colon
1259 (not (equal ?: (char-before (1- (point)))))
1260 (not (python-syntax-comment-or-string-p)))
1261 ;; Just re-indent dedenters
1262 (let ((dedenter-pos (python-info-dedenter-statement-p))
1263 (current-pos (point)))
1266 (goto-char dedenter-pos)
1267 (python-indent-line)
1268 (unless (= (line-number-at-pos dedenter-pos)
1269 (line-number-at-pos current-pos))
1270 ;; Reindent region if this is a multiline statement
1271 (python-indent-region dedenter-pos current-pos)))))))))
1276 (defun python-mark-defun (&optional allow-extend)
1277 "Put mark at end of this defun, point at beginning.
1278 The defun marked is the one that contains point or follows point.
1280 Interactively (or with ALLOW-EXTEND non-nil), if this command is
1281 repeated or (in Transient Mark mode) if the mark is active, it
1282 marks the next defun after the ones already marked."
1284 (when (python-info-looking-at-beginning-of-defun)
1286 (mark-defun allow-extend))
1291 (defvar python-nav-beginning-of-defun-regexp
1292 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1293 "Regexp matching class or function definition.
1294 The name of the defun should be grouped so it can be retrieved
1295 via `match-string'.")
1297 (defun python-nav--beginning-of-defun (&optional arg)
1298 "Internal implementation of `python-nav-beginning-of-defun'.
1299 With positive ARG search backwards, else search forwards."
1300 (when (or (null arg) (= arg 0)) (setq arg 1))
1301 (let* ((re-search-fn (if (> arg 0)
1302 #'re-search-backward
1303 #'re-search-forward))
1304 (line-beg-pos (line-beginning-position))
1305 (line-content-start (+ line-beg-pos (current-indentation)))
1306 (pos (point-marker))
1311 (not (python-info-looking-at-beginning-of-defun))
1312 (python-nav-backward-block)))
1313 (or (and (python-info-looking-at-beginning-of-defun)
1314 (+ (current-indentation) python-indent-offset))
1318 (when (and (< arg 0)
1319 (python-info-looking-at-beginning-of-defun))
1321 (while (and (funcall re-search-fn
1322 python-nav-beginning-of-defun-regexp nil t)
1323 (or (python-syntax-context-type)
1324 ;; Handle nested defuns when moving
1325 ;; backwards by checking indentation.
1327 (not (= (current-indentation) 0))
1328 (>= (current-indentation) beg-indentation)))))
1329 (and (python-info-looking-at-beginning-of-defun)
1330 (or (not (= (line-number-at-pos pos)
1331 (line-number-at-pos)))
1332 (and (>= (point) line-beg-pos)
1333 (<= (point) line-content-start)
1334 (> pos line-content-start)))))))
1336 (or (beginning-of-line 1) t)
1337 (and (goto-char pos) nil))))
1339 (defun python-nav-beginning-of-defun (&optional arg)
1340 "Move point to `beginning-of-defun'.
1341 With positive ARG search backwards else search forward.
1342 ARG nil or 0 defaults to 1. When searching backwards,
1343 nested defuns are handled with care depending on current
1344 point position. Return non-nil if point is moved to
1345 `beginning-of-defun'."
1346 (when (or (null arg) (= arg 0)) (setq arg 1))
1348 (while (and (not (= arg 0))
1349 (let ((keep-searching-p
1350 (python-nav--beginning-of-defun arg)))
1351 (when (and keep-searching-p (null found))
1354 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1357 (defun python-nav-end-of-defun ()
1358 "Move point to the end of def or class.
1359 Returns nil if point is not in a def or class."
1361 (let ((beg-defun-indent)
1363 (when (or (python-info-looking-at-beginning-of-defun)
1364 (python-nav-beginning-of-defun 1)
1365 (python-nav-beginning-of-defun -1))
1366 (setq beg-defun-indent (current-indentation))
1368 (python-nav-end-of-statement)
1369 (python-util-forward-comment 1)
1370 (and (> (current-indentation) beg-defun-indent)
1372 (python-util-forward-comment -1)
1374 ;; Ensure point moves forward.
1375 (and (> beg-pos (point)) (goto-char beg-pos)))))
1377 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1378 "Move point using FN avoiding places with specific context.
1379 FN must take no arguments. POSCOMPFN is a two arguments function
1380 used to compare current and previous point after it is moved
1381 using FN, this is normally a less-than or greater-than
1382 comparison. Optional argument CONTEXTFN defaults to
1383 `python-syntax-context-type' and is used for checking current
1384 point context, it must return a non-nil value if this point must
1386 (let ((contextfn (or contextfn 'python-syntax-context-type))
1387 (start-pos (point-marker))
1392 (and (funcall fn) (point-marker)))
1393 (context (funcall contextfn)))
1394 (cond ((and (not context) newpos
1395 (or (and (not prev-pos) newpos)
1396 (and prev-pos newpos
1397 (funcall poscompfn newpos prev-pos))))
1398 (throw 'found (point-marker)))
1399 ((and newpos context)
1400 (setq prev-pos (point)))
1401 (t (when (not newpos) (goto-char start-pos))
1402 (throw 'found nil))))))))
1404 (defun python-nav--forward-defun (arg)
1405 "Internal implementation of python-nav-{backward,forward}-defun.
1406 Uses ARG to define which function to call, and how many times
1409 (while (and (> arg 0)
1411 (python-nav--syntactically
1414 python-nav-beginning-of-defun-regexp nil t))
1416 (setq arg (1- arg)))
1417 (while (and (< arg 0)
1419 (python-nav--syntactically
1422 python-nav-beginning-of-defun-regexp nil t))
1424 (setq arg (1+ arg)))
1427 (defun python-nav-backward-defun (&optional arg)
1428 "Navigate to closer defun backward ARG times.
1429 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1430 nested definitions."
1432 (python-nav--forward-defun (- (or arg 1))))
1434 (defun python-nav-forward-defun (&optional arg)
1435 "Navigate to closer defun forward ARG times.
1436 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1437 nested definitions."
1439 (python-nav--forward-defun (or arg 1)))
1441 (defun python-nav-beginning-of-statement ()
1442 "Move to start of current statement."
1444 (back-to-indentation)
1445 (let* ((ppss (syntax-ppss))
1448 (python-syntax-context 'paren ppss)
1449 (python-syntax-context 'string ppss))))
1452 (goto-char context-point)
1453 (python-nav-beginning-of-statement))
1456 (python-info-line-ends-backslash-p))
1458 (python-nav-beginning-of-statement))))
1461 (defun python-nav-end-of-statement (&optional noend)
1462 "Move to end of current statement.
1463 Optional argument NOEND is internal and makes the logic to not
1464 jump to the end of line when moving forward searching for the end
1467 (let (string-start bs-pos)
1468 (while (and (or noend (goto-char (line-end-position)))
1470 (cond ((setq string-start (python-syntax-context 'string))
1471 (goto-char string-start)
1472 (if (python-syntax-context 'paren)
1473 ;; Ended up inside a paren, roll again.
1474 (python-nav-end-of-statement t)
1475 ;; This is not inside a paren, move to the
1476 ;; end of this string.
1477 (goto-char (+ (point)
1478 (python-syntax-count-quotes
1479 (char-after (point)) (point))))
1480 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1481 (goto-char (point-max)))))
1482 ((python-syntax-context 'paren)
1483 ;; The statement won't end before we've escaped
1484 ;; at least one level of parenthesis.
1486 (goto-char (scan-lists (point) 1 -1))
1487 (scan-error (goto-char (nth 3 err)))))
1488 ((setq bs-pos (python-info-line-ends-backslash-p))
1490 (forward-line 1))))))
1493 (defun python-nav-backward-statement (&optional arg)
1494 "Move backward to previous statement.
1495 With ARG, repeat. See `python-nav-forward-statement'."
1497 (or arg (setq arg 1))
1498 (python-nav-forward-statement (- arg)))
1500 (defun python-nav-forward-statement (&optional arg)
1501 "Move forward to next statement.
1502 With ARG, repeat. With negative argument, move ARG times
1503 backward to previous statement."
1505 (or arg (setq arg 1))
1507 (python-nav-end-of-statement)
1508 (python-util-forward-comment)
1509 (python-nav-beginning-of-statement)
1510 (setq arg (1- arg)))
1512 (python-nav-beginning-of-statement)
1513 (python-util-forward-comment -1)
1514 (python-nav-beginning-of-statement)
1515 (setq arg (1+ arg))))
1517 (defun python-nav-beginning-of-block ()
1518 "Move to start of current block."
1520 (let ((starting-pos (point)))
1522 (python-nav-beginning-of-statement)
1523 (looking-at (python-rx block-start)))
1525 ;; Go to first line beginning a statement
1526 (while (and (not (bobp))
1527 (or (and (python-nav-beginning-of-statement) nil)
1528 (python-info-current-line-comment-p)
1529 (python-info-current-line-empty-p)))
1531 (let ((block-matching-indent
1532 (- (current-indentation) python-indent-offset)))
1534 (and (python-nav-backward-block)
1535 (> (current-indentation) block-matching-indent)))
1536 (if (and (looking-at (python-rx block-start))
1537 (= (current-indentation) block-matching-indent))
1539 (and (goto-char starting-pos) nil))))))
1541 (defun python-nav-end-of-block ()
1542 "Move to end of current block."
1544 (when (python-nav-beginning-of-block)
1545 (let ((block-indentation (current-indentation)))
1546 (python-nav-end-of-statement)
1547 (while (and (forward-line 1)
1549 (or (and (> (current-indentation) block-indentation)
1550 (or (python-nav-end-of-statement) t))
1551 (python-info-current-line-comment-p)
1552 (python-info-current-line-empty-p))))
1553 (python-util-forward-comment -1)
1556 (defun python-nav-backward-block (&optional arg)
1557 "Move backward to previous block of code.
1558 With ARG, repeat. See `python-nav-forward-block'."
1560 (or arg (setq arg 1))
1561 (python-nav-forward-block (- arg)))
1563 (defun python-nav-forward-block (&optional arg)
1564 "Move forward to next block of code.
1565 With ARG, repeat. With negative argument, move ARG times
1566 backward to previous block."
1568 (or arg (setq arg 1))
1569 (let ((block-start-regexp
1570 (python-rx line-start (* whitespace) block-start))
1571 (starting-pos (point)))
1573 (python-nav-end-of-statement)
1575 (re-search-forward block-start-regexp nil t)
1576 (python-syntax-context-type)))
1577 (setq arg (1- arg)))
1579 (python-nav-beginning-of-statement)
1581 (re-search-backward block-start-regexp nil t)
1582 (python-syntax-context-type)))
1583 (setq arg (1+ arg)))
1584 (python-nav-beginning-of-statement)
1585 (if (not (looking-at (python-rx block-start)))
1586 (and (goto-char starting-pos) nil)
1587 (and (not (= (point) starting-pos)) (point-marker)))))
1589 (defun python-nav--lisp-forward-sexp (&optional arg)
1590 "Standard version `forward-sexp'.
1591 It ignores completely the value of `forward-sexp-function' by
1592 setting it to nil before calling `forward-sexp'. With positive
1593 ARG move forward only one sexp, else move backwards."
1594 (let ((forward-sexp-function)
1595 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1596 (forward-sexp arg)))
1598 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1599 "Safe version of standard `forward-sexp'.
1600 When at end of sexp (i.e. looking at a opening/closing paren)
1601 skips it instead of throwing an error. With positive ARG move
1602 forward only one sexp, else move backwards."
1603 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1605 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1607 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1609 (python-nav--lisp-forward-sexp arg)
1611 (while (and (funcall search-fn paren-regexp nil t)
1612 (python-syntax-context 'paren)))))))
1614 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p)
1615 "Move to forward sexp.
1616 With positive optional argument DIR direction move forward, else
1617 backwards. When optional argument SAFE is non-nil do not throw
1618 errors when at end of sexp, skip it instead. With optional
1619 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1620 expressions when looking at them in either direction."
1621 (setq dir (or dir 1))
1623 (let* ((forward-p (if (> dir 0)
1624 (and (setq dir 1) t)
1625 (and (setq dir -1) nil)))
1626 (context-type (python-syntax-context-type)))
1628 ((memq context-type '(string comment))
1629 ;; Inside of a string, get out of it.
1630 (let ((forward-sexp-function))
1631 (forward-sexp dir)))
1632 ((and (not skip-parens-p)
1633 (or (eq context-type 'paren)
1635 (eq (syntax-class (syntax-after (point)))
1636 (car (string-to-syntax "(")))
1637 (eq (syntax-class (syntax-after (1- (point))))
1638 (car (string-to-syntax ")"))))))
1639 ;; Inside a paren or looking at it, lisp knows what to do.
1641 (python-nav--lisp-forward-sexp-safe dir)
1642 (python-nav--lisp-forward-sexp dir)))
1644 ;; This part handles the lispy feel of
1645 ;; `python-nav-forward-sexp'. Knowing everything about the
1646 ;; current context and the context of the next sexp tries to
1647 ;; follow the lisp sexp motion commands in a symmetric manner.
1650 ((python-info-beginning-of-block-p) 'block-start)
1651 ((python-info-end-of-block-p) 'block-end)
1652 ((python-info-beginning-of-statement-p) 'statement-start)
1653 ((python-info-end-of-statement-p) 'statement-end)))
1657 (python-nav--lisp-forward-sexp-safe dir)
1658 (python-nav--lisp-forward-sexp dir))
1662 (goto-char next-sexp-pos)
1664 ((python-info-beginning-of-block-p) 'block-start)
1665 ((python-info-end-of-block-p) 'block-end)
1666 ((python-info-beginning-of-statement-p) 'statement-start)
1667 ((python-info-end-of-statement-p) 'statement-end)
1668 ((python-info-statement-starts-block-p) 'starts-block)
1669 ((python-info-statement-ends-block-p) 'ends-block)))))
1671 (cond ((and (not (eobp))
1672 (python-info-current-line-empty-p))
1673 (python-util-forward-comment dir)
1674 (python-nav--forward-sexp dir safe skip-parens-p))
1675 ((eq context 'block-start)
1676 (python-nav-end-of-block))
1677 ((eq context 'statement-start)
1678 (python-nav-end-of-statement))
1679 ((and (memq context '(statement-end block-end))
1680 (eq next-sexp-context 'ends-block))
1681 (goto-char next-sexp-pos)
1682 (python-nav-end-of-block))
1683 ((and (memq context '(statement-end block-end))
1684 (eq next-sexp-context 'starts-block))
1685 (goto-char next-sexp-pos)
1686 (python-nav-end-of-block))
1687 ((memq context '(statement-end block-end))
1688 (goto-char next-sexp-pos)
1689 (python-nav-end-of-statement))
1690 (t (goto-char next-sexp-pos)))
1691 (cond ((and (not (bobp))
1692 (python-info-current-line-empty-p))
1693 (python-util-forward-comment dir)
1694 (python-nav--forward-sexp dir safe skip-parens-p))
1695 ((eq context 'block-end)
1696 (python-nav-beginning-of-block))
1697 ((eq context 'statement-end)
1698 (python-nav-beginning-of-statement))
1699 ((and (memq context '(statement-start block-start))
1700 (eq next-sexp-context 'starts-block))
1701 (goto-char next-sexp-pos)
1702 (python-nav-beginning-of-block))
1703 ((and (memq context '(statement-start block-start))
1704 (eq next-sexp-context 'ends-block))
1705 (goto-char next-sexp-pos)
1706 (python-nav-beginning-of-block))
1707 ((memq context '(statement-start block-start))
1708 (goto-char next-sexp-pos)
1709 (python-nav-beginning-of-statement))
1710 (t (goto-char next-sexp-pos))))))))))
1712 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p)
1713 "Move forward across expressions.
1714 With ARG, do it that many times. Negative arg -N means move
1715 backward N times. When optional argument SAFE is non-nil do not
1716 throw errors when at end of sexp, skip it instead. With optional
1717 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1718 expressions when looking at them in either direction (forced to t
1719 in interactive calls)."
1721 (or arg (setq arg 1))
1722 ;; Do not follow parens on interactive calls. This hack to detect
1723 ;; if the function was called interactively copes with the way
1724 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1725 ;; interactive detection by checking `current-prefix-arg'. The
1726 ;; reason to make this distinction is that lisp functions like
1727 ;; `blink-matching-open' get confused causing issues like the one in
1728 ;; Bug#16191. With this approach the user gets a symmetric behavior
1729 ;; when working interactively while called functions expecting
1730 ;; paren-based sexp motion work just fine.
1734 (memq real-this-command
1736 #'forward-sexp #'backward-sexp
1737 #'python-nav-forward-sexp #'python-nav-backward-sexp
1738 #'python-nav-forward-sexp-safe #'python-nav-backward-sexp))))
1740 (python-nav--forward-sexp 1 safe skip-parens-p)
1741 (setq arg (1- arg)))
1743 (python-nav--forward-sexp -1 safe skip-parens-p)
1744 (setq arg (1+ arg))))
1746 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p)
1747 "Move backward across expressions.
1748 With ARG, do it that many times. Negative arg -N means move
1749 forward N times. When optional argument SAFE is non-nil do not
1750 throw errors when at end of sexp, skip it instead. With optional
1751 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1752 expressions when looking at them in either direction (forced to t
1753 in interactive calls)."
1755 (or arg (setq arg 1))
1756 (python-nav-forward-sexp (- arg) safe skip-parens-p))
1758 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p)
1759 "Move forward safely across expressions.
1760 With ARG, do it that many times. Negative arg -N means move
1761 backward N times. With optional argument SKIP-PARENS-P force
1762 sexp motion to ignore parenthesized expressions when looking at
1763 them in either direction (forced to t in interactive calls)."
1765 (python-nav-forward-sexp arg t skip-parens-p))
1767 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p)
1768 "Move backward safely across expressions.
1769 With ARG, do it that many times. Negative arg -N means move
1770 forward N times. With optional argument SKIP-PARENS-P force sexp
1771 motion to ignore parenthesized expressions when looking at them in
1772 either direction (forced to t in interactive calls)."
1774 (python-nav-backward-sexp arg t skip-parens-p))
1776 (defun python-nav--up-list (&optional dir)
1777 "Internal implementation of `python-nav-up-list'.
1778 DIR is always 1 or -1 and comes sanitized from
1779 `python-nav-up-list' calls."
1780 (let ((context (python-syntax-context-type))
1781 (forward-p (> dir 0)))
1783 ((memq context '(string comment)))
1784 ((eq context 'paren)
1785 (let ((forward-sexp-function))
1787 ((and forward-p (python-info-end-of-block-p))
1788 (let ((parent-end-pos
1790 (let ((indentation (and
1791 (python-nav-beginning-of-block)
1792 (current-indentation))))
1793 (while (and indentation
1795 (>= (current-indentation) indentation)
1796 (python-nav-backward-block)))
1797 (python-nav-end-of-block)))))
1798 (and (> (or parent-end-pos (point)) (point))
1799 (goto-char parent-end-pos))))
1800 (forward-p (python-nav-end-of-block))
1801 ((and (not forward-p)
1802 (> (current-indentation) 0)
1803 (python-info-beginning-of-block-p))
1804 (let ((prev-block-pos
1806 (let ((indentation (current-indentation)))
1807 (while (and (python-nav-backward-block)
1808 (>= (current-indentation) indentation))))
1810 (and (> (point) prev-block-pos)
1811 (goto-char prev-block-pos))))
1812 ((not forward-p) (python-nav-beginning-of-block)))))
1814 (defun python-nav-up-list (&optional arg)
1815 "Move forward out of one level of parentheses (or blocks).
1816 With ARG, do this that many times.
1817 A negative argument means move backward but still to a less deep spot.
1818 This command assumes point is not in a string or comment."
1820 (or arg (setq arg 1))
1822 (python-nav--up-list 1)
1823 (setq arg (1- arg)))
1825 (python-nav--up-list -1)
1826 (setq arg (1+ arg))))
1828 (defun python-nav-backward-up-list (&optional arg)
1829 "Move backward out of one level of parentheses (or blocks).
1830 With ARG, do this that many times.
1831 A negative argument means move forward but still to a less deep spot.
1832 This command assumes point is not in a string or comment."
1834 (or arg (setq arg 1))
1835 (python-nav-up-list (- arg)))
1837 (defun python-nav-if-name-main ()
1838 "Move point at the beginning the __main__ block.
1839 When \"if __name__ == '__main__':\" is found returns its
1840 position, else returns nil."
1842 (let ((point (point))
1843 (found (catch 'found
1844 (goto-char (point-min))
1845 (while (re-search-forward
1846 (python-rx line-start
1848 "__name__" (+ space)
1850 (group-n 1 (or ?\" ?\'))
1851 "__main__" (backref 1) (* space) ":")
1853 (when (not (python-syntax-context-type))
1855 (throw 'found t))))))
1858 (ignore (goto-char point)))))
1861 ;;; Shell integration
1863 (defcustom python-shell-buffer-name "Python"
1864 "Default buffer name for Python interpreter."
1869 (defcustom python-shell-interpreter "python"
1870 "Default Python interpreter for shell."
1874 (defcustom python-shell-internal-buffer-name "Python Internal"
1875 "Default buffer name for the Internal Python interpreter."
1880 (defcustom python-shell-interpreter-args "-i"
1881 "Default arguments for the Python interpreter."
1885 (defcustom python-shell-interpreter-interactive-arg "-i"
1886 "Interpreter argument to force it to run interactively."
1890 (defcustom python-shell-prompt-detect-enabled t
1891 "Non-nil enables autodetection of interpreter prompts."
1896 (defcustom python-shell-prompt-detect-failure-warning t
1897 "Non-nil enables warnings when detection of prompts fail."
1902 (defcustom python-shell-prompt-input-regexps
1903 '(">>> " "\\.\\.\\. " ; Python
1904 "In \\[[0-9]+\\]: " ; IPython
1905 " \\.\\.\\.: " ; IPython
1906 ;; Using ipdb outside IPython may fail to cleanup and leave static
1907 ;; IPython prompts activated, this adds some safeguard for that.
1908 "In : " "\\.\\.\\.: ")
1909 "List of regular expressions matching input prompts."
1910 :type '(repeat string)
1913 (defcustom python-shell-prompt-output-regexps
1915 "Out\\[[0-9]+\\]: " ; IPython
1916 "Out :") ; ipdb safeguard
1917 "List of regular expressions matching output prompts."
1918 :type '(repeat string)
1921 (defcustom python-shell-prompt-regexp ">>> "
1922 "Regular expression matching top level input prompt of Python shell.
1923 It should not contain a caret (^) at the beginning."
1926 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1927 "Regular expression matching block input prompt of Python shell.
1928 It should not contain a caret (^) at the beginning."
1931 (defcustom python-shell-prompt-output-regexp ""
1932 "Regular expression matching output prompt of Python shell.
1933 It should not contain a caret (^) at the beginning."
1936 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1937 "Regular expression matching pdb input prompt of Python shell.
1938 It should not contain a caret (^) at the beginning."
1941 (define-obsolete-variable-alias
1942 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1944 (defcustom python-shell-font-lock-enable t
1945 "Should syntax highlighting be enabled in the Python shell buffer?
1946 Restart the Python shell after changing this variable for it to take effect."
1951 (defcustom python-shell-unbuffered t
1952 "Should shell output be unbuffered?.
1953 When non-nil, this may prevent delayed and missing output in the
1954 Python shell. See commentary for details."
1959 (defcustom python-shell-process-environment nil
1960 "List of overridden environment variables for subprocesses to inherit.
1961 Each element should be a string of the form ENVVARNAME=VALUE.
1962 When this variable is non-nil, values are exported into the
1963 process environment before starting it. Any variables already
1964 present in the current environment are superseded by variables
1966 :type '(repeat string)
1969 (defcustom python-shell-extra-pythonpaths nil
1970 "List of extra pythonpaths for Python shell.
1971 When this variable is non-nil, values added at the beginning of
1972 the PYTHONPATH before starting processes. Any values present
1973 here that already exists in PYTHONPATH are moved to the beginning
1974 of the list so that they are prioritized when looking for
1976 :type '(repeat string)
1979 (defcustom python-shell-exec-path nil
1980 "List of paths for searching executables.
1981 When this variable is non-nil, values added at the beginning of
1982 the PATH before starting processes. Any values present here that
1983 already exists in PATH are moved to the beginning of the list so
1984 that they are prioritized when looking for executables."
1985 :type '(repeat string)
1988 (defcustom python-shell-remote-exec-path nil
1989 "List of paths to be ensured remotely for searching executables.
1990 When this variable is non-nil, values are exported into remote
1991 hosts PATH before starting processes. Values defined in
1992 `python-shell-exec-path' will take precedence to paths defined
1993 here. Normally you wont use this variable directly unless you
1994 plan to ensure a particular set of paths to all Python shell
1995 executed through tramp connections."
1996 :type '(repeat string)
1999 (defcustom python-shell-virtualenv-root nil
2000 "Path to virtualenv root.
2001 This variable, when set to a string, makes the environment to be
2002 modified such that shells are started within the specified
2004 :type '(choice (const nil) string)
2007 (define-obsolete-variable-alias
2008 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
2010 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
2011 python-ffap-setup-code
2012 python-eldoc-setup-code)
2013 "List of code run by `python-shell-send-setup-codes'."
2014 :type '(repeat symbol)
2017 (defcustom python-shell-compilation-regexp-alist
2018 `((,(rx line-start (1+ (any " \t")) "File \""
2019 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
2020 "\", line " (group (1+ digit)))
2022 (,(rx " in file " (group (1+ not-newline)) " on line "
2025 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
2026 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
2028 "`compilation-error-regexp-alist' for inferior Python."
2029 :type '(alist string)
2032 (defmacro python-shell--add-to-path-with-priority (pathvar paths)
2033 "Modify PATHVAR and ensure PATHS are added only once at beginning."
2034 `(dolist (path (reverse ,paths))
2035 (cl-delete path ,pathvar :test #'string=)
2036 (cl-pushnew path ,pathvar :test #'string=)))
2038 (defun python-shell-calculate-pythonpath ()
2039 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2041 (tramp-compat-split-string
2042 (or (getenv "PYTHONPATH") "") path-separator)))
2043 (python-shell--add-to-path-with-priority
2044 pythonpath python-shell-extra-pythonpaths)
2045 (mapconcat 'identity pythonpath path-separator)))
2047 (defun python-shell-calculate-process-environment ()
2048 "Calculate `process-environment' or `tramp-remote-process-environment'.
2049 Prepends `python-shell-process-environment', sets extra
2050 pythonpaths from `python-shell-extra-pythonpaths' and sets a few
2051 virtualenv related vars. If `default-directory' points to a
2052 remote host, the returned value is intended for
2053 `tramp-remote-process-environment'."
2054 (let* ((remote-p (file-remote-p default-directory))
2055 (process-environment (if remote-p
2056 tramp-remote-process-environment
2057 process-environment))
2058 (virtualenv (when python-shell-virtualenv-root
2059 (directory-file-name python-shell-virtualenv-root))))
2060 (dolist (env python-shell-process-environment)
2061 (pcase-let ((`(,key ,value) (split-string env "=")))
2062 (setenv key value)))
2063 (when python-shell-unbuffered
2064 (setenv "PYTHONUNBUFFERED" "1"))
2065 (when python-shell-extra-pythonpaths
2066 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2067 (if (not virtualenv)
2069 (setenv "PYTHONHOME" nil)
2070 (setenv "VIRTUAL_ENV" virtualenv))
2071 process-environment))
2073 (defun python-shell-calculate-exec-path ()
2074 "Calculate `exec-path'.
2075 Prepends `python-shell-exec-path' and adds the binary directory
2076 for virtualenv if `python-shell-virtualenv-root' is set. If
2077 `default-directory' points to a remote host, the returned value
2078 appends `python-shell-remote-exec-path' instead of `exec-path'."
2079 (let ((new-path (copy-sequence
2080 (if (file-remote-p default-directory)
2081 python-shell-remote-exec-path
2083 (python-shell--add-to-path-with-priority
2084 new-path python-shell-exec-path)
2085 (if (not python-shell-virtualenv-root)
2087 (python-shell--add-to-path-with-priority
2089 (list (expand-file-name "bin" python-shell-virtualenv-root)))
2092 (defun python-shell-tramp-refresh-remote-path (vec paths)
2093 "Update VEC's remote-path giving PATHS priority."
2094 (let ((remote-path (tramp-get-connection-property vec "remote-path" nil)))
2096 (python-shell--add-to-path-with-priority remote-path paths)
2097 (tramp-set-connection-property vec "remote-path" remote-path)
2098 (tramp-set-remote-path vec))))
2100 (defvar python-shell--with-environment-wrapped nil)
2102 (defmacro python-shell-with-environment (&rest body)
2103 "Modify shell environment during execution of BODY.
2104 Temporarily sets `process-environment' and `exec-path' during
2105 execution of body. If `default-directory' points to a remote
2106 machine then modifies `tramp-remote-process-environment' and
2107 `python-shell-remote-exec-path' instead."
2108 (declare (indent 0) (debug (body)))
2109 (let ((vec (make-symbol "vec")))
2111 (if python-shell--with-environment-wrapped
2112 ,(macroexp-progn body)
2114 (when (file-remote-p default-directory)
2116 (tramp-dissect-file-name default-directory 'noexpand))))
2117 (process-environment
2120 (python-shell-calculate-process-environment)))
2124 (python-shell-calculate-exec-path)))
2125 (tramp-remote-process-environment
2127 (python-shell-calculate-process-environment)
2128 tramp-remote-process-environment))
2129 (python-shell--with-environment-wrapped t))
2130 (when (tramp-get-connection-process ,vec)
2131 ;; For already existing connections, modified env vars must
2132 ;; be re-set again. This is a normal thing to happen when
2133 ;; remote dir-locals are read from remote and *then*
2134 ;; processes should be started within the same connection
2135 ;; with env vars calculated from them.
2136 (python-shell-tramp-refresh-remote-path
2137 ,vec (python-shell-calculate-exec-path)))
2138 ,(macroexp-progn body))))))
2140 (defvar python-shell--prompt-calculated-input-regexp nil
2141 "Calculated input prompt regexp for inferior python shell.
2142 Do not set this variable directly, instead use
2143 `python-shell-prompt-set-calculated-regexps'.")
2145 (defvar python-shell--prompt-calculated-output-regexp nil
2146 "Calculated output prompt regexp for inferior python shell.
2147 Do not set this variable directly, instead use
2148 `python-shell-set-prompt-regexp'.")
2150 (defun python-shell-prompt-detect ()
2151 "Detect prompts for the current `python-shell-interpreter'.
2152 When prompts can be retrieved successfully from the
2153 `python-shell-interpreter' run with
2154 `python-shell-interpreter-interactive-arg', returns a list of
2155 three elements, where the first two are input prompts and the
2156 last one is an output prompt. When no prompts can be detected
2157 and `python-shell-prompt-detect-failure-warning' is non-nil,
2158 shows a warning with instructions to avoid hangs and returns nil.
2159 When `python-shell-prompt-detect-enabled' is nil avoids any
2160 detection and just returns nil."
2161 (when python-shell-prompt-detect-enabled
2162 (python-shell-with-environment
2163 (let* ((code (concat
2165 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2166 ;; JSON is built manually for compatibility
2167 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2172 ;; TODO: improve error handling by using
2173 ;; `condition-case' and displaying the error message to
2174 ;; the user in the no-prompts warning.
2176 (let ((code-file (python-shell--save-temp-file code)))
2177 ;; Use `process-file' as it is remote-host friendly.
2179 python-shell-interpreter
2183 python-shell-interpreter-interactive-arg)
2185 (delete-file code-file)))
2189 (dolist (line (split-string output "\n" t))
2191 ;; Check if current line is a valid JSON array
2192 (and (string= (substring line 0 2) "[\"")
2194 ;; Return prompts as a list, not vector
2195 (append (json-read-from-string line) nil)))))
2196 ;; The list must contain 3 strings, where the first
2197 ;; is the input prompt, the second is the block
2198 ;; prompt and the last one is the output prompt. The
2199 ;; input prompt is the only one that can't be empty.
2200 (when (and (= (length res) 3)
2201 (cl-every #'stringp res)
2202 (not (string= (car res) "")))
2203 (throw 'prompts res))))
2205 (when (and (not prompts)
2206 python-shell-prompt-detect-failure-warning)
2208 '(python python-shell-prompt-regexp)
2211 "Python shell prompts cannot be detected.\n"
2212 "If your emacs session hangs when starting python shells\n"
2213 "recover with `keyboard-quit' and then try fixing the\n"
2214 "interactive flag for your interpreter by adjusting the\n"
2215 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2216 "matching shell prompts in the directory-local friendly vars:\n"
2217 " + `python-shell-prompt-regexp'\n"
2218 " + `python-shell-prompt-block-regexp'\n"
2219 " + `python-shell-prompt-output-regexp'\n"
2220 "Or alternatively in:\n"
2221 " + `python-shell-prompt-input-regexps'\n"
2222 " + `python-shell-prompt-output-regexps'")))
2225 (defun python-shell-prompt-validate-regexps ()
2226 "Validate all user provided regexps for prompts.
2227 Signals `user-error' if any of these vars contain invalid
2228 regexps: `python-shell-prompt-regexp',
2229 `python-shell-prompt-block-regexp',
2230 `python-shell-prompt-pdb-regexp',
2231 `python-shell-prompt-output-regexp',
2232 `python-shell-prompt-input-regexps',
2233 `python-shell-prompt-output-regexps'."
2234 (dolist (symbol (list 'python-shell-prompt-input-regexps
2235 'python-shell-prompt-output-regexps
2236 'python-shell-prompt-regexp
2237 'python-shell-prompt-block-regexp
2238 'python-shell-prompt-pdb-regexp
2239 'python-shell-prompt-output-regexp))
2240 (dolist (regexp (let ((regexps (symbol-value symbol)))
2244 (when (not (python-util-valid-regexp-p regexp))
2245 (user-error "Invalid regexp %s in `%s'"
2248 (defun python-shell-prompt-set-calculated-regexps ()
2249 "Detect and set input and output prompt regexps.
2250 Build and set the values for `python-shell-input-prompt-regexp'
2251 and `python-shell-output-prompt-regexp' using the values from
2252 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2253 `python-shell-prompt-pdb-regexp',
2254 `python-shell-prompt-output-regexp',
2255 `python-shell-prompt-input-regexps',
2256 `python-shell-prompt-output-regexps' and detected prompts from
2257 `python-shell-prompt-detect'."
2258 (when (not (and python-shell--prompt-calculated-input-regexp
2259 python-shell--prompt-calculated-output-regexp))
2260 (let* ((detected-prompts (python-shell-prompt-detect))
2262 (output-prompts nil)
2266 (mapconcat #'identity
2269 (let ((length-a (length a))
2270 (length-b (length b)))
2271 (if (= length-a length-b)
2273 (> (length a) (length b))))))
2276 ;; Validate ALL regexps
2277 (python-shell-prompt-validate-regexps)
2278 ;; Collect all user defined input prompts
2279 (dolist (prompt (append python-shell-prompt-input-regexps
2280 (list python-shell-prompt-regexp
2281 python-shell-prompt-block-regexp
2282 python-shell-prompt-pdb-regexp)))
2283 (cl-pushnew prompt input-prompts :test #'string=))
2284 ;; Collect all user defined output prompts
2285 (dolist (prompt (cons python-shell-prompt-output-regexp
2286 python-shell-prompt-output-regexps))
2287 (cl-pushnew prompt output-prompts :test #'string=))
2288 ;; Collect detected prompts if any
2289 (when detected-prompts
2290 (dolist (prompt (butlast detected-prompts))
2291 (setq prompt (regexp-quote prompt))
2292 (cl-pushnew prompt input-prompts :test #'string=))
2293 (cl-pushnew (regexp-quote
2294 (car (last detected-prompts)))
2295 output-prompts :test #'string=))
2296 ;; Set input and output prompt regexps from collected prompts
2297 (setq python-shell--prompt-calculated-input-regexp
2298 (funcall build-regexp input-prompts)
2299 python-shell--prompt-calculated-output-regexp
2300 (funcall build-regexp output-prompts)))))
2302 (defun python-shell-get-process-name (dedicated)
2303 "Calculate the appropriate process name for inferior Python process.
2304 If DEDICATED is t returns a string with the form
2305 `python-shell-buffer-name'[`buffer-name'] else returns the value
2306 of `python-shell-buffer-name'."
2308 (format "%s[%s]" python-shell-buffer-name (buffer-name))
2309 python-shell-buffer-name))
2311 (defun python-shell-internal-get-process-name ()
2312 "Calculate the appropriate process name for Internal Python process.
2313 The name is calculated from `python-shell-global-buffer-name' and
2315 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
2317 (defun python-shell-calculate-command ()
2318 "Calculate the string used to execute the inferior Python process."
2320 (shell-quote-argument python-shell-interpreter)
2321 python-shell-interpreter-args))
2323 (define-obsolete-function-alias
2324 'python-shell-parse-command
2325 #'python-shell-calculate-command "25.1")
2327 (defvar python-shell--package-depth 10)
2329 (defun python-shell-package-enable (directory package)
2330 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2332 (let* ((dir (expand-file-name
2333 (read-directory-name
2335 (file-name-directory
2336 (or (buffer-file-name) default-directory)))))
2337 (name (completing-read
2339 (python-util-list-packages
2340 dir python-shell--package-depth))))
2342 (python-shell-send-string
2345 "import os.path;import sys;"
2346 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2347 "__package__ = '''%s''';"
2349 directory package package)
2350 (python-shell-get-process)))
2352 (defun python-shell-accept-process-output (process &optional timeout regexp)
2353 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2354 Optional argument TIMEOUT is the timeout argument to
2355 `accept-process-output' calls. Optional argument REGEXP
2356 overrides the regexp to match the end of output, defaults to
2357 `comint-prompt-regexp.'. Returns non-nil when output was
2360 This utility is useful in situations where the output may be
2361 received in chunks, since `accept-process-output' gives no
2362 guarantees they will be grabbed in a single call. An example use
2363 case for this would be the CPython shell start-up, where the
2364 banner and the initial prompt are received separately."
2365 (let ((regexp (or regexp comint-prompt-regexp)))
2368 (when (not (accept-process-output process timeout))
2371 regexp (car (python-util-comint-last-prompt)))
2372 (throw 'found t))))))
2374 (defun python-shell-comint-end-of-output-p (output)
2375 "Return non-nil if OUTPUT is ends with input prompt."
2377 ;; XXX: It seems on OSX an extra carriage return is attached
2378 ;; at the end of output, this handles that too.
2381 ;; Remove initial caret from calculated regexp
2382 (replace-regexp-in-string
2383 (rx string-start ?^) ""
2384 python-shell--prompt-calculated-input-regexp)
2388 (define-obsolete-function-alias
2389 'python-comint-output-filter-function
2390 'ansi-color-filter-apply
2393 (defun python-comint-postoutput-scroll-to-bottom (output)
2394 "Faster version of `comint-postoutput-scroll-to-bottom'.
2395 Avoids `recenter' calls until OUTPUT is completely sent."
2396 (when (and (not (string= "" output))
2397 (python-shell-comint-end-of-output-p
2398 (ansi-color-filter-apply output)))
2399 (comint-postoutput-scroll-to-bottom output))
2402 (defvar python-shell--parent-buffer nil)
2404 (defmacro python-shell-with-shell-buffer (&rest body)
2405 "Execute the forms in BODY with the shell buffer temporarily current.
2406 Signals an error if no shell buffer is available for current buffer."
2407 (declare (indent 0) (debug t))
2408 (let ((shell-process (make-symbol "shell-process")))
2409 `(let ((,shell-process (python-shell-get-process-or-error)))
2410 (with-current-buffer (process-buffer ,shell-process)
2413 (defvar python-shell--font-lock-buffer nil)
2415 (defun python-shell-font-lock-get-or-create-buffer ()
2416 "Get or create a font-lock buffer for current inferior process."
2417 (python-shell-with-shell-buffer
2418 (if python-shell--font-lock-buffer
2419 python-shell--font-lock-buffer
2421 (process-name (get-buffer-process (current-buffer)))))
2422 (generate-new-buffer
2423 (format " *%s-font-lock*" process-name))))))
2425 (defun python-shell-font-lock-kill-buffer ()
2426 "Kill the font-lock buffer safely."
2427 (when (and python-shell--font-lock-buffer
2428 (buffer-live-p python-shell--font-lock-buffer))
2429 (kill-buffer python-shell--font-lock-buffer)
2430 (when (derived-mode-p 'inferior-python-mode)
2431 (setq python-shell--font-lock-buffer nil))))
2433 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2434 "Execute the forms in BODY in the font-lock buffer.
2435 The value returned is the value of the last form in BODY. See
2436 also `with-current-buffer'."
2437 (declare (indent 0) (debug t))
2438 `(python-shell-with-shell-buffer
2439 (save-current-buffer
2440 (when (not (and python-shell--font-lock-buffer
2441 (get-buffer python-shell--font-lock-buffer)))
2442 (setq python-shell--font-lock-buffer
2443 (python-shell-font-lock-get-or-create-buffer)))
2444 (set-buffer python-shell--font-lock-buffer)
2445 (when (not font-lock-mode)
2447 (set (make-local-variable 'delay-mode-hooks) t)
2448 (let ((python-indent-guess-indent-offset nil))
2449 (when (not (derived-mode-p 'python-mode))
2453 (defun python-shell-font-lock-cleanup-buffer ()
2454 "Cleanup the font-lock buffer.
2455 Provided as a command because this might be handy if something
2456 goes wrong and syntax highlighting in the shell gets messed up."
2458 (python-shell-with-shell-buffer
2459 (python-shell-font-lock-with-font-lock-buffer
2462 (defun python-shell-font-lock-comint-output-filter-function (output)
2463 "Clean up the font-lock buffer after any OUTPUT."
2464 (if (and (not (string= "" output))
2465 ;; Is end of output and is not just a prompt.
2467 (python-shell-comint-end-of-output-p
2468 (ansi-color-filter-apply output))
2470 ;; If output is other than an input prompt then "real" output has
2471 ;; been received and the font-lock buffer must be cleaned up.
2472 (python-shell-font-lock-cleanup-buffer)
2473 ;; Otherwise just add a newline.
2474 (python-shell-font-lock-with-font-lock-buffer
2475 (goto-char (point-max))
2479 (defun python-shell-font-lock-post-command-hook ()
2480 "Fontifies current line in shell buffer."
2481 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2482 (when (and prompt-end (> (point) prompt-end)
2483 (process-live-p (get-buffer-process (current-buffer))))
2484 (let* ((input (buffer-substring-no-properties
2485 prompt-end (point-max)))
2486 (deactivate-mark nil)
2487 (start-pos prompt-end)
2488 (buffer-undo-list t)
2489 (font-lock-buffer-pos nil)
2491 (python-shell-font-lock-with-font-lock-buffer
2492 (delete-region (line-beginning-position)
2494 (setq font-lock-buffer-pos (point))
2496 ;; Ensure buffer is fontified, keeping it
2497 ;; compatible with Emacs < 24.4.
2498 (if (fboundp 'font-lock-ensure)
2499 (funcall 'font-lock-ensure)
2500 (font-lock-default-fontify-buffer))
2501 (buffer-substring font-lock-buffer-pos
2503 (replacement-length (length replacement))
2505 ;; Inject text properties to get input fontified.
2506 (while (not (= i replacement-length))
2507 (let* ((plist (text-properties-at i replacement))
2508 (next-change (or (next-property-change i replacement)
2509 replacement-length))
2510 (plist (let ((face (plist-get plist 'face)))
2513 ;; Replace FACE text properties with
2514 ;; FONT-LOCK-FACE so input is fontified.
2515 (plist-put plist 'face nil)
2516 (plist-put plist 'font-lock-face face)))))
2517 (set-text-properties
2518 (+ start-pos i) (+ start-pos next-change) plist)
2519 (setq i next-change)))))))
2521 (defun python-shell-font-lock-turn-on (&optional msg)
2522 "Turn on shell font-lock.
2523 With argument MSG show activation message."
2525 (python-shell-with-shell-buffer
2526 (python-shell-font-lock-kill-buffer)
2527 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2528 (add-hook 'post-command-hook
2529 #'python-shell-font-lock-post-command-hook nil 'local)
2530 (add-hook 'kill-buffer-hook
2531 #'python-shell-font-lock-kill-buffer nil 'local)
2532 (add-hook 'comint-output-filter-functions
2533 #'python-shell-font-lock-comint-output-filter-function
2536 (message "Shell font-lock is enabled"))))
2538 (defun python-shell-font-lock-turn-off (&optional msg)
2539 "Turn off shell font-lock.
2540 With argument MSG show deactivation message."
2542 (python-shell-with-shell-buffer
2543 (python-shell-font-lock-kill-buffer)
2544 (when (python-util-comint-last-prompt)
2545 ;; Cleanup current fontification
2546 (remove-text-properties
2547 (cdr (python-util-comint-last-prompt))
2549 '(face nil font-lock-face nil)))
2550 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2551 (remove-hook 'post-command-hook
2552 #'python-shell-font-lock-post-command-hook 'local)
2553 (remove-hook 'kill-buffer-hook
2554 #'python-shell-font-lock-kill-buffer 'local)
2555 (remove-hook 'comint-output-filter-functions
2556 #'python-shell-font-lock-comint-output-filter-function
2559 (message "Shell font-lock is disabled"))))
2561 (defun python-shell-font-lock-toggle (&optional msg)
2562 "Toggle font-lock for shell.
2563 With argument MSG show activation/deactivation message."
2565 (python-shell-with-shell-buffer
2566 (set (make-local-variable 'python-shell-font-lock-enable)
2567 (not python-shell-font-lock-enable))
2568 (if python-shell-font-lock-enable
2569 (python-shell-font-lock-turn-on msg)
2570 (python-shell-font-lock-turn-off msg))
2571 python-shell-font-lock-enable))
2573 ;; Used to hold user interactive overrides to
2574 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2575 ;; will be made buffer-local by `inferior-python-mode':
2576 (defvar python-shell--interpreter)
2577 (defvar python-shell--interpreter-args)
2579 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2580 "Major mode for Python inferior process.
2581 Runs a Python interpreter as a subprocess of Emacs, with Python
2582 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2583 and `python-shell-interpreter-args' control which Python
2584 interpreter is run. Variables
2585 `python-shell-prompt-regexp',
2586 `python-shell-prompt-output-regexp',
2587 `python-shell-prompt-block-regexp',
2588 `python-shell-font-lock-enable',
2589 `python-shell-completion-setup-code',
2590 `python-shell-completion-string-code',
2591 `python-eldoc-setup-code', `python-eldoc-string-code',
2592 `python-ffap-setup-code' and `python-ffap-string-code' can
2593 customize this mode for different Python interpreters.
2595 This mode resets `comint-output-filter-functions' locally, so you
2596 may want to re-add custom functions to it using the
2597 `inferior-python-mode-hook'.
2599 You can also add additional setup code to be run at
2600 initialization of the interpreter via `python-shell-setup-codes'
2603 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2604 (when python-shell--parent-buffer
2605 (python-util-clone-local-variables python-shell--parent-buffer))
2606 ;; Users can interactively override default values for
2607 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2608 ;; when calling `run-python'. This ensures values let-bound in
2609 ;; `python-shell-make-comint' are locally set if needed.
2610 (set (make-local-variable 'python-shell-interpreter)
2611 (or python-shell--interpreter python-shell-interpreter))
2612 (set (make-local-variable 'python-shell-interpreter-args)
2613 (or python-shell--interpreter-args python-shell-interpreter-args))
2614 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2615 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2616 (python-shell-prompt-set-calculated-regexps)
2617 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2618 (set (make-local-variable 'comint-prompt-read-only) t)
2619 (setq mode-line-process '(":%s"))
2620 (set (make-local-variable 'comint-output-filter-functions)
2621 '(ansi-color-process-output
2622 python-pdbtrack-comint-output-filter-function
2623 python-comint-postoutput-scroll-to-bottom))
2624 (set (make-local-variable 'compilation-error-regexp-alist)
2625 python-shell-compilation-regexp-alist)
2626 (add-hook 'completion-at-point-functions
2627 #'python-shell-completion-at-point nil 'local)
2628 (define-key inferior-python-mode-map "\t"
2629 'python-shell-completion-complete-or-indent)
2630 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2631 (make-local-variable 'python-pdbtrack-tracked-buffer)
2632 (make-local-variable 'python-shell-internal-last-output)
2633 (when python-shell-font-lock-enable
2634 (python-shell-font-lock-turn-on))
2635 (compilation-shell-minor-mode 1)
2636 (python-shell-accept-process-output
2637 (get-buffer-process (current-buffer))))
2639 (defun python-shell-make-comint (cmd proc-name &optional show internal)
2640 "Create a Python shell comint buffer.
2641 CMD is the Python command to be executed and PROC-NAME is the
2642 process name the comint buffer will get. After the comint buffer
2643 is created the `inferior-python-mode' is activated. When
2644 optional argument SHOW is non-nil the buffer is shown. When
2645 optional argument INTERNAL is non-nil this process is run on a
2646 buffer with a name that starts with a space, following the Emacs
2647 convention for temporary/internal buffers, and also makes sure
2648 the user is not queried for confirmation when the process is
2651 (python-shell-with-environment
2652 (let* ((proc-buffer-name
2653 (format (if (not internal) "*%s*" " *%s*") proc-name)))
2654 (when (not (comint-check-proc proc-buffer-name))
2655 (let* ((cmdlist (split-string-and-unquote cmd))
2656 (interpreter (car cmdlist))
2657 (args (cdr cmdlist))
2658 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2659 interpreter nil args))
2660 (python-shell--parent-buffer (current-buffer))
2661 (process (get-buffer-process buffer))
2662 ;; Users can override the interpreter and args
2663 ;; interactively when calling `run-python', let-binding
2664 ;; these allows to have the new right values in all
2665 ;; setup code that is done in `inferior-python-mode',
2666 ;; which is important, especially for prompt detection.
2667 (python-shell--interpreter interpreter)
2668 (python-shell--interpreter-args
2669 (mapconcat #'identity args " ")))
2670 (with-current-buffer buffer
2671 (inferior-python-mode))
2672 (when show (display-buffer buffer))
2673 (and internal (set-process-query-on-exit-flag process nil))))
2674 proc-buffer-name))))
2677 (defun run-python (&optional cmd dedicated show)
2678 "Run an inferior Python process.
2680 Argument CMD defaults to `python-shell-calculate-command' return
2681 value. When called interactively with `prefix-arg', it allows
2682 the user to edit such value and choose whether the interpreter
2683 should be DEDICATED for the current buffer. When numeric prefix
2684 arg is other than 0 or 4 do not SHOW.
2686 For a given buffer and same values of DEDICATED, if a process is
2687 already running for it, it will do nothing. This means that if
2688 the current buffer is using a global process, the user is still
2689 able to switch it to use a dedicated one.
2691 Runs the hook `inferior-python-mode-hook' after
2692 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2693 process buffer for a list of commands.)"
2695 (if current-prefix-arg
2697 (read-shell-command "Run Python: " (python-shell-calculate-command))
2698 (y-or-n-p "Make dedicated process? ")
2699 (= (prefix-numeric-value current-prefix-arg) 4))
2700 (list (python-shell-calculate-command) nil t)))
2702 (python-shell-make-comint
2703 (or cmd (python-shell-calculate-command))
2704 (python-shell-get-process-name dedicated) show)))
2706 (defun run-python-internal ()
2707 "Run an inferior Internal Python process.
2708 Input and output via buffer named after
2709 `python-shell-internal-buffer-name' and what
2710 `python-shell-internal-get-process-name' returns.
2712 This new kind of shell is intended to be used for generic
2713 communication related to defined configurations; the main
2714 difference with global or dedicated shells is that these ones are
2715 attached to a configuration, not a buffer. This means that can
2716 be used for example to retrieve the sys.path and other stuff,
2717 without messing with user shells. Note that
2718 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2719 are set to nil for these shells, so setup codes are not sent at
2721 (let ((python-shell-font-lock-enable nil)
2722 (inferior-python-mode-hook nil))
2724 (python-shell-make-comint
2725 (python-shell-calculate-command)
2726 (python-shell-internal-get-process-name) nil t))))
2728 (defun python-shell-get-buffer ()
2729 "Return inferior Python buffer for current buffer.
2730 If current buffer is in `inferior-python-mode', return it."
2731 (if (derived-mode-p 'inferior-python-mode)
2733 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2734 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2735 (global-proc-name (python-shell-get-process-name nil))
2736 (global-proc-buffer-name (format "*%s*" global-proc-name))
2737 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2738 (global-running (comint-check-proc global-proc-buffer-name)))
2739 ;; Always prefer dedicated
2740 (or (and dedicated-running dedicated-proc-buffer-name)
2741 (and global-running global-proc-buffer-name)))))
2743 (defun python-shell-get-process ()
2744 "Return inferior Python process for current buffer."
2745 (get-buffer-process (python-shell-get-buffer)))
2747 (defun python-shell-get-process-or-error (&optional interactivep)
2748 "Return inferior Python process for current buffer or signal error.
2749 When argument INTERACTIVEP is non-nil, use `user-error' instead
2750 of `error' with a user-friendly message."
2751 (or (python-shell-get-process)
2754 "Start a Python process first with ‘%s’ or ‘%s’."
2755 (substitute-command-keys "\\[run-python]")
2759 #'run-python overriding-local-map t)))
2761 "No inferior Python process running."))))
2763 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2764 "Get or create an inferior Python process for current buffer and return it.
2765 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2766 are used to start the shell. If those arguments are not
2767 provided, `run-python' is called interactively and the user will
2768 be asked for their values."
2769 (let ((shell-process (python-shell-get-process)))
2770 (when (not shell-process)
2772 ;; XXX: Refactor code such that calling `run-python'
2773 ;; interactively is not needed anymore.
2774 (call-interactively 'run-python)
2775 (run-python cmd dedicated show)))
2776 (or shell-process (python-shell-get-process))))
2779 #'python-shell-get-or-create-process
2780 "Instead call `python-shell-get-process' and create one if returns nil."
2783 (defvar python-shell-internal-buffer nil
2784 "Current internal shell buffer for the current buffer.
2785 This is really not necessary at all for the code to work but it's
2786 there for compatibility with CEDET.")
2788 (defvar python-shell-internal-last-output nil
2789 "Last output captured by the internal shell.
2790 This is really not necessary at all for the code to work but it's
2791 there for compatibility with CEDET.")
2793 (defun python-shell-internal-get-or-create-process ()
2794 "Get or create an inferior Internal Python process."
2795 (let ((proc-name (python-shell-internal-get-process-name)))
2796 (if (process-live-p proc-name)
2797 (get-process proc-name)
2798 (run-python-internal))))
2800 (define-obsolete-function-alias
2801 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2803 (define-obsolete-variable-alias
2804 'python-buffer 'python-shell-internal-buffer "24.3")
2806 (define-obsolete-variable-alias
2807 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2809 (defun python-shell--save-temp-file (string)
2810 (let* ((temporary-file-directory
2811 (if (file-remote-p default-directory)
2812 (concat (file-remote-p default-directory) "/tmp")
2813 temporary-file-directory))
2814 (temp-file-name (make-temp-file "py"))
2815 (coding-system-for-write (python-info-encoding)))
2816 (with-temp-file temp-file-name
2818 (delete-trailing-whitespace))
2821 (defun python-shell-send-string (string &optional process msg)
2822 "Send STRING to inferior Python PROCESS.
2823 When optional argument MSG is non-nil, forces display of a
2824 user-friendly message if there's no process running; defaults to
2825 t when called interactively."
2827 (list (read-string "Python command: ") nil t))
2828 (let ((process (or process (python-shell-get-process-or-error msg))))
2829 (if (string-match ".\n+." string) ;Multiline.
2830 (let* ((temp-file-name (python-shell--save-temp-file string))
2831 (file-name (or (buffer-file-name) temp-file-name)))
2832 (python-shell-send-file file-name process temp-file-name t))
2833 (comint-send-string process string)
2834 (when (or (not (string-match "\n\\'" string))
2835 (string-match "\n[ \t].*\n?\\'" string))
2836 (comint-send-string process "\n")))))
2838 (defvar python-shell-output-filter-in-progress nil)
2839 (defvar python-shell-output-filter-buffer nil)
2841 (defun python-shell-output-filter (string)
2842 "Filter used in `python-shell-send-string-no-output' to grab output.
2843 STRING is the output received to this point from the process.
2844 This filter saves received output from the process in
2845 `python-shell-output-filter-buffer' and stops receiving it after
2846 detecting a prompt at the end of the buffer."
2848 string (ansi-color-filter-apply string)
2849 python-shell-output-filter-buffer
2850 (concat python-shell-output-filter-buffer string))
2851 (when (python-shell-comint-end-of-output-p
2852 python-shell-output-filter-buffer)
2853 ;; Output ends when `python-shell-output-filter-buffer' contains
2854 ;; the prompt attached at the end of it.
2855 (setq python-shell-output-filter-in-progress nil
2856 python-shell-output-filter-buffer
2857 (substring python-shell-output-filter-buffer
2858 0 (match-beginning 0)))
2860 python-shell--prompt-calculated-output-regexp
2861 python-shell-output-filter-buffer)
2862 ;; Some shells, like IPython might append a prompt before the
2863 ;; output, clean that.
2864 (setq python-shell-output-filter-buffer
2865 (substring python-shell-output-filter-buffer (match-end 0)))))
2868 (defun python-shell-send-string-no-output (string &optional process)
2869 "Send STRING to PROCESS and inhibit output.
2871 (let ((process (or process (python-shell-get-process-or-error)))
2872 (comint-preoutput-filter-functions
2873 '(python-shell-output-filter))
2874 (python-shell-output-filter-in-progress t)
2878 (python-shell-send-string string process)
2879 (while python-shell-output-filter-in-progress
2880 ;; `python-shell-output-filter' takes care of setting
2881 ;; `python-shell-output-filter-in-progress' to NIL after it
2882 ;; detects end of output.
2883 (accept-process-output process))
2885 python-shell-output-filter-buffer
2886 (setq python-shell-output-filter-buffer nil)))
2887 (with-current-buffer (process-buffer process)
2888 (comint-interrupt-subjob)))))
2890 (defun python-shell-internal-send-string (string)
2891 "Send STRING to the Internal Python interpreter.
2892 Returns the output. See `python-shell-send-string-no-output'."
2893 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2894 ;; updated to support this new mode.
2895 (setq python-shell-internal-last-output
2896 (python-shell-send-string-no-output
2897 ;; Makes this function compatible with the old
2898 ;; python-send-receive. (At least for CEDET).
2899 (replace-regexp-in-string "_emacs_out +" "" string)
2900 (python-shell-internal-get-or-create-process))))
2902 (define-obsolete-function-alias
2903 'python-send-receive 'python-shell-internal-send-string "24.3")
2905 (define-obsolete-function-alias
2906 'python-send-string 'python-shell-internal-send-string "24.3")
2908 (defun python-shell-buffer-substring (start end &optional nomain)
2909 "Send buffer substring from START to END formatted for shell.
2910 This is a wrapper over `buffer-substring' that takes care of
2911 different transformations for the code sent to be evaluated in
2913 1. When optional argument NOMAIN is non-nil everything under an
2914 \"if __name__ == '__main__'\" block will be removed.
2915 2. When a subregion of the buffer is sent, it takes care of
2916 appending extra empty lines so tracebacks are correct.
2917 3. When the region sent is a substring of the current buffer, a
2918 coding cookie is added.
2919 4. Wraps indented regions under an \"if True:\" block so the
2920 interpreter evaluates them correctly."
2921 (let* ((substring (buffer-substring-no-properties start end))
2922 (starts-at-point-min-p (save-restriction
2924 (= (point-min) start)))
2925 (encoding (python-info-encoding))
2926 (fillstr (when (not starts-at-point-min-p)
2928 (format "# -*- coding: %s -*-\n" encoding)
2930 ;; Subtract 2 because of the coding cookie.
2931 (- (line-number-at-pos start) 2) ?\n))))
2932 (toplevel-block-p (save-excursion
2934 (or (zerop (line-number-at-pos start))
2936 (python-util-forward-comment 1)
2937 (zerop (current-indentation)))))))
2940 (if fillstr (insert fillstr))
2942 (goto-char (point-min))
2943 (when (not toplevel-block-p)
2945 (delete-region (point) (line-end-position)))
2947 (let* ((if-name-main-start-end
2950 (when (python-nav-if-name-main)
2952 (progn (python-nav-forward-sexp-safe)
2953 ;; Include ending newline
2956 ;; Oh destructuring bind, how I miss you.
2957 (if-name-main-start (car if-name-main-start-end))
2958 (if-name-main-end (cdr if-name-main-start-end))
2959 (fillstr (make-string
2960 (- (line-number-at-pos if-name-main-end)
2961 (line-number-at-pos if-name-main-start)) ?\n)))
2962 (when if-name-main-start-end
2963 (goto-char if-name-main-start)
2964 (delete-region if-name-main-start if-name-main-end)
2966 ;; Ensure there's only one coding cookie in the generated string.
2967 (goto-char (point-min))
2968 (when (looking-at-p (python-rx coding-cookie))
2970 (when (looking-at-p (python-rx coding-cookie))
2972 (line-beginning-position) (line-end-position))))
2973 (buffer-substring-no-properties (point-min) (point-max)))))
2975 (defun python-shell-send-region (start end &optional send-main msg)
2976 "Send the region delimited by START and END to inferior Python process.
2977 When optional argument SEND-MAIN is non-nil, allow execution of
2978 code inside blocks delimited by \"if __name__== '__main__':\".
2979 When called interactively SEND-MAIN defaults to nil, unless it's
2980 called with prefix argument. When optional argument MSG is
2981 non-nil, forces display of a user-friendly message if there's no
2982 process running; defaults to t when called interactively."
2984 (list (region-beginning) (region-end) current-prefix-arg t))
2985 (let* ((string (python-shell-buffer-substring start end (not send-main)))
2986 (process (python-shell-get-process-or-error msg))
2987 (original-string (buffer-substring-no-properties start end))
2988 (_ (string-match "\\`\n*\\(.*\\)" original-string)))
2989 (message "Sent: %s..." (match-string 1 original-string))
2990 (python-shell-send-string string process)))
2992 (defun python-shell-send-buffer (&optional send-main msg)
2993 "Send the entire buffer to inferior Python process.
2994 When optional argument SEND-MAIN is non-nil, allow execution of
2995 code inside blocks delimited by \"if __name__== '__main__':\".
2996 When called interactively SEND-MAIN defaults to nil, unless it's
2997 called with prefix argument. When optional argument MSG is
2998 non-nil, forces display of a user-friendly message if there's no
2999 process running; defaults to t when called interactively."
3000 (interactive (list current-prefix-arg t))
3003 (python-shell-send-region (point-min) (point-max) send-main msg)))
3005 (defun python-shell-send-defun (&optional arg msg)
3006 "Send the current defun to inferior Python process.
3007 When argument ARG is non-nil do not include decorators. When
3008 optional argument MSG is non-nil, forces display of a
3009 user-friendly message if there's no process running; defaults to
3010 t when called interactively."
3011 (interactive (list current-prefix-arg t))
3013 (python-shell-send-region
3016 (while (and (or (python-nav-beginning-of-defun)
3017 (beginning-of-line 1))
3018 (> (current-indentation) 0)))
3020 (while (and (forward-line -1)
3021 (looking-at (python-rx decorator))))
3025 (or (python-nav-end-of-defun)
3031 (defun python-shell-send-file (file-name &optional process temp-file-name
3033 "Send FILE-NAME to inferior Python PROCESS.
3034 If TEMP-FILE-NAME is passed then that file is used for processing
3035 instead, while internally the shell will continue to use
3036 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
3037 TEMP-FILE-NAME is deleted after evaluation is performed. When
3038 optional argument MSG is non-nil, forces display of a
3039 user-friendly message if there's no process running; defaults to
3040 t when called interactively."
3043 (read-file-name "File to send: ") ; file-name
3045 nil ; temp-file-name
3048 (let* ((process (or process (python-shell-get-process-or-error msg)))
3049 (encoding (with-temp-buffer
3050 (insert-file-contents
3051 (or temp-file-name file-name))
3052 (python-info-encoding)))
3053 (file-name (expand-file-name
3054 (or (file-remote-p file-name 'localname)
3056 (temp-file-name (when temp-file-name
3058 (or (file-remote-p temp-file-name 'localname)
3060 (python-shell-send-string
3063 "import codecs, os;"
3064 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
3065 "__code = __pyfile.read().encode('''%s''');"
3067 (when (and delete temp-file-name)
3068 (format "os.remove('''%s''');" temp-file-name))
3069 "exec(compile(__code, '''%s''', 'exec'));")
3070 (or temp-file-name file-name) encoding encoding file-name)
3073 (defun python-shell-switch-to-shell (&optional msg)
3074 "Switch to inferior Python process buffer.
3075 When optional argument MSG is non-nil, forces display of a
3076 user-friendly message if there's no process running; defaults to
3077 t when called interactively."
3080 (process-buffer (python-shell-get-process-or-error msg)) nil t))
3082 (defun python-shell-send-setup-code ()
3083 "Send all setup code for shell.
3084 This function takes the list of setup code to send from the
3085 `python-shell-setup-codes' list."
3086 (let ((process (python-shell-get-process))
3090 (cond ((stringp elt) elt)
3091 ((symbolp elt) (symbol-value elt))
3093 python-shell-setup-codes
3095 "\n\nprint ('python.el: sent setup code')")))
3096 (python-shell-send-string code process)
3097 (python-shell-accept-process-output process)))
3099 (add-hook 'inferior-python-mode-hook
3100 #'python-shell-send-setup-code)
3103 ;;; Shell completion
3105 (defcustom python-shell-completion-setup-code
3109 def __PYTHON_EL_get_completions(text):
3112 def __PYTHON_EL_get_completions(text):
3117 import builtins as __builtin__
3118 builtins = dir(__builtin__)
3120 is_ipython = ('__IPYTHON__' in builtins or
3121 '__IPYTHON__active' in builtins)
3122 splits = text.split()
3123 is_module = splits and splits[0] in ('from', 'import')
3125 if is_ipython and is_module:
3126 from IPython.core.completerlib import module_completion
3127 completions = module_completion(text.strip())
3128 elif is_ipython and '__IP' in builtins:
3129 completions = __IP.complete(text)
3130 elif is_ipython and 'get_ipython' in builtins:
3131 completions = get_ipython().Completer.all_completions(text)
3133 # Try to reuse current completer.
3134 completer = readline.get_completer()
3136 # importing rlcompleter sets the completer, use it as a
3137 # last resort to avoid breaking customizations.
3139 completer = readline.get_completer()
3142 completion = completer(text, i)
3146 completions.append(completion)
3150 "Code used to setup completion in inferior Python processes."
3154 (defcustom python-shell-completion-string-code
3155 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3156 "Python code used to get a string of completions separated by semicolons.
3157 The string passed to the function is the current python name or
3158 the full statement in the case of imports."
3162 (define-obsolete-variable-alias
3163 'python-shell-completion-module-string-code
3164 'python-shell-completion-string-code
3166 "Completion string code must also autocomplete modules.")
3168 (define-obsolete-variable-alias
3169 'python-shell-completion-pdb-string-code
3170 'python-shell-completion-string-code
3172 "Completion string code must work for (i)pdb.")
3174 (defcustom python-shell-completion-native-disabled-interpreters
3175 ;; PyPy's readline cannot handle some escape sequences yet.
3177 "List of disabled interpreters.
3178 When a match is found, native completion is disabled."
3179 :type '(repeat string))
3181 (defcustom python-shell-completion-native-enable t
3182 "Enable readline based native completion."
3185 (defcustom python-shell-completion-native-output-timeout 5.0
3186 "Time in seconds to wait for completion output before giving up."
3189 (defcustom python-shell-completion-native-try-output-timeout 1.0
3190 "Time in seconds to wait for *trying* native completion output."
3193 (defvar python-shell-completion-native-redirect-buffer
3194 " *Python completions redirect*"
3195 "Buffer to be used to redirect output of readline commands.")
3197 (defun python-shell-completion-native-interpreter-disabled-p ()
3198 "Return non-nil if interpreter has native completion disabled."
3199 (when python-shell-completion-native-disabled-interpreters
3201 (regexp-opt python-shell-completion-native-disabled-interpreters)
3202 (file-name-nondirectory python-shell-interpreter))))
3204 (defun python-shell-completion-native-try ()
3205 "Return non-nil if can trigger native completion."
3206 (let ((python-shell-completion-native-enable t)
3207 (python-shell-completion-native-output-timeout
3208 python-shell-completion-native-try-output-timeout))
3209 (python-shell-completion-native-get-completions
3210 (get-buffer-process (current-buffer))
3213 (defun python-shell-completion-native-setup ()
3214 "Try to setup native completion, return non-nil on success."
3215 (let ((process (python-shell-get-process)))
3216 (python-shell-send-string "
3217 def __PYTHON_EL_native_completion_setup():
3224 import builtins as __builtin__
3225 builtins = dir(__builtin__)
3226 is_ipython = ('__IPYTHON__' in builtins or
3227 '__IPYTHON__active' in builtins)
3228 class __PYTHON_EL_Completer:
3229 PYTHON_EL_WRAPPED = True
3230 def __init__(self, completer):
3231 self.completer = completer
3232 self.last_completion = None
3233 def __call__(self, text, state):
3235 # The first completion is always a dummy completion. This
3236 # ensures proper output for sole completions and a current
3237 # input safeguard when no completions are available.
3238 self.last_completion = None
3239 completion = '0__dummy_completion__'
3241 completion = self.completer(text, state - 1)
3244 # When no completions are available, two non-sharing
3245 # prefix strings are returned just to ensure output
3246 # while preventing changes to current input.
3247 completion = '1__dummy_completion__'
3248 elif self.last_completion != '~~~~__dummy_completion__':
3249 # This marks the end of output.
3250 completion = '~~~~__dummy_completion__'
3251 elif completion.endswith('('):
3252 # Remove parens on callables as it breaks completion on
3253 # arguments (e.g. str(Ari<tab>)).
3254 completion = completion[:-1]
3255 self.last_completion = completion
3257 completer = readline.get_completer()
3259 # Used as last resort to avoid breaking customizations.
3261 completer = readline.get_completer()
3262 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3263 # Wrap the existing completer function only once.
3264 new_completer = __PYTHON_EL_Completer(completer)
3266 readline.set_completer(new_completer)
3268 # Try both initializations to cope with all IPython versions.
3269 # This works fine for IPython 3.x but not for earlier:
3270 readline.set_completer(new_completer)
3271 # IPython<3 hacks readline such that `readline.set_completer`
3272 # won't work. This workaround injects the new completer
3273 # function into the existing instance directly:
3274 instance = getattr(completer, 'im_self', completer.__self__)
3275 instance.rlcomplete = new_completer
3276 if readline.__doc__ and 'libedit' in readline.__doc__:
3277 readline.parse_and_bind('bind ^I rl_complete')
3279 readline.parse_and_bind('tab: complete')
3280 # Require just one tab to send output.
3281 readline.parse_and_bind('set show-all-if-ambiguous on')
3282 print ('python.el: readline is available')
3284 print ('python.el: readline not available')
3285 __PYTHON_EL_native_completion_setup()"
3287 (python-shell-accept-process-output process)
3288 (when (save-excursion
3290 (regexp-quote "python.el: readline is available") nil t 1))
3291 (python-shell-completion-native-try))))
3293 (defun python-shell-completion-native-turn-off (&optional msg)
3294 "Turn off shell native completions.
3295 With argument MSG show deactivation message."
3297 (python-shell-with-shell-buffer
3298 (set (make-local-variable 'python-shell-completion-native-enable) nil)
3300 (message "Shell native completion is disabled, using fallback"))))
3302 (defun python-shell-completion-native-turn-on (&optional msg)
3303 "Turn on shell native completions.
3304 With argument MSG show deactivation message."
3306 (python-shell-with-shell-buffer
3307 (set (make-local-variable 'python-shell-completion-native-enable) t)
3308 (python-shell-completion-native-turn-on-maybe msg)))
3310 (defun python-shell-completion-native-turn-on-maybe (&optional msg)
3311 "Turn on native completions if enabled and available.
3312 With argument MSG show activation/deactivation message."
3314 (python-shell-with-shell-buffer
3315 (when python-shell-completion-native-enable
3317 ((python-shell-completion-native-interpreter-disabled-p)
3318 (python-shell-completion-native-turn-off msg))
3319 ((python-shell-completion-native-setup)
3321 (message "Shell native completion is enabled.")))
3323 '(python python-shell-completion-native-turn-on-maybe)
3326 "Your `python-shell-interpreter' doesn't seem to "
3327 "support readline, yet `python-shell-completion-native' "
3328 (format "was t and %S is not part of the "
3329 (file-name-nondirectory python-shell-interpreter))
3330 "`python-shell-completion-native-disabled-interpreters' "
3331 "list. Native completions have been disabled locally. "))
3332 (python-shell-completion-native-turn-off msg))))))
3334 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3335 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3336 (python-shell-completion-native-turn-on-maybe t))
3338 (add-hook 'inferior-python-mode-hook
3339 #'python-shell-completion-native-turn-on-maybe-with-msg)
3341 (defun python-shell-completion-native-toggle (&optional msg)
3342 "Toggle shell native completion.
3343 With argument MSG show activation/deactivation message."
3345 (python-shell-with-shell-buffer
3346 (if python-shell-completion-native-enable
3347 (python-shell-completion-native-turn-off msg)
3348 (python-shell-completion-native-turn-on msg))
3349 python-shell-completion-native-enable))
3351 (defun python-shell-completion-native-get-completions (process import input)
3352 "Get completions using native readline for PROCESS.
3353 When IMPORT is non-nil takes precedence over INPUT for
3355 (with-current-buffer (process-buffer process)
3356 (when (and python-shell-completion-native-enable
3357 (python-util-comint-last-prompt)
3358 (>= (point) (cdr (python-util-comint-last-prompt))))
3359 (let* ((input (or import input))
3360 (original-filter-fn (process-filter process))
3361 (redirect-buffer (get-buffer-create
3362 python-shell-completion-native-redirect-buffer))
3363 (separators (python-rx (or whitespace open-paren close-paren)))
3365 (new-input (concat input trigger))
3368 (+ (- (point-max) (comint-bol)) (length new-input))))
3369 (delete-line-command (make-string input-length ?\b))
3370 (input-to-send (concat new-input delete-line-command)))
3371 ;; Ensure restoring the process filter, even if the user quits
3372 ;; or there's some other error.
3374 (with-current-buffer redirect-buffer
3375 ;; Cleanup the redirect buffer
3376 (delete-region (point-min) (point-max))
3377 ;; Mimic `comint-redirect-send-command', unfortunately it
3378 ;; can't be used here because it expects a newline in the
3379 ;; command and that's exactly what we are trying to avoid.
3380 (let ((comint-redirect-echo-input nil)
3381 (comint-redirect-verbose nil)
3382 (comint-redirect-perform-sanity-check nil)
3383 (comint-redirect-insert-matching-regexp nil)
3384 ;; Feed it some regex that will never match.
3385 (comint-redirect-finished-regexp "^\\'$")
3386 (comint-redirect-output-buffer redirect-buffer)
3387 (current-time (float-time)))
3388 ;; Compatibility with Emacs 24.x. Comint changed and
3389 ;; now `comint-redirect-filter' gets 3 args. This
3390 ;; checks which version of `comint-redirect-filter' is
3391 ;; in use based on its args and uses `apply-partially'
3392 ;; to make it up for the 3 args case.
3394 (help-function-arglist 'comint-redirect-filter)) 3)
3396 process (apply-partially
3397 #'comint-redirect-filter original-filter-fn))
3398 (set-process-filter process #'comint-redirect-filter))
3399 (process-send-string process input-to-send)
3400 ;; Grab output until our dummy completion used as
3401 ;; output end marker is found. Output is accepted
3402 ;; *very* quickly to keep the shell super-responsive.
3403 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t))
3404 (< (- (float-time) current-time)
3405 python-shell-completion-native-output-timeout))
3406 (accept-process-output process 0.01))
3407 (cl-remove-duplicates
3410 (string-match "__dummy_completion__" c))
3412 (buffer-substring-no-properties
3413 (point-min) (point-max))
3416 (set-process-filter process original-filter-fn))))))
3418 (defun python-shell-completion-get-completions (process import input)
3419 "Do completion at point using PROCESS for IMPORT or INPUT.
3420 When IMPORT is non-nil takes precedence over INPUT for
3422 (with-current-buffer (process-buffer process)
3424 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3425 (buffer-substring-no-properties
3426 (car prompt-boundaries) (cdr prompt-boundaries))))
3428 ;; Check whether a prompt matches a pdb string, an import
3429 ;; statement or just the standard prompt and use the
3430 ;; correct python-shell-completion-*-code string
3431 (cond ((and (string-match
3432 (concat "^" python-shell-prompt-pdb-regexp) prompt))
3433 ;; Since there are no guarantees the user will remain
3434 ;; in the same context where completion code was sent
3435 ;; (e.g. user steps into a function), safeguard
3436 ;; resending completion setup continuously.
3437 (concat python-shell-completion-setup-code
3438 "\nprint (" python-shell-completion-string-code ")"))
3440 python-shell--prompt-calculated-input-regexp prompt)
3441 python-shell-completion-string-code)
3443 (subject (or import input)))
3444 (and completion-code
3445 (> (length input) 0)
3447 (python-util-strip-string
3448 (python-shell-send-string-no-output
3449 (format completion-code subject) process))))
3450 (and (> (length completions) 2)
3451 (split-string completions
3452 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
3454 (defun python-shell-completion-at-point (&optional process)
3455 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3456 Optional argument PROCESS forces completions to be retrieved
3457 using that one instead of current buffer's process."
3458 (setq process (or process (get-buffer-process (current-buffer))))
3459 (let* ((line-start (if (derived-mode-p 'inferior-python-mode)
3460 ;; Working on a shell buffer: use prompt end.
3461 (cdr (python-util-comint-last-prompt))
3462 (line-beginning-position)))
3464 (when (string-match-p
3465 (rx (* space) word-start (or "from" "import") word-end space)
3466 (buffer-substring-no-properties line-start (point)))
3467 (buffer-substring-no-properties line-start (point))))
3470 (if (not (re-search-backward
3472 (or whitespace open-paren close-paren string-delimiter))
3476 (forward-char (length (match-string-no-properties 0)))
3480 (if python-shell-completion-native-enable
3481 #'python-shell-completion-native-get-completions
3482 #'python-shell-completion-get-completions)))
3484 (completion-table-dynamic
3487 process import-statement)))))
3489 (define-obsolete-function-alias
3490 'python-shell-completion-complete-at-point
3491 'python-shell-completion-at-point
3494 (defun python-shell-completion-complete-or-indent ()
3495 "Complete or indent depending on the context.
3496 If content before pointer is all whitespace, indent.
3497 If not try to complete."
3499 (if (string-match "^[[:space:]]*$"
3500 (buffer-substring (comint-line-beginning-position)
3502 (indent-for-tab-command)
3503 (completion-at-point)))
3506 ;;; PDB Track integration
3508 (defcustom python-pdbtrack-activate t
3509 "Non-nil makes Python shell enable pdbtracking."
3514 (defcustom python-pdbtrack-stacktrace-info-regexp
3515 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3516 "Regular expression matching stacktrace information.
3517 Used to extract the current line and module being inspected."
3522 (defvar python-pdbtrack-tracked-buffer nil
3523 "Variable containing the value of the current tracked buffer.
3524 Never set this variable directly, use
3525 `python-pdbtrack-set-tracked-buffer' instead.")
3527 (defvar python-pdbtrack-buffers-to-kill nil
3528 "List of buffers to be deleted after tracking finishes.")
3530 (defun python-pdbtrack-set-tracked-buffer (file-name)
3531 "Set the buffer for FILE-NAME as the tracked buffer.
3532 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3533 Returns the tracked buffer."
3534 (let ((file-buffer (get-file-buffer
3535 (concat (file-remote-p default-directory)
3538 (setq python-pdbtrack-tracked-buffer file-buffer)
3539 (setq file-buffer (find-file-noselect file-name))
3540 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3541 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3544 (defun python-pdbtrack-comint-output-filter-function (output)
3545 "Move overlay arrow to current pdb line in tracked buffer.
3546 Argument OUTPUT is a string with the output from the comint process."
3547 (when (and python-pdbtrack-activate (not (string= output "")))
3548 (let* ((full-output (ansi-color-filter-apply
3549 (buffer-substring comint-last-input-end (point-max))))
3553 (insert full-output)
3554 ;; When the debugger encounters a pdb.set_trace()
3555 ;; command, it prints a single stack frame. Sometimes
3556 ;; it prints a bit of extra information about the
3557 ;; arguments of the present function. When ipdb
3558 ;; encounters an exception, it prints the _entire_ stack
3559 ;; trace. To handle all of these cases, we want to find
3560 ;; the _last_ stack frame printed in the most recent
3561 ;; batch of output, then jump to the corresponding
3562 ;; file/line number.
3563 (goto-char (point-max))
3564 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3565 (setq line-number (string-to-number
3566 (match-string-no-properties 2)))
3567 (match-string-no-properties 1)))))
3568 (if (and file-name line-number)
3569 (let* ((tracked-buffer
3570 (python-pdbtrack-set-tracked-buffer file-name))
3571 (shell-buffer (current-buffer))
3572 (tracked-buffer-window (get-buffer-window tracked-buffer))
3573 (tracked-buffer-line-pos))
3574 (with-current-buffer tracked-buffer
3575 (set (make-local-variable 'overlay-arrow-string) "=>")
3576 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3577 (setq tracked-buffer-line-pos (progn
3578 (goto-char (point-min))
3579 (forward-line (1- line-number))
3581 (when tracked-buffer-window
3583 tracked-buffer-window tracked-buffer-line-pos))
3584 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3585 (pop-to-buffer tracked-buffer)
3586 (switch-to-buffer-other-window shell-buffer))
3587 (when python-pdbtrack-tracked-buffer
3588 (with-current-buffer python-pdbtrack-tracked-buffer
3589 (set-marker overlay-arrow-position nil))
3590 (mapc #'(lambda (buffer)
3591 (ignore-errors (kill-buffer buffer)))
3592 python-pdbtrack-buffers-to-kill)
3593 (setq python-pdbtrack-tracked-buffer nil
3594 python-pdbtrack-buffers-to-kill nil)))))
3598 ;;; Symbol completion
3600 (defun python-completion-at-point ()
3601 "Function for `completion-at-point-functions' in `python-mode'.
3602 For this to work as best as possible you should call
3603 `python-shell-send-buffer' from time to time so context in
3604 inferior Python process is updated properly."
3605 (let ((process (python-shell-get-process)))
3607 (python-shell-completion-at-point process))))
3609 (define-obsolete-function-alias
3610 'python-completion-complete-at-point
3611 'python-completion-at-point
3617 (defcustom python-fill-comment-function 'python-fill-comment
3618 "Function to fill comments.
3619 This is the function used by `python-fill-paragraph' to
3624 (defcustom python-fill-string-function 'python-fill-string
3625 "Function to fill strings.
3626 This is the function used by `python-fill-paragraph' to
3631 (defcustom python-fill-decorator-function 'python-fill-decorator
3632 "Function to fill decorators.
3633 This is the function used by `python-fill-paragraph' to
3638 (defcustom python-fill-paren-function 'python-fill-paren
3639 "Function to fill parens.
3640 This is the function used by `python-fill-paragraph' to
3645 (defcustom python-fill-docstring-style 'pep-257
3646 "Style used to fill docstrings.
3647 This affects `python-fill-string' behavior with regards to
3648 triple quotes positioning.
3650 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3651 `symmetric', and nil. A value of nil won't care about quotes
3652 position and will treat docstrings a normal string, any other
3653 value may result in one of the following docstring styles:
3658 Process foo, return bar.
3662 Process foo, return bar.
3664 If processing fails throw ProcessingError.
3669 \"\"\"Process foo, return bar.\"\"\"
3672 Process foo, return bar.
3674 If processing fails throw ProcessingError.
3680 \"\"\"Process foo, return bar.\"\"\"
3682 \"\"\"Process foo, return bar.
3684 If processing fails throw ProcessingError.
3690 \"\"\"Process foo, return bar.\"\"\"
3692 \"\"\"Process foo, return bar.
3694 If processing fails throw ProcessingError.
3699 \"\"\"Process foo, return bar.\"\"\"
3702 Process foo, return bar.
3704 If processing fails throw ProcessingError.
3707 (const :tag "Don't format docstrings" nil)
3708 (const :tag "Django's coding standards style." django)
3709 (const :tag "One newline and start and Two at end style." onetwo)
3710 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3711 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3712 (const :tag "Symmetric style." symmetric))
3715 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3717 (defun python-fill-paragraph (&optional justify)
3718 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3719 If any of the current line is in or at the end of a multi-line string,
3720 fill the string or the paragraph of it that point is in, preserving
3721 the string's indentation.
3722 Optional argument JUSTIFY defines if the paragraph should be justified."
3727 ((python-syntax-context 'comment)
3728 (funcall python-fill-comment-function justify))
3729 ;; Strings/Docstrings
3730 ((save-excursion (or (python-syntax-context 'string)
3731 (equal (string-to-syntax "|")
3732 (syntax-after (point)))))
3733 (funcall python-fill-string-function justify))
3735 ((equal (char-after (save-excursion
3736 (python-nav-beginning-of-statement))) ?@)
3737 (funcall python-fill-decorator-function justify))
3739 ((or (python-syntax-context 'paren)
3740 (looking-at (python-rx open-paren))
3742 (skip-syntax-forward "^(" (line-end-position))
3743 (looking-at (python-rx open-paren))))
3744 (funcall python-fill-paren-function justify))
3747 (defun python-fill-comment (&optional justify)
3748 "Comment fill function for `python-fill-paragraph'.
3749 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3750 (fill-comment-paragraph justify))
3752 (defun python-fill-string (&optional justify)
3753 "String fill function for `python-fill-paragraph'.
3754 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3755 (let* ((str-start-pos
3758 (or (python-syntax-context 'string)
3759 (and (equal (string-to-syntax "|")
3760 (syntax-after (point)))
3762 (num-quotes (python-syntax-count-quotes
3763 (char-after str-start-pos) str-start-pos))
3766 (goto-char (+ str-start-pos num-quotes))
3767 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3768 (goto-char (point-max)))
3771 ;; Docstring styles may vary for oneliners and multi-liners.
3772 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3774 (pcase python-fill-docstring-style
3775 ;; delimiters-style is a cons cell with the form
3776 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3777 ;; is NIL means to not add any newlines for start or end
3778 ;; of docstring. See `python-fill-docstring-style' for a
3779 ;; graphic idea of each style.
3780 (`django (cons 1 1))
3781 (`onetwo (and multi-line-p (cons 1 2)))
3782 (`pep-257 (and multi-line-p (cons nil 2)))
3783 (`pep-257-nn (and multi-line-p (cons nil 1)))
3784 (`symmetric (and multi-line-p (cons 1 1)))))
3785 (fill-paragraph-function))
3787 (narrow-to-region str-start-pos str-end-pos)
3788 (fill-paragraph justify))
3790 (when (and (python-info-docstring-p) python-fill-docstring-style)
3791 ;; Add the number of newlines indicated by the selected style
3792 ;; at the start of the docstring.
3793 (goto-char (+ str-start-pos num-quotes))
3794 (delete-region (point) (progn
3795 (skip-syntax-forward "> ")
3797 (and (car delimiters-style)
3798 (or (newline (car delimiters-style)) t)
3799 ;; Indent only if a newline is added.
3800 (indent-according-to-mode))
3801 ;; Add the number of newlines indicated by the selected style
3802 ;; at the end of the docstring.
3803 (goto-char (if (not (= str-end-pos (point-max)))
3804 (- str-end-pos num-quotes)
3806 (delete-region (point) (progn
3807 (skip-syntax-backward "> ")
3809 (and (cdr delimiters-style)
3810 ;; Add newlines only if string ends.
3811 (not (= str-end-pos (point-max)))
3812 (or (newline (cdr delimiters-style)) t)
3813 ;; Again indent only if a newline is added.
3814 (indent-according-to-mode))))) t)
3816 (defun python-fill-decorator (&optional _justify)
3817 "Decorator fill function for `python-fill-paragraph'.
3818 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3821 (defun python-fill-paren (&optional justify)
3822 "Paren fill function for `python-fill-paragraph'.
3823 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3825 (narrow-to-region (progn
3826 (while (python-syntax-context 'paren)
3827 (goto-char (1- (point))))
3828 (line-beginning-position))
3830 (when (not (python-syntax-context 'paren))
3832 (when (not (python-syntax-context 'paren))
3833 (skip-syntax-backward "^)")))
3834 (while (and (python-syntax-context 'paren)
3836 (goto-char (1+ (point))))
3838 (let ((paragraph-start "\f\\|[ \t]*$")
3839 (paragraph-separate ",")
3840 (fill-paragraph-function))
3841 (goto-char (point-min))
3842 (fill-paragraph justify))
3845 (python-indent-line)
3846 (goto-char (line-end-position))))
3852 (defcustom python-skeleton-autoinsert nil
3853 "Non-nil means template skeletons will be automagically inserted.
3854 This happens when pressing \"if<SPACE>\", for example, to prompt for
3860 (define-obsolete-variable-alias
3861 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3863 (defvar python-skeleton-available '()
3864 "Internal list of available skeletons.")
3866 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3867 "Abbrev table for Python mode skeletons."
3869 ;; Allow / inside abbrevs.
3870 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3871 ;; Only expand in code.
3872 :enable-function (lambda ()
3874 (not (python-syntax-comment-or-string-p))
3875 python-skeleton-autoinsert)))
3877 (defmacro python-skeleton-define (name doc &rest skel)
3878 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3879 The skeleton will be bound to python-skeleton-NAME and will
3880 be added to `python-mode-skeleton-abbrev-table'."
3881 (declare (indent 2))
3882 (let* ((name (symbol-name name))
3883 (function-name (intern (concat "python-skeleton-" name))))
3885 (define-abbrev python-mode-skeleton-abbrev-table
3886 ,name "" ',function-name :system t)
3887 (setq python-skeleton-available
3888 (cons ',function-name python-skeleton-available))
3889 (define-skeleton ,function-name
3891 (format "Insert %s statement." name))
3894 (define-abbrev-table 'python-mode-abbrev-table ()
3895 "Abbrev table for Python mode."
3896 :parents (list python-mode-skeleton-abbrev-table))
3898 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3899 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3900 The skeleton will be bound to python-skeleton-NAME."
3901 (declare (indent 2))
3902 (let* ((name (symbol-name name))
3903 (function-name (intern (concat "python-skeleton--" name)))
3905 "Add '%s' clause? " name)))
3908 `(< ,(format "%s:" name) \n \n
3910 `(define-skeleton ,function-name
3912 (format "Auxiliary skeleton for %s statement." name))
3914 (unless (y-or-n-p ,msg)
3918 (python-define-auxiliary-skeleton else nil)
3920 (python-define-auxiliary-skeleton except nil)
3922 (python-define-auxiliary-skeleton finally nil)
3924 (python-skeleton-define if nil
3928 ("other condition, %s: "
3932 '(python-skeleton--else) | ^)
3934 (python-skeleton-define while nil
3938 '(python-skeleton--else) | ^)
3940 (python-skeleton-define for nil
3944 '(python-skeleton--else) | ^)
3946 (python-skeleton-define import nil
3947 "Import from module: "
3948 "from " str & " " | -5
3950 ("Identifier: " str ", ") -2 \n _)
3952 (python-skeleton-define try nil
3958 "except " str ":" \n
3961 '(python-skeleton--except)
3962 '(python-skeleton--else)
3963 '(python-skeleton--finally) | ^)
3965 (python-skeleton-define def nil
3967 "def " str "(" ("Parameter, %s: "
3968 (unless (equal ?\( (char-before)) ", ")
3970 "\"\"\"" - "\"\"\"" \n
3973 (python-skeleton-define class nil
3975 "class " str "(" ("Inheritance, %s: "
3976 (unless (equal ?\( (char-before)) ", ")
3980 "\"\"\"" - "\"\"\"" \n
3983 (defun python-skeleton-add-menu-items ()
3984 "Add menu items to Python->Skeletons menu."
3985 (let ((skeletons (sort python-skeleton-available 'string<)))
3986 (dolist (skeleton skeletons)
3988 nil '("Python" "Skeletons")
3990 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3995 (defcustom python-ffap-setup-code
3996 "def __FFAP_get_module_path(module):
3999 path = __import__(module).__file__
4000 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
4005 "Python code to get a module path."
4009 (defcustom python-ffap-string-code
4010 "__FFAP_get_module_path('''%s''')\n"
4011 "Python code used to get a string with the path of a module."
4015 (defun python-ffap-module-path (module)
4016 "Function for `ffap-alist' to return path for MODULE."
4018 (and (derived-mode-p 'inferior-python-mode)
4019 (get-buffer-process (current-buffer)))
4020 (python-shell-get-process))))
4024 (python-shell-send-string-no-output
4025 (format python-ffap-string-code module) process)))
4027 (substring-no-properties module-file 1 -1))))))
4031 (eval-after-load "ffap"
4033 (push '(python-mode . python-ffap-module-path) ffap-alist)
4034 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
4039 (defcustom python-check-command
4040 (or (executable-find "pyflakes")
4041 (executable-find "epylint")
4042 "install pyflakes, pylint or something else")
4043 "Command used to check a Python file."
4047 (defcustom python-check-buffer-name
4048 "*Python check: %s*"
4049 "Buffer name used for check commands."
4053 (defvar python-check-custom-command nil
4055 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
4056 (make-variable-buffer-local 'python-check-custom-command)
4058 (defun python-check (command)
4059 "Check a Python file (default current buffer's file).
4060 Runs COMMAND, a shell command, as if by `compile'.
4061 See `python-check-command' for the default."
4063 (list (read-string "Check command: "
4064 (or python-check-custom-command
4065 (concat python-check-command " "
4066 (shell-quote-argument
4068 (let ((name (buffer-file-name)))
4070 (file-name-nondirectory name)))
4072 (setq python-check-custom-command command)
4073 (save-some-buffers (not compilation-ask-about-save) nil)
4074 (python-shell-with-environment
4075 (compilation-start command nil
4077 (format python-check-buffer-name command)))))
4082 (defcustom python-eldoc-setup-code
4083 "def __PYDOC_get_help(obj):
4087 str_type = basestring
4090 if isinstance(obj, str_type):
4091 obj = eval(obj, globals())
4092 doc = inspect.getdoc(obj)
4093 if not doc and callable(obj):
4095 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4096 target = obj.__init__
4102 args = inspect.formatargspec(
4103 *inspect.getargspec(target)
4106 doc = '{objtype} {name}{args}'.format(
4107 objtype=objtype, name=name, args=args
4110 doc = doc.splitlines()[0]
4114 "Python code to setup documentation retrieval."
4118 (defcustom python-eldoc-string-code
4119 "__PYDOC_get_help('''%s''')\n"
4120 "Python code used to get a string with the documentation of an object."
4124 (defun python-eldoc--get-symbol-at-point ()
4125 "Get the current symbol for eldoc.
4126 Returns the current symbol handling point within arguments."
4128 (let ((start (python-syntax-context 'paren)))
4133 (memq (char-syntax (char-after)) '(?\ ?-)))
4134 ;; Try to adjust to closest symbol if not in one.
4135 (python-util-forward-comment -1)))
4136 (python-info-current-symbol t)))
4138 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
4139 "Internal implementation to get documentation at point.
4140 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4141 returns will be used. If not FORCE-PROCESS is passed what
4142 `python-shell-get-process' returns is used."
4143 (let ((process (or force-process (python-shell-get-process))))
4145 (let ((input (or force-input
4146 (python-eldoc--get-symbol-at-point))))
4148 ;; Prevent resizing the echo area when iPython is
4149 ;; enabled. Bug#18794.
4150 (python-util-strip-string
4151 (python-shell-send-string-no-output
4152 (format python-eldoc-string-code input)
4155 (defun python-eldoc-function ()
4156 "`eldoc-documentation-function' for Python.
4157 For this to work as best as possible you should call
4158 `python-shell-send-buffer' from time to time so context in
4159 inferior Python process is updated properly."
4160 (python-eldoc--get-doc-at-point))
4162 (defun python-eldoc-at-point (symbol)
4163 "Get help on SYMBOL using `help'.
4164 Interactively, prompt for symbol."
4166 (let ((symbol (python-eldoc--get-symbol-at-point))
4167 (enable-recursive-minibuffers t))
4168 (list (read-string (if symbol
4169 (format "Describe symbol (default %s): " symbol)
4170 "Describe symbol: ")
4172 (message (python-eldoc--get-doc-at-point symbol)))
4177 (defun python-hideshow-forward-sexp-function (arg)
4178 "Python specific `forward-sexp' function for `hs-minor-mode'.
4179 Argument ARG is ignored."
4180 arg ; Shut up, byte compiler.
4181 (python-nav-end-of-defun)
4182 (unless (python-info-current-line-empty-p)
4188 (defvar python-imenu-format-item-label-function
4189 'python-imenu-format-item-label
4190 "Imenu function used to format an item label.
4191 It must be a function with two arguments: TYPE and NAME.")
4193 (defvar python-imenu-format-parent-item-label-function
4194 'python-imenu-format-parent-item-label
4195 "Imenu function used to format a parent item label.
4196 It must be a function with two arguments: TYPE and NAME.")
4198 (defvar python-imenu-format-parent-item-jump-label-function
4199 'python-imenu-format-parent-item-jump-label
4200 "Imenu function used to format a parent jump item label.
4201 It must be a function with two arguments: TYPE and NAME.")
4203 (defun python-imenu-format-item-label (type name)
4204 "Return Imenu label for single node using TYPE and NAME."
4205 (format "%s (%s)" name type))
4207 (defun python-imenu-format-parent-item-label (type name)
4208 "Return Imenu label for parent node using TYPE and NAME."
4209 (format "%s..." (python-imenu-format-item-label type name)))
4211 (defun python-imenu-format-parent-item-jump-label (type _name)
4212 "Return Imenu label for parent node jump using TYPE and NAME."
4213 (if (string= type "class")
4214 "*class definition*"
4215 "*function definition*"))
4217 (defun python-imenu--put-parent (type name pos tree)
4218 "Add the parent with TYPE, NAME and POS to TREE."
4220 (funcall python-imenu-format-item-label-function type name))
4222 (funcall python-imenu-format-parent-item-jump-label-function type name)))
4225 (cons label (cons (cons jump-label pos) tree)))))
4227 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
4228 "Recursively build the tree of nested definitions of a node.
4229 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4230 not be passed explicitly unless you know what you are doing."
4231 (setq min-indent (or min-indent 0)
4232 prev-indent (or prev-indent python-indent-offset))
4233 (let* ((pos (python-nav-backward-defun))
4235 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
4236 (let ((split (split-string (match-string-no-properties 0))))
4237 (setq type (car split))
4240 (funcall python-imenu-format-item-label-function type name)))
4241 (indent (current-indentation))
4242 (children-indent-limit (+ python-indent-offset min-indent)))
4244 ;; Nothing found, probably near to bobp.
4246 ((<= indent min-indent)
4247 ;; The current indentation points that this is a parent
4248 ;; node, add it to the tree and stop recursing.
4249 (python-imenu--put-parent type name pos tree))
4251 (python-imenu--build-tree
4254 (if (<= indent children-indent-limit)
4255 ;; This lies within the children indent offset range,
4256 ;; so it's a normal child of its parent (i.e., not
4257 ;; a child of a child).
4258 (cons (cons label pos) tree)
4259 ;; Oh no, a child of a child?! Fear not, we
4260 ;; know how to roll. We recursively parse these by
4261 ;; swapping prev-indent and min-indent plus adding this
4262 ;; newly found item to a fresh subtree. This works, I
4265 (python-imenu--build-tree
4266 prev-indent indent (list (cons label pos)))
4269 (defun python-imenu-create-index ()
4270 "Return tree Imenu alist for the current Python buffer.
4271 Change `python-imenu-format-item-label-function',
4272 `python-imenu-format-parent-item-label-function',
4273 `python-imenu-format-parent-item-jump-label-function' to
4274 customize how labels are formatted."
4275 (goto-char (point-max))
4278 (while (setq tree (python-imenu--build-tree))
4279 (setq index (cons tree index)))
4282 (defun python-imenu-create-flat-index (&optional alist prefix)
4283 "Return flat outline of the current Python buffer for Imenu.
4284 Optional argument ALIST is the tree to be flattened; when nil
4285 `python-imenu-build-index' is used with
4286 `python-imenu-format-parent-item-jump-label-function'
4287 `python-imenu-format-parent-item-label-function'
4288 `python-imenu-format-item-label-function' set to
4289 (lambda (type name) name)
4290 Optional argument PREFIX is used in recursive calls and should
4291 not be passed explicitly.
4298 (\"decorator\" . 173)
4301 (\"wrapped_f\" . 393))))
4307 (\"decorator\" . 173)
4308 (\"decorator.wrap\" . 353)
4309 (\"decorator.wrapped_f\" . 393))"
4310 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4315 (let ((name (if prefix
4316 (concat prefix "." (car item))
4319 (cond ((or (numberp pos) (markerp pos))
4320 (list (cons name pos)))
4323 (cons name (cdar pos))
4324 (python-imenu-create-flat-index (cddr item) name))))))
4326 (let* ((fn (lambda (_type name) name))
4327 (python-imenu-format-item-label-function fn)
4328 (python-imenu-format-parent-item-label-function fn)
4329 (python-imenu-format-parent-item-jump-label-function fn))
4330 (python-imenu-create-index))))))
4335 (defun python-info-current-defun (&optional include-type)
4336 "Return name of surrounding function with Python compatible dotty syntax.
4337 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4338 This function can be used as the value of `add-log-current-defun-function'
4339 since it returns nil if point is not inside a defun."
4345 (starting-indentation (current-indentation))
4346 (starting-pos (point))
4351 (while (python-nav-beginning-of-defun 1)
4352 (when (save-match-data
4354 (or (not last-indent)
4355 (< (current-indentation) last-indent))
4359 ;; If this is the first run, we may add
4360 ;; the current defun at point.
4361 (setq first-run nil)
4362 (goto-char starting-pos)
4363 (python-nav-beginning-of-statement)
4364 (beginning-of-line 1)
4366 python-nav-beginning-of-defun-regexp)))
4370 (+ (current-indentation)
4371 python-indent-offset)))
4372 (if (< starting-indentation min-indent)
4373 ;; If the starting indentation is not
4374 ;; within the min defun indent make the
4377 ;; Else go to the end of defun and add
4378 ;; up the current indentation to the
4380 (python-nav-end-of-defun)
4382 (if (>= (current-indentation) min-indent)
4383 (1+ (current-indentation))
4385 (save-match-data (setq last-indent (current-indentation)))
4386 (if (or (not include-type) type)
4387 (setq names (cons (match-string-no-properties 1) names))
4388 (let ((match (split-string (match-string-no-properties 0))))
4389 (setq type (car match))
4390 (setq names (cons (cadr match) names)))))
4391 ;; Stop searching ASAP.
4392 (and (= (current-indentation) 0) (throw 'exit t))))
4394 (concat (and type (format "%s " type))
4395 (mapconcat 'identity names ".")))))))
4397 (defun python-info-current-symbol (&optional replace-self)
4398 "Return current symbol using dotty syntax.
4399 With optional argument REPLACE-SELF convert \"self\" to current
4402 (and (not (python-syntax-comment-or-string-p))
4403 (with-syntax-table python-dotty-syntax-table
4404 (let ((sym (symbol-at-point)))
4406 (substring-no-properties (symbol-name sym))))))))
4408 (if (not replace-self)
4410 (let ((current-defun (python-info-current-defun)))
4411 (if (not current-defun)
4413 (replace-regexp-in-string
4414 (python-rx line-start word-start "self" word-end ?.)
4416 (mapconcat 'identity
4417 (butlast (split-string current-defun "\\."))
4421 (defun python-info-statement-starts-block-p ()
4422 "Return non-nil if current statement opens a block."
4424 (python-nav-beginning-of-statement)
4425 (looking-at (python-rx block-start))))
4427 (defun python-info-statement-ends-block-p ()
4428 "Return non-nil if point is at end of block."
4429 (let ((end-of-block-pos (save-excursion
4430 (python-nav-end-of-block)))
4431 (end-of-statement-pos (save-excursion
4432 (python-nav-end-of-statement))))
4433 (and end-of-block-pos end-of-statement-pos
4434 (= end-of-block-pos end-of-statement-pos))))
4436 (defun python-info-beginning-of-statement-p ()
4437 "Return non-nil if point is at beginning of statement."
4438 (= (point) (save-excursion
4439 (python-nav-beginning-of-statement)
4442 (defun python-info-end-of-statement-p ()
4443 "Return non-nil if point is at end of statement."
4444 (= (point) (save-excursion
4445 (python-nav-end-of-statement)
4448 (defun python-info-beginning-of-block-p ()
4449 "Return non-nil if point is at beginning of block."
4450 (and (python-info-beginning-of-statement-p)
4451 (python-info-statement-starts-block-p)))
4453 (defun python-info-end-of-block-p ()
4454 "Return non-nil if point is at end of block."
4455 (and (python-info-end-of-statement-p)
4456 (python-info-statement-ends-block-p)))
4458 (define-obsolete-function-alias
4459 'python-info-closing-block
4460 'python-info-dedenter-opening-block-position "24.4")
4462 (defun python-info-dedenter-opening-block-position ()
4463 "Return the point of the closest block the current line closes.
4464 Returns nil if point is not on a dedenter statement or no opening
4465 block can be detected. The latter case meaning current file is
4466 likely an invalid python file."
4467 (let ((positions (python-info-dedenter-opening-block-positions))
4468 (indentation (current-indentation))
4470 (while (and (not position)
4473 (goto-char (car positions))
4474 (if (<= (current-indentation) indentation)
4475 (setq position (car positions))
4476 (setq positions (cdr positions)))))
4479 (defun python-info-dedenter-opening-block-positions ()
4480 "Return points of blocks the current line may close sorted by closer.
4481 Returns nil if point is not on a dedenter statement or no opening
4482 block can be detected. The latter case meaning current file is
4483 likely an invalid python file."
4485 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4487 (goto-char dedenter-pos)
4488 (let* ((pairs '(("elif" "elif" "if")
4489 ("else" "if" "elif" "except" "for" "while")
4490 ("except" "except" "try")
4491 ("finally" "else" "except" "try")))
4492 (dedenter (match-string-no-properties 0))
4493 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
4494 (collected-indentations)
4497 (while (python-nav--syntactically
4499 (re-search-backward (python-rx block-start) nil t))
4501 (let ((indentation (current-indentation)))
4502 (when (and (not (memq indentation collected-indentations))
4503 (or (not collected-indentations)
4504 (< indentation (apply #'min collected-indentations))))
4505 (setq collected-indentations
4506 (cons indentation collected-indentations))
4507 (when (member (match-string-no-properties 0)
4508 possible-opening-blocks)
4509 (setq opening-blocks (cons (point) opening-blocks))))
4510 (when (zerop indentation)
4511 (throw 'exit nil)))))
4513 (nreverse opening-blocks))))))
4515 (define-obsolete-function-alias
4516 'python-info-closing-block-message
4517 'python-info-dedenter-opening-block-message "24.4")
4519 (defun python-info-dedenter-opening-block-message ()
4520 "Message the first line of the block the current statement closes."
4521 (let ((point (python-info-dedenter-opening-block-position)))
4525 (message "Closes %s" (save-excursion
4528 (point) (line-end-position))))))))
4530 (defun python-info-dedenter-statement-p ()
4531 "Return point if current statement is a dedenter.
4532 Sets `match-data' to the keyword that starts the dedenter
4535 (python-nav-beginning-of-statement)
4536 (when (and (not (python-syntax-context-type))
4537 (looking-at (python-rx dedenter)))
4540 (defun python-info-line-ends-backslash-p (&optional line-number)
4541 "Return non-nil if current line ends with backslash.
4542 With optional argument LINE-NUMBER, check that line instead."
4547 (python-util-goto-line line-number))
4548 (while (and (not (eobp))
4549 (goto-char (line-end-position))
4550 (python-syntax-context 'paren)
4551 (not (equal (char-before (point)) ?\\)))
4553 (when (equal (char-before) ?\\)
4556 (defun python-info-beginning-of-backslash (&optional line-number)
4557 "Return the point where the backslashed line start.
4558 Optional argument LINE-NUMBER forces the line number to check against."
4563 (python-util-goto-line line-number))
4564 (when (python-info-line-ends-backslash-p)
4565 (while (save-excursion
4566 (goto-char (line-beginning-position))
4567 (python-syntax-context 'paren))
4569 (back-to-indentation)
4572 (defun python-info-continuation-line-p ()
4573 "Check if current line is continuation of another.
4574 When current line is continuation of another return the point
4575 where the continued line ends."
4579 (let* ((context-type (progn
4580 (back-to-indentation)
4581 (python-syntax-context-type)))
4582 (line-start (line-number-at-pos))
4583 (context-start (when context-type
4584 (python-syntax-context context-type))))
4585 (cond ((equal context-type 'paren)
4586 ;; Lines inside a paren are always a continuation line
4587 ;; (except the first one).
4588 (python-util-forward-comment -1)
4590 ((member context-type '(string comment))
4591 ;; move forward an roll again
4592 (goto-char context-start)
4593 (python-util-forward-comment)
4594 (python-info-continuation-line-p))
4596 ;; Not within a paren, string or comment, the only way
4597 ;; we are dealing with a continuation line is that
4598 ;; previous line contains a backslash, and this can
4599 ;; only be the previous line from current
4600 (back-to-indentation)
4601 (python-util-forward-comment -1)
4602 (when (and (equal (1- line-start) (line-number-at-pos))
4603 (python-info-line-ends-backslash-p))
4604 (point-marker))))))))
4606 (defun python-info-block-continuation-line-p ()
4607 "Return non-nil if current line is a continuation of a block."
4609 (when (python-info-continuation-line-p)
4611 (back-to-indentation)
4612 (when (looking-at (python-rx block-start))
4615 (defun python-info-assignment-statement-p (&optional current-line-only)
4616 "Check if current line is an assignment.
4617 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4618 continuations, just check the if current line is an assignment."
4621 (if current-line-only
4622 (back-to-indentation)
4623 (python-nav-beginning-of-statement))
4625 (re-search-forward (python-rx not-simple-operator
4627 (group not-simple-operator))
4628 (line-end-position) t)
4631 ;; The assignment operator should not be inside a string.
4632 (backward-char (length (match-string-no-properties 1)))
4633 (setq found (not (python-syntax-context-type)))))
4635 (skip-syntax-forward " ")
4638 ;; TODO: rename to clarify this is only for the first continuation
4639 ;; line or remove it and move its body to `python-indent-context'.
4640 (defun python-info-assignment-continuation-line-p ()
4641 "Check if current line is the first continuation of an assignment.
4642 When current line is continuation of another with an assignment
4643 return the point of the first non-blank character after the
4646 (when (python-info-continuation-line-p)
4648 (python-info-assignment-statement-p t))))
4650 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4651 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4652 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4654 (beginning-of-line 1)
4655 (looking-at python-nav-beginning-of-defun-regexp))))
4657 (defun python-info-current-line-comment-p ()
4658 "Return non-nil if current line is a comment line."
4660 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4663 (defun python-info-current-line-empty-p ()
4664 "Return non-nil if current line is empty, ignoring whitespace."
4666 (beginning-of-line 1)
4668 (python-rx line-start (* whitespace)
4669 (group (* not-newline))
4670 (* whitespace) line-end))
4671 (string-equal "" (match-string-no-properties 1))))
4673 (defun python-info-docstring-p (&optional syntax-ppss)
4674 "Return non-nil if point is in a docstring.
4675 When optional argument SYNTAX-PPSS is given, use that instead of
4676 point's current `syntax-ppss'."
4677 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4679 (when (and syntax-ppss (python-syntax-context 'string syntax-ppss))
4680 (goto-char (nth 8 syntax-ppss)))
4681 (python-nav-beginning-of-statement)
4683 (indentation (current-indentation))
4684 (backward-sexp-point)
4685 (re (concat "[uU]?[rR]?"
4686 (python-rx string-delimiter))))
4688 (not (python-info-assignment-statement-p))
4690 ;; Allow up to two consecutive docstrings only.
4694 (while (save-excursion
4695 (python-nav-backward-sexp)
4696 (setq backward-sexp-point (point))
4697 (and (= indentation (current-indentation))
4698 (not (bobp)) ; Prevent infloop.
4700 (concat "[uU]?[rR]?"
4701 (python-rx string-delimiter)))))
4702 ;; Previous sexp was a string, restore point.
4703 (goto-char backward-sexp-point)
4706 (python-util-forward-comment -1)
4707 (python-nav-beginning-of-statement)
4709 ((python-info-assignment-statement-p) t)
4710 ((python-info-looking-at-beginning-of-defun))
4713 (defun python-info-encoding-from-cookie ()
4714 "Detect current buffer's encoding from its coding cookie.
4715 Returns the encoding as a symbol."
4716 (let ((first-two-lines
4720 (goto-char (point-min))
4722 (buffer-substring-no-properties
4725 (when (string-match (python-rx coding-cookie) first-two-lines)
4726 (intern (match-string-no-properties 1 first-two-lines)))))
4728 (defun python-info-encoding ()
4729 "Return encoding for file.
4730 Try `python-info-encoding-from-cookie', if none is found then
4732 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4733 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4734 ;; in the worst case scenario python.el will make things work for
4735 ;; Python 2 files with unicode data and no encoding defined.
4736 (or (python-info-encoding-from-cookie)
4740 ;;; Utility functions
4742 (defun python-util-goto-line (line-number)
4743 "Move point to LINE-NUMBER."
4744 (goto-char (point-min))
4745 (forward-line (1- line-number)))
4747 ;; Stolen from org-mode
4748 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4749 "Clone local variables from FROM-BUFFER.
4750 Optional argument REGEXP selects variables to clone and defaults
4754 (and (symbolp (car pair))
4755 (string-match (or regexp "^python-")
4756 (symbol-name (car pair)))
4757 (set (make-local-variable (car pair))
4759 (buffer-local-variables from-buffer)))
4761 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4763 (defun python-util-comint-last-prompt ()
4764 "Return comint last prompt overlay start and end.
4765 This is for compatibility with Emacs < 24.4."
4766 (cond ((bound-and-true-p comint-last-prompt-overlay)
4767 (cons (overlay-start comint-last-prompt-overlay)
4768 (overlay-end comint-last-prompt-overlay)))
4769 ((bound-and-true-p comint-last-prompt)
4773 (defun python-util-forward-comment (&optional direction)
4774 "Python mode specific version of `forward-comment'.
4775 Optional argument DIRECTION defines the direction to move to."
4776 (let ((comment-start (python-syntax-context 'comment))
4777 (factor (if (< (or direction 0) 0)
4781 (goto-char comment-start))
4782 (forward-comment factor)))
4784 (defun python-util-list-directories (directory &optional predicate max-depth)
4785 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4786 Argument PREDICATE defaults to `identity' and must be a function
4787 that takes one argument (a full path) and returns non-nil for
4788 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4789 searching when depth is reached, else don't limit."
4790 (let* ((dir (expand-file-name directory))
4791 (dir-length (length dir))
4792 (predicate (or predicate #'identity))
4793 (to-scan (list dir))
4796 (let ((current-dir (car to-scan)))
4797 (when (funcall predicate current-dir)
4798 (setq tally (cons current-dir tally)))
4799 (setq to-scan (append (cdr to-scan)
4800 (python-util-list-files
4801 current-dir #'file-directory-p)
4803 (when (and max-depth
4805 (length (split-string
4806 (substring current-dir dir-length)
4808 (setq to-scan nil))))
4811 (defun python-util-list-files (dir &optional predicate)
4812 "List files in DIR, filtering with PREDICATE.
4813 Argument PREDICATE defaults to `identity' and must be a function
4814 that takes one argument (a full path) and returns non-nil for
4816 (let ((dir-name (file-name-as-directory dir)))
4818 (mapcar (lambda (file-name)
4819 (let ((full-file-name (expand-file-name file-name dir-name)))
4821 (not (member file-name '("." "..")))
4822 (funcall (or predicate #'identity) full-file-name))
4823 (list full-file-name))))
4824 (directory-files dir-name)))))
4826 (defun python-util-list-packages (dir &optional max-depth)
4827 "List packages in DIR, limited by MAX-DEPTH.
4828 When optional argument MAX-DEPTH is non-nil, stop searching when
4829 depth is reached, else don't limit."
4830 (let* ((dir (expand-file-name dir))
4831 (parent-dir (file-name-directory
4832 (directory-file-name
4833 (file-name-directory
4834 (file-name-as-directory dir)))))
4835 (subpath-length (length parent-dir)))
4838 (replace-regexp-in-string
4839 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4840 (python-util-list-directories
4841 (directory-file-name dir)
4843 (file-exists-p (expand-file-name "__init__.py" dir)))
4846 (defun python-util-popn (lst n)
4847 "Return LST first N elements.
4848 N should be an integer, when negative its opposite is used.
4849 When N is bigger than the length of LST, the list is
4851 (let* ((n (min (abs n)))
4857 (setq acc (cons (car lst) acc)
4862 (defun python-util-strip-string (string)
4863 "Strip STRING whitespace and newlines from end and beginning."
4864 (replace-regexp-in-string
4865 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4866 (: (* (any whitespace ?\r ?\n)) string-end)))
4870 (defun python-util-valid-regexp-p (regexp)
4871 "Return non-nil if REGEXP is valid."
4872 (ignore-errors (string-match regexp "") t))
4875 (defun python-electric-pair-string-delimiter ()
4876 (when (and electric-pair-mode
4877 (memq last-command-event '(?\" ?\'))
4879 (while (eq (char-before (- (point) count)) last-command-event)
4882 (eq (char-after) last-command-event))
4883 (save-excursion (insert (make-string 2 last-command-event)))))
4885 (defvar electric-indent-inhibit)
4888 (define-derived-mode python-mode prog-mode "Python"
4889 "Major mode for editing Python files.
4891 \\{python-mode-map}"
4892 (set (make-local-variable 'tab-width) 8)
4893 (set (make-local-variable 'indent-tabs-mode) nil)
4895 (set (make-local-variable 'comment-start) "# ")
4896 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4898 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4899 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4901 (set (make-local-variable 'forward-sexp-function)
4902 'python-nav-forward-sexp)
4904 (set (make-local-variable 'font-lock-defaults)
4905 '(python-font-lock-keywords
4907 (font-lock-syntactic-face-function
4908 . python-font-lock-syntactic-face-function)))
4910 (set (make-local-variable 'syntax-propertize-function)
4911 python-syntax-propertize-function)
4913 (set (make-local-variable 'indent-line-function)
4914 #'python-indent-line-function)
4915 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4916 ;; Because indentation is not redundant, we cannot safely reindent code.
4917 (set (make-local-variable 'electric-indent-inhibit) t)
4918 (set (make-local-variable 'electric-indent-chars)
4919 (cons ?: electric-indent-chars))
4921 ;; Add """ ... """ pairing to electric-pair-mode.
4922 (add-hook 'post-self-insert-hook
4923 #'python-electric-pair-string-delimiter 'append t)
4925 (set (make-local-variable 'paragraph-start) "\\s-*$")
4926 (set (make-local-variable 'fill-paragraph-function)
4927 #'python-fill-paragraph)
4929 (set (make-local-variable 'beginning-of-defun-function)
4930 #'python-nav-beginning-of-defun)
4931 (set (make-local-variable 'end-of-defun-function)
4932 #'python-nav-end-of-defun)
4934 (add-hook 'completion-at-point-functions
4935 #'python-completion-at-point nil 'local)
4937 (add-hook 'post-self-insert-hook
4938 #'python-indent-post-self-insert-function 'append 'local)
4940 (set (make-local-variable 'imenu-create-index-function)
4941 #'python-imenu-create-index)
4943 (set (make-local-variable 'add-log-current-defun-function)
4944 #'python-info-current-defun)
4946 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4948 (set (make-local-variable 'skeleton-further-elements)
4950 (< '(backward-delete-char-untabify (min python-indent-offset
4952 (^ '(- (1+ (current-indentation))))))
4954 (if (null eldoc-documentation-function)
4956 (set (make-local-variable 'eldoc-documentation-function)
4957 #'python-eldoc-function)
4958 (add-function :before-until (local 'eldoc-documentation-function)
4959 #'python-eldoc-function))
4962 'hs-special-modes-alist
4964 "\\s-*\\(?:def\\|class\\)\\>"
4965 ;; Use the empty string as end regexp so it doesn't default to
4966 ;; "\\s)". This way parens at end of defun are properly hidden.
4969 python-hideshow-forward-sexp-function
4972 (set (make-local-variable 'outline-regexp)
4973 (python-rx (* space) block-start))
4974 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4975 (set (make-local-variable 'outline-level)
4977 "`outline-level' function for Python mode."
4978 (1+ (/ (current-indentation) python-indent-offset))))
4980 (python-skeleton-add-menu-items)
4982 (make-local-variable 'python-shell-internal-buffer)
4984 (when python-indent-guess-indent-offset
4985 (python-indent-guess-indent-offset)))
4992 ;; indent-tabs-mode: nil
4995 ;;; python.el ends here