lisp/let-alist.el (let-alist): Evaluate `alist' only once.
[emacs.git] / lisp / progmodes / python.el
blob35e24e14e1c9eca9b6491a297670e68eeebf5bc0
1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2014 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
7 ;; Version: 0.24.4
8 ;; Maintainer: emacs-devel@gnu.org
9 ;; Created: Jul 2010
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/>.
27 ;;; Commentary:
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
91 ;; your system):
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. Shell completion is implemented in such way that if you
123 ;; change the `python-shell-interpreter' it should be possible to
124 ;; integrate custom logic to calculate completions. To achieve this
125 ;; you just need to set `python-shell-completion-setup-code' and
126 ;; `python-shell-completion-string-code'. The default provided code,
127 ;; enables autocompletion for both CPython and IPython (and ideally
128 ;; any readline based Python shell). This code depends on the
129 ;; readline module, so if you are using some Operating System that
130 ;; bundles Python without it (like Windows), installing pyreadline
131 ;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
132 ;; suffice. To troubleshoot why you are not getting any completions
133 ;; you can try the following in your Python shell:
135 ;; >>> import readline, rlcompleter
137 ;; If you see an error, then you need to either install pyreadline or
138 ;; setup custom code that avoids that dependency.
140 ;; Shell virtualenv support: The shell also contains support for
141 ;; virtualenvs and other special environment modifications thanks to
142 ;; `python-shell-process-environment' and `python-shell-exec-path'.
143 ;; These two variables allows you to modify execution paths and
144 ;; environment variables to make easy for you to setup virtualenv rules
145 ;; or behavior modifications when running shells. Here is an example
146 ;; of how to make shell processes to be run using the /path/to/env/
147 ;; virtualenv:
149 ;; (setq python-shell-process-environment
150 ;; (list
151 ;; (format "PATH=%s" (mapconcat
152 ;; 'identity
153 ;; (reverse
154 ;; (cons (getenv "PATH")
155 ;; '("/path/to/env/bin/")))
156 ;; ":"))
157 ;; "VIRTUAL_ENV=/path/to/env/"))
158 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
160 ;; Since the above is cumbersome and can be programmatically
161 ;; calculated, the variable `python-shell-virtualenv-root' is
162 ;; provided. When this variable is set with the path of the
163 ;; virtualenv to use, `process-environment' and `exec-path' get proper
164 ;; values in order to run shells inside the specified virtualenv. So
165 ;; the following will achieve the same as the previous example:
167 ;; (setq python-shell-virtualenv-root "/path/to/env/")
169 ;; Also the `python-shell-extra-pythonpaths' variable have been
170 ;; introduced as simple way of adding paths to the PYTHONPATH without
171 ;; affecting existing values.
173 ;; Shell package support: you can enable a package in the current
174 ;; shell so that relative imports work properly using the
175 ;; `python-shell-package-enable' command.
177 ;; Shell syntax highlighting: when enabled current input in shell is
178 ;; highlighted. The variable `python-shell-font-lock-enable' controls
179 ;; activation of this feature globally when shells are started.
180 ;; Activation/deactivation can be also controlled on the fly via the
181 ;; `python-shell-font-lock-toggle' command.
183 ;; Pdb tracking: when you execute a block of code that contains some
184 ;; call to pdb (or ipdb) it will prompt the block of code and will
185 ;; follow the execution of pdb marking the current line with an arrow.
187 ;; Symbol completion: you can complete the symbol at point. It uses
188 ;; the shell completion in background so you should run
189 ;; `python-shell-send-buffer' from time to time to get better results.
191 ;; Skeletons: skeletons are provided for simple inserting of things like class,
192 ;; def, for, import, if, try, and while. These skeletons are
193 ;; integrated with abbrev. If you have `abbrev-mode' activated and
194 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
195 ;; the name of any of those defined and hit SPC, they will be
196 ;; automatically expanded. As an alternative you can use the defined
197 ;; skeleton commands: `python-skeleton-<foo>'.
199 ;; FFAP: You can find the filename for a given module when using ffap
200 ;; out of the box. This feature needs an inferior python shell
201 ;; running.
203 ;; Code check: Check the current file for errors with `python-check'
204 ;; using the program defined in `python-check-command'.
206 ;; Eldoc: returns documentation for object at point by using the
207 ;; inferior python subprocess to inspect its documentation. As you
208 ;; might guessed you should run `python-shell-send-buffer' from time
209 ;; to time to get better results too.
211 ;; Imenu: There are two index building functions to be used as
212 ;; `imenu-create-index-function': `python-imenu-create-index' (the
213 ;; default one, builds the alist in form of a tree) and
214 ;; `python-imenu-create-flat-index'. See also
215 ;; `python-imenu-format-item-label-function',
216 ;; `python-imenu-format-parent-item-label-function',
217 ;; `python-imenu-format-parent-item-jump-label-function' variables for
218 ;; changing the way labels are formatted in the tree version.
220 ;; If you used python-mode.el you may miss auto-indentation when
221 ;; inserting newlines. To achieve the same behavior you have two
222 ;; options:
224 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
225 ;; default) and use RET. If this mode is disabled use
226 ;; `newline-and-indent', bound to C-j.
228 ;; 2) Add the following hook in your .emacs:
230 ;; (add-hook 'python-mode-hook
231 ;; #'(lambda ()
232 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
234 ;; I'd recommend the first one since you'll get the same behavior for
235 ;; all modes out-of-the-box.
237 ;;; Installation:
239 ;; Add this to your .emacs:
241 ;; (add-to-list 'load-path "/folder/containing/file")
242 ;; (require 'python)
244 ;;; TODO:
246 ;;; Code:
248 (require 'ansi-color)
249 (require 'cl-lib)
250 (require 'comint)
251 (require 'json)
253 ;; Avoid compiler warnings
254 (defvar view-return-to-alist)
255 (defvar compilation-error-regexp-alist)
256 (defvar outline-heading-end-regexp)
258 (autoload 'comint-mode "comint")
260 ;;;###autoload
261 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
262 ;;;###autoload
263 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
265 (defgroup python nil
266 "Python Language's flying circus support for Emacs."
267 :group 'languages
268 :version "24.3"
269 :link '(emacs-commentary-link "python"))
272 ;;; Bindings
274 (defvar python-mode-map
275 (let ((map (make-sparse-keymap)))
276 ;; Movement
277 (define-key map [remap backward-sentence] 'python-nav-backward-block)
278 (define-key map [remap forward-sentence] 'python-nav-forward-block)
279 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
280 (define-key map "\C-c\C-j" 'imenu)
281 ;; Indent specific
282 (define-key map "\177" 'python-indent-dedent-line-backspace)
283 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
284 (define-key map "\C-c<" 'python-indent-shift-left)
285 (define-key map "\C-c>" 'python-indent-shift-right)
286 ;; Skeletons
287 (define-key map "\C-c\C-tc" 'python-skeleton-class)
288 (define-key map "\C-c\C-td" 'python-skeleton-def)
289 (define-key map "\C-c\C-tf" 'python-skeleton-for)
290 (define-key map "\C-c\C-ti" 'python-skeleton-if)
291 (define-key map "\C-c\C-tm" 'python-skeleton-import)
292 (define-key map "\C-c\C-tt" 'python-skeleton-try)
293 (define-key map "\C-c\C-tw" 'python-skeleton-while)
294 ;; Shell interaction
295 (define-key map "\C-c\C-p" 'run-python)
296 (define-key map "\C-c\C-s" 'python-shell-send-string)
297 (define-key map "\C-c\C-r" 'python-shell-send-region)
298 (define-key map "\C-\M-x" 'python-shell-send-defun)
299 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
300 (define-key map "\C-c\C-l" 'python-shell-send-file)
301 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
302 ;; Some util commands
303 (define-key map "\C-c\C-v" 'python-check)
304 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
305 ;; Utilities
306 (substitute-key-definition 'complete-symbol 'completion-at-point
307 map global-map)
308 (easy-menu-define python-menu map "Python Mode menu"
309 `("Python"
310 :help "Python-specific Features"
311 ["Shift region left" python-indent-shift-left :active mark-active
312 :help "Shift region left by a single indentation step"]
313 ["Shift region right" python-indent-shift-right :active mark-active
314 :help "Shift region right by a single indentation step"]
316 ["Start of def/class" beginning-of-defun
317 :help "Go to start of outermost definition around point"]
318 ["End of def/class" end-of-defun
319 :help "Go to end of definition around point"]
320 ["Mark def/class" mark-defun
321 :help "Mark outermost definition around point"]
322 ["Jump to def/class" imenu
323 :help "Jump to a class or function definition"]
324 "--"
325 ("Skeletons")
326 "---"
327 ["Start interpreter" run-python
328 :help "Run inferior Python process in a separate buffer"]
329 ["Switch to shell" python-shell-switch-to-shell
330 :help "Switch to running inferior Python process"]
331 ["Eval string" python-shell-send-string
332 :help "Eval string in inferior Python session"]
333 ["Eval buffer" python-shell-send-buffer
334 :help "Eval buffer in inferior Python session"]
335 ["Eval region" python-shell-send-region
336 :help "Eval region in inferior Python session"]
337 ["Eval defun" python-shell-send-defun
338 :help "Eval defun in inferior Python session"]
339 ["Eval file" python-shell-send-file
340 :help "Eval file in inferior Python session"]
341 ["Debugger" pdb :help "Run pdb under GUD"]
342 "----"
343 ["Check file" python-check
344 :help "Check file for errors"]
345 ["Help on symbol" python-eldoc-at-point
346 :help "Get help on symbol at point"]
347 ["Complete symbol" completion-at-point
348 :help "Complete symbol before point"]))
349 map)
350 "Keymap for `python-mode'.")
353 ;;; Python specialized rx
355 (eval-when-compile
356 (defconst python-rx-constituents
357 `((block-start . ,(rx symbol-start
358 (or "def" "class" "if" "elif" "else" "try"
359 "except" "finally" "for" "while" "with")
360 symbol-end))
361 (dedenter . ,(rx symbol-start
362 (or "elif" "else" "except" "finally")
363 symbol-end))
364 (block-ender . ,(rx symbol-start
366 "break" "continue" "pass" "raise" "return")
367 symbol-end))
368 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
369 (* (any word ?_))))
370 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
371 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
372 (+ space) "==" (+ space)
373 (any ?' ?\") "__main__" (any ?' ?\")
374 (* space) ?:))
375 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
376 (open-paren . ,(rx (or "{" "[" "(")))
377 (close-paren . ,(rx (or "}" "]" ")")))
378 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
379 ;; FIXME: rx should support (not simple-operator).
380 (not-simple-operator . ,(rx
381 (not
382 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
383 ;; FIXME: Use regexp-opt.
384 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
385 "=" "%" "**" "//" "<<" ">>" "<=" "!="
386 "==" ">=" "is" "not")))
387 ;; FIXME: Use regexp-opt.
388 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
389 ">>=" "<<=" "&=" "^=" "|=")))
390 (string-delimiter . ,(rx (and
391 ;; Match even number of backslashes.
392 (or (not (any ?\\ ?\' ?\")) point
393 ;; Quotes might be preceded by a escaped quote.
394 (and (or (not (any ?\\)) point) ?\\
395 (* ?\\ ?\\) (any ?\' ?\")))
396 (* ?\\ ?\\)
397 ;; Match single or triple quotes of any kind.
398 (group (or "\"" "\"\"\"" "'" "'''"))))))
399 "Additional Python specific sexps for `python-rx'")
401 (defmacro python-rx (&rest regexps)
402 "Python mode specialized rx macro.
403 This variant of `rx' supports common Python named REGEXPS."
404 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
405 (cond ((null regexps)
406 (error "No regexp"))
407 ((cdr regexps)
408 (rx-to-string `(and ,@regexps) t))
410 (rx-to-string (car regexps) t))))))
413 ;;; Font-lock and syntax
415 (eval-when-compile
416 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
417 (pcase type
418 (`'comment
419 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
420 (and (nth 4 ppss) (nth 8 ppss))))
421 (`'string
422 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
423 (and (nth 3 ppss) (nth 8 ppss))))
424 (`'paren
425 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
426 (_ form))))
428 (defun python-syntax-context (type &optional syntax-ppss)
429 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
430 TYPE can be `comment', `string' or `paren'. It returns the start
431 character address of the specified TYPE."
432 (declare (compiler-macro python-syntax--context-compiler-macro))
433 (let ((ppss (or syntax-ppss (syntax-ppss))))
434 (pcase type
435 (`comment (and (nth 4 ppss) (nth 8 ppss)))
436 (`string (and (nth 3 ppss) (nth 8 ppss)))
437 (`paren (nth 1 ppss))
438 (_ nil))))
440 (defun python-syntax-context-type (&optional syntax-ppss)
441 "Return the context type using SYNTAX-PPSS.
442 The type returned can be `comment', `string' or `paren'."
443 (let ((ppss (or syntax-ppss (syntax-ppss))))
444 (cond
445 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
446 ((nth 1 ppss) 'paren))))
448 (defsubst python-syntax-comment-or-string-p ()
449 "Return non-nil if point is inside 'comment or 'string."
450 (nth 8 (syntax-ppss)))
452 (define-obsolete-function-alias
453 'python-info-ppss-context #'python-syntax-context "24.3")
455 (define-obsolete-function-alias
456 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
458 (define-obsolete-function-alias
459 'python-info-ppss-comment-or-string-p
460 #'python-syntax-comment-or-string-p "24.3")
462 (defun python-docstring-at-p (pos)
463 "Check to see if there is a docstring at POS."
464 (save-excursion
465 (goto-char pos)
466 (if (looking-at-p "'''\\|\"\"\"")
467 (progn
468 (python-nav-backward-statement)
469 (looking-at "\\`\\|class \\|def "))
470 nil)))
472 (defun python-font-lock-syntactic-face-function (state)
473 (if (nth 3 state)
474 (if (python-docstring-at-p (nth 8 state))
475 font-lock-doc-face
476 font-lock-string-face)
477 font-lock-comment-face))
479 (defvar python-font-lock-keywords
480 ;; Keywords
481 `(,(rx symbol-start
483 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
484 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
485 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
486 "try"
487 ;; Python 2:
488 "print" "exec"
489 ;; Python 3:
490 ;; False, None, and True are listed as keywords on the Python 3
491 ;; documentation, but since they also qualify as constants they are
492 ;; fontified like that in order to keep font-lock consistent between
493 ;; Python versions.
494 "nonlocal"
495 ;; Extra:
496 "self")
497 symbol-end)
498 ;; functions
499 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
500 (1 font-lock-function-name-face))
501 ;; classes
502 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
503 (1 font-lock-type-face))
504 ;; Constants
505 (,(rx symbol-start
507 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
508 ;; copyright, license, credits, quit and exit are added by the site
509 ;; module and they are not intended to be used in programs
510 "copyright" "credits" "exit" "license" "quit")
511 symbol-end) . font-lock-constant-face)
512 ;; Decorators.
513 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
514 (0+ "." (1+ (or word ?_)))))
515 (1 font-lock-type-face))
516 ;; Builtin Exceptions
517 (,(rx symbol-start
519 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
520 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
521 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
522 "ImportError" "ImportWarning" "IndexError" "KeyError"
523 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
524 "NotImplementedError" "OSError" "OverflowError"
525 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
526 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
527 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
528 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
529 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
530 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
531 ;; Python 2:
532 "StandardError"
533 ;; Python 3:
534 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
535 "TabError")
536 symbol-end) . font-lock-type-face)
537 ;; Builtins
538 (,(rx symbol-start
540 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
541 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
542 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
543 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
544 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
545 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
546 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
547 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
548 "__import__"
549 ;; Python 2:
550 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
551 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
552 "intern"
553 ;; Python 3:
554 "ascii" "bytearray" "bytes" "exec"
555 ;; Extra:
556 "__all__" "__doc__" "__name__" "__package__")
557 symbol-end) . font-lock-builtin-face)
558 ;; assignments
559 ;; support for a = b = c = 5
560 (,(lambda (limit)
561 (let ((re (python-rx (group (+ (any word ?. ?_)))
562 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
563 assignment-operator))
564 (res nil))
565 (while (and (setq res (re-search-forward re limit t))
566 (or (python-syntax-context 'paren)
567 (equal (char-after (point)) ?=))))
568 res))
569 (1 font-lock-variable-name-face nil nil))
570 ;; support for a, b, c = (1, 2, 3)
571 (,(lambda (limit)
572 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
573 (* ?, (* space) (+ (any word ?. ?_)) (* space))
574 ?, (* space) (+ (any word ?. ?_)) (* space)
575 assignment-operator))
576 (res nil))
577 (while (and (setq res (re-search-forward re limit t))
578 (goto-char (match-end 1))
579 (python-syntax-context 'paren)))
580 res))
581 (1 font-lock-variable-name-face nil nil))))
583 (defconst python-syntax-propertize-function
584 (syntax-propertize-rules
585 ((python-rx string-delimiter)
586 (0 (ignore (python-syntax-stringify))))))
588 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
589 "Count number of quotes around point (max is 3).
590 QUOTE-CHAR is the quote char to count. Optional argument POINT is
591 the point where scan starts (defaults to current point), and LIMIT
592 is used to limit the scan."
593 (let ((i 0))
594 (while (and (< i 3)
595 (or (not limit) (< (+ point i) limit))
596 (eq (char-after (+ point i)) quote-char))
597 (setq i (1+ i)))
600 (defun python-syntax-stringify ()
601 "Put `syntax-table' property correctly on single/triple quotes."
602 (let* ((num-quotes (length (match-string-no-properties 1)))
603 (ppss (prog2
604 (backward-char num-quotes)
605 (syntax-ppss)
606 (forward-char num-quotes)))
607 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
608 (quote-starting-pos (- (point) num-quotes))
609 (quote-ending-pos (point))
610 (num-closing-quotes
611 (and string-start
612 (python-syntax-count-quotes
613 (char-before) string-start quote-starting-pos))))
614 (cond ((and string-start (= num-closing-quotes 0))
615 ;; This set of quotes doesn't match the string starting
616 ;; kind. Do nothing.
617 nil)
618 ((not string-start)
619 ;; This set of quotes delimit the start of a string.
620 (put-text-property quote-starting-pos (1+ quote-starting-pos)
621 'syntax-table (string-to-syntax "|")))
622 ((= num-quotes num-closing-quotes)
623 ;; This set of quotes delimit the end of a string.
624 (put-text-property (1- quote-ending-pos) quote-ending-pos
625 'syntax-table (string-to-syntax "|")))
626 ((> num-quotes num-closing-quotes)
627 ;; This may only happen whenever a triple quote is closing
628 ;; a single quoted string. Add string delimiter syntax to
629 ;; all three quotes.
630 (put-text-property quote-starting-pos quote-ending-pos
631 'syntax-table (string-to-syntax "|"))))))
633 (defvar python-mode-syntax-table
634 (let ((table (make-syntax-table)))
635 ;; Give punctuation syntax to ASCII that normally has symbol
636 ;; syntax or has word syntax and isn't a letter.
637 (let ((symbol (string-to-syntax "_"))
638 (sst (standard-syntax-table)))
639 (dotimes (i 128)
640 (unless (= i ?_)
641 (if (equal symbol (aref sst i))
642 (modify-syntax-entry i "." table)))))
643 (modify-syntax-entry ?$ "." table)
644 (modify-syntax-entry ?% "." table)
645 ;; exceptions
646 (modify-syntax-entry ?# "<" table)
647 (modify-syntax-entry ?\n ">" table)
648 (modify-syntax-entry ?' "\"" table)
649 (modify-syntax-entry ?` "$" table)
650 table)
651 "Syntax table for Python files.")
653 (defvar python-dotty-syntax-table
654 (let ((table (make-syntax-table python-mode-syntax-table)))
655 (modify-syntax-entry ?. "w" table)
656 (modify-syntax-entry ?_ "w" table)
657 table)
658 "Dotty syntax table for Python files.
659 It makes underscores and dots word constituent chars.")
662 ;;; Indentation
664 (defcustom python-indent-offset 4
665 "Default indentation offset for Python."
666 :group 'python
667 :type 'integer
668 :safe 'integerp)
670 (defcustom python-indent-guess-indent-offset t
671 "Non-nil tells Python mode to guess `python-indent-offset' value."
672 :type 'boolean
673 :group 'python
674 :safe 'booleanp)
676 (defcustom python-indent-trigger-commands
677 '(indent-for-tab-command yas-expand yas/expand)
678 "Commands that might trigger a `python-indent-line' call."
679 :type '(repeat symbol)
680 :group 'python)
682 (define-obsolete-variable-alias
683 'python-indent 'python-indent-offset "24.3")
685 (define-obsolete-variable-alias
686 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
688 (defvar python-indent-current-level 0
689 "Current indentation level `python-indent-line-function' is using.")
691 (defvar python-indent-levels '(0)
692 "Levels of indentation available for `python-indent-line-function'.
693 Can also be `noindent' if automatic indentation can't be used.")
695 (defun python-indent-guess-indent-offset ()
696 "Guess and set `python-indent-offset' for the current buffer."
697 (interactive)
698 (save-excursion
699 (save-restriction
700 (widen)
701 (goto-char (point-min))
702 (let ((block-end))
703 (while (and (not block-end)
704 (re-search-forward
705 (python-rx line-start block-start) nil t))
706 (when (and
707 (not (python-syntax-context-type))
708 (progn
709 (goto-char (line-end-position))
710 (python-util-forward-comment -1)
711 (if (equal (char-before) ?:)
713 (forward-line 1)
714 (when (python-info-block-continuation-line-p)
715 (while (and (python-info-continuation-line-p)
716 (not (eobp)))
717 (forward-line 1))
718 (python-util-forward-comment -1)
719 (when (equal (char-before) ?:)
720 t)))))
721 (setq block-end (point-marker))))
722 (let ((indentation
723 (when block-end
724 (goto-char block-end)
725 (python-util-forward-comment)
726 (current-indentation))))
727 (if (and indentation (not (zerop indentation)))
728 (set (make-local-variable 'python-indent-offset) indentation)
729 (message "Can't guess python-indent-offset, using defaults: %s"
730 python-indent-offset)))))))
732 (defun python-indent-context ()
733 "Get information on indentation context.
734 Context information is returned with a cons with the form:
735 (STATUS . START)
737 Where status can be any of the following symbols:
739 * after-comment: When current line might continue a comment block
740 * inside-paren: If point in between (), {} or []
741 * inside-string: If point is inside a string
742 * after-backslash: Previous line ends in a backslash
743 * after-beginning-of-block: Point is after beginning of block
744 * after-line: Point is after normal line
745 * dedenter-statement: Point is on a dedenter statement.
746 * no-indent: Point is at beginning of buffer or other special case
747 START is the buffer position where the sexp starts."
748 (save-restriction
749 (widen)
750 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
751 (start))
752 (cons
753 (cond
754 ;; Beginning of buffer
755 ((save-excursion
756 (goto-char (line-beginning-position))
757 (bobp))
758 'no-indent)
759 ;; Comment continuation
760 ((save-excursion
761 (when (and
763 (python-info-current-line-comment-p)
764 (python-info-current-line-empty-p))
765 (progn
766 (forward-comment -1)
767 (python-info-current-line-comment-p)))
768 (setq start (point))
769 'after-comment)))
770 ;; Inside string
771 ((setq start (python-syntax-context 'string ppss))
772 'inside-string)
773 ;; Inside a paren
774 ((setq start (python-syntax-context 'paren ppss))
775 'inside-paren)
776 ;; After backslash
777 ((setq start (when (not (or (python-syntax-context 'string ppss)
778 (python-syntax-context 'comment ppss)))
779 (let ((line-beg-pos (line-number-at-pos)))
780 (python-info-line-ends-backslash-p
781 (1- line-beg-pos)))))
782 'after-backslash)
783 ;; After beginning of block
784 ((setq start (save-excursion
785 (when (progn
786 (back-to-indentation)
787 (python-util-forward-comment -1)
788 (equal (char-before) ?:))
789 ;; Move to the first block start that's not in within
790 ;; a string, comment or paren and that's not a
791 ;; continuation line.
792 (while (and (re-search-backward
793 (python-rx block-start) nil t)
795 (python-syntax-context-type)
796 (python-info-continuation-line-p))))
797 (when (looking-at (python-rx block-start))
798 (point-marker)))))
799 'after-beginning-of-block)
800 ((when (setq start (python-info-dedenter-statement-p))
801 'dedenter-statement))
802 ;; After normal line
803 ((setq start (save-excursion
804 (back-to-indentation)
805 (skip-chars-backward (rx (or whitespace ?\n)))
806 (python-nav-beginning-of-statement)
807 (point-marker)))
808 'after-line)
809 ;; Do not indent
810 (t 'no-indent))
811 start))))
813 (defun python-indent-calculate-indentation ()
814 "Calculate correct indentation offset for the current line.
815 Returns `noindent' if the indentation does not depend on Python syntax,
816 such as in strings."
817 (let* ((indentation-context (python-indent-context))
818 (context-status (car indentation-context))
819 (context-start (cdr indentation-context)))
820 (save-restriction
821 (widen)
822 (save-excursion
823 (pcase context-status
824 (`no-indent 0)
825 (`after-comment
826 (goto-char context-start)
827 (current-indentation))
828 ;; When point is after beginning of block just add one level
829 ;; of indentation relative to the context-start
830 (`after-beginning-of-block
831 (goto-char context-start)
832 (+ (current-indentation) python-indent-offset))
833 ;; When after a simple line just use previous line
834 ;; indentation.
835 (`after-line
836 (let* ((pair (save-excursion
837 (goto-char context-start)
838 (cons
839 (current-indentation)
840 (python-info-beginning-of-block-p))))
841 (context-indentation (car pair))
842 ;; TODO: Separate block enders into its own case.
843 (adjustment
844 (if (save-excursion
845 (python-util-forward-comment -1)
846 (python-nav-beginning-of-statement)
847 (looking-at (python-rx block-ender)))
848 python-indent-offset
849 0)))
850 (- context-indentation adjustment)))
851 ;; When point is on a dedenter statement, search for the
852 ;; opening block that corresponds to it and use its
853 ;; indentation. If no opening block is found just remove
854 ;; indentation as this is an invalid python file.
855 (`dedenter-statement
856 (let ((block-start-point
857 (python-info-dedenter-opening-block-position)))
858 (save-excursion
859 (if (not block-start-point)
861 (goto-char block-start-point)
862 (current-indentation)))))
863 ;; When inside of a string, do nothing. just use the current
864 ;; indentation. XXX: perhaps it would be a good idea to
865 ;; invoke standard text indentation here
866 (`inside-string 'noindent)
867 ;; After backslash we have several possibilities.
868 (`after-backslash
869 (cond
870 ;; Check if current line is a dot continuation. For this
871 ;; the current line must start with a dot and previous
872 ;; line must contain a dot too.
873 ((save-excursion
874 (back-to-indentation)
875 (when (looking-at "\\.")
876 ;; If after moving one line back point is inside a paren it
877 ;; needs to move back until it's not anymore
878 (while (prog2
879 (forward-line -1)
880 (and (not (bobp))
881 (python-syntax-context 'paren))))
882 (goto-char (line-end-position))
883 (while (and (re-search-backward
884 "\\." (line-beginning-position) t)
885 (python-syntax-context-type)))
886 (if (and (looking-at "\\.")
887 (not (python-syntax-context-type)))
888 ;; The indentation is the same column of the
889 ;; first matching dot that's not inside a
890 ;; comment, a string or a paren
891 (current-column)
892 ;; No dot found on previous line, just add another
893 ;; indentation level.
894 (+ (current-indentation) python-indent-offset)))))
895 ;; Check if prev line is a block continuation
896 ((let ((block-continuation-start
897 (python-info-block-continuation-line-p)))
898 (when block-continuation-start
899 ;; If block-continuation-start is set jump to that
900 ;; marker and use first column after the block start
901 ;; as indentation value.
902 (goto-char block-continuation-start)
903 (re-search-forward
904 (python-rx block-start (* space))
905 (line-end-position) t)
906 (current-column))))
907 ;; Check if current line is an assignment continuation
908 ((let ((assignment-continuation-start
909 (python-info-assignment-continuation-line-p)))
910 (when assignment-continuation-start
911 ;; If assignment-continuation is set jump to that
912 ;; marker and use first column after the assignment
913 ;; operator as indentation value.
914 (goto-char assignment-continuation-start)
915 (current-column))))
917 (forward-line -1)
918 (goto-char (python-info-beginning-of-backslash))
919 (if (save-excursion
920 (and
921 (forward-line -1)
922 (goto-char
923 (or (python-info-beginning-of-backslash) (point)))
924 (python-info-line-ends-backslash-p)))
925 ;; The two previous lines ended in a backslash so we must
926 ;; respect previous line indentation.
927 (current-indentation)
928 ;; What happens here is that we are dealing with the second
929 ;; line of a backslash continuation, in that case we just going
930 ;; to add one indentation level.
931 (+ (current-indentation) python-indent-offset)))))
932 ;; When inside a paren there's a need to handle nesting
933 ;; correctly
934 (`inside-paren
935 (cond
936 ;; If current line closes the outermost open paren use the
937 ;; current indentation of the context-start line.
938 ((save-excursion
939 (skip-syntax-forward "\s" (line-end-position))
940 (when (and (looking-at (regexp-opt '(")" "]" "}")))
941 (progn
942 (forward-char 1)
943 (not (python-syntax-context 'paren))))
944 (goto-char context-start)
945 (current-indentation))))
946 ;; If open paren is contained on a line by itself add another
947 ;; indentation level, else look for the first word after the
948 ;; opening paren and use it's column position as indentation
949 ;; level.
950 ((let* ((content-starts-in-newline)
951 (indent
952 (save-excursion
953 (if (setq content-starts-in-newline
954 (progn
955 (goto-char context-start)
956 (forward-char)
957 (save-restriction
958 (narrow-to-region
959 (line-beginning-position)
960 (line-end-position))
961 (python-util-forward-comment))
962 (looking-at "$")))
963 (+ (current-indentation) python-indent-offset)
964 (current-column)))))
965 ;; Adjustments
966 (cond
967 ;; If current line closes a nested open paren de-indent one
968 ;; level.
969 ((progn
970 (back-to-indentation)
971 (looking-at (regexp-opt '(")" "]" "}"))))
972 (- indent python-indent-offset))
973 ;; If the line of the opening paren that wraps the current
974 ;; line starts a block add another level of indentation to
975 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
976 ((save-excursion
977 (when (and content-starts-in-newline
978 (progn
979 (goto-char context-start)
980 (back-to-indentation)
981 (looking-at (python-rx block-start))))
982 (+ indent python-indent-offset))))
983 (t indent)))))))))))
985 (defun python-indent-calculate-levels ()
986 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
987 (if (or (python-info-continuation-line-p)
988 (not (python-info-dedenter-statement-p)))
989 ;; XXX: This asks for a refactor. Even if point is on a
990 ;; dedenter statement, it could be multiline and in that case
991 ;; the continuation lines should be indented with normal rules.
992 (let* ((indentation (python-indent-calculate-indentation)))
993 (if (not (numberp indentation))
994 (setq python-indent-levels indentation)
995 (let* ((remainder (% indentation python-indent-offset))
996 (steps (/ (- indentation remainder) python-indent-offset)))
997 (setq python-indent-levels (list 0))
998 (dotimes (step steps)
999 (push (* python-indent-offset (1+ step)) python-indent-levels))
1000 (when (not (eq 0 remainder))
1001 (push (+ (* python-indent-offset steps) remainder)
1002 python-indent-levels)))))
1003 (setq python-indent-levels
1005 (mapcar (lambda (pos)
1006 (save-excursion
1007 (goto-char pos)
1008 (current-indentation)))
1009 (python-info-dedenter-opening-block-positions))
1010 (list 0))))
1011 (when (listp python-indent-levels)
1012 (setq python-indent-current-level (1- (length python-indent-levels))
1013 python-indent-levels (nreverse python-indent-levels))))
1015 (defun python-indent-toggle-levels ()
1016 "Toggle `python-indent-current-level' over `python-indent-levels'."
1017 (setq python-indent-current-level (1- python-indent-current-level))
1018 (when (< python-indent-current-level 0)
1019 (setq python-indent-current-level (1- (length python-indent-levels)))))
1021 (defun python-indent-line (&optional force-toggle)
1022 "Internal implementation of `python-indent-line-function'.
1023 Uses the offset calculated in
1024 `python-indent-calculate-indentation' and available levels
1025 indicated by the variable `python-indent-levels' to set the
1026 current indentation.
1028 When the variable `last-command' is equal to one of the symbols
1029 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
1030 non-nil it cycles levels indicated in the variable
1031 `python-indent-levels' by setting the current level in the
1032 variable `python-indent-current-level'.
1034 When the variable `last-command' is not equal to one of the
1035 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
1036 is nil it calculates possible indentation levels and saves them
1037 in the variable `python-indent-levels'. Afterwards it sets the
1038 variable `python-indent-current-level' correctly so offset is
1039 equal to
1040 (nth python-indent-current-level python-indent-levels)"
1041 (if (and (or (and (memq this-command python-indent-trigger-commands)
1042 (eq last-command this-command))
1043 force-toggle)
1044 (not (equal python-indent-levels '(0))))
1045 (if (listp python-indent-levels)
1046 (python-indent-toggle-levels))
1047 (python-indent-calculate-levels))
1048 (if (eq python-indent-levels 'noindent)
1049 python-indent-levels
1050 (let* ((starting-pos (point-marker))
1051 (indent-ending-position
1052 (+ (line-beginning-position) (current-indentation)))
1053 (follow-indentation-p
1054 (or (bolp)
1055 (and (<= (line-beginning-position) starting-pos)
1056 (>= indent-ending-position starting-pos))))
1057 (next-indent (nth python-indent-current-level python-indent-levels)))
1058 (unless (= next-indent (current-indentation))
1059 (beginning-of-line)
1060 (delete-horizontal-space)
1061 (indent-to next-indent)
1062 (goto-char starting-pos))
1063 (and follow-indentation-p (back-to-indentation)))
1064 (python-info-dedenter-opening-block-message)))
1066 (defun python-indent-line-function ()
1067 "`indent-line-function' for Python mode.
1068 See `python-indent-line' for details."
1069 (python-indent-line))
1071 (defun python-indent-dedent-line ()
1072 "De-indent current line."
1073 (interactive "*")
1074 (when (and (not (python-syntax-comment-or-string-p))
1075 (<= (point) (save-excursion
1076 (back-to-indentation)
1077 (point)))
1078 (> (current-column) 0))
1079 (python-indent-line t)
1082 (defun python-indent-dedent-line-backspace (arg)
1083 "De-indent current line.
1084 Argument ARG is passed to `backward-delete-char-untabify' when
1085 point is not in between the indentation."
1086 (interactive "*p")
1087 (when (not (python-indent-dedent-line))
1088 (backward-delete-char-untabify arg)))
1089 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1091 (defun python-indent-region (start end)
1092 "Indent a Python region automagically.
1094 Called from a program, START and END specify the region to indent."
1095 (let ((deactivate-mark nil))
1096 (save-excursion
1097 (goto-char end)
1098 (setq end (point-marker))
1099 (goto-char start)
1100 (or (bolp) (forward-line 1))
1101 (while (< (point) end)
1102 (or (and (bolp) (eolp))
1103 (when (and
1104 ;; Skip if previous line is empty or a comment.
1105 (save-excursion
1106 (let ((line-is-comment-p
1107 (python-info-current-line-comment-p)))
1108 (forward-line -1)
1109 (not
1110 (or (and (python-info-current-line-comment-p)
1111 ;; Unless this line is a comment too.
1112 (not line-is-comment-p))
1113 (python-info-current-line-empty-p)))))
1114 ;; Don't mess with strings, unless it's the
1115 ;; enclosing set of quotes.
1116 (or (not (python-syntax-context 'string))
1118 (syntax-after
1119 (+ (1- (point))
1120 (current-indentation)
1121 (python-syntax-count-quotes (char-after) (point))))
1122 (string-to-syntax "|")))
1123 ;; Skip if current line is a block start, a
1124 ;; dedenter or block ender.
1125 (save-excursion
1126 (back-to-indentation)
1127 (not (looking-at
1128 (python-rx
1129 (or block-start dedenter block-ender))))))
1130 (python-indent-line)))
1131 (forward-line 1))
1132 (move-marker end nil))))
1134 (defun python-indent-shift-left (start end &optional count)
1135 "Shift lines contained in region START END by COUNT columns to the left.
1136 COUNT defaults to `python-indent-offset'. If region isn't
1137 active, the current line is shifted. The shifted region includes
1138 the lines in which START and END lie. An error is signaled if
1139 any lines in the region are indented less than COUNT columns."
1140 (interactive
1141 (if mark-active
1142 (list (region-beginning) (region-end) current-prefix-arg)
1143 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1144 (if count
1145 (setq count (prefix-numeric-value count))
1146 (setq count python-indent-offset))
1147 (when (> count 0)
1148 (let ((deactivate-mark nil))
1149 (save-excursion
1150 (goto-char start)
1151 (while (< (point) end)
1152 (if (and (< (current-indentation) count)
1153 (not (looking-at "[ \t]*$")))
1154 (user-error "Can't shift all lines enough"))
1155 (forward-line))
1156 (indent-rigidly start end (- count))))))
1158 (defun python-indent-shift-right (start end &optional count)
1159 "Shift lines contained in region START END by COUNT columns to the right.
1160 COUNT defaults to `python-indent-offset'. If region isn't
1161 active, the current line is shifted. The shifted region includes
1162 the lines in which START and END lie."
1163 (interactive
1164 (if mark-active
1165 (list (region-beginning) (region-end) current-prefix-arg)
1166 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1167 (let ((deactivate-mark nil))
1168 (setq count (if count (prefix-numeric-value count)
1169 python-indent-offset))
1170 (indent-rigidly start end count)))
1172 (defun python-indent-post-self-insert-function ()
1173 "Adjust indentation after insertion of some characters.
1174 This function is intended to be added to `post-self-insert-hook.'
1175 If a line renders a paren alone, after adding a char before it,
1176 the line will be re-indented automatically if needed."
1177 (when (and electric-indent-mode
1178 (eq (char-before) last-command-event))
1179 (cond
1180 ;; Electric indent inside parens
1181 ((and
1182 (not (bolp))
1183 (let ((paren-start (python-syntax-context 'paren)))
1184 ;; Check that point is inside parens.
1185 (when paren-start
1186 (not
1187 ;; Filter the case where input is happening in the same
1188 ;; line where the open paren is.
1189 (= (line-number-at-pos)
1190 (line-number-at-pos paren-start)))))
1191 ;; When content has been added before the closing paren or a
1192 ;; comma has been inserted, it's ok to do the trick.
1194 (memq (char-after) '(?\) ?\] ?\}))
1195 (eq (char-before) ?,)))
1196 (save-excursion
1197 (goto-char (line-beginning-position))
1198 (let ((indentation (python-indent-calculate-indentation)))
1199 (when (and (numberp indentation) (< (current-indentation) indentation))
1200 (indent-line-to indentation)))))
1201 ;; Electric colon
1202 ((and (eq ?: last-command-event)
1203 (memq ?: electric-indent-chars)
1204 (not current-prefix-arg)
1205 ;; Trigger electric colon only at end of line
1206 (eolp)
1207 ;; Avoid re-indenting on extra colon
1208 (not (equal ?: (char-before (1- (point)))))
1209 (not (python-syntax-comment-or-string-p))
1210 ;; Never re-indent at beginning of defun
1211 (not (save-excursion
1212 (python-nav-beginning-of-statement)
1213 (python-info-looking-at-beginning-of-defun))))
1214 (python-indent-line)))))
1217 ;;; Navigation
1219 (defvar python-nav-beginning-of-defun-regexp
1220 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1221 "Regexp matching class or function definition.
1222 The name of the defun should be grouped so it can be retrieved
1223 via `match-string'.")
1225 (defun python-nav--beginning-of-defun (&optional arg)
1226 "Internal implementation of `python-nav-beginning-of-defun'.
1227 With positive ARG search backwards, else search forwards."
1228 (when (or (null arg) (= arg 0)) (setq arg 1))
1229 (let* ((re-search-fn (if (> arg 0)
1230 #'re-search-backward
1231 #'re-search-forward))
1232 (line-beg-pos (line-beginning-position))
1233 (line-content-start (+ line-beg-pos (current-indentation)))
1234 (pos (point-marker))
1235 (beg-indentation
1236 (and (> arg 0)
1237 (save-excursion
1238 (while (and
1239 (not (python-info-looking-at-beginning-of-defun))
1240 (python-nav-backward-block)))
1241 (or (and (python-info-looking-at-beginning-of-defun)
1242 (+ (current-indentation) python-indent-offset))
1243 0))))
1244 (found
1245 (progn
1246 (when (and (< arg 0)
1247 (python-info-looking-at-beginning-of-defun))
1248 (end-of-line 1))
1249 (while (and (funcall re-search-fn
1250 python-nav-beginning-of-defun-regexp nil t)
1251 (or (python-syntax-context-type)
1252 ;; Handle nested defuns when moving
1253 ;; backwards by checking indentation.
1254 (and (> arg 0)
1255 (not (= (current-indentation) 0))
1256 (>= (current-indentation) beg-indentation)))))
1257 (and (python-info-looking-at-beginning-of-defun)
1258 (or (not (= (line-number-at-pos pos)
1259 (line-number-at-pos)))
1260 (and (>= (point) line-beg-pos)
1261 (<= (point) line-content-start)
1262 (> pos line-content-start)))))))
1263 (if found
1264 (or (beginning-of-line 1) t)
1265 (and (goto-char pos) nil))))
1267 (defun python-nav-beginning-of-defun (&optional arg)
1268 "Move point to `beginning-of-defun'.
1269 With positive ARG search backwards else search forward.
1270 ARG nil or 0 defaults to 1. When searching backwards,
1271 nested defuns are handled with care depending on current
1272 point position. Return non-nil if point is moved to
1273 `beginning-of-defun'."
1274 (when (or (null arg) (= arg 0)) (setq arg 1))
1275 (let ((found))
1276 (while (and (not (= arg 0))
1277 (let ((keep-searching-p
1278 (python-nav--beginning-of-defun arg)))
1279 (when (and keep-searching-p (null found))
1280 (setq found t))
1281 keep-searching-p))
1282 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1283 found))
1285 (defun python-nav-end-of-defun ()
1286 "Move point to the end of def or class.
1287 Returns nil if point is not in a def or class."
1288 (interactive)
1289 (let ((beg-defun-indent)
1290 (beg-pos (point)))
1291 (when (or (python-info-looking-at-beginning-of-defun)
1292 (python-nav-beginning-of-defun 1)
1293 (python-nav-beginning-of-defun -1))
1294 (setq beg-defun-indent (current-indentation))
1295 (while (progn
1296 (python-nav-end-of-statement)
1297 (python-util-forward-comment 1)
1298 (and (> (current-indentation) beg-defun-indent)
1299 (not (eobp)))))
1300 (python-util-forward-comment -1)
1301 (forward-line 1)
1302 ;; Ensure point moves forward.
1303 (and (> beg-pos (point)) (goto-char beg-pos)))))
1305 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1306 "Move point using FN avoiding places with specific context.
1307 FN must take no arguments. POSCOMPFN is a two arguments function
1308 used to compare current and previous point after it is moved
1309 using FN, this is normally a less-than or greater-than
1310 comparison. Optional argument CONTEXTFN defaults to
1311 `python-syntax-context-type' and is used for checking current
1312 point context, it must return a non-nil value if this point must
1313 be skipped."
1314 (let ((contextfn (or contextfn 'python-syntax-context-type))
1315 (start-pos (point-marker))
1316 (prev-pos))
1317 (catch 'found
1318 (while t
1319 (let* ((newpos
1320 (and (funcall fn) (point-marker)))
1321 (context (funcall contextfn)))
1322 (cond ((and (not context) newpos
1323 (or (and (not prev-pos) newpos)
1324 (and prev-pos newpos
1325 (funcall poscompfn newpos prev-pos))))
1326 (throw 'found (point-marker)))
1327 ((and newpos context)
1328 (setq prev-pos (point)))
1329 (t (when (not newpos) (goto-char start-pos))
1330 (throw 'found nil))))))))
1332 (defun python-nav--forward-defun (arg)
1333 "Internal implementation of python-nav-{backward,forward}-defun.
1334 Uses ARG to define which function to call, and how many times
1335 repeat it."
1336 (let ((found))
1337 (while (and (> arg 0)
1338 (setq found
1339 (python-nav--syntactically
1340 (lambda ()
1341 (re-search-forward
1342 python-nav-beginning-of-defun-regexp nil t))
1343 '>)))
1344 (setq arg (1- arg)))
1345 (while (and (< arg 0)
1346 (setq found
1347 (python-nav--syntactically
1348 (lambda ()
1349 (re-search-backward
1350 python-nav-beginning-of-defun-regexp nil t))
1351 '<)))
1352 (setq arg (1+ arg)))
1353 found))
1355 (defun python-nav-backward-defun (&optional arg)
1356 "Navigate to closer defun backward ARG times.
1357 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1358 nested definitions."
1359 (interactive "^p")
1360 (python-nav--forward-defun (- (or arg 1))))
1362 (defun python-nav-forward-defun (&optional arg)
1363 "Navigate to closer defun forward ARG times.
1364 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1365 nested definitions."
1366 (interactive "^p")
1367 (python-nav--forward-defun (or arg 1)))
1369 (defun python-nav-beginning-of-statement ()
1370 "Move to start of current statement."
1371 (interactive "^")
1372 (back-to-indentation)
1373 (let* ((ppss (syntax-ppss))
1374 (context-point
1376 (python-syntax-context 'paren ppss)
1377 (python-syntax-context 'string ppss))))
1378 (cond ((bobp))
1379 (context-point
1380 (goto-char context-point)
1381 (python-nav-beginning-of-statement))
1382 ((save-excursion
1383 (forward-line -1)
1384 (python-info-line-ends-backslash-p))
1385 (forward-line -1)
1386 (python-nav-beginning-of-statement))))
1387 (point-marker))
1389 (defun python-nav-end-of-statement (&optional noend)
1390 "Move to end of current statement.
1391 Optional argument NOEND is internal and makes the logic to not
1392 jump to the end of line when moving forward searching for the end
1393 of the statement."
1394 (interactive "^")
1395 (let (string-start bs-pos)
1396 (while (and (or noend (goto-char (line-end-position)))
1397 (not (eobp))
1398 (cond ((setq string-start (python-syntax-context 'string))
1399 (goto-char string-start)
1400 (if (python-syntax-context 'paren)
1401 ;; Ended up inside a paren, roll again.
1402 (python-nav-end-of-statement t)
1403 ;; This is not inside a paren, move to the
1404 ;; end of this string.
1405 (goto-char (+ (point)
1406 (python-syntax-count-quotes
1407 (char-after (point)) (point))))
1408 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1409 (goto-char (point-max)))))
1410 ((python-syntax-context 'paren)
1411 ;; The statement won't end before we've escaped
1412 ;; at least one level of parenthesis.
1413 (condition-case err
1414 (goto-char (scan-lists (point) 1 -1))
1415 (scan-error (goto-char (nth 3 err)))))
1416 ((setq bs-pos (python-info-line-ends-backslash-p))
1417 (goto-char bs-pos)
1418 (forward-line 1))))))
1419 (point-marker))
1421 (defun python-nav-backward-statement (&optional arg)
1422 "Move backward to previous statement.
1423 With ARG, repeat. See `python-nav-forward-statement'."
1424 (interactive "^p")
1425 (or arg (setq arg 1))
1426 (python-nav-forward-statement (- arg)))
1428 (defun python-nav-forward-statement (&optional arg)
1429 "Move forward to next statement.
1430 With ARG, repeat. With negative argument, move ARG times
1431 backward to previous statement."
1432 (interactive "^p")
1433 (or arg (setq arg 1))
1434 (while (> arg 0)
1435 (python-nav-end-of-statement)
1436 (python-util-forward-comment)
1437 (python-nav-beginning-of-statement)
1438 (setq arg (1- arg)))
1439 (while (< arg 0)
1440 (python-nav-beginning-of-statement)
1441 (python-util-forward-comment -1)
1442 (python-nav-beginning-of-statement)
1443 (setq arg (1+ arg))))
1445 (defun python-nav-beginning-of-block ()
1446 "Move to start of current block."
1447 (interactive "^")
1448 (let ((starting-pos (point)))
1449 (if (progn
1450 (python-nav-beginning-of-statement)
1451 (looking-at (python-rx block-start)))
1452 (point-marker)
1453 ;; Go to first line beginning a statement
1454 (while (and (not (bobp))
1455 (or (and (python-nav-beginning-of-statement) nil)
1456 (python-info-current-line-comment-p)
1457 (python-info-current-line-empty-p)))
1458 (forward-line -1))
1459 (let ((block-matching-indent
1460 (- (current-indentation) python-indent-offset)))
1461 (while
1462 (and (python-nav-backward-block)
1463 (> (current-indentation) block-matching-indent)))
1464 (if (and (looking-at (python-rx block-start))
1465 (= (current-indentation) block-matching-indent))
1466 (point-marker)
1467 (and (goto-char starting-pos) nil))))))
1469 (defun python-nav-end-of-block ()
1470 "Move to end of current block."
1471 (interactive "^")
1472 (when (python-nav-beginning-of-block)
1473 (let ((block-indentation (current-indentation)))
1474 (python-nav-end-of-statement)
1475 (while (and (forward-line 1)
1476 (not (eobp))
1477 (or (and (> (current-indentation) block-indentation)
1478 (or (python-nav-end-of-statement) t))
1479 (python-info-current-line-comment-p)
1480 (python-info-current-line-empty-p))))
1481 (python-util-forward-comment -1)
1482 (point-marker))))
1484 (defun python-nav-backward-block (&optional arg)
1485 "Move backward to previous block of code.
1486 With ARG, repeat. See `python-nav-forward-block'."
1487 (interactive "^p")
1488 (or arg (setq arg 1))
1489 (python-nav-forward-block (- arg)))
1491 (defun python-nav-forward-block (&optional arg)
1492 "Move forward to next block of code.
1493 With ARG, repeat. With negative argument, move ARG times
1494 backward to previous block."
1495 (interactive "^p")
1496 (or arg (setq arg 1))
1497 (let ((block-start-regexp
1498 (python-rx line-start (* whitespace) block-start))
1499 (starting-pos (point)))
1500 (while (> arg 0)
1501 (python-nav-end-of-statement)
1502 (while (and
1503 (re-search-forward block-start-regexp nil t)
1504 (python-syntax-context-type)))
1505 (setq arg (1- arg)))
1506 (while (< arg 0)
1507 (python-nav-beginning-of-statement)
1508 (while (and
1509 (re-search-backward block-start-regexp nil t)
1510 (python-syntax-context-type)))
1511 (setq arg (1+ arg)))
1512 (python-nav-beginning-of-statement)
1513 (if (not (looking-at (python-rx block-start)))
1514 (and (goto-char starting-pos) nil)
1515 (and (not (= (point) starting-pos)) (point-marker)))))
1517 (defun python-nav--lisp-forward-sexp (&optional arg)
1518 "Standard version `forward-sexp'.
1519 It ignores completely the value of `forward-sexp-function' by
1520 setting it to nil before calling `forward-sexp'. With positive
1521 ARG move forward only one sexp, else move backwards."
1522 (let ((forward-sexp-function)
1523 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1524 (forward-sexp arg)))
1526 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1527 "Safe version of standard `forward-sexp'.
1528 When at end of sexp (i.e. looking at a opening/closing paren)
1529 skips it instead of throwing an error. With positive ARG move
1530 forward only one sexp, else move backwards."
1531 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1532 (paren-regexp
1533 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1534 (search-fn
1535 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1536 (condition-case nil
1537 (python-nav--lisp-forward-sexp arg)
1538 (error
1539 (while (and (funcall search-fn paren-regexp nil t)
1540 (python-syntax-context 'paren)))))))
1542 (defun python-nav--forward-sexp (&optional dir safe)
1543 "Move to forward sexp.
1544 With positive optional argument DIR direction move forward, else
1545 backwards. When optional argument SAFE is non-nil do not throw
1546 errors when at end of sexp, skip it instead."
1547 (setq dir (or dir 1))
1548 (unless (= dir 0)
1549 (let* ((forward-p (if (> dir 0)
1550 (and (setq dir 1) t)
1551 (and (setq dir -1) nil)))
1552 (context-type (python-syntax-context-type)))
1553 (cond
1554 ((memq context-type '(string comment))
1555 ;; Inside of a string, get out of it.
1556 (let ((forward-sexp-function))
1557 (forward-sexp dir)))
1558 ((or (eq context-type 'paren)
1559 (and forward-p (looking-at (python-rx open-paren)))
1560 (and (not forward-p)
1561 (eq (syntax-class (syntax-after (1- (point))))
1562 (car (string-to-syntax ")")))))
1563 ;; Inside a paren or looking at it, lisp knows what to do.
1564 (if safe
1565 (python-nav--lisp-forward-sexp-safe dir)
1566 (python-nav--lisp-forward-sexp dir)))
1568 ;; This part handles the lispy feel of
1569 ;; `python-nav-forward-sexp'. Knowing everything about the
1570 ;; current context and the context of the next sexp tries to
1571 ;; follow the lisp sexp motion commands in a symmetric manner.
1572 (let* ((context
1573 (cond
1574 ((python-info-beginning-of-block-p) 'block-start)
1575 ((python-info-end-of-block-p) 'block-end)
1576 ((python-info-beginning-of-statement-p) 'statement-start)
1577 ((python-info-end-of-statement-p) 'statement-end)))
1578 (next-sexp-pos
1579 (save-excursion
1580 (if safe
1581 (python-nav--lisp-forward-sexp-safe dir)
1582 (python-nav--lisp-forward-sexp dir))
1583 (point)))
1584 (next-sexp-context
1585 (save-excursion
1586 (goto-char next-sexp-pos)
1587 (cond
1588 ((python-info-beginning-of-block-p) 'block-start)
1589 ((python-info-end-of-block-p) 'block-end)
1590 ((python-info-beginning-of-statement-p) 'statement-start)
1591 ((python-info-end-of-statement-p) 'statement-end)
1592 ((python-info-statement-starts-block-p) 'starts-block)
1593 ((python-info-statement-ends-block-p) 'ends-block)))))
1594 (if forward-p
1595 (cond ((and (not (eobp))
1596 (python-info-current-line-empty-p))
1597 (python-util-forward-comment dir)
1598 (python-nav--forward-sexp dir))
1599 ((eq context 'block-start)
1600 (python-nav-end-of-block))
1601 ((eq context 'statement-start)
1602 (python-nav-end-of-statement))
1603 ((and (memq context '(statement-end block-end))
1604 (eq next-sexp-context 'ends-block))
1605 (goto-char next-sexp-pos)
1606 (python-nav-end-of-block))
1607 ((and (memq context '(statement-end block-end))
1608 (eq next-sexp-context 'starts-block))
1609 (goto-char next-sexp-pos)
1610 (python-nav-end-of-block))
1611 ((memq context '(statement-end block-end))
1612 (goto-char next-sexp-pos)
1613 (python-nav-end-of-statement))
1614 (t (goto-char next-sexp-pos)))
1615 (cond ((and (not (bobp))
1616 (python-info-current-line-empty-p))
1617 (python-util-forward-comment dir)
1618 (python-nav--forward-sexp dir))
1619 ((eq context 'block-end)
1620 (python-nav-beginning-of-block))
1621 ((eq context 'statement-end)
1622 (python-nav-beginning-of-statement))
1623 ((and (memq context '(statement-start block-start))
1624 (eq next-sexp-context 'starts-block))
1625 (goto-char next-sexp-pos)
1626 (python-nav-beginning-of-block))
1627 ((and (memq context '(statement-start block-start))
1628 (eq next-sexp-context 'ends-block))
1629 (goto-char next-sexp-pos)
1630 (python-nav-beginning-of-block))
1631 ((memq context '(statement-start block-start))
1632 (goto-char next-sexp-pos)
1633 (python-nav-beginning-of-statement))
1634 (t (goto-char next-sexp-pos))))))))))
1636 (defun python-nav-forward-sexp (&optional arg)
1637 "Move forward across expressions.
1638 With ARG, do it that many times. Negative arg -N means move
1639 backward N times."
1640 (interactive "^p")
1641 (or arg (setq arg 1))
1642 (while (> arg 0)
1643 (python-nav--forward-sexp 1)
1644 (setq arg (1- arg)))
1645 (while (< arg 0)
1646 (python-nav--forward-sexp -1)
1647 (setq arg (1+ arg))))
1649 (defun python-nav-backward-sexp (&optional arg)
1650 "Move backward across expressions.
1651 With ARG, do it that many times. Negative arg -N means move
1652 forward N times."
1653 (interactive "^p")
1654 (or arg (setq arg 1))
1655 (python-nav-forward-sexp (- arg)))
1657 (defun python-nav-forward-sexp-safe (&optional arg)
1658 "Move forward safely across expressions.
1659 With ARG, do it that many times. Negative arg -N means move
1660 backward N times."
1661 (interactive "^p")
1662 (or arg (setq arg 1))
1663 (while (> arg 0)
1664 (python-nav--forward-sexp 1 t)
1665 (setq arg (1- arg)))
1666 (while (< arg 0)
1667 (python-nav--forward-sexp -1 t)
1668 (setq arg (1+ arg))))
1670 (defun python-nav-backward-sexp-safe (&optional arg)
1671 "Move backward safely across expressions.
1672 With ARG, do it that many times. Negative arg -N means move
1673 forward N times."
1674 (interactive "^p")
1675 (or arg (setq arg 1))
1676 (python-nav-forward-sexp-safe (- arg)))
1678 (defun python-nav--up-list (&optional dir)
1679 "Internal implementation of `python-nav-up-list'.
1680 DIR is always 1 or -1 and comes sanitized from
1681 `python-nav-up-list' calls."
1682 (let ((context (python-syntax-context-type))
1683 (forward-p (> dir 0)))
1684 (cond
1685 ((memq context '(string comment)))
1686 ((eq context 'paren)
1687 (let ((forward-sexp-function))
1688 (up-list dir)))
1689 ((and forward-p (python-info-end-of-block-p))
1690 (let ((parent-end-pos
1691 (save-excursion
1692 (let ((indentation (and
1693 (python-nav-beginning-of-block)
1694 (current-indentation))))
1695 (while (and indentation
1696 (> indentation 0)
1697 (>= (current-indentation) indentation)
1698 (python-nav-backward-block)))
1699 (python-nav-end-of-block)))))
1700 (and (> (or parent-end-pos (point)) (point))
1701 (goto-char parent-end-pos))))
1702 (forward-p (python-nav-end-of-block))
1703 ((and (not forward-p)
1704 (> (current-indentation) 0)
1705 (python-info-beginning-of-block-p))
1706 (let ((prev-block-pos
1707 (save-excursion
1708 (let ((indentation (current-indentation)))
1709 (while (and (python-nav-backward-block)
1710 (>= (current-indentation) indentation))))
1711 (point))))
1712 (and (> (point) prev-block-pos)
1713 (goto-char prev-block-pos))))
1714 ((not forward-p) (python-nav-beginning-of-block)))))
1716 (defun python-nav-up-list (&optional arg)
1717 "Move forward out of one level of parentheses (or blocks).
1718 With ARG, do this that many times.
1719 A negative argument means move backward but still to a less deep spot.
1720 This command assumes point is not in a string or comment."
1721 (interactive "^p")
1722 (or arg (setq arg 1))
1723 (while (> arg 0)
1724 (python-nav--up-list 1)
1725 (setq arg (1- arg)))
1726 (while (< arg 0)
1727 (python-nav--up-list -1)
1728 (setq arg (1+ arg))))
1730 (defun python-nav-backward-up-list (&optional arg)
1731 "Move backward out of one level of parentheses (or blocks).
1732 With ARG, do this that many times.
1733 A negative argument means move forward but still to a less deep spot.
1734 This command assumes point is not in a string or comment."
1735 (interactive "^p")
1736 (or arg (setq arg 1))
1737 (python-nav-up-list (- arg)))
1739 (defun python-nav-if-name-main ()
1740 "Move point at the beginning the __main__ block.
1741 When \"if __name__ == '__main__':\" is found returns its
1742 position, else returns nil."
1743 (interactive)
1744 (let ((point (point))
1745 (found (catch 'found
1746 (goto-char (point-min))
1747 (while (re-search-forward
1748 (python-rx line-start
1749 "if" (+ space)
1750 "__name__" (+ space)
1751 "==" (+ space)
1752 (group-n 1 (or ?\" ?\'))
1753 "__main__" (backref 1) (* space) ":")
1754 nil t)
1755 (when (not (python-syntax-context-type))
1756 (beginning-of-line)
1757 (throw 'found t))))))
1758 (if found
1759 (point)
1760 (ignore (goto-char point)))))
1763 ;;; Shell integration
1765 (defcustom python-shell-buffer-name "Python"
1766 "Default buffer name for Python interpreter."
1767 :type 'string
1768 :group 'python
1769 :safe 'stringp)
1771 (defcustom python-shell-interpreter "python"
1772 "Default Python interpreter for shell."
1773 :type 'string
1774 :group 'python)
1776 (defcustom python-shell-internal-buffer-name "Python Internal"
1777 "Default buffer name for the Internal Python interpreter."
1778 :type 'string
1779 :group 'python
1780 :safe 'stringp)
1782 (defcustom python-shell-interpreter-args "-i"
1783 "Default arguments for the Python interpreter."
1784 :type 'string
1785 :group 'python)
1787 (defcustom python-shell-interpreter-interactive-arg "-i"
1788 "Interpreter argument to force it to run interactively."
1789 :type 'string
1790 :version "24.4")
1792 (defcustom python-shell-prompt-detect-enabled t
1793 "Non-nil enables autodetection of interpreter prompts."
1794 :type 'boolean
1795 :safe 'booleanp
1796 :version "24.4")
1798 (defcustom python-shell-prompt-detect-failure-warning t
1799 "Non-nil enables warnings when detection of prompts fail."
1800 :type 'boolean
1801 :safe 'booleanp
1802 :version "24.4")
1804 (defcustom python-shell-prompt-input-regexps
1805 '(">>> " "\\.\\.\\. " ; Python
1806 "In \\[[0-9]+\\]: " ; IPython
1807 " \\.\\.\\.: " ; IPython
1808 ;; Using ipdb outside IPython may fail to cleanup and leave static
1809 ;; IPython prompts activated, this adds some safeguard for that.
1810 "In : " "\\.\\.\\.: ")
1811 "List of regular expressions matching input prompts."
1812 :type '(repeat string)
1813 :version "24.4")
1815 (defcustom python-shell-prompt-output-regexps
1816 '("" ; Python
1817 "Out\\[[0-9]+\\]: " ; IPython
1818 "Out :") ; ipdb safeguard
1819 "List of regular expressions matching output prompts."
1820 :type '(repeat string)
1821 :version "24.4")
1823 (defcustom python-shell-prompt-regexp ">>> "
1824 "Regular expression matching top level input prompt of Python shell.
1825 It should not contain a caret (^) at the beginning."
1826 :type 'string)
1828 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1829 "Regular expression matching block input prompt of Python shell.
1830 It should not contain a caret (^) at the beginning."
1831 :type 'string)
1833 (defcustom python-shell-prompt-output-regexp ""
1834 "Regular expression matching output prompt of Python shell.
1835 It should not contain a caret (^) at the beginning."
1836 :type 'string)
1838 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1839 "Regular expression matching pdb input prompt of Python shell.
1840 It should not contain a caret (^) at the beginning."
1841 :type 'string)
1843 (define-obsolete-variable-alias
1844 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1846 (defcustom python-shell-font-lock-enable t
1847 "Should syntax highlighting be enabled in the Python shell buffer?
1848 Restart the Python shell after changing this variable for it to take effect."
1849 :type 'boolean
1850 :group 'python
1851 :safe 'booleanp)
1853 (defcustom python-shell-unbuffered t
1854 "Should shell output be unbuffered?.
1855 When non-nil, this may prevent delayed and missing output in the
1856 Python shell. See commentary for details."
1857 :type 'boolean
1858 :group 'python
1859 :safe 'booleanp)
1861 (defcustom python-shell-process-environment nil
1862 "List of environment variables for Python shell.
1863 This variable follows the same rules as `process-environment'
1864 since it merges with it before the process creation routines are
1865 called. When this variable is nil, the Python shell is run with
1866 the default `process-environment'."
1867 :type '(repeat string)
1868 :group 'python
1869 :safe 'listp)
1871 (defcustom python-shell-extra-pythonpaths nil
1872 "List of extra pythonpaths for Python shell.
1873 The values of this variable are added to the existing value of
1874 PYTHONPATH in the `process-environment' variable."
1875 :type '(repeat string)
1876 :group 'python
1877 :safe 'listp)
1879 (defcustom python-shell-exec-path nil
1880 "List of path to search for binaries.
1881 This variable follows the same rules as `exec-path' since it
1882 merges with it before the process creation routines are called.
1883 When this variable is nil, the Python shell is run with the
1884 default `exec-path'."
1885 :type '(repeat string)
1886 :group 'python
1887 :safe 'listp)
1889 (defcustom python-shell-virtualenv-root nil
1890 "Path to virtualenv root.
1891 This variable, when set to a string, makes the values stored in
1892 `python-shell-process-environment' and `python-shell-exec-path'
1893 to be modified properly so shells are started with the specified
1894 virtualenv."
1895 :type '(choice (const nil) string)
1896 :group 'python
1897 :safe 'stringp)
1899 (define-obsolete-variable-alias
1900 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
1902 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1903 python-ffap-setup-code
1904 python-eldoc-setup-code)
1905 "List of code run by `python-shell-send-setup-codes'."
1906 :type '(repeat symbol)
1907 :group 'python
1908 :safe 'listp)
1910 (defcustom python-shell-compilation-regexp-alist
1911 `((,(rx line-start (1+ (any " \t")) "File \""
1912 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1913 "\", line " (group (1+ digit)))
1914 1 2)
1915 (,(rx " in file " (group (1+ not-newline)) " on line "
1916 (group (1+ digit)))
1917 1 2)
1918 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1919 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1920 1 2))
1921 "`compilation-error-regexp-alist' for inferior Python."
1922 :type '(alist string)
1923 :group 'python)
1925 (defvar python-shell--prompt-calculated-input-regexp nil
1926 "Calculated input prompt regexp for inferior python shell.
1927 Do not set this variable directly, instead use
1928 `python-shell-prompt-set-calculated-regexps'.")
1930 (defvar python-shell--prompt-calculated-output-regexp nil
1931 "Calculated output prompt regexp for inferior python shell.
1932 Do not set this variable directly, instead use
1933 `python-shell-set-prompt-regexp'.")
1935 (defun python-shell-prompt-detect ()
1936 "Detect prompts for the current `python-shell-interpreter'.
1937 When prompts can be retrieved successfully from the
1938 `python-shell-interpreter' run with
1939 `python-shell-interpreter-interactive-arg', returns a list of
1940 three elements, where the first two are input prompts and the
1941 last one is an output prompt. When no prompts can be detected
1942 and `python-shell-prompt-detect-failure-warning' is non-nil,
1943 shows a warning with instructions to avoid hangs and returns nil.
1944 When `python-shell-prompt-detect-enabled' is nil avoids any
1945 detection and just returns nil."
1946 (when python-shell-prompt-detect-enabled
1947 (let* ((process-environment (python-shell-calculate-process-environment))
1948 (exec-path (python-shell-calculate-exec-path))
1949 (code (concat
1950 "import sys\n"
1951 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1952 ;; JSON is built manually for compatibility
1953 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1954 "print (ps_json)\n"
1955 "sys.exit(0)\n"))
1956 (output
1957 (with-temp-buffer
1958 ;; TODO: improve error handling by using
1959 ;; `condition-case' and displaying the error message to
1960 ;; the user in the no-prompts warning.
1961 (ignore-errors
1962 (let ((code-file (python-shell--save-temp-file code)))
1963 ;; Use `process-file' as it is remote-host friendly.
1964 (process-file
1965 python-shell-interpreter
1966 code-file
1967 '(t nil)
1969 python-shell-interpreter-interactive-arg)
1970 ;; Try to cleanup
1971 (delete-file code-file)))
1972 (buffer-string)))
1973 (prompts
1974 (catch 'prompts
1975 (dolist (line (split-string output "\n" t))
1976 (let ((res
1977 ;; Check if current line is a valid JSON array
1978 (and (string= (substring line 0 2) "[\"")
1979 (ignore-errors
1980 ;; Return prompts as a list, not vector
1981 (append (json-read-from-string line) nil)))))
1982 ;; The list must contain 3 strings, where the first
1983 ;; is the input prompt, the second is the block
1984 ;; prompt and the last one is the output prompt. The
1985 ;; input prompt is the only one that can't be empty.
1986 (when (and (= (length res) 3)
1987 (cl-every #'stringp res)
1988 (not (string= (car res) "")))
1989 (throw 'prompts res))))
1990 nil)))
1991 (when (and (not prompts)
1992 python-shell-prompt-detect-failure-warning)
1993 (lwarn
1994 '(python python-shell-prompt-regexp)
1995 :warning
1996 (concat
1997 "Python shell prompts cannot be detected.\n"
1998 "If your emacs session hangs when starting python shells\n"
1999 "recover with `keyboard-quit' and then try fixing the\n"
2000 "interactive flag for your interpreter by adjusting the\n"
2001 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2002 "matching shell prompts in the directory-local friendly vars:\n"
2003 " + `python-shell-prompt-regexp'\n"
2004 " + `python-shell-prompt-block-regexp'\n"
2005 " + `python-shell-prompt-output-regexp'\n"
2006 "Or alternatively in:\n"
2007 " + `python-shell-prompt-input-regexps'\n"
2008 " + `python-shell-prompt-output-regexps'")))
2009 prompts)))
2011 (defun python-shell-prompt-validate-regexps ()
2012 "Validate all user provided regexps for prompts.
2013 Signals `user-error' if any of these vars contain invalid
2014 regexps: `python-shell-prompt-regexp',
2015 `python-shell-prompt-block-regexp',
2016 `python-shell-prompt-pdb-regexp',
2017 `python-shell-prompt-output-regexp',
2018 `python-shell-prompt-input-regexps',
2019 `python-shell-prompt-output-regexps'."
2020 (dolist (symbol (list 'python-shell-prompt-input-regexps
2021 'python-shell-prompt-output-regexps
2022 'python-shell-prompt-regexp
2023 'python-shell-prompt-block-regexp
2024 'python-shell-prompt-pdb-regexp
2025 'python-shell-prompt-output-regexp))
2026 (dolist (regexp (let ((regexps (symbol-value symbol)))
2027 (if (listp regexps)
2028 regexps
2029 (list regexps))))
2030 (when (not (python-util-valid-regexp-p regexp))
2031 (user-error "Invalid regexp %s in `%s'"
2032 regexp symbol)))))
2034 (defun python-shell-prompt-set-calculated-regexps ()
2035 "Detect and set input and output prompt regexps.
2036 Build and set the values for `python-shell-input-prompt-regexp'
2037 and `python-shell-output-prompt-regexp' using the values from
2038 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2039 `python-shell-prompt-pdb-regexp',
2040 `python-shell-prompt-output-regexp',
2041 `python-shell-prompt-input-regexps',
2042 `python-shell-prompt-output-regexps' and detected prompts from
2043 `python-shell-prompt-detect'."
2044 (when (not (and python-shell--prompt-calculated-input-regexp
2045 python-shell--prompt-calculated-output-regexp))
2046 (let* ((detected-prompts (python-shell-prompt-detect))
2047 (input-prompts nil)
2048 (output-prompts nil)
2049 (build-regexp
2050 (lambda (prompts)
2051 (concat "^\\("
2052 (mapconcat #'identity
2053 (sort prompts
2054 (lambda (a b)
2055 (let ((length-a (length a))
2056 (length-b (length b)))
2057 (if (= length-a length-b)
2058 (string< a b)
2059 (> (length a) (length b))))))
2060 "\\|")
2061 "\\)"))))
2062 ;; Validate ALL regexps
2063 (python-shell-prompt-validate-regexps)
2064 ;; Collect all user defined input prompts
2065 (dolist (prompt (append python-shell-prompt-input-regexps
2066 (list python-shell-prompt-regexp
2067 python-shell-prompt-block-regexp
2068 python-shell-prompt-pdb-regexp)))
2069 (cl-pushnew prompt input-prompts :test #'string=))
2070 ;; Collect all user defined output prompts
2071 (dolist (prompt (cons python-shell-prompt-output-regexp
2072 python-shell-prompt-output-regexps))
2073 (cl-pushnew prompt output-prompts :test #'string=))
2074 ;; Collect detected prompts if any
2075 (when detected-prompts
2076 (dolist (prompt (butlast detected-prompts))
2077 (setq prompt (regexp-quote prompt))
2078 (cl-pushnew prompt input-prompts :test #'string=))
2079 (cl-pushnew (regexp-quote
2080 (car (last detected-prompts)))
2081 output-prompts :test #'string=))
2082 ;; Set input and output prompt regexps from collected prompts
2083 (setq python-shell--prompt-calculated-input-regexp
2084 (funcall build-regexp input-prompts)
2085 python-shell--prompt-calculated-output-regexp
2086 (funcall build-regexp output-prompts)))))
2088 (defun python-shell-get-process-name (dedicated)
2089 "Calculate the appropriate process name for inferior Python process.
2090 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2091 returns a string with the form
2092 `python-shell-buffer-name'[variable `buffer-file-name'] else
2093 returns the value of `python-shell-buffer-name'."
2094 (let ((process-name
2095 (if (and dedicated
2096 buffer-file-name)
2097 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
2098 (format "%s" python-shell-buffer-name))))
2099 process-name))
2101 (defun python-shell-internal-get-process-name ()
2102 "Calculate the appropriate process name for Internal Python process.
2103 The name is calculated from `python-shell-global-buffer-name' and
2104 a hash of all relevant global shell settings in order to ensure
2105 uniqueness for different types of configurations."
2106 (format "%s [%s]"
2107 python-shell-internal-buffer-name
2108 (md5
2109 (concat
2110 python-shell-interpreter
2111 python-shell-interpreter-args
2112 python-shell--prompt-calculated-input-regexp
2113 python-shell--prompt-calculated-output-regexp
2114 (mapconcat #'symbol-value python-shell-setup-codes "")
2115 (mapconcat #'identity python-shell-process-environment "")
2116 (mapconcat #'identity python-shell-extra-pythonpaths "")
2117 (mapconcat #'identity python-shell-exec-path "")
2118 (or python-shell-virtualenv-root "")
2119 (mapconcat #'identity python-shell-exec-path "")))))
2121 (defun python-shell-calculate-command ()
2122 "Calculate the string used to execute the inferior Python process."
2123 (let ((exec-path (python-shell-calculate-exec-path)))
2124 ;; `exec-path' gets tweaked so that virtualenv's specific
2125 ;; `python-shell-interpreter' absolute path can be found by
2126 ;; `executable-find'.
2127 (format "%s %s"
2128 ;; FIXME: Why executable-find?
2129 (shell-quote-argument
2130 (executable-find python-shell-interpreter))
2131 python-shell-interpreter-args)))
2133 (define-obsolete-function-alias
2134 'python-shell-parse-command
2135 #'python-shell-calculate-command "25.1")
2137 (defun python-shell-calculate-pythonpath ()
2138 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2139 (let ((pythonpath (getenv "PYTHONPATH"))
2140 (extra (mapconcat 'identity
2141 python-shell-extra-pythonpaths
2142 path-separator)))
2143 (if pythonpath
2144 (concat extra path-separator pythonpath)
2145 extra)))
2147 (defun python-shell-calculate-process-environment ()
2148 "Calculate process environment given `python-shell-virtualenv-root'."
2149 (let ((process-environment (append
2150 python-shell-process-environment
2151 process-environment nil))
2152 (virtualenv (if python-shell-virtualenv-root
2153 (directory-file-name python-shell-virtualenv-root)
2154 nil)))
2155 (when python-shell-unbuffered
2156 (setenv "PYTHONUNBUFFERED" "1"))
2157 (when python-shell-extra-pythonpaths
2158 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2159 (if (not virtualenv)
2160 process-environment
2161 (setenv "PYTHONHOME" nil)
2162 (setenv "PATH" (format "%s/bin%s%s"
2163 virtualenv path-separator
2164 (or (getenv "PATH") "")))
2165 (setenv "VIRTUAL_ENV" virtualenv))
2166 process-environment))
2168 (defun python-shell-calculate-exec-path ()
2169 "Calculate exec path given `python-shell-virtualenv-root'."
2170 (let ((path (append
2171 ;; Use nil as the tail so that the list is a full copy,
2172 ;; this is a paranoid safeguard for side-effects.
2173 python-shell-exec-path exec-path nil)))
2174 (if (not python-shell-virtualenv-root)
2175 path
2176 (cons (expand-file-name "bin" python-shell-virtualenv-root)
2177 path))))
2179 (defvar python-shell--package-depth 10)
2181 (defun python-shell-package-enable (directory package)
2182 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2183 (interactive
2184 (let* ((dir (expand-file-name
2185 (read-directory-name
2186 "Package root: "
2187 (file-name-directory
2188 (or (buffer-file-name) default-directory)))))
2189 (name (completing-read
2190 "Package: "
2191 (python-util-list-packages
2192 dir python-shell--package-depth))))
2193 (list dir name)))
2194 (python-shell-send-string
2195 (format
2196 (concat
2197 "import os.path;import sys;"
2198 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2199 "__package__ = '''%s''';"
2200 "import %s")
2201 directory package package)
2202 (python-shell-get-process)))
2204 (defun python-shell-accept-process-output (process &optional timeout regexp)
2205 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2206 Optional argument TIMEOUT is the timeout argument to
2207 `accept-process-output' calls. Optional argument REGEXP
2208 overrides the regexp to match the end of output, defaults to
2209 `comint-prompt-regexp.'. Returns non-nil when output was
2210 properly captured.
2212 This utility is useful in situations where the output may be
2213 received in chunks, since `accept-process-output' gives no
2214 guarantees they will be grabbed in a single call. An example use
2215 case for this would be the CPython shell start-up, where the
2216 banner and the initial prompt are received separately."
2217 (let ((regexp (or regexp comint-prompt-regexp)))
2218 (catch 'found
2219 (while t
2220 (when (not (accept-process-output process timeout))
2221 (throw 'found nil))
2222 (when (looking-back regexp)
2223 (throw 'found t))))))
2225 (defun python-shell-comint-end-of-output-p (output)
2226 "Return non-nil if OUTPUT is ends with input prompt."
2227 (string-match
2228 ;; XXX: It seems on OSX an extra carriage return is attached
2229 ;; at the end of output, this handles that too.
2230 (concat
2231 "\r?\n?"
2232 ;; Remove initial caret from calculated regexp
2233 (replace-regexp-in-string
2234 (rx string-start ?^) ""
2235 python-shell--prompt-calculated-input-regexp)
2236 (rx eos))
2237 output))
2239 (define-obsolete-function-alias
2240 'python-comint-output-filter-function
2241 'ansi-color-filter-apply
2242 "25.1")
2244 (defun python-comint-postoutput-scroll-to-bottom (output)
2245 "Faster version of `comint-postoutput-scroll-to-bottom'.
2246 Avoids `recenter' calls until OUTPUT is completely sent."
2247 (when (and (not (string= "" output))
2248 (python-shell-comint-end-of-output-p
2249 (ansi-color-filter-apply output)))
2250 (comint-postoutput-scroll-to-bottom output))
2251 output)
2253 (defvar python-shell--parent-buffer nil)
2255 (defmacro python-shell-with-shell-buffer (&rest body)
2256 "Execute the forms in BODY with the shell buffer temporarily current.
2257 Signals an error if no shell buffer is available for current buffer."
2258 (declare (indent 0) (debug t))
2259 (let ((shell-buffer (make-symbol "shell-buffer")))
2260 `(let ((,shell-buffer (python-shell-get-buffer)))
2261 (when (not ,shell-buffer)
2262 (error "No inferior Python buffer available."))
2263 (with-current-buffer ,shell-buffer
2264 ,@body))))
2266 (defvar python-shell--font-lock-buffer nil)
2268 (defun python-shell-font-lock-get-or-create-buffer ()
2269 "Get or create a font-lock buffer for current inferior process."
2270 (python-shell-with-shell-buffer
2271 (if python-shell--font-lock-buffer
2272 python-shell--font-lock-buffer
2273 (let ((process-name
2274 (process-name (get-buffer-process (current-buffer)))))
2275 (generate-new-buffer
2276 (format "*%s-font-lock*" process-name))))))
2278 (defun python-shell-font-lock-kill-buffer ()
2279 "Kill the font-lock buffer safely."
2280 (python-shell-with-shell-buffer
2281 (when (and python-shell--font-lock-buffer
2282 (buffer-live-p python-shell--font-lock-buffer))
2283 (kill-buffer python-shell--font-lock-buffer)
2284 (when (derived-mode-p 'inferior-python-mode)
2285 (setq python-shell--font-lock-buffer nil)))))
2287 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2288 "Execute the forms in BODY in the font-lock buffer.
2289 The value returned is the value of the last form in BODY. See
2290 also `with-current-buffer'."
2291 (declare (indent 0) (debug t))
2292 `(python-shell-with-shell-buffer
2293 (save-current-buffer
2294 (when (not (and python-shell--font-lock-buffer
2295 (get-buffer python-shell--font-lock-buffer)))
2296 (setq python-shell--font-lock-buffer
2297 (python-shell-font-lock-get-or-create-buffer)))
2298 (set-buffer python-shell--font-lock-buffer)
2299 (set (make-local-variable 'delay-mode-hooks) t)
2300 (let ((python-indent-guess-indent-offset nil))
2301 (when (not (derived-mode-p 'python-mode))
2302 (python-mode))
2303 ,@body))))
2305 (defun python-shell-font-lock-cleanup-buffer ()
2306 "Cleanup the font-lock buffer.
2307 Provided as a command because this might be handy if something
2308 goes wrong and syntax highlighting in the shell gets messed up."
2309 (interactive)
2310 (python-shell-with-shell-buffer
2311 (python-shell-font-lock-with-font-lock-buffer
2312 (delete-region (point-min) (point-max)))))
2314 (defun python-shell-font-lock-comint-output-filter-function (output)
2315 "Clean up the font-lock buffer after any OUTPUT."
2316 (when (and (not (string= "" output))
2317 ;; Is end of output and is not just a prompt.
2318 (not (member
2319 (python-shell-comint-end-of-output-p
2320 (ansi-color-filter-apply output))
2321 '(nil 0))))
2322 ;; If output is other than an input prompt then "real" output has
2323 ;; been received and the font-lock buffer must be cleaned up.
2324 (python-shell-font-lock-cleanup-buffer))
2325 output)
2327 (defun python-shell-font-lock-post-command-hook ()
2328 "Fontifies current line in shell buffer."
2329 (if (eq this-command 'comint-send-input)
2330 ;; Add a newline when user sends input as this may be a block.
2331 (python-shell-font-lock-with-font-lock-buffer
2332 (goto-char (line-end-position))
2333 (newline))
2334 (when (and (python-util-comint-last-prompt)
2335 (> (point) (cdr (python-util-comint-last-prompt))))
2336 (let ((input (buffer-substring-no-properties
2337 (cdr (python-util-comint-last-prompt)) (point-max)))
2338 (old-input (python-shell-font-lock-with-font-lock-buffer
2339 (buffer-substring-no-properties
2340 (line-beginning-position) (point-max))))
2341 (current-point (point))
2342 (buffer-undo-list t))
2343 ;; When input hasn't changed, do nothing.
2344 (when (not (string= input old-input))
2345 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2346 (insert
2347 (python-shell-font-lock-with-font-lock-buffer
2348 (delete-region (line-beginning-position)
2349 (line-end-position))
2350 (insert input)
2351 ;; Ensure buffer is fontified, keeping it
2352 ;; compatible with Emacs < 24.4.
2353 (if (fboundp 'font-lock-ensure)
2354 (funcall 'font-lock-ensure)
2355 (font-lock-default-fontify-buffer))
2356 ;; Replace FACE text properties with FONT-LOCK-FACE so
2357 ;; they are not overwritten by comint buffer's font lock.
2358 (python-util-text-properties-replace-name
2359 'face 'font-lock-face)
2360 (buffer-substring (line-beginning-position)
2361 (line-end-position))))
2362 (goto-char current-point))))))
2364 (defun python-shell-font-lock-turn-on (&optional msg)
2365 "Turn on shell font-lock.
2366 With argument MSG show activation message."
2367 (interactive "p")
2368 (python-shell-with-shell-buffer
2369 (python-shell-font-lock-kill-buffer)
2370 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2371 (add-hook 'post-command-hook
2372 #'python-shell-font-lock-post-command-hook nil 'local)
2373 (add-hook 'kill-buffer-hook
2374 #'python-shell-font-lock-kill-buffer nil 'local)
2375 (add-hook 'comint-output-filter-functions
2376 #'python-shell-font-lock-comint-output-filter-function
2377 'append 'local)
2378 (when msg
2379 (message "Shell font-lock is enabled"))))
2381 (defun python-shell-font-lock-turn-off (&optional msg)
2382 "Turn off shell font-lock.
2383 With argument MSG show deactivation message."
2384 (interactive "p")
2385 (python-shell-with-shell-buffer
2386 (python-shell-font-lock-kill-buffer)
2387 (when (python-util-comint-last-prompt)
2388 ;; Cleanup current fontification
2389 (remove-text-properties
2390 (cdr (python-util-comint-last-prompt))
2391 (line-end-position)
2392 '(face nil font-lock-face nil)))
2393 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2394 (remove-hook 'post-command-hook
2395 #'python-shell-font-lock-post-command-hook'local)
2396 (remove-hook 'kill-buffer-hook
2397 #'python-shell-font-lock-kill-buffer 'local)
2398 (remove-hook 'comint-output-filter-functions
2399 #'python-shell-font-lock-comint-output-filter-function
2400 'local)
2401 (when msg
2402 (message "Shell font-lock is disabled"))))
2404 (defun python-shell-font-lock-toggle (&optional msg)
2405 "Toggle font-lock for shell.
2406 With argument MSG show activation/deactivation message."
2407 (interactive "p")
2408 (python-shell-with-shell-buffer
2409 (set (make-local-variable 'python-shell-font-lock-enable)
2410 (not python-shell-font-lock-enable))
2411 (if python-shell-font-lock-enable
2412 (python-shell-font-lock-turn-on msg)
2413 (python-shell-font-lock-turn-off msg))
2414 python-shell-font-lock-enable))
2416 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2417 "Major mode for Python inferior process.
2418 Runs a Python interpreter as a subprocess of Emacs, with Python
2419 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2420 and `python-shell-interpreter-args' control which Python
2421 interpreter is run. Variables
2422 `python-shell-prompt-regexp',
2423 `python-shell-prompt-output-regexp',
2424 `python-shell-prompt-block-regexp',
2425 `python-shell-font-lock-enable',
2426 `python-shell-completion-setup-code',
2427 `python-shell-completion-string-code',
2428 `python-eldoc-setup-code', `python-eldoc-string-code',
2429 `python-ffap-setup-code' and `python-ffap-string-code' can
2430 customize this mode for different Python interpreters.
2432 This mode resets `comint-output-filter-functions' locally, so you
2433 may want to re-add custom functions to it using the
2434 `inferior-python-mode-hook'.
2436 You can also add additional setup code to be run at
2437 initialization of the interpreter via `python-shell-setup-codes'
2438 variable.
2440 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2441 (let ((interpreter python-shell-interpreter)
2442 (args python-shell-interpreter-args))
2443 (when python-shell--parent-buffer
2444 (python-util-clone-local-variables python-shell--parent-buffer))
2445 ;; Users can override default values for these vars when calling
2446 ;; `run-python'. This ensures new values let-bound in
2447 ;; `python-shell-make-comint' are locally set.
2448 (set (make-local-variable 'python-shell-interpreter) interpreter)
2449 (set (make-local-variable 'python-shell-interpreter-args) args))
2450 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2451 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2452 (python-shell-prompt-set-calculated-regexps)
2453 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2454 (set (make-local-variable 'comint-prompt-read-only) t)
2455 (setq mode-line-process '(":%s"))
2456 (set (make-local-variable 'comint-output-filter-functions)
2457 '(ansi-color-process-output
2458 python-pdbtrack-comint-output-filter-function
2459 python-comint-postoutput-scroll-to-bottom))
2460 (set (make-local-variable 'compilation-error-regexp-alist)
2461 python-shell-compilation-regexp-alist)
2462 (add-hook 'completion-at-point-functions
2463 #'python-shell-completion-at-point nil 'local)
2464 (define-key inferior-python-mode-map "\t"
2465 'python-shell-completion-complete-or-indent)
2466 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2467 (make-local-variable 'python-pdbtrack-tracked-buffer)
2468 (make-local-variable 'python-shell-internal-last-output)
2469 (when python-shell-font-lock-enable
2470 (python-shell-font-lock-turn-on))
2471 (compilation-shell-minor-mode 1)
2472 (python-shell-accept-process-output
2473 (get-buffer-process (current-buffer))))
2475 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
2476 "Create a Python shell comint buffer.
2477 CMD is the Python command to be executed and PROC-NAME is the
2478 process name the comint buffer will get. After the comint buffer
2479 is created the `inferior-python-mode' is activated. When
2480 optional argument POP is non-nil the buffer is shown. When
2481 optional argument INTERNAL is non-nil this process is run on a
2482 buffer with a name that starts with a space, following the Emacs
2483 convention for temporary/internal buffers, and also makes sure
2484 the user is not queried for confirmation when the process is
2485 killed."
2486 (save-excursion
2487 (let* ((proc-buffer-name
2488 (format (if (not internal) "*%s*" " *%s*") proc-name))
2489 (process-environment (python-shell-calculate-process-environment))
2490 (exec-path (python-shell-calculate-exec-path)))
2491 (when (not (comint-check-proc proc-buffer-name))
2492 (let* ((cmdlist (split-string-and-unquote cmd))
2493 (interpreter (car cmdlist))
2494 (args (cdr cmdlist))
2495 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2496 interpreter nil args))
2497 (python-shell--parent-buffer (current-buffer))
2498 (process (get-buffer-process buffer))
2499 ;; As the user may have overridden default values for
2500 ;; these vars on `run-python', let-binding them allows
2501 ;; to have the new right values in all setup code
2502 ;; that's is done in `inferior-python-mode', which is
2503 ;; important, especially for prompt detection.
2504 (python-shell-interpreter interpreter)
2505 (python-shell-interpreter-args
2506 (mapconcat #'identity args " ")))
2507 (with-current-buffer buffer
2508 (inferior-python-mode))
2509 (and pop (pop-to-buffer buffer t))
2510 (and internal (set-process-query-on-exit-flag process nil))))
2511 proc-buffer-name)))
2513 ;;;###autoload
2514 (defun run-python (&optional cmd dedicated show)
2515 "Run an inferior Python process.
2516 Input and output via buffer named after
2517 `python-shell-buffer-name'. If there is a process already
2518 running in that buffer, just switch to it.
2520 Argument CMD defaults to `python-shell-calculate-command' return
2521 value. When called interactively with `prefix-arg', it allows
2522 the user to edit such value and choose whether the interpreter
2523 should be DEDICATED for the current buffer. When numeric prefix
2524 arg is other than 0 or 4 do not SHOW.
2526 Runs the hook `inferior-python-mode-hook' after
2527 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2528 process buffer for a list of commands.)"
2529 (interactive
2530 (if current-prefix-arg
2531 (list
2532 (read-shell-command "Run Python: " (python-shell-calculate-command))
2533 (y-or-n-p "Make dedicated process? ")
2534 (= (prefix-numeric-value current-prefix-arg) 4))
2535 (list (python-shell-calculate-command) nil t)))
2536 (python-shell-make-comint
2537 (or cmd (python-shell-calculate-command))
2538 (python-shell-get-process-name dedicated) show)
2539 dedicated)
2541 (defun run-python-internal ()
2542 "Run an inferior Internal Python process.
2543 Input and output via buffer named after
2544 `python-shell-internal-buffer-name' and what
2545 `python-shell-internal-get-process-name' returns.
2547 This new kind of shell is intended to be used for generic
2548 communication related to defined configurations; the main
2549 difference with global or dedicated shells is that these ones are
2550 attached to a configuration, not a buffer. This means that can
2551 be used for example to retrieve the sys.path and other stuff,
2552 without messing with user shells. Note that
2553 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2554 are set to nil for these shells, so setup codes are not sent at
2555 startup."
2556 (let ((python-shell-font-lock-enable nil)
2557 (inferior-python-mode-hook nil))
2558 (get-buffer-process
2559 (python-shell-make-comint
2560 (python-shell-calculate-command)
2561 (python-shell-internal-get-process-name) nil t))))
2563 (defun python-shell-get-buffer ()
2564 "Return inferior Python buffer for current buffer.
2565 If current buffer is in `inferior-python-mode', return it."
2566 (if (derived-mode-p 'inferior-python-mode)
2567 (current-buffer)
2568 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2569 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2570 (global-proc-name (python-shell-get-process-name nil))
2571 (global-proc-buffer-name (format "*%s*" global-proc-name))
2572 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2573 (global-running (comint-check-proc global-proc-buffer-name)))
2574 ;; Always prefer dedicated
2575 (or (and dedicated-running dedicated-proc-buffer-name)
2576 (and global-running global-proc-buffer-name)))))
2578 (defun python-shell-get-process ()
2579 "Return inferior Python process for current buffer."
2580 (get-buffer-process (python-shell-get-buffer)))
2582 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2583 "Get or create an inferior Python process for current buffer and return it.
2584 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2585 are used to start the shell. If those arguments are not
2586 provided, `run-python' is called interactively and the user will
2587 be asked for their values."
2588 (let ((shell-process (python-shell-get-process)))
2589 (when (not shell-process)
2590 (if (not cmd)
2591 ;; XXX: Refactor code such that calling `run-python'
2592 ;; interactively is not needed anymore.
2593 (call-interactively 'run-python)
2594 (run-python cmd dedicated show)))
2595 (or shell-process (python-shell-get-process))))
2597 (defvar python-shell-internal-buffer nil
2598 "Current internal shell buffer for the current buffer.
2599 This is really not necessary at all for the code to work but it's
2600 there for compatibility with CEDET.")
2602 (defvar python-shell-internal-last-output nil
2603 "Last output captured by the internal shell.
2604 This is really not necessary at all for the code to work but it's
2605 there for compatibility with CEDET.")
2607 (defun python-shell-internal-get-or-create-process ()
2608 "Get or create an inferior Internal Python process."
2609 (let* ((proc-name (python-shell-internal-get-process-name))
2610 (proc-buffer-name (format " *%s*" proc-name)))
2611 (when (not (process-live-p proc-name))
2612 (run-python-internal)
2613 (setq python-shell-internal-buffer proc-buffer-name))
2614 (get-buffer-process proc-buffer-name)))
2616 (define-obsolete-function-alias
2617 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2619 (define-obsolete-variable-alias
2620 'python-buffer 'python-shell-internal-buffer "24.3")
2622 (define-obsolete-variable-alias
2623 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2625 (defun python-shell--save-temp-file (string)
2626 (let* ((temporary-file-directory
2627 (if (file-remote-p default-directory)
2628 (concat (file-remote-p default-directory) "/tmp")
2629 temporary-file-directory))
2630 (temp-file-name (make-temp-file "py"))
2631 (coding-system-for-write 'utf-8))
2632 (with-temp-file temp-file-name
2633 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2634 (insert string)
2635 (delete-trailing-whitespace))
2636 temp-file-name))
2638 (defun python-shell-send-string (string &optional process)
2639 "Send STRING to inferior Python PROCESS."
2640 (interactive "sPython command: ")
2641 (let ((process (or process (python-shell-get-or-create-process))))
2642 (if (string-match ".\n+." string) ;Multiline.
2643 (let* ((temp-file-name (python-shell--save-temp-file string)))
2644 (python-shell-send-file temp-file-name process temp-file-name t))
2645 (comint-send-string process string)
2646 (when (or (not (string-match "\n\\'" string))
2647 (string-match "\n[ \t].*\n?\\'" string))
2648 (comint-send-string process "\n")))))
2650 (defvar python-shell-output-filter-in-progress nil)
2651 (defvar python-shell-output-filter-buffer nil)
2653 (defun python-shell-output-filter (string)
2654 "Filter used in `python-shell-send-string-no-output' to grab output.
2655 STRING is the output received to this point from the process.
2656 This filter saves received output from the process in
2657 `python-shell-output-filter-buffer' and stops receiving it after
2658 detecting a prompt at the end of the buffer."
2659 (setq
2660 string (ansi-color-filter-apply string)
2661 python-shell-output-filter-buffer
2662 (concat python-shell-output-filter-buffer string))
2663 (when (python-shell-comint-end-of-output-p
2664 python-shell-output-filter-buffer)
2665 ;; Output ends when `python-shell-output-filter-buffer' contains
2666 ;; the prompt attached at the end of it.
2667 (setq python-shell-output-filter-in-progress nil
2668 python-shell-output-filter-buffer
2669 (substring python-shell-output-filter-buffer
2670 0 (match-beginning 0)))
2671 (when (string-match
2672 python-shell--prompt-calculated-output-regexp
2673 python-shell-output-filter-buffer)
2674 ;; Some shells, like IPython might append a prompt before the
2675 ;; output, clean that.
2676 (setq python-shell-output-filter-buffer
2677 (substring python-shell-output-filter-buffer (match-end 0)))))
2680 (defun python-shell-send-string-no-output (string &optional process)
2681 "Send STRING to PROCESS and inhibit output.
2682 Return the output."
2683 (let ((process (or process (python-shell-get-or-create-process)))
2684 (comint-preoutput-filter-functions
2685 '(python-shell-output-filter))
2686 (python-shell-output-filter-in-progress t)
2687 (inhibit-quit t))
2689 (with-local-quit
2690 (python-shell-send-string string process)
2691 (while python-shell-output-filter-in-progress
2692 ;; `python-shell-output-filter' takes care of setting
2693 ;; `python-shell-output-filter-in-progress' to NIL after it
2694 ;; detects end of output.
2695 (accept-process-output process))
2696 (prog1
2697 python-shell-output-filter-buffer
2698 (setq python-shell-output-filter-buffer nil)))
2699 (with-current-buffer (process-buffer process)
2700 (comint-interrupt-subjob)))))
2702 (defun python-shell-internal-send-string (string)
2703 "Send STRING to the Internal Python interpreter.
2704 Returns the output. See `python-shell-send-string-no-output'."
2705 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2706 ;; updated to support this new mode.
2707 (setq python-shell-internal-last-output
2708 (python-shell-send-string-no-output
2709 ;; Makes this function compatible with the old
2710 ;; python-send-receive. (At least for CEDET).
2711 (replace-regexp-in-string "_emacs_out +" "" string)
2712 (python-shell-internal-get-or-create-process))))
2714 (define-obsolete-function-alias
2715 'python-send-receive 'python-shell-internal-send-string "24.3")
2717 (define-obsolete-function-alias
2718 'python-send-string 'python-shell-internal-send-string "24.3")
2720 (defvar python--use-fake-loc nil
2721 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2722 If nil, regions of text are prepended by the corresponding number of empty
2723 lines and Python is told to output error messages referring to the whole
2724 source file.")
2726 (defun python-shell-buffer-substring (start end &optional nomain)
2727 "Send buffer substring from START to END formatted for shell.
2728 This is a wrapper over `buffer-substring' that takes care of
2729 different transformations for the code sent to be evaluated in
2730 the python shell:
2731 1. When optional argument NOMAIN is non-nil everything under an
2732 \"if __name__ == '__main__'\" block will be removed.
2733 2. When a subregion of the buffer is sent, it takes care of
2734 appending extra empty lines so tracebacks are correct.
2735 3. Wraps indented regions under an \"if True:\" block so the
2736 interpreter evaluates them correctly."
2737 (let ((substring (buffer-substring-no-properties start end))
2738 (fillstr (unless python--use-fake-loc
2739 (make-string (1- (line-number-at-pos start)) ?\n)))
2740 (toplevel-block-p (save-excursion
2741 (goto-char start)
2742 (or (zerop (line-number-at-pos start))
2743 (progn
2744 (python-util-forward-comment 1)
2745 (zerop (current-indentation)))))))
2746 (with-temp-buffer
2747 (python-mode)
2748 (if fillstr (insert fillstr))
2749 (insert substring)
2750 (goto-char (point-min))
2751 (unless python--use-fake-loc
2752 ;; python-shell--save-temp-file adds an extra coding line, which would
2753 ;; throw off the line-counts, so let's try to compensate here.
2754 (if (looking-at "[ \t]*[#\n]")
2755 (delete-region (point) (line-beginning-position 2))))
2756 (when (not toplevel-block-p)
2757 (insert "if True:")
2758 (delete-region (point) (line-end-position)))
2759 (when nomain
2760 (let* ((if-name-main-start-end
2761 (and nomain
2762 (save-excursion
2763 (when (python-nav-if-name-main)
2764 (cons (point)
2765 (progn (python-nav-forward-sexp-safe)
2766 (point)))))))
2767 ;; Oh destructuring bind, how I miss you.
2768 (if-name-main-start (car if-name-main-start-end))
2769 (if-name-main-end (cdr if-name-main-start-end)))
2770 (when if-name-main-start-end
2771 (goto-char if-name-main-start)
2772 (delete-region if-name-main-start if-name-main-end)
2773 (insert
2774 (make-string
2775 (- (line-number-at-pos if-name-main-end)
2776 (line-number-at-pos if-name-main-start)) ?\n)))))
2777 (buffer-substring-no-properties (point-min) (point-max)))))
2779 (declare-function compilation-fake-loc "compile"
2780 (marker file &optional line col))
2782 (defun python-shell-send-region (start end &optional nomain)
2783 "Send the region delimited by START and END to inferior Python process."
2784 (interactive "r")
2785 (let* ((python--use-fake-loc
2786 (or python--use-fake-loc (not buffer-file-name)))
2787 (string (python-shell-buffer-substring start end nomain))
2788 (process (python-shell-get-or-create-process))
2789 (_ (string-match "\\`\n*\\(.*\\)" string)))
2790 (message "Sent: %s..." (match-string 1 string))
2791 (let* ((temp-file-name (python-shell--save-temp-file string))
2792 (file-name (or (buffer-file-name) temp-file-name)))
2793 (python-shell-send-file file-name process temp-file-name t)
2794 (unless python--use-fake-loc
2795 (with-current-buffer (process-buffer process)
2796 (compilation-fake-loc (copy-marker start) temp-file-name
2797 2)) ;; Not 1, because of the added coding line.
2798 ))))
2800 (defun python-shell-send-buffer (&optional arg)
2801 "Send the entire buffer to inferior Python process.
2802 With prefix ARG allow execution of code inside blocks delimited
2803 by \"if __name__== '__main__':\"."
2804 (interactive "P")
2805 (save-restriction
2806 (widen)
2807 (python-shell-send-region (point-min) (point-max) (not arg))))
2809 (defun python-shell-send-defun (arg)
2810 "Send the current defun to inferior Python process.
2811 When argument ARG is non-nil do not include decorators."
2812 (interactive "P")
2813 (save-excursion
2814 (python-shell-send-region
2815 (progn
2816 (end-of-line 1)
2817 (while (and (or (python-nav-beginning-of-defun)
2818 (beginning-of-line 1))
2819 (> (current-indentation) 0)))
2820 (when (not arg)
2821 (while (and (forward-line -1)
2822 (looking-at (python-rx decorator))))
2823 (forward-line 1))
2824 (point-marker))
2825 (progn
2826 (or (python-nav-end-of-defun)
2827 (end-of-line 1))
2828 (point-marker)))))
2830 (defun python-shell-send-file (file-name &optional process temp-file-name
2831 delete)
2832 "Send FILE-NAME to inferior Python PROCESS.
2833 If TEMP-FILE-NAME is passed then that file is used for processing
2834 instead, while internally the shell will continue to use FILE-NAME.
2835 If DELETE is non-nil, delete the file afterwards."
2836 (interactive "fFile to send: ")
2837 (let* ((process (or process (python-shell-get-or-create-process)))
2838 (temp-file-name (when temp-file-name
2839 (expand-file-name
2840 (or (file-remote-p temp-file-name 'localname)
2841 temp-file-name))))
2842 (file-name (or (when file-name
2843 (expand-file-name
2844 (or (file-remote-p file-name 'localname)
2845 file-name)))
2846 temp-file-name)))
2847 (when (not file-name)
2848 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2849 (python-shell-send-string
2850 (format
2851 (concat "__pyfile = open('''%s''');"
2852 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2853 "__pyfile.close()%s")
2854 (or temp-file-name file-name) file-name
2855 (if delete (format "; import os; os.remove('''%s''')"
2856 (or temp-file-name file-name))
2857 ""))
2858 process)))
2860 (defun python-shell-switch-to-shell ()
2861 "Switch to inferior Python process buffer."
2862 (interactive)
2863 (process-buffer (python-shell-get-or-create-process)) t)
2865 (defun python-shell-send-setup-code ()
2866 "Send all setup code for shell.
2867 This function takes the list of setup code to send from the
2868 `python-shell-setup-codes' list."
2869 (let ((process (python-shell-get-process))
2870 (code (concat
2871 (mapconcat
2872 (lambda (elt)
2873 (cond ((stringp elt) elt)
2874 ((symbolp elt) (symbol-value elt))
2875 (t "")))
2876 python-shell-setup-codes
2877 "\n\n")
2878 "\n\nprint ('python.el: sent setup code')")))
2879 (python-shell-send-string code process)
2880 (python-shell-accept-process-output process)))
2882 (add-hook 'inferior-python-mode-hook
2883 #'python-shell-send-setup-code)
2886 ;;; Shell completion
2888 (defcustom python-shell-completion-setup-code
2889 "try:
2890 import __builtin__
2891 except ImportError:
2892 # Python 3
2893 import builtins as __builtin__
2894 try:
2895 import readline, rlcompleter
2896 except:
2897 def __PYTHON_EL_get_completions(text):
2898 return []
2899 else:
2900 def __PYTHON_EL_get_completions(text):
2901 builtins = dir(__builtin__)
2902 completions = []
2903 try:
2904 splits = text.split()
2905 is_module = splits and splits[0] in ('from', 'import')
2906 is_ipython = ('__IPYTHON__' in builtins or
2907 '__IPYTHON__active' in builtins)
2908 if is_module:
2909 from IPython.core.completerlib import module_completion
2910 completions = module_completion(text.strip())
2911 elif is_ipython and '__IP' in builtins:
2912 completions = __IP.complete(text)
2913 elif is_ipython and 'get_ipython' in builtins:
2914 completions = get_ipython().Completer.all_completions(text)
2915 else:
2916 i = 0
2917 while True:
2918 res = readline.get_completer()(text, i)
2919 if not res:
2920 break
2921 i += 1
2922 completions.append(res)
2923 except:
2924 pass
2925 return completions"
2926 "Code used to setup completion in inferior Python processes."
2927 :type 'string
2928 :group 'python)
2930 (defcustom python-shell-completion-string-code
2931 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2932 "Python code used to get a string of completions separated by semicolons.
2933 The string passed to the function is the current python name or
2934 the full statement in the case of imports."
2935 :type 'string
2936 :group 'python)
2938 (define-obsolete-variable-alias
2939 'python-shell-completion-module-string-code
2940 'python-shell-completion-string-code
2941 "24.4"
2942 "Completion string code must also autocomplete modules.")
2944 (define-obsolete-variable-alias
2945 'python-shell-completion-pdb-string-code
2946 'python-shell-completion-string-code
2947 "25.1"
2948 "Completion string code must work for (i)pdb.")
2950 (defun python-shell-completion-get-completions (process import input)
2951 "Do completion at point using PROCESS for IMPORT or INPUT.
2952 When IMPORT is non-nil takes precedence over INPUT for
2953 completion."
2954 (with-current-buffer (process-buffer process)
2955 (let* ((prompt
2956 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2957 (buffer-substring-no-properties
2958 (car prompt-boundaries) (cdr prompt-boundaries))))
2959 (completion-code
2960 ;; Check whether a prompt matches a pdb string, an import
2961 ;; statement or just the standard prompt and use the
2962 ;; correct python-shell-completion-*-code string
2963 (cond ((and (string-match
2964 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2965 ;; Since there are no guarantees the user will remain
2966 ;; in the same context where completion code was sent
2967 ;; (e.g. user steps into a function), safeguard
2968 ;; resending completion setup continuously.
2969 (concat python-shell-completion-setup-code
2970 "\nprint (" python-shell-completion-string-code ")"))
2971 ((string-match
2972 python-shell--prompt-calculated-input-regexp prompt)
2973 python-shell-completion-string-code)
2974 (t nil)))
2975 (subject (or import input)))
2976 (and completion-code
2977 (> (length input) 0)
2978 (let ((completions
2979 (python-util-strip-string
2980 (python-shell-send-string-no-output
2981 (format completion-code subject) process))))
2982 (and (> (length completions) 2)
2983 (split-string completions
2984 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2986 (defun python-shell-completion-at-point (&optional process)
2987 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2988 Optional argument PROCESS forces completions to be retrieved
2989 using that one instead of current buffer's process."
2990 (setq process (or process (get-buffer-process (current-buffer))))
2991 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2992 (import-statement
2993 (when (string-match-p
2994 (rx (* space) word-start (or "from" "import") word-end space)
2995 (buffer-substring-no-properties last-prompt-end (point)))
2996 (buffer-substring-no-properties last-prompt-end (point))))
2997 (start
2998 (save-excursion
2999 (if (not (re-search-backward
3000 (python-rx
3001 (or whitespace open-paren close-paren string-delimiter))
3002 last-prompt-end
3003 t 1))
3004 last-prompt-end
3005 (forward-char (length (match-string-no-properties 0)))
3006 (point))))
3007 (end (point)))
3008 (list start end
3009 (completion-table-dynamic
3010 (apply-partially
3011 #'python-shell-completion-get-completions
3012 process import-statement)))))
3014 (define-obsolete-function-alias
3015 'python-shell-completion-complete-at-point
3016 'python-shell-completion-at-point
3017 "25.1")
3019 (defun python-shell-completion-complete-or-indent ()
3020 "Complete or indent depending on the context.
3021 If content before pointer is all whitespace, indent.
3022 If not try to complete."
3023 (interactive)
3024 (if (string-match "^[[:space:]]*$"
3025 (buffer-substring (comint-line-beginning-position)
3026 (point)))
3027 (indent-for-tab-command)
3028 (completion-at-point)))
3031 ;;; PDB Track integration
3033 (defcustom python-pdbtrack-activate t
3034 "Non-nil makes Python shell enable pdbtracking."
3035 :type 'boolean
3036 :group 'python
3037 :safe 'booleanp)
3039 (defcustom python-pdbtrack-stacktrace-info-regexp
3040 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3041 "Regular expression matching stacktrace information.
3042 Used to extract the current line and module being inspected."
3043 :type 'string
3044 :group 'python
3045 :safe 'stringp)
3047 (defvar python-pdbtrack-tracked-buffer nil
3048 "Variable containing the value of the current tracked buffer.
3049 Never set this variable directly, use
3050 `python-pdbtrack-set-tracked-buffer' instead.")
3052 (defvar python-pdbtrack-buffers-to-kill nil
3053 "List of buffers to be deleted after tracking finishes.")
3055 (defun python-pdbtrack-set-tracked-buffer (file-name)
3056 "Set the buffer for FILE-NAME as the tracked buffer.
3057 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3058 Returns the tracked buffer."
3059 (let ((file-buffer (get-file-buffer
3060 (concat (file-remote-p default-directory)
3061 file-name))))
3062 (if file-buffer
3063 (setq python-pdbtrack-tracked-buffer file-buffer)
3064 (setq file-buffer (find-file-noselect file-name))
3065 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3066 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3067 file-buffer))
3069 (defun python-pdbtrack-comint-output-filter-function (output)
3070 "Move overlay arrow to current pdb line in tracked buffer.
3071 Argument OUTPUT is a string with the output from the comint process."
3072 (when (and python-pdbtrack-activate (not (string= output "")))
3073 (let* ((full-output (ansi-color-filter-apply
3074 (buffer-substring comint-last-input-end (point-max))))
3075 (line-number)
3076 (file-name
3077 (with-temp-buffer
3078 (insert full-output)
3079 ;; When the debugger encounters a pdb.set_trace()
3080 ;; command, it prints a single stack frame. Sometimes
3081 ;; it prints a bit of extra information about the
3082 ;; arguments of the present function. When ipdb
3083 ;; encounters an exception, it prints the _entire_ stack
3084 ;; trace. To handle all of these cases, we want to find
3085 ;; the _last_ stack frame printed in the most recent
3086 ;; batch of output, then jump to the corresponding
3087 ;; file/line number.
3088 (goto-char (point-max))
3089 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3090 (setq line-number (string-to-number
3091 (match-string-no-properties 2)))
3092 (match-string-no-properties 1)))))
3093 (if (and file-name line-number)
3094 (let* ((tracked-buffer
3095 (python-pdbtrack-set-tracked-buffer file-name))
3096 (shell-buffer (current-buffer))
3097 (tracked-buffer-window (get-buffer-window tracked-buffer))
3098 (tracked-buffer-line-pos))
3099 (with-current-buffer tracked-buffer
3100 (set (make-local-variable 'overlay-arrow-string) "=>")
3101 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3102 (setq tracked-buffer-line-pos (progn
3103 (goto-char (point-min))
3104 (forward-line (1- line-number))
3105 (point-marker)))
3106 (when tracked-buffer-window
3107 (set-window-point
3108 tracked-buffer-window tracked-buffer-line-pos))
3109 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3110 (pop-to-buffer tracked-buffer)
3111 (switch-to-buffer-other-window shell-buffer))
3112 (when python-pdbtrack-tracked-buffer
3113 (with-current-buffer python-pdbtrack-tracked-buffer
3114 (set-marker overlay-arrow-position nil))
3115 (mapc #'(lambda (buffer)
3116 (ignore-errors (kill-buffer buffer)))
3117 python-pdbtrack-buffers-to-kill)
3118 (setq python-pdbtrack-tracked-buffer nil
3119 python-pdbtrack-buffers-to-kill nil)))))
3120 output)
3123 ;;; Symbol completion
3125 (defun python-completion-at-point ()
3126 "Function for `completion-at-point-functions' in `python-mode'.
3127 For this to work as best as possible you should call
3128 `python-shell-send-buffer' from time to time so context in
3129 inferior Python process is updated properly."
3130 (let ((process (python-shell-get-process)))
3131 (when process
3132 (python-shell-completion-at-point process))))
3134 (define-obsolete-function-alias
3135 'python-completion-complete-at-point
3136 'python-completion-at-point
3137 "25.1")
3140 ;;; Fill paragraph
3142 (defcustom python-fill-comment-function 'python-fill-comment
3143 "Function to fill comments.
3144 This is the function used by `python-fill-paragraph' to
3145 fill comments."
3146 :type 'symbol
3147 :group 'python)
3149 (defcustom python-fill-string-function 'python-fill-string
3150 "Function to fill strings.
3151 This is the function used by `python-fill-paragraph' to
3152 fill strings."
3153 :type 'symbol
3154 :group 'python)
3156 (defcustom python-fill-decorator-function 'python-fill-decorator
3157 "Function to fill decorators.
3158 This is the function used by `python-fill-paragraph' to
3159 fill decorators."
3160 :type 'symbol
3161 :group 'python)
3163 (defcustom python-fill-paren-function 'python-fill-paren
3164 "Function to fill parens.
3165 This is the function used by `python-fill-paragraph' to
3166 fill parens."
3167 :type 'symbol
3168 :group 'python)
3170 (defcustom python-fill-docstring-style 'pep-257
3171 "Style used to fill docstrings.
3172 This affects `python-fill-string' behavior with regards to
3173 triple quotes positioning.
3175 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3176 `symmetric', and nil. A value of nil won't care about quotes
3177 position and will treat docstrings a normal string, any other
3178 value may result in one of the following docstring styles:
3180 `django':
3182 \"\"\"
3183 Process foo, return bar.
3184 \"\"\"
3186 \"\"\"
3187 Process foo, return bar.
3189 If processing fails throw ProcessingError.
3190 \"\"\"
3192 `onetwo':
3194 \"\"\"Process foo, return bar.\"\"\"
3196 \"\"\"
3197 Process foo, return bar.
3199 If processing fails throw ProcessingError.
3201 \"\"\"
3203 `pep-257':
3205 \"\"\"Process foo, return bar.\"\"\"
3207 \"\"\"Process foo, return bar.
3209 If processing fails throw ProcessingError.
3211 \"\"\"
3213 `pep-257-nn':
3215 \"\"\"Process foo, return bar.\"\"\"
3217 \"\"\"Process foo, return bar.
3219 If processing fails throw ProcessingError.
3220 \"\"\"
3222 `symmetric':
3224 \"\"\"Process foo, return bar.\"\"\"
3226 \"\"\"
3227 Process foo, return bar.
3229 If processing fails throw ProcessingError.
3230 \"\"\""
3231 :type '(choice
3232 (const :tag "Don't format docstrings" nil)
3233 (const :tag "Django's coding standards style." django)
3234 (const :tag "One newline and start and Two at end style." onetwo)
3235 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3236 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3237 (const :tag "Symmetric style." symmetric))
3238 :group 'python
3239 :safe (lambda (val)
3240 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3242 (defun python-fill-paragraph (&optional justify)
3243 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3244 If any of the current line is in or at the end of a multi-line string,
3245 fill the string or the paragraph of it that point is in, preserving
3246 the string's indentation.
3247 Optional argument JUSTIFY defines if the paragraph should be justified."
3248 (interactive "P")
3249 (save-excursion
3250 (cond
3251 ;; Comments
3252 ((python-syntax-context 'comment)
3253 (funcall python-fill-comment-function justify))
3254 ;; Strings/Docstrings
3255 ((save-excursion (or (python-syntax-context 'string)
3256 (equal (string-to-syntax "|")
3257 (syntax-after (point)))))
3258 (funcall python-fill-string-function justify))
3259 ;; Decorators
3260 ((equal (char-after (save-excursion
3261 (python-nav-beginning-of-statement))) ?@)
3262 (funcall python-fill-decorator-function justify))
3263 ;; Parens
3264 ((or (python-syntax-context 'paren)
3265 (looking-at (python-rx open-paren))
3266 (save-excursion
3267 (skip-syntax-forward "^(" (line-end-position))
3268 (looking-at (python-rx open-paren))))
3269 (funcall python-fill-paren-function justify))
3270 (t t))))
3272 (defun python-fill-comment (&optional justify)
3273 "Comment fill function for `python-fill-paragraph'.
3274 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3275 (fill-comment-paragraph justify))
3277 (defun python-fill-string (&optional justify)
3278 "String fill function for `python-fill-paragraph'.
3279 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3280 (let* ((str-start-pos
3281 (set-marker
3282 (make-marker)
3283 (or (python-syntax-context 'string)
3284 (and (equal (string-to-syntax "|")
3285 (syntax-after (point)))
3286 (point)))))
3287 (num-quotes (python-syntax-count-quotes
3288 (char-after str-start-pos) str-start-pos))
3289 (str-end-pos
3290 (save-excursion
3291 (goto-char (+ str-start-pos num-quotes))
3292 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3293 (goto-char (point-max)))
3294 (point-marker)))
3295 (multi-line-p
3296 ;; Docstring styles may vary for oneliners and multi-liners.
3297 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3298 (delimiters-style
3299 (pcase python-fill-docstring-style
3300 ;; delimiters-style is a cons cell with the form
3301 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3302 ;; is NIL means to not add any newlines for start or end
3303 ;; of docstring. See `python-fill-docstring-style' for a
3304 ;; graphic idea of each style.
3305 (`django (cons 1 1))
3306 (`onetwo (and multi-line-p (cons 1 2)))
3307 (`pep-257 (and multi-line-p (cons nil 2)))
3308 (`pep-257-nn (and multi-line-p (cons nil 1)))
3309 (`symmetric (and multi-line-p (cons 1 1)))))
3310 (docstring-p (save-excursion
3311 ;; Consider docstrings those strings which
3312 ;; start on a line by themselves.
3313 (python-nav-beginning-of-statement)
3314 (and (= (point) str-start-pos))))
3315 (fill-paragraph-function))
3316 (save-restriction
3317 (narrow-to-region str-start-pos str-end-pos)
3318 (fill-paragraph justify))
3319 (save-excursion
3320 (when (and docstring-p python-fill-docstring-style)
3321 ;; Add the number of newlines indicated by the selected style
3322 ;; at the start of the docstring.
3323 (goto-char (+ str-start-pos num-quotes))
3324 (delete-region (point) (progn
3325 (skip-syntax-forward "> ")
3326 (point)))
3327 (and (car delimiters-style)
3328 (or (newline (car delimiters-style)) t)
3329 ;; Indent only if a newline is added.
3330 (indent-according-to-mode))
3331 ;; Add the number of newlines indicated by the selected style
3332 ;; at the end of the docstring.
3333 (goto-char (if (not (= str-end-pos (point-max)))
3334 (- str-end-pos num-quotes)
3335 str-end-pos))
3336 (delete-region (point) (progn
3337 (skip-syntax-backward "> ")
3338 (point)))
3339 (and (cdr delimiters-style)
3340 ;; Add newlines only if string ends.
3341 (not (= str-end-pos (point-max)))
3342 (or (newline (cdr delimiters-style)) t)
3343 ;; Again indent only if a newline is added.
3344 (indent-according-to-mode))))) t)
3346 (defun python-fill-decorator (&optional _justify)
3347 "Decorator fill function for `python-fill-paragraph'.
3348 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3351 (defun python-fill-paren (&optional justify)
3352 "Paren fill function for `python-fill-paragraph'.
3353 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3354 (save-restriction
3355 (narrow-to-region (progn
3356 (while (python-syntax-context 'paren)
3357 (goto-char (1- (point))))
3358 (line-beginning-position))
3359 (progn
3360 (when (not (python-syntax-context 'paren))
3361 (end-of-line)
3362 (when (not (python-syntax-context 'paren))
3363 (skip-syntax-backward "^)")))
3364 (while (and (python-syntax-context 'paren)
3365 (not (eobp)))
3366 (goto-char (1+ (point))))
3367 (point)))
3368 (let ((paragraph-start "\f\\|[ \t]*$")
3369 (paragraph-separate ",")
3370 (fill-paragraph-function))
3371 (goto-char (point-min))
3372 (fill-paragraph justify))
3373 (while (not (eobp))
3374 (forward-line 1)
3375 (python-indent-line)
3376 (goto-char (line-end-position))))
3380 ;;; Skeletons
3382 (defcustom python-skeleton-autoinsert nil
3383 "Non-nil means template skeletons will be automagically inserted.
3384 This happens when pressing \"if<SPACE>\", for example, to prompt for
3385 the if condition."
3386 :type 'boolean
3387 :group 'python
3388 :safe 'booleanp)
3390 (define-obsolete-variable-alias
3391 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3393 (defvar python-skeleton-available '()
3394 "Internal list of available skeletons.")
3396 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3397 "Abbrev table for Python mode skeletons."
3398 :case-fixed t
3399 ;; Allow / inside abbrevs.
3400 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3401 ;; Only expand in code.
3402 :enable-function (lambda ()
3403 (and
3404 (not (python-syntax-comment-or-string-p))
3405 python-skeleton-autoinsert)))
3407 (defmacro python-skeleton-define (name doc &rest skel)
3408 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3409 The skeleton will be bound to python-skeleton-NAME and will
3410 be added to `python-mode-skeleton-abbrev-table'."
3411 (declare (indent 2))
3412 (let* ((name (symbol-name name))
3413 (function-name (intern (concat "python-skeleton-" name))))
3414 `(progn
3415 (define-abbrev python-mode-skeleton-abbrev-table
3416 ,name "" ',function-name :system t)
3417 (setq python-skeleton-available
3418 (cons ',function-name python-skeleton-available))
3419 (define-skeleton ,function-name
3420 ,(or doc
3421 (format "Insert %s statement." name))
3422 ,@skel))))
3424 (define-abbrev-table 'python-mode-abbrev-table ()
3425 "Abbrev table for Python mode."
3426 :parents (list python-mode-skeleton-abbrev-table))
3428 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3429 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3430 The skeleton will be bound to python-skeleton-NAME."
3431 (declare (indent 2))
3432 (let* ((name (symbol-name name))
3433 (function-name (intern (concat "python-skeleton--" name)))
3434 (msg (format
3435 "Add '%s' clause? " name)))
3436 (when (not skel)
3437 (setq skel
3438 `(< ,(format "%s:" name) \n \n
3439 > _ \n)))
3440 `(define-skeleton ,function-name
3441 ,(or doc
3442 (format "Auxiliary skeleton for %s statement." name))
3444 (unless (y-or-n-p ,msg)
3445 (signal 'quit t))
3446 ,@skel)))
3448 (python-define-auxiliary-skeleton else nil)
3450 (python-define-auxiliary-skeleton except nil)
3452 (python-define-auxiliary-skeleton finally nil)
3454 (python-skeleton-define if nil
3455 "Condition: "
3456 "if " str ":" \n
3457 _ \n
3458 ("other condition, %s: "
3460 "elif " str ":" \n
3461 > _ \n nil)
3462 '(python-skeleton--else) | ^)
3464 (python-skeleton-define while nil
3465 "Condition: "
3466 "while " str ":" \n
3467 > _ \n
3468 '(python-skeleton--else) | ^)
3470 (python-skeleton-define for nil
3471 "Iteration spec: "
3472 "for " str ":" \n
3473 > _ \n
3474 '(python-skeleton--else) | ^)
3476 (python-skeleton-define import nil
3477 "Import from module: "
3478 "from " str & " " | -5
3479 "import "
3480 ("Identifier: " str ", ") -2 \n _)
3482 (python-skeleton-define try nil
3484 "try:" \n
3485 > _ \n
3486 ("Exception, %s: "
3488 "except " str ":" \n
3489 > _ \n nil)
3490 resume:
3491 '(python-skeleton--except)
3492 '(python-skeleton--else)
3493 '(python-skeleton--finally) | ^)
3495 (python-skeleton-define def nil
3496 "Function name: "
3497 "def " str "(" ("Parameter, %s: "
3498 (unless (equal ?\( (char-before)) ", ")
3499 str) "):" \n
3500 "\"\"\"" - "\"\"\"" \n
3501 > _ \n)
3503 (python-skeleton-define class nil
3504 "Class name: "
3505 "class " str "(" ("Inheritance, %s: "
3506 (unless (equal ?\( (char-before)) ", ")
3507 str)
3508 & ")" | -1
3509 ":" \n
3510 "\"\"\"" - "\"\"\"" \n
3511 > _ \n)
3513 (defun python-skeleton-add-menu-items ()
3514 "Add menu items to Python->Skeletons menu."
3515 (let ((skeletons (sort python-skeleton-available 'string<)))
3516 (dolist (skeleton skeletons)
3517 (easy-menu-add-item
3518 nil '("Python" "Skeletons")
3519 `[,(format
3520 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3521 ,skeleton t]))))
3523 ;;; FFAP
3525 (defcustom python-ffap-setup-code
3526 "def __FFAP_get_module_path(module):
3527 try:
3528 import os
3529 path = __import__(module).__file__
3530 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3531 path = path[:-1]
3532 return path
3533 except:
3534 return ''"
3535 "Python code to get a module path."
3536 :type 'string
3537 :group 'python)
3539 (defcustom python-ffap-string-code
3540 "__FFAP_get_module_path('''%s''')\n"
3541 "Python code used to get a string with the path of a module."
3542 :type 'string
3543 :group 'python)
3545 (defun python-ffap-module-path (module)
3546 "Function for `ffap-alist' to return path for MODULE."
3547 (let ((process (or
3548 (and (derived-mode-p 'inferior-python-mode)
3549 (get-buffer-process (current-buffer)))
3550 (python-shell-get-process))))
3551 (if (not process)
3553 (let ((module-file
3554 (python-shell-send-string-no-output
3555 (format python-ffap-string-code module) process)))
3556 (when module-file
3557 (substring-no-properties module-file 1 -1))))))
3559 (defvar ffap-alist)
3561 (eval-after-load "ffap"
3562 '(progn
3563 (push '(python-mode . python-ffap-module-path) ffap-alist)
3564 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3567 ;;; Code check
3569 (defcustom python-check-command
3570 "pyflakes"
3571 "Command used to check a Python file."
3572 :type 'string
3573 :group 'python)
3575 (defcustom python-check-buffer-name
3576 "*Python check: %s*"
3577 "Buffer name used for check commands."
3578 :type 'string
3579 :group 'python)
3581 (defvar python-check-custom-command nil
3582 "Internal use.")
3584 (defun python-check (command)
3585 "Check a Python file (default current buffer's file).
3586 Runs COMMAND, a shell command, as if by `compile'.
3587 See `python-check-command' for the default."
3588 (interactive
3589 (list (read-string "Check command: "
3590 (or python-check-custom-command
3591 (concat python-check-command " "
3592 (shell-quote-argument
3594 (let ((name (buffer-file-name)))
3595 (and name
3596 (file-name-nondirectory name)))
3597 "")))))))
3598 (setq python-check-custom-command command)
3599 (save-some-buffers (not compilation-ask-about-save) nil)
3600 (let ((process-environment (python-shell-calculate-process-environment))
3601 (exec-path (python-shell-calculate-exec-path)))
3602 (compilation-start command nil
3603 (lambda (_modename)
3604 (format python-check-buffer-name command)))))
3607 ;;; Eldoc
3609 (defcustom python-eldoc-setup-code
3610 "def __PYDOC_get_help(obj):
3611 try:
3612 import inspect
3613 try:
3614 str_type = basestring
3615 except NameError:
3616 str_type = str
3617 if isinstance(obj, str_type):
3618 obj = eval(obj, globals())
3619 doc = inspect.getdoc(obj)
3620 if not doc and callable(obj):
3621 target = None
3622 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3623 target = obj.__init__
3624 objtype = 'class'
3625 else:
3626 target = obj
3627 objtype = 'def'
3628 if target:
3629 args = inspect.formatargspec(
3630 *inspect.getargspec(target)
3632 name = obj.__name__
3633 doc = '{objtype} {name}{args}'.format(
3634 objtype=objtype, name=name, args=args
3636 else:
3637 doc = doc.splitlines()[0]
3638 except:
3639 doc = ''
3640 print (doc)"
3641 "Python code to setup documentation retrieval."
3642 :type 'string
3643 :group 'python)
3645 (defcustom python-eldoc-string-code
3646 "__PYDOC_get_help('''%s''')\n"
3647 "Python code used to get a string with the documentation of an object."
3648 :type 'string
3649 :group 'python)
3651 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3652 "Internal implementation to get documentation at point.
3653 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3654 returns will be used. If not FORCE-PROCESS is passed what
3655 `python-shell-get-process' returns is used."
3656 (let ((process (or force-process (python-shell-get-process))))
3657 (when process
3658 (let ((input (or force-input
3659 (python-info-current-symbol t))))
3660 (and input
3661 ;; Prevent resizing the echo area when iPython is
3662 ;; enabled. Bug#18794.
3663 (python-util-strip-string
3664 (python-shell-send-string-no-output
3665 (format python-eldoc-string-code input)
3666 process)))))))
3668 (defun python-eldoc-function ()
3669 "`eldoc-documentation-function' for Python.
3670 For this to work as best as possible you should call
3671 `python-shell-send-buffer' from time to time so context in
3672 inferior Python process is updated properly."
3673 (python-eldoc--get-doc-at-point))
3675 (defun python-eldoc-at-point (symbol)
3676 "Get help on SYMBOL using `help'.
3677 Interactively, prompt for symbol."
3678 (interactive
3679 (let ((symbol (python-info-current-symbol t))
3680 (enable-recursive-minibuffers t))
3681 (list (read-string (if symbol
3682 (format "Describe symbol (default %s): " symbol)
3683 "Describe symbol: ")
3684 nil nil symbol))))
3685 (message (python-eldoc--get-doc-at-point symbol)))
3688 ;;; Imenu
3690 (defvar python-imenu-format-item-label-function
3691 'python-imenu-format-item-label
3692 "Imenu function used to format an item label.
3693 It must be a function with two arguments: TYPE and NAME.")
3695 (defvar python-imenu-format-parent-item-label-function
3696 'python-imenu-format-parent-item-label
3697 "Imenu function used to format a parent item label.
3698 It must be a function with two arguments: TYPE and NAME.")
3700 (defvar python-imenu-format-parent-item-jump-label-function
3701 'python-imenu-format-parent-item-jump-label
3702 "Imenu function used to format a parent jump item label.
3703 It must be a function with two arguments: TYPE and NAME.")
3705 (defun python-imenu-format-item-label (type name)
3706 "Return Imenu label for single node using TYPE and NAME."
3707 (format "%s (%s)" name type))
3709 (defun python-imenu-format-parent-item-label (type name)
3710 "Return Imenu label for parent node using TYPE and NAME."
3711 (format "%s..." (python-imenu-format-item-label type name)))
3713 (defun python-imenu-format-parent-item-jump-label (type _name)
3714 "Return Imenu label for parent node jump using TYPE and NAME."
3715 (if (string= type "class")
3716 "*class definition*"
3717 "*function definition*"))
3719 (defun python-imenu--put-parent (type name pos tree)
3720 "Add the parent with TYPE, NAME and POS to TREE."
3721 (let ((label
3722 (funcall python-imenu-format-item-label-function type name))
3723 (jump-label
3724 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3725 (if (not tree)
3726 (cons label pos)
3727 (cons label (cons (cons jump-label pos) tree)))))
3729 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3730 "Recursively build the tree of nested definitions of a node.
3731 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3732 not be passed explicitly unless you know what you are doing."
3733 (setq min-indent (or min-indent 0)
3734 prev-indent (or prev-indent python-indent-offset))
3735 (let* ((pos (python-nav-backward-defun))
3736 (type)
3737 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3738 (let ((split (split-string (match-string-no-properties 0))))
3739 (setq type (car split))
3740 (cadr split))))
3741 (label (when name
3742 (funcall python-imenu-format-item-label-function type name)))
3743 (indent (current-indentation))
3744 (children-indent-limit (+ python-indent-offset min-indent)))
3745 (cond ((not pos)
3746 ;; Nothing found, probably near to bobp.
3747 nil)
3748 ((<= indent min-indent)
3749 ;; The current indentation points that this is a parent
3750 ;; node, add it to the tree and stop recursing.
3751 (python-imenu--put-parent type name pos tree))
3753 (python-imenu--build-tree
3754 min-indent
3755 indent
3756 (if (<= indent children-indent-limit)
3757 ;; This lies within the children indent offset range,
3758 ;; so it's a normal child of its parent (i.e., not
3759 ;; a child of a child).
3760 (cons (cons label pos) tree)
3761 ;; Oh no, a child of a child?! Fear not, we
3762 ;; know how to roll. We recursively parse these by
3763 ;; swapping prev-indent and min-indent plus adding this
3764 ;; newly found item to a fresh subtree. This works, I
3765 ;; promise.
3766 (cons
3767 (python-imenu--build-tree
3768 prev-indent indent (list (cons label pos)))
3769 tree)))))))
3771 (defun python-imenu-create-index ()
3772 "Return tree Imenu alist for the current Python buffer.
3773 Change `python-imenu-format-item-label-function',
3774 `python-imenu-format-parent-item-label-function',
3775 `python-imenu-format-parent-item-jump-label-function' to
3776 customize how labels are formatted."
3777 (goto-char (point-max))
3778 (let ((index)
3779 (tree))
3780 (while (setq tree (python-imenu--build-tree))
3781 (setq index (cons tree index)))
3782 index))
3784 (defun python-imenu-create-flat-index (&optional alist prefix)
3785 "Return flat outline of the current Python buffer for Imenu.
3786 Optional argument ALIST is the tree to be flattened; when nil
3787 `python-imenu-build-index' is used with
3788 `python-imenu-format-parent-item-jump-label-function'
3789 `python-imenu-format-parent-item-label-function'
3790 `python-imenu-format-item-label-function' set to
3791 (lambda (type name) name)
3792 Optional argument PREFIX is used in recursive calls and should
3793 not be passed explicitly.
3795 Converts this:
3797 ((\"Foo\" . 103)
3798 (\"Bar\" . 138)
3799 (\"decorator\"
3800 (\"decorator\" . 173)
3801 (\"wrap\"
3802 (\"wrap\" . 353)
3803 (\"wrapped_f\" . 393))))
3805 To this:
3807 ((\"Foo\" . 103)
3808 (\"Bar\" . 138)
3809 (\"decorator\" . 173)
3810 (\"decorator.wrap\" . 353)
3811 (\"decorator.wrapped_f\" . 393))"
3812 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3813 (apply
3814 'nconc
3815 (mapcar
3816 (lambda (item)
3817 (let ((name (if prefix
3818 (concat prefix "." (car item))
3819 (car item)))
3820 (pos (cdr item)))
3821 (cond ((or (numberp pos) (markerp pos))
3822 (list (cons name pos)))
3823 ((listp pos)
3824 (cons
3825 (cons name (cdar pos))
3826 (python-imenu-create-flat-index (cddr item) name))))))
3827 (or alist
3828 (let* ((fn (lambda (_type name) name))
3829 (python-imenu-format-item-label-function fn)
3830 (python-imenu-format-parent-item-label-function fn)
3831 (python-imenu-format-parent-item-jump-label-function fn))
3832 (python-imenu-create-index))))))
3835 ;;; Misc helpers
3837 (defun python-info-current-defun (&optional include-type)
3838 "Return name of surrounding function with Python compatible dotty syntax.
3839 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3840 This function can be used as the value of `add-log-current-defun-function'
3841 since it returns nil if point is not inside a defun."
3842 (save-restriction
3843 (widen)
3844 (save-excursion
3845 (end-of-line 1)
3846 (let ((names)
3847 (starting-indentation (current-indentation))
3848 (starting-pos (point))
3849 (first-run t)
3850 (last-indent)
3851 (type))
3852 (catch 'exit
3853 (while (python-nav-beginning-of-defun 1)
3854 (when (save-match-data
3855 (and
3856 (or (not last-indent)
3857 (< (current-indentation) last-indent))
3859 (and first-run
3860 (save-excursion
3861 ;; If this is the first run, we may add
3862 ;; the current defun at point.
3863 (setq first-run nil)
3864 (goto-char starting-pos)
3865 (python-nav-beginning-of-statement)
3866 (beginning-of-line 1)
3867 (looking-at-p
3868 python-nav-beginning-of-defun-regexp)))
3869 (< starting-pos
3870 (save-excursion
3871 (let ((min-indent
3872 (+ (current-indentation)
3873 python-indent-offset)))
3874 (if (< starting-indentation min-indent)
3875 ;; If the starting indentation is not
3876 ;; within the min defun indent make the
3877 ;; check fail.
3878 starting-pos
3879 ;; Else go to the end of defun and add
3880 ;; up the current indentation to the
3881 ;; ending position.
3882 (python-nav-end-of-defun)
3883 (+ (point)
3884 (if (>= (current-indentation) min-indent)
3885 (1+ (current-indentation))
3886 0)))))))))
3887 (save-match-data (setq last-indent (current-indentation)))
3888 (if (or (not include-type) type)
3889 (setq names (cons (match-string-no-properties 1) names))
3890 (let ((match (split-string (match-string-no-properties 0))))
3891 (setq type (car match))
3892 (setq names (cons (cadr match) names)))))
3893 ;; Stop searching ASAP.
3894 (and (= (current-indentation) 0) (throw 'exit t))))
3895 (and names
3896 (concat (and type (format "%s " type))
3897 (mapconcat 'identity names ".")))))))
3899 (defun python-info-current-symbol (&optional replace-self)
3900 "Return current symbol using dotty syntax.
3901 With optional argument REPLACE-SELF convert \"self\" to current
3902 parent defun name."
3903 (let ((name
3904 (and (not (python-syntax-comment-or-string-p))
3905 (with-syntax-table python-dotty-syntax-table
3906 (let ((sym (symbol-at-point)))
3907 (and sym
3908 (substring-no-properties (symbol-name sym))))))))
3909 (when name
3910 (if (not replace-self)
3911 name
3912 (let ((current-defun (python-info-current-defun)))
3913 (if (not current-defun)
3914 name
3915 (replace-regexp-in-string
3916 (python-rx line-start word-start "self" word-end ?.)
3917 (concat
3918 (mapconcat 'identity
3919 (butlast (split-string current-defun "\\."))
3920 ".") ".")
3921 name)))))))
3923 (defun python-info-statement-starts-block-p ()
3924 "Return non-nil if current statement opens a block."
3925 (save-excursion
3926 (python-nav-beginning-of-statement)
3927 (looking-at (python-rx block-start))))
3929 (defun python-info-statement-ends-block-p ()
3930 "Return non-nil if point is at end of block."
3931 (let ((end-of-block-pos (save-excursion
3932 (python-nav-end-of-block)))
3933 (end-of-statement-pos (save-excursion
3934 (python-nav-end-of-statement))))
3935 (and end-of-block-pos end-of-statement-pos
3936 (= end-of-block-pos end-of-statement-pos))))
3938 (defun python-info-beginning-of-statement-p ()
3939 "Return non-nil if point is at beginning of statement."
3940 (= (point) (save-excursion
3941 (python-nav-beginning-of-statement)
3942 (point))))
3944 (defun python-info-end-of-statement-p ()
3945 "Return non-nil if point is at end of statement."
3946 (= (point) (save-excursion
3947 (python-nav-end-of-statement)
3948 (point))))
3950 (defun python-info-beginning-of-block-p ()
3951 "Return non-nil if point is at beginning of block."
3952 (and (python-info-beginning-of-statement-p)
3953 (python-info-statement-starts-block-p)))
3955 (defun python-info-end-of-block-p ()
3956 "Return non-nil if point is at end of block."
3957 (and (python-info-end-of-statement-p)
3958 (python-info-statement-ends-block-p)))
3960 (define-obsolete-function-alias
3961 'python-info-closing-block
3962 'python-info-dedenter-opening-block-position "24.4")
3964 (defun python-info-dedenter-opening-block-position ()
3965 "Return the point of the closest block the current line closes.
3966 Returns nil if point is not on a dedenter statement or no opening
3967 block can be detected. The latter case meaning current file is
3968 likely an invalid python file."
3969 (let ((positions (python-info-dedenter-opening-block-positions))
3970 (indentation (current-indentation))
3971 (position))
3972 (while (and (not position)
3973 positions)
3974 (save-excursion
3975 (goto-char (car positions))
3976 (if (<= (current-indentation) indentation)
3977 (setq position (car positions))
3978 (setq positions (cdr positions)))))
3979 position))
3981 (defun python-info-dedenter-opening-block-positions ()
3982 "Return points of blocks the current line may close sorted by closer.
3983 Returns nil if point is not on a dedenter statement or no opening
3984 block can be detected. The latter case meaning current file is
3985 likely an invalid python file."
3986 (save-excursion
3987 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3988 (when dedenter-pos
3989 (goto-char dedenter-pos)
3990 (let* ((pairs '(("elif" "elif" "if")
3991 ("else" "if" "elif" "except" "for" "while")
3992 ("except" "except" "try")
3993 ("finally" "else" "except" "try")))
3994 (dedenter (match-string-no-properties 0))
3995 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
3996 (collected-indentations)
3997 (opening-blocks))
3998 (catch 'exit
3999 (while (python-nav--syntactically
4000 (lambda ()
4001 (re-search-backward (python-rx block-start) nil t))
4002 #'<)
4003 (let ((indentation (current-indentation)))
4004 (when (and (not (memq indentation collected-indentations))
4005 (or (not collected-indentations)
4006 (< indentation (apply #'min collected-indentations))))
4007 (setq collected-indentations
4008 (cons indentation collected-indentations))
4009 (when (member (match-string-no-properties 0)
4010 possible-opening-blocks)
4011 (setq opening-blocks (cons (point) opening-blocks))))
4012 (when (zerop indentation)
4013 (throw 'exit nil)))))
4014 ;; sort by closer
4015 (nreverse opening-blocks))))))
4017 (define-obsolete-function-alias
4018 'python-info-closing-block-message
4019 'python-info-dedenter-opening-block-message "24.4")
4021 (defun python-info-dedenter-opening-block-message ()
4022 "Message the first line of the block the current statement closes."
4023 (let ((point (python-info-dedenter-opening-block-position)))
4024 (when point
4025 (save-restriction
4026 (widen)
4027 (message "Closes %s" (save-excursion
4028 (goto-char point)
4029 (buffer-substring
4030 (point) (line-end-position))))))))
4032 (defun python-info-dedenter-statement-p ()
4033 "Return point if current statement is a dedenter.
4034 Sets `match-data' to the keyword that starts the dedenter
4035 statement."
4036 (save-excursion
4037 (python-nav-beginning-of-statement)
4038 (when (and (not (python-syntax-context-type))
4039 (looking-at (python-rx dedenter)))
4040 (point))))
4042 (defun python-info-line-ends-backslash-p (&optional line-number)
4043 "Return non-nil if current line ends with backslash.
4044 With optional argument LINE-NUMBER, check that line instead."
4045 (save-excursion
4046 (save-restriction
4047 (widen)
4048 (when line-number
4049 (python-util-goto-line line-number))
4050 (while (and (not (eobp))
4051 (goto-char (line-end-position))
4052 (python-syntax-context 'paren)
4053 (not (equal (char-before (point)) ?\\)))
4054 (forward-line 1))
4055 (when (equal (char-before) ?\\)
4056 (point-marker)))))
4058 (defun python-info-beginning-of-backslash (&optional line-number)
4059 "Return the point where the backslashed line start.
4060 Optional argument LINE-NUMBER forces the line number to check against."
4061 (save-excursion
4062 (save-restriction
4063 (widen)
4064 (when line-number
4065 (python-util-goto-line line-number))
4066 (when (python-info-line-ends-backslash-p)
4067 (while (save-excursion
4068 (goto-char (line-beginning-position))
4069 (python-syntax-context 'paren))
4070 (forward-line -1))
4071 (back-to-indentation)
4072 (point-marker)))))
4074 (defun python-info-continuation-line-p ()
4075 "Check if current line is continuation of another.
4076 When current line is continuation of another return the point
4077 where the continued line ends."
4078 (save-excursion
4079 (save-restriction
4080 (widen)
4081 (let* ((context-type (progn
4082 (back-to-indentation)
4083 (python-syntax-context-type)))
4084 (line-start (line-number-at-pos))
4085 (context-start (when context-type
4086 (python-syntax-context context-type))))
4087 (cond ((equal context-type 'paren)
4088 ;; Lines inside a paren are always a continuation line
4089 ;; (except the first one).
4090 (python-util-forward-comment -1)
4091 (point-marker))
4092 ((member context-type '(string comment))
4093 ;; move forward an roll again
4094 (goto-char context-start)
4095 (python-util-forward-comment)
4096 (python-info-continuation-line-p))
4098 ;; Not within a paren, string or comment, the only way
4099 ;; we are dealing with a continuation line is that
4100 ;; previous line contains a backslash, and this can
4101 ;; only be the previous line from current
4102 (back-to-indentation)
4103 (python-util-forward-comment -1)
4104 (when (and (equal (1- line-start) (line-number-at-pos))
4105 (python-info-line-ends-backslash-p))
4106 (point-marker))))))))
4108 (defun python-info-block-continuation-line-p ()
4109 "Return non-nil if current line is a continuation of a block."
4110 (save-excursion
4111 (when (python-info-continuation-line-p)
4112 (forward-line -1)
4113 (back-to-indentation)
4114 (when (looking-at (python-rx block-start))
4115 (point-marker)))))
4117 (defun python-info-assignment-continuation-line-p ()
4118 "Check if current line is a continuation of an assignment.
4119 When current line is continuation of another with an assignment
4120 return the point of the first non-blank character after the
4121 operator."
4122 (save-excursion
4123 (when (python-info-continuation-line-p)
4124 (forward-line -1)
4125 (back-to-indentation)
4126 (when (and (not (looking-at (python-rx block-start)))
4127 (and (re-search-forward (python-rx not-simple-operator
4128 assignment-operator
4129 not-simple-operator)
4130 (line-end-position) t)
4131 (not (python-syntax-context-type))))
4132 (skip-syntax-forward "\s")
4133 (point-marker)))))
4135 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4136 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4137 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4138 (save-excursion
4139 (beginning-of-line 1)
4140 (looking-at python-nav-beginning-of-defun-regexp))))
4142 (defun python-info-current-line-comment-p ()
4143 "Return non-nil if current line is a comment line."
4144 (char-equal
4145 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4146 ?#))
4148 (defun python-info-current-line-empty-p ()
4149 "Return non-nil if current line is empty, ignoring whitespace."
4150 (save-excursion
4151 (beginning-of-line 1)
4152 (looking-at
4153 (python-rx line-start (* whitespace)
4154 (group (* not-newline))
4155 (* whitespace) line-end))
4156 (string-equal "" (match-string-no-properties 1))))
4159 ;;; Utility functions
4161 (defun python-util-goto-line (line-number)
4162 "Move point to LINE-NUMBER."
4163 (goto-char (point-min))
4164 (forward-line (1- line-number)))
4166 ;; Stolen from org-mode
4167 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4168 "Clone local variables from FROM-BUFFER.
4169 Optional argument REGEXP selects variables to clone and defaults
4170 to \"^python-\"."
4171 (mapc
4172 (lambda (pair)
4173 (and (symbolp (car pair))
4174 (string-match (or regexp "^python-")
4175 (symbol-name (car pair)))
4176 (set (make-local-variable (car pair))
4177 (cdr pair))))
4178 (buffer-local-variables from-buffer)))
4180 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4182 (defun python-util-comint-last-prompt ()
4183 "Return comint last prompt overlay start and end.
4184 This is for compatibility with Emacs < 24.4."
4185 (cond ((bound-and-true-p comint-last-prompt-overlay)
4186 (cons (overlay-start comint-last-prompt-overlay)
4187 (overlay-end comint-last-prompt-overlay)))
4188 ((bound-and-true-p comint-last-prompt)
4189 comint-last-prompt)
4190 (t nil)))
4192 (defun python-util-forward-comment (&optional direction)
4193 "Python mode specific version of `forward-comment'.
4194 Optional argument DIRECTION defines the direction to move to."
4195 (let ((comment-start (python-syntax-context 'comment))
4196 (factor (if (< (or direction 0) 0)
4197 -99999
4198 99999)))
4199 (when comment-start
4200 (goto-char comment-start))
4201 (forward-comment factor)))
4203 (defun python-util-list-directories (directory &optional predicate max-depth)
4204 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4205 Argument PREDICATE defaults to `identity' and must be a function
4206 that takes one argument (a full path) and returns non-nil for
4207 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4208 searching when depth is reached, else don't limit."
4209 (let* ((dir (expand-file-name directory))
4210 (dir-length (length dir))
4211 (predicate (or predicate #'identity))
4212 (to-scan (list dir))
4213 (tally nil))
4214 (while to-scan
4215 (let ((current-dir (car to-scan)))
4216 (when (funcall predicate current-dir)
4217 (setq tally (cons current-dir tally)))
4218 (setq to-scan (append (cdr to-scan)
4219 (python-util-list-files
4220 current-dir #'file-directory-p)
4221 nil))
4222 (when (and max-depth
4223 (<= max-depth
4224 (length (split-string
4225 (substring current-dir dir-length)
4226 "/\\|\\\\" t))))
4227 (setq to-scan nil))))
4228 (nreverse tally)))
4230 (defun python-util-list-files (dir &optional predicate)
4231 "List files in DIR, filtering with PREDICATE.
4232 Argument PREDICATE defaults to `identity' and must be a function
4233 that takes one argument (a full path) and returns non-nil for
4234 allowed files."
4235 (let ((dir-name (file-name-as-directory dir)))
4236 (apply #'nconc
4237 (mapcar (lambda (file-name)
4238 (let ((full-file-name (expand-file-name file-name dir-name)))
4239 (when (and
4240 (not (member file-name '("." "..")))
4241 (funcall (or predicate #'identity) full-file-name))
4242 (list full-file-name))))
4243 (directory-files dir-name)))))
4245 (defun python-util-list-packages (dir &optional max-depth)
4246 "List packages in DIR, limited by MAX-DEPTH.
4247 When optional argument MAX-DEPTH is non-nil, stop searching when
4248 depth is reached, else don't limit."
4249 (let* ((dir (expand-file-name dir))
4250 (parent-dir (file-name-directory
4251 (directory-file-name
4252 (file-name-directory
4253 (file-name-as-directory dir)))))
4254 (subpath-length (length parent-dir)))
4255 (mapcar
4256 (lambda (file-name)
4257 (replace-regexp-in-string
4258 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4259 (python-util-list-directories
4260 (directory-file-name dir)
4261 (lambda (dir)
4262 (file-exists-p (expand-file-name "__init__.py" dir)))
4263 max-depth))))
4265 (defun python-util-popn (lst n)
4266 "Return LST first N elements.
4267 N should be an integer, when negative its opposite is used.
4268 When N is bigger than the length of LST, the list is
4269 returned as is."
4270 (let* ((n (min (abs n)))
4271 (len (length lst))
4272 (acc))
4273 (if (> n len)
4275 (while (< 0 n)
4276 (setq acc (cons (car lst) acc)
4277 lst (cdr lst)
4278 n (1- n)))
4279 (reverse acc))))
4281 (defun python-util-text-properties-replace-name
4282 (from to &optional start end)
4283 "Replace properties named FROM to TO, keeping its value.
4284 Arguments START and END narrow the buffer region to work on."
4285 (save-excursion
4286 (goto-char (or start (point-min)))
4287 (while (not (eobp))
4288 (let ((plist (text-properties-at (point)))
4289 (next-change (or (next-property-change (point) (current-buffer))
4290 (or end (point-max)))))
4291 (when (plist-get plist from)
4292 (let* ((face (plist-get plist from))
4293 (plist (plist-put plist from nil))
4294 (plist (plist-put plist to face)))
4295 (set-text-properties (point) next-change plist (current-buffer))))
4296 (goto-char next-change)))))
4298 (defun python-util-strip-string (string)
4299 "Strip STRING whitespace and newlines from end and beginning."
4300 (replace-regexp-in-string
4301 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4302 (: (* (any whitespace ?\r ?\n)) string-end)))
4304 string))
4306 (defun python-util-valid-regexp-p (regexp)
4307 "Return non-nil if REGEXP is valid."
4308 (ignore-errors (string-match regexp "") t))
4311 (defun python-electric-pair-string-delimiter ()
4312 (when (and electric-pair-mode
4313 (memq last-command-event '(?\" ?\'))
4314 (let ((count 0))
4315 (while (eq (char-before (- (point) count)) last-command-event)
4316 (cl-incf count))
4317 (= count 3))
4318 (eq (char-after) last-command-event))
4319 (save-excursion (insert (make-string 2 last-command-event)))))
4321 (defvar electric-indent-inhibit)
4323 ;;;###autoload
4324 (define-derived-mode python-mode prog-mode "Python"
4325 "Major mode for editing Python files.
4327 \\{python-mode-map}"
4328 (set (make-local-variable 'tab-width) 8)
4329 (set (make-local-variable 'indent-tabs-mode) nil)
4331 (set (make-local-variable 'comment-start) "# ")
4332 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4334 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4335 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4337 (set (make-local-variable 'forward-sexp-function)
4338 'python-nav-forward-sexp)
4340 (set (make-local-variable 'font-lock-defaults)
4341 '(python-font-lock-keywords
4342 nil nil nil nil
4343 (font-lock-syntactic-face-function
4344 . python-font-lock-syntactic-face-function)))
4346 (set (make-local-variable 'syntax-propertize-function)
4347 python-syntax-propertize-function)
4349 (set (make-local-variable 'indent-line-function)
4350 #'python-indent-line-function)
4351 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4352 ;; Because indentation is not redundant, we cannot safely reindent code.
4353 (set (make-local-variable 'electric-indent-inhibit) t)
4354 (set (make-local-variable 'electric-indent-chars)
4355 (cons ?: electric-indent-chars))
4357 ;; Add """ ... """ pairing to electric-pair-mode.
4358 (add-hook 'post-self-insert-hook
4359 #'python-electric-pair-string-delimiter 'append t)
4361 (set (make-local-variable 'paragraph-start) "\\s-*$")
4362 (set (make-local-variable 'fill-paragraph-function)
4363 #'python-fill-paragraph)
4365 (set (make-local-variable 'beginning-of-defun-function)
4366 #'python-nav-beginning-of-defun)
4367 (set (make-local-variable 'end-of-defun-function)
4368 #'python-nav-end-of-defun)
4370 (add-hook 'completion-at-point-functions
4371 #'python-completion-at-point nil 'local)
4373 (add-hook 'post-self-insert-hook
4374 #'python-indent-post-self-insert-function 'append 'local)
4376 (set (make-local-variable 'imenu-create-index-function)
4377 #'python-imenu-create-index)
4379 (set (make-local-variable 'add-log-current-defun-function)
4380 #'python-info-current-defun)
4382 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4384 (set (make-local-variable 'skeleton-further-elements)
4385 '((abbrev-mode nil)
4386 (< '(backward-delete-char-untabify (min python-indent-offset
4387 (current-column))))
4388 (^ '(- (1+ (current-indentation))))))
4390 (set (make-local-variable 'eldoc-documentation-function)
4391 #'python-eldoc-function)
4393 (add-to-list 'hs-special-modes-alist
4394 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
4395 ,(lambda (_arg)
4396 (python-nav-end-of-defun))
4397 nil))
4399 (set (make-local-variable 'outline-regexp)
4400 (python-rx (* space) block-start))
4401 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4402 (set (make-local-variable 'outline-level)
4403 #'(lambda ()
4404 "`outline-level' function for Python mode."
4405 (1+ (/ (current-indentation) python-indent-offset))))
4407 (python-skeleton-add-menu-items)
4409 (make-local-variable 'python-shell-internal-buffer)
4411 (when python-indent-guess-indent-offset
4412 (python-indent-guess-indent-offset)))
4415 (provide 'python)
4417 ;; Local Variables:
4418 ;; coding: utf-8
4419 ;; indent-tabs-mode: nil
4420 ;; End:
4422 ;;; python.el ends here