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 syntax highlighting: when enabled current input in shell is
184 ;; highlighted. The variable `python-shell-font-lock-enable' controls
185 ;; activation of this feature globally when shells are started.
186 ;; Activation/deactivation can be also controlled on the fly via the
187 ;; `python-shell-font-lock-toggle' command.
189 ;; Pdb tracking: when you execute a block of code that contains some
190 ;; call to pdb (or ipdb) it will prompt the block of code and will
191 ;; follow the execution of pdb marking the current line with an arrow.
193 ;; Symbol completion: you can complete the symbol at point. It uses
194 ;; the shell completion in background so you should run
195 ;; `python-shell-send-buffer' from time to time to get better results.
197 ;; Skeletons: skeletons are provided for simple inserting of things like class,
198 ;; def, for, import, if, try, and while. These skeletons are
199 ;; integrated with abbrev. If you have `abbrev-mode' activated and
200 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
201 ;; the name of any of those defined and hit SPC, they will be
202 ;; automatically expanded. As an alternative you can use the defined
203 ;; skeleton commands: `python-skeleton-<foo>'.
205 ;; FFAP: You can find the filename for a given module when using ffap
206 ;; out of the box. This feature needs an inferior python shell
209 ;; Code check: Check the current file for errors with `python-check'
210 ;; using the program defined in `python-check-command'.
212 ;; Eldoc: returns documentation for object at point by using the
213 ;; inferior python subprocess to inspect its documentation. As you
214 ;; might guessed you should run `python-shell-send-buffer' from time
215 ;; to time to get better results too.
217 ;; Imenu: There are two index building functions to be used as
218 ;; `imenu-create-index-function': `python-imenu-create-index' (the
219 ;; default one, builds the alist in form of a tree) and
220 ;; `python-imenu-create-flat-index'. See also
221 ;; `python-imenu-format-item-label-function',
222 ;; `python-imenu-format-parent-item-label-function',
223 ;; `python-imenu-format-parent-item-jump-label-function' variables for
224 ;; changing the way labels are formatted in the tree version.
226 ;; If you used python-mode.el you may miss auto-indentation when
227 ;; inserting newlines. To achieve the same behavior you have two
230 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
231 ;; default) and use RET. If this mode is disabled use
232 ;; `newline-and-indent', bound to C-j.
234 ;; 2) Add the following hook in your .emacs:
236 ;; (add-hook 'python-mode-hook
238 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
240 ;; I'd recommend the first one since you'll get the same behavior for
241 ;; all modes out-of-the-box.
245 ;; Add this to your .emacs:
247 ;; (add-to-list 'load-path "/folder/containing/file")
254 (require 'ansi-color)
259 ;; Avoid compiler warnings
260 (defvar view-return-to-alist)
261 (defvar compilation-error-regexp-alist)
262 (defvar outline-heading-end-regexp)
264 (autoload 'comint-mode "comint")
265 (autoload 'help-function-arglist "help-fns")
268 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
270 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
273 "Python Language's flying circus support for Emacs."
276 :link '(emacs-commentary-link "python"))
281 (defvar python-mode-map
282 (let ((map (make-sparse-keymap)))
284 (define-key map [remap backward-sentence] 'python-nav-backward-block)
285 (define-key map [remap forward-sentence] 'python-nav-forward-block)
286 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
287 (define-key map [remap mark-defun] 'python-mark-defun)
288 (define-key map "\C-c\C-j" 'imenu)
290 (define-key map "\177" 'python-indent-dedent-line-backspace)
291 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
292 (define-key map "\C-c<" 'python-indent-shift-left)
293 (define-key map "\C-c>" 'python-indent-shift-right)
295 (define-key map "\C-c\C-tc" 'python-skeleton-class)
296 (define-key map "\C-c\C-td" 'python-skeleton-def)
297 (define-key map "\C-c\C-tf" 'python-skeleton-for)
298 (define-key map "\C-c\C-ti" 'python-skeleton-if)
299 (define-key map "\C-c\C-tm" 'python-skeleton-import)
300 (define-key map "\C-c\C-tt" 'python-skeleton-try)
301 (define-key map "\C-c\C-tw" 'python-skeleton-while)
303 (define-key map "\C-c\C-p" 'run-python)
304 (define-key map "\C-c\C-s" 'python-shell-send-string)
305 (define-key map "\C-c\C-r" 'python-shell-send-region)
306 (define-key map "\C-\M-x" 'python-shell-send-defun)
307 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
308 (define-key map "\C-c\C-l" 'python-shell-send-file)
309 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
310 ;; Some util commands
311 (define-key map "\C-c\C-v" 'python-check)
312 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
314 (substitute-key-definition 'complete-symbol 'completion-at-point
316 (easy-menu-define python-menu map "Python Mode menu"
318 :help "Python-specific Features"
319 ["Shift region left" python-indent-shift-left :active mark-active
320 :help "Shift region left by a single indentation step"]
321 ["Shift region right" python-indent-shift-right :active mark-active
322 :help "Shift region right by a single indentation step"]
324 ["Start of def/class" beginning-of-defun
325 :help "Go to start of outermost definition around point"]
326 ["End of def/class" end-of-defun
327 :help "Go to end of definition around point"]
328 ["Mark def/class" mark-defun
329 :help "Mark outermost definition around point"]
330 ["Jump to def/class" imenu
331 :help "Jump to a class or function definition"]
335 ["Start interpreter" run-python
336 :help "Run inferior Python process in a separate buffer"]
337 ["Switch to shell" python-shell-switch-to-shell
338 :help "Switch to running inferior Python process"]
339 ["Eval string" python-shell-send-string
340 :help "Eval string in inferior Python session"]
341 ["Eval buffer" python-shell-send-buffer
342 :help "Eval buffer in inferior Python session"]
343 ["Eval region" python-shell-send-region
344 :help "Eval region in inferior Python session"]
345 ["Eval defun" python-shell-send-defun
346 :help "Eval defun in inferior Python session"]
347 ["Eval file" python-shell-send-file
348 :help "Eval file in inferior Python session"]
349 ["Debugger" pdb :help "Run pdb under GUD"]
351 ["Check file" python-check
352 :help "Check file for errors"]
353 ["Help on symbol" python-eldoc-at-point
354 :help "Get help on symbol at point"]
355 ["Complete symbol" completion-at-point
356 :help "Complete symbol before point"]))
358 "Keymap for `python-mode'.")
361 ;;; Python specialized rx
364 (defconst python-rx-constituents
365 `((block-start . ,(rx symbol-start
366 (or "def" "class" "if" "elif" "else" "try"
367 "except" "finally" "for" "while" "with")
369 (dedenter . ,(rx symbol-start
370 (or "elif" "else" "except" "finally")
372 (block-ender . ,(rx symbol-start
374 "break" "continue" "pass" "raise" "return")
376 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
378 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
379 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
380 (+ space) "==" (+ space)
381 (any ?' ?\") "__main__" (any ?' ?\")
383 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
384 (open-paren . ,(rx (or "{" "[" "(")))
385 (close-paren . ,(rx (or "}" "]" ")")))
386 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
387 ;; FIXME: rx should support (not simple-operator).
388 (not-simple-operator . ,(rx
390 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
391 ;; FIXME: Use regexp-opt.
392 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
393 "=" "%" "**" "//" "<<" ">>" "<=" "!="
394 "==" ">=" "is" "not")))
395 ;; FIXME: Use regexp-opt.
396 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
397 ">>=" "<<=" "&=" "^=" "|=")))
398 (string-delimiter . ,(rx (and
399 ;; Match even number of backslashes.
400 (or (not (any ?\\ ?\' ?\")) point
401 ;; Quotes might be preceded by a escaped quote.
402 (and (or (not (any ?\\)) point) ?\\
403 (* ?\\ ?\\) (any ?\' ?\")))
405 ;; Match single or triple quotes of any kind.
406 (group (or "\"" "\"\"\"" "'" "'''")))))
407 (coding-cookie . ,(rx line-start ?# (* space)
409 ;; # coding=<encoding name>
410 (: "coding" (or ?: ?=) (* space) (group-n 1 (+ (or word ?-))))
411 ;; # -*- coding: <encoding name> -*-
412 (: "-*-" (* space) "coding:" (* space)
413 (group-n 1 (+ (or word ?-))) (* space) "-*-")
414 ;; # vim: set fileencoding=<encoding name> :
415 (: "vim:" (* space) "set" (+ space)
416 "fileencoding" (* space) ?= (* space)
417 (group-n 1 (+ (or word ?-))) (* space) ":")))))
418 "Additional Python specific sexps for `python-rx'")
420 (defmacro python-rx (&rest regexps)
421 "Python mode specialized rx macro.
422 This variant of `rx' supports common Python named REGEXPS."
423 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
424 (cond ((null regexps)
427 (rx-to-string `(and ,@regexps) t))
429 (rx-to-string (car regexps) t))))))
432 ;;; Font-lock and syntax
435 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
438 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
439 (and (nth 4 ppss) (nth 8 ppss))))
441 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
442 (and (nth 3 ppss) (nth 8 ppss))))
444 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
447 (defun python-syntax-context (type &optional syntax-ppss)
448 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
449 TYPE can be `comment', `string' or `paren'. It returns the start
450 character address of the specified TYPE."
451 (declare (compiler-macro python-syntax--context-compiler-macro))
452 (let ((ppss (or syntax-ppss (syntax-ppss))))
454 (`comment (and (nth 4 ppss) (nth 8 ppss)))
455 (`string (and (nth 3 ppss) (nth 8 ppss)))
456 (`paren (nth 1 ppss))
459 (defun python-syntax-context-type (&optional syntax-ppss)
460 "Return the context type using SYNTAX-PPSS.
461 The type returned can be `comment', `string' or `paren'."
462 (let ((ppss (or syntax-ppss (syntax-ppss))))
464 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
465 ((nth 1 ppss) 'paren))))
467 (defsubst python-syntax-comment-or-string-p (&optional ppss)
468 "Return non-nil if PPSS is inside 'comment or 'string."
469 (nth 8 (or ppss (syntax-ppss))))
471 (defsubst python-syntax-closing-paren-p ()
472 "Return non-nil if char after point is a closing paren."
473 (= (syntax-class (syntax-after (point)))
474 (syntax-class (string-to-syntax ")"))))
476 (define-obsolete-function-alias
477 'python-info-ppss-context #'python-syntax-context "24.3")
479 (define-obsolete-function-alias
480 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
482 (define-obsolete-function-alias
483 'python-info-ppss-comment-or-string-p
484 #'python-syntax-comment-or-string-p "24.3")
486 (defun python-font-lock-syntactic-face-function (state)
487 "Return syntactic face given STATE."
489 (if (python-info-docstring-p state)
491 font-lock-string-face)
492 font-lock-comment-face))
494 (defvar python-font-lock-keywords
498 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
499 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
500 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
505 ;; False, None, and True are listed as keywords on the Python 3
506 ;; documentation, but since they also qualify as constants they are
507 ;; fontified like that in order to keep font-lock consistent between
514 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
515 (1 font-lock-function-name-face))
517 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
518 (1 font-lock-type-face))
522 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
523 ;; copyright, license, credits, quit and exit are added by the site
524 ;; module and they are not intended to be used in programs
525 "copyright" "credits" "exit" "license" "quit")
526 symbol-end) . font-lock-constant-face)
528 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
529 (0+ "." (1+ (or word ?_)))))
530 (1 font-lock-type-face))
531 ;; Builtin Exceptions
534 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
535 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
536 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
537 "ImportError" "ImportWarning" "IndexError" "KeyError"
538 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
539 "NotImplementedError" "OSError" "OverflowError"
540 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
541 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
542 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
543 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
544 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
545 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
549 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
551 symbol-end) . font-lock-type-face)
555 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
556 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
557 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
558 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
559 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
560 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
561 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
562 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
565 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
566 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
569 "ascii" "bytearray" "bytes" "exec"
571 "__all__" "__doc__" "__name__" "__package__")
572 symbol-end) . font-lock-builtin-face)
574 ;; support for a = b = c = 5
576 (let ((re (python-rx (group (+ (any word ?. ?_)))
577 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
578 assignment-operator))
580 (while (and (setq res (re-search-forward re limit t))
581 (or (python-syntax-context 'paren)
582 (equal (char-after (point)) ?=))))
584 (1 font-lock-variable-name-face nil nil))
585 ;; support for a, b, c = (1, 2, 3)
587 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
588 (* ?, (* space) (+ (any word ?. ?_)) (* space))
589 ?, (* space) (+ (any word ?. ?_)) (* space)
590 assignment-operator))
592 (while (and (setq res (re-search-forward re limit t))
593 (goto-char (match-end 1))
594 (python-syntax-context 'paren)))
596 (1 font-lock-variable-name-face nil nil))))
598 (defconst python-syntax-propertize-function
599 (syntax-propertize-rules
600 ((python-rx string-delimiter)
601 (0 (ignore (python-syntax-stringify))))))
603 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
604 "Count number of quotes around point (max is 3).
605 QUOTE-CHAR is the quote char to count. Optional argument POINT is
606 the point where scan starts (defaults to current point), and LIMIT
607 is used to limit the scan."
610 (or (not limit) (< (+ point i) limit))
611 (eq (char-after (+ point i)) quote-char))
615 (defun python-syntax-stringify ()
616 "Put `syntax-table' property correctly on single/triple quotes."
617 (let* ((num-quotes (length (match-string-no-properties 1)))
619 (backward-char num-quotes)
621 (forward-char num-quotes)))
622 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
623 (quote-starting-pos (- (point) num-quotes))
624 (quote-ending-pos (point))
627 (python-syntax-count-quotes
628 (char-before) string-start quote-starting-pos))))
629 (cond ((and string-start (= num-closing-quotes 0))
630 ;; This set of quotes doesn't match the string starting
634 ;; This set of quotes delimit the start of a string.
635 (put-text-property quote-starting-pos (1+ quote-starting-pos)
636 'syntax-table (string-to-syntax "|")))
637 ((= num-quotes num-closing-quotes)
638 ;; This set of quotes delimit the end of a string.
639 (put-text-property (1- quote-ending-pos) quote-ending-pos
640 'syntax-table (string-to-syntax "|")))
641 ((> num-quotes num-closing-quotes)
642 ;; This may only happen whenever a triple quote is closing
643 ;; a single quoted string. Add string delimiter syntax to
645 (put-text-property quote-starting-pos quote-ending-pos
646 'syntax-table (string-to-syntax "|"))))))
648 (defvar python-mode-syntax-table
649 (let ((table (make-syntax-table)))
650 ;; Give punctuation syntax to ASCII that normally has symbol
651 ;; syntax or has word syntax and isn't a letter.
652 (let ((symbol (string-to-syntax "_"))
653 (sst (standard-syntax-table)))
656 (if (equal symbol (aref sst i))
657 (modify-syntax-entry i "." table)))))
658 (modify-syntax-entry ?$ "." table)
659 (modify-syntax-entry ?% "." table)
661 (modify-syntax-entry ?# "<" table)
662 (modify-syntax-entry ?\n ">" table)
663 (modify-syntax-entry ?' "\"" table)
664 (modify-syntax-entry ?` "$" table)
666 "Syntax table for Python files.")
668 (defvar python-dotty-syntax-table
669 (let ((table (make-syntax-table python-mode-syntax-table)))
670 (modify-syntax-entry ?. "w" table)
671 (modify-syntax-entry ?_ "w" table)
673 "Dotty syntax table for Python files.
674 It makes underscores and dots word constituent chars.")
679 (defcustom python-indent-offset 4
680 "Default indentation offset for Python."
685 (defcustom python-indent-guess-indent-offset t
686 "Non-nil tells Python mode to guess `python-indent-offset' value."
691 (defcustom python-indent-guess-indent-offset-verbose t
692 "Non-nil means to emit a warning when indentation guessing fails."
697 (defcustom python-indent-trigger-commands
698 '(indent-for-tab-command yas-expand yas/expand)
699 "Commands that might trigger a `python-indent-line' call."
700 :type '(repeat symbol)
703 (define-obsolete-variable-alias
704 'python-indent 'python-indent-offset "24.3")
706 (define-obsolete-variable-alias
707 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
709 (defvar python-indent-current-level 0
710 "Deprecated var available for compatibility.")
712 (defvar python-indent-levels '(0)
713 "Deprecated var available for compatibility.")
715 (make-obsolete-variable
716 'python-indent-current-level
717 "The indentation API changed to avoid global state.
718 The function `python-indent-calculate-levels' does not use it
719 anymore. If you were defadvising it and or depended on this
720 variable for indentation customizations, refactor your code to
721 work on `python-indent-calculate-indentation' instead."
724 (make-obsolete-variable
725 'python-indent-levels
726 "The indentation API changed to avoid global state.
727 The function `python-indent-calculate-levels' does not use it
728 anymore. If you were defadvising it and or depended on this
729 variable for indentation customizations, refactor your code to
730 work on `python-indent-calculate-indentation' instead."
733 (defun python-indent-guess-indent-offset ()
734 "Guess and set `python-indent-offset' for the current buffer."
739 (goto-char (point-min))
741 (while (and (not block-end)
743 (python-rx line-start block-start) nil t))
745 (not (python-syntax-context-type))
747 (goto-char (line-end-position))
748 (python-util-forward-comment -1)
749 (if (equal (char-before) ?:)
752 (when (python-info-block-continuation-line-p)
753 (while (and (python-info-continuation-line-p)
756 (python-util-forward-comment -1)
757 (when (equal (char-before) ?:)
759 (setq block-end (point-marker))))
762 (goto-char block-end)
763 (python-util-forward-comment)
764 (current-indentation))))
765 (if (and indentation (not (zerop indentation)))
766 (set (make-local-variable 'python-indent-offset) indentation)
767 (when python-indent-guess-indent-offset-verbose
768 (message "Can't guess python-indent-offset, using defaults: %s"
769 python-indent-offset))))))))
771 (defun python-indent-context ()
772 "Get information about the current indentation context.
773 Context is returned in a cons with the form (STATUS . START).
775 STATUS can be one of the following:
781 - Point is after a comment line.
782 - START is the position of the \"#\" character.
784 - Point is inside string.
785 - START is the position of the first quote that starts it.
787 - No possible indentation case matches.
788 - START is always zero.
791 - Fallback case when point is inside paren.
792 - START is the first non space char position *after* the open paren.
793 :inside-paren-at-closing-nested-paren
794 - Point is on a line that contains a nested paren closer.
795 - START is the position of the open paren it closes.
796 :inside-paren-at-closing-paren
797 - Point is on a line that contains a paren closer.
798 - START is the position of the open paren.
799 :inside-paren-newline-start
800 - Point is inside a paren with items starting in their own line.
801 - START is the position of the open paren.
802 :inside-paren-newline-start-from-block
803 - Point is inside a paren with items starting in their own line
805 - START is the position of the open paren.
808 - Fallback case when point is after backslash.
809 - START is the char after the position of the backslash.
810 :after-backslash-assignment-continuation
811 - Point is after a backslashed assignment.
812 - START is the char after the position of the backslash.
813 :after-backslash-block-continuation
814 - Point is after a backslashed block continuation.
815 - START is the char after the position of the backslash.
816 :after-backslash-dotted-continuation
817 - Point is after a backslashed dotted continuation. Previous
818 line must contain a dot to align with.
819 - START is the char after the position of the backslash.
820 :after-backslash-first-line
821 - First line following a backslashed continuation.
822 - START is the char after the position of the backslash.
825 - Point is after a line containing a block ender.
826 - START is the position where the ender starts.
828 - Point is after a line starting a block.
829 - START is the position where the block starts.
831 - Point is after a simple line.
832 - START is the position where the previous line starts.
833 :at-dedenter-block-start
834 - Point is on a line starting a dedenter block.
835 - START is the position where the dedenter block starts."
838 (let ((ppss (save-excursion
842 ;; Beginning of buffer.
843 ((= (line-number-at-pos) 1)
846 ((let ((start (python-syntax-context 'string ppss)))
848 (cons (if (python-info-docstring-p)
850 :inside-string) start))))
852 ((let* ((start (python-syntax-context 'paren ppss))
859 (= (line-number-at-pos)
861 (python-util-forward-comment)
862 (line-number-at-pos))))))))
865 ;; Current line only holds the closing paren.
867 (skip-syntax-forward " ")
868 (when (and (python-syntax-closing-paren-p)
871 (not (python-syntax-context 'paren))))
872 (cons :inside-paren-at-closing-paren start))))
873 ;; Current line only holds a closing paren for nested.
875 (back-to-indentation)
876 (python-syntax-closing-paren-p))
877 (cons :inside-paren-at-closing-nested-paren start))
878 ;; This line starts from a opening block in its own line.
884 (back-to-indentation)
885 (looking-at (python-rx block-start))))
887 :inside-paren-newline-start-from-block start))))
889 (cons :inside-paren-newline-start start))
891 (t (cons :inside-paren
893 (goto-char (1+ start))
894 (skip-syntax-forward "(" 1)
895 (skip-syntax-forward " ")
898 ((let ((start (when (not (python-syntax-comment-or-string-p ppss))
899 (python-info-line-ends-backslash-p
900 (1- (line-number-at-pos))))))
903 ;; Continuation of dotted expression.
905 (back-to-indentation)
906 (when (eq (char-after) ?\.)
907 ;; Move point back until it's not inside a paren.
911 (python-syntax-context 'paren))))
912 (goto-char (line-end-position))
913 (while (and (search-backward
914 "." (line-beginning-position) t)
915 (python-syntax-context-type)))
916 ;; Ensure previous statement has dot to align with.
917 (when (and (eq (char-after) ?\.)
918 (not (python-syntax-context-type)))
919 (cons :after-backslash-dotted-continuation (point))))))
920 ;; Continuation of block definition.
921 ((let ((block-continuation-start
922 (python-info-block-continuation-line-p)))
923 (when block-continuation-start
925 (goto-char block-continuation-start)
927 (python-rx block-start (* space))
928 (line-end-position) t)
929 (cons :after-backslash-block-continuation (point))))))
930 ;; Continuation of assignment.
931 ((let ((assignment-continuation-start
932 (python-info-assignment-continuation-line-p)))
933 (when assignment-continuation-start
935 (goto-char assignment-continuation-start)
936 (cons :after-backslash-assignment-continuation (point))))))
937 ;; First line after backslash continuation start.
940 (when (or (= (line-number-at-pos) 1)
941 (not (python-info-beginning-of-backslash
942 (1- (line-number-at-pos)))))
943 (cons :after-backslash-first-line start))))
945 (t (cons :after-backslash start))))))
946 ;; After beginning of block.
947 ((let ((start (save-excursion
948 (back-to-indentation)
949 (python-util-forward-comment -1)
950 (when (equal (char-before) ?:)
951 (python-nav-beginning-of-block)))))
953 (cons :after-block-start start))))
954 ;; At dedenter statement.
955 ((let ((start (python-info-dedenter-statement-p)))
957 (cons :at-dedenter-block-start start))))
958 ;; After normal line, comment or ender (default case).
960 (back-to-indentation)
961 (skip-chars-backward " \t\n")
964 (python-nav-beginning-of-statement)
966 (cond ((python-info-current-line-comment-p)
969 (goto-char (line-end-position))
970 (python-util-forward-comment -1)
971 (python-nav-beginning-of-statement)
972 (looking-at (python-rx block-ender)))
977 (defun python-indent--calculate-indentation ()
978 "Internal implementation of `python-indent-calculate-indentation'.
979 May return an integer for the maximum possible indentation at
980 current context or a list of integers. The latter case is only
981 happening for :at-dedenter-block-start context since the
982 possibilities can be narrowed to specific indentation points."
986 (pcase (python-indent-context)
987 (`(:no-indent . ,_) (prog-first-column)) ; usually 0
992 :inside-paren-at-closing-paren
993 :inside-paren-at-closing-nested-paren) . ,start)
994 ;; Copy previous indentation.
996 (current-indentation))
997 (`(:inside-docstring . ,start)
998 (let* ((line-indentation (current-indentation))
1001 (current-indentation))))
1002 (max line-indentation base-indent)))
1003 (`(,(or :after-block-start
1004 :after-backslash-first-line
1005 :inside-paren-newline-start) . ,start)
1006 ;; Add one indentation level.
1008 (+ (current-indentation) python-indent-offset))
1009 (`(,(or :inside-paren
1010 :after-backslash-block-continuation
1011 :after-backslash-assignment-continuation
1012 :after-backslash-dotted-continuation) . ,start)
1013 ;; Use the column given by the context.
1016 (`(:after-block-end . ,start)
1017 ;; Subtract one indentation level.
1019 (- (current-indentation) python-indent-offset))
1020 (`(:at-dedenter-block-start . ,_)
1021 ;; List all possible indentation levels from opening blocks.
1022 (let ((opening-block-start-points
1023 (python-info-dedenter-opening-block-positions)))
1024 (if (not opening-block-start-points)
1025 (prog-first-column) ; if not found default to first column
1026 (mapcar (lambda (pos)
1029 (current-indentation)))
1030 opening-block-start-points))))
1031 (`(,(or :inside-paren-newline-start-from-block) . ,start)
1032 ;; Add two indentation levels to make the suite stand out.
1034 (+ (current-indentation) (* python-indent-offset 2)))))))
1036 (defun python-indent--calculate-levels (indentation)
1037 "Calculate levels list given INDENTATION.
1038 Argument INDENTATION can either be an integer or a list of
1039 integers. Levels are returned in ascending order, and in the
1040 case INDENTATION is a list, this order is enforced."
1041 (if (listp indentation)
1042 (sort (copy-sequence indentation) #'<)
1043 (nconc (number-sequence (prog-first-column) (1- indentation)
1044 python-indent-offset)
1045 (list indentation))))
1047 (defun python-indent--previous-level (levels indentation)
1048 "Return previous level from LEVELS relative to INDENTATION."
1049 (let* ((levels (sort (copy-sequence levels) #'>))
1050 (default (car levels)))
1052 (dolist (level levels)
1053 (when (funcall #'< level indentation)
1054 (throw 'return level)))
1057 (defun python-indent-calculate-indentation (&optional previous)
1058 "Calculate indentation.
1059 Get indentation of PREVIOUS level when argument is non-nil.
1060 Return the max level of the cycle when indentation reaches the
1062 (let* ((indentation (python-indent--calculate-indentation))
1063 (levels (python-indent--calculate-levels indentation)))
1065 (python-indent--previous-level levels (current-indentation))
1067 (apply #'max levels)
1068 (prog-first-column)))))
1070 (defun python-indent-line (&optional previous)
1071 "Internal implementation of `python-indent-line-function'.
1072 Use the PREVIOUS level when argument is non-nil, otherwise indent
1073 to the maximum available level. When indentation is the minimum
1074 possible and PREVIOUS is non-nil, cycle back to the maximum
1076 (let ((follow-indentation-p
1077 ;; Check if point is within indentation.
1078 (and (<= (line-beginning-position) (point))
1079 (>= (+ (line-beginning-position)
1080 (current-indentation))
1084 (python-indent-calculate-indentation previous))
1085 (python-info-dedenter-opening-block-message))
1086 (when follow-indentation-p
1087 (back-to-indentation))))
1089 (defun python-indent-calculate-levels ()
1090 "Return possible indentation levels."
1091 (python-indent--calculate-levels
1092 (python-indent--calculate-indentation)))
1094 (defun python-indent-line-function ()
1095 "`indent-line-function' for Python mode.
1096 When the variable `last-command' is equal to one of the symbols
1097 inside `python-indent-trigger-commands' it cycles possible
1098 indentation levels from right to left."
1100 (and (memq this-command python-indent-trigger-commands)
1101 (eq last-command this-command))))
1103 (defun python-indent-dedent-line ()
1104 "De-indent current line."
1106 (when (and (not (bolp))
1107 (not (python-syntax-comment-or-string-p))
1108 (= (current-indentation) (current-column)))
1109 (python-indent-line t)
1112 (defun python-indent-dedent-line-backspace (arg)
1113 "De-indent current line.
1114 Argument ARG is passed to `backward-delete-char-untabify' when
1115 point is not in between the indentation."
1117 (unless (python-indent-dedent-line)
1118 (backward-delete-char-untabify arg)))
1120 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1122 (defun python-indent-region (start end)
1123 "Indent a Python region automagically.
1125 Called from a program, START and END specify the region to indent."
1126 (let ((deactivate-mark nil))
1129 (setq end (point-marker))
1131 (or (bolp) (forward-line 1))
1132 (while (< (point) end)
1133 (or (and (bolp) (eolp))
1135 ;; Skip if previous line is empty or a comment.
1137 (let ((line-is-comment-p
1138 (python-info-current-line-comment-p)))
1141 (or (and (python-info-current-line-comment-p)
1142 ;; Unless this line is a comment too.
1143 (not line-is-comment-p))
1144 (python-info-current-line-empty-p)))))
1145 ;; Don't mess with strings, unless it's the
1146 ;; enclosing set of quotes or a docstring.
1147 (or (not (python-syntax-context 'string))
1151 (current-indentation)
1152 (python-syntax-count-quotes (char-after) (point))))
1153 (string-to-syntax "|"))
1154 (python-info-docstring-p))
1155 ;; Skip if current line is a block start, a
1156 ;; dedenter or block ender.
1158 (back-to-indentation)
1161 (or block-start dedenter block-ender))))))
1162 (python-indent-line)))
1164 (move-marker end nil))))
1166 (defun python-indent-shift-left (start end &optional count)
1167 "Shift lines contained in region START END by COUNT columns to the left.
1168 COUNT defaults to `python-indent-offset'. If region isn't
1169 active, the current line is shifted. The shifted region includes
1170 the lines in which START and END lie. An error is signaled if
1171 any lines in the region are indented less than COUNT columns."
1174 (list (region-beginning) (region-end) current-prefix-arg)
1175 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1177 (setq count (prefix-numeric-value count))
1178 (setq count python-indent-offset))
1180 (let ((deactivate-mark nil))
1183 (while (< (point) end)
1184 (if (and (< (current-indentation) count)
1185 (not (looking-at "[ \t]*$")))
1186 (user-error "Can't shift all lines enough"))
1188 (indent-rigidly start end (- count))))))
1190 (defun python-indent-shift-right (start end &optional count)
1191 "Shift lines contained in region START END by COUNT columns to the right.
1192 COUNT defaults to `python-indent-offset'. If region isn't
1193 active, the current line is shifted. The shifted region includes
1194 the lines in which START and END lie."
1197 (list (region-beginning) (region-end) current-prefix-arg)
1198 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1199 (let ((deactivate-mark nil))
1200 (setq count (if count (prefix-numeric-value count)
1201 python-indent-offset))
1202 (indent-rigidly start end count)))
1204 (defun python-indent-post-self-insert-function ()
1205 "Adjust indentation after insertion of some characters.
1206 This function is intended to be added to `post-self-insert-hook.'
1207 If a line renders a paren alone, after adding a char before it,
1208 the line will be re-indented automatically if needed."
1209 (when (and electric-indent-mode
1210 (eq (char-before) last-command-event))
1212 ;; Electric indent inside parens
1215 (let ((paren-start (python-syntax-context 'paren)))
1216 ;; Check that point is inside parens.
1219 ;; Filter the case where input is happening in the same
1220 ;; line where the open paren is.
1221 (= (line-number-at-pos)
1222 (line-number-at-pos paren-start)))))
1223 ;; When content has been added before the closing paren or a
1224 ;; comma has been inserted, it's ok to do the trick.
1226 (memq (char-after) '(?\) ?\] ?\}))
1227 (eq (char-before) ?,)))
1229 (goto-char (line-beginning-position))
1230 (let ((indentation (python-indent-calculate-indentation)))
1231 (when (and (numberp indentation) (< (current-indentation) indentation))
1232 (indent-line-to indentation)))))
1234 ((and (eq ?: last-command-event)
1235 (memq ?: electric-indent-chars)
1236 (not current-prefix-arg)
1237 ;; Trigger electric colon only at end of line
1239 ;; Avoid re-indenting on extra colon
1240 (not (equal ?: (char-before (1- (point)))))
1241 (not (python-syntax-comment-or-string-p)))
1242 ;; Just re-indent dedenters
1243 (let ((dedenter-pos (python-info-dedenter-statement-p))
1244 (current-pos (point)))
1247 (goto-char dedenter-pos)
1248 (python-indent-line)
1249 (unless (= (line-number-at-pos dedenter-pos)
1250 (line-number-at-pos current-pos))
1251 ;; Reindent region if this is a multiline statement
1252 (python-indent-region dedenter-pos current-pos)))))))))
1257 (defun python-mark-defun (&optional allow-extend)
1258 "Put mark at end of this defun, point at beginning.
1259 The defun marked is the one that contains point or follows point.
1261 Interactively (or with ALLOW-EXTEND non-nil), if this command is
1262 repeated or (in Transient Mark mode) if the mark is active, it
1263 marks the next defun after the ones already marked."
1265 (when (python-info-looking-at-beginning-of-defun)
1267 (mark-defun allow-extend))
1272 (defvar python-nav-beginning-of-defun-regexp
1273 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1274 "Regexp matching class or function definition.
1275 The name of the defun should be grouped so it can be retrieved
1276 via `match-string'.")
1278 (defun python-nav--beginning-of-defun (&optional arg)
1279 "Internal implementation of `python-nav-beginning-of-defun'.
1280 With positive ARG search backwards, else search forwards."
1281 (when (or (null arg) (= arg 0)) (setq arg 1))
1282 (let* ((re-search-fn (if (> arg 0)
1283 #'re-search-backward
1284 #'re-search-forward))
1285 (line-beg-pos (line-beginning-position))
1286 (line-content-start (+ line-beg-pos (current-indentation)))
1287 (pos (point-marker))
1292 (not (python-info-looking-at-beginning-of-defun))
1293 (python-nav-backward-block)))
1294 (or (and (python-info-looking-at-beginning-of-defun)
1295 (+ (current-indentation) python-indent-offset))
1299 (when (and (< arg 0)
1300 (python-info-looking-at-beginning-of-defun))
1302 (while (and (funcall re-search-fn
1303 python-nav-beginning-of-defun-regexp nil t)
1304 (or (python-syntax-context-type)
1305 ;; Handle nested defuns when moving
1306 ;; backwards by checking indentation.
1308 (not (= (current-indentation) 0))
1309 (>= (current-indentation) beg-indentation)))))
1310 (and (python-info-looking-at-beginning-of-defun)
1311 (or (not (= (line-number-at-pos pos)
1312 (line-number-at-pos)))
1313 (and (>= (point) line-beg-pos)
1314 (<= (point) line-content-start)
1315 (> pos line-content-start)))))))
1317 (or (beginning-of-line 1) t)
1318 (and (goto-char pos) nil))))
1320 (defun python-nav-beginning-of-defun (&optional arg)
1321 "Move point to `beginning-of-defun'.
1322 With positive ARG search backwards else search forward.
1323 ARG nil or 0 defaults to 1. When searching backwards,
1324 nested defuns are handled with care depending on current
1325 point position. Return non-nil if point is moved to
1326 `beginning-of-defun'."
1327 (when (or (null arg) (= arg 0)) (setq arg 1))
1329 (while (and (not (= arg 0))
1330 (let ((keep-searching-p
1331 (python-nav--beginning-of-defun arg)))
1332 (when (and keep-searching-p (null found))
1335 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1338 (defun python-nav-end-of-defun ()
1339 "Move point to the end of def or class.
1340 Returns nil if point is not in a def or class."
1342 (let ((beg-defun-indent)
1344 (when (or (python-info-looking-at-beginning-of-defun)
1345 (python-nav-beginning-of-defun 1)
1346 (python-nav-beginning-of-defun -1))
1347 (setq beg-defun-indent (current-indentation))
1349 (python-nav-end-of-statement)
1350 (python-util-forward-comment 1)
1351 (and (> (current-indentation) beg-defun-indent)
1353 (python-util-forward-comment -1)
1355 ;; Ensure point moves forward.
1356 (and (> beg-pos (point)) (goto-char beg-pos)))))
1358 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1359 "Move point using FN avoiding places with specific context.
1360 FN must take no arguments. POSCOMPFN is a two arguments function
1361 used to compare current and previous point after it is moved
1362 using FN, this is normally a less-than or greater-than
1363 comparison. Optional argument CONTEXTFN defaults to
1364 `python-syntax-context-type' and is used for checking current
1365 point context, it must return a non-nil value if this point must
1367 (let ((contextfn (or contextfn 'python-syntax-context-type))
1368 (start-pos (point-marker))
1373 (and (funcall fn) (point-marker)))
1374 (context (funcall contextfn)))
1375 (cond ((and (not context) newpos
1376 (or (and (not prev-pos) newpos)
1377 (and prev-pos newpos
1378 (funcall poscompfn newpos prev-pos))))
1379 (throw 'found (point-marker)))
1380 ((and newpos context)
1381 (setq prev-pos (point)))
1382 (t (when (not newpos) (goto-char start-pos))
1383 (throw 'found nil))))))))
1385 (defun python-nav--forward-defun (arg)
1386 "Internal implementation of python-nav-{backward,forward}-defun.
1387 Uses ARG to define which function to call, and how many times
1390 (while (and (> arg 0)
1392 (python-nav--syntactically
1395 python-nav-beginning-of-defun-regexp nil t))
1397 (setq arg (1- arg)))
1398 (while (and (< arg 0)
1400 (python-nav--syntactically
1403 python-nav-beginning-of-defun-regexp nil t))
1405 (setq arg (1+ arg)))
1408 (defun python-nav-backward-defun (&optional arg)
1409 "Navigate to closer defun backward ARG times.
1410 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1411 nested definitions."
1413 (python-nav--forward-defun (- (or arg 1))))
1415 (defun python-nav-forward-defun (&optional arg)
1416 "Navigate to closer defun forward ARG times.
1417 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1418 nested definitions."
1420 (python-nav--forward-defun (or arg 1)))
1422 (defun python-nav-beginning-of-statement ()
1423 "Move to start of current statement."
1425 (back-to-indentation)
1426 (let* ((ppss (syntax-ppss))
1429 (python-syntax-context 'paren ppss)
1430 (python-syntax-context 'string ppss))))
1433 (goto-char context-point)
1434 (python-nav-beginning-of-statement))
1437 (python-info-line-ends-backslash-p))
1439 (python-nav-beginning-of-statement))))
1442 (defun python-nav-end-of-statement (&optional noend)
1443 "Move to end of current statement.
1444 Optional argument NOEND is internal and makes the logic to not
1445 jump to the end of line when moving forward searching for the end
1448 (let (string-start bs-pos)
1449 (while (and (or noend (goto-char (line-end-position)))
1451 (cond ((setq string-start (python-syntax-context 'string))
1452 (goto-char string-start)
1453 (if (python-syntax-context 'paren)
1454 ;; Ended up inside a paren, roll again.
1455 (python-nav-end-of-statement t)
1456 ;; This is not inside a paren, move to the
1457 ;; end of this string.
1458 (goto-char (+ (point)
1459 (python-syntax-count-quotes
1460 (char-after (point)) (point))))
1461 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1462 (goto-char (point-max)))))
1463 ((python-syntax-context 'paren)
1464 ;; The statement won't end before we've escaped
1465 ;; at least one level of parenthesis.
1467 (goto-char (scan-lists (point) 1 -1))
1468 (scan-error (goto-char (nth 3 err)))))
1469 ((setq bs-pos (python-info-line-ends-backslash-p))
1471 (forward-line 1))))))
1474 (defun python-nav-backward-statement (&optional arg)
1475 "Move backward to previous statement.
1476 With ARG, repeat. See `python-nav-forward-statement'."
1478 (or arg (setq arg 1))
1479 (python-nav-forward-statement (- arg)))
1481 (defun python-nav-forward-statement (&optional arg)
1482 "Move forward to next statement.
1483 With ARG, repeat. With negative argument, move ARG times
1484 backward to previous statement."
1486 (or arg (setq arg 1))
1488 (python-nav-end-of-statement)
1489 (python-util-forward-comment)
1490 (python-nav-beginning-of-statement)
1491 (setq arg (1- arg)))
1493 (python-nav-beginning-of-statement)
1494 (python-util-forward-comment -1)
1495 (python-nav-beginning-of-statement)
1496 (setq arg (1+ arg))))
1498 (defun python-nav-beginning-of-block ()
1499 "Move to start of current block."
1501 (let ((starting-pos (point)))
1503 (python-nav-beginning-of-statement)
1504 (looking-at (python-rx block-start)))
1506 ;; Go to first line beginning a statement
1507 (while (and (not (bobp))
1508 (or (and (python-nav-beginning-of-statement) nil)
1509 (python-info-current-line-comment-p)
1510 (python-info-current-line-empty-p)))
1512 (let ((block-matching-indent
1513 (- (current-indentation) python-indent-offset)))
1515 (and (python-nav-backward-block)
1516 (> (current-indentation) block-matching-indent)))
1517 (if (and (looking-at (python-rx block-start))
1518 (= (current-indentation) block-matching-indent))
1520 (and (goto-char starting-pos) nil))))))
1522 (defun python-nav-end-of-block ()
1523 "Move to end of current block."
1525 (when (python-nav-beginning-of-block)
1526 (let ((block-indentation (current-indentation)))
1527 (python-nav-end-of-statement)
1528 (while (and (forward-line 1)
1530 (or (and (> (current-indentation) block-indentation)
1531 (or (python-nav-end-of-statement) t))
1532 (python-info-current-line-comment-p)
1533 (python-info-current-line-empty-p))))
1534 (python-util-forward-comment -1)
1537 (defun python-nav-backward-block (&optional arg)
1538 "Move backward to previous block of code.
1539 With ARG, repeat. See `python-nav-forward-block'."
1541 (or arg (setq arg 1))
1542 (python-nav-forward-block (- arg)))
1544 (defun python-nav-forward-block (&optional arg)
1545 "Move forward to next block of code.
1546 With ARG, repeat. With negative argument, move ARG times
1547 backward to previous block."
1549 (or arg (setq arg 1))
1550 (let ((block-start-regexp
1551 (python-rx line-start (* whitespace) block-start))
1552 (starting-pos (point)))
1554 (python-nav-end-of-statement)
1556 (re-search-forward block-start-regexp nil t)
1557 (python-syntax-context-type)))
1558 (setq arg (1- arg)))
1560 (python-nav-beginning-of-statement)
1562 (re-search-backward block-start-regexp nil t)
1563 (python-syntax-context-type)))
1564 (setq arg (1+ arg)))
1565 (python-nav-beginning-of-statement)
1566 (if (not (looking-at (python-rx block-start)))
1567 (and (goto-char starting-pos) nil)
1568 (and (not (= (point) starting-pos)) (point-marker)))))
1570 (defun python-nav--lisp-forward-sexp (&optional arg)
1571 "Standard version `forward-sexp'.
1572 It ignores completely the value of `forward-sexp-function' by
1573 setting it to nil before calling `forward-sexp'. With positive
1574 ARG move forward only one sexp, else move backwards."
1575 (let ((forward-sexp-function)
1576 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1577 (forward-sexp arg)))
1579 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1580 "Safe version of standard `forward-sexp'.
1581 When at end of sexp (i.e. looking at a opening/closing paren)
1582 skips it instead of throwing an error. With positive ARG move
1583 forward only one sexp, else move backwards."
1584 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1586 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1588 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1590 (python-nav--lisp-forward-sexp arg)
1592 (while (and (funcall search-fn paren-regexp nil t)
1593 (python-syntax-context 'paren)))))))
1595 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p)
1596 "Move to forward sexp.
1597 With positive optional argument DIR direction move forward, else
1598 backwards. When optional argument SAFE is non-nil do not throw
1599 errors when at end of sexp, skip it instead. With optional
1600 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1601 expressions when looking at them in either direction."
1602 (setq dir (or dir 1))
1604 (let* ((forward-p (if (> dir 0)
1605 (and (setq dir 1) t)
1606 (and (setq dir -1) nil)))
1607 (context-type (python-syntax-context-type)))
1609 ((memq context-type '(string comment))
1610 ;; Inside of a string, get out of it.
1611 (let ((forward-sexp-function))
1612 (forward-sexp dir)))
1613 ((and (not skip-parens-p)
1614 (or (eq context-type 'paren)
1616 (eq (syntax-class (syntax-after (point)))
1617 (car (string-to-syntax "(")))
1618 (eq (syntax-class (syntax-after (1- (point))))
1619 (car (string-to-syntax ")"))))))
1620 ;; Inside a paren or looking at it, lisp knows what to do.
1622 (python-nav--lisp-forward-sexp-safe dir)
1623 (python-nav--lisp-forward-sexp dir)))
1625 ;; This part handles the lispy feel of
1626 ;; `python-nav-forward-sexp'. Knowing everything about the
1627 ;; current context and the context of the next sexp tries to
1628 ;; follow the lisp sexp motion commands in a symmetric manner.
1631 ((python-info-beginning-of-block-p) 'block-start)
1632 ((python-info-end-of-block-p) 'block-end)
1633 ((python-info-beginning-of-statement-p) 'statement-start)
1634 ((python-info-end-of-statement-p) 'statement-end)))
1638 (python-nav--lisp-forward-sexp-safe dir)
1639 (python-nav--lisp-forward-sexp dir))
1643 (goto-char next-sexp-pos)
1645 ((python-info-beginning-of-block-p) 'block-start)
1646 ((python-info-end-of-block-p) 'block-end)
1647 ((python-info-beginning-of-statement-p) 'statement-start)
1648 ((python-info-end-of-statement-p) 'statement-end)
1649 ((python-info-statement-starts-block-p) 'starts-block)
1650 ((python-info-statement-ends-block-p) 'ends-block)))))
1652 (cond ((and (not (eobp))
1653 (python-info-current-line-empty-p))
1654 (python-util-forward-comment dir)
1655 (python-nav--forward-sexp dir safe skip-parens-p))
1656 ((eq context 'block-start)
1657 (python-nav-end-of-block))
1658 ((eq context 'statement-start)
1659 (python-nav-end-of-statement))
1660 ((and (memq context '(statement-end block-end))
1661 (eq next-sexp-context 'ends-block))
1662 (goto-char next-sexp-pos)
1663 (python-nav-end-of-block))
1664 ((and (memq context '(statement-end block-end))
1665 (eq next-sexp-context 'starts-block))
1666 (goto-char next-sexp-pos)
1667 (python-nav-end-of-block))
1668 ((memq context '(statement-end block-end))
1669 (goto-char next-sexp-pos)
1670 (python-nav-end-of-statement))
1671 (t (goto-char next-sexp-pos)))
1672 (cond ((and (not (bobp))
1673 (python-info-current-line-empty-p))
1674 (python-util-forward-comment dir)
1675 (python-nav--forward-sexp dir safe skip-parens-p))
1676 ((eq context 'block-end)
1677 (python-nav-beginning-of-block))
1678 ((eq context 'statement-end)
1679 (python-nav-beginning-of-statement))
1680 ((and (memq context '(statement-start block-start))
1681 (eq next-sexp-context 'starts-block))
1682 (goto-char next-sexp-pos)
1683 (python-nav-beginning-of-block))
1684 ((and (memq context '(statement-start block-start))
1685 (eq next-sexp-context 'ends-block))
1686 (goto-char next-sexp-pos)
1687 (python-nav-beginning-of-block))
1688 ((memq context '(statement-start block-start))
1689 (goto-char next-sexp-pos)
1690 (python-nav-beginning-of-statement))
1691 (t (goto-char next-sexp-pos))))))))))
1693 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p)
1694 "Move forward across expressions.
1695 With ARG, do it that many times. Negative arg -N means move
1696 backward N times. When optional argument SAFE is non-nil do not
1697 throw errors when at end of sexp, skip it instead. With optional
1698 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1699 expressions when looking at them in either direction (forced to t
1700 in interactive calls)."
1702 (or arg (setq arg 1))
1703 ;; Do not follow parens on interactive calls. This hack to detect
1704 ;; if the function was called interactively copes with the way
1705 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1706 ;; interactive detection by checking `current-prefix-arg'. The
1707 ;; reason to make this distinction is that lisp functions like
1708 ;; `blink-matching-open' get confused causing issues like the one in
1709 ;; Bug#16191. With this approach the user gets a symmetric behavior
1710 ;; when working interactively while called functions expecting
1711 ;; paren-based sexp motion work just fine.
1715 (memq real-this-command
1717 #'forward-sexp #'backward-sexp
1718 #'python-nav-forward-sexp #'python-nav-backward-sexp
1719 #'python-nav-forward-sexp-safe #'python-nav-backward-sexp))))
1721 (python-nav--forward-sexp 1 safe skip-parens-p)
1722 (setq arg (1- arg)))
1724 (python-nav--forward-sexp -1 safe skip-parens-p)
1725 (setq arg (1+ arg))))
1727 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p)
1728 "Move backward across expressions.
1729 With ARG, do it that many times. Negative arg -N means move
1730 forward N times. When optional argument SAFE is non-nil do not
1731 throw errors when at end of sexp, skip it instead. With optional
1732 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1733 expressions when looking at them in either direction (forced to t
1734 in interactive calls)."
1736 (or arg (setq arg 1))
1737 (python-nav-forward-sexp (- arg) safe skip-parens-p))
1739 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p)
1740 "Move forward safely across expressions.
1741 With ARG, do it that many times. Negative arg -N means move
1742 backward N times. With optional argument SKIP-PARENS-P force
1743 sexp motion to ignore parenthesized expressions when looking at
1744 them in either direction (forced to t in interactive calls)."
1746 (python-nav-forward-sexp arg t skip-parens-p))
1748 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p)
1749 "Move backward safely across expressions.
1750 With ARG, do it that many times. Negative arg -N means move
1751 forward N times. With optional argument SKIP-PARENS-P force sexp
1752 motion to ignore parenthesized expressions when looking at them in
1753 either direction (forced to t in interactive calls)."
1755 (python-nav-backward-sexp arg t skip-parens-p))
1757 (defun python-nav--up-list (&optional dir)
1758 "Internal implementation of `python-nav-up-list'.
1759 DIR is always 1 or -1 and comes sanitized from
1760 `python-nav-up-list' calls."
1761 (let ((context (python-syntax-context-type))
1762 (forward-p (> dir 0)))
1764 ((memq context '(string comment)))
1765 ((eq context 'paren)
1766 (let ((forward-sexp-function))
1768 ((and forward-p (python-info-end-of-block-p))
1769 (let ((parent-end-pos
1771 (let ((indentation (and
1772 (python-nav-beginning-of-block)
1773 (current-indentation))))
1774 (while (and indentation
1776 (>= (current-indentation) indentation)
1777 (python-nav-backward-block)))
1778 (python-nav-end-of-block)))))
1779 (and (> (or parent-end-pos (point)) (point))
1780 (goto-char parent-end-pos))))
1781 (forward-p (python-nav-end-of-block))
1782 ((and (not forward-p)
1783 (> (current-indentation) 0)
1784 (python-info-beginning-of-block-p))
1785 (let ((prev-block-pos
1787 (let ((indentation (current-indentation)))
1788 (while (and (python-nav-backward-block)
1789 (>= (current-indentation) indentation))))
1791 (and (> (point) prev-block-pos)
1792 (goto-char prev-block-pos))))
1793 ((not forward-p) (python-nav-beginning-of-block)))))
1795 (defun python-nav-up-list (&optional arg)
1796 "Move forward out of one level of parentheses (or blocks).
1797 With ARG, do this that many times.
1798 A negative argument means move backward but still to a less deep spot.
1799 This command assumes point is not in a string or comment."
1801 (or arg (setq arg 1))
1803 (python-nav--up-list 1)
1804 (setq arg (1- arg)))
1806 (python-nav--up-list -1)
1807 (setq arg (1+ arg))))
1809 (defun python-nav-backward-up-list (&optional arg)
1810 "Move backward out of one level of parentheses (or blocks).
1811 With ARG, do this that many times.
1812 A negative argument means move forward but still to a less deep spot.
1813 This command assumes point is not in a string or comment."
1815 (or arg (setq arg 1))
1816 (python-nav-up-list (- arg)))
1818 (defun python-nav-if-name-main ()
1819 "Move point at the beginning the __main__ block.
1820 When \"if __name__ == '__main__':\" is found returns its
1821 position, else returns nil."
1823 (let ((point (point))
1824 (found (catch 'found
1825 (goto-char (point-min))
1826 (while (re-search-forward
1827 (python-rx line-start
1829 "__name__" (+ space)
1831 (group-n 1 (or ?\" ?\'))
1832 "__main__" (backref 1) (* space) ":")
1834 (when (not (python-syntax-context-type))
1836 (throw 'found t))))))
1839 (ignore (goto-char point)))))
1842 ;;; Shell integration
1844 (defcustom python-shell-buffer-name "Python"
1845 "Default buffer name for Python interpreter."
1850 (defcustom python-shell-interpreter "python"
1851 "Default Python interpreter for shell."
1855 (defcustom python-shell-internal-buffer-name "Python Internal"
1856 "Default buffer name for the Internal Python interpreter."
1861 (defcustom python-shell-interpreter-args "-i"
1862 "Default arguments for the Python interpreter."
1866 (defcustom python-shell-interpreter-interactive-arg "-i"
1867 "Interpreter argument to force it to run interactively."
1871 (defcustom python-shell-prompt-detect-enabled t
1872 "Non-nil enables autodetection of interpreter prompts."
1877 (defcustom python-shell-prompt-detect-failure-warning t
1878 "Non-nil enables warnings when detection of prompts fail."
1883 (defcustom python-shell-prompt-input-regexps
1884 '(">>> " "\\.\\.\\. " ; Python
1885 "In \\[[0-9]+\\]: " ; IPython
1886 " \\.\\.\\.: " ; IPython
1887 ;; Using ipdb outside IPython may fail to cleanup and leave static
1888 ;; IPython prompts activated, this adds some safeguard for that.
1889 "In : " "\\.\\.\\.: ")
1890 "List of regular expressions matching input prompts."
1891 :type '(repeat string)
1894 (defcustom python-shell-prompt-output-regexps
1896 "Out\\[[0-9]+\\]: " ; IPython
1897 "Out :") ; ipdb safeguard
1898 "List of regular expressions matching output prompts."
1899 :type '(repeat string)
1902 (defcustom python-shell-prompt-regexp ">>> "
1903 "Regular expression matching top level input prompt of Python shell.
1904 It should not contain a caret (^) at the beginning."
1907 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1908 "Regular expression matching block input prompt of Python shell.
1909 It should not contain a caret (^) at the beginning."
1912 (defcustom python-shell-prompt-output-regexp ""
1913 "Regular expression matching output prompt of Python shell.
1914 It should not contain a caret (^) at the beginning."
1917 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1918 "Regular expression matching pdb input prompt of Python shell.
1919 It should not contain a caret (^) at the beginning."
1922 (define-obsolete-variable-alias
1923 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1925 (defcustom python-shell-font-lock-enable t
1926 "Should syntax highlighting be enabled in the Python shell buffer?
1927 Restart the Python shell after changing this variable for it to take effect."
1932 (defcustom python-shell-unbuffered t
1933 "Should shell output be unbuffered?.
1934 When non-nil, this may prevent delayed and missing output in the
1935 Python shell. See commentary for details."
1940 (defcustom python-shell-process-environment nil
1941 "List of environment variables for Python shell.
1942 This variable follows the same rules as `process-environment'
1943 since it merges with it before the process creation routines are
1944 called. When this variable is nil, the Python shell is run with
1945 the default `process-environment'."
1946 :type '(repeat string)
1950 (defcustom python-shell-extra-pythonpaths nil
1951 "List of extra pythonpaths for Python shell.
1952 The values of this variable are added to the existing value of
1953 PYTHONPATH in the `process-environment' variable."
1954 :type '(repeat string)
1958 (defcustom python-shell-exec-path nil
1959 "List of path to search for binaries.
1960 This variable follows the same rules as `exec-path' since it
1961 merges with it before the process creation routines are called.
1962 When this variable is nil, the Python shell is run with the
1963 default `exec-path'."
1964 :type '(repeat string)
1968 (defcustom python-shell-virtualenv-root nil
1969 "Path to virtualenv root.
1970 This variable, when set to a string, makes the values stored in
1971 `python-shell-process-environment' and `python-shell-exec-path'
1972 to be modified properly so shells are started with the specified
1974 :type '(choice (const nil) string)
1978 (define-obsolete-variable-alias
1979 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
1981 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1982 python-ffap-setup-code
1983 python-eldoc-setup-code)
1984 "List of code run by `python-shell-send-setup-codes'."
1985 :type '(repeat symbol)
1989 (defcustom python-shell-compilation-regexp-alist
1990 `((,(rx line-start (1+ (any " \t")) "File \""
1991 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1992 "\", line " (group (1+ digit)))
1994 (,(rx " in file " (group (1+ not-newline)) " on line "
1997 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1998 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
2000 "`compilation-error-regexp-alist' for inferior Python."
2001 :type '(alist string)
2004 (defvar python-shell--prompt-calculated-input-regexp nil
2005 "Calculated input prompt regexp for inferior python shell.
2006 Do not set this variable directly, instead use
2007 `python-shell-prompt-set-calculated-regexps'.")
2009 (defvar python-shell--prompt-calculated-output-regexp nil
2010 "Calculated output prompt regexp for inferior python shell.
2011 Do not set this variable directly, instead use
2012 `python-shell-set-prompt-regexp'.")
2014 (defun python-shell-prompt-detect ()
2015 "Detect prompts for the current `python-shell-interpreter'.
2016 When prompts can be retrieved successfully from the
2017 `python-shell-interpreter' run with
2018 `python-shell-interpreter-interactive-arg', returns a list of
2019 three elements, where the first two are input prompts and the
2020 last one is an output prompt. When no prompts can be detected
2021 and `python-shell-prompt-detect-failure-warning' is non-nil,
2022 shows a warning with instructions to avoid hangs and returns nil.
2023 When `python-shell-prompt-detect-enabled' is nil avoids any
2024 detection and just returns nil."
2025 (when python-shell-prompt-detect-enabled
2026 (let* ((process-environment (python-shell-calculate-process-environment))
2027 (exec-path (python-shell-calculate-exec-path))
2030 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2031 ;; JSON is built manually for compatibility
2032 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2037 ;; TODO: improve error handling by using
2038 ;; `condition-case' and displaying the error message to
2039 ;; the user in the no-prompts warning.
2041 (let ((code-file (python-shell--save-temp-file code)))
2042 ;; Use `process-file' as it is remote-host friendly.
2044 python-shell-interpreter
2048 python-shell-interpreter-interactive-arg)
2050 (delete-file code-file)))
2054 (dolist (line (split-string output "\n" t))
2056 ;; Check if current line is a valid JSON array
2057 (and (string= (substring line 0 2) "[\"")
2059 ;; Return prompts as a list, not vector
2060 (append (json-read-from-string line) nil)))))
2061 ;; The list must contain 3 strings, where the first
2062 ;; is the input prompt, the second is the block
2063 ;; prompt and the last one is the output prompt. The
2064 ;; input prompt is the only one that can't be empty.
2065 (when (and (= (length res) 3)
2066 (cl-every #'stringp res)
2067 (not (string= (car res) "")))
2068 (throw 'prompts res))))
2070 (when (and (not prompts)
2071 python-shell-prompt-detect-failure-warning)
2073 '(python python-shell-prompt-regexp)
2076 "Python shell prompts cannot be detected.\n"
2077 "If your emacs session hangs when starting python shells\n"
2078 "recover with `keyboard-quit' and then try fixing the\n"
2079 "interactive flag for your interpreter by adjusting the\n"
2080 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2081 "matching shell prompts in the directory-local friendly vars:\n"
2082 " + `python-shell-prompt-regexp'\n"
2083 " + `python-shell-prompt-block-regexp'\n"
2084 " + `python-shell-prompt-output-regexp'\n"
2085 "Or alternatively in:\n"
2086 " + `python-shell-prompt-input-regexps'\n"
2087 " + `python-shell-prompt-output-regexps'")))
2090 (defun python-shell-prompt-validate-regexps ()
2091 "Validate all user provided regexps for prompts.
2092 Signals `user-error' if any of these vars contain invalid
2093 regexps: `python-shell-prompt-regexp',
2094 `python-shell-prompt-block-regexp',
2095 `python-shell-prompt-pdb-regexp',
2096 `python-shell-prompt-output-regexp',
2097 `python-shell-prompt-input-regexps',
2098 `python-shell-prompt-output-regexps'."
2099 (dolist (symbol (list 'python-shell-prompt-input-regexps
2100 'python-shell-prompt-output-regexps
2101 'python-shell-prompt-regexp
2102 'python-shell-prompt-block-regexp
2103 'python-shell-prompt-pdb-regexp
2104 'python-shell-prompt-output-regexp))
2105 (dolist (regexp (let ((regexps (symbol-value symbol)))
2109 (when (not (python-util-valid-regexp-p regexp))
2110 (user-error "Invalid regexp %s in `%s'"
2113 (defun python-shell-prompt-set-calculated-regexps ()
2114 "Detect and set input and output prompt regexps.
2115 Build and set the values for `python-shell-input-prompt-regexp'
2116 and `python-shell-output-prompt-regexp' using the values from
2117 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2118 `python-shell-prompt-pdb-regexp',
2119 `python-shell-prompt-output-regexp',
2120 `python-shell-prompt-input-regexps',
2121 `python-shell-prompt-output-regexps' and detected prompts from
2122 `python-shell-prompt-detect'."
2123 (when (not (and python-shell--prompt-calculated-input-regexp
2124 python-shell--prompt-calculated-output-regexp))
2125 (let* ((detected-prompts (python-shell-prompt-detect))
2127 (output-prompts nil)
2131 (mapconcat #'identity
2134 (let ((length-a (length a))
2135 (length-b (length b)))
2136 (if (= length-a length-b)
2138 (> (length a) (length b))))))
2141 ;; Validate ALL regexps
2142 (python-shell-prompt-validate-regexps)
2143 ;; Collect all user defined input prompts
2144 (dolist (prompt (append python-shell-prompt-input-regexps
2145 (list python-shell-prompt-regexp
2146 python-shell-prompt-block-regexp
2147 python-shell-prompt-pdb-regexp)))
2148 (cl-pushnew prompt input-prompts :test #'string=))
2149 ;; Collect all user defined output prompts
2150 (dolist (prompt (cons python-shell-prompt-output-regexp
2151 python-shell-prompt-output-regexps))
2152 (cl-pushnew prompt output-prompts :test #'string=))
2153 ;; Collect detected prompts if any
2154 (when detected-prompts
2155 (dolist (prompt (butlast detected-prompts))
2156 (setq prompt (regexp-quote prompt))
2157 (cl-pushnew prompt input-prompts :test #'string=))
2158 (cl-pushnew (regexp-quote
2159 (car (last detected-prompts)))
2160 output-prompts :test #'string=))
2161 ;; Set input and output prompt regexps from collected prompts
2162 (setq python-shell--prompt-calculated-input-regexp
2163 (funcall build-regexp input-prompts)
2164 python-shell--prompt-calculated-output-regexp
2165 (funcall build-regexp output-prompts)))))
2167 (defun python-shell-get-process-name (dedicated)
2168 "Calculate the appropriate process name for inferior Python process.
2169 If DEDICATED is t returns a string with the form
2170 `python-shell-buffer-name'[`buffer-name'] else returns the value
2171 of `python-shell-buffer-name'."
2173 (format "%s[%s]" python-shell-buffer-name (buffer-name))
2174 python-shell-buffer-name))
2176 (defun python-shell-internal-get-process-name ()
2177 "Calculate the appropriate process name for Internal Python process.
2178 The name is calculated from `python-shell-global-buffer-name' and
2180 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
2182 (defun python-shell-calculate-command ()
2183 "Calculate the string used to execute the inferior Python process."
2184 (let ((exec-path (python-shell-calculate-exec-path)))
2185 ;; `exec-path' gets tweaked so that virtualenv's specific
2186 ;; `python-shell-interpreter' absolute path can be found by
2187 ;; `executable-find'.
2189 ;; FIXME: Why executable-find?
2190 (shell-quote-argument
2191 (executable-find python-shell-interpreter))
2192 python-shell-interpreter-args)))
2194 (define-obsolete-function-alias
2195 'python-shell-parse-command
2196 #'python-shell-calculate-command "25.1")
2198 (defun python-shell-calculate-pythonpath ()
2199 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2200 (let ((pythonpath (getenv "PYTHONPATH"))
2201 (extra (mapconcat 'identity
2202 python-shell-extra-pythonpaths
2205 (concat extra path-separator pythonpath)
2208 (defun python-shell-calculate-process-environment ()
2209 "Calculate process environment given `python-shell-virtualenv-root'."
2210 (let ((process-environment (append
2211 python-shell-process-environment
2212 process-environment nil))
2213 (virtualenv (if python-shell-virtualenv-root
2214 (directory-file-name python-shell-virtualenv-root)
2216 (when python-shell-unbuffered
2217 (setenv "PYTHONUNBUFFERED" "1"))
2218 (when python-shell-extra-pythonpaths
2219 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2220 (if (not virtualenv)
2222 (setenv "PYTHONHOME" nil)
2223 (setenv "PATH" (format "%s/bin%s%s"
2224 virtualenv path-separator
2225 (or (getenv "PATH") "")))
2226 (setenv "VIRTUAL_ENV" virtualenv))
2227 process-environment))
2229 (defun python-shell-calculate-exec-path ()
2230 "Calculate exec path given `python-shell-virtualenv-root'."
2232 ;; Use nil as the tail so that the list is a full copy,
2233 ;; this is a paranoid safeguard for side-effects.
2234 python-shell-exec-path exec-path nil)))
2235 (if (not python-shell-virtualenv-root)
2237 (cons (expand-file-name "bin" python-shell-virtualenv-root)
2240 (defvar python-shell--package-depth 10)
2242 (defun python-shell-package-enable (directory package)
2243 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2245 (let* ((dir (expand-file-name
2246 (read-directory-name
2248 (file-name-directory
2249 (or (buffer-file-name) default-directory)))))
2250 (name (completing-read
2252 (python-util-list-packages
2253 dir python-shell--package-depth))))
2255 (python-shell-send-string
2258 "import os.path;import sys;"
2259 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2260 "__package__ = '''%s''';"
2262 directory package package)
2263 (python-shell-get-process)))
2265 (defun python-shell-accept-process-output (process &optional timeout regexp)
2266 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2267 Optional argument TIMEOUT is the timeout argument to
2268 `accept-process-output' calls. Optional argument REGEXP
2269 overrides the regexp to match the end of output, defaults to
2270 `comint-prompt-regexp.'. Returns non-nil when output was
2273 This utility is useful in situations where the output may be
2274 received in chunks, since `accept-process-output' gives no
2275 guarantees they will be grabbed in a single call. An example use
2276 case for this would be the CPython shell start-up, where the
2277 banner and the initial prompt are received separately."
2278 (let ((regexp (or regexp comint-prompt-regexp)))
2281 (when (not (accept-process-output process timeout))
2284 regexp (car (python-util-comint-last-prompt)))
2285 (throw 'found t))))))
2287 (defun python-shell-comint-end-of-output-p (output)
2288 "Return non-nil if OUTPUT is ends with input prompt."
2290 ;; XXX: It seems on OSX an extra carriage return is attached
2291 ;; at the end of output, this handles that too.
2294 ;; Remove initial caret from calculated regexp
2295 (replace-regexp-in-string
2296 (rx string-start ?^) ""
2297 python-shell--prompt-calculated-input-regexp)
2301 (define-obsolete-function-alias
2302 'python-comint-output-filter-function
2303 'ansi-color-filter-apply
2306 (defun python-comint-postoutput-scroll-to-bottom (output)
2307 "Faster version of `comint-postoutput-scroll-to-bottom'.
2308 Avoids `recenter' calls until OUTPUT is completely sent."
2309 (when (and (not (string= "" output))
2310 (python-shell-comint-end-of-output-p
2311 (ansi-color-filter-apply output)))
2312 (comint-postoutput-scroll-to-bottom output))
2315 (defvar python-shell--parent-buffer nil)
2317 (defmacro python-shell-with-shell-buffer (&rest body)
2318 "Execute the forms in BODY with the shell buffer temporarily current.
2319 Signals an error if no shell buffer is available for current buffer."
2320 (declare (indent 0) (debug t))
2321 (let ((shell-process (make-symbol "shell-process")))
2322 `(let ((,shell-process (python-shell-get-process-or-error)))
2323 (with-current-buffer (process-buffer ,shell-process)
2326 (defvar python-shell--font-lock-buffer nil)
2328 (defun python-shell-font-lock-get-or-create-buffer ()
2329 "Get or create a font-lock buffer for current inferior process."
2330 (python-shell-with-shell-buffer
2331 (if python-shell--font-lock-buffer
2332 python-shell--font-lock-buffer
2334 (process-name (get-buffer-process (current-buffer)))))
2335 (generate-new-buffer
2336 (format " *%s-font-lock*" process-name))))))
2338 (defun python-shell-font-lock-kill-buffer ()
2339 "Kill the font-lock buffer safely."
2340 (when (and python-shell--font-lock-buffer
2341 (buffer-live-p python-shell--font-lock-buffer))
2342 (kill-buffer python-shell--font-lock-buffer)
2343 (when (derived-mode-p 'inferior-python-mode)
2344 (setq python-shell--font-lock-buffer nil))))
2346 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2347 "Execute the forms in BODY in the font-lock buffer.
2348 The value returned is the value of the last form in BODY. See
2349 also `with-current-buffer'."
2350 (declare (indent 0) (debug t))
2351 `(python-shell-with-shell-buffer
2352 (save-current-buffer
2353 (when (not (and python-shell--font-lock-buffer
2354 (get-buffer python-shell--font-lock-buffer)))
2355 (setq python-shell--font-lock-buffer
2356 (python-shell-font-lock-get-or-create-buffer)))
2357 (set-buffer python-shell--font-lock-buffer)
2358 (when (not font-lock-mode)
2360 (set (make-local-variable 'delay-mode-hooks) t)
2361 (let ((python-indent-guess-indent-offset nil))
2362 (when (not (derived-mode-p 'python-mode))
2366 (defun python-shell-font-lock-cleanup-buffer ()
2367 "Cleanup the font-lock buffer.
2368 Provided as a command because this might be handy if something
2369 goes wrong and syntax highlighting in the shell gets messed up."
2371 (python-shell-with-shell-buffer
2372 (python-shell-font-lock-with-font-lock-buffer
2375 (defun python-shell-font-lock-comint-output-filter-function (output)
2376 "Clean up the font-lock buffer after any OUTPUT."
2377 (if (and (not (string= "" output))
2378 ;; Is end of output and is not just a prompt.
2380 (python-shell-comint-end-of-output-p
2381 (ansi-color-filter-apply output))
2383 ;; If output is other than an input prompt then "real" output has
2384 ;; been received and the font-lock buffer must be cleaned up.
2385 (python-shell-font-lock-cleanup-buffer)
2386 ;; Otherwise just add a newline.
2387 (python-shell-font-lock-with-font-lock-buffer
2388 (goto-char (point-max))
2392 (defun python-shell-font-lock-post-command-hook ()
2393 "Fontifies current line in shell buffer."
2394 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2395 (when (and prompt-end (> (point) prompt-end)
2396 (process-live-p (get-buffer-process (current-buffer))))
2397 (let* ((input (buffer-substring-no-properties
2398 prompt-end (point-max)))
2399 (deactivate-mark nil)
2400 (start-pos prompt-end)
2401 (buffer-undo-list t)
2402 (font-lock-buffer-pos nil)
2404 (python-shell-font-lock-with-font-lock-buffer
2405 (delete-region (line-beginning-position)
2407 (setq font-lock-buffer-pos (point))
2409 ;; Ensure buffer is fontified, keeping it
2410 ;; compatible with Emacs < 24.4.
2411 (if (fboundp 'font-lock-ensure)
2412 (funcall 'font-lock-ensure)
2413 (font-lock-default-fontify-buffer))
2414 (buffer-substring font-lock-buffer-pos
2416 (replacement-length (length replacement))
2418 ;; Inject text properties to get input fontified.
2419 (while (not (= i replacement-length))
2420 (let* ((plist (text-properties-at i replacement))
2421 (next-change (or (next-property-change i replacement)
2422 replacement-length))
2423 (plist (let ((face (plist-get plist 'face)))
2426 ;; Replace FACE text properties with
2427 ;; FONT-LOCK-FACE so input is fontified.
2428 (plist-put plist 'face nil)
2429 (plist-put plist 'font-lock-face face)))))
2430 (set-text-properties
2431 (+ start-pos i) (+ start-pos next-change) plist)
2432 (setq i next-change)))))))
2434 (defun python-shell-font-lock-turn-on (&optional msg)
2435 "Turn on shell font-lock.
2436 With argument MSG show activation message."
2438 (python-shell-with-shell-buffer
2439 (python-shell-font-lock-kill-buffer)
2440 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2441 (add-hook 'post-command-hook
2442 #'python-shell-font-lock-post-command-hook nil 'local)
2443 (add-hook 'kill-buffer-hook
2444 #'python-shell-font-lock-kill-buffer nil 'local)
2445 (add-hook 'comint-output-filter-functions
2446 #'python-shell-font-lock-comint-output-filter-function
2449 (message "Shell font-lock is enabled"))))
2451 (defun python-shell-font-lock-turn-off (&optional msg)
2452 "Turn off shell font-lock.
2453 With argument MSG show deactivation message."
2455 (python-shell-with-shell-buffer
2456 (python-shell-font-lock-kill-buffer)
2457 (when (python-util-comint-last-prompt)
2458 ;; Cleanup current fontification
2459 (remove-text-properties
2460 (cdr (python-util-comint-last-prompt))
2462 '(face nil font-lock-face nil)))
2463 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2464 (remove-hook 'post-command-hook
2465 #'python-shell-font-lock-post-command-hook 'local)
2466 (remove-hook 'kill-buffer-hook
2467 #'python-shell-font-lock-kill-buffer 'local)
2468 (remove-hook 'comint-output-filter-functions
2469 #'python-shell-font-lock-comint-output-filter-function
2472 (message "Shell font-lock is disabled"))))
2474 (defun python-shell-font-lock-toggle (&optional msg)
2475 "Toggle font-lock for shell.
2476 With argument MSG show activation/deactivation message."
2478 (python-shell-with-shell-buffer
2479 (set (make-local-variable 'python-shell-font-lock-enable)
2480 (not python-shell-font-lock-enable))
2481 (if python-shell-font-lock-enable
2482 (python-shell-font-lock-turn-on msg)
2483 (python-shell-font-lock-turn-off msg))
2484 python-shell-font-lock-enable))
2486 ;; Used to hold user interactive overrides to
2487 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2488 ;; will be made buffer-local by `inferior-python-mode':
2489 (defvar python-shell--interpreter)
2490 (defvar python-shell--interpreter-args)
2492 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2493 "Major mode for Python inferior process.
2494 Runs a Python interpreter as a subprocess of Emacs, with Python
2495 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2496 and `python-shell-interpreter-args' control which Python
2497 interpreter is run. Variables
2498 `python-shell-prompt-regexp',
2499 `python-shell-prompt-output-regexp',
2500 `python-shell-prompt-block-regexp',
2501 `python-shell-font-lock-enable',
2502 `python-shell-completion-setup-code',
2503 `python-shell-completion-string-code',
2504 `python-eldoc-setup-code', `python-eldoc-string-code',
2505 `python-ffap-setup-code' and `python-ffap-string-code' can
2506 customize this mode for different Python interpreters.
2508 This mode resets `comint-output-filter-functions' locally, so you
2509 may want to re-add custom functions to it using the
2510 `inferior-python-mode-hook'.
2512 You can also add additional setup code to be run at
2513 initialization of the interpreter via `python-shell-setup-codes'
2516 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2517 (when python-shell--parent-buffer
2518 (python-util-clone-local-variables python-shell--parent-buffer))
2519 ;; Users can interactively override default values for
2520 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2521 ;; when calling `run-python'. This ensures values let-bound in
2522 ;; `python-shell-make-comint' are locally set if needed.
2523 (set (make-local-variable 'python-shell-interpreter)
2524 (or python-shell--interpreter python-shell-interpreter))
2525 (set (make-local-variable 'python-shell-interpreter-args)
2526 (or python-shell--interpreter-args python-shell-interpreter-args))
2527 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2528 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2529 (python-shell-prompt-set-calculated-regexps)
2530 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2531 (set (make-local-variable 'comint-prompt-read-only) t)
2532 (setq mode-line-process '(":%s"))
2533 (set (make-local-variable 'comint-output-filter-functions)
2534 '(ansi-color-process-output
2535 python-pdbtrack-comint-output-filter-function
2536 python-comint-postoutput-scroll-to-bottom))
2537 (set (make-local-variable 'compilation-error-regexp-alist)
2538 python-shell-compilation-regexp-alist)
2539 (add-hook 'completion-at-point-functions
2540 #'python-shell-completion-at-point nil 'local)
2541 (define-key inferior-python-mode-map "\t"
2542 'python-shell-completion-complete-or-indent)
2543 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2544 (make-local-variable 'python-pdbtrack-tracked-buffer)
2545 (make-local-variable 'python-shell-internal-last-output)
2546 (when python-shell-font-lock-enable
2547 (python-shell-font-lock-turn-on))
2548 (compilation-shell-minor-mode 1)
2549 (python-shell-accept-process-output
2550 (get-buffer-process (current-buffer))))
2552 (defun python-shell-make-comint (cmd proc-name &optional show internal)
2553 "Create a Python shell comint buffer.
2554 CMD is the Python command to be executed and PROC-NAME is the
2555 process name the comint buffer will get. After the comint buffer
2556 is created the `inferior-python-mode' is activated. When
2557 optional argument SHOW is non-nil the buffer is shown. When
2558 optional argument INTERNAL is non-nil this process is run on a
2559 buffer with a name that starts with a space, following the Emacs
2560 convention for temporary/internal buffers, and also makes sure
2561 the user is not queried for confirmation when the process is
2564 (let* ((proc-buffer-name
2565 (format (if (not internal) "*%s*" " *%s*") proc-name))
2566 (process-environment (python-shell-calculate-process-environment))
2567 (exec-path (python-shell-calculate-exec-path)))
2568 (when (not (comint-check-proc proc-buffer-name))
2569 (let* ((cmdlist (split-string-and-unquote cmd))
2570 (interpreter (car cmdlist))
2571 (args (cdr cmdlist))
2572 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2573 interpreter nil args))
2574 (python-shell--parent-buffer (current-buffer))
2575 (process (get-buffer-process buffer))
2576 ;; Users can override the interpreter and args
2577 ;; interactively when calling `run-python', let-binding
2578 ;; these allows to have the new right values in all
2579 ;; setup code that is done in `inferior-python-mode',
2580 ;; which is important, especially for prompt detection.
2581 (python-shell--interpreter interpreter)
2582 (python-shell--interpreter-args
2583 (mapconcat #'identity args " ")))
2584 (with-current-buffer buffer
2585 (inferior-python-mode))
2586 (when show (display-buffer buffer))
2587 (and internal (set-process-query-on-exit-flag process nil))))
2591 (defun run-python (&optional cmd dedicated show)
2592 "Run an inferior Python process.
2594 Argument CMD defaults to `python-shell-calculate-command' return
2595 value. When called interactively with `prefix-arg', it allows
2596 the user to edit such value and choose whether the interpreter
2597 should be DEDICATED for the current buffer. When numeric prefix
2598 arg is other than 0 or 4 do not SHOW.
2600 For a given buffer and same values of DEDICATED, if a process is
2601 already running for it, it will do nothing. This means that if
2602 the current buffer is using a global process, the user is still
2603 able to switch it to use a dedicated one.
2605 Runs the hook `inferior-python-mode-hook' after
2606 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2607 process buffer for a list of commands.)"
2609 (if current-prefix-arg
2611 (read-shell-command "Run Python: " (python-shell-calculate-command))
2612 (y-or-n-p "Make dedicated process? ")
2613 (= (prefix-numeric-value current-prefix-arg) 4))
2614 (list (python-shell-calculate-command) nil t)))
2616 (python-shell-make-comint
2617 (or cmd (python-shell-calculate-command))
2618 (python-shell-get-process-name dedicated) show)))
2620 (defun run-python-internal ()
2621 "Run an inferior Internal Python process.
2622 Input and output via buffer named after
2623 `python-shell-internal-buffer-name' and what
2624 `python-shell-internal-get-process-name' returns.
2626 This new kind of shell is intended to be used for generic
2627 communication related to defined configurations; the main
2628 difference with global or dedicated shells is that these ones are
2629 attached to a configuration, not a buffer. This means that can
2630 be used for example to retrieve the sys.path and other stuff,
2631 without messing with user shells. Note that
2632 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2633 are set to nil for these shells, so setup codes are not sent at
2635 (let ((python-shell-font-lock-enable nil)
2636 (inferior-python-mode-hook nil))
2638 (python-shell-make-comint
2639 (python-shell-calculate-command)
2640 (python-shell-internal-get-process-name) nil t))))
2642 (defun python-shell-get-buffer ()
2643 "Return inferior Python buffer for current buffer.
2644 If current buffer is in `inferior-python-mode', return it."
2645 (if (derived-mode-p 'inferior-python-mode)
2647 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2648 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2649 (global-proc-name (python-shell-get-process-name nil))
2650 (global-proc-buffer-name (format "*%s*" global-proc-name))
2651 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2652 (global-running (comint-check-proc global-proc-buffer-name)))
2653 ;; Always prefer dedicated
2654 (or (and dedicated-running dedicated-proc-buffer-name)
2655 (and global-running global-proc-buffer-name)))))
2657 (defun python-shell-get-process ()
2658 "Return inferior Python process for current buffer."
2659 (get-buffer-process (python-shell-get-buffer)))
2661 (defun python-shell-get-process-or-error (&optional interactivep)
2662 "Return inferior Python process for current buffer or signal error.
2663 When argument INTERACTIVEP is non-nil, use `user-error' instead
2664 of `error' with a user-friendly message."
2665 (or (python-shell-get-process)
2668 "Start a Python process first with `M-x run-python' or `%s'."
2672 #'run-python overriding-local-map t)))
2674 "No inferior Python process running."))))
2676 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2677 "Get or create an inferior Python process for current buffer and return it.
2678 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2679 are used to start the shell. If those arguments are not
2680 provided, `run-python' is called interactively and the user will
2681 be asked for their values."
2682 (let ((shell-process (python-shell-get-process)))
2683 (when (not shell-process)
2685 ;; XXX: Refactor code such that calling `run-python'
2686 ;; interactively is not needed anymore.
2687 (call-interactively 'run-python)
2688 (run-python cmd dedicated show)))
2689 (or shell-process (python-shell-get-process))))
2692 #'python-shell-get-or-create-process
2693 "Instead call `python-shell-get-process' and create one if returns nil."
2696 (defvar python-shell-internal-buffer nil
2697 "Current internal shell buffer for the current buffer.
2698 This is really not necessary at all for the code to work but it's
2699 there for compatibility with CEDET.")
2701 (defvar python-shell-internal-last-output nil
2702 "Last output captured by the internal shell.
2703 This is really not necessary at all for the code to work but it's
2704 there for compatibility with CEDET.")
2706 (defun python-shell-internal-get-or-create-process ()
2707 "Get or create an inferior Internal Python process."
2708 (let ((proc-name (python-shell-internal-get-process-name)))
2709 (if (process-live-p proc-name)
2710 (get-process proc-name)
2711 (run-python-internal))))
2713 (define-obsolete-function-alias
2714 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2716 (define-obsolete-variable-alias
2717 'python-buffer 'python-shell-internal-buffer "24.3")
2719 (define-obsolete-variable-alias
2720 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2722 (defun python-shell--save-temp-file (string)
2723 (let* ((temporary-file-directory
2724 (if (file-remote-p default-directory)
2725 (concat (file-remote-p default-directory) "/tmp")
2726 temporary-file-directory))
2727 (temp-file-name (make-temp-file "py"))
2728 (coding-system-for-write (python-info-encoding)))
2729 (with-temp-file temp-file-name
2731 (delete-trailing-whitespace))
2734 (defun python-shell-send-string (string &optional process msg)
2735 "Send STRING to inferior Python PROCESS.
2736 When optional argument MSG is non-nil, forces display of a
2737 user-friendly message if there's no process running; defaults to
2738 t when called interactively."
2740 (list (read-string "Python command: ") nil t))
2741 (let ((process (or process (python-shell-get-process-or-error msg))))
2742 (if (string-match ".\n+." string) ;Multiline.
2743 (let* ((temp-file-name (python-shell--save-temp-file string))
2744 (file-name (or (buffer-file-name) temp-file-name)))
2745 (python-shell-send-file file-name process temp-file-name t))
2746 (comint-send-string process string)
2747 (when (or (not (string-match "\n\\'" string))
2748 (string-match "\n[ \t].*\n?\\'" string))
2749 (comint-send-string process "\n")))))
2751 (defvar python-shell-output-filter-in-progress nil)
2752 (defvar python-shell-output-filter-buffer nil)
2754 (defun python-shell-output-filter (string)
2755 "Filter used in `python-shell-send-string-no-output' to grab output.
2756 STRING is the output received to this point from the process.
2757 This filter saves received output from the process in
2758 `python-shell-output-filter-buffer' and stops receiving it after
2759 detecting a prompt at the end of the buffer."
2761 string (ansi-color-filter-apply string)
2762 python-shell-output-filter-buffer
2763 (concat python-shell-output-filter-buffer string))
2764 (when (python-shell-comint-end-of-output-p
2765 python-shell-output-filter-buffer)
2766 ;; Output ends when `python-shell-output-filter-buffer' contains
2767 ;; the prompt attached at the end of it.
2768 (setq python-shell-output-filter-in-progress nil
2769 python-shell-output-filter-buffer
2770 (substring python-shell-output-filter-buffer
2771 0 (match-beginning 0)))
2773 python-shell--prompt-calculated-output-regexp
2774 python-shell-output-filter-buffer)
2775 ;; Some shells, like IPython might append a prompt before the
2776 ;; output, clean that.
2777 (setq python-shell-output-filter-buffer
2778 (substring python-shell-output-filter-buffer (match-end 0)))))
2781 (defun python-shell-send-string-no-output (string &optional process)
2782 "Send STRING to PROCESS and inhibit output.
2784 (let ((process (or process (python-shell-get-process-or-error)))
2785 (comint-preoutput-filter-functions
2786 '(python-shell-output-filter))
2787 (python-shell-output-filter-in-progress t)
2791 (python-shell-send-string string process)
2792 (while python-shell-output-filter-in-progress
2793 ;; `python-shell-output-filter' takes care of setting
2794 ;; `python-shell-output-filter-in-progress' to NIL after it
2795 ;; detects end of output.
2796 (accept-process-output process))
2798 python-shell-output-filter-buffer
2799 (setq python-shell-output-filter-buffer nil)))
2800 (with-current-buffer (process-buffer process)
2801 (comint-interrupt-subjob)))))
2803 (defun python-shell-internal-send-string (string)
2804 "Send STRING to the Internal Python interpreter.
2805 Returns the output. See `python-shell-send-string-no-output'."
2806 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2807 ;; updated to support this new mode.
2808 (setq python-shell-internal-last-output
2809 (python-shell-send-string-no-output
2810 ;; Makes this function compatible with the old
2811 ;; python-send-receive. (At least for CEDET).
2812 (replace-regexp-in-string "_emacs_out +" "" string)
2813 (python-shell-internal-get-or-create-process))))
2815 (define-obsolete-function-alias
2816 'python-send-receive 'python-shell-internal-send-string "24.3")
2818 (define-obsolete-function-alias
2819 'python-send-string 'python-shell-internal-send-string "24.3")
2821 (defun python-shell-buffer-substring (start end &optional nomain)
2822 "Send buffer substring from START to END formatted for shell.
2823 This is a wrapper over `buffer-substring' that takes care of
2824 different transformations for the code sent to be evaluated in
2826 1. When optional argument NOMAIN is non-nil everything under an
2827 \"if __name__ == '__main__'\" block will be removed.
2828 2. When a subregion of the buffer is sent, it takes care of
2829 appending extra empty lines so tracebacks are correct.
2830 3. When the region sent is a substring of the current buffer, a
2831 coding cookie is added.
2832 4. Wraps indented regions under an \"if True:\" block so the
2833 interpreter evaluates them correctly."
2834 (let* ((substring (buffer-substring-no-properties start end))
2835 (starts-at-point-min-p (save-restriction
2837 (= (point-min) start)))
2838 (encoding (python-info-encoding))
2839 (fillstr (when (not starts-at-point-min-p)
2841 (format "# -*- coding: %s -*-\n" encoding)
2843 ;; Subtract 2 because of the coding cookie.
2844 (- (line-number-at-pos start) 2) ?\n))))
2845 (toplevel-block-p (save-excursion
2847 (or (zerop (line-number-at-pos start))
2849 (python-util-forward-comment 1)
2850 (zerop (current-indentation)))))))
2853 (if fillstr (insert fillstr))
2855 (goto-char (point-min))
2856 (when (not toplevel-block-p)
2858 (delete-region (point) (line-end-position)))
2860 (let* ((if-name-main-start-end
2863 (when (python-nav-if-name-main)
2865 (progn (python-nav-forward-sexp-safe)
2866 ;; Include ending newline
2869 ;; Oh destructuring bind, how I miss you.
2870 (if-name-main-start (car if-name-main-start-end))
2871 (if-name-main-end (cdr if-name-main-start-end))
2872 (fillstr (make-string
2873 (- (line-number-at-pos if-name-main-end)
2874 (line-number-at-pos if-name-main-start)) ?\n)))
2875 (when if-name-main-start-end
2876 (goto-char if-name-main-start)
2877 (delete-region if-name-main-start if-name-main-end)
2879 ;; Ensure there's only one coding cookie in the generated string.
2880 (goto-char (point-min))
2881 (when (looking-at-p (python-rx coding-cookie))
2883 (when (looking-at-p (python-rx coding-cookie))
2885 (line-beginning-position) (line-end-position))))
2886 (buffer-substring-no-properties (point-min) (point-max)))))
2888 (defun python-shell-send-region (start end &optional send-main msg)
2889 "Send the region delimited by START and END to inferior Python process.
2890 When optional argument SEND-MAIN is non-nil, allow execution of
2891 code inside blocks delimited by \"if __name__== '__main__':\".
2892 When called interactively SEND-MAIN defaults to nil, unless it's
2893 called with prefix argument. When optional argument MSG is
2894 non-nil, forces display of a user-friendly message if there's no
2895 process running; defaults to t when called interactively."
2897 (list (region-beginning) (region-end) current-prefix-arg t))
2898 (let* ((string (python-shell-buffer-substring start end (not send-main)))
2899 (process (python-shell-get-process-or-error msg))
2900 (original-string (buffer-substring-no-properties start end))
2901 (_ (string-match "\\`\n*\\(.*\\)" original-string)))
2902 (message "Sent: %s..." (match-string 1 original-string))
2903 (python-shell-send-string string process)))
2905 (defun python-shell-send-buffer (&optional send-main msg)
2906 "Send the entire buffer to inferior Python process.
2907 When optional argument SEND-MAIN is non-nil, allow execution of
2908 code inside blocks delimited by \"if __name__== '__main__':\".
2909 When called interactively SEND-MAIN defaults to nil, unless it's
2910 called with prefix argument. When optional argument MSG is
2911 non-nil, forces display of a user-friendly message if there's no
2912 process running; defaults to t when called interactively."
2913 (interactive (list current-prefix-arg t))
2916 (python-shell-send-region (point-min) (point-max) send-main msg)))
2918 (defun python-shell-send-defun (&optional arg msg)
2919 "Send the current defun to inferior Python process.
2920 When argument ARG is non-nil do not include decorators. When
2921 optional argument MSG is non-nil, forces display of a
2922 user-friendly message if there's no process running; defaults to
2923 t when called interactively."
2924 (interactive (list current-prefix-arg t))
2926 (python-shell-send-region
2929 (while (and (or (python-nav-beginning-of-defun)
2930 (beginning-of-line 1))
2931 (> (current-indentation) 0)))
2933 (while (and (forward-line -1)
2934 (looking-at (python-rx decorator))))
2938 (or (python-nav-end-of-defun)
2944 (defun python-shell-send-file (file-name &optional process temp-file-name
2946 "Send FILE-NAME to inferior Python PROCESS.
2947 If TEMP-FILE-NAME is passed then that file is used for processing
2948 instead, while internally the shell will continue to use
2949 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
2950 TEMP-FILE-NAME is deleted after evaluation is performed. When
2951 optional argument MSG is non-nil, forces display of a
2952 user-friendly message if there's no process running; defaults to
2953 t when called interactively."
2956 (read-file-name "File to send: ") ; file-name
2958 nil ; temp-file-name
2961 (let* ((process (or process (python-shell-get-process-or-error msg)))
2962 (encoding (with-temp-buffer
2963 (insert-file-contents
2964 (or temp-file-name file-name))
2965 (python-info-encoding)))
2966 (file-name (expand-file-name
2967 (or (file-remote-p file-name 'localname)
2969 (temp-file-name (when temp-file-name
2971 (or (file-remote-p temp-file-name 'localname)
2973 (python-shell-send-string
2976 "import codecs, os;"
2977 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
2978 "__code = __pyfile.read().encode('''%s''');"
2980 (when (and delete temp-file-name)
2981 (format "os.remove('''%s''');" temp-file-name))
2982 "exec(compile(__code, '''%s''', 'exec'));")
2983 (or temp-file-name file-name) encoding encoding file-name)
2986 (defun python-shell-switch-to-shell (&optional msg)
2987 "Switch to inferior Python process buffer.
2988 When optional argument MSG is non-nil, forces display of a
2989 user-friendly message if there's no process running; defaults to
2990 t when called interactively."
2993 (process-buffer (python-shell-get-process-or-error msg)) nil t))
2995 (defun python-shell-send-setup-code ()
2996 "Send all setup code for shell.
2997 This function takes the list of setup code to send from the
2998 `python-shell-setup-codes' list."
2999 (let ((process (python-shell-get-process))
3003 (cond ((stringp elt) elt)
3004 ((symbolp elt) (symbol-value elt))
3006 python-shell-setup-codes
3008 "\n\nprint ('python.el: sent setup code')")))
3009 (python-shell-send-string code process)
3010 (python-shell-accept-process-output process)))
3012 (add-hook 'inferior-python-mode-hook
3013 #'python-shell-send-setup-code)
3016 ;;; Shell completion
3018 (defcustom python-shell-completion-setup-code
3022 def __PYTHON_EL_get_completions(text):
3025 def __PYTHON_EL_get_completions(text):
3030 import builtins as __builtin__
3031 builtins = dir(__builtin__)
3033 is_ipython = ('__IPYTHON__' in builtins or
3034 '__IPYTHON__active' in builtins)
3035 splits = text.split()
3036 is_module = splits and splits[0] in ('from', 'import')
3038 if is_ipython and is_module:
3039 from IPython.core.completerlib import module_completion
3040 completions = module_completion(text.strip())
3041 elif is_ipython and '__IP' in builtins:
3042 completions = __IP.complete(text)
3043 elif is_ipython and 'get_ipython' in builtins:
3044 completions = get_ipython().Completer.all_completions(text)
3046 # Try to reuse current completer.
3047 completer = readline.get_completer()
3049 # importing rlcompleter sets the completer, use it as a
3050 # last resort to avoid breaking customizations.
3052 completer = readline.get_completer()
3055 completion = completer(text, i)
3059 completions.append(completion)
3063 "Code used to setup completion in inferior Python processes."
3067 (defcustom python-shell-completion-string-code
3068 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3069 "Python code used to get a string of completions separated by semicolons.
3070 The string passed to the function is the current python name or
3071 the full statement in the case of imports."
3075 (define-obsolete-variable-alias
3076 'python-shell-completion-module-string-code
3077 'python-shell-completion-string-code
3079 "Completion string code must also autocomplete modules.")
3081 (define-obsolete-variable-alias
3082 'python-shell-completion-pdb-string-code
3083 'python-shell-completion-string-code
3085 "Completion string code must work for (i)pdb.")
3087 (defcustom python-shell-completion-native-disabled-interpreters
3088 ;; PyPy's readline cannot handle some escape sequences yet.
3090 "List of disabled interpreters.
3091 When a match is found, native completion is disabled."
3092 :type '(repeat string))
3094 (defcustom python-shell-completion-native-enable t
3095 "Enable readline based native completion."
3098 (defcustom python-shell-completion-native-output-timeout 5.0
3099 "Time in seconds to wait for completion output before giving up."
3102 (defcustom python-shell-completion-native-try-output-timeout 1.0
3103 "Time in seconds to wait for *trying* native completion output."
3106 (defvar python-shell-completion-native-redirect-buffer
3107 " *Python completions redirect*"
3108 "Buffer to be used to redirect output of readline commands.")
3110 (defun python-shell-completion-native-interpreter-disabled-p ()
3111 "Return non-nil if interpreter has native completion disabled."
3112 (when python-shell-completion-native-disabled-interpreters
3114 (regexp-opt python-shell-completion-native-disabled-interpreters)
3115 (file-name-nondirectory python-shell-interpreter))))
3117 (defun python-shell-completion-native-try ()
3118 "Return non-nil if can trigger native completion."
3119 (let ((python-shell-completion-native-enable t)
3120 (python-shell-completion-native-output-timeout
3121 python-shell-completion-native-try-output-timeout))
3122 (python-shell-completion-native-get-completions
3123 (get-buffer-process (current-buffer))
3126 (defun python-shell-completion-native-setup ()
3127 "Try to setup native completion, return non-nil on success."
3128 (let ((process (python-shell-get-process)))
3129 (python-shell-send-string "
3130 def __PYTHON_EL_native_completion_setup():
3137 import builtins as __builtin__
3138 builtins = dir(__builtin__)
3139 is_ipython = ('__IPYTHON__' in builtins or
3140 '__IPYTHON__active' in builtins)
3141 class __PYTHON_EL_Completer:
3142 PYTHON_EL_WRAPPED = True
3143 def __init__(self, completer):
3144 self.completer = completer
3145 self.last_completion = None
3146 def __call__(self, text, state):
3148 # The first completion is always a dummy completion. This
3149 # ensures proper output for sole completions and a current
3150 # input safeguard when no completions are available.
3151 self.last_completion = None
3152 completion = '0__dummy_completion__'
3154 completion = self.completer(text, state - 1)
3157 # When no completions are available, two non-sharing
3158 # prefix strings are returned just to ensure output
3159 # while preventing changes to current input.
3160 completion = '1__dummy_completion__'
3161 elif self.last_completion != '~~~~__dummy_completion__':
3162 # This marks the end of output.
3163 completion = '~~~~__dummy_completion__'
3164 elif completion.endswith('('):
3165 # Remove parens on callables as it breaks completion on
3166 # arguments (e.g. str(Ari<tab>)).
3167 completion = completion[:-1]
3168 self.last_completion = completion
3170 completer = readline.get_completer()
3172 # Used as last resort to avoid breaking customizations.
3174 completer = readline.get_completer()
3175 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3176 # Wrap the existing completer function only once.
3177 new_completer = __PYTHON_EL_Completer(completer)
3179 readline.set_completer(new_completer)
3181 # Try both initializations to cope with all IPython versions.
3182 # This works fine for IPython 3.x but not for earlier:
3183 readline.set_completer(new_completer)
3184 # IPython<3 hacks readline such that `readline.set_completer`
3185 # won't work. This workaround injects the new completer
3186 # function into the existing instance directly:
3187 instance = getattr(completer, 'im_self', completer.__self__)
3188 instance.rlcomplete = new_completer
3189 if readline.__doc__ and 'libedit' in readline.__doc__:
3190 readline.parse_and_bind('bind ^I rl_complete')
3192 readline.parse_and_bind('tab: complete')
3193 # Require just one tab to send output.
3194 readline.parse_and_bind('set show-all-if-ambiguous on')
3195 print ('python.el: readline is available')
3197 print ('python.el: readline not available')
3198 __PYTHON_EL_native_completion_setup()"
3200 (python-shell-accept-process-output process)
3201 (when (save-excursion
3203 (regexp-quote "python.el: readline is available") nil t 1))
3204 (python-shell-completion-native-try))))
3206 (defun python-shell-completion-native-turn-off (&optional msg)
3207 "Turn off shell native completions.
3208 With argument MSG show deactivation message."
3210 (python-shell-with-shell-buffer
3211 (set (make-local-variable 'python-shell-completion-native-enable) nil)
3213 (message "Shell native completion is disabled, using fallback"))))
3215 (defun python-shell-completion-native-turn-on (&optional msg)
3216 "Turn on shell native completions.
3217 With argument MSG show deactivation message."
3219 (python-shell-with-shell-buffer
3220 (set (make-local-variable 'python-shell-completion-native-enable) t)
3221 (python-shell-completion-native-turn-on-maybe msg)))
3223 (defun python-shell-completion-native-turn-on-maybe (&optional msg)
3224 "Turn on native completions if enabled and available.
3225 With argument MSG show activation/deactivation message."
3227 (python-shell-with-shell-buffer
3228 (when python-shell-completion-native-enable
3230 ((python-shell-completion-native-interpreter-disabled-p)
3231 (python-shell-completion-native-turn-off msg))
3232 ((python-shell-completion-native-setup)
3234 (message "Shell native completion is enabled.")))
3236 '(python python-shell-completion-native-turn-on-maybe)
3239 "Your `python-shell-interpreter' doesn't seem to "
3240 "support readline, yet `python-shell-completion-native' "
3241 (format "was t and %S is not part of the "
3242 (file-name-nondirectory python-shell-interpreter))
3243 "`python-shell-completion-native-disabled-interpreters' "
3244 "list. Native completions have been disabled locally. "))
3245 (python-shell-completion-native-turn-off msg))))))
3247 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3248 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3249 (python-shell-completion-native-turn-on-maybe t))
3251 (add-hook 'inferior-python-mode-hook
3252 #'python-shell-completion-native-turn-on-maybe-with-msg)
3254 (defun python-shell-completion-native-toggle (&optional msg)
3255 "Toggle shell native completion.
3256 With argument MSG show activation/deactivation message."
3258 (python-shell-with-shell-buffer
3259 (if python-shell-completion-native-enable
3260 (python-shell-completion-native-turn-off msg)
3261 (python-shell-completion-native-turn-on msg))
3262 python-shell-completion-native-enable))
3264 (defun python-shell-completion-native-get-completions (process import input)
3265 "Get completions using native readline for PROCESS.
3266 When IMPORT is non-nil takes precedence over INPUT for
3268 (with-current-buffer (process-buffer process)
3269 (when (and python-shell-completion-native-enable
3270 (python-util-comint-last-prompt)
3271 (>= (point) (cdr (python-util-comint-last-prompt))))
3272 (let* ((input (or import input))
3273 (original-filter-fn (process-filter process))
3274 (redirect-buffer (get-buffer-create
3275 python-shell-completion-native-redirect-buffer))
3276 (separators (python-rx (or whitespace open-paren close-paren)))
3278 (new-input (concat input trigger))
3281 (+ (- (point-max) (comint-bol)) (length new-input))))
3282 (delete-line-command (make-string input-length ?\b))
3283 (input-to-send (concat new-input delete-line-command)))
3284 ;; Ensure restoring the process filter, even if the user quits
3285 ;; or there's some other error.
3287 (with-current-buffer redirect-buffer
3288 ;; Cleanup the redirect buffer
3289 (delete-region (point-min) (point-max))
3290 ;; Mimic `comint-redirect-send-command', unfortunately it
3291 ;; can't be used here because it expects a newline in the
3292 ;; command and that's exactly what we are trying to avoid.
3293 (let ((comint-redirect-echo-input nil)
3294 (comint-redirect-verbose nil)
3295 (comint-redirect-perform-sanity-check nil)
3296 (comint-redirect-insert-matching-regexp nil)
3297 ;; Feed it some regex that will never match.
3298 (comint-redirect-finished-regexp "^\\'$")
3299 (comint-redirect-output-buffer redirect-buffer)
3300 (current-time (float-time)))
3301 ;; Compatibility with Emacs 24.x. Comint changed and
3302 ;; now `comint-redirect-filter' gets 3 args. This
3303 ;; checks which version of `comint-redirect-filter' is
3304 ;; in use based on its args and uses `apply-partially'
3305 ;; to make it up for the 3 args case.
3307 (help-function-arglist 'comint-redirect-filter)) 3)
3309 process (apply-partially
3310 #'comint-redirect-filter original-filter-fn))
3311 (set-process-filter process #'comint-redirect-filter))
3312 (process-send-string process input-to-send)
3313 ;; Grab output until our dummy completion used as
3314 ;; output end marker is found. Output is accepted
3315 ;; *very* quickly to keep the shell super-responsive.
3316 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t))
3317 (< (- (float-time) current-time)
3318 python-shell-completion-native-output-timeout))
3319 (accept-process-output process 0.01))
3320 (cl-remove-duplicates
3323 (string-match "__dummy_completion__" c))
3325 (buffer-substring-no-properties
3326 (point-min) (point-max))
3329 (set-process-filter process original-filter-fn))))))
3331 (defun python-shell-completion-get-completions (process import input)
3332 "Do completion at point using PROCESS for IMPORT or INPUT.
3333 When IMPORT is non-nil takes precedence over INPUT for
3335 (with-current-buffer (process-buffer process)
3337 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3338 (buffer-substring-no-properties
3339 (car prompt-boundaries) (cdr prompt-boundaries))))
3341 ;; Check whether a prompt matches a pdb string, an import
3342 ;; statement or just the standard prompt and use the
3343 ;; correct python-shell-completion-*-code string
3344 (cond ((and (string-match
3345 (concat "^" python-shell-prompt-pdb-regexp) prompt))
3346 ;; Since there are no guarantees the user will remain
3347 ;; in the same context where completion code was sent
3348 ;; (e.g. user steps into a function), safeguard
3349 ;; resending completion setup continuously.
3350 (concat python-shell-completion-setup-code
3351 "\nprint (" python-shell-completion-string-code ")"))
3353 python-shell--prompt-calculated-input-regexp prompt)
3354 python-shell-completion-string-code)
3356 (subject (or import input)))
3357 (and completion-code
3358 (> (length input) 0)
3360 (python-util-strip-string
3361 (python-shell-send-string-no-output
3362 (format completion-code subject) process))))
3363 (and (> (length completions) 2)
3364 (split-string completions
3365 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
3367 (defun python-shell-completion-at-point (&optional process)
3368 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3369 Optional argument PROCESS forces completions to be retrieved
3370 using that one instead of current buffer's process."
3371 (setq process (or process (get-buffer-process (current-buffer))))
3372 (let* ((line-start (if (derived-mode-p 'inferior-python-mode)
3373 ;; Working on a shell buffer: use prompt end.
3374 (cdr (python-util-comint-last-prompt))
3375 (line-beginning-position)))
3377 (when (string-match-p
3378 (rx (* space) word-start (or "from" "import") word-end space)
3379 (buffer-substring-no-properties line-start (point)))
3380 (buffer-substring-no-properties line-start (point))))
3383 (if (not (re-search-backward
3385 (or whitespace open-paren close-paren string-delimiter))
3389 (forward-char (length (match-string-no-properties 0)))
3393 (if python-shell-completion-native-enable
3394 #'python-shell-completion-native-get-completions
3395 #'python-shell-completion-get-completions)))
3397 (completion-table-dynamic
3400 process import-statement)))))
3402 (define-obsolete-function-alias
3403 'python-shell-completion-complete-at-point
3404 'python-shell-completion-at-point
3407 (defun python-shell-completion-complete-or-indent ()
3408 "Complete or indent depending on the context.
3409 If content before pointer is all whitespace, indent.
3410 If not try to complete."
3412 (if (string-match "^[[:space:]]*$"
3413 (buffer-substring (comint-line-beginning-position)
3415 (indent-for-tab-command)
3416 (completion-at-point)))
3419 ;;; PDB Track integration
3421 (defcustom python-pdbtrack-activate t
3422 "Non-nil makes Python shell enable pdbtracking."
3427 (defcustom python-pdbtrack-stacktrace-info-regexp
3428 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3429 "Regular expression matching stacktrace information.
3430 Used to extract the current line and module being inspected."
3435 (defvar python-pdbtrack-tracked-buffer nil
3436 "Variable containing the value of the current tracked buffer.
3437 Never set this variable directly, use
3438 `python-pdbtrack-set-tracked-buffer' instead.")
3440 (defvar python-pdbtrack-buffers-to-kill nil
3441 "List of buffers to be deleted after tracking finishes.")
3443 (defun python-pdbtrack-set-tracked-buffer (file-name)
3444 "Set the buffer for FILE-NAME as the tracked buffer.
3445 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3446 Returns the tracked buffer."
3447 (let ((file-buffer (get-file-buffer
3448 (concat (file-remote-p default-directory)
3451 (setq python-pdbtrack-tracked-buffer file-buffer)
3452 (setq file-buffer (find-file-noselect file-name))
3453 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3454 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3457 (defun python-pdbtrack-comint-output-filter-function (output)
3458 "Move overlay arrow to current pdb line in tracked buffer.
3459 Argument OUTPUT is a string with the output from the comint process."
3460 (when (and python-pdbtrack-activate (not (string= output "")))
3461 (let* ((full-output (ansi-color-filter-apply
3462 (buffer-substring comint-last-input-end (point-max))))
3466 (insert full-output)
3467 ;; When the debugger encounters a pdb.set_trace()
3468 ;; command, it prints a single stack frame. Sometimes
3469 ;; it prints a bit of extra information about the
3470 ;; arguments of the present function. When ipdb
3471 ;; encounters an exception, it prints the _entire_ stack
3472 ;; trace. To handle all of these cases, we want to find
3473 ;; the _last_ stack frame printed in the most recent
3474 ;; batch of output, then jump to the corresponding
3475 ;; file/line number.
3476 (goto-char (point-max))
3477 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3478 (setq line-number (string-to-number
3479 (match-string-no-properties 2)))
3480 (match-string-no-properties 1)))))
3481 (if (and file-name line-number)
3482 (let* ((tracked-buffer
3483 (python-pdbtrack-set-tracked-buffer file-name))
3484 (shell-buffer (current-buffer))
3485 (tracked-buffer-window (get-buffer-window tracked-buffer))
3486 (tracked-buffer-line-pos))
3487 (with-current-buffer tracked-buffer
3488 (set (make-local-variable 'overlay-arrow-string) "=>")
3489 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3490 (setq tracked-buffer-line-pos (progn
3491 (goto-char (point-min))
3492 (forward-line (1- line-number))
3494 (when tracked-buffer-window
3496 tracked-buffer-window tracked-buffer-line-pos))
3497 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3498 (pop-to-buffer tracked-buffer)
3499 (switch-to-buffer-other-window shell-buffer))
3500 (when python-pdbtrack-tracked-buffer
3501 (with-current-buffer python-pdbtrack-tracked-buffer
3502 (set-marker overlay-arrow-position nil))
3503 (mapc #'(lambda (buffer)
3504 (ignore-errors (kill-buffer buffer)))
3505 python-pdbtrack-buffers-to-kill)
3506 (setq python-pdbtrack-tracked-buffer nil
3507 python-pdbtrack-buffers-to-kill nil)))))
3511 ;;; Symbol completion
3513 (defun python-completion-at-point ()
3514 "Function for `completion-at-point-functions' in `python-mode'.
3515 For this to work as best as possible you should call
3516 `python-shell-send-buffer' from time to time so context in
3517 inferior Python process is updated properly."
3518 (let ((process (python-shell-get-process)))
3520 (python-shell-completion-at-point process))))
3522 (define-obsolete-function-alias
3523 'python-completion-complete-at-point
3524 'python-completion-at-point
3530 (defcustom python-fill-comment-function 'python-fill-comment
3531 "Function to fill comments.
3532 This is the function used by `python-fill-paragraph' to
3537 (defcustom python-fill-string-function 'python-fill-string
3538 "Function to fill strings.
3539 This is the function used by `python-fill-paragraph' to
3544 (defcustom python-fill-decorator-function 'python-fill-decorator
3545 "Function to fill decorators.
3546 This is the function used by `python-fill-paragraph' to
3551 (defcustom python-fill-paren-function 'python-fill-paren
3552 "Function to fill parens.
3553 This is the function used by `python-fill-paragraph' to
3558 (defcustom python-fill-docstring-style 'pep-257
3559 "Style used to fill docstrings.
3560 This affects `python-fill-string' behavior with regards to
3561 triple quotes positioning.
3563 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3564 `symmetric', and nil. A value of nil won't care about quotes
3565 position and will treat docstrings a normal string, any other
3566 value may result in one of the following docstring styles:
3571 Process foo, return bar.
3575 Process foo, return bar.
3577 If processing fails throw ProcessingError.
3582 \"\"\"Process foo, return bar.\"\"\"
3585 Process foo, return bar.
3587 If processing fails throw ProcessingError.
3593 \"\"\"Process foo, return bar.\"\"\"
3595 \"\"\"Process foo, return bar.
3597 If processing fails throw ProcessingError.
3603 \"\"\"Process foo, return bar.\"\"\"
3605 \"\"\"Process foo, return bar.
3607 If processing fails throw ProcessingError.
3612 \"\"\"Process foo, return bar.\"\"\"
3615 Process foo, return bar.
3617 If processing fails throw ProcessingError.
3620 (const :tag "Don't format docstrings" nil)
3621 (const :tag "Django's coding standards style." django)
3622 (const :tag "One newline and start and Two at end style." onetwo)
3623 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3624 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3625 (const :tag "Symmetric style." symmetric))
3628 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3630 (defun python-fill-paragraph (&optional justify)
3631 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3632 If any of the current line is in or at the end of a multi-line string,
3633 fill the string or the paragraph of it that point is in, preserving
3634 the string's indentation.
3635 Optional argument JUSTIFY defines if the paragraph should be justified."
3640 ((python-syntax-context 'comment)
3641 (funcall python-fill-comment-function justify))
3642 ;; Strings/Docstrings
3643 ((save-excursion (or (python-syntax-context 'string)
3644 (equal (string-to-syntax "|")
3645 (syntax-after (point)))))
3646 (funcall python-fill-string-function justify))
3648 ((equal (char-after (save-excursion
3649 (python-nav-beginning-of-statement))) ?@)
3650 (funcall python-fill-decorator-function justify))
3652 ((or (python-syntax-context 'paren)
3653 (looking-at (python-rx open-paren))
3655 (skip-syntax-forward "^(" (line-end-position))
3656 (looking-at (python-rx open-paren))))
3657 (funcall python-fill-paren-function justify))
3660 (defun python-fill-comment (&optional justify)
3661 "Comment fill function for `python-fill-paragraph'.
3662 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3663 (fill-comment-paragraph justify))
3665 (defun python-fill-string (&optional justify)
3666 "String fill function for `python-fill-paragraph'.
3667 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3668 (let* ((str-start-pos
3671 (or (python-syntax-context 'string)
3672 (and (equal (string-to-syntax "|")
3673 (syntax-after (point)))
3675 (num-quotes (python-syntax-count-quotes
3676 (char-after str-start-pos) str-start-pos))
3679 (goto-char (+ str-start-pos num-quotes))
3680 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3681 (goto-char (point-max)))
3684 ;; Docstring styles may vary for oneliners and multi-liners.
3685 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3687 (pcase python-fill-docstring-style
3688 ;; delimiters-style is a cons cell with the form
3689 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3690 ;; is NIL means to not add any newlines for start or end
3691 ;; of docstring. See `python-fill-docstring-style' for a
3692 ;; graphic idea of each style.
3693 (`django (cons 1 1))
3694 (`onetwo (and multi-line-p (cons 1 2)))
3695 (`pep-257 (and multi-line-p (cons nil 2)))
3696 (`pep-257-nn (and multi-line-p (cons nil 1)))
3697 (`symmetric (and multi-line-p (cons 1 1)))))
3698 (fill-paragraph-function))
3700 (narrow-to-region str-start-pos str-end-pos)
3701 (fill-paragraph justify))
3703 (when (and (python-info-docstring-p) python-fill-docstring-style)
3704 ;; Add the number of newlines indicated by the selected style
3705 ;; at the start of the docstring.
3706 (goto-char (+ str-start-pos num-quotes))
3707 (delete-region (point) (progn
3708 (skip-syntax-forward "> ")
3710 (and (car delimiters-style)
3711 (or (newline (car delimiters-style)) t)
3712 ;; Indent only if a newline is added.
3713 (indent-according-to-mode))
3714 ;; Add the number of newlines indicated by the selected style
3715 ;; at the end of the docstring.
3716 (goto-char (if (not (= str-end-pos (point-max)))
3717 (- str-end-pos num-quotes)
3719 (delete-region (point) (progn
3720 (skip-syntax-backward "> ")
3722 (and (cdr delimiters-style)
3723 ;; Add newlines only if string ends.
3724 (not (= str-end-pos (point-max)))
3725 (or (newline (cdr delimiters-style)) t)
3726 ;; Again indent only if a newline is added.
3727 (indent-according-to-mode))))) t)
3729 (defun python-fill-decorator (&optional _justify)
3730 "Decorator fill function for `python-fill-paragraph'.
3731 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3734 (defun python-fill-paren (&optional justify)
3735 "Paren fill function for `python-fill-paragraph'.
3736 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3738 (narrow-to-region (progn
3739 (while (python-syntax-context 'paren)
3740 (goto-char (1- (point))))
3741 (line-beginning-position))
3743 (when (not (python-syntax-context 'paren))
3745 (when (not (python-syntax-context 'paren))
3746 (skip-syntax-backward "^)")))
3747 (while (and (python-syntax-context 'paren)
3749 (goto-char (1+ (point))))
3751 (let ((paragraph-start "\f\\|[ \t]*$")
3752 (paragraph-separate ",")
3753 (fill-paragraph-function))
3754 (goto-char (point-min))
3755 (fill-paragraph justify))
3758 (python-indent-line)
3759 (goto-char (line-end-position))))
3765 (defcustom python-skeleton-autoinsert nil
3766 "Non-nil means template skeletons will be automagically inserted.
3767 This happens when pressing \"if<SPACE>\", for example, to prompt for
3773 (define-obsolete-variable-alias
3774 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3776 (defvar python-skeleton-available '()
3777 "Internal list of available skeletons.")
3779 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3780 "Abbrev table for Python mode skeletons."
3782 ;; Allow / inside abbrevs.
3783 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3784 ;; Only expand in code.
3785 :enable-function (lambda ()
3787 (not (python-syntax-comment-or-string-p))
3788 python-skeleton-autoinsert)))
3790 (defmacro python-skeleton-define (name doc &rest skel)
3791 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3792 The skeleton will be bound to python-skeleton-NAME and will
3793 be added to `python-mode-skeleton-abbrev-table'."
3794 (declare (indent 2))
3795 (let* ((name (symbol-name name))
3796 (function-name (intern (concat "python-skeleton-" name))))
3798 (define-abbrev python-mode-skeleton-abbrev-table
3799 ,name "" ',function-name :system t)
3800 (setq python-skeleton-available
3801 (cons ',function-name python-skeleton-available))
3802 (define-skeleton ,function-name
3804 (format "Insert %s statement." name))
3807 (define-abbrev-table 'python-mode-abbrev-table ()
3808 "Abbrev table for Python mode."
3809 :parents (list python-mode-skeleton-abbrev-table))
3811 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3812 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3813 The skeleton will be bound to python-skeleton-NAME."
3814 (declare (indent 2))
3815 (let* ((name (symbol-name name))
3816 (function-name (intern (concat "python-skeleton--" name)))
3818 "Add '%s' clause? " name)))
3821 `(< ,(format "%s:" name) \n \n
3823 `(define-skeleton ,function-name
3825 (format "Auxiliary skeleton for %s statement." name))
3827 (unless (y-or-n-p ,msg)
3831 (python-define-auxiliary-skeleton else nil)
3833 (python-define-auxiliary-skeleton except nil)
3835 (python-define-auxiliary-skeleton finally nil)
3837 (python-skeleton-define if nil
3841 ("other condition, %s: "
3845 '(python-skeleton--else) | ^)
3847 (python-skeleton-define while nil
3851 '(python-skeleton--else) | ^)
3853 (python-skeleton-define for nil
3857 '(python-skeleton--else) | ^)
3859 (python-skeleton-define import nil
3860 "Import from module: "
3861 "from " str & " " | -5
3863 ("Identifier: " str ", ") -2 \n _)
3865 (python-skeleton-define try nil
3871 "except " str ":" \n
3874 '(python-skeleton--except)
3875 '(python-skeleton--else)
3876 '(python-skeleton--finally) | ^)
3878 (python-skeleton-define def nil
3880 "def " str "(" ("Parameter, %s: "
3881 (unless (equal ?\( (char-before)) ", ")
3883 "\"\"\"" - "\"\"\"" \n
3886 (python-skeleton-define class nil
3888 "class " str "(" ("Inheritance, %s: "
3889 (unless (equal ?\( (char-before)) ", ")
3893 "\"\"\"" - "\"\"\"" \n
3896 (defun python-skeleton-add-menu-items ()
3897 "Add menu items to Python->Skeletons menu."
3898 (let ((skeletons (sort python-skeleton-available 'string<)))
3899 (dolist (skeleton skeletons)
3901 nil '("Python" "Skeletons")
3903 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3908 (defcustom python-ffap-setup-code
3909 "def __FFAP_get_module_path(module):
3912 path = __import__(module).__file__
3913 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3918 "Python code to get a module path."
3922 (defcustom python-ffap-string-code
3923 "__FFAP_get_module_path('''%s''')\n"
3924 "Python code used to get a string with the path of a module."
3928 (defun python-ffap-module-path (module)
3929 "Function for `ffap-alist' to return path for MODULE."
3931 (and (derived-mode-p 'inferior-python-mode)
3932 (get-buffer-process (current-buffer)))
3933 (python-shell-get-process))))
3937 (python-shell-send-string-no-output
3938 (format python-ffap-string-code module) process)))
3940 (substring-no-properties module-file 1 -1))))))
3944 (eval-after-load "ffap"
3946 (push '(python-mode . python-ffap-module-path) ffap-alist)
3947 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3952 (defcustom python-check-command
3953 (or (executable-find "pyflakes")
3954 (executable-find "epylint")
3955 "install pyflakes, pylint or something else")
3956 "Command used to check a Python file."
3960 (defcustom python-check-buffer-name
3961 "*Python check: %s*"
3962 "Buffer name used for check commands."
3966 (defvar python-check-custom-command nil
3968 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
3969 (make-variable-buffer-local 'python-check-custom-command)
3971 (defun python-check (command)
3972 "Check a Python file (default current buffer's file).
3973 Runs COMMAND, a shell command, as if by `compile'.
3974 See `python-check-command' for the default."
3976 (list (read-string "Check command: "
3977 (or python-check-custom-command
3978 (concat python-check-command " "
3979 (shell-quote-argument
3981 (let ((name (buffer-file-name)))
3983 (file-name-nondirectory name)))
3985 (setq python-check-custom-command command)
3986 (save-some-buffers (not compilation-ask-about-save) nil)
3987 (let ((process-environment (python-shell-calculate-process-environment))
3988 (exec-path (python-shell-calculate-exec-path)))
3989 (compilation-start command nil
3991 (format python-check-buffer-name command)))))
3996 (defcustom python-eldoc-setup-code
3997 "def __PYDOC_get_help(obj):
4001 str_type = basestring
4004 if isinstance(obj, str_type):
4005 obj = eval(obj, globals())
4006 doc = inspect.getdoc(obj)
4007 if not doc and callable(obj):
4009 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4010 target = obj.__init__
4016 args = inspect.formatargspec(
4017 *inspect.getargspec(target)
4020 doc = '{objtype} {name}{args}'.format(
4021 objtype=objtype, name=name, args=args
4024 doc = doc.splitlines()[0]
4028 "Python code to setup documentation retrieval."
4032 (defcustom python-eldoc-string-code
4033 "__PYDOC_get_help('''%s''')\n"
4034 "Python code used to get a string with the documentation of an object."
4038 (defun python-eldoc--get-symbol-at-point ()
4039 "Get the current symbol for eldoc.
4040 Returns the current symbol handling point within arguments."
4042 (let ((start (python-syntax-context 'paren)))
4047 (memq (char-syntax (char-after)) '(?\ ?-)))
4048 ;; Try to adjust to closest symbol if not in one.
4049 (python-util-forward-comment -1)))
4050 (python-info-current-symbol t)))
4052 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
4053 "Internal implementation to get documentation at point.
4054 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4055 returns will be used. If not FORCE-PROCESS is passed what
4056 `python-shell-get-process' returns is used."
4057 (let ((process (or force-process (python-shell-get-process))))
4059 (let ((input (or force-input
4060 (python-eldoc--get-symbol-at-point))))
4062 ;; Prevent resizing the echo area when iPython is
4063 ;; enabled. Bug#18794.
4064 (python-util-strip-string
4065 (python-shell-send-string-no-output
4066 (format python-eldoc-string-code input)
4069 (defun python-eldoc-function ()
4070 "`eldoc-documentation-function' for Python.
4071 For this to work as best as possible you should call
4072 `python-shell-send-buffer' from time to time so context in
4073 inferior Python process is updated properly."
4074 (python-eldoc--get-doc-at-point))
4076 (defun python-eldoc-at-point (symbol)
4077 "Get help on SYMBOL using `help'.
4078 Interactively, prompt for symbol."
4080 (let ((symbol (python-eldoc--get-symbol-at-point))
4081 (enable-recursive-minibuffers t))
4082 (list (read-string (if symbol
4083 (format "Describe symbol (default %s): " symbol)
4084 "Describe symbol: ")
4086 (message (python-eldoc--get-doc-at-point symbol)))
4091 (defun python-hideshow-forward-sexp-function (arg)
4092 "Python specific `forward-sexp' function for `hs-minor-mode'.
4093 Argument ARG is ignored."
4094 arg ; Shut up, byte compiler.
4095 (python-nav-end-of-defun)
4096 (unless (python-info-current-line-empty-p)
4102 (defvar python-imenu-format-item-label-function
4103 'python-imenu-format-item-label
4104 "Imenu function used to format an item label.
4105 It must be a function with two arguments: TYPE and NAME.")
4107 (defvar python-imenu-format-parent-item-label-function
4108 'python-imenu-format-parent-item-label
4109 "Imenu function used to format a parent item label.
4110 It must be a function with two arguments: TYPE and NAME.")
4112 (defvar python-imenu-format-parent-item-jump-label-function
4113 'python-imenu-format-parent-item-jump-label
4114 "Imenu function used to format a parent jump item label.
4115 It must be a function with two arguments: TYPE and NAME.")
4117 (defun python-imenu-format-item-label (type name)
4118 "Return Imenu label for single node using TYPE and NAME."
4119 (format "%s (%s)" name type))
4121 (defun python-imenu-format-parent-item-label (type name)
4122 "Return Imenu label for parent node using TYPE and NAME."
4123 (format "%s..." (python-imenu-format-item-label type name)))
4125 (defun python-imenu-format-parent-item-jump-label (type _name)
4126 "Return Imenu label for parent node jump using TYPE and NAME."
4127 (if (string= type "class")
4128 "*class definition*"
4129 "*function definition*"))
4131 (defun python-imenu--put-parent (type name pos tree)
4132 "Add the parent with TYPE, NAME and POS to TREE."
4134 (funcall python-imenu-format-item-label-function type name))
4136 (funcall python-imenu-format-parent-item-jump-label-function type name)))
4139 (cons label (cons (cons jump-label pos) tree)))))
4141 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
4142 "Recursively build the tree of nested definitions of a node.
4143 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4144 not be passed explicitly unless you know what you are doing."
4145 (setq min-indent (or min-indent 0)
4146 prev-indent (or prev-indent python-indent-offset))
4147 (let* ((pos (python-nav-backward-defun))
4149 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
4150 (let ((split (split-string (match-string-no-properties 0))))
4151 (setq type (car split))
4154 (funcall python-imenu-format-item-label-function type name)))
4155 (indent (current-indentation))
4156 (children-indent-limit (+ python-indent-offset min-indent)))
4158 ;; Nothing found, probably near to bobp.
4160 ((<= indent min-indent)
4161 ;; The current indentation points that this is a parent
4162 ;; node, add it to the tree and stop recursing.
4163 (python-imenu--put-parent type name pos tree))
4165 (python-imenu--build-tree
4168 (if (<= indent children-indent-limit)
4169 ;; This lies within the children indent offset range,
4170 ;; so it's a normal child of its parent (i.e., not
4171 ;; a child of a child).
4172 (cons (cons label pos) tree)
4173 ;; Oh no, a child of a child?! Fear not, we
4174 ;; know how to roll. We recursively parse these by
4175 ;; swapping prev-indent and min-indent plus adding this
4176 ;; newly found item to a fresh subtree. This works, I
4179 (python-imenu--build-tree
4180 prev-indent indent (list (cons label pos)))
4183 (defun python-imenu-create-index ()
4184 "Return tree Imenu alist for the current Python buffer.
4185 Change `python-imenu-format-item-label-function',
4186 `python-imenu-format-parent-item-label-function',
4187 `python-imenu-format-parent-item-jump-label-function' to
4188 customize how labels are formatted."
4189 (goto-char (point-max))
4192 (while (setq tree (python-imenu--build-tree))
4193 (setq index (cons tree index)))
4196 (defun python-imenu-create-flat-index (&optional alist prefix)
4197 "Return flat outline of the current Python buffer for Imenu.
4198 Optional argument ALIST is the tree to be flattened; when nil
4199 `python-imenu-build-index' is used with
4200 `python-imenu-format-parent-item-jump-label-function'
4201 `python-imenu-format-parent-item-label-function'
4202 `python-imenu-format-item-label-function' set to
4203 (lambda (type name) name)
4204 Optional argument PREFIX is used in recursive calls and should
4205 not be passed explicitly.
4212 (\"decorator\" . 173)
4215 (\"wrapped_f\" . 393))))
4221 (\"decorator\" . 173)
4222 (\"decorator.wrap\" . 353)
4223 (\"decorator.wrapped_f\" . 393))"
4224 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4229 (let ((name (if prefix
4230 (concat prefix "." (car item))
4233 (cond ((or (numberp pos) (markerp pos))
4234 (list (cons name pos)))
4237 (cons name (cdar pos))
4238 (python-imenu-create-flat-index (cddr item) name))))))
4240 (let* ((fn (lambda (_type name) name))
4241 (python-imenu-format-item-label-function fn)
4242 (python-imenu-format-parent-item-label-function fn)
4243 (python-imenu-format-parent-item-jump-label-function fn))
4244 (python-imenu-create-index))))))
4249 (defun python-info-current-defun (&optional include-type)
4250 "Return name of surrounding function with Python compatible dotty syntax.
4251 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4252 This function can be used as the value of `add-log-current-defun-function'
4253 since it returns nil if point is not inside a defun."
4259 (starting-indentation (current-indentation))
4260 (starting-pos (point))
4265 (while (python-nav-beginning-of-defun 1)
4266 (when (save-match-data
4268 (or (not last-indent)
4269 (< (current-indentation) last-indent))
4273 ;; If this is the first run, we may add
4274 ;; the current defun at point.
4275 (setq first-run nil)
4276 (goto-char starting-pos)
4277 (python-nav-beginning-of-statement)
4278 (beginning-of-line 1)
4280 python-nav-beginning-of-defun-regexp)))
4284 (+ (current-indentation)
4285 python-indent-offset)))
4286 (if (< starting-indentation min-indent)
4287 ;; If the starting indentation is not
4288 ;; within the min defun indent make the
4291 ;; Else go to the end of defun and add
4292 ;; up the current indentation to the
4294 (python-nav-end-of-defun)
4296 (if (>= (current-indentation) min-indent)
4297 (1+ (current-indentation))
4299 (save-match-data (setq last-indent (current-indentation)))
4300 (if (or (not include-type) type)
4301 (setq names (cons (match-string-no-properties 1) names))
4302 (let ((match (split-string (match-string-no-properties 0))))
4303 (setq type (car match))
4304 (setq names (cons (cadr match) names)))))
4305 ;; Stop searching ASAP.
4306 (and (= (current-indentation) 0) (throw 'exit t))))
4308 (concat (and type (format "%s " type))
4309 (mapconcat 'identity names ".")))))))
4311 (defun python-info-current-symbol (&optional replace-self)
4312 "Return current symbol using dotty syntax.
4313 With optional argument REPLACE-SELF convert \"self\" to current
4316 (and (not (python-syntax-comment-or-string-p))
4317 (with-syntax-table python-dotty-syntax-table
4318 (let ((sym (symbol-at-point)))
4320 (substring-no-properties (symbol-name sym))))))))
4322 (if (not replace-self)
4324 (let ((current-defun (python-info-current-defun)))
4325 (if (not current-defun)
4327 (replace-regexp-in-string
4328 (python-rx line-start word-start "self" word-end ?.)
4330 (mapconcat 'identity
4331 (butlast (split-string current-defun "\\."))
4335 (defun python-info-statement-starts-block-p ()
4336 "Return non-nil if current statement opens a block."
4338 (python-nav-beginning-of-statement)
4339 (looking-at (python-rx block-start))))
4341 (defun python-info-statement-ends-block-p ()
4342 "Return non-nil if point is at end of block."
4343 (let ((end-of-block-pos (save-excursion
4344 (python-nav-end-of-block)))
4345 (end-of-statement-pos (save-excursion
4346 (python-nav-end-of-statement))))
4347 (and end-of-block-pos end-of-statement-pos
4348 (= end-of-block-pos end-of-statement-pos))))
4350 (defun python-info-beginning-of-statement-p ()
4351 "Return non-nil if point is at beginning of statement."
4352 (= (point) (save-excursion
4353 (python-nav-beginning-of-statement)
4356 (defun python-info-end-of-statement-p ()
4357 "Return non-nil if point is at end of statement."
4358 (= (point) (save-excursion
4359 (python-nav-end-of-statement)
4362 (defun python-info-beginning-of-block-p ()
4363 "Return non-nil if point is at beginning of block."
4364 (and (python-info-beginning-of-statement-p)
4365 (python-info-statement-starts-block-p)))
4367 (defun python-info-end-of-block-p ()
4368 "Return non-nil if point is at end of block."
4369 (and (python-info-end-of-statement-p)
4370 (python-info-statement-ends-block-p)))
4372 (define-obsolete-function-alias
4373 'python-info-closing-block
4374 'python-info-dedenter-opening-block-position "24.4")
4376 (defun python-info-dedenter-opening-block-position ()
4377 "Return the point of the closest block the current line closes.
4378 Returns nil if point is not on a dedenter statement or no opening
4379 block can be detected. The latter case meaning current file is
4380 likely an invalid python file."
4381 (let ((positions (python-info-dedenter-opening-block-positions))
4382 (indentation (current-indentation))
4384 (while (and (not position)
4387 (goto-char (car positions))
4388 (if (<= (current-indentation) indentation)
4389 (setq position (car positions))
4390 (setq positions (cdr positions)))))
4393 (defun python-info-dedenter-opening-block-positions ()
4394 "Return points of blocks the current line may close sorted by closer.
4395 Returns nil if point is not on a dedenter statement or no opening
4396 block can be detected. The latter case meaning current file is
4397 likely an invalid python file."
4399 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4401 (goto-char dedenter-pos)
4402 (let* ((pairs '(("elif" "elif" "if")
4403 ("else" "if" "elif" "except" "for" "while")
4404 ("except" "except" "try")
4405 ("finally" "else" "except" "try")))
4406 (dedenter (match-string-no-properties 0))
4407 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
4408 (collected-indentations)
4411 (while (python-nav--syntactically
4413 (re-search-backward (python-rx block-start) nil t))
4415 (let ((indentation (current-indentation)))
4416 (when (and (not (memq indentation collected-indentations))
4417 (or (not collected-indentations)
4418 (< indentation (apply #'min collected-indentations))))
4419 (setq collected-indentations
4420 (cons indentation collected-indentations))
4421 (when (member (match-string-no-properties 0)
4422 possible-opening-blocks)
4423 (setq opening-blocks (cons (point) opening-blocks))))
4424 (when (zerop indentation)
4425 (throw 'exit nil)))))
4427 (nreverse opening-blocks))))))
4429 (define-obsolete-function-alias
4430 'python-info-closing-block-message
4431 'python-info-dedenter-opening-block-message "24.4")
4433 (defun python-info-dedenter-opening-block-message ()
4434 "Message the first line of the block the current statement closes."
4435 (let ((point (python-info-dedenter-opening-block-position)))
4439 (message "Closes %s" (save-excursion
4442 (point) (line-end-position))))))))
4444 (defun python-info-dedenter-statement-p ()
4445 "Return point if current statement is a dedenter.
4446 Sets `match-data' to the keyword that starts the dedenter
4449 (python-nav-beginning-of-statement)
4450 (when (and (not (python-syntax-context-type))
4451 (looking-at (python-rx dedenter)))
4454 (defun python-info-line-ends-backslash-p (&optional line-number)
4455 "Return non-nil if current line ends with backslash.
4456 With optional argument LINE-NUMBER, check that line instead."
4461 (python-util-goto-line line-number))
4462 (while (and (not (eobp))
4463 (goto-char (line-end-position))
4464 (python-syntax-context 'paren)
4465 (not (equal (char-before (point)) ?\\)))
4467 (when (equal (char-before) ?\\)
4470 (defun python-info-beginning-of-backslash (&optional line-number)
4471 "Return the point where the backslashed line start.
4472 Optional argument LINE-NUMBER forces the line number to check against."
4477 (python-util-goto-line line-number))
4478 (when (python-info-line-ends-backslash-p)
4479 (while (save-excursion
4480 (goto-char (line-beginning-position))
4481 (python-syntax-context 'paren))
4483 (back-to-indentation)
4486 (defun python-info-continuation-line-p ()
4487 "Check if current line is continuation of another.
4488 When current line is continuation of another return the point
4489 where the continued line ends."
4493 (let* ((context-type (progn
4494 (back-to-indentation)
4495 (python-syntax-context-type)))
4496 (line-start (line-number-at-pos))
4497 (context-start (when context-type
4498 (python-syntax-context context-type))))
4499 (cond ((equal context-type 'paren)
4500 ;; Lines inside a paren are always a continuation line
4501 ;; (except the first one).
4502 (python-util-forward-comment -1)
4504 ((member context-type '(string comment))
4505 ;; move forward an roll again
4506 (goto-char context-start)
4507 (python-util-forward-comment)
4508 (python-info-continuation-line-p))
4510 ;; Not within a paren, string or comment, the only way
4511 ;; we are dealing with a continuation line is that
4512 ;; previous line contains a backslash, and this can
4513 ;; only be the previous line from current
4514 (back-to-indentation)
4515 (python-util-forward-comment -1)
4516 (when (and (equal (1- line-start) (line-number-at-pos))
4517 (python-info-line-ends-backslash-p))
4518 (point-marker))))))))
4520 (defun python-info-block-continuation-line-p ()
4521 "Return non-nil if current line is a continuation of a block."
4523 (when (python-info-continuation-line-p)
4525 (back-to-indentation)
4526 (when (looking-at (python-rx block-start))
4529 (defun python-info-assignment-statement-p (&optional current-line-only)
4530 "Check if current line is an assignment.
4531 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4532 continuations, just check the if current line is an assignment."
4535 (if current-line-only
4536 (back-to-indentation)
4537 (python-nav-beginning-of-statement))
4539 (re-search-forward (python-rx not-simple-operator
4541 (group not-simple-operator))
4542 (line-end-position) t)
4545 ;; The assignment operator should not be inside a string.
4546 (backward-char (length (match-string-no-properties 1)))
4547 (setq found (not (python-syntax-context-type)))))
4549 (skip-syntax-forward " ")
4552 ;; TODO: rename to clarify this is only for the first continuation
4553 ;; line or remove it and move its body to `python-indent-context'.
4554 (defun python-info-assignment-continuation-line-p ()
4555 "Check if current line is the first continuation of an assignment.
4556 When current line is continuation of another with an assignment
4557 return the point of the first non-blank character after the
4560 (when (python-info-continuation-line-p)
4562 (python-info-assignment-statement-p t))))
4564 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4565 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4566 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4568 (beginning-of-line 1)
4569 (looking-at python-nav-beginning-of-defun-regexp))))
4571 (defun python-info-current-line-comment-p ()
4572 "Return non-nil if current line is a comment line."
4574 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4577 (defun python-info-current-line-empty-p ()
4578 "Return non-nil if current line is empty, ignoring whitespace."
4580 (beginning-of-line 1)
4582 (python-rx line-start (* whitespace)
4583 (group (* not-newline))
4584 (* whitespace) line-end))
4585 (string-equal "" (match-string-no-properties 1))))
4587 (defun python-info-docstring-p (&optional syntax-ppss)
4588 "Return non-nil if point is in a docstring.
4589 When optional argument SYNTAX-PPSS is given, use that instead of
4590 point's current `syntax-ppss'."
4591 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4593 (when (and syntax-ppss (python-syntax-context 'string syntax-ppss))
4594 (goto-char (nth 8 syntax-ppss)))
4595 (python-nav-beginning-of-statement)
4597 (indentation (current-indentation))
4598 (backward-sexp-point)
4599 (re (concat "[uU]?[rR]?"
4600 (python-rx string-delimiter))))
4602 (not (python-info-assignment-statement-p))
4604 ;; Allow up to two consecutive docstrings only.
4608 (while (save-excursion
4609 (python-nav-backward-sexp)
4610 (setq backward-sexp-point (point))
4611 (and (= indentation (current-indentation))
4612 (not (bobp)) ; Prevent infloop.
4614 (concat "[uU]?[rR]?"
4615 (python-rx string-delimiter)))))
4616 ;; Previous sexp was a string, restore point.
4617 (goto-char backward-sexp-point)
4620 (python-util-forward-comment -1)
4621 (python-nav-beginning-of-statement)
4623 ((python-info-assignment-statement-p) t)
4624 ((python-info-looking-at-beginning-of-defun))
4627 (defun python-info-encoding-from-cookie ()
4628 "Detect current buffer's encoding from its coding cookie.
4629 Returns the encoding as a symbol."
4630 (let ((first-two-lines
4634 (goto-char (point-min))
4636 (buffer-substring-no-properties
4639 (when (string-match (python-rx coding-cookie) first-two-lines)
4640 (intern (match-string-no-properties 1 first-two-lines)))))
4642 (defun python-info-encoding ()
4643 "Return encoding for file.
4644 Try `python-info-encoding-from-cookie', if none is found then
4646 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4647 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4648 ;; in the worst case scenario python.el will make things work for
4649 ;; Python 2 files with unicode data and no encoding defined.
4650 (or (python-info-encoding-from-cookie)
4654 ;;; Utility functions
4656 (defun python-util-goto-line (line-number)
4657 "Move point to LINE-NUMBER."
4658 (goto-char (point-min))
4659 (forward-line (1- line-number)))
4661 ;; Stolen from org-mode
4662 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4663 "Clone local variables from FROM-BUFFER.
4664 Optional argument REGEXP selects variables to clone and defaults
4668 (and (symbolp (car pair))
4669 (string-match (or regexp "^python-")
4670 (symbol-name (car pair)))
4671 (set (make-local-variable (car pair))
4673 (buffer-local-variables from-buffer)))
4675 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4677 (defun python-util-comint-last-prompt ()
4678 "Return comint last prompt overlay start and end.
4679 This is for compatibility with Emacs < 24.4."
4680 (cond ((bound-and-true-p comint-last-prompt-overlay)
4681 (cons (overlay-start comint-last-prompt-overlay)
4682 (overlay-end comint-last-prompt-overlay)))
4683 ((bound-and-true-p comint-last-prompt)
4687 (defun python-util-forward-comment (&optional direction)
4688 "Python mode specific version of `forward-comment'.
4689 Optional argument DIRECTION defines the direction to move to."
4690 (let ((comment-start (python-syntax-context 'comment))
4691 (factor (if (< (or direction 0) 0)
4695 (goto-char comment-start))
4696 (forward-comment factor)))
4698 (defun python-util-list-directories (directory &optional predicate max-depth)
4699 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4700 Argument PREDICATE defaults to `identity' and must be a function
4701 that takes one argument (a full path) and returns non-nil for
4702 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4703 searching when depth is reached, else don't limit."
4704 (let* ((dir (expand-file-name directory))
4705 (dir-length (length dir))
4706 (predicate (or predicate #'identity))
4707 (to-scan (list dir))
4710 (let ((current-dir (car to-scan)))
4711 (when (funcall predicate current-dir)
4712 (setq tally (cons current-dir tally)))
4713 (setq to-scan (append (cdr to-scan)
4714 (python-util-list-files
4715 current-dir #'file-directory-p)
4717 (when (and max-depth
4719 (length (split-string
4720 (substring current-dir dir-length)
4722 (setq to-scan nil))))
4725 (defun python-util-list-files (dir &optional predicate)
4726 "List files in DIR, filtering with PREDICATE.
4727 Argument PREDICATE defaults to `identity' and must be a function
4728 that takes one argument (a full path) and returns non-nil for
4730 (let ((dir-name (file-name-as-directory dir)))
4732 (mapcar (lambda (file-name)
4733 (let ((full-file-name (expand-file-name file-name dir-name)))
4735 (not (member file-name '("." "..")))
4736 (funcall (or predicate #'identity) full-file-name))
4737 (list full-file-name))))
4738 (directory-files dir-name)))))
4740 (defun python-util-list-packages (dir &optional max-depth)
4741 "List packages in DIR, limited by MAX-DEPTH.
4742 When optional argument MAX-DEPTH is non-nil, stop searching when
4743 depth is reached, else don't limit."
4744 (let* ((dir (expand-file-name dir))
4745 (parent-dir (file-name-directory
4746 (directory-file-name
4747 (file-name-directory
4748 (file-name-as-directory dir)))))
4749 (subpath-length (length parent-dir)))
4752 (replace-regexp-in-string
4753 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4754 (python-util-list-directories
4755 (directory-file-name dir)
4757 (file-exists-p (expand-file-name "__init__.py" dir)))
4760 (defun python-util-popn (lst n)
4761 "Return LST first N elements.
4762 N should be an integer, when negative its opposite is used.
4763 When N is bigger than the length of LST, the list is
4765 (let* ((n (min (abs n)))
4771 (setq acc (cons (car lst) acc)
4776 (defun python-util-strip-string (string)
4777 "Strip STRING whitespace and newlines from end and beginning."
4778 (replace-regexp-in-string
4779 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4780 (: (* (any whitespace ?\r ?\n)) string-end)))
4784 (defun python-util-valid-regexp-p (regexp)
4785 "Return non-nil if REGEXP is valid."
4786 (ignore-errors (string-match regexp "") t))
4789 (defun python-electric-pair-string-delimiter ()
4790 (when (and electric-pair-mode
4791 (memq last-command-event '(?\" ?\'))
4793 (while (eq (char-before (- (point) count)) last-command-event)
4796 (eq (char-after) last-command-event))
4797 (save-excursion (insert (make-string 2 last-command-event)))))
4799 (defvar electric-indent-inhibit)
4802 (define-derived-mode python-mode prog-mode "Python"
4803 "Major mode for editing Python files.
4805 \\{python-mode-map}"
4806 (set (make-local-variable 'tab-width) 8)
4807 (set (make-local-variable 'indent-tabs-mode) nil)
4809 (set (make-local-variable 'comment-start) "# ")
4810 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4812 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4813 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4815 (set (make-local-variable 'forward-sexp-function)
4816 'python-nav-forward-sexp)
4818 (set (make-local-variable 'font-lock-defaults)
4819 '(python-font-lock-keywords
4821 (font-lock-syntactic-face-function
4822 . python-font-lock-syntactic-face-function)))
4824 (set (make-local-variable 'syntax-propertize-function)
4825 python-syntax-propertize-function)
4827 (set (make-local-variable 'indent-line-function)
4828 #'python-indent-line-function)
4829 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4830 ;; Because indentation is not redundant, we cannot safely reindent code.
4831 (set (make-local-variable 'electric-indent-inhibit) t)
4832 (set (make-local-variable 'electric-indent-chars)
4833 (cons ?: electric-indent-chars))
4835 ;; Add """ ... """ pairing to electric-pair-mode.
4836 (add-hook 'post-self-insert-hook
4837 #'python-electric-pair-string-delimiter 'append t)
4839 (set (make-local-variable 'paragraph-start) "\\s-*$")
4840 (set (make-local-variable 'fill-paragraph-function)
4841 #'python-fill-paragraph)
4843 (set (make-local-variable 'beginning-of-defun-function)
4844 #'python-nav-beginning-of-defun)
4845 (set (make-local-variable 'end-of-defun-function)
4846 #'python-nav-end-of-defun)
4848 (add-hook 'completion-at-point-functions
4849 #'python-completion-at-point nil 'local)
4851 (add-hook 'post-self-insert-hook
4852 #'python-indent-post-self-insert-function 'append 'local)
4854 (set (make-local-variable 'imenu-create-index-function)
4855 #'python-imenu-create-index)
4857 (set (make-local-variable 'add-log-current-defun-function)
4858 #'python-info-current-defun)
4860 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4862 (set (make-local-variable 'skeleton-further-elements)
4864 (< '(backward-delete-char-untabify (min python-indent-offset
4866 (^ '(- (1+ (current-indentation))))))
4868 (if (null eldoc-documentation-function)
4870 (set (make-local-variable 'eldoc-documentation-function)
4871 #'python-eldoc-function)
4872 (add-function :before-until (local 'eldoc-documentation-function)
4873 #'python-eldoc-function))
4876 'hs-special-modes-alist
4878 "\\s-*\\(?:def\\|class\\)\\>"
4879 ;; Use the empty string as end regexp so it doesn't default to
4880 ;; "\\s)". This way parens at end of defun are properly hidden.
4883 python-hideshow-forward-sexp-function
4886 (set (make-local-variable 'outline-regexp)
4887 (python-rx (* space) block-start))
4888 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4889 (set (make-local-variable 'outline-level)
4891 "`outline-level' function for Python mode."
4892 (1+ (/ (current-indentation) python-indent-offset))))
4894 (python-skeleton-add-menu-items)
4896 (make-local-variable 'python-shell-internal-buffer)
4898 (when python-indent-guess-indent-offset
4899 (python-indent-guess-indent-offset)))
4906 ;; indent-tabs-mode: nil
4909 ;;; python.el ends here