Merge from origin/emacs-24
[emacs.git] / lisp / progmodes / python.el
blobb1c6b01c4dcb9466c285654908d1f1216bb83d78
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 ;; Just re-indent dedenters
1211 (let ((dedenter-pos (python-info-dedenter-statement-p))
1212 (current-pos (point)))
1213 (when dedenter-pos
1214 (save-excursion
1215 (goto-char dedenter-pos)
1216 (python-indent-line)
1217 (unless (= (line-number-at-pos dedenter-pos)
1218 (line-number-at-pos current-pos))
1219 ;; Reindent region if this is a multiline statement
1220 (python-indent-region dedenter-pos current-pos)))))))))
1223 ;;; Navigation
1225 (defvar python-nav-beginning-of-defun-regexp
1226 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1227 "Regexp matching class or function definition.
1228 The name of the defun should be grouped so it can be retrieved
1229 via `match-string'.")
1231 (defun python-nav--beginning-of-defun (&optional arg)
1232 "Internal implementation of `python-nav-beginning-of-defun'.
1233 With positive ARG search backwards, else search forwards."
1234 (when (or (null arg) (= arg 0)) (setq arg 1))
1235 (let* ((re-search-fn (if (> arg 0)
1236 #'re-search-backward
1237 #'re-search-forward))
1238 (line-beg-pos (line-beginning-position))
1239 (line-content-start (+ line-beg-pos (current-indentation)))
1240 (pos (point-marker))
1241 (beg-indentation
1242 (and (> arg 0)
1243 (save-excursion
1244 (while (and
1245 (not (python-info-looking-at-beginning-of-defun))
1246 (python-nav-backward-block)))
1247 (or (and (python-info-looking-at-beginning-of-defun)
1248 (+ (current-indentation) python-indent-offset))
1249 0))))
1250 (found
1251 (progn
1252 (when (and (< arg 0)
1253 (python-info-looking-at-beginning-of-defun))
1254 (end-of-line 1))
1255 (while (and (funcall re-search-fn
1256 python-nav-beginning-of-defun-regexp nil t)
1257 (or (python-syntax-context-type)
1258 ;; Handle nested defuns when moving
1259 ;; backwards by checking indentation.
1260 (and (> arg 0)
1261 (not (= (current-indentation) 0))
1262 (>= (current-indentation) beg-indentation)))))
1263 (and (python-info-looking-at-beginning-of-defun)
1264 (or (not (= (line-number-at-pos pos)
1265 (line-number-at-pos)))
1266 (and (>= (point) line-beg-pos)
1267 (<= (point) line-content-start)
1268 (> pos line-content-start)))))))
1269 (if found
1270 (or (beginning-of-line 1) t)
1271 (and (goto-char pos) nil))))
1273 (defun python-nav-beginning-of-defun (&optional arg)
1274 "Move point to `beginning-of-defun'.
1275 With positive ARG search backwards else search forward.
1276 ARG nil or 0 defaults to 1. When searching backwards,
1277 nested defuns are handled with care depending on current
1278 point position. Return non-nil if point is moved to
1279 `beginning-of-defun'."
1280 (when (or (null arg) (= arg 0)) (setq arg 1))
1281 (let ((found))
1282 (while (and (not (= arg 0))
1283 (let ((keep-searching-p
1284 (python-nav--beginning-of-defun arg)))
1285 (when (and keep-searching-p (null found))
1286 (setq found t))
1287 keep-searching-p))
1288 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1289 found))
1291 (defun python-nav-end-of-defun ()
1292 "Move point to the end of def or class.
1293 Returns nil if point is not in a def or class."
1294 (interactive)
1295 (let ((beg-defun-indent)
1296 (beg-pos (point)))
1297 (when (or (python-info-looking-at-beginning-of-defun)
1298 (python-nav-beginning-of-defun 1)
1299 (python-nav-beginning-of-defun -1))
1300 (setq beg-defun-indent (current-indentation))
1301 (while (progn
1302 (python-nav-end-of-statement)
1303 (python-util-forward-comment 1)
1304 (and (> (current-indentation) beg-defun-indent)
1305 (not (eobp)))))
1306 (python-util-forward-comment -1)
1307 (forward-line 1)
1308 ;; Ensure point moves forward.
1309 (and (> beg-pos (point)) (goto-char beg-pos)))))
1311 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1312 "Move point using FN avoiding places with specific context.
1313 FN must take no arguments. POSCOMPFN is a two arguments function
1314 used to compare current and previous point after it is moved
1315 using FN, this is normally a less-than or greater-than
1316 comparison. Optional argument CONTEXTFN defaults to
1317 `python-syntax-context-type' and is used for checking current
1318 point context, it must return a non-nil value if this point must
1319 be skipped."
1320 (let ((contextfn (or contextfn 'python-syntax-context-type))
1321 (start-pos (point-marker))
1322 (prev-pos))
1323 (catch 'found
1324 (while t
1325 (let* ((newpos
1326 (and (funcall fn) (point-marker)))
1327 (context (funcall contextfn)))
1328 (cond ((and (not context) newpos
1329 (or (and (not prev-pos) newpos)
1330 (and prev-pos newpos
1331 (funcall poscompfn newpos prev-pos))))
1332 (throw 'found (point-marker)))
1333 ((and newpos context)
1334 (setq prev-pos (point)))
1335 (t (when (not newpos) (goto-char start-pos))
1336 (throw 'found nil))))))))
1338 (defun python-nav--forward-defun (arg)
1339 "Internal implementation of python-nav-{backward,forward}-defun.
1340 Uses ARG to define which function to call, and how many times
1341 repeat it."
1342 (let ((found))
1343 (while (and (> arg 0)
1344 (setq found
1345 (python-nav--syntactically
1346 (lambda ()
1347 (re-search-forward
1348 python-nav-beginning-of-defun-regexp nil t))
1349 '>)))
1350 (setq arg (1- arg)))
1351 (while (and (< arg 0)
1352 (setq found
1353 (python-nav--syntactically
1354 (lambda ()
1355 (re-search-backward
1356 python-nav-beginning-of-defun-regexp nil t))
1357 '<)))
1358 (setq arg (1+ arg)))
1359 found))
1361 (defun python-nav-backward-defun (&optional arg)
1362 "Navigate to closer defun backward ARG times.
1363 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1364 nested definitions."
1365 (interactive "^p")
1366 (python-nav--forward-defun (- (or arg 1))))
1368 (defun python-nav-forward-defun (&optional arg)
1369 "Navigate to closer defun forward ARG times.
1370 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1371 nested definitions."
1372 (interactive "^p")
1373 (python-nav--forward-defun (or arg 1)))
1375 (defun python-nav-beginning-of-statement ()
1376 "Move to start of current statement."
1377 (interactive "^")
1378 (back-to-indentation)
1379 (let* ((ppss (syntax-ppss))
1380 (context-point
1382 (python-syntax-context 'paren ppss)
1383 (python-syntax-context 'string ppss))))
1384 (cond ((bobp))
1385 (context-point
1386 (goto-char context-point)
1387 (python-nav-beginning-of-statement))
1388 ((save-excursion
1389 (forward-line -1)
1390 (python-info-line-ends-backslash-p))
1391 (forward-line -1)
1392 (python-nav-beginning-of-statement))))
1393 (point-marker))
1395 (defun python-nav-end-of-statement (&optional noend)
1396 "Move to end of current statement.
1397 Optional argument NOEND is internal and makes the logic to not
1398 jump to the end of line when moving forward searching for the end
1399 of the statement."
1400 (interactive "^")
1401 (let (string-start bs-pos)
1402 (while (and (or noend (goto-char (line-end-position)))
1403 (not (eobp))
1404 (cond ((setq string-start (python-syntax-context 'string))
1405 (goto-char string-start)
1406 (if (python-syntax-context 'paren)
1407 ;; Ended up inside a paren, roll again.
1408 (python-nav-end-of-statement t)
1409 ;; This is not inside a paren, move to the
1410 ;; end of this string.
1411 (goto-char (+ (point)
1412 (python-syntax-count-quotes
1413 (char-after (point)) (point))))
1414 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1415 (goto-char (point-max)))))
1416 ((python-syntax-context 'paren)
1417 ;; The statement won't end before we've escaped
1418 ;; at least one level of parenthesis.
1419 (condition-case err
1420 (goto-char (scan-lists (point) 1 -1))
1421 (scan-error (goto-char (nth 3 err)))))
1422 ((setq bs-pos (python-info-line-ends-backslash-p))
1423 (goto-char bs-pos)
1424 (forward-line 1))))))
1425 (point-marker))
1427 (defun python-nav-backward-statement (&optional arg)
1428 "Move backward to previous statement.
1429 With ARG, repeat. See `python-nav-forward-statement'."
1430 (interactive "^p")
1431 (or arg (setq arg 1))
1432 (python-nav-forward-statement (- arg)))
1434 (defun python-nav-forward-statement (&optional arg)
1435 "Move forward to next statement.
1436 With ARG, repeat. With negative argument, move ARG times
1437 backward to previous statement."
1438 (interactive "^p")
1439 (or arg (setq arg 1))
1440 (while (> arg 0)
1441 (python-nav-end-of-statement)
1442 (python-util-forward-comment)
1443 (python-nav-beginning-of-statement)
1444 (setq arg (1- arg)))
1445 (while (< arg 0)
1446 (python-nav-beginning-of-statement)
1447 (python-util-forward-comment -1)
1448 (python-nav-beginning-of-statement)
1449 (setq arg (1+ arg))))
1451 (defun python-nav-beginning-of-block ()
1452 "Move to start of current block."
1453 (interactive "^")
1454 (let ((starting-pos (point)))
1455 (if (progn
1456 (python-nav-beginning-of-statement)
1457 (looking-at (python-rx block-start)))
1458 (point-marker)
1459 ;; Go to first line beginning a statement
1460 (while (and (not (bobp))
1461 (or (and (python-nav-beginning-of-statement) nil)
1462 (python-info-current-line-comment-p)
1463 (python-info-current-line-empty-p)))
1464 (forward-line -1))
1465 (let ((block-matching-indent
1466 (- (current-indentation) python-indent-offset)))
1467 (while
1468 (and (python-nav-backward-block)
1469 (> (current-indentation) block-matching-indent)))
1470 (if (and (looking-at (python-rx block-start))
1471 (= (current-indentation) block-matching-indent))
1472 (point-marker)
1473 (and (goto-char starting-pos) nil))))))
1475 (defun python-nav-end-of-block ()
1476 "Move to end of current block."
1477 (interactive "^")
1478 (when (python-nav-beginning-of-block)
1479 (let ((block-indentation (current-indentation)))
1480 (python-nav-end-of-statement)
1481 (while (and (forward-line 1)
1482 (not (eobp))
1483 (or (and (> (current-indentation) block-indentation)
1484 (or (python-nav-end-of-statement) t))
1485 (python-info-current-line-comment-p)
1486 (python-info-current-line-empty-p))))
1487 (python-util-forward-comment -1)
1488 (point-marker))))
1490 (defun python-nav-backward-block (&optional arg)
1491 "Move backward to previous block of code.
1492 With ARG, repeat. See `python-nav-forward-block'."
1493 (interactive "^p")
1494 (or arg (setq arg 1))
1495 (python-nav-forward-block (- arg)))
1497 (defun python-nav-forward-block (&optional arg)
1498 "Move forward to next block of code.
1499 With ARG, repeat. With negative argument, move ARG times
1500 backward to previous block."
1501 (interactive "^p")
1502 (or arg (setq arg 1))
1503 (let ((block-start-regexp
1504 (python-rx line-start (* whitespace) block-start))
1505 (starting-pos (point)))
1506 (while (> arg 0)
1507 (python-nav-end-of-statement)
1508 (while (and
1509 (re-search-forward block-start-regexp nil t)
1510 (python-syntax-context-type)))
1511 (setq arg (1- arg)))
1512 (while (< arg 0)
1513 (python-nav-beginning-of-statement)
1514 (while (and
1515 (re-search-backward block-start-regexp nil t)
1516 (python-syntax-context-type)))
1517 (setq arg (1+ arg)))
1518 (python-nav-beginning-of-statement)
1519 (if (not (looking-at (python-rx block-start)))
1520 (and (goto-char starting-pos) nil)
1521 (and (not (= (point) starting-pos)) (point-marker)))))
1523 (defun python-nav--lisp-forward-sexp (&optional arg)
1524 "Standard version `forward-sexp'.
1525 It ignores completely the value of `forward-sexp-function' by
1526 setting it to nil before calling `forward-sexp'. With positive
1527 ARG move forward only one sexp, else move backwards."
1528 (let ((forward-sexp-function)
1529 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1530 (forward-sexp arg)))
1532 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1533 "Safe version of standard `forward-sexp'.
1534 When at end of sexp (i.e. looking at a opening/closing paren)
1535 skips it instead of throwing an error. With positive ARG move
1536 forward only one sexp, else move backwards."
1537 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1538 (paren-regexp
1539 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1540 (search-fn
1541 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1542 (condition-case nil
1543 (python-nav--lisp-forward-sexp arg)
1544 (error
1545 (while (and (funcall search-fn paren-regexp nil t)
1546 (python-syntax-context 'paren)))))))
1548 (defun python-nav--forward-sexp (&optional dir safe)
1549 "Move to forward sexp.
1550 With positive optional argument DIR direction move forward, else
1551 backwards. When optional argument SAFE is non-nil do not throw
1552 errors when at end of sexp, skip it instead."
1553 (setq dir (or dir 1))
1554 (unless (= dir 0)
1555 (let* ((forward-p (if (> dir 0)
1556 (and (setq dir 1) t)
1557 (and (setq dir -1) nil)))
1558 (context-type (python-syntax-context-type)))
1559 (cond
1560 ((memq context-type '(string comment))
1561 ;; Inside of a string, get out of it.
1562 (let ((forward-sexp-function))
1563 (forward-sexp dir)))
1564 ((or (eq context-type 'paren)
1565 (and forward-p (looking-at (python-rx open-paren)))
1566 (and (not forward-p)
1567 (eq (syntax-class (syntax-after (1- (point))))
1568 (car (string-to-syntax ")")))))
1569 ;; Inside a paren or looking at it, lisp knows what to do.
1570 (if safe
1571 (python-nav--lisp-forward-sexp-safe dir)
1572 (python-nav--lisp-forward-sexp dir)))
1574 ;; This part handles the lispy feel of
1575 ;; `python-nav-forward-sexp'. Knowing everything about the
1576 ;; current context and the context of the next sexp tries to
1577 ;; follow the lisp sexp motion commands in a symmetric manner.
1578 (let* ((context
1579 (cond
1580 ((python-info-beginning-of-block-p) 'block-start)
1581 ((python-info-end-of-block-p) 'block-end)
1582 ((python-info-beginning-of-statement-p) 'statement-start)
1583 ((python-info-end-of-statement-p) 'statement-end)))
1584 (next-sexp-pos
1585 (save-excursion
1586 (if safe
1587 (python-nav--lisp-forward-sexp-safe dir)
1588 (python-nav--lisp-forward-sexp dir))
1589 (point)))
1590 (next-sexp-context
1591 (save-excursion
1592 (goto-char next-sexp-pos)
1593 (cond
1594 ((python-info-beginning-of-block-p) 'block-start)
1595 ((python-info-end-of-block-p) 'block-end)
1596 ((python-info-beginning-of-statement-p) 'statement-start)
1597 ((python-info-end-of-statement-p) 'statement-end)
1598 ((python-info-statement-starts-block-p) 'starts-block)
1599 ((python-info-statement-ends-block-p) 'ends-block)))))
1600 (if forward-p
1601 (cond ((and (not (eobp))
1602 (python-info-current-line-empty-p))
1603 (python-util-forward-comment dir)
1604 (python-nav--forward-sexp dir))
1605 ((eq context 'block-start)
1606 (python-nav-end-of-block))
1607 ((eq context 'statement-start)
1608 (python-nav-end-of-statement))
1609 ((and (memq context '(statement-end block-end))
1610 (eq next-sexp-context 'ends-block))
1611 (goto-char next-sexp-pos)
1612 (python-nav-end-of-block))
1613 ((and (memq context '(statement-end block-end))
1614 (eq next-sexp-context 'starts-block))
1615 (goto-char next-sexp-pos)
1616 (python-nav-end-of-block))
1617 ((memq context '(statement-end block-end))
1618 (goto-char next-sexp-pos)
1619 (python-nav-end-of-statement))
1620 (t (goto-char next-sexp-pos)))
1621 (cond ((and (not (bobp))
1622 (python-info-current-line-empty-p))
1623 (python-util-forward-comment dir)
1624 (python-nav--forward-sexp dir))
1625 ((eq context 'block-end)
1626 (python-nav-beginning-of-block))
1627 ((eq context 'statement-end)
1628 (python-nav-beginning-of-statement))
1629 ((and (memq context '(statement-start block-start))
1630 (eq next-sexp-context 'starts-block))
1631 (goto-char next-sexp-pos)
1632 (python-nav-beginning-of-block))
1633 ((and (memq context '(statement-start block-start))
1634 (eq next-sexp-context 'ends-block))
1635 (goto-char next-sexp-pos)
1636 (python-nav-beginning-of-block))
1637 ((memq context '(statement-start block-start))
1638 (goto-char next-sexp-pos)
1639 (python-nav-beginning-of-statement))
1640 (t (goto-char next-sexp-pos))))))))))
1642 (defun python-nav-forward-sexp (&optional arg)
1643 "Move forward across expressions.
1644 With ARG, do it that many times. Negative arg -N means move
1645 backward N times."
1646 (interactive "^p")
1647 (or arg (setq arg 1))
1648 (while (> arg 0)
1649 (python-nav--forward-sexp 1)
1650 (setq arg (1- arg)))
1651 (while (< arg 0)
1652 (python-nav--forward-sexp -1)
1653 (setq arg (1+ arg))))
1655 (defun python-nav-backward-sexp (&optional arg)
1656 "Move backward across expressions.
1657 With ARG, do it that many times. Negative arg -N means move
1658 forward N times."
1659 (interactive "^p")
1660 (or arg (setq arg 1))
1661 (python-nav-forward-sexp (- arg)))
1663 (defun python-nav-forward-sexp-safe (&optional arg)
1664 "Move forward safely across expressions.
1665 With ARG, do it that many times. Negative arg -N means move
1666 backward N times."
1667 (interactive "^p")
1668 (or arg (setq arg 1))
1669 (while (> arg 0)
1670 (python-nav--forward-sexp 1 t)
1671 (setq arg (1- arg)))
1672 (while (< arg 0)
1673 (python-nav--forward-sexp -1 t)
1674 (setq arg (1+ arg))))
1676 (defun python-nav-backward-sexp-safe (&optional arg)
1677 "Move backward safely across expressions.
1678 With ARG, do it that many times. Negative arg -N means move
1679 forward N times."
1680 (interactive "^p")
1681 (or arg (setq arg 1))
1682 (python-nav-forward-sexp-safe (- arg)))
1684 (defun python-nav--up-list (&optional dir)
1685 "Internal implementation of `python-nav-up-list'.
1686 DIR is always 1 or -1 and comes sanitized from
1687 `python-nav-up-list' calls."
1688 (let ((context (python-syntax-context-type))
1689 (forward-p (> dir 0)))
1690 (cond
1691 ((memq context '(string comment)))
1692 ((eq context 'paren)
1693 (let ((forward-sexp-function))
1694 (up-list dir)))
1695 ((and forward-p (python-info-end-of-block-p))
1696 (let ((parent-end-pos
1697 (save-excursion
1698 (let ((indentation (and
1699 (python-nav-beginning-of-block)
1700 (current-indentation))))
1701 (while (and indentation
1702 (> indentation 0)
1703 (>= (current-indentation) indentation)
1704 (python-nav-backward-block)))
1705 (python-nav-end-of-block)))))
1706 (and (> (or parent-end-pos (point)) (point))
1707 (goto-char parent-end-pos))))
1708 (forward-p (python-nav-end-of-block))
1709 ((and (not forward-p)
1710 (> (current-indentation) 0)
1711 (python-info-beginning-of-block-p))
1712 (let ((prev-block-pos
1713 (save-excursion
1714 (let ((indentation (current-indentation)))
1715 (while (and (python-nav-backward-block)
1716 (>= (current-indentation) indentation))))
1717 (point))))
1718 (and (> (point) prev-block-pos)
1719 (goto-char prev-block-pos))))
1720 ((not forward-p) (python-nav-beginning-of-block)))))
1722 (defun python-nav-up-list (&optional arg)
1723 "Move forward out of one level of parentheses (or blocks).
1724 With ARG, do this that many times.
1725 A negative argument means move backward but still to a less deep spot.
1726 This command assumes point is not in a string or comment."
1727 (interactive "^p")
1728 (or arg (setq arg 1))
1729 (while (> arg 0)
1730 (python-nav--up-list 1)
1731 (setq arg (1- arg)))
1732 (while (< arg 0)
1733 (python-nav--up-list -1)
1734 (setq arg (1+ arg))))
1736 (defun python-nav-backward-up-list (&optional arg)
1737 "Move backward out of one level of parentheses (or blocks).
1738 With ARG, do this that many times.
1739 A negative argument means move forward but still to a less deep spot.
1740 This command assumes point is not in a string or comment."
1741 (interactive "^p")
1742 (or arg (setq arg 1))
1743 (python-nav-up-list (- arg)))
1745 (defun python-nav-if-name-main ()
1746 "Move point at the beginning the __main__ block.
1747 When \"if __name__ == '__main__':\" is found returns its
1748 position, else returns nil."
1749 (interactive)
1750 (let ((point (point))
1751 (found (catch 'found
1752 (goto-char (point-min))
1753 (while (re-search-forward
1754 (python-rx line-start
1755 "if" (+ space)
1756 "__name__" (+ space)
1757 "==" (+ space)
1758 (group-n 1 (or ?\" ?\'))
1759 "__main__" (backref 1) (* space) ":")
1760 nil t)
1761 (when (not (python-syntax-context-type))
1762 (beginning-of-line)
1763 (throw 'found t))))))
1764 (if found
1765 (point)
1766 (ignore (goto-char point)))))
1769 ;;; Shell integration
1771 (defcustom python-shell-buffer-name "Python"
1772 "Default buffer name for Python interpreter."
1773 :type 'string
1774 :group 'python
1775 :safe 'stringp)
1777 (defcustom python-shell-interpreter "python"
1778 "Default Python interpreter for shell."
1779 :type 'string
1780 :group 'python)
1782 (defcustom python-shell-internal-buffer-name "Python Internal"
1783 "Default buffer name for the Internal Python interpreter."
1784 :type 'string
1785 :group 'python
1786 :safe 'stringp)
1788 (defcustom python-shell-interpreter-args "-i"
1789 "Default arguments for the Python interpreter."
1790 :type 'string
1791 :group 'python)
1793 (defcustom python-shell-interpreter-interactive-arg "-i"
1794 "Interpreter argument to force it to run interactively."
1795 :type 'string
1796 :version "24.4")
1798 (defcustom python-shell-prompt-detect-enabled t
1799 "Non-nil enables autodetection of interpreter prompts."
1800 :type 'boolean
1801 :safe 'booleanp
1802 :version "24.4")
1804 (defcustom python-shell-prompt-detect-failure-warning t
1805 "Non-nil enables warnings when detection of prompts fail."
1806 :type 'boolean
1807 :safe 'booleanp
1808 :version "24.4")
1810 (defcustom python-shell-prompt-input-regexps
1811 '(">>> " "\\.\\.\\. " ; Python
1812 "In \\[[0-9]+\\]: " ; IPython
1813 " \\.\\.\\.: " ; IPython
1814 ;; Using ipdb outside IPython may fail to cleanup and leave static
1815 ;; IPython prompts activated, this adds some safeguard for that.
1816 "In : " "\\.\\.\\.: ")
1817 "List of regular expressions matching input prompts."
1818 :type '(repeat string)
1819 :version "24.4")
1821 (defcustom python-shell-prompt-output-regexps
1822 '("" ; Python
1823 "Out\\[[0-9]+\\]: " ; IPython
1824 "Out :") ; ipdb safeguard
1825 "List of regular expressions matching output prompts."
1826 :type '(repeat string)
1827 :version "24.4")
1829 (defcustom python-shell-prompt-regexp ">>> "
1830 "Regular expression matching top level input prompt of Python shell.
1831 It should not contain a caret (^) at the beginning."
1832 :type 'string)
1834 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1835 "Regular expression matching block input prompt of Python shell.
1836 It should not contain a caret (^) at the beginning."
1837 :type 'string)
1839 (defcustom python-shell-prompt-output-regexp ""
1840 "Regular expression matching output prompt of Python shell.
1841 It should not contain a caret (^) at the beginning."
1842 :type 'string)
1844 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1845 "Regular expression matching pdb input prompt of Python shell.
1846 It should not contain a caret (^) at the beginning."
1847 :type 'string)
1849 (define-obsolete-variable-alias
1850 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1852 (defcustom python-shell-font-lock-enable t
1853 "Should syntax highlighting be enabled in the Python shell buffer?
1854 Restart the Python shell after changing this variable for it to take effect."
1855 :type 'boolean
1856 :group 'python
1857 :safe 'booleanp)
1859 (defcustom python-shell-unbuffered t
1860 "Should shell output be unbuffered?.
1861 When non-nil, this may prevent delayed and missing output in the
1862 Python shell. See commentary for details."
1863 :type 'boolean
1864 :group 'python
1865 :safe 'booleanp)
1867 (defcustom python-shell-process-environment nil
1868 "List of environment variables for Python shell.
1869 This variable follows the same rules as `process-environment'
1870 since it merges with it before the process creation routines are
1871 called. When this variable is nil, the Python shell is run with
1872 the default `process-environment'."
1873 :type '(repeat string)
1874 :group 'python
1875 :safe 'listp)
1877 (defcustom python-shell-extra-pythonpaths nil
1878 "List of extra pythonpaths for Python shell.
1879 The values of this variable are added to the existing value of
1880 PYTHONPATH in the `process-environment' variable."
1881 :type '(repeat string)
1882 :group 'python
1883 :safe 'listp)
1885 (defcustom python-shell-exec-path nil
1886 "List of path to search for binaries.
1887 This variable follows the same rules as `exec-path' since it
1888 merges with it before the process creation routines are called.
1889 When this variable is nil, the Python shell is run with the
1890 default `exec-path'."
1891 :type '(repeat string)
1892 :group 'python
1893 :safe 'listp)
1895 (defcustom python-shell-virtualenv-root nil
1896 "Path to virtualenv root.
1897 This variable, when set to a string, makes the values stored in
1898 `python-shell-process-environment' and `python-shell-exec-path'
1899 to be modified properly so shells are started with the specified
1900 virtualenv."
1901 :type '(choice (const nil) string)
1902 :group 'python
1903 :safe 'stringp)
1905 (define-obsolete-variable-alias
1906 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
1908 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1909 python-ffap-setup-code
1910 python-eldoc-setup-code)
1911 "List of code run by `python-shell-send-setup-codes'."
1912 :type '(repeat symbol)
1913 :group 'python
1914 :safe 'listp)
1916 (defcustom python-shell-compilation-regexp-alist
1917 `((,(rx line-start (1+ (any " \t")) "File \""
1918 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1919 "\", line " (group (1+ digit)))
1920 1 2)
1921 (,(rx " in file " (group (1+ not-newline)) " on line "
1922 (group (1+ digit)))
1923 1 2)
1924 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1925 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1926 1 2))
1927 "`compilation-error-regexp-alist' for inferior Python."
1928 :type '(alist string)
1929 :group 'python)
1931 (defvar python-shell--prompt-calculated-input-regexp nil
1932 "Calculated input prompt regexp for inferior python shell.
1933 Do not set this variable directly, instead use
1934 `python-shell-prompt-set-calculated-regexps'.")
1936 (defvar python-shell--prompt-calculated-output-regexp nil
1937 "Calculated output prompt regexp for inferior python shell.
1938 Do not set this variable directly, instead use
1939 `python-shell-set-prompt-regexp'.")
1941 (defun python-shell-prompt-detect ()
1942 "Detect prompts for the current `python-shell-interpreter'.
1943 When prompts can be retrieved successfully from the
1944 `python-shell-interpreter' run with
1945 `python-shell-interpreter-interactive-arg', returns a list of
1946 three elements, where the first two are input prompts and the
1947 last one is an output prompt. When no prompts can be detected
1948 and `python-shell-prompt-detect-failure-warning' is non-nil,
1949 shows a warning with instructions to avoid hangs and returns nil.
1950 When `python-shell-prompt-detect-enabled' is nil avoids any
1951 detection and just returns nil."
1952 (when python-shell-prompt-detect-enabled
1953 (let* ((process-environment (python-shell-calculate-process-environment))
1954 (exec-path (python-shell-calculate-exec-path))
1955 (code (concat
1956 "import sys\n"
1957 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1958 ;; JSON is built manually for compatibility
1959 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1960 "print (ps_json)\n"
1961 "sys.exit(0)\n"))
1962 (output
1963 (with-temp-buffer
1964 ;; TODO: improve error handling by using
1965 ;; `condition-case' and displaying the error message to
1966 ;; the user in the no-prompts warning.
1967 (ignore-errors
1968 (let ((code-file (python-shell--save-temp-file code)))
1969 ;; Use `process-file' as it is remote-host friendly.
1970 (process-file
1971 python-shell-interpreter
1972 code-file
1973 '(t nil)
1975 python-shell-interpreter-interactive-arg)
1976 ;; Try to cleanup
1977 (delete-file code-file)))
1978 (buffer-string)))
1979 (prompts
1980 (catch 'prompts
1981 (dolist (line (split-string output "\n" t))
1982 (let ((res
1983 ;; Check if current line is a valid JSON array
1984 (and (string= (substring line 0 2) "[\"")
1985 (ignore-errors
1986 ;; Return prompts as a list, not vector
1987 (append (json-read-from-string line) nil)))))
1988 ;; The list must contain 3 strings, where the first
1989 ;; is the input prompt, the second is the block
1990 ;; prompt and the last one is the output prompt. The
1991 ;; input prompt is the only one that can't be empty.
1992 (when (and (= (length res) 3)
1993 (cl-every #'stringp res)
1994 (not (string= (car res) "")))
1995 (throw 'prompts res))))
1996 nil)))
1997 (when (and (not prompts)
1998 python-shell-prompt-detect-failure-warning)
1999 (lwarn
2000 '(python python-shell-prompt-regexp)
2001 :warning
2002 (concat
2003 "Python shell prompts cannot be detected.\n"
2004 "If your emacs session hangs when starting python shells\n"
2005 "recover with `keyboard-quit' and then try fixing the\n"
2006 "interactive flag for your interpreter by adjusting the\n"
2007 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2008 "matching shell prompts in the directory-local friendly vars:\n"
2009 " + `python-shell-prompt-regexp'\n"
2010 " + `python-shell-prompt-block-regexp'\n"
2011 " + `python-shell-prompt-output-regexp'\n"
2012 "Or alternatively in:\n"
2013 " + `python-shell-prompt-input-regexps'\n"
2014 " + `python-shell-prompt-output-regexps'")))
2015 prompts)))
2017 (defun python-shell-prompt-validate-regexps ()
2018 "Validate all user provided regexps for prompts.
2019 Signals `user-error' if any of these vars contain invalid
2020 regexps: `python-shell-prompt-regexp',
2021 `python-shell-prompt-block-regexp',
2022 `python-shell-prompt-pdb-regexp',
2023 `python-shell-prompt-output-regexp',
2024 `python-shell-prompt-input-regexps',
2025 `python-shell-prompt-output-regexps'."
2026 (dolist (symbol (list 'python-shell-prompt-input-regexps
2027 'python-shell-prompt-output-regexps
2028 'python-shell-prompt-regexp
2029 'python-shell-prompt-block-regexp
2030 'python-shell-prompt-pdb-regexp
2031 'python-shell-prompt-output-regexp))
2032 (dolist (regexp (let ((regexps (symbol-value symbol)))
2033 (if (listp regexps)
2034 regexps
2035 (list regexps))))
2036 (when (not (python-util-valid-regexp-p regexp))
2037 (user-error "Invalid regexp %s in `%s'"
2038 regexp symbol)))))
2040 (defun python-shell-prompt-set-calculated-regexps ()
2041 "Detect and set input and output prompt regexps.
2042 Build and set the values for `python-shell-input-prompt-regexp'
2043 and `python-shell-output-prompt-regexp' using the values from
2044 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2045 `python-shell-prompt-pdb-regexp',
2046 `python-shell-prompt-output-regexp',
2047 `python-shell-prompt-input-regexps',
2048 `python-shell-prompt-output-regexps' and detected prompts from
2049 `python-shell-prompt-detect'."
2050 (when (not (and python-shell--prompt-calculated-input-regexp
2051 python-shell--prompt-calculated-output-regexp))
2052 (let* ((detected-prompts (python-shell-prompt-detect))
2053 (input-prompts nil)
2054 (output-prompts nil)
2055 (build-regexp
2056 (lambda (prompts)
2057 (concat "^\\("
2058 (mapconcat #'identity
2059 (sort prompts
2060 (lambda (a b)
2061 (let ((length-a (length a))
2062 (length-b (length b)))
2063 (if (= length-a length-b)
2064 (string< a b)
2065 (> (length a) (length b))))))
2066 "\\|")
2067 "\\)"))))
2068 ;; Validate ALL regexps
2069 (python-shell-prompt-validate-regexps)
2070 ;; Collect all user defined input prompts
2071 (dolist (prompt (append python-shell-prompt-input-regexps
2072 (list python-shell-prompt-regexp
2073 python-shell-prompt-block-regexp
2074 python-shell-prompt-pdb-regexp)))
2075 (cl-pushnew prompt input-prompts :test #'string=))
2076 ;; Collect all user defined output prompts
2077 (dolist (prompt (cons python-shell-prompt-output-regexp
2078 python-shell-prompt-output-regexps))
2079 (cl-pushnew prompt output-prompts :test #'string=))
2080 ;; Collect detected prompts if any
2081 (when detected-prompts
2082 (dolist (prompt (butlast detected-prompts))
2083 (setq prompt (regexp-quote prompt))
2084 (cl-pushnew prompt input-prompts :test #'string=))
2085 (cl-pushnew (regexp-quote
2086 (car (last detected-prompts)))
2087 output-prompts :test #'string=))
2088 ;; Set input and output prompt regexps from collected prompts
2089 (setq python-shell--prompt-calculated-input-regexp
2090 (funcall build-regexp input-prompts)
2091 python-shell--prompt-calculated-output-regexp
2092 (funcall build-regexp output-prompts)))))
2094 (defun python-shell-get-process-name (dedicated)
2095 "Calculate the appropriate process name for inferior Python process.
2096 If DEDICATED is t returns a string with the form
2097 `python-shell-buffer-name'[`buffer-name'] else returns the value
2098 of `python-shell-buffer-name'."
2099 (if dedicated
2100 (format "%s[%s]" python-shell-buffer-name (buffer-name))
2101 python-shell-buffer-name))
2103 (defun python-shell-internal-get-process-name ()
2104 "Calculate the appropriate process name for Internal Python process.
2105 The name is calculated from `python-shell-global-buffer-name' and
2106 the `buffer-name'."
2107 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
2109 (defun python-shell-calculate-command ()
2110 "Calculate the string used to execute the inferior Python process."
2111 (let ((exec-path (python-shell-calculate-exec-path)))
2112 ;; `exec-path' gets tweaked so that virtualenv's specific
2113 ;; `python-shell-interpreter' absolute path can be found by
2114 ;; `executable-find'.
2115 (format "%s %s"
2116 ;; FIXME: Why executable-find?
2117 (shell-quote-argument
2118 (executable-find python-shell-interpreter))
2119 python-shell-interpreter-args)))
2121 (define-obsolete-function-alias
2122 'python-shell-parse-command
2123 #'python-shell-calculate-command "25.1")
2125 (defun python-shell-calculate-pythonpath ()
2126 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2127 (let ((pythonpath (getenv "PYTHONPATH"))
2128 (extra (mapconcat 'identity
2129 python-shell-extra-pythonpaths
2130 path-separator)))
2131 (if pythonpath
2132 (concat extra path-separator pythonpath)
2133 extra)))
2135 (defun python-shell-calculate-process-environment ()
2136 "Calculate process environment given `python-shell-virtualenv-root'."
2137 (let ((process-environment (append
2138 python-shell-process-environment
2139 process-environment nil))
2140 (virtualenv (if python-shell-virtualenv-root
2141 (directory-file-name python-shell-virtualenv-root)
2142 nil)))
2143 (when python-shell-unbuffered
2144 (setenv "PYTHONUNBUFFERED" "1"))
2145 (when python-shell-extra-pythonpaths
2146 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2147 (if (not virtualenv)
2148 process-environment
2149 (setenv "PYTHONHOME" nil)
2150 (setenv "PATH" (format "%s/bin%s%s"
2151 virtualenv path-separator
2152 (or (getenv "PATH") "")))
2153 (setenv "VIRTUAL_ENV" virtualenv))
2154 process-environment))
2156 (defun python-shell-calculate-exec-path ()
2157 "Calculate exec path given `python-shell-virtualenv-root'."
2158 (let ((path (append
2159 ;; Use nil as the tail so that the list is a full copy,
2160 ;; this is a paranoid safeguard for side-effects.
2161 python-shell-exec-path exec-path nil)))
2162 (if (not python-shell-virtualenv-root)
2163 path
2164 (cons (expand-file-name "bin" python-shell-virtualenv-root)
2165 path))))
2167 (defvar python-shell--package-depth 10)
2169 (defun python-shell-package-enable (directory package)
2170 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2171 (interactive
2172 (let* ((dir (expand-file-name
2173 (read-directory-name
2174 "Package root: "
2175 (file-name-directory
2176 (or (buffer-file-name) default-directory)))))
2177 (name (completing-read
2178 "Package: "
2179 (python-util-list-packages
2180 dir python-shell--package-depth))))
2181 (list dir name)))
2182 (python-shell-send-string
2183 (format
2184 (concat
2185 "import os.path;import sys;"
2186 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2187 "__package__ = '''%s''';"
2188 "import %s")
2189 directory package package)
2190 (python-shell-get-process)))
2192 (defun python-shell-accept-process-output (process &optional timeout regexp)
2193 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2194 Optional argument TIMEOUT is the timeout argument to
2195 `accept-process-output' calls. Optional argument REGEXP
2196 overrides the regexp to match the end of output, defaults to
2197 `comint-prompt-regexp.'. Returns non-nil when output was
2198 properly captured.
2200 This utility is useful in situations where the output may be
2201 received in chunks, since `accept-process-output' gives no
2202 guarantees they will be grabbed in a single call. An example use
2203 case for this would be the CPython shell start-up, where the
2204 banner and the initial prompt are received separately."
2205 (let ((regexp (or regexp comint-prompt-regexp)))
2206 (catch 'found
2207 (while t
2208 (when (not (accept-process-output process timeout))
2209 (throw 'found nil))
2210 (when (looking-back regexp)
2211 (throw 'found t))))))
2213 (defun python-shell-comint-end-of-output-p (output)
2214 "Return non-nil if OUTPUT is ends with input prompt."
2215 (string-match
2216 ;; XXX: It seems on OSX an extra carriage return is attached
2217 ;; at the end of output, this handles that too.
2218 (concat
2219 "\r?\n?"
2220 ;; Remove initial caret from calculated regexp
2221 (replace-regexp-in-string
2222 (rx string-start ?^) ""
2223 python-shell--prompt-calculated-input-regexp)
2224 (rx eos))
2225 output))
2227 (define-obsolete-function-alias
2228 'python-comint-output-filter-function
2229 'ansi-color-filter-apply
2230 "25.1")
2232 (defun python-comint-postoutput-scroll-to-bottom (output)
2233 "Faster version of `comint-postoutput-scroll-to-bottom'.
2234 Avoids `recenter' calls until OUTPUT is completely sent."
2235 (when (and (not (string= "" output))
2236 (python-shell-comint-end-of-output-p
2237 (ansi-color-filter-apply output)))
2238 (comint-postoutput-scroll-to-bottom output))
2239 output)
2241 (defvar python-shell--parent-buffer nil)
2243 (defmacro python-shell-with-shell-buffer (&rest body)
2244 "Execute the forms in BODY with the shell buffer temporarily current.
2245 Signals an error if no shell buffer is available for current buffer."
2246 (declare (indent 0) (debug t))
2247 (let ((shell-buffer (make-symbol "shell-buffer")))
2248 `(let ((,shell-buffer (python-shell-get-buffer)))
2249 (when (not ,shell-buffer)
2250 (error "No inferior Python buffer available."))
2251 (with-current-buffer ,shell-buffer
2252 ,@body))))
2254 (defvar python-shell--font-lock-buffer nil)
2256 (defun python-shell-font-lock-get-or-create-buffer ()
2257 "Get or create a font-lock buffer for current inferior process."
2258 (python-shell-with-shell-buffer
2259 (if python-shell--font-lock-buffer
2260 python-shell--font-lock-buffer
2261 (let ((process-name
2262 (process-name (get-buffer-process (current-buffer)))))
2263 (generate-new-buffer
2264 (format "*%s-font-lock*" process-name))))))
2266 (defun python-shell-font-lock-kill-buffer ()
2267 "Kill the font-lock buffer safely."
2268 (python-shell-with-shell-buffer
2269 (when (and python-shell--font-lock-buffer
2270 (buffer-live-p python-shell--font-lock-buffer))
2271 (kill-buffer python-shell--font-lock-buffer)
2272 (when (derived-mode-p 'inferior-python-mode)
2273 (setq python-shell--font-lock-buffer nil)))))
2275 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2276 "Execute the forms in BODY in the font-lock buffer.
2277 The value returned is the value of the last form in BODY. See
2278 also `with-current-buffer'."
2279 (declare (indent 0) (debug t))
2280 `(python-shell-with-shell-buffer
2281 (save-current-buffer
2282 (when (not (and python-shell--font-lock-buffer
2283 (get-buffer python-shell--font-lock-buffer)))
2284 (setq python-shell--font-lock-buffer
2285 (python-shell-font-lock-get-or-create-buffer)))
2286 (set-buffer python-shell--font-lock-buffer)
2287 (set (make-local-variable 'delay-mode-hooks) t)
2288 (let ((python-indent-guess-indent-offset nil))
2289 (when (not (derived-mode-p 'python-mode))
2290 (python-mode))
2291 ,@body))))
2293 (defun python-shell-font-lock-cleanup-buffer ()
2294 "Cleanup the font-lock buffer.
2295 Provided as a command because this might be handy if something
2296 goes wrong and syntax highlighting in the shell gets messed up."
2297 (interactive)
2298 (python-shell-with-shell-buffer
2299 (python-shell-font-lock-with-font-lock-buffer
2300 (delete-region (point-min) (point-max)))))
2302 (defun python-shell-font-lock-comint-output-filter-function (output)
2303 "Clean up the font-lock buffer after any OUTPUT."
2304 (when (and (not (string= "" output))
2305 ;; Is end of output and is not just a prompt.
2306 (not (member
2307 (python-shell-comint-end-of-output-p
2308 (ansi-color-filter-apply output))
2309 '(nil 0))))
2310 ;; If output is other than an input prompt then "real" output has
2311 ;; been received and the font-lock buffer must be cleaned up.
2312 (python-shell-font-lock-cleanup-buffer))
2313 output)
2315 (defun python-shell-font-lock-post-command-hook ()
2316 "Fontifies current line in shell buffer."
2317 (if (eq this-command 'comint-send-input)
2318 ;; Add a newline when user sends input as this may be a block.
2319 (python-shell-font-lock-with-font-lock-buffer
2320 (goto-char (line-end-position))
2321 (newline))
2322 (when (and (python-util-comint-last-prompt)
2323 (> (point) (cdr (python-util-comint-last-prompt))))
2324 (let ((input (buffer-substring-no-properties
2325 (cdr (python-util-comint-last-prompt)) (point-max)))
2326 (old-input (python-shell-font-lock-with-font-lock-buffer
2327 (buffer-substring-no-properties
2328 (line-beginning-position) (point-max))))
2329 (current-point (point))
2330 (buffer-undo-list t))
2331 ;; When input hasn't changed, do nothing.
2332 (when (not (string= input old-input))
2333 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2334 (insert
2335 (python-shell-font-lock-with-font-lock-buffer
2336 (delete-region (line-beginning-position)
2337 (line-end-position))
2338 (insert input)
2339 ;; Ensure buffer is fontified, keeping it
2340 ;; compatible with Emacs < 24.4.
2341 (if (fboundp 'font-lock-ensure)
2342 (funcall 'font-lock-ensure)
2343 (font-lock-default-fontify-buffer))
2344 ;; Replace FACE text properties with FONT-LOCK-FACE so
2345 ;; they are not overwritten by comint buffer's font lock.
2346 (python-util-text-properties-replace-name
2347 'face 'font-lock-face)
2348 (buffer-substring (line-beginning-position)
2349 (line-end-position))))
2350 (goto-char current-point))))))
2352 (defun python-shell-font-lock-turn-on (&optional msg)
2353 "Turn on shell font-lock.
2354 With argument MSG show activation message."
2355 (interactive "p")
2356 (python-shell-with-shell-buffer
2357 (python-shell-font-lock-kill-buffer)
2358 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2359 (add-hook 'post-command-hook
2360 #'python-shell-font-lock-post-command-hook nil 'local)
2361 (add-hook 'kill-buffer-hook
2362 #'python-shell-font-lock-kill-buffer nil 'local)
2363 (add-hook 'comint-output-filter-functions
2364 #'python-shell-font-lock-comint-output-filter-function
2365 'append 'local)
2366 (when msg
2367 (message "Shell font-lock is enabled"))))
2369 (defun python-shell-font-lock-turn-off (&optional msg)
2370 "Turn off shell font-lock.
2371 With argument MSG show deactivation message."
2372 (interactive "p")
2373 (python-shell-with-shell-buffer
2374 (python-shell-font-lock-kill-buffer)
2375 (when (python-util-comint-last-prompt)
2376 ;; Cleanup current fontification
2377 (remove-text-properties
2378 (cdr (python-util-comint-last-prompt))
2379 (line-end-position)
2380 '(face nil font-lock-face nil)))
2381 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2382 (remove-hook 'post-command-hook
2383 #'python-shell-font-lock-post-command-hook'local)
2384 (remove-hook 'kill-buffer-hook
2385 #'python-shell-font-lock-kill-buffer 'local)
2386 (remove-hook 'comint-output-filter-functions
2387 #'python-shell-font-lock-comint-output-filter-function
2388 'local)
2389 (when msg
2390 (message "Shell font-lock is disabled"))))
2392 (defun python-shell-font-lock-toggle (&optional msg)
2393 "Toggle font-lock for shell.
2394 With argument MSG show activation/deactivation message."
2395 (interactive "p")
2396 (python-shell-with-shell-buffer
2397 (set (make-local-variable 'python-shell-font-lock-enable)
2398 (not python-shell-font-lock-enable))
2399 (if python-shell-font-lock-enable
2400 (python-shell-font-lock-turn-on msg)
2401 (python-shell-font-lock-turn-off msg))
2402 python-shell-font-lock-enable))
2404 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2405 "Major mode for Python inferior process.
2406 Runs a Python interpreter as a subprocess of Emacs, with Python
2407 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2408 and `python-shell-interpreter-args' control which Python
2409 interpreter is run. Variables
2410 `python-shell-prompt-regexp',
2411 `python-shell-prompt-output-regexp',
2412 `python-shell-prompt-block-regexp',
2413 `python-shell-font-lock-enable',
2414 `python-shell-completion-setup-code',
2415 `python-shell-completion-string-code',
2416 `python-eldoc-setup-code', `python-eldoc-string-code',
2417 `python-ffap-setup-code' and `python-ffap-string-code' can
2418 customize this mode for different Python interpreters.
2420 This mode resets `comint-output-filter-functions' locally, so you
2421 may want to re-add custom functions to it using the
2422 `inferior-python-mode-hook'.
2424 You can also add additional setup code to be run at
2425 initialization of the interpreter via `python-shell-setup-codes'
2426 variable.
2428 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2429 (let ((interpreter python-shell-interpreter)
2430 (args python-shell-interpreter-args))
2431 (when python-shell--parent-buffer
2432 (python-util-clone-local-variables python-shell--parent-buffer))
2433 ;; Users can override default values for these vars when calling
2434 ;; `run-python'. This ensures new values let-bound in
2435 ;; `python-shell-make-comint' are locally set.
2436 (set (make-local-variable 'python-shell-interpreter) interpreter)
2437 (set (make-local-variable 'python-shell-interpreter-args) args))
2438 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2439 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2440 (python-shell-prompt-set-calculated-regexps)
2441 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2442 (set (make-local-variable 'comint-prompt-read-only) t)
2443 (setq mode-line-process '(":%s"))
2444 (set (make-local-variable 'comint-output-filter-functions)
2445 '(ansi-color-process-output
2446 python-pdbtrack-comint-output-filter-function
2447 python-comint-postoutput-scroll-to-bottom))
2448 (set (make-local-variable 'compilation-error-regexp-alist)
2449 python-shell-compilation-regexp-alist)
2450 (add-hook 'completion-at-point-functions
2451 #'python-shell-completion-at-point nil 'local)
2452 (define-key inferior-python-mode-map "\t"
2453 'python-shell-completion-complete-or-indent)
2454 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2455 (make-local-variable 'python-pdbtrack-tracked-buffer)
2456 (make-local-variable 'python-shell-internal-last-output)
2457 (when python-shell-font-lock-enable
2458 (python-shell-font-lock-turn-on))
2459 (compilation-shell-minor-mode 1)
2460 (python-shell-accept-process-output
2461 (get-buffer-process (current-buffer))))
2463 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
2464 "Create a Python shell comint buffer.
2465 CMD is the Python command to be executed and PROC-NAME is the
2466 process name the comint buffer will get. After the comint buffer
2467 is created the `inferior-python-mode' is activated. When
2468 optional argument POP is non-nil the buffer is shown. When
2469 optional argument INTERNAL is non-nil this process is run on a
2470 buffer with a name that starts with a space, following the Emacs
2471 convention for temporary/internal buffers, and also makes sure
2472 the user is not queried for confirmation when the process is
2473 killed."
2474 (save-excursion
2475 (let* ((proc-buffer-name
2476 (format (if (not internal) "*%s*" " *%s*") proc-name))
2477 (process-environment (python-shell-calculate-process-environment))
2478 (exec-path (python-shell-calculate-exec-path)))
2479 (when (not (comint-check-proc proc-buffer-name))
2480 (let* ((cmdlist (split-string-and-unquote cmd))
2481 (interpreter (car cmdlist))
2482 (args (cdr cmdlist))
2483 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2484 interpreter nil args))
2485 (python-shell--parent-buffer (current-buffer))
2486 (process (get-buffer-process buffer))
2487 ;; As the user may have overridden default values for
2488 ;; these vars on `run-python', let-binding them allows
2489 ;; to have the new right values in all setup code
2490 ;; that's is done in `inferior-python-mode', which is
2491 ;; important, especially for prompt detection.
2492 (python-shell-interpreter interpreter)
2493 (python-shell-interpreter-args
2494 (mapconcat #'identity args " ")))
2495 (with-current-buffer buffer
2496 (inferior-python-mode))
2497 (and pop (pop-to-buffer buffer t))
2498 (and internal (set-process-query-on-exit-flag process nil))))
2499 proc-buffer-name)))
2501 ;;;###autoload
2502 (defun run-python (&optional cmd dedicated show)
2503 "Run an inferior Python process.
2504 Input and output via buffer named after
2505 `python-shell-buffer-name'. If there is a process already
2506 running in that buffer, just switch to it.
2508 Argument CMD defaults to `python-shell-calculate-command' return
2509 value. When called interactively with `prefix-arg', it allows
2510 the user to edit such value and choose whether the interpreter
2511 should be DEDICATED for the current buffer. When numeric prefix
2512 arg is other than 0 or 4 do not SHOW.
2514 Runs the hook `inferior-python-mode-hook' after
2515 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2516 process buffer for a list of commands.)"
2517 (interactive
2518 (if current-prefix-arg
2519 (list
2520 (read-shell-command "Run Python: " (python-shell-calculate-command))
2521 (y-or-n-p "Make dedicated process? ")
2522 (= (prefix-numeric-value current-prefix-arg) 4))
2523 (list (python-shell-calculate-command) nil t)))
2524 (python-shell-make-comint
2525 (or cmd (python-shell-calculate-command))
2526 (python-shell-get-process-name dedicated) show)
2527 dedicated)
2529 (defun run-python-internal ()
2530 "Run an inferior Internal Python process.
2531 Input and output via buffer named after
2532 `python-shell-internal-buffer-name' and what
2533 `python-shell-internal-get-process-name' returns.
2535 This new kind of shell is intended to be used for generic
2536 communication related to defined configurations; the main
2537 difference with global or dedicated shells is that these ones are
2538 attached to a configuration, not a buffer. This means that can
2539 be used for example to retrieve the sys.path and other stuff,
2540 without messing with user shells. Note that
2541 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2542 are set to nil for these shells, so setup codes are not sent at
2543 startup."
2544 (let ((python-shell-font-lock-enable nil)
2545 (inferior-python-mode-hook nil))
2546 (get-buffer-process
2547 (python-shell-make-comint
2548 (python-shell-calculate-command)
2549 (python-shell-internal-get-process-name) nil t))))
2551 (defun python-shell-get-buffer ()
2552 "Return inferior Python buffer for current buffer.
2553 If current buffer is in `inferior-python-mode', return it."
2554 (if (derived-mode-p 'inferior-python-mode)
2555 (current-buffer)
2556 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2557 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2558 (global-proc-name (python-shell-get-process-name nil))
2559 (global-proc-buffer-name (format "*%s*" global-proc-name))
2560 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2561 (global-running (comint-check-proc global-proc-buffer-name)))
2562 ;; Always prefer dedicated
2563 (or (and dedicated-running dedicated-proc-buffer-name)
2564 (and global-running global-proc-buffer-name)))))
2566 (defun python-shell-get-process ()
2567 "Return inferior Python process for current buffer."
2568 (get-buffer-process (python-shell-get-buffer)))
2570 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2571 "Get or create an inferior Python process for current buffer and return it.
2572 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2573 are used to start the shell. If those arguments are not
2574 provided, `run-python' is called interactively and the user will
2575 be asked for their values."
2576 (let ((shell-process (python-shell-get-process)))
2577 (when (not shell-process)
2578 (if (not cmd)
2579 ;; XXX: Refactor code such that calling `run-python'
2580 ;; interactively is not needed anymore.
2581 (call-interactively 'run-python)
2582 (run-python cmd dedicated show)))
2583 (or shell-process (python-shell-get-process))))
2585 (defvar python-shell-internal-buffer nil
2586 "Current internal shell buffer for the current buffer.
2587 This is really not necessary at all for the code to work but it's
2588 there for compatibility with CEDET.")
2590 (defvar python-shell-internal-last-output nil
2591 "Last output captured by the internal shell.
2592 This is really not necessary at all for the code to work but it's
2593 there for compatibility with CEDET.")
2595 (defun python-shell-internal-get-or-create-process ()
2596 "Get or create an inferior Internal Python process."
2597 (let ((proc-name (python-shell-internal-get-process-name)))
2598 (if (process-live-p proc-name)
2599 (get-process proc-name)
2600 (run-python-internal))))
2602 (define-obsolete-function-alias
2603 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2605 (define-obsolete-variable-alias
2606 'python-buffer 'python-shell-internal-buffer "24.3")
2608 (define-obsolete-variable-alias
2609 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2611 (defun python-shell--save-temp-file (string)
2612 (let* ((temporary-file-directory
2613 (if (file-remote-p default-directory)
2614 (concat (file-remote-p default-directory) "/tmp")
2615 temporary-file-directory))
2616 (temp-file-name (make-temp-file "py"))
2617 ;; XXX: Python's built-in compile function accepts utf-8 as
2618 ;; input so there's no need to enforce a coding cookie. In
2619 ;; the future making `coding-system-for-write' match the
2620 ;; current buffer's coding may be a good idea.
2621 (coding-system-for-write 'utf-8))
2622 (with-temp-file temp-file-name
2623 (insert string)
2624 (delete-trailing-whitespace))
2625 temp-file-name))
2627 (defun python-shell-send-string (string &optional process)
2628 "Send STRING to inferior Python PROCESS."
2629 (interactive "sPython command: ")
2630 (let ((process (or process (python-shell-get-or-create-process))))
2631 (if (string-match ".\n+." string) ;Multiline.
2632 (let* ((temp-file-name (python-shell--save-temp-file string))
2633 (file-name (or (buffer-file-name) temp-file-name)))
2634 (python-shell-send-file file-name process temp-file-name t))
2635 (comint-send-string process string)
2636 (when (or (not (string-match "\n\\'" string))
2637 (string-match "\n[ \t].*\n?\\'" string))
2638 (comint-send-string process "\n")))))
2640 (defvar python-shell-output-filter-in-progress nil)
2641 (defvar python-shell-output-filter-buffer nil)
2643 (defun python-shell-output-filter (string)
2644 "Filter used in `python-shell-send-string-no-output' to grab output.
2645 STRING is the output received to this point from the process.
2646 This filter saves received output from the process in
2647 `python-shell-output-filter-buffer' and stops receiving it after
2648 detecting a prompt at the end of the buffer."
2649 (setq
2650 string (ansi-color-filter-apply string)
2651 python-shell-output-filter-buffer
2652 (concat python-shell-output-filter-buffer string))
2653 (when (python-shell-comint-end-of-output-p
2654 python-shell-output-filter-buffer)
2655 ;; Output ends when `python-shell-output-filter-buffer' contains
2656 ;; the prompt attached at the end of it.
2657 (setq python-shell-output-filter-in-progress nil
2658 python-shell-output-filter-buffer
2659 (substring python-shell-output-filter-buffer
2660 0 (match-beginning 0)))
2661 (when (string-match
2662 python-shell--prompt-calculated-output-regexp
2663 python-shell-output-filter-buffer)
2664 ;; Some shells, like IPython might append a prompt before the
2665 ;; output, clean that.
2666 (setq python-shell-output-filter-buffer
2667 (substring python-shell-output-filter-buffer (match-end 0)))))
2670 (defun python-shell-send-string-no-output (string &optional process)
2671 "Send STRING to PROCESS and inhibit output.
2672 Return the output."
2673 (let ((process (or process (python-shell-get-or-create-process)))
2674 (comint-preoutput-filter-functions
2675 '(python-shell-output-filter))
2676 (python-shell-output-filter-in-progress t)
2677 (inhibit-quit t))
2679 (with-local-quit
2680 (python-shell-send-string string process)
2681 (while python-shell-output-filter-in-progress
2682 ;; `python-shell-output-filter' takes care of setting
2683 ;; `python-shell-output-filter-in-progress' to NIL after it
2684 ;; detects end of output.
2685 (accept-process-output process))
2686 (prog1
2687 python-shell-output-filter-buffer
2688 (setq python-shell-output-filter-buffer nil)))
2689 (with-current-buffer (process-buffer process)
2690 (comint-interrupt-subjob)))))
2692 (defun python-shell-internal-send-string (string)
2693 "Send STRING to the Internal Python interpreter.
2694 Returns the output. See `python-shell-send-string-no-output'."
2695 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2696 ;; updated to support this new mode.
2697 (setq python-shell-internal-last-output
2698 (python-shell-send-string-no-output
2699 ;; Makes this function compatible with the old
2700 ;; python-send-receive. (At least for CEDET).
2701 (replace-regexp-in-string "_emacs_out +" "" string)
2702 (python-shell-internal-get-or-create-process))))
2704 (define-obsolete-function-alias
2705 'python-send-receive 'python-shell-internal-send-string "24.3")
2707 (define-obsolete-function-alias
2708 'python-send-string 'python-shell-internal-send-string "24.3")
2710 (defun python-shell-buffer-substring (start end &optional nomain)
2711 "Send buffer substring from START to END formatted for shell.
2712 This is a wrapper over `buffer-substring' that takes care of
2713 different transformations for the code sent to be evaluated in
2714 the python shell:
2715 1. When optional argument NOMAIN is non-nil everything under an
2716 \"if __name__ == '__main__'\" block will be removed.
2717 2. When a subregion of the buffer is sent, it takes care of
2718 appending extra empty lines so tracebacks are correct.
2719 3. Wraps indented regions under an \"if True:\" block so the
2720 interpreter evaluates them correctly."
2721 (let ((substring (buffer-substring-no-properties start end))
2722 (fillstr (make-string (1- (line-number-at-pos start)) ?\n))
2723 (toplevel-block-p (save-excursion
2724 (goto-char start)
2725 (or (zerop (line-number-at-pos start))
2726 (progn
2727 (python-util-forward-comment 1)
2728 (zerop (current-indentation)))))))
2729 (with-temp-buffer
2730 (python-mode)
2731 (if fillstr (insert fillstr))
2732 (insert substring)
2733 (goto-char (point-min))
2734 (when (not toplevel-block-p)
2735 (insert "if True:")
2736 (delete-region (point) (line-end-position)))
2737 (when nomain
2738 (let* ((if-name-main-start-end
2739 (and nomain
2740 (save-excursion
2741 (when (python-nav-if-name-main)
2742 (cons (point)
2743 (progn (python-nav-forward-sexp-safe)
2744 (point)))))))
2745 ;; Oh destructuring bind, how I miss you.
2746 (if-name-main-start (car if-name-main-start-end))
2747 (if-name-main-end (cdr if-name-main-start-end)))
2748 (when if-name-main-start-end
2749 (goto-char if-name-main-start)
2750 (delete-region if-name-main-start if-name-main-end)
2751 (insert
2752 (make-string
2753 (- (line-number-at-pos if-name-main-end)
2754 (line-number-at-pos if-name-main-start)) ?\n)))))
2755 (buffer-substring-no-properties (point-min) (point-max)))))
2757 (defun python-shell-send-region (start end &optional nomain)
2758 "Send the region delimited by START and END to inferior Python process."
2759 (interactive "r")
2760 (let* ((string (python-shell-buffer-substring start end nomain))
2761 (process (python-shell-get-or-create-process))
2762 (_ (string-match "\\`\n*\\(.*\\)" string)))
2763 (message "Sent: %s..." (match-string 1 string))
2764 (python-shell-send-string string process)))
2766 (defun python-shell-send-buffer (&optional arg)
2767 "Send the entire buffer to inferior Python process.
2768 With prefix ARG allow execution of code inside blocks delimited
2769 by \"if __name__== '__main__':\"."
2770 (interactive "P")
2771 (save-restriction
2772 (widen)
2773 (python-shell-send-region (point-min) (point-max) (not arg))))
2775 (defun python-shell-send-defun (arg)
2776 "Send the current defun to inferior Python process.
2777 When argument ARG is non-nil do not include decorators."
2778 (interactive "P")
2779 (save-excursion
2780 (python-shell-send-region
2781 (progn
2782 (end-of-line 1)
2783 (while (and (or (python-nav-beginning-of-defun)
2784 (beginning-of-line 1))
2785 (> (current-indentation) 0)))
2786 (when (not arg)
2787 (while (and (forward-line -1)
2788 (looking-at (python-rx decorator))))
2789 (forward-line 1))
2790 (point-marker))
2791 (progn
2792 (or (python-nav-end-of-defun)
2793 (end-of-line 1))
2794 (point-marker)))))
2796 (defun python-shell-send-file (file-name &optional process temp-file-name
2797 delete)
2798 "Send FILE-NAME to inferior Python PROCESS.
2799 If TEMP-FILE-NAME is passed then that file is used for processing
2800 instead, while internally the shell will continue to use FILE-NAME.
2801 If DELETE is non-nil, delete the file afterwards."
2802 (interactive "fFile to send: ")
2803 (let* ((process (or process (python-shell-get-or-create-process)))
2804 (temp-file-name (when temp-file-name
2805 (expand-file-name
2806 (or (file-remote-p temp-file-name 'localname)
2807 temp-file-name))))
2808 (file-name (or (when file-name
2809 (expand-file-name
2810 (or (file-remote-p file-name 'localname)
2811 file-name)))
2812 temp-file-name)))
2813 (when (not file-name)
2814 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2815 (python-shell-send-string
2816 (format
2817 (concat "__pyfile = open('''%s''');"
2818 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2819 "__pyfile.close()%s")
2820 (or temp-file-name file-name) file-name
2821 (if delete (format "; import os; os.remove('''%s''')"
2822 (or temp-file-name file-name))
2823 ""))
2824 process)))
2826 (defun python-shell-switch-to-shell ()
2827 "Switch to inferior Python process buffer."
2828 (interactive)
2829 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2831 (defun python-shell-send-setup-code ()
2832 "Send all setup code for shell.
2833 This function takes the list of setup code to send from the
2834 `python-shell-setup-codes' list."
2835 (let ((process (python-shell-get-process))
2836 (code (concat
2837 (mapconcat
2838 (lambda (elt)
2839 (cond ((stringp elt) elt)
2840 ((symbolp elt) (symbol-value elt))
2841 (t "")))
2842 python-shell-setup-codes
2843 "\n\n")
2844 "\n\nprint ('python.el: sent setup code')")))
2845 (python-shell-send-string code process)
2846 (python-shell-accept-process-output process)))
2848 (add-hook 'inferior-python-mode-hook
2849 #'python-shell-send-setup-code)
2852 ;;; Shell completion
2854 (defcustom python-shell-completion-setup-code
2855 "try:
2856 import __builtin__
2857 except ImportError:
2858 # Python 3
2859 import builtins as __builtin__
2860 try:
2861 import readline, rlcompleter
2862 except:
2863 def __PYTHON_EL_get_completions(text):
2864 return []
2865 else:
2866 def __PYTHON_EL_get_completions(text):
2867 builtins = dir(__builtin__)
2868 completions = []
2869 try:
2870 splits = text.split()
2871 is_module = splits and splits[0] in ('from', 'import')
2872 is_ipython = ('__IPYTHON__' in builtins or
2873 '__IPYTHON__active' in builtins)
2874 if is_module:
2875 from IPython.core.completerlib import module_completion
2876 completions = module_completion(text.strip())
2877 elif is_ipython and '__IP' in builtins:
2878 completions = __IP.complete(text)
2879 elif is_ipython and 'get_ipython' in builtins:
2880 completions = get_ipython().Completer.all_completions(text)
2881 else:
2882 i = 0
2883 while True:
2884 res = readline.get_completer()(text, i)
2885 if not res:
2886 break
2887 i += 1
2888 completions.append(res)
2889 except:
2890 pass
2891 return completions"
2892 "Code used to setup completion in inferior Python processes."
2893 :type 'string
2894 :group 'python)
2896 (defcustom python-shell-completion-string-code
2897 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2898 "Python code used to get a string of completions separated by semicolons.
2899 The string passed to the function is the current python name or
2900 the full statement in the case of imports."
2901 :type 'string
2902 :group 'python)
2904 (define-obsolete-variable-alias
2905 'python-shell-completion-module-string-code
2906 'python-shell-completion-string-code
2907 "24.4"
2908 "Completion string code must also autocomplete modules.")
2910 (define-obsolete-variable-alias
2911 'python-shell-completion-pdb-string-code
2912 'python-shell-completion-string-code
2913 "25.1"
2914 "Completion string code must work for (i)pdb.")
2916 (defun python-shell-completion-get-completions (process import input)
2917 "Do completion at point using PROCESS for IMPORT or INPUT.
2918 When IMPORT is non-nil takes precedence over INPUT for
2919 completion."
2920 (with-current-buffer (process-buffer process)
2921 (let* ((prompt
2922 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2923 (buffer-substring-no-properties
2924 (car prompt-boundaries) (cdr prompt-boundaries))))
2925 (completion-code
2926 ;; Check whether a prompt matches a pdb string, an import
2927 ;; statement or just the standard prompt and use the
2928 ;; correct python-shell-completion-*-code string
2929 (cond ((and (string-match
2930 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2931 ;; Since there are no guarantees the user will remain
2932 ;; in the same context where completion code was sent
2933 ;; (e.g. user steps into a function), safeguard
2934 ;; resending completion setup continuously.
2935 (concat python-shell-completion-setup-code
2936 "\nprint (" python-shell-completion-string-code ")"))
2937 ((string-match
2938 python-shell--prompt-calculated-input-regexp prompt)
2939 python-shell-completion-string-code)
2940 (t nil)))
2941 (subject (or import input)))
2942 (and completion-code
2943 (> (length input) 0)
2944 (let ((completions
2945 (python-util-strip-string
2946 (python-shell-send-string-no-output
2947 (format completion-code subject) process))))
2948 (and (> (length completions) 2)
2949 (split-string completions
2950 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2952 (defun python-shell-completion-at-point (&optional process)
2953 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2954 Optional argument PROCESS forces completions to be retrieved
2955 using that one instead of current buffer's process."
2956 (setq process (or process (get-buffer-process (current-buffer))))
2957 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2958 (import-statement
2959 (when (string-match-p
2960 (rx (* space) word-start (or "from" "import") word-end space)
2961 (buffer-substring-no-properties last-prompt-end (point)))
2962 (buffer-substring-no-properties last-prompt-end (point))))
2963 (start
2964 (save-excursion
2965 (if (not (re-search-backward
2966 (python-rx
2967 (or whitespace open-paren close-paren string-delimiter))
2968 last-prompt-end
2969 t 1))
2970 last-prompt-end
2971 (forward-char (length (match-string-no-properties 0)))
2972 (point))))
2973 (end (point)))
2974 (list start end
2975 (completion-table-dynamic
2976 (apply-partially
2977 #'python-shell-completion-get-completions
2978 process import-statement)))))
2980 (define-obsolete-function-alias
2981 'python-shell-completion-complete-at-point
2982 'python-shell-completion-at-point
2983 "25.1")
2985 (defun python-shell-completion-complete-or-indent ()
2986 "Complete or indent depending on the context.
2987 If content before pointer is all whitespace, indent.
2988 If not try to complete."
2989 (interactive)
2990 (if (string-match "^[[:space:]]*$"
2991 (buffer-substring (comint-line-beginning-position)
2992 (point)))
2993 (indent-for-tab-command)
2994 (completion-at-point)))
2997 ;;; PDB Track integration
2999 (defcustom python-pdbtrack-activate t
3000 "Non-nil makes Python shell enable pdbtracking."
3001 :type 'boolean
3002 :group 'python
3003 :safe 'booleanp)
3005 (defcustom python-pdbtrack-stacktrace-info-regexp
3006 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3007 "Regular expression matching stacktrace information.
3008 Used to extract the current line and module being inspected."
3009 :type 'string
3010 :group 'python
3011 :safe 'stringp)
3013 (defvar python-pdbtrack-tracked-buffer nil
3014 "Variable containing the value of the current tracked buffer.
3015 Never set this variable directly, use
3016 `python-pdbtrack-set-tracked-buffer' instead.")
3018 (defvar python-pdbtrack-buffers-to-kill nil
3019 "List of buffers to be deleted after tracking finishes.")
3021 (defun python-pdbtrack-set-tracked-buffer (file-name)
3022 "Set the buffer for FILE-NAME as the tracked buffer.
3023 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3024 Returns the tracked buffer."
3025 (let ((file-buffer (get-file-buffer
3026 (concat (file-remote-p default-directory)
3027 file-name))))
3028 (if file-buffer
3029 (setq python-pdbtrack-tracked-buffer file-buffer)
3030 (setq file-buffer (find-file-noselect file-name))
3031 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3032 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3033 file-buffer))
3035 (defun python-pdbtrack-comint-output-filter-function (output)
3036 "Move overlay arrow to current pdb line in tracked buffer.
3037 Argument OUTPUT is a string with the output from the comint process."
3038 (when (and python-pdbtrack-activate (not (string= output "")))
3039 (let* ((full-output (ansi-color-filter-apply
3040 (buffer-substring comint-last-input-end (point-max))))
3041 (line-number)
3042 (file-name
3043 (with-temp-buffer
3044 (insert full-output)
3045 ;; When the debugger encounters a pdb.set_trace()
3046 ;; command, it prints a single stack frame. Sometimes
3047 ;; it prints a bit of extra information about the
3048 ;; arguments of the present function. When ipdb
3049 ;; encounters an exception, it prints the _entire_ stack
3050 ;; trace. To handle all of these cases, we want to find
3051 ;; the _last_ stack frame printed in the most recent
3052 ;; batch of output, then jump to the corresponding
3053 ;; file/line number.
3054 (goto-char (point-max))
3055 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3056 (setq line-number (string-to-number
3057 (match-string-no-properties 2)))
3058 (match-string-no-properties 1)))))
3059 (if (and file-name line-number)
3060 (let* ((tracked-buffer
3061 (python-pdbtrack-set-tracked-buffer file-name))
3062 (shell-buffer (current-buffer))
3063 (tracked-buffer-window (get-buffer-window tracked-buffer))
3064 (tracked-buffer-line-pos))
3065 (with-current-buffer tracked-buffer
3066 (set (make-local-variable 'overlay-arrow-string) "=>")
3067 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3068 (setq tracked-buffer-line-pos (progn
3069 (goto-char (point-min))
3070 (forward-line (1- line-number))
3071 (point-marker)))
3072 (when tracked-buffer-window
3073 (set-window-point
3074 tracked-buffer-window tracked-buffer-line-pos))
3075 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3076 (pop-to-buffer tracked-buffer)
3077 (switch-to-buffer-other-window shell-buffer))
3078 (when python-pdbtrack-tracked-buffer
3079 (with-current-buffer python-pdbtrack-tracked-buffer
3080 (set-marker overlay-arrow-position nil))
3081 (mapc #'(lambda (buffer)
3082 (ignore-errors (kill-buffer buffer)))
3083 python-pdbtrack-buffers-to-kill)
3084 (setq python-pdbtrack-tracked-buffer nil
3085 python-pdbtrack-buffers-to-kill nil)))))
3086 output)
3089 ;;; Symbol completion
3091 (defun python-completion-at-point ()
3092 "Function for `completion-at-point-functions' in `python-mode'.
3093 For this to work as best as possible you should call
3094 `python-shell-send-buffer' from time to time so context in
3095 inferior Python process is updated properly."
3096 (let ((process (python-shell-get-process)))
3097 (when process
3098 (python-shell-completion-at-point process))))
3100 (define-obsolete-function-alias
3101 'python-completion-complete-at-point
3102 'python-completion-at-point
3103 "25.1")
3106 ;;; Fill paragraph
3108 (defcustom python-fill-comment-function 'python-fill-comment
3109 "Function to fill comments.
3110 This is the function used by `python-fill-paragraph' to
3111 fill comments."
3112 :type 'symbol
3113 :group 'python)
3115 (defcustom python-fill-string-function 'python-fill-string
3116 "Function to fill strings.
3117 This is the function used by `python-fill-paragraph' to
3118 fill strings."
3119 :type 'symbol
3120 :group 'python)
3122 (defcustom python-fill-decorator-function 'python-fill-decorator
3123 "Function to fill decorators.
3124 This is the function used by `python-fill-paragraph' to
3125 fill decorators."
3126 :type 'symbol
3127 :group 'python)
3129 (defcustom python-fill-paren-function 'python-fill-paren
3130 "Function to fill parens.
3131 This is the function used by `python-fill-paragraph' to
3132 fill parens."
3133 :type 'symbol
3134 :group 'python)
3136 (defcustom python-fill-docstring-style 'pep-257
3137 "Style used to fill docstrings.
3138 This affects `python-fill-string' behavior with regards to
3139 triple quotes positioning.
3141 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3142 `symmetric', and nil. A value of nil won't care about quotes
3143 position and will treat docstrings a normal string, any other
3144 value may result in one of the following docstring styles:
3146 `django':
3148 \"\"\"
3149 Process foo, return bar.
3150 \"\"\"
3152 \"\"\"
3153 Process foo, return bar.
3155 If processing fails throw ProcessingError.
3156 \"\"\"
3158 `onetwo':
3160 \"\"\"Process foo, return bar.\"\"\"
3162 \"\"\"
3163 Process foo, return bar.
3165 If processing fails throw ProcessingError.
3167 \"\"\"
3169 `pep-257':
3171 \"\"\"Process foo, return bar.\"\"\"
3173 \"\"\"Process foo, return bar.
3175 If processing fails throw ProcessingError.
3177 \"\"\"
3179 `pep-257-nn':
3181 \"\"\"Process foo, return bar.\"\"\"
3183 \"\"\"Process foo, return bar.
3185 If processing fails throw ProcessingError.
3186 \"\"\"
3188 `symmetric':
3190 \"\"\"Process foo, return bar.\"\"\"
3192 \"\"\"
3193 Process foo, return bar.
3195 If processing fails throw ProcessingError.
3196 \"\"\""
3197 :type '(choice
3198 (const :tag "Don't format docstrings" nil)
3199 (const :tag "Django's coding standards style." django)
3200 (const :tag "One newline and start and Two at end style." onetwo)
3201 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3202 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3203 (const :tag "Symmetric style." symmetric))
3204 :group 'python
3205 :safe (lambda (val)
3206 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3208 (defun python-fill-paragraph (&optional justify)
3209 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3210 If any of the current line is in or at the end of a multi-line string,
3211 fill the string or the paragraph of it that point is in, preserving
3212 the string's indentation.
3213 Optional argument JUSTIFY defines if the paragraph should be justified."
3214 (interactive "P")
3215 (save-excursion
3216 (cond
3217 ;; Comments
3218 ((python-syntax-context 'comment)
3219 (funcall python-fill-comment-function justify))
3220 ;; Strings/Docstrings
3221 ((save-excursion (or (python-syntax-context 'string)
3222 (equal (string-to-syntax "|")
3223 (syntax-after (point)))))
3224 (funcall python-fill-string-function justify))
3225 ;; Decorators
3226 ((equal (char-after (save-excursion
3227 (python-nav-beginning-of-statement))) ?@)
3228 (funcall python-fill-decorator-function justify))
3229 ;; Parens
3230 ((or (python-syntax-context 'paren)
3231 (looking-at (python-rx open-paren))
3232 (save-excursion
3233 (skip-syntax-forward "^(" (line-end-position))
3234 (looking-at (python-rx open-paren))))
3235 (funcall python-fill-paren-function justify))
3236 (t t))))
3238 (defun python-fill-comment (&optional justify)
3239 "Comment fill function for `python-fill-paragraph'.
3240 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3241 (fill-comment-paragraph justify))
3243 (defun python-fill-string (&optional justify)
3244 "String fill function for `python-fill-paragraph'.
3245 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3246 (let* ((str-start-pos
3247 (set-marker
3248 (make-marker)
3249 (or (python-syntax-context 'string)
3250 (and (equal (string-to-syntax "|")
3251 (syntax-after (point)))
3252 (point)))))
3253 (num-quotes (python-syntax-count-quotes
3254 (char-after str-start-pos) str-start-pos))
3255 (str-end-pos
3256 (save-excursion
3257 (goto-char (+ str-start-pos num-quotes))
3258 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3259 (goto-char (point-max)))
3260 (point-marker)))
3261 (multi-line-p
3262 ;; Docstring styles may vary for oneliners and multi-liners.
3263 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3264 (delimiters-style
3265 (pcase python-fill-docstring-style
3266 ;; delimiters-style is a cons cell with the form
3267 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3268 ;; is NIL means to not add any newlines for start or end
3269 ;; of docstring. See `python-fill-docstring-style' for a
3270 ;; graphic idea of each style.
3271 (`django (cons 1 1))
3272 (`onetwo (and multi-line-p (cons 1 2)))
3273 (`pep-257 (and multi-line-p (cons nil 2)))
3274 (`pep-257-nn (and multi-line-p (cons nil 1)))
3275 (`symmetric (and multi-line-p (cons 1 1)))))
3276 (docstring-p (save-excursion
3277 ;; Consider docstrings those strings which
3278 ;; start on a line by themselves.
3279 (python-nav-beginning-of-statement)
3280 (and (= (point) str-start-pos))))
3281 (fill-paragraph-function))
3282 (save-restriction
3283 (narrow-to-region str-start-pos str-end-pos)
3284 (fill-paragraph justify))
3285 (save-excursion
3286 (when (and docstring-p python-fill-docstring-style)
3287 ;; Add the number of newlines indicated by the selected style
3288 ;; at the start of the docstring.
3289 (goto-char (+ str-start-pos num-quotes))
3290 (delete-region (point) (progn
3291 (skip-syntax-forward "> ")
3292 (point)))
3293 (and (car delimiters-style)
3294 (or (newline (car delimiters-style)) t)
3295 ;; Indent only if a newline is added.
3296 (indent-according-to-mode))
3297 ;; Add the number of newlines indicated by the selected style
3298 ;; at the end of the docstring.
3299 (goto-char (if (not (= str-end-pos (point-max)))
3300 (- str-end-pos num-quotes)
3301 str-end-pos))
3302 (delete-region (point) (progn
3303 (skip-syntax-backward "> ")
3304 (point)))
3305 (and (cdr delimiters-style)
3306 ;; Add newlines only if string ends.
3307 (not (= str-end-pos (point-max)))
3308 (or (newline (cdr delimiters-style)) t)
3309 ;; Again indent only if a newline is added.
3310 (indent-according-to-mode))))) t)
3312 (defun python-fill-decorator (&optional _justify)
3313 "Decorator fill function for `python-fill-paragraph'.
3314 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3317 (defun python-fill-paren (&optional justify)
3318 "Paren fill function for `python-fill-paragraph'.
3319 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3320 (save-restriction
3321 (narrow-to-region (progn
3322 (while (python-syntax-context 'paren)
3323 (goto-char (1- (point))))
3324 (line-beginning-position))
3325 (progn
3326 (when (not (python-syntax-context 'paren))
3327 (end-of-line)
3328 (when (not (python-syntax-context 'paren))
3329 (skip-syntax-backward "^)")))
3330 (while (and (python-syntax-context 'paren)
3331 (not (eobp)))
3332 (goto-char (1+ (point))))
3333 (point)))
3334 (let ((paragraph-start "\f\\|[ \t]*$")
3335 (paragraph-separate ",")
3336 (fill-paragraph-function))
3337 (goto-char (point-min))
3338 (fill-paragraph justify))
3339 (while (not (eobp))
3340 (forward-line 1)
3341 (python-indent-line)
3342 (goto-char (line-end-position))))
3346 ;;; Skeletons
3348 (defcustom python-skeleton-autoinsert nil
3349 "Non-nil means template skeletons will be automagically inserted.
3350 This happens when pressing \"if<SPACE>\", for example, to prompt for
3351 the if condition."
3352 :type 'boolean
3353 :group 'python
3354 :safe 'booleanp)
3356 (define-obsolete-variable-alias
3357 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3359 (defvar python-skeleton-available '()
3360 "Internal list of available skeletons.")
3362 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3363 "Abbrev table for Python mode skeletons."
3364 :case-fixed t
3365 ;; Allow / inside abbrevs.
3366 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3367 ;; Only expand in code.
3368 :enable-function (lambda ()
3369 (and
3370 (not (python-syntax-comment-or-string-p))
3371 python-skeleton-autoinsert)))
3373 (defmacro python-skeleton-define (name doc &rest skel)
3374 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3375 The skeleton will be bound to python-skeleton-NAME and will
3376 be added to `python-mode-skeleton-abbrev-table'."
3377 (declare (indent 2))
3378 (let* ((name (symbol-name name))
3379 (function-name (intern (concat "python-skeleton-" name))))
3380 `(progn
3381 (define-abbrev python-mode-skeleton-abbrev-table
3382 ,name "" ',function-name :system t)
3383 (setq python-skeleton-available
3384 (cons ',function-name python-skeleton-available))
3385 (define-skeleton ,function-name
3386 ,(or doc
3387 (format "Insert %s statement." name))
3388 ,@skel))))
3390 (define-abbrev-table 'python-mode-abbrev-table ()
3391 "Abbrev table for Python mode."
3392 :parents (list python-mode-skeleton-abbrev-table))
3394 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3395 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3396 The skeleton will be bound to python-skeleton-NAME."
3397 (declare (indent 2))
3398 (let* ((name (symbol-name name))
3399 (function-name (intern (concat "python-skeleton--" name)))
3400 (msg (format
3401 "Add '%s' clause? " name)))
3402 (when (not skel)
3403 (setq skel
3404 `(< ,(format "%s:" name) \n \n
3405 > _ \n)))
3406 `(define-skeleton ,function-name
3407 ,(or doc
3408 (format "Auxiliary skeleton for %s statement." name))
3410 (unless (y-or-n-p ,msg)
3411 (signal 'quit t))
3412 ,@skel)))
3414 (python-define-auxiliary-skeleton else nil)
3416 (python-define-auxiliary-skeleton except nil)
3418 (python-define-auxiliary-skeleton finally nil)
3420 (python-skeleton-define if nil
3421 "Condition: "
3422 "if " str ":" \n
3423 _ \n
3424 ("other condition, %s: "
3426 "elif " str ":" \n
3427 > _ \n nil)
3428 '(python-skeleton--else) | ^)
3430 (python-skeleton-define while nil
3431 "Condition: "
3432 "while " str ":" \n
3433 > _ \n
3434 '(python-skeleton--else) | ^)
3436 (python-skeleton-define for nil
3437 "Iteration spec: "
3438 "for " str ":" \n
3439 > _ \n
3440 '(python-skeleton--else) | ^)
3442 (python-skeleton-define import nil
3443 "Import from module: "
3444 "from " str & " " | -5
3445 "import "
3446 ("Identifier: " str ", ") -2 \n _)
3448 (python-skeleton-define try nil
3450 "try:" \n
3451 > _ \n
3452 ("Exception, %s: "
3454 "except " str ":" \n
3455 > _ \n nil)
3456 resume:
3457 '(python-skeleton--except)
3458 '(python-skeleton--else)
3459 '(python-skeleton--finally) | ^)
3461 (python-skeleton-define def nil
3462 "Function name: "
3463 "def " str "(" ("Parameter, %s: "
3464 (unless (equal ?\( (char-before)) ", ")
3465 str) "):" \n
3466 "\"\"\"" - "\"\"\"" \n
3467 > _ \n)
3469 (python-skeleton-define class nil
3470 "Class name: "
3471 "class " str "(" ("Inheritance, %s: "
3472 (unless (equal ?\( (char-before)) ", ")
3473 str)
3474 & ")" | -1
3475 ":" \n
3476 "\"\"\"" - "\"\"\"" \n
3477 > _ \n)
3479 (defun python-skeleton-add-menu-items ()
3480 "Add menu items to Python->Skeletons menu."
3481 (let ((skeletons (sort python-skeleton-available 'string<)))
3482 (dolist (skeleton skeletons)
3483 (easy-menu-add-item
3484 nil '("Python" "Skeletons")
3485 `[,(format
3486 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3487 ,skeleton t]))))
3489 ;;; FFAP
3491 (defcustom python-ffap-setup-code
3492 "def __FFAP_get_module_path(module):
3493 try:
3494 import os
3495 path = __import__(module).__file__
3496 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3497 path = path[:-1]
3498 return path
3499 except:
3500 return ''"
3501 "Python code to get a module path."
3502 :type 'string
3503 :group 'python)
3505 (defcustom python-ffap-string-code
3506 "__FFAP_get_module_path('''%s''')\n"
3507 "Python code used to get a string with the path of a module."
3508 :type 'string
3509 :group 'python)
3511 (defun python-ffap-module-path (module)
3512 "Function for `ffap-alist' to return path for MODULE."
3513 (let ((process (or
3514 (and (derived-mode-p 'inferior-python-mode)
3515 (get-buffer-process (current-buffer)))
3516 (python-shell-get-process))))
3517 (if (not process)
3519 (let ((module-file
3520 (python-shell-send-string-no-output
3521 (format python-ffap-string-code module) process)))
3522 (when module-file
3523 (substring-no-properties module-file 1 -1))))))
3525 (defvar ffap-alist)
3527 (eval-after-load "ffap"
3528 '(progn
3529 (push '(python-mode . python-ffap-module-path) ffap-alist)
3530 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3533 ;;; Code check
3535 (defcustom python-check-command
3536 "pyflakes"
3537 "Command used to check a Python file."
3538 :type 'string
3539 :group 'python)
3541 (defcustom python-check-buffer-name
3542 "*Python check: %s*"
3543 "Buffer name used for check commands."
3544 :type 'string
3545 :group 'python)
3547 (defvar python-check-custom-command nil
3548 "Internal use.")
3550 (defun python-check (command)
3551 "Check a Python file (default current buffer's file).
3552 Runs COMMAND, a shell command, as if by `compile'.
3553 See `python-check-command' for the default."
3554 (interactive
3555 (list (read-string "Check command: "
3556 (or python-check-custom-command
3557 (concat python-check-command " "
3558 (shell-quote-argument
3560 (let ((name (buffer-file-name)))
3561 (and name
3562 (file-name-nondirectory name)))
3563 "")))))))
3564 (setq python-check-custom-command command)
3565 (save-some-buffers (not compilation-ask-about-save) nil)
3566 (let ((process-environment (python-shell-calculate-process-environment))
3567 (exec-path (python-shell-calculate-exec-path)))
3568 (compilation-start command nil
3569 (lambda (_modename)
3570 (format python-check-buffer-name command)))))
3573 ;;; Eldoc
3575 (defcustom python-eldoc-setup-code
3576 "def __PYDOC_get_help(obj):
3577 try:
3578 import inspect
3579 try:
3580 str_type = basestring
3581 except NameError:
3582 str_type = str
3583 if isinstance(obj, str_type):
3584 obj = eval(obj, globals())
3585 doc = inspect.getdoc(obj)
3586 if not doc and callable(obj):
3587 target = None
3588 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3589 target = obj.__init__
3590 objtype = 'class'
3591 else:
3592 target = obj
3593 objtype = 'def'
3594 if target:
3595 args = inspect.formatargspec(
3596 *inspect.getargspec(target)
3598 name = obj.__name__
3599 doc = '{objtype} {name}{args}'.format(
3600 objtype=objtype, name=name, args=args
3602 else:
3603 doc = doc.splitlines()[0]
3604 except:
3605 doc = ''
3606 print (doc)"
3607 "Python code to setup documentation retrieval."
3608 :type 'string
3609 :group 'python)
3611 (defcustom python-eldoc-string-code
3612 "__PYDOC_get_help('''%s''')\n"
3613 "Python code used to get a string with the documentation of an object."
3614 :type 'string
3615 :group 'python)
3617 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3618 "Internal implementation to get documentation at point.
3619 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3620 returns will be used. If not FORCE-PROCESS is passed what
3621 `python-shell-get-process' returns is used."
3622 (let ((process (or force-process (python-shell-get-process))))
3623 (when process
3624 (let ((input (or force-input
3625 (python-info-current-symbol t))))
3626 (and input
3627 ;; Prevent resizing the echo area when iPython is
3628 ;; enabled. Bug#18794.
3629 (python-util-strip-string
3630 (python-shell-send-string-no-output
3631 (format python-eldoc-string-code input)
3632 process)))))))
3634 (defun python-eldoc-function ()
3635 "`eldoc-documentation-function' for Python.
3636 For this to work as best as possible you should call
3637 `python-shell-send-buffer' from time to time so context in
3638 inferior Python process is updated properly."
3639 (python-eldoc--get-doc-at-point))
3641 (defun python-eldoc-at-point (symbol)
3642 "Get help on SYMBOL using `help'.
3643 Interactively, prompt for symbol."
3644 (interactive
3645 (let ((symbol (python-info-current-symbol t))
3646 (enable-recursive-minibuffers t))
3647 (list (read-string (if symbol
3648 (format "Describe symbol (default %s): " symbol)
3649 "Describe symbol: ")
3650 nil nil symbol))))
3651 (message (python-eldoc--get-doc-at-point symbol)))
3654 ;;; Imenu
3656 (defvar python-imenu-format-item-label-function
3657 'python-imenu-format-item-label
3658 "Imenu function used to format an item label.
3659 It must be a function with two arguments: TYPE and NAME.")
3661 (defvar python-imenu-format-parent-item-label-function
3662 'python-imenu-format-parent-item-label
3663 "Imenu function used to format a parent item label.
3664 It must be a function with two arguments: TYPE and NAME.")
3666 (defvar python-imenu-format-parent-item-jump-label-function
3667 'python-imenu-format-parent-item-jump-label
3668 "Imenu function used to format a parent jump item label.
3669 It must be a function with two arguments: TYPE and NAME.")
3671 (defun python-imenu-format-item-label (type name)
3672 "Return Imenu label for single node using TYPE and NAME."
3673 (format "%s (%s)" name type))
3675 (defun python-imenu-format-parent-item-label (type name)
3676 "Return Imenu label for parent node using TYPE and NAME."
3677 (format "%s..." (python-imenu-format-item-label type name)))
3679 (defun python-imenu-format-parent-item-jump-label (type _name)
3680 "Return Imenu label for parent node jump using TYPE and NAME."
3681 (if (string= type "class")
3682 "*class definition*"
3683 "*function definition*"))
3685 (defun python-imenu--put-parent (type name pos tree)
3686 "Add the parent with TYPE, NAME and POS to TREE."
3687 (let ((label
3688 (funcall python-imenu-format-item-label-function type name))
3689 (jump-label
3690 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3691 (if (not tree)
3692 (cons label pos)
3693 (cons label (cons (cons jump-label pos) tree)))))
3695 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3696 "Recursively build the tree of nested definitions of a node.
3697 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3698 not be passed explicitly unless you know what you are doing."
3699 (setq min-indent (or min-indent 0)
3700 prev-indent (or prev-indent python-indent-offset))
3701 (let* ((pos (python-nav-backward-defun))
3702 (type)
3703 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3704 (let ((split (split-string (match-string-no-properties 0))))
3705 (setq type (car split))
3706 (cadr split))))
3707 (label (when name
3708 (funcall python-imenu-format-item-label-function type name)))
3709 (indent (current-indentation))
3710 (children-indent-limit (+ python-indent-offset min-indent)))
3711 (cond ((not pos)
3712 ;; Nothing found, probably near to bobp.
3713 nil)
3714 ((<= indent min-indent)
3715 ;; The current indentation points that this is a parent
3716 ;; node, add it to the tree and stop recursing.
3717 (python-imenu--put-parent type name pos tree))
3719 (python-imenu--build-tree
3720 min-indent
3721 indent
3722 (if (<= indent children-indent-limit)
3723 ;; This lies within the children indent offset range,
3724 ;; so it's a normal child of its parent (i.e., not
3725 ;; a child of a child).
3726 (cons (cons label pos) tree)
3727 ;; Oh no, a child of a child?! Fear not, we
3728 ;; know how to roll. We recursively parse these by
3729 ;; swapping prev-indent and min-indent plus adding this
3730 ;; newly found item to a fresh subtree. This works, I
3731 ;; promise.
3732 (cons
3733 (python-imenu--build-tree
3734 prev-indent indent (list (cons label pos)))
3735 tree)))))))
3737 (defun python-imenu-create-index ()
3738 "Return tree Imenu alist for the current Python buffer.
3739 Change `python-imenu-format-item-label-function',
3740 `python-imenu-format-parent-item-label-function',
3741 `python-imenu-format-parent-item-jump-label-function' to
3742 customize how labels are formatted."
3743 (goto-char (point-max))
3744 (let ((index)
3745 (tree))
3746 (while (setq tree (python-imenu--build-tree))
3747 (setq index (cons tree index)))
3748 index))
3750 (defun python-imenu-create-flat-index (&optional alist prefix)
3751 "Return flat outline of the current Python buffer for Imenu.
3752 Optional argument ALIST is the tree to be flattened; when nil
3753 `python-imenu-build-index' is used with
3754 `python-imenu-format-parent-item-jump-label-function'
3755 `python-imenu-format-parent-item-label-function'
3756 `python-imenu-format-item-label-function' set to
3757 (lambda (type name) name)
3758 Optional argument PREFIX is used in recursive calls and should
3759 not be passed explicitly.
3761 Converts this:
3763 ((\"Foo\" . 103)
3764 (\"Bar\" . 138)
3765 (\"decorator\"
3766 (\"decorator\" . 173)
3767 (\"wrap\"
3768 (\"wrap\" . 353)
3769 (\"wrapped_f\" . 393))))
3771 To this:
3773 ((\"Foo\" . 103)
3774 (\"Bar\" . 138)
3775 (\"decorator\" . 173)
3776 (\"decorator.wrap\" . 353)
3777 (\"decorator.wrapped_f\" . 393))"
3778 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3779 (apply
3780 'nconc
3781 (mapcar
3782 (lambda (item)
3783 (let ((name (if prefix
3784 (concat prefix "." (car item))
3785 (car item)))
3786 (pos (cdr item)))
3787 (cond ((or (numberp pos) (markerp pos))
3788 (list (cons name pos)))
3789 ((listp pos)
3790 (cons
3791 (cons name (cdar pos))
3792 (python-imenu-create-flat-index (cddr item) name))))))
3793 (or alist
3794 (let* ((fn (lambda (_type name) name))
3795 (python-imenu-format-item-label-function fn)
3796 (python-imenu-format-parent-item-label-function fn)
3797 (python-imenu-format-parent-item-jump-label-function fn))
3798 (python-imenu-create-index))))))
3801 ;;; Misc helpers
3803 (defun python-info-current-defun (&optional include-type)
3804 "Return name of surrounding function with Python compatible dotty syntax.
3805 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3806 This function can be used as the value of `add-log-current-defun-function'
3807 since it returns nil if point is not inside a defun."
3808 (save-restriction
3809 (widen)
3810 (save-excursion
3811 (end-of-line 1)
3812 (let ((names)
3813 (starting-indentation (current-indentation))
3814 (starting-pos (point))
3815 (first-run t)
3816 (last-indent)
3817 (type))
3818 (catch 'exit
3819 (while (python-nav-beginning-of-defun 1)
3820 (when (save-match-data
3821 (and
3822 (or (not last-indent)
3823 (< (current-indentation) last-indent))
3825 (and first-run
3826 (save-excursion
3827 ;; If this is the first run, we may add
3828 ;; the current defun at point.
3829 (setq first-run nil)
3830 (goto-char starting-pos)
3831 (python-nav-beginning-of-statement)
3832 (beginning-of-line 1)
3833 (looking-at-p
3834 python-nav-beginning-of-defun-regexp)))
3835 (< starting-pos
3836 (save-excursion
3837 (let ((min-indent
3838 (+ (current-indentation)
3839 python-indent-offset)))
3840 (if (< starting-indentation min-indent)
3841 ;; If the starting indentation is not
3842 ;; within the min defun indent make the
3843 ;; check fail.
3844 starting-pos
3845 ;; Else go to the end of defun and add
3846 ;; up the current indentation to the
3847 ;; ending position.
3848 (python-nav-end-of-defun)
3849 (+ (point)
3850 (if (>= (current-indentation) min-indent)
3851 (1+ (current-indentation))
3852 0)))))))))
3853 (save-match-data (setq last-indent (current-indentation)))
3854 (if (or (not include-type) type)
3855 (setq names (cons (match-string-no-properties 1) names))
3856 (let ((match (split-string (match-string-no-properties 0))))
3857 (setq type (car match))
3858 (setq names (cons (cadr match) names)))))
3859 ;; Stop searching ASAP.
3860 (and (= (current-indentation) 0) (throw 'exit t))))
3861 (and names
3862 (concat (and type (format "%s " type))
3863 (mapconcat 'identity names ".")))))))
3865 (defun python-info-current-symbol (&optional replace-self)
3866 "Return current symbol using dotty syntax.
3867 With optional argument REPLACE-SELF convert \"self\" to current
3868 parent defun name."
3869 (let ((name
3870 (and (not (python-syntax-comment-or-string-p))
3871 (with-syntax-table python-dotty-syntax-table
3872 (let ((sym (symbol-at-point)))
3873 (and sym
3874 (substring-no-properties (symbol-name sym))))))))
3875 (when name
3876 (if (not replace-self)
3877 name
3878 (let ((current-defun (python-info-current-defun)))
3879 (if (not current-defun)
3880 name
3881 (replace-regexp-in-string
3882 (python-rx line-start word-start "self" word-end ?.)
3883 (concat
3884 (mapconcat 'identity
3885 (butlast (split-string current-defun "\\."))
3886 ".") ".")
3887 name)))))))
3889 (defun python-info-statement-starts-block-p ()
3890 "Return non-nil if current statement opens a block."
3891 (save-excursion
3892 (python-nav-beginning-of-statement)
3893 (looking-at (python-rx block-start))))
3895 (defun python-info-statement-ends-block-p ()
3896 "Return non-nil if point is at end of block."
3897 (let ((end-of-block-pos (save-excursion
3898 (python-nav-end-of-block)))
3899 (end-of-statement-pos (save-excursion
3900 (python-nav-end-of-statement))))
3901 (and end-of-block-pos end-of-statement-pos
3902 (= end-of-block-pos end-of-statement-pos))))
3904 (defun python-info-beginning-of-statement-p ()
3905 "Return non-nil if point is at beginning of statement."
3906 (= (point) (save-excursion
3907 (python-nav-beginning-of-statement)
3908 (point))))
3910 (defun python-info-end-of-statement-p ()
3911 "Return non-nil if point is at end of statement."
3912 (= (point) (save-excursion
3913 (python-nav-end-of-statement)
3914 (point))))
3916 (defun python-info-beginning-of-block-p ()
3917 "Return non-nil if point is at beginning of block."
3918 (and (python-info-beginning-of-statement-p)
3919 (python-info-statement-starts-block-p)))
3921 (defun python-info-end-of-block-p ()
3922 "Return non-nil if point is at end of block."
3923 (and (python-info-end-of-statement-p)
3924 (python-info-statement-ends-block-p)))
3926 (define-obsolete-function-alias
3927 'python-info-closing-block
3928 'python-info-dedenter-opening-block-position "24.4")
3930 (defun python-info-dedenter-opening-block-position ()
3931 "Return the point of the closest block the current line closes.
3932 Returns nil if point is not on a dedenter statement or no opening
3933 block can be detected. The latter case meaning current file is
3934 likely an invalid python file."
3935 (let ((positions (python-info-dedenter-opening-block-positions))
3936 (indentation (current-indentation))
3937 (position))
3938 (while (and (not position)
3939 positions)
3940 (save-excursion
3941 (goto-char (car positions))
3942 (if (<= (current-indentation) indentation)
3943 (setq position (car positions))
3944 (setq positions (cdr positions)))))
3945 position))
3947 (defun python-info-dedenter-opening-block-positions ()
3948 "Return points of blocks the current line may close sorted by closer.
3949 Returns nil if point is not on a dedenter statement or no opening
3950 block can be detected. The latter case meaning current file is
3951 likely an invalid python file."
3952 (save-excursion
3953 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3954 (when dedenter-pos
3955 (goto-char dedenter-pos)
3956 (let* ((pairs '(("elif" "elif" "if")
3957 ("else" "if" "elif" "except" "for" "while")
3958 ("except" "except" "try")
3959 ("finally" "else" "except" "try")))
3960 (dedenter (match-string-no-properties 0))
3961 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
3962 (collected-indentations)
3963 (opening-blocks))
3964 (catch 'exit
3965 (while (python-nav--syntactically
3966 (lambda ()
3967 (re-search-backward (python-rx block-start) nil t))
3968 #'<)
3969 (let ((indentation (current-indentation)))
3970 (when (and (not (memq indentation collected-indentations))
3971 (or (not collected-indentations)
3972 (< indentation (apply #'min collected-indentations))))
3973 (setq collected-indentations
3974 (cons indentation collected-indentations))
3975 (when (member (match-string-no-properties 0)
3976 possible-opening-blocks)
3977 (setq opening-blocks (cons (point) opening-blocks))))
3978 (when (zerop indentation)
3979 (throw 'exit nil)))))
3980 ;; sort by closer
3981 (nreverse opening-blocks))))))
3983 (define-obsolete-function-alias
3984 'python-info-closing-block-message
3985 'python-info-dedenter-opening-block-message "24.4")
3987 (defun python-info-dedenter-opening-block-message ()
3988 "Message the first line of the block the current statement closes."
3989 (let ((point (python-info-dedenter-opening-block-position)))
3990 (when point
3991 (save-restriction
3992 (widen)
3993 (message "Closes %s" (save-excursion
3994 (goto-char point)
3995 (buffer-substring
3996 (point) (line-end-position))))))))
3998 (defun python-info-dedenter-statement-p ()
3999 "Return point if current statement is a dedenter.
4000 Sets `match-data' to the keyword that starts the dedenter
4001 statement."
4002 (save-excursion
4003 (python-nav-beginning-of-statement)
4004 (when (and (not (python-syntax-context-type))
4005 (looking-at (python-rx dedenter)))
4006 (point))))
4008 (defun python-info-line-ends-backslash-p (&optional line-number)
4009 "Return non-nil if current line ends with backslash.
4010 With optional argument LINE-NUMBER, check that line instead."
4011 (save-excursion
4012 (save-restriction
4013 (widen)
4014 (when line-number
4015 (python-util-goto-line line-number))
4016 (while (and (not (eobp))
4017 (goto-char (line-end-position))
4018 (python-syntax-context 'paren)
4019 (not (equal (char-before (point)) ?\\)))
4020 (forward-line 1))
4021 (when (equal (char-before) ?\\)
4022 (point-marker)))))
4024 (defun python-info-beginning-of-backslash (&optional line-number)
4025 "Return the point where the backslashed line start.
4026 Optional argument LINE-NUMBER forces the line number to check against."
4027 (save-excursion
4028 (save-restriction
4029 (widen)
4030 (when line-number
4031 (python-util-goto-line line-number))
4032 (when (python-info-line-ends-backslash-p)
4033 (while (save-excursion
4034 (goto-char (line-beginning-position))
4035 (python-syntax-context 'paren))
4036 (forward-line -1))
4037 (back-to-indentation)
4038 (point-marker)))))
4040 (defun python-info-continuation-line-p ()
4041 "Check if current line is continuation of another.
4042 When current line is continuation of another return the point
4043 where the continued line ends."
4044 (save-excursion
4045 (save-restriction
4046 (widen)
4047 (let* ((context-type (progn
4048 (back-to-indentation)
4049 (python-syntax-context-type)))
4050 (line-start (line-number-at-pos))
4051 (context-start (when context-type
4052 (python-syntax-context context-type))))
4053 (cond ((equal context-type 'paren)
4054 ;; Lines inside a paren are always a continuation line
4055 ;; (except the first one).
4056 (python-util-forward-comment -1)
4057 (point-marker))
4058 ((member context-type '(string comment))
4059 ;; move forward an roll again
4060 (goto-char context-start)
4061 (python-util-forward-comment)
4062 (python-info-continuation-line-p))
4064 ;; Not within a paren, string or comment, the only way
4065 ;; we are dealing with a continuation line is that
4066 ;; previous line contains a backslash, and this can
4067 ;; only be the previous line from current
4068 (back-to-indentation)
4069 (python-util-forward-comment -1)
4070 (when (and (equal (1- line-start) (line-number-at-pos))
4071 (python-info-line-ends-backslash-p))
4072 (point-marker))))))))
4074 (defun python-info-block-continuation-line-p ()
4075 "Return non-nil if current line is a continuation of a block."
4076 (save-excursion
4077 (when (python-info-continuation-line-p)
4078 (forward-line -1)
4079 (back-to-indentation)
4080 (when (looking-at (python-rx block-start))
4081 (point-marker)))))
4083 (defun python-info-assignment-continuation-line-p ()
4084 "Check if current line is a continuation of an assignment.
4085 When current line is continuation of another with an assignment
4086 return the point of the first non-blank character after the
4087 operator."
4088 (save-excursion
4089 (when (python-info-continuation-line-p)
4090 (forward-line -1)
4091 (back-to-indentation)
4092 (when (and (not (looking-at (python-rx block-start)))
4093 (and (re-search-forward (python-rx not-simple-operator
4094 assignment-operator
4095 not-simple-operator)
4096 (line-end-position) t)
4097 (not (python-syntax-context-type))))
4098 (skip-syntax-forward "\s")
4099 (point-marker)))))
4101 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4102 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4103 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4104 (save-excursion
4105 (beginning-of-line 1)
4106 (looking-at python-nav-beginning-of-defun-regexp))))
4108 (defun python-info-current-line-comment-p ()
4109 "Return non-nil if current line is a comment line."
4110 (char-equal
4111 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4112 ?#))
4114 (defun python-info-current-line-empty-p ()
4115 "Return non-nil if current line is empty, ignoring whitespace."
4116 (save-excursion
4117 (beginning-of-line 1)
4118 (looking-at
4119 (python-rx line-start (* whitespace)
4120 (group (* not-newline))
4121 (* whitespace) line-end))
4122 (string-equal "" (match-string-no-properties 1))))
4125 ;;; Utility functions
4127 (defun python-util-goto-line (line-number)
4128 "Move point to LINE-NUMBER."
4129 (goto-char (point-min))
4130 (forward-line (1- line-number)))
4132 ;; Stolen from org-mode
4133 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4134 "Clone local variables from FROM-BUFFER.
4135 Optional argument REGEXP selects variables to clone and defaults
4136 to \"^python-\"."
4137 (mapc
4138 (lambda (pair)
4139 (and (symbolp (car pair))
4140 (string-match (or regexp "^python-")
4141 (symbol-name (car pair)))
4142 (set (make-local-variable (car pair))
4143 (cdr pair))))
4144 (buffer-local-variables from-buffer)))
4146 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4148 (defun python-util-comint-last-prompt ()
4149 "Return comint last prompt overlay start and end.
4150 This is for compatibility with Emacs < 24.4."
4151 (cond ((bound-and-true-p comint-last-prompt-overlay)
4152 (cons (overlay-start comint-last-prompt-overlay)
4153 (overlay-end comint-last-prompt-overlay)))
4154 ((bound-and-true-p comint-last-prompt)
4155 comint-last-prompt)
4156 (t nil)))
4158 (defun python-util-forward-comment (&optional direction)
4159 "Python mode specific version of `forward-comment'.
4160 Optional argument DIRECTION defines the direction to move to."
4161 (let ((comment-start (python-syntax-context 'comment))
4162 (factor (if (< (or direction 0) 0)
4163 -99999
4164 99999)))
4165 (when comment-start
4166 (goto-char comment-start))
4167 (forward-comment factor)))
4169 (defun python-util-list-directories (directory &optional predicate max-depth)
4170 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4171 Argument PREDICATE defaults to `identity' and must be a function
4172 that takes one argument (a full path) and returns non-nil for
4173 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4174 searching when depth is reached, else don't limit."
4175 (let* ((dir (expand-file-name directory))
4176 (dir-length (length dir))
4177 (predicate (or predicate #'identity))
4178 (to-scan (list dir))
4179 (tally nil))
4180 (while to-scan
4181 (let ((current-dir (car to-scan)))
4182 (when (funcall predicate current-dir)
4183 (setq tally (cons current-dir tally)))
4184 (setq to-scan (append (cdr to-scan)
4185 (python-util-list-files
4186 current-dir #'file-directory-p)
4187 nil))
4188 (when (and max-depth
4189 (<= max-depth
4190 (length (split-string
4191 (substring current-dir dir-length)
4192 "/\\|\\\\" t))))
4193 (setq to-scan nil))))
4194 (nreverse tally)))
4196 (defun python-util-list-files (dir &optional predicate)
4197 "List files in DIR, filtering with PREDICATE.
4198 Argument PREDICATE defaults to `identity' and must be a function
4199 that takes one argument (a full path) and returns non-nil for
4200 allowed files."
4201 (let ((dir-name (file-name-as-directory dir)))
4202 (apply #'nconc
4203 (mapcar (lambda (file-name)
4204 (let ((full-file-name (expand-file-name file-name dir-name)))
4205 (when (and
4206 (not (member file-name '("." "..")))
4207 (funcall (or predicate #'identity) full-file-name))
4208 (list full-file-name))))
4209 (directory-files dir-name)))))
4211 (defun python-util-list-packages (dir &optional max-depth)
4212 "List packages in DIR, limited by MAX-DEPTH.
4213 When optional argument MAX-DEPTH is non-nil, stop searching when
4214 depth is reached, else don't limit."
4215 (let* ((dir (expand-file-name dir))
4216 (parent-dir (file-name-directory
4217 (directory-file-name
4218 (file-name-directory
4219 (file-name-as-directory dir)))))
4220 (subpath-length (length parent-dir)))
4221 (mapcar
4222 (lambda (file-name)
4223 (replace-regexp-in-string
4224 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4225 (python-util-list-directories
4226 (directory-file-name dir)
4227 (lambda (dir)
4228 (file-exists-p (expand-file-name "__init__.py" dir)))
4229 max-depth))))
4231 (defun python-util-popn (lst n)
4232 "Return LST first N elements.
4233 N should be an integer, when negative its opposite is used.
4234 When N is bigger than the length of LST, the list is
4235 returned as is."
4236 (let* ((n (min (abs n)))
4237 (len (length lst))
4238 (acc))
4239 (if (> n len)
4241 (while (< 0 n)
4242 (setq acc (cons (car lst) acc)
4243 lst (cdr lst)
4244 n (1- n)))
4245 (reverse acc))))
4247 (defun python-util-text-properties-replace-name
4248 (from to &optional start end)
4249 "Replace properties named FROM to TO, keeping its value.
4250 Arguments START and END narrow the buffer region to work on."
4251 (save-excursion
4252 (goto-char (or start (point-min)))
4253 (while (not (eobp))
4254 (let ((plist (text-properties-at (point)))
4255 (next-change (or (next-property-change (point) (current-buffer))
4256 (or end (point-max)))))
4257 (when (plist-get plist from)
4258 (let* ((face (plist-get plist from))
4259 (plist (plist-put plist from nil))
4260 (plist (plist-put plist to face)))
4261 (set-text-properties (point) next-change plist (current-buffer))))
4262 (goto-char next-change)))))
4264 (defun python-util-strip-string (string)
4265 "Strip STRING whitespace and newlines from end and beginning."
4266 (replace-regexp-in-string
4267 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4268 (: (* (any whitespace ?\r ?\n)) string-end)))
4270 string))
4272 (defun python-util-valid-regexp-p (regexp)
4273 "Return non-nil if REGEXP is valid."
4274 (ignore-errors (string-match regexp "") t))
4277 (defun python-electric-pair-string-delimiter ()
4278 (when (and electric-pair-mode
4279 (memq last-command-event '(?\" ?\'))
4280 (let ((count 0))
4281 (while (eq (char-before (- (point) count)) last-command-event)
4282 (cl-incf count))
4283 (= count 3))
4284 (eq (char-after) last-command-event))
4285 (save-excursion (insert (make-string 2 last-command-event)))))
4287 (defvar electric-indent-inhibit)
4289 ;;;###autoload
4290 (define-derived-mode python-mode prog-mode "Python"
4291 "Major mode for editing Python files.
4293 \\{python-mode-map}"
4294 (set (make-local-variable 'tab-width) 8)
4295 (set (make-local-variable 'indent-tabs-mode) nil)
4297 (set (make-local-variable 'comment-start) "# ")
4298 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4300 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4301 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4303 (set (make-local-variable 'forward-sexp-function)
4304 'python-nav-forward-sexp)
4306 (set (make-local-variable 'font-lock-defaults)
4307 '(python-font-lock-keywords
4308 nil nil nil nil
4309 (font-lock-syntactic-face-function
4310 . python-font-lock-syntactic-face-function)))
4312 (set (make-local-variable 'syntax-propertize-function)
4313 python-syntax-propertize-function)
4315 (set (make-local-variable 'indent-line-function)
4316 #'python-indent-line-function)
4317 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4318 ;; Because indentation is not redundant, we cannot safely reindent code.
4319 (set (make-local-variable 'electric-indent-inhibit) t)
4320 (set (make-local-variable 'electric-indent-chars)
4321 (cons ?: electric-indent-chars))
4323 ;; Add """ ... """ pairing to electric-pair-mode.
4324 (add-hook 'post-self-insert-hook
4325 #'python-electric-pair-string-delimiter 'append t)
4327 (set (make-local-variable 'paragraph-start) "\\s-*$")
4328 (set (make-local-variable 'fill-paragraph-function)
4329 #'python-fill-paragraph)
4331 (set (make-local-variable 'beginning-of-defun-function)
4332 #'python-nav-beginning-of-defun)
4333 (set (make-local-variable 'end-of-defun-function)
4334 #'python-nav-end-of-defun)
4336 (add-hook 'completion-at-point-functions
4337 #'python-completion-at-point nil 'local)
4339 (add-hook 'post-self-insert-hook
4340 #'python-indent-post-self-insert-function 'append 'local)
4342 (set (make-local-variable 'imenu-create-index-function)
4343 #'python-imenu-create-index)
4345 (set (make-local-variable 'add-log-current-defun-function)
4346 #'python-info-current-defun)
4348 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4350 (set (make-local-variable 'skeleton-further-elements)
4351 '((abbrev-mode nil)
4352 (< '(backward-delete-char-untabify (min python-indent-offset
4353 (current-column))))
4354 (^ '(- (1+ (current-indentation))))))
4356 (set (make-local-variable 'eldoc-documentation-function)
4357 #'python-eldoc-function)
4359 (add-to-list 'hs-special-modes-alist
4360 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
4361 ,(lambda (_arg)
4362 (python-nav-end-of-defun))
4363 nil))
4365 (set (make-local-variable 'outline-regexp)
4366 (python-rx (* space) block-start))
4367 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4368 (set (make-local-variable 'outline-level)
4369 #'(lambda ()
4370 "`outline-level' function for Python mode."
4371 (1+ (/ (current-indentation) python-indent-offset))))
4373 (python-skeleton-add-menu-items)
4375 (make-local-variable 'python-shell-internal-buffer)
4377 (when python-indent-guess-indent-offset
4378 (python-indent-guess-indent-offset)))
4381 (provide 'python)
4383 ;; Local Variables:
4384 ;; coding: utf-8
4385 ;; indent-tabs-mode: nil
4386 ;; End:
4388 ;;; python.el ends here