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