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 <fgallina@gnu.org>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Package-Requires: ((emacs "24.1") (cl-lib "1.0"))
9 ;; Maintainer: emacs-devel@gnu.org
11 ;; Keywords: languages
13 ;; This file is part of GNU Emacs.
15 ;; GNU Emacs is free software: you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published
17 ;; by the Free Software Foundation, either version 3 of the License,
18 ;; or (at your option) any later version.
20 ;; GNU Emacs is distributed in the hope that it will be useful, but
21 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
23 ;; General Public License for more details.
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;; Major mode for editing Python files with some fontification and
31 ;; indentation bits extracted from original Dave Love's python.el
32 ;; found in GNU/Emacs.
34 ;; Implements Syntax highlighting, Indentation, Movement, Shell
35 ;; interaction, Shell completion, Shell virtualenv support, Shell
36 ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
37 ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
39 ;; Syntax highlighting: Fontification of code is provided and supports
40 ;; python's triple quoted strings properly.
42 ;; Indentation: Automatic indentation with indentation cycling is
43 ;; provided, it allows you to navigate different available levels of
44 ;; indentation by hitting <tab> several times. Also electric-indent-mode
45 ;; is supported such that when inserting a colon the current line is
46 ;; dedented automatically if needed.
48 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
49 ;; properly implemented. There are also specialized
50 ;; `forward-sentence' and `backward-sentence' replacements called
51 ;; `python-nav-forward-block', `python-nav-backward-block'
52 ;; respectively which navigate between beginning of blocks of code.
53 ;; Extra functions `python-nav-forward-statement',
54 ;; `python-nav-backward-statement',
55 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
56 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
57 ;; `python-nav-if-name-main' are included but no bound to any key. At
58 ;; last but not least the specialized `python-nav-forward-sexp' allows
59 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
60 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
61 ;; enough, You can do that using the `python-mode-hook':
63 ;; (add-hook 'python-mode-hook
64 ;; (lambda () (setq forward-sexp-function nil)))
66 ;; Shell interaction: is provided and allows opening Python shells
67 ;; inside Emacs and executing any block of code of your current buffer
68 ;; in that inferior Python process.
70 ;; Besides that only the standard CPython (2.x and 3.x) shell and
71 ;; IPython are officially supported out of the box, the interaction
72 ;; should support any other readline based Python shells as well
73 ;; (e.g. Jython and PyPy have been reported to work). You can change
74 ;; your default interpreter and commandline arguments by setting the
75 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
76 ;; variables. This example enables IPython globally:
78 ;; (setq python-shell-interpreter "ipython"
79 ;; python-shell-interpreter-args "-i")
81 ;; Using the "console" subcommand to start IPython in server-client
82 ;; mode is known to fail intermittently due a bug on IPython itself
83 ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
84 ;; There seems to be a race condition in the IPython server (A.K.A
85 ;; kernel) when code is sent while it is still initializing, sometimes
86 ;; causing the shell to get stalled. With that said, if an IPython
87 ;; kernel is already running, "console --existing" seems to work fine.
89 ;; Running IPython on Windows needs more tweaking. The way you should
90 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
91 ;; is as follows (of course you need to modify the paths according to
94 ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
95 ;; python-shell-interpreter-args
96 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
98 ;; Missing or delayed output used to happen due to differences between
99 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
100 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
102 ;; controls whether `python-shell-calculate-process-environment'
103 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
104 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
106 ;; The interaction relies upon having prompts for input (e.g. ">>> "
107 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
108 ;; IPython) detected properly. Failing that Emacs may hang but, in
109 ;; the case that happens, you can recover with \\[keyboard-quit]. To
110 ;; avoid this issue, a two-step prompt autodetection mechanism is
111 ;; provided: the first step is manual and consists of a collection of
112 ;; regular expressions matching common prompts for Python shells
113 ;; stored in `python-shell-prompt-input-regexps' and
114 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
115 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
116 ;; `python-shell-prompt-output-regexp' which are appended to the
117 ;; former automatically when a shell spawns; the second step is
118 ;; automatic and depends on the `python-shell-prompt-detect' helper
119 ;; function. See its docstring for details on global variables that
120 ;; modify its behavior.
122 ;; Shell completion: hitting tab will try to complete the current
123 ;; word. The two built-in mechanisms depend on Python's readline
124 ;; module: the "native" completion is tried first and is activated
125 ;; when `python-shell-completion-native-enable' is non-nil, the
126 ;; current `python-shell-interpreter' is not a member of the
127 ;; `python-shell-completion-native-disabled-interpreters' variable and
128 ;; `python-shell-completion-native-setup' succeeds; the "fallback" or
129 ;; "legacy" mechanism works by executing Python code in the background
130 ;; and enables auto-completion for shells that do not support
131 ;; receiving escape sequences (with some limitations, i.e. completion
132 ;; in blocks does not work). The code executed for the "fallback"
133 ;; completion can be found in `python-shell-completion-setup-code' and
134 ;; `python-shell-completion-string-code' variables. Their default
135 ;; values enable completion for both CPython and IPython, and probably
136 ;; any readline based shell (it's known to work with PyPy). If your
137 ;; Python installation lacks readline (like CPython for Windows),
138 ;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
139 ;; should suffice. To troubleshoot why you are not getting any
140 ;; completions, you can try the following in your Python shell:
142 ;; >>> import readline, rlcompleter
144 ;; If you see an error, then you need to either install pyreadline or
145 ;; setup custom code that avoids that dependency.
147 ;; Shell virtualenv support: The shell also contains support for
148 ;; virtualenvs and other special environment modifications thanks to
149 ;; `python-shell-process-environment' and `python-shell-exec-path'.
150 ;; These two variables allows you to modify execution paths and
151 ;; environment variables to make easy for you to setup virtualenv rules
152 ;; or behavior modifications when running shells. Here is an example
153 ;; of how to make shell processes to be run using the /path/to/env/
156 ;; (setq python-shell-process-environment
158 ;; (format "PATH=%s" (mapconcat
161 ;; (cons (getenv "PATH")
162 ;; '("/path/to/env/bin/")))
164 ;; "VIRTUAL_ENV=/path/to/env/"))
165 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
167 ;; Since the above is cumbersome and can be programmatically
168 ;; calculated, the variable `python-shell-virtualenv-root' is
169 ;; provided. When this variable is set with the path of the
170 ;; virtualenv to use, `process-environment' and `exec-path' get proper
171 ;; values in order to run shells inside the specified virtualenv. So
172 ;; the following will achieve the same as the previous example:
174 ;; (setq python-shell-virtualenv-root "/path/to/env/")
176 ;; Also the `python-shell-extra-pythonpaths' variable have been
177 ;; introduced as simple way of adding paths to the PYTHONPATH without
178 ;; affecting existing values.
180 ;; Shell package support: you can enable a package in the current
181 ;; shell so that relative imports work properly using the
182 ;; `python-shell-package-enable' command.
184 ;; Shell remote support: remote Python shells are started with the
185 ;; correct environment for files opened remotely through tramp, also
186 ;; respecting dir-local variables provided `enable-remote-dir-locals'
187 ;; is non-nil. The logic for this is transparently handled by the
188 ;; `python-shell-with-environment' macro.
190 ;; Shell syntax highlighting: when enabled current input in shell is
191 ;; highlighted. The variable `python-shell-font-lock-enable' controls
192 ;; activation of this feature globally when shells are started.
193 ;; Activation/deactivation can be also controlled on the fly via the
194 ;; `python-shell-font-lock-toggle' command.
196 ;; Pdb tracking: when you execute a block of code that contains some
197 ;; call to pdb (or ipdb) it will prompt the block of code and will
198 ;; follow the execution of pdb marking the current line with an arrow.
200 ;; Symbol completion: you can complete the symbol at point. It uses
201 ;; the shell completion in background so you should run
202 ;; `python-shell-send-buffer' from time to time to get better results.
204 ;; Skeletons: skeletons are provided for simple inserting of things like class,
205 ;; def, for, import, if, try, and while. These skeletons are
206 ;; integrated with abbrev. If you have `abbrev-mode' activated and
207 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
208 ;; the name of any of those defined and hit SPC, they will be
209 ;; automatically expanded. As an alternative you can use the defined
210 ;; skeleton commands: `python-skeleton-<foo>'.
212 ;; FFAP: You can find the filename for a given module when using ffap
213 ;; out of the box. This feature needs an inferior python shell
216 ;; Code check: Check the current file for errors with `python-check'
217 ;; using the program defined in `python-check-command'.
219 ;; Eldoc: returns documentation for object at point by using the
220 ;; inferior python subprocess to inspect its documentation. As you
221 ;; might guessed you should run `python-shell-send-buffer' from time
222 ;; to time to get better results too.
224 ;; Imenu: There are two index building functions to be used as
225 ;; `imenu-create-index-function': `python-imenu-create-index' (the
226 ;; default one, builds the alist in form of a tree) and
227 ;; `python-imenu-create-flat-index'. See also
228 ;; `python-imenu-format-item-label-function',
229 ;; `python-imenu-format-parent-item-label-function',
230 ;; `python-imenu-format-parent-item-jump-label-function' variables for
231 ;; changing the way labels are formatted in the tree version.
233 ;; If you used python-mode.el you may miss auto-indentation when
234 ;; inserting newlines. To achieve the same behavior you have two
237 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
238 ;; default) and use RET. If this mode is disabled use
239 ;; `newline-and-indent', bound to C-j.
241 ;; 2) Add the following hook in your .emacs:
243 ;; (add-hook 'python-mode-hook
245 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
247 ;; I'd recommend the first one since you'll get the same behavior for
248 ;; all modes out-of-the-box.
252 ;; Add this to your .emacs:
254 ;; (add-to-list 'load-path "/folder/containing/file")
261 (require 'ansi-color
)
267 ;; Avoid compiler warnings
268 (defvar view-return-to-alist
)
269 (defvar compilation-error-regexp-alist
)
270 (defvar outline-heading-end-regexp
)
272 (autoload 'comint-mode
"comint")
273 (autoload 'help-function-arglist
"help-fns")
276 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
278 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
281 "Python Language's flying circus support for Emacs."
284 :link
'(emacs-commentary-link "python"))
290 (unless (fboundp 'prog-widen
)
294 (unless (fboundp 'prog-first-column
)
295 (defun prog-first-column ()
301 (defvar python-mode-map
302 (let ((map (make-sparse-keymap)))
304 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
305 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
306 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
307 (define-key map
[remap mark-defun
] 'python-mark-defun
)
308 (define-key map
"\C-c\C-j" 'imenu
)
310 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
311 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
312 (define-key map
"\C-c<" 'python-indent-shift-left
)
313 (define-key map
"\C-c>" 'python-indent-shift-right
)
315 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
316 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
317 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
318 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
319 (define-key map
"\C-c\C-tm" 'python-skeleton-import
)
320 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
321 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
323 (define-key map
"\C-c\C-p" 'run-python
)
324 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
325 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
326 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
327 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
328 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
329 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
330 ;; Some util commands
331 (define-key map
"\C-c\C-v" 'python-check
)
332 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
334 (substitute-key-definition 'complete-symbol
'completion-at-point
336 (easy-menu-define python-menu map
"Python Mode menu"
338 :help
"Python-specific Features"
339 ["Shift region left" python-indent-shift-left
:active mark-active
340 :help
"Shift region left by a single indentation step"]
341 ["Shift region right" python-indent-shift-right
:active mark-active
342 :help
"Shift region right by a single indentation step"]
344 ["Start of def/class" beginning-of-defun
345 :help
"Go to start of outermost definition around point"]
346 ["End of def/class" end-of-defun
347 :help
"Go to end of definition around point"]
348 ["Mark def/class" mark-defun
349 :help
"Mark outermost definition around point"]
350 ["Jump to def/class" imenu
351 :help
"Jump to a class or function definition"]
355 ["Start interpreter" run-python
356 :help
"Run inferior Python process in a separate buffer"]
357 ["Switch to shell" python-shell-switch-to-shell
358 :help
"Switch to running inferior Python process"]
359 ["Eval string" python-shell-send-string
360 :help
"Eval string in inferior Python session"]
361 ["Eval buffer" python-shell-send-buffer
362 :help
"Eval buffer in inferior Python session"]
363 ["Eval region" python-shell-send-region
364 :help
"Eval region in inferior Python session"]
365 ["Eval defun" python-shell-send-defun
366 :help
"Eval defun in inferior Python session"]
367 ["Eval file" python-shell-send-file
368 :help
"Eval file in inferior Python session"]
369 ["Debugger" pdb
:help
"Run pdb under GUD"]
371 ["Check file" python-check
372 :help
"Check file for errors"]
373 ["Help on symbol" python-eldoc-at-point
374 :help
"Get help on symbol at point"]
375 ["Complete symbol" completion-at-point
376 :help
"Complete symbol before point"]))
378 "Keymap for `python-mode'.")
381 ;;; Python specialized rx
384 (defconst python-rx-constituents
385 `((block-start .
,(rx symbol-start
386 (or "def" "class" "if" "elif" "else" "try"
387 "except" "finally" "for" "while" "with")
389 (dedenter .
,(rx symbol-start
390 (or "elif" "else" "except" "finally")
392 (block-ender .
,(rx symbol-start
394 "break" "continue" "pass" "raise" "return")
396 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
398 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
399 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
400 (+ space
) "==" (+ space
)
401 (any ?
' ?
\") "__main__" (any ?
' ?
\")
403 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
404 (open-paren .
,(rx (or "{" "[" "(")))
405 (close-paren .
,(rx (or "}" "]" ")")))
406 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
407 ;; FIXME: rx should support (not simple-operator).
408 (not-simple-operator .
,(rx
410 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
411 ;; FIXME: Use regexp-opt.
412 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
413 "=" "%" "**" "//" "<<" ">>" "<=" "!="
414 "==" ">=" "is" "not")))
415 ;; FIXME: Use regexp-opt.
416 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
417 ">>=" "<<=" "&=" "^=" "|=")))
418 (string-delimiter .
,(rx (and
419 ;; Match even number of backslashes.
420 (or (not (any ?
\\ ?
\' ?
\")) point
421 ;; Quotes might be preceded by a escaped quote.
422 (and (or (not (any ?
\\)) point
) ?
\\
423 (* ?
\\ ?
\\) (any ?
\' ?
\")))
425 ;; Match single or triple quotes of any kind.
426 (group (or "\"" "\"\"\"" "'" "'''")))))
427 (coding-cookie .
,(rx line-start ?
# (* space
)
429 ;; # coding=<encoding name>
430 (: "coding" (or ?
: ?
=) (* space
) (group-n 1 (+ (or word ?-
))))
431 ;; # -*- coding: <encoding name> -*-
432 (: "-*-" (* space
) "coding:" (* space
)
433 (group-n 1 (+ (or word ?-
))) (* space
) "-*-")
434 ;; # vim: set fileencoding=<encoding name> :
435 (: "vim:" (* space
) "set" (+ space
)
436 "fileencoding" (* space
) ?
= (* space
)
437 (group-n 1 (+ (or word ?-
))) (* space
) ":")))))
438 "Additional Python specific sexps for `python-rx'")
440 (defmacro python-rx
(&rest regexps
)
441 "Python mode specialized rx macro.
442 This variant of `rx' supports common Python named REGEXPS."
443 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
444 (cond ((null regexps
)
447 (rx-to-string `(and ,@regexps
) t
))
449 (rx-to-string (car regexps
) t
))))))
452 ;;; Font-lock and syntax
455 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
458 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
459 (and (nth 4 ppss
) (nth 8 ppss
))))
461 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
462 (and (nth 3 ppss
) (nth 8 ppss
))))
464 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
467 (defun python-syntax-context (type &optional syntax-ppss
)
468 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
469 TYPE can be `comment', `string' or `paren'. It returns the start
470 character address of the specified TYPE."
471 (declare (compiler-macro python-syntax--context-compiler-macro
))
472 (let ((ppss (or syntax-ppss
(syntax-ppss))))
474 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
475 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
476 (`paren
(nth 1 ppss
))
479 (defun python-syntax-context-type (&optional syntax-ppss
)
480 "Return the context type using SYNTAX-PPSS.
481 The type returned can be `comment', `string' or `paren'."
482 (let ((ppss (or syntax-ppss
(syntax-ppss))))
484 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
485 ((nth 1 ppss
) 'paren
))))
487 (defsubst python-syntax-comment-or-string-p
(&optional ppss
)
488 "Return non-nil if PPSS is inside 'comment or 'string."
489 (nth 8 (or ppss
(syntax-ppss))))
491 (defsubst python-syntax-closing-paren-p
()
492 "Return non-nil if char after point is a closing paren."
493 (= (syntax-class (syntax-after (point)))
494 (syntax-class (string-to-syntax ")"))))
496 (define-obsolete-function-alias
497 'python-info-ppss-context
#'python-syntax-context
"24.3")
499 (define-obsolete-function-alias
500 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
502 (define-obsolete-function-alias
503 'python-info-ppss-comment-or-string-p
504 #'python-syntax-comment-or-string-p
"24.3")
506 (defun python-font-lock-syntactic-face-function (state)
507 "Return syntactic face given STATE."
509 (if (python-info-docstring-p state
)
511 font-lock-string-face
)
512 font-lock-comment-face
))
514 (defvar python-font-lock-keywords
518 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
519 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
520 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
525 ;; False, None, and True are listed as keywords on the Python 3
526 ;; documentation, but since they also qualify as constants they are
527 ;; fontified like that in order to keep font-lock consistent between
534 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
535 (1 font-lock-function-name-face
))
537 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
538 (1 font-lock-type-face
))
542 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
543 ;; copyright, license, credits, quit and exit are added by the site
544 ;; module and they are not intended to be used in programs
545 "copyright" "credits" "exit" "license" "quit")
546 symbol-end
) . font-lock-constant-face
)
548 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
549 (0+ "." (1+ (or word ?_
)))))
550 (1 font-lock-type-face
))
551 ;; Builtin Exceptions
554 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
555 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
556 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
557 "ImportError" "ImportWarning" "IndexError" "KeyError"
558 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
559 "NotImplementedError" "OSError" "OverflowError"
560 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
561 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
562 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
563 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
564 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
565 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
569 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
571 symbol-end
) . font-lock-type-face
)
575 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
576 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
577 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
578 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
579 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
580 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
581 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
582 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
585 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
586 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
589 "ascii" "bytearray" "bytes" "exec"
591 "__all__" "__doc__" "__name__" "__package__")
592 symbol-end
) . font-lock-builtin-face
)
594 ;; support for a = b = c = 5
596 (let ((re (python-rx (group (+ (any word ?. ?_
)))
597 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
598 assignment-operator
))
600 (while (and (setq res
(re-search-forward re limit t
))
601 (or (python-syntax-context 'paren
)
602 (equal (char-after (point)) ?
=))))
604 (1 font-lock-variable-name-face nil nil
))
605 ;; support for a, b, c = (1, 2, 3)
607 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
608 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
609 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
610 assignment-operator
))
612 (while (and (setq res
(re-search-forward re limit t
))
613 (goto-char (match-end 1))
614 (python-syntax-context 'paren
)))
616 (1 font-lock-variable-name-face nil nil
))))
618 (defconst python-syntax-propertize-function
619 (syntax-propertize-rules
620 ((python-rx string-delimiter
)
621 (0 (ignore (python-syntax-stringify))))))
623 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
624 "Count number of quotes around point (max is 3).
625 QUOTE-CHAR is the quote char to count. Optional argument POINT is
626 the point where scan starts (defaults to current point), and LIMIT
627 is used to limit the scan."
630 (or (not limit
) (< (+ point i
) limit
))
631 (eq (char-after (+ point i
)) quote-char
))
635 (defun python-syntax-stringify ()
636 "Put `syntax-table' property correctly on single/triple quotes."
637 (let* ((num-quotes (length (match-string-no-properties 1)))
639 (backward-char num-quotes
)
641 (forward-char num-quotes
)))
642 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
643 (quote-starting-pos (- (point) num-quotes
))
644 (quote-ending-pos (point))
647 (python-syntax-count-quotes
648 (char-before) string-start quote-starting-pos
))))
649 (cond ((and string-start
(= num-closing-quotes
0))
650 ;; This set of quotes doesn't match the string starting
654 ;; This set of quotes delimit the start of a string.
655 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
656 'syntax-table
(string-to-syntax "|")))
657 ((= num-quotes num-closing-quotes
)
658 ;; This set of quotes delimit the end of a string.
659 (put-text-property (1- quote-ending-pos
) quote-ending-pos
660 'syntax-table
(string-to-syntax "|")))
661 ((> num-quotes num-closing-quotes
)
662 ;; This may only happen whenever a triple quote is closing
663 ;; a single quoted string. Add string delimiter syntax to
665 (put-text-property quote-starting-pos quote-ending-pos
666 'syntax-table
(string-to-syntax "|"))))))
668 (defvar python-mode-syntax-table
669 (let ((table (make-syntax-table)))
670 ;; Give punctuation syntax to ASCII that normally has symbol
671 ;; syntax or has word syntax and isn't a letter.
672 (let ((symbol (string-to-syntax "_"))
673 (sst (standard-syntax-table)))
676 (if (equal symbol
(aref sst i
))
677 (modify-syntax-entry i
"." table
)))))
678 (modify-syntax-entry ?$
"." table
)
679 (modify-syntax-entry ?%
"." table
)
681 (modify-syntax-entry ?
# "<" table
)
682 (modify-syntax-entry ?
\n ">" table
)
683 (modify-syntax-entry ?
' "\"" table
)
684 (modify-syntax-entry ?
` "$" table
)
686 "Syntax table for Python files.")
688 (defvar python-dotty-syntax-table
689 (let ((table (make-syntax-table python-mode-syntax-table
)))
690 (modify-syntax-entry ?.
"w" table
)
691 (modify-syntax-entry ?_
"w" table
)
693 "Dotty syntax table for Python files.
694 It makes underscores and dots word constituent chars.")
699 (defcustom python-indent-offset
4
700 "Default indentation offset for Python."
705 (defcustom python-indent-guess-indent-offset t
706 "Non-nil tells Python mode to guess `python-indent-offset' value."
711 (defcustom python-indent-guess-indent-offset-verbose t
712 "Non-nil means to emit a warning when indentation guessing fails."
717 (defcustom python-indent-trigger-commands
718 '(indent-for-tab-command yas-expand yas
/expand
)
719 "Commands that might trigger a `python-indent-line' call."
720 :type
'(repeat symbol
)
723 (define-obsolete-variable-alias
724 'python-indent
'python-indent-offset
"24.3")
726 (define-obsolete-variable-alias
727 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
729 (defvar python-indent-current-level
0
730 "Deprecated var available for compatibility.")
732 (defvar python-indent-levels
'(0)
733 "Deprecated var available for compatibility.")
735 (make-obsolete-variable
736 'python-indent-current-level
737 "The indentation API changed to avoid global state.
738 The function `python-indent-calculate-levels' does not use it
739 anymore. If you were defadvising it and or depended on this
740 variable for indentation customizations, refactor your code to
741 work on `python-indent-calculate-indentation' instead."
744 (make-obsolete-variable
745 'python-indent-levels
746 "The indentation API changed to avoid global state.
747 The function `python-indent-calculate-levels' does not use it
748 anymore. If you were defadvising it and or depended on this
749 variable for indentation customizations, refactor your code to
750 work on `python-indent-calculate-indentation' instead."
753 (defun python-indent-guess-indent-offset ()
754 "Guess and set `python-indent-offset' for the current buffer."
759 (goto-char (point-min))
761 (while (and (not block-end
)
763 (python-rx line-start block-start
) nil t
))
765 (not (python-syntax-context-type))
767 (goto-char (line-end-position))
768 (python-util-forward-comment -
1)
769 (if (equal (char-before) ?
:)
772 (when (python-info-block-continuation-line-p)
773 (while (and (python-info-continuation-line-p)
776 (python-util-forward-comment -
1)
777 (when (equal (char-before) ?
:)
779 (setq block-end
(point-marker))))
782 (goto-char block-end
)
783 (python-util-forward-comment)
784 (current-indentation))))
785 (if (and indentation
(not (zerop indentation
)))
786 (set (make-local-variable 'python-indent-offset
) indentation
)
787 (when python-indent-guess-indent-offset-verbose
788 (message "Can't guess python-indent-offset, using defaults: %s"
789 python-indent-offset
))))))))
791 (defun python-indent-context ()
792 "Get information about the current indentation context.
793 Context is returned in a cons with the form (STATUS . START).
795 STATUS can be one of the following:
801 - Point is after a comment line.
802 - START is the position of the \"#\" character.
804 - Point is inside string.
805 - START is the position of the first quote that starts it.
807 - No possible indentation case matches.
808 - START is always zero.
811 - Fallback case when point is inside paren.
812 - START is the first non space char position *after* the open paren.
813 :inside-paren-at-closing-nested-paren
814 - Point is on a line that contains a nested paren closer.
815 - START is the position of the open paren it closes.
816 :inside-paren-at-closing-paren
817 - Point is on a line that contains a paren closer.
818 - START is the position of the open paren.
819 :inside-paren-newline-start
820 - Point is inside a paren with items starting in their own line.
821 - START is the position of the open paren.
822 :inside-paren-newline-start-from-block
823 - Point is inside a paren with items starting in their own line
825 - START is the position of the open paren.
828 - Fallback case when point is after backslash.
829 - START is the char after the position of the backslash.
830 :after-backslash-assignment-continuation
831 - Point is after a backslashed assignment.
832 - START is the char after the position of the backslash.
833 :after-backslash-block-continuation
834 - Point is after a backslashed block continuation.
835 - START is the char after the position of the backslash.
836 :after-backslash-dotted-continuation
837 - Point is after a backslashed dotted continuation. Previous
838 line must contain a dot to align with.
839 - START is the char after the position of the backslash.
840 :after-backslash-first-line
841 - First line following a backslashed continuation.
842 - START is the char after the position of the backslash.
845 - Point is after a line containing a block ender.
846 - START is the position where the ender starts.
848 - Point is after a line starting a block.
849 - START is the position where the block starts.
851 - Point is after a simple line.
852 - START is the position where the previous line starts.
853 :at-dedenter-block-start
854 - Point is on a line starting a dedenter block.
855 - START is the position where the dedenter block starts."
858 (let ((ppss (save-excursion
862 ;; Beginning of buffer.
863 ((= (line-number-at-pos) 1)
866 ((let ((start (python-syntax-context 'string ppss
)))
868 (cons (if (python-info-docstring-p)
870 :inside-string
) start
))))
872 ((let* ((start (python-syntax-context 'paren ppss
))
879 (= (line-number-at-pos)
881 (python-util-forward-comment)
882 (line-number-at-pos))))))))
885 ;; Current line only holds the closing paren.
887 (skip-syntax-forward " ")
888 (when (and (python-syntax-closing-paren-p)
891 (not (python-syntax-context 'paren
))))
892 (cons :inside-paren-at-closing-paren start
))))
893 ;; Current line only holds a closing paren for nested.
895 (back-to-indentation)
896 (python-syntax-closing-paren-p))
897 (cons :inside-paren-at-closing-nested-paren start
))
898 ;; This line starts from a opening block in its own line.
904 (back-to-indentation)
905 (looking-at (python-rx block-start
))))
907 :inside-paren-newline-start-from-block start
))))
909 (cons :inside-paren-newline-start start
))
911 (t (cons :inside-paren
913 (goto-char (1+ start
))
914 (skip-syntax-forward "(" 1)
915 (skip-syntax-forward " ")
918 ((let ((start (when (not (python-syntax-comment-or-string-p ppss
))
919 (python-info-line-ends-backslash-p
920 (1- (line-number-at-pos))))))
923 ;; Continuation of dotted expression.
925 (back-to-indentation)
926 (when (eq (char-after) ?\.
)
927 ;; Move point back until it's not inside a paren.
931 (python-syntax-context 'paren
))))
932 (goto-char (line-end-position))
933 (while (and (search-backward
934 "." (line-beginning-position) t
)
935 (python-syntax-context-type)))
936 ;; Ensure previous statement has dot to align with.
937 (when (and (eq (char-after) ?\.
)
938 (not (python-syntax-context-type)))
939 (cons :after-backslash-dotted-continuation
(point))))))
940 ;; Continuation of block definition.
941 ((let ((block-continuation-start
942 (python-info-block-continuation-line-p)))
943 (when block-continuation-start
945 (goto-char block-continuation-start
)
947 (python-rx block-start
(* space
))
948 (line-end-position) t
)
949 (cons :after-backslash-block-continuation
(point))))))
950 ;; Continuation of assignment.
951 ((let ((assignment-continuation-start
952 (python-info-assignment-continuation-line-p)))
953 (when assignment-continuation-start
955 (goto-char assignment-continuation-start
)
956 (cons :after-backslash-assignment-continuation
(point))))))
957 ;; First line after backslash continuation start.
960 (when (or (= (line-number-at-pos) 1)
961 (not (python-info-beginning-of-backslash
962 (1- (line-number-at-pos)))))
963 (cons :after-backslash-first-line start
))))
965 (t (cons :after-backslash start
))))))
966 ;; After beginning of block.
967 ((let ((start (save-excursion
968 (back-to-indentation)
969 (python-util-forward-comment -
1)
970 (when (equal (char-before) ?
:)
971 (python-nav-beginning-of-block)))))
973 (cons :after-block-start start
))))
974 ;; At dedenter statement.
975 ((let ((start (python-info-dedenter-statement-p)))
977 (cons :at-dedenter-block-start start
))))
978 ;; After normal line, comment or ender (default case).
980 (back-to-indentation)
981 (skip-chars-backward " \t\n")
984 (python-nav-beginning-of-statement)
986 (cond ((python-info-current-line-comment-p)
989 (goto-char (line-end-position))
990 (python-util-forward-comment -
1)
991 (python-nav-beginning-of-statement)
992 (looking-at (python-rx block-ender
)))
997 (defun python-indent--calculate-indentation ()
998 "Internal implementation of `python-indent-calculate-indentation'.
999 May return an integer for the maximum possible indentation at
1000 current context or a list of integers. The latter case is only
1001 happening for :at-dedenter-block-start context since the
1002 possibilities can be narrowed to specific indentation points."
1006 (pcase (python-indent-context)
1007 (`(:no-indent .
,_
) (prog-first-column)) ; usually 0
1012 :inside-paren-at-closing-paren
1013 :inside-paren-at-closing-nested-paren
) .
,start
)
1014 ;; Copy previous indentation.
1016 (current-indentation))
1017 (`(:inside-docstring .
,start
)
1018 (let* ((line-indentation (current-indentation))
1021 (current-indentation))))
1022 (max line-indentation base-indent
)))
1023 (`(,(or :after-block-start
1024 :after-backslash-first-line
1025 :inside-paren-newline-start
) .
,start
)
1026 ;; Add one indentation level.
1028 (+ (current-indentation) python-indent-offset
))
1029 (`(,(or :inside-paren
1030 :after-backslash-block-continuation
1031 :after-backslash-assignment-continuation
1032 :after-backslash-dotted-continuation
) .
,start
)
1033 ;; Use the column given by the context.
1036 (`(:after-block-end .
,start
)
1037 ;; Subtract one indentation level.
1039 (- (current-indentation) python-indent-offset
))
1040 (`(:at-dedenter-block-start .
,_
)
1041 ;; List all possible indentation levels from opening blocks.
1042 (let ((opening-block-start-points
1043 (python-info-dedenter-opening-block-positions)))
1044 (if (not opening-block-start-points
)
1045 (prog-first-column) ; if not found default to first column
1046 (mapcar (lambda (pos)
1049 (current-indentation)))
1050 opening-block-start-points
))))
1051 (`(,(or :inside-paren-newline-start-from-block
) .
,start
)
1052 ;; Add two indentation levels to make the suite stand out.
1054 (+ (current-indentation) (* python-indent-offset
2)))))))
1056 (defun python-indent--calculate-levels (indentation)
1057 "Calculate levels list given INDENTATION.
1058 Argument INDENTATION can either be an integer or a list of
1059 integers. Levels are returned in ascending order, and in the
1060 case INDENTATION is a list, this order is enforced."
1061 (if (listp indentation
)
1062 (sort (copy-sequence indentation
) #'<)
1063 (nconc (number-sequence (prog-first-column) (1- indentation
)
1064 python-indent-offset
)
1065 (list indentation
))))
1067 (defun python-indent--previous-level (levels indentation
)
1068 "Return previous level from LEVELS relative to INDENTATION."
1069 (let* ((levels (sort (copy-sequence levels
) #'>))
1070 (default (car levels
)))
1072 (dolist (level levels
)
1073 (when (funcall #'< level indentation
)
1074 (throw 'return level
)))
1077 (defun python-indent-calculate-indentation (&optional previous
)
1078 "Calculate indentation.
1079 Get indentation of PREVIOUS level when argument is non-nil.
1080 Return the max level of the cycle when indentation reaches the
1082 (let* ((indentation (python-indent--calculate-indentation))
1083 (levels (python-indent--calculate-levels indentation
)))
1085 (python-indent--previous-level levels
(current-indentation))
1087 (apply #'max levels
)
1088 (prog-first-column)))))
1090 (defun python-indent-line (&optional previous
)
1091 "Internal implementation of `python-indent-line-function'.
1092 Use the PREVIOUS level when argument is non-nil, otherwise indent
1093 to the maximum available level. When indentation is the minimum
1094 possible and PREVIOUS is non-nil, cycle back to the maximum
1096 (let ((follow-indentation-p
1097 ;; Check if point is within indentation.
1098 (and (<= (line-beginning-position) (point))
1099 (>= (+ (line-beginning-position)
1100 (current-indentation))
1104 (python-indent-calculate-indentation previous
))
1105 (python-info-dedenter-opening-block-message))
1106 (when follow-indentation-p
1107 (back-to-indentation))))
1109 (defun python-indent-calculate-levels ()
1110 "Return possible indentation levels."
1111 (python-indent--calculate-levels
1112 (python-indent--calculate-indentation)))
1114 (defun python-indent-line-function ()
1115 "`indent-line-function' for Python mode.
1116 When the variable `last-command' is equal to one of the symbols
1117 inside `python-indent-trigger-commands' it cycles possible
1118 indentation levels from right to left."
1120 (and (memq this-command python-indent-trigger-commands
)
1121 (eq last-command this-command
))))
1123 (defun python-indent-dedent-line ()
1124 "De-indent current line."
1126 (when (and (not (bolp))
1127 (not (python-syntax-comment-or-string-p))
1128 (= (current-indentation) (current-column)))
1129 (python-indent-line t
)
1132 (defun python-indent-dedent-line-backspace (arg)
1133 "De-indent current line.
1134 Argument ARG is passed to `backward-delete-char-untabify' when
1135 point is not in between the indentation."
1137 (unless (python-indent-dedent-line)
1138 (backward-delete-char-untabify arg
)))
1140 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1142 (defun python-indent-region (start end
)
1143 "Indent a Python region automagically.
1145 Called from a program, START and END specify the region to indent."
1146 (let ((deactivate-mark nil
))
1149 (setq end
(point-marker))
1151 (or (bolp) (forward-line 1))
1152 (while (< (point) end
)
1153 (or (and (bolp) (eolp))
1155 ;; Skip if previous line is empty or a comment.
1157 (let ((line-is-comment-p
1158 (python-info-current-line-comment-p)))
1161 (or (and (python-info-current-line-comment-p)
1162 ;; Unless this line is a comment too.
1163 (not line-is-comment-p
))
1164 (python-info-current-line-empty-p)))))
1165 ;; Don't mess with strings, unless it's the
1166 ;; enclosing set of quotes or a docstring.
1167 (or (not (python-syntax-context 'string
))
1171 (current-indentation)
1172 (python-syntax-count-quotes (char-after) (point))))
1173 (string-to-syntax "|"))
1174 (python-info-docstring-p))
1175 ;; Skip if current line is a block start, a
1176 ;; dedenter or block ender.
1178 (back-to-indentation)
1181 (or block-start dedenter block-ender
))))))
1182 (python-indent-line)))
1184 (move-marker end nil
))))
1186 (defun python-indent-shift-left (start end
&optional count
)
1187 "Shift lines contained in region START END by COUNT columns to the left.
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. An error is signaled if
1191 any lines in the region are indented less than COUNT columns."
1194 (list (region-beginning) (region-end) current-prefix-arg
)
1195 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1197 (setq count
(prefix-numeric-value count
))
1198 (setq count python-indent-offset
))
1200 (let ((deactivate-mark nil
))
1203 (while (< (point) end
)
1204 (if (and (< (current-indentation) count
)
1205 (not (looking-at "[ \t]*$")))
1206 (user-error "Can't shift all lines enough"))
1208 (indent-rigidly start end
(- count
))))))
1210 (defun python-indent-shift-right (start end
&optional count
)
1211 "Shift lines contained in region START END by COUNT columns to the right.
1212 COUNT defaults to `python-indent-offset'. If region isn't
1213 active, the current line is shifted. The shifted region includes
1214 the lines in which START and END lie."
1217 (list (region-beginning) (region-end) current-prefix-arg
)
1218 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1219 (let ((deactivate-mark nil
))
1220 (setq count
(if count
(prefix-numeric-value count
)
1221 python-indent-offset
))
1222 (indent-rigidly start end count
)))
1224 (defun python-indent-post-self-insert-function ()
1225 "Adjust indentation after insertion of some characters.
1226 This function is intended to be added to `post-self-insert-hook.'
1227 If a line renders a paren alone, after adding a char before it,
1228 the line will be re-indented automatically if needed."
1229 (when (and electric-indent-mode
1230 (eq (char-before) last-command-event
))
1232 ;; Electric indent inside parens
1235 (let ((paren-start (python-syntax-context 'paren
)))
1236 ;; Check that point is inside parens.
1239 ;; Filter the case where input is happening in the same
1240 ;; line where the open paren is.
1241 (= (line-number-at-pos)
1242 (line-number-at-pos paren-start
)))))
1243 ;; When content has been added before the closing paren or a
1244 ;; comma has been inserted, it's ok to do the trick.
1246 (memq (char-after) '(?\
) ?\
] ?\
}))
1247 (eq (char-before) ?
,)))
1249 (goto-char (line-beginning-position))
1250 (let ((indentation (python-indent-calculate-indentation)))
1251 (when (and (numberp indentation
) (< (current-indentation) indentation
))
1252 (indent-line-to indentation
)))))
1254 ((and (eq ?
: last-command-event
)
1255 (memq ?
: electric-indent-chars
)
1256 (not current-prefix-arg
)
1257 ;; Trigger electric colon only at end of line
1259 ;; Avoid re-indenting on extra colon
1260 (not (equal ?
: (char-before (1- (point)))))
1261 (not (python-syntax-comment-or-string-p)))
1262 ;; Just re-indent dedenters
1263 (let ((dedenter-pos (python-info-dedenter-statement-p))
1264 (current-pos (point)))
1267 (goto-char dedenter-pos
)
1268 (python-indent-line)
1269 (unless (= (line-number-at-pos dedenter-pos
)
1270 (line-number-at-pos current-pos
))
1271 ;; Reindent region if this is a multiline statement
1272 (python-indent-region dedenter-pos current-pos
)))))))))
1277 (defun python-mark-defun (&optional allow-extend
)
1278 "Put mark at end of this defun, point at beginning.
1279 The defun marked is the one that contains point or follows point.
1281 Interactively (or with ALLOW-EXTEND non-nil), if this command is
1282 repeated or (in Transient Mark mode) if the mark is active, it
1283 marks the next defun after the ones already marked."
1285 (when (python-info-looking-at-beginning-of-defun)
1287 (mark-defun allow-extend))
1292 (defvar python-nav-beginning-of-defun-regexp
1293 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1294 "Regexp matching class or function definition.
1295 The name of the defun should be grouped so it can be retrieved
1296 via `match-string'.")
1298 (defun python-nav--beginning-of-defun (&optional arg
)
1299 "Internal implementation of `python-nav-beginning-of-defun'.
1300 With positive ARG search backwards, else search forwards."
1301 (when (or (null arg
) (= arg
0)) (setq arg
1))
1302 (let* ((re-search-fn (if (> arg
0)
1303 #'re-search-backward
1304 #'re-search-forward
))
1305 (line-beg-pos (line-beginning-position))
1306 (line-content-start (+ line-beg-pos
(current-indentation)))
1307 (pos (point-marker))
1312 (not (python-info-looking-at-beginning-of-defun))
1313 (python-nav-backward-block)))
1314 (or (and (python-info-looking-at-beginning-of-defun)
1315 (+ (current-indentation) python-indent-offset
))
1319 (when (and (< arg
0)
1320 (python-info-looking-at-beginning-of-defun))
1322 (while (and (funcall re-search-fn
1323 python-nav-beginning-of-defun-regexp nil t
)
1324 (or (python-syntax-context-type)
1325 ;; Handle nested defuns when moving
1326 ;; backwards by checking indentation.
1328 (not (= (current-indentation) 0))
1329 (>= (current-indentation) beg-indentation
)))))
1330 (and (python-info-looking-at-beginning-of-defun)
1331 (or (not (= (line-number-at-pos pos
)
1332 (line-number-at-pos)))
1333 (and (>= (point) line-beg-pos
)
1334 (<= (point) line-content-start
)
1335 (> pos line-content-start
)))))))
1337 (or (beginning-of-line 1) t
)
1338 (and (goto-char pos
) nil
))))
1340 (defun python-nav-beginning-of-defun (&optional arg
)
1341 "Move point to `beginning-of-defun'.
1342 With positive ARG search backwards else search forward.
1343 ARG nil or 0 defaults to 1. When searching backwards,
1344 nested defuns are handled with care depending on current
1345 point position. Return non-nil if point is moved to
1346 `beginning-of-defun'."
1347 (when (or (null arg
) (= arg
0)) (setq arg
1))
1349 (while (and (not (= arg
0))
1350 (let ((keep-searching-p
1351 (python-nav--beginning-of-defun arg)))
1352 (when (and keep-searching-p
(null found
))
1355 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1358 (defun python-nav-end-of-defun ()
1359 "Move point to the end of def or class.
1360 Returns nil if point is not in a def or class."
1362 (let ((beg-defun-indent)
1364 (when (or (python-info-looking-at-beginning-of-defun)
1365 (python-nav-beginning-of-defun 1)
1366 (python-nav-beginning-of-defun -1))
1367 (setq beg-defun-indent
(current-indentation))
1369 (python-nav-end-of-statement)
1370 (python-util-forward-comment 1)
1371 (and (> (current-indentation) beg-defun-indent
)
1373 (python-util-forward-comment -
1)
1375 ;; Ensure point moves forward.
1376 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1378 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1379 "Move point using FN avoiding places with specific context.
1380 FN must take no arguments. POSCOMPFN is a two arguments function
1381 used to compare current and previous point after it is moved
1382 using FN, this is normally a less-than or greater-than
1383 comparison. Optional argument CONTEXTFN defaults to
1384 `python-syntax-context-type' and is used for checking current
1385 point context, it must return a non-nil value if this point must
1387 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1388 (start-pos (point-marker))
1393 (and (funcall fn
) (point-marker)))
1394 (context (funcall contextfn
)))
1395 (cond ((and (not context
) newpos
1396 (or (and (not prev-pos
) newpos
)
1397 (and prev-pos newpos
1398 (funcall poscompfn newpos prev-pos
))))
1399 (throw 'found
(point-marker)))
1400 ((and newpos context
)
1401 (setq prev-pos
(point)))
1402 (t (when (not newpos
) (goto-char start-pos
))
1403 (throw 'found nil
))))))))
1405 (defun python-nav--forward-defun (arg)
1406 "Internal implementation of python-nav-{backward,forward}-defun.
1407 Uses ARG to define which function to call, and how many times
1410 (while (and (> arg
0)
1412 (python-nav--syntactically
1415 python-nav-beginning-of-defun-regexp nil t
))
1417 (setq arg
(1- arg
)))
1418 (while (and (< arg
0)
1420 (python-nav--syntactically
1423 python-nav-beginning-of-defun-regexp nil t
))
1425 (setq arg
(1+ arg
)))
1428 (defun python-nav-backward-defun (&optional arg
)
1429 "Navigate to closer defun backward ARG times.
1430 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1431 nested definitions."
1433 (python-nav--forward-defun (- (or arg
1))))
1435 (defun python-nav-forward-defun (&optional arg
)
1436 "Navigate to closer defun forward ARG times.
1437 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1438 nested definitions."
1440 (python-nav--forward-defun (or arg
1)))
1442 (defun python-nav-beginning-of-statement ()
1443 "Move to start of current statement."
1445 (back-to-indentation)
1446 (let* ((ppss (syntax-ppss))
1449 (python-syntax-context 'paren ppss
)
1450 (python-syntax-context 'string ppss
))))
1453 (goto-char context-point
)
1454 (python-nav-beginning-of-statement))
1457 (python-info-line-ends-backslash-p))
1459 (python-nav-beginning-of-statement))))
1462 (defun python-nav-end-of-statement (&optional noend
)
1463 "Move to end of current statement.
1464 Optional argument NOEND is internal and makes the logic to not
1465 jump to the end of line when moving forward searching for the end
1468 (let (string-start bs-pos
)
1469 (while (and (or noend
(goto-char (line-end-position)))
1471 (cond ((setq string-start
(python-syntax-context 'string
))
1472 (goto-char string-start
)
1473 (if (python-syntax-context 'paren
)
1474 ;; Ended up inside a paren, roll again.
1475 (python-nav-end-of-statement t
)
1476 ;; This is not inside a paren, move to the
1477 ;; end of this string.
1478 (goto-char (+ (point)
1479 (python-syntax-count-quotes
1480 (char-after (point)) (point))))
1481 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1482 (goto-char (point-max)))))
1483 ((python-syntax-context 'paren
)
1484 ;; The statement won't end before we've escaped
1485 ;; at least one level of parenthesis.
1487 (goto-char (scan-lists (point) 1 -
1))
1488 (scan-error (goto-char (nth 3 err
)))))
1489 ((setq bs-pos
(python-info-line-ends-backslash-p))
1491 (forward-line 1))))))
1494 (defun python-nav-backward-statement (&optional arg
)
1495 "Move backward to previous statement.
1496 With ARG, repeat. See `python-nav-forward-statement'."
1498 (or arg
(setq arg
1))
1499 (python-nav-forward-statement (- arg
)))
1501 (defun python-nav-forward-statement (&optional arg
)
1502 "Move forward to next statement.
1503 With ARG, repeat. With negative argument, move ARG times
1504 backward to previous statement."
1506 (or arg
(setq arg
1))
1508 (python-nav-end-of-statement)
1509 (python-util-forward-comment)
1510 (python-nav-beginning-of-statement)
1511 (setq arg
(1- arg
)))
1513 (python-nav-beginning-of-statement)
1514 (python-util-forward-comment -
1)
1515 (python-nav-beginning-of-statement)
1516 (setq arg
(1+ arg
))))
1518 (defun python-nav-beginning-of-block ()
1519 "Move to start of current block."
1521 (let ((starting-pos (point)))
1523 (python-nav-beginning-of-statement)
1524 (looking-at (python-rx block-start
)))
1526 ;; Go to first line beginning a statement
1527 (while (and (not (bobp))
1528 (or (and (python-nav-beginning-of-statement) nil
)
1529 (python-info-current-line-comment-p)
1530 (python-info-current-line-empty-p)))
1532 (let ((block-matching-indent
1533 (- (current-indentation) python-indent-offset
)))
1535 (and (python-nav-backward-block)
1536 (> (current-indentation) block-matching-indent
)))
1537 (if (and (looking-at (python-rx block-start
))
1538 (= (current-indentation) block-matching-indent
))
1540 (and (goto-char starting-pos
) nil
))))))
1542 (defun python-nav-end-of-block ()
1543 "Move to end of current block."
1545 (when (python-nav-beginning-of-block)
1546 (let ((block-indentation (current-indentation)))
1547 (python-nav-end-of-statement)
1548 (while (and (forward-line 1)
1550 (or (and (> (current-indentation) block-indentation
)
1551 (or (python-nav-end-of-statement) t
))
1552 (python-info-current-line-comment-p)
1553 (python-info-current-line-empty-p))))
1554 (python-util-forward-comment -
1)
1557 (defun python-nav-backward-block (&optional arg
)
1558 "Move backward to previous block of code.
1559 With ARG, repeat. See `python-nav-forward-block'."
1561 (or arg
(setq arg
1))
1562 (python-nav-forward-block (- arg
)))
1564 (defun python-nav-forward-block (&optional arg
)
1565 "Move forward to next block of code.
1566 With ARG, repeat. With negative argument, move ARG times
1567 backward to previous block."
1569 (or arg
(setq arg
1))
1570 (let ((block-start-regexp
1571 (python-rx line-start
(* whitespace
) block-start
))
1572 (starting-pos (point)))
1574 (python-nav-end-of-statement)
1576 (re-search-forward block-start-regexp nil t
)
1577 (python-syntax-context-type)))
1578 (setq arg
(1- arg
)))
1580 (python-nav-beginning-of-statement)
1582 (re-search-backward block-start-regexp nil t
)
1583 (python-syntax-context-type)))
1584 (setq arg
(1+ arg
)))
1585 (python-nav-beginning-of-statement)
1586 (if (not (looking-at (python-rx block-start
)))
1587 (and (goto-char starting-pos
) nil
)
1588 (and (not (= (point) starting-pos
)) (point-marker)))))
1590 (defun python-nav--lisp-forward-sexp (&optional arg
)
1591 "Standard version `forward-sexp'.
1592 It ignores completely the value of `forward-sexp-function' by
1593 setting it to nil before calling `forward-sexp'. With positive
1594 ARG move forward only one sexp, else move backwards."
1595 (let ((forward-sexp-function)
1596 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1597 (forward-sexp arg
)))
1599 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1600 "Safe version of standard `forward-sexp'.
1601 When at end of sexp (i.e. looking at a opening/closing paren)
1602 skips it instead of throwing an error. With positive ARG move
1603 forward only one sexp, else move backwards."
1604 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1606 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1608 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1610 (python-nav--lisp-forward-sexp arg
)
1612 (while (and (funcall search-fn paren-regexp nil t
)
1613 (python-syntax-context 'paren
)))))))
1615 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p
)
1616 "Move to forward sexp.
1617 With positive optional argument DIR direction move forward, else
1618 backwards. When optional argument SAFE is non-nil do not throw
1619 errors when at end of sexp, skip it instead. With optional
1620 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1621 expressions when looking at them in either direction."
1622 (setq dir
(or dir
1))
1624 (let* ((forward-p (if (> dir
0)
1625 (and (setq dir
1) t
)
1626 (and (setq dir -
1) nil
)))
1627 (context-type (python-syntax-context-type)))
1629 ((memq context-type
'(string comment
))
1630 ;; Inside of a string, get out of it.
1631 (let ((forward-sexp-function))
1632 (forward-sexp dir
)))
1633 ((and (not skip-parens-p
)
1634 (or (eq context-type
'paren
)
1636 (eq (syntax-class (syntax-after (point)))
1637 (car (string-to-syntax "(")))
1638 (eq (syntax-class (syntax-after (1- (point))))
1639 (car (string-to-syntax ")"))))))
1640 ;; Inside a paren or looking at it, lisp knows what to do.
1642 (python-nav--lisp-forward-sexp-safe dir
)
1643 (python-nav--lisp-forward-sexp dir
)))
1645 ;; This part handles the lispy feel of
1646 ;; `python-nav-forward-sexp'. Knowing everything about the
1647 ;; current context and the context of the next sexp tries to
1648 ;; follow the lisp sexp motion commands in a symmetric manner.
1651 ((python-info-beginning-of-block-p) 'block-start
)
1652 ((python-info-end-of-block-p) 'block-end
)
1653 ((python-info-beginning-of-statement-p) 'statement-start
)
1654 ((python-info-end-of-statement-p) 'statement-end
)))
1658 (python-nav--lisp-forward-sexp-safe dir
)
1659 (python-nav--lisp-forward-sexp dir
))
1663 (goto-char next-sexp-pos
)
1665 ((python-info-beginning-of-block-p) 'block-start
)
1666 ((python-info-end-of-block-p) 'block-end
)
1667 ((python-info-beginning-of-statement-p) 'statement-start
)
1668 ((python-info-end-of-statement-p) 'statement-end
)
1669 ((python-info-statement-starts-block-p) 'starts-block
)
1670 ((python-info-statement-ends-block-p) 'ends-block
)))))
1672 (cond ((and (not (eobp))
1673 (python-info-current-line-empty-p))
1674 (python-util-forward-comment dir
)
1675 (python-nav--forward-sexp dir safe skip-parens-p
))
1676 ((eq context
'block-start
)
1677 (python-nav-end-of-block))
1678 ((eq context
'statement-start
)
1679 (python-nav-end-of-statement))
1680 ((and (memq context
'(statement-end block-end
))
1681 (eq next-sexp-context
'ends-block
))
1682 (goto-char next-sexp-pos
)
1683 (python-nav-end-of-block))
1684 ((and (memq context
'(statement-end block-end
))
1685 (eq next-sexp-context
'starts-block
))
1686 (goto-char next-sexp-pos
)
1687 (python-nav-end-of-block))
1688 ((memq context
'(statement-end block-end
))
1689 (goto-char next-sexp-pos
)
1690 (python-nav-end-of-statement))
1691 (t (goto-char next-sexp-pos
)))
1692 (cond ((and (not (bobp))
1693 (python-info-current-line-empty-p))
1694 (python-util-forward-comment dir
)
1695 (python-nav--forward-sexp dir safe skip-parens-p
))
1696 ((eq context
'block-end
)
1697 (python-nav-beginning-of-block))
1698 ((eq context
'statement-end
)
1699 (python-nav-beginning-of-statement))
1700 ((and (memq context
'(statement-start block-start
))
1701 (eq next-sexp-context
'starts-block
))
1702 (goto-char next-sexp-pos
)
1703 (python-nav-beginning-of-block))
1704 ((and (memq context
'(statement-start block-start
))
1705 (eq next-sexp-context
'ends-block
))
1706 (goto-char next-sexp-pos
)
1707 (python-nav-beginning-of-block))
1708 ((memq context
'(statement-start block-start
))
1709 (goto-char next-sexp-pos
)
1710 (python-nav-beginning-of-statement))
1711 (t (goto-char next-sexp-pos
))))))))))
1713 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p
)
1714 "Move forward across expressions.
1715 With ARG, do it that many times. Negative arg -N means move
1716 backward N times. When optional argument SAFE is non-nil do not
1717 throw errors when at end of sexp, skip it instead. With optional
1718 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1719 expressions when looking at them in either direction (forced to t
1720 in interactive calls)."
1722 (or arg
(setq arg
1))
1723 ;; Do not follow parens on interactive calls. This hack to detect
1724 ;; if the function was called interactively copes with the way
1725 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1726 ;; interactive detection by checking `current-prefix-arg'. The
1727 ;; reason to make this distinction is that lisp functions like
1728 ;; `blink-matching-open' get confused causing issues like the one in
1729 ;; Bug#16191. With this approach the user gets a symmetric behavior
1730 ;; when working interactively while called functions expecting
1731 ;; paren-based sexp motion work just fine.
1735 (memq real-this-command
1737 #'forward-sexp
#'backward-sexp
1738 #'python-nav-forward-sexp
#'python-nav-backward-sexp
1739 #'python-nav-forward-sexp-safe
#'python-nav-backward-sexp
))))
1741 (python-nav--forward-sexp 1 safe skip-parens-p
)
1742 (setq arg
(1- arg
)))
1744 (python-nav--forward-sexp -
1 safe skip-parens-p
)
1745 (setq arg
(1+ arg
))))
1747 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p
)
1748 "Move backward across expressions.
1749 With ARG, do it that many times. Negative arg -N means move
1750 forward N times. When optional argument SAFE is non-nil do not
1751 throw errors when at end of sexp, skip it instead. With optional
1752 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1753 expressions when looking at them in either direction (forced to t
1754 in interactive calls)."
1756 (or arg
(setq arg
1))
1757 (python-nav-forward-sexp (- arg
) safe skip-parens-p
))
1759 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p
)
1760 "Move forward safely across expressions.
1761 With ARG, do it that many times. Negative arg -N means move
1762 backward N times. With optional argument SKIP-PARENS-P force
1763 sexp motion to ignore parenthesized expressions when looking at
1764 them in either direction (forced to t in interactive calls)."
1766 (python-nav-forward-sexp arg t skip-parens-p
))
1768 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p
)
1769 "Move backward safely across expressions.
1770 With ARG, do it that many times. Negative arg -N means move
1771 forward N times. With optional argument SKIP-PARENS-P force sexp
1772 motion to ignore parenthesized expressions when looking at them in
1773 either direction (forced to t in interactive calls)."
1775 (python-nav-backward-sexp arg t skip-parens-p
))
1777 (defun python-nav--up-list (&optional dir
)
1778 "Internal implementation of `python-nav-up-list'.
1779 DIR is always 1 or -1 and comes sanitized from
1780 `python-nav-up-list' calls."
1781 (let ((context (python-syntax-context-type))
1782 (forward-p (> dir
0)))
1784 ((memq context
'(string comment
)))
1785 ((eq context
'paren
)
1786 (let ((forward-sexp-function))
1788 ((and forward-p
(python-info-end-of-block-p))
1789 (let ((parent-end-pos
1791 (let ((indentation (and
1792 (python-nav-beginning-of-block)
1793 (current-indentation))))
1794 (while (and indentation
1796 (>= (current-indentation) indentation
)
1797 (python-nav-backward-block)))
1798 (python-nav-end-of-block)))))
1799 (and (> (or parent-end-pos
(point)) (point))
1800 (goto-char parent-end-pos
))))
1801 (forward-p (python-nav-end-of-block))
1802 ((and (not forward-p
)
1803 (> (current-indentation) 0)
1804 (python-info-beginning-of-block-p))
1805 (let ((prev-block-pos
1807 (let ((indentation (current-indentation)))
1808 (while (and (python-nav-backward-block)
1809 (>= (current-indentation) indentation
))))
1811 (and (> (point) prev-block-pos
)
1812 (goto-char prev-block-pos
))))
1813 ((not forward-p
) (python-nav-beginning-of-block)))))
1815 (defun python-nav-up-list (&optional arg
)
1816 "Move forward out of one level of parentheses (or blocks).
1817 With ARG, do this that many times.
1818 A negative argument means move backward but still to a less deep spot.
1819 This command assumes point is not in a string or comment."
1821 (or arg
(setq arg
1))
1823 (python-nav--up-list 1)
1824 (setq arg
(1- arg
)))
1826 (python-nav--up-list -
1)
1827 (setq arg
(1+ arg
))))
1829 (defun python-nav-backward-up-list (&optional arg
)
1830 "Move backward out of one level of parentheses (or blocks).
1831 With ARG, do this that many times.
1832 A negative argument means move forward but still to a less deep spot.
1833 This command assumes point is not in a string or comment."
1835 (or arg
(setq arg
1))
1836 (python-nav-up-list (- arg
)))
1838 (defun python-nav-if-name-main ()
1839 "Move point at the beginning the __main__ block.
1840 When \"if __name__ == '__main__':\" is found returns its
1841 position, else returns nil."
1843 (let ((point (point))
1844 (found (catch 'found
1845 (goto-char (point-min))
1846 (while (re-search-forward
1847 (python-rx line-start
1849 "__name__" (+ space
)
1851 (group-n 1 (or ?
\" ?
\'))
1852 "__main__" (backref 1) (* space
) ":")
1854 (when (not (python-syntax-context-type))
1856 (throw 'found t
))))))
1859 (ignore (goto-char point
)))))
1862 ;;; Shell integration
1864 (defcustom python-shell-buffer-name
"Python"
1865 "Default buffer name for Python interpreter."
1870 (defcustom python-shell-interpreter
"python"
1871 "Default Python interpreter for shell."
1875 (defcustom python-shell-internal-buffer-name
"Python Internal"
1876 "Default buffer name for the Internal Python interpreter."
1881 (defcustom python-shell-interpreter-args
"-i"
1882 "Default arguments for the Python interpreter."
1886 (defcustom python-shell-interpreter-interactive-arg
"-i"
1887 "Interpreter argument to force it to run interactively."
1891 (defcustom python-shell-prompt-detect-enabled t
1892 "Non-nil enables autodetection of interpreter prompts."
1897 (defcustom python-shell-prompt-detect-failure-warning t
1898 "Non-nil enables warnings when detection of prompts fail."
1903 (defcustom python-shell-prompt-input-regexps
1904 '(">>> " "\\.\\.\\. " ; Python
1905 "In \\[[0-9]+\\]: " ; IPython
1906 " \\.\\.\\.: " ; IPython
1907 ;; Using ipdb outside IPython may fail to cleanup and leave static
1908 ;; IPython prompts activated, this adds some safeguard for that.
1909 "In : " "\\.\\.\\.: ")
1910 "List of regular expressions matching input prompts."
1911 :type
'(repeat string
)
1914 (defcustom python-shell-prompt-output-regexps
1916 "Out\\[[0-9]+\\]: " ; IPython
1917 "Out :") ; ipdb safeguard
1918 "List of regular expressions matching output prompts."
1919 :type
'(repeat string
)
1922 (defcustom python-shell-prompt-regexp
">>> "
1923 "Regular expression matching top level input prompt of Python shell.
1924 It should not contain a caret (^) at the beginning."
1927 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1928 "Regular expression matching block input prompt of Python shell.
1929 It should not contain a caret (^) at the beginning."
1932 (defcustom python-shell-prompt-output-regexp
""
1933 "Regular expression matching output prompt of Python shell.
1934 It should not contain a caret (^) at the beginning."
1937 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1938 "Regular expression matching pdb input prompt of Python shell.
1939 It should not contain a caret (^) at the beginning."
1942 (define-obsolete-variable-alias
1943 'python-shell-enable-font-lock
'python-shell-font-lock-enable
"25.1")
1945 (defcustom python-shell-font-lock-enable t
1946 "Should syntax highlighting be enabled in the Python shell buffer?
1947 Restart the Python shell after changing this variable for it to take effect."
1952 (defcustom python-shell-unbuffered t
1953 "Should shell output be unbuffered?.
1954 When non-nil, this may prevent delayed and missing output in the
1955 Python shell. See commentary for details."
1960 (defcustom python-shell-process-environment nil
1961 "List of overridden environment variables for subprocesses to inherit.
1962 Each element should be a string of the form ENVVARNAME=VALUE.
1963 When this variable is non-nil, values are exported into the
1964 process environment before starting it. Any variables already
1965 present in the current environment are superseded by variables
1967 :type
'(repeat string
)
1970 (defcustom python-shell-extra-pythonpaths nil
1971 "List of extra pythonpaths for Python shell.
1972 When this variable is non-nil, values added at the beginning of
1973 the PYTHONPATH before starting processes. Any values present
1974 here that already exists in PYTHONPATH are moved to the beginning
1975 of the list so that they are prioritized when looking for
1977 :type
'(repeat string
)
1980 (defcustom python-shell-exec-path nil
1981 "List of paths for searching executables.
1982 When this variable is non-nil, values added at the beginning of
1983 the PATH before starting processes. Any values present here that
1984 already exists in PATH are moved to the beginning of the list so
1985 that they are prioritized when looking for executables."
1986 :type
'(repeat string
)
1989 (defcustom python-shell-remote-exec-path nil
1990 "List of paths to be ensured remotely for searching executables.
1991 When this variable is non-nil, values are exported into remote
1992 hosts PATH before starting processes. Values defined in
1993 `python-shell-exec-path' will take precedence to paths defined
1994 here. Normally you wont use this variable directly unless you
1995 plan to ensure a particular set of paths to all Python shell
1996 executed through tramp connections."
1997 :type
'(repeat string
)
2000 (defcustom python-shell-virtualenv-root nil
2001 "Path to virtualenv root.
2002 This variable, when set to a string, makes the environment to be
2003 modified such that shells are started within the specified
2005 :type
'(choice (const nil
) string
)
2008 (define-obsolete-variable-alias
2009 'python-shell-virtualenv-path
'python-shell-virtualenv-root
"25.1")
2011 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
2012 python-ffap-setup-code
2013 python-eldoc-setup-code
)
2014 "List of code run by `python-shell-send-setup-codes'."
2015 :type
'(repeat symbol
)
2018 (defcustom python-shell-compilation-regexp-alist
2019 `((,(rx line-start
(1+ (any " \t")) "File \""
2020 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
2021 "\", line " (group (1+ digit
)))
2023 (,(rx " in file " (group (1+ not-newline
)) " on line "
2026 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
2027 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
2029 "`compilation-error-regexp-alist' for inferior Python."
2030 :type
'(alist string
)
2033 (defmacro python-shell--add-to-path-with-priority
(pathvar paths
)
2034 "Modify PATHVAR and ensure PATHS are added only once at beginning."
2035 `(dolist (path (reverse ,paths
))
2036 (cl-delete path
,pathvar
:test
#'string
=)
2037 (cl-pushnew path
,pathvar
:test
#'string
=)))
2039 (defun python-shell-calculate-pythonpath ()
2040 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2042 (tramp-compat-split-string
2043 (or (getenv "PYTHONPATH") "") path-separator
)))
2044 (python-shell--add-to-path-with-priority
2045 pythonpath python-shell-extra-pythonpaths
)
2046 (mapconcat 'identity pythonpath path-separator
)))
2048 (defun python-shell-calculate-process-environment ()
2049 "Calculate `process-environment' or `tramp-remote-process-environment'.
2050 Prepends `python-shell-process-environment', sets extra
2051 pythonpaths from `python-shell-extra-pythonpaths' and sets a few
2052 virtualenv related vars. If `default-directory' points to a
2053 remote host, the returned value is intended for
2054 `tramp-remote-process-environment'."
2055 (let* ((remote-p (file-remote-p default-directory
))
2056 (process-environment (if remote-p
2057 tramp-remote-process-environment
2058 process-environment
))
2059 (virtualenv (when python-shell-virtualenv-root
2060 (directory-file-name python-shell-virtualenv-root
))))
2061 (dolist (env python-shell-process-environment
)
2062 (pcase-let ((`(,key
,value
) (split-string env
"=")))
2063 (setenv key value
)))
2064 (when python-shell-unbuffered
2065 (setenv "PYTHONUNBUFFERED" "1"))
2066 (when python-shell-extra-pythonpaths
2067 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2068 (if (not virtualenv
)
2070 (setenv "PYTHONHOME" nil
)
2071 (setenv "VIRTUAL_ENV" virtualenv
))
2072 process-environment
))
2074 (defun python-shell-calculate-exec-path ()
2075 "Calculate `exec-path'.
2076 Prepends `python-shell-exec-path' and adds the binary directory
2077 for virtualenv if `python-shell-virtualenv-root' is set. If
2078 `default-directory' points to a remote host, the returned value
2079 appends `python-shell-remote-exec-path' instead of `exec-path'."
2080 (let ((new-path (copy-sequence
2081 (if (file-remote-p default-directory
)
2082 python-shell-remote-exec-path
2084 (python-shell--add-to-path-with-priority
2085 new-path python-shell-exec-path
)
2086 (if (not python-shell-virtualenv-root
)
2088 (python-shell--add-to-path-with-priority
2090 (list (expand-file-name "bin" python-shell-virtualenv-root
)))
2093 (defun python-shell-tramp-refresh-remote-path (vec paths
)
2094 "Update VEC's remote-path giving PATHS priority."
2095 (let ((remote-path (tramp-get-connection-property vec
"remote-path" nil
)))
2097 (python-shell--add-to-path-with-priority remote-path paths
)
2098 (tramp-set-connection-property vec
"remote-path" remote-path
)
2099 (tramp-set-remote-path vec
))))
2101 (defun python-shell-tramp-refresh-process-environment (vec env
)
2102 "Update VEC's process environment with ENV."
2103 ;; Stolen from `tramp-open-connection-setup-interactive-shell'.
2104 (let ((env (append `(,(tramp-get-remote-locale vec
))
2105 (copy-sequence env
)))
2108 (setq item
(tramp-compat-split-string (car env
) "="))
2109 (setcdr item
(mapconcat 'identity
(cdr item
) "="))
2110 (if (and (stringp (cdr item
)) (not (string-equal (cdr item
) "")))
2111 (push (format "%s %s" (car item
) (cdr item
)) vars
)
2112 (push (car item
) unset
))
2113 (setq env
(cdr env
)))
2117 (format "while read var val; do export $var=$val; done <<'%s'\n%s\n%s"
2118 tramp-end-of-heredoc
2119 (mapconcat 'identity vars
"\n")
2120 tramp-end-of-heredoc
)
2124 vec
(format "unset %s" (mapconcat 'identity unset
" ")) t
))))
2126 (defmacro python-shell-with-environment
(&rest body
)
2127 "Modify shell environment during execution of BODY.
2128 Temporarily sets `process-environment' and `exec-path' during
2129 execution of body. If `default-directory' points to a remote
2130 machine then modifies `tramp-remote-process-environment' and
2131 `python-shell-remote-exec-path' instead."
2132 (declare (indent 0) (debug (body)))
2133 (let ((vec (make-symbol "vec")))
2136 (when (file-remote-p default-directory
)
2138 (tramp-dissect-file-name default-directory
'noexpand
))))
2139 (process-environment
2142 (python-shell-calculate-process-environment)))
2146 (python-shell-calculate-exec-path)))
2147 (tramp-remote-process-environment
2149 (python-shell-calculate-process-environment)
2150 tramp-remote-process-environment
)))
2151 (when (tramp-get-connection-process ,vec
)
2152 ;; For already existing connections, the new exec path must
2153 ;; be re-set, otherwise it won't take effect. One example
2154 ;; of such case is when remote dir-locals are read and
2155 ;; *then* subprocesses are triggered within the same
2157 (python-shell-tramp-refresh-remote-path
2158 ,vec
(python-shell-calculate-exec-path))
2159 ;; The `tramp-remote-process-environment' variable is only
2160 ;; effective when the started process is an interactive
2161 ;; shell, otherwise (like in the case of processes started
2162 ;; with `process-file') the environment is not changed.
2163 ;; This makes environment modifications effective
2165 (python-shell-tramp-refresh-process-environment
2166 ,vec tramp-remote-process-environment
))
2167 ,(macroexp-progn body
)))))
2169 (defvar python-shell--prompt-calculated-input-regexp nil
2170 "Calculated input prompt regexp for inferior python shell.
2171 Do not set this variable directly, instead use
2172 `python-shell-prompt-set-calculated-regexps'.")
2174 (defvar python-shell--prompt-calculated-output-regexp nil
2175 "Calculated output prompt regexp for inferior python shell.
2176 Do not set this variable directly, instead use
2177 `python-shell-set-prompt-regexp'.")
2179 (defun python-shell-prompt-detect ()
2180 "Detect prompts for the current `python-shell-interpreter'.
2181 When prompts can be retrieved successfully from the
2182 `python-shell-interpreter' run with
2183 `python-shell-interpreter-interactive-arg', returns a list of
2184 three elements, where the first two are input prompts and the
2185 last one is an output prompt. When no prompts can be detected
2186 and `python-shell-prompt-detect-failure-warning' is non-nil,
2187 shows a warning with instructions to avoid hangs and returns nil.
2188 When `python-shell-prompt-detect-enabled' is nil avoids any
2189 detection and just returns nil."
2190 (when python-shell-prompt-detect-enabled
2191 (python-shell-with-environment
2192 (let* ((code (concat
2194 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2195 ;; JSON is built manually for compatibility
2196 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2201 ;; TODO: improve error handling by using
2202 ;; `condition-case' and displaying the error message to
2203 ;; the user in the no-prompts warning.
2205 (let ((code-file (python-shell--save-temp-file code
)))
2206 ;; Use `process-file' as it is remote-host friendly.
2208 python-shell-interpreter
2212 python-shell-interpreter-interactive-arg
)
2214 (delete-file code-file
)))
2218 (dolist (line (split-string output
"\n" t
))
2220 ;; Check if current line is a valid JSON array
2221 (and (string= (substring line
0 2) "[\"")
2223 ;; Return prompts as a list, not vector
2224 (append (json-read-from-string line
) nil
)))))
2225 ;; The list must contain 3 strings, where the first
2226 ;; is the input prompt, the second is the block
2227 ;; prompt and the last one is the output prompt. The
2228 ;; input prompt is the only one that can't be empty.
2229 (when (and (= (length res
) 3)
2230 (cl-every #'stringp res
)
2231 (not (string= (car res
) "")))
2232 (throw 'prompts res
))))
2234 (when (and (not prompts
)
2235 python-shell-prompt-detect-failure-warning
)
2237 '(python python-shell-prompt-regexp
)
2240 "Python shell prompts cannot be detected.\n"
2241 "If your emacs session hangs when starting python shells\n"
2242 "recover with `keyboard-quit' and then try fixing the\n"
2243 "interactive flag for your interpreter by adjusting the\n"
2244 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2245 "matching shell prompts in the directory-local friendly vars:\n"
2246 " + `python-shell-prompt-regexp'\n"
2247 " + `python-shell-prompt-block-regexp'\n"
2248 " + `python-shell-prompt-output-regexp'\n"
2249 "Or alternatively in:\n"
2250 " + `python-shell-prompt-input-regexps'\n"
2251 " + `python-shell-prompt-output-regexps'")))
2254 (defun python-shell-prompt-validate-regexps ()
2255 "Validate all user provided regexps for prompts.
2256 Signals `user-error' if any of these vars contain invalid
2257 regexps: `python-shell-prompt-regexp',
2258 `python-shell-prompt-block-regexp',
2259 `python-shell-prompt-pdb-regexp',
2260 `python-shell-prompt-output-regexp',
2261 `python-shell-prompt-input-regexps',
2262 `python-shell-prompt-output-regexps'."
2263 (dolist (symbol (list 'python-shell-prompt-input-regexps
2264 'python-shell-prompt-output-regexps
2265 'python-shell-prompt-regexp
2266 'python-shell-prompt-block-regexp
2267 'python-shell-prompt-pdb-regexp
2268 'python-shell-prompt-output-regexp
))
2269 (dolist (regexp (let ((regexps (symbol-value symbol
)))
2273 (when (not (python-util-valid-regexp-p regexp
))
2274 (user-error "Invalid regexp %s in `%s'"
2277 (defun python-shell-prompt-set-calculated-regexps ()
2278 "Detect and set input and output prompt regexps.
2279 Build and set the values for `python-shell-input-prompt-regexp'
2280 and `python-shell-output-prompt-regexp' using the values from
2281 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2282 `python-shell-prompt-pdb-regexp',
2283 `python-shell-prompt-output-regexp',
2284 `python-shell-prompt-input-regexps',
2285 `python-shell-prompt-output-regexps' and detected prompts from
2286 `python-shell-prompt-detect'."
2287 (when (not (and python-shell--prompt-calculated-input-regexp
2288 python-shell--prompt-calculated-output-regexp
))
2289 (let* ((detected-prompts (python-shell-prompt-detect))
2291 (output-prompts nil
)
2295 (mapconcat #'identity
2298 (let ((length-a (length a
))
2299 (length-b (length b
)))
2300 (if (= length-a length-b
)
2302 (> (length a
) (length b
))))))
2305 ;; Validate ALL regexps
2306 (python-shell-prompt-validate-regexps)
2307 ;; Collect all user defined input prompts
2308 (dolist (prompt (append python-shell-prompt-input-regexps
2309 (list python-shell-prompt-regexp
2310 python-shell-prompt-block-regexp
2311 python-shell-prompt-pdb-regexp
)))
2312 (cl-pushnew prompt input-prompts
:test
#'string
=))
2313 ;; Collect all user defined output prompts
2314 (dolist (prompt (cons python-shell-prompt-output-regexp
2315 python-shell-prompt-output-regexps
))
2316 (cl-pushnew prompt output-prompts
:test
#'string
=))
2317 ;; Collect detected prompts if any
2318 (when detected-prompts
2319 (dolist (prompt (butlast detected-prompts
))
2320 (setq prompt
(regexp-quote prompt
))
2321 (cl-pushnew prompt input-prompts
:test
#'string
=))
2322 (cl-pushnew (regexp-quote
2323 (car (last detected-prompts
)))
2324 output-prompts
:test
#'string
=))
2325 ;; Set input and output prompt regexps from collected prompts
2326 (setq python-shell--prompt-calculated-input-regexp
2327 (funcall build-regexp input-prompts
)
2328 python-shell--prompt-calculated-output-regexp
2329 (funcall build-regexp output-prompts
)))))
2331 (defun python-shell-get-process-name (dedicated)
2332 "Calculate the appropriate process name for inferior Python process.
2333 If DEDICATED is t returns a string with the form
2334 `python-shell-buffer-name'[`buffer-name'] else returns the value
2335 of `python-shell-buffer-name'."
2337 (format "%s[%s]" python-shell-buffer-name
(buffer-name))
2338 python-shell-buffer-name
))
2340 (defun python-shell-internal-get-process-name ()
2341 "Calculate the appropriate process name for Internal Python process.
2342 The name is calculated from `python-shell-global-buffer-name' and
2344 (format "%s[%s]" python-shell-internal-buffer-name
(buffer-name)))
2346 (defun python-shell-calculate-command ()
2347 "Calculate the string used to execute the inferior Python process."
2349 (shell-quote-argument python-shell-interpreter
)
2350 python-shell-interpreter-args
))
2352 (define-obsolete-function-alias
2353 'python-shell-parse-command
2354 #'python-shell-calculate-command
"25.1")
2356 (defvar python-shell--package-depth
10)
2358 (defun python-shell-package-enable (directory package
)
2359 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2361 (let* ((dir (expand-file-name
2362 (read-directory-name
2364 (file-name-directory
2365 (or (buffer-file-name) default-directory
)))))
2366 (name (completing-read
2368 (python-util-list-packages
2369 dir python-shell--package-depth
))))
2371 (python-shell-send-string
2374 "import os.path;import sys;"
2375 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2376 "__package__ = '''%s''';"
2378 directory package package
)
2379 (python-shell-get-process)))
2381 (defun python-shell-accept-process-output (process &optional timeout regexp
)
2382 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2383 Optional argument TIMEOUT is the timeout argument to
2384 `accept-process-output' calls. Optional argument REGEXP
2385 overrides the regexp to match the end of output, defaults to
2386 `comint-prompt-regexp.'. Returns non-nil when output was
2389 This utility is useful in situations where the output may be
2390 received in chunks, since `accept-process-output' gives no
2391 guarantees they will be grabbed in a single call. An example use
2392 case for this would be the CPython shell start-up, where the
2393 banner and the initial prompt are received separately."
2394 (let ((regexp (or regexp comint-prompt-regexp
)))
2397 (when (not (accept-process-output process timeout
))
2400 regexp
(car (python-util-comint-last-prompt)))
2401 (throw 'found t
))))))
2403 (defun python-shell-comint-end-of-output-p (output)
2404 "Return non-nil if OUTPUT is ends with input prompt."
2406 ;; XXX: It seems on OSX an extra carriage return is attached
2407 ;; at the end of output, this handles that too.
2410 ;; Remove initial caret from calculated regexp
2411 (replace-regexp-in-string
2412 (rx string-start ?^
) ""
2413 python-shell--prompt-calculated-input-regexp
)
2417 (define-obsolete-function-alias
2418 'python-comint-output-filter-function
2419 'ansi-color-filter-apply
2422 (defun python-comint-postoutput-scroll-to-bottom (output)
2423 "Faster version of `comint-postoutput-scroll-to-bottom'.
2424 Avoids `recenter' calls until OUTPUT is completely sent."
2425 (when (and (not (string= "" output
))
2426 (python-shell-comint-end-of-output-p
2427 (ansi-color-filter-apply output
)))
2428 (comint-postoutput-scroll-to-bottom output
))
2431 (defvar python-shell--parent-buffer nil
)
2433 (defmacro python-shell-with-shell-buffer
(&rest body
)
2434 "Execute the forms in BODY with the shell buffer temporarily current.
2435 Signals an error if no shell buffer is available for current buffer."
2436 (declare (indent 0) (debug t
))
2437 (let ((shell-process (make-symbol "shell-process")))
2438 `(let ((,shell-process
(python-shell-get-process-or-error)))
2439 (with-current-buffer (process-buffer ,shell-process
)
2442 (defvar python-shell--font-lock-buffer nil
)
2444 (defun python-shell-font-lock-get-or-create-buffer ()
2445 "Get or create a font-lock buffer for current inferior process."
2446 (python-shell-with-shell-buffer
2447 (if python-shell--font-lock-buffer
2448 python-shell--font-lock-buffer
2450 (process-name (get-buffer-process (current-buffer)))))
2451 (generate-new-buffer
2452 (format " *%s-font-lock*" process-name
))))))
2454 (defun python-shell-font-lock-kill-buffer ()
2455 "Kill the font-lock buffer safely."
2456 (when (and python-shell--font-lock-buffer
2457 (buffer-live-p python-shell--font-lock-buffer
))
2458 (kill-buffer python-shell--font-lock-buffer
)
2459 (when (derived-mode-p 'inferior-python-mode
)
2460 (setq python-shell--font-lock-buffer nil
))))
2462 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2463 "Execute the forms in BODY in the font-lock buffer.
2464 The value returned is the value of the last form in BODY. See
2465 also `with-current-buffer'."
2466 (declare (indent 0) (debug t
))
2467 `(python-shell-with-shell-buffer
2468 (save-current-buffer
2469 (when (not (and python-shell--font-lock-buffer
2470 (get-buffer python-shell--font-lock-buffer
)))
2471 (setq python-shell--font-lock-buffer
2472 (python-shell-font-lock-get-or-create-buffer)))
2473 (set-buffer python-shell--font-lock-buffer
)
2474 (when (not font-lock-mode
)
2476 (set (make-local-variable 'delay-mode-hooks
) t
)
2477 (let ((python-indent-guess-indent-offset nil
))
2478 (when (not (derived-mode-p 'python-mode
))
2482 (defun python-shell-font-lock-cleanup-buffer ()
2483 "Cleanup the font-lock buffer.
2484 Provided as a command because this might be handy if something
2485 goes wrong and syntax highlighting in the shell gets messed up."
2487 (python-shell-with-shell-buffer
2488 (python-shell-font-lock-with-font-lock-buffer
2491 (defun python-shell-font-lock-comint-output-filter-function (output)
2492 "Clean up the font-lock buffer after any OUTPUT."
2493 (if (and (not (string= "" output
))
2494 ;; Is end of output and is not just a prompt.
2496 (python-shell-comint-end-of-output-p
2497 (ansi-color-filter-apply output
))
2499 ;; If output is other than an input prompt then "real" output has
2500 ;; been received and the font-lock buffer must be cleaned up.
2501 (python-shell-font-lock-cleanup-buffer)
2502 ;; Otherwise just add a newline.
2503 (python-shell-font-lock-with-font-lock-buffer
2504 (goto-char (point-max))
2508 (defun python-shell-font-lock-post-command-hook ()
2509 "Fontifies current line in shell buffer."
2510 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2511 (when (and prompt-end
(> (point) prompt-end
)
2512 (process-live-p (get-buffer-process (current-buffer))))
2513 (let* ((input (buffer-substring-no-properties
2514 prompt-end
(point-max)))
2515 (deactivate-mark nil
)
2516 (start-pos prompt-end
)
2517 (buffer-undo-list t
)
2518 (font-lock-buffer-pos nil
)
2520 (python-shell-font-lock-with-font-lock-buffer
2521 (delete-region (line-beginning-position)
2523 (setq font-lock-buffer-pos
(point))
2525 ;; Ensure buffer is fontified, keeping it
2526 ;; compatible with Emacs < 24.4.
2527 (if (fboundp 'font-lock-ensure
)
2528 (funcall 'font-lock-ensure
)
2529 (font-lock-default-fontify-buffer))
2530 (buffer-substring font-lock-buffer-pos
2532 (replacement-length (length replacement
))
2534 ;; Inject text properties to get input fontified.
2535 (while (not (= i replacement-length
))
2536 (let* ((plist (text-properties-at i replacement
))
2537 (next-change (or (next-property-change i replacement
)
2538 replacement-length
))
2539 (plist (let ((face (plist-get plist
'face
)))
2542 ;; Replace FACE text properties with
2543 ;; FONT-LOCK-FACE so input is fontified.
2544 (plist-put plist
'face nil
)
2545 (plist-put plist
'font-lock-face face
)))))
2546 (set-text-properties
2547 (+ start-pos i
) (+ start-pos next-change
) plist
)
2548 (setq i next-change
)))))))
2550 (defun python-shell-font-lock-turn-on (&optional msg
)
2551 "Turn on shell font-lock.
2552 With argument MSG show activation message."
2554 (python-shell-with-shell-buffer
2555 (python-shell-font-lock-kill-buffer)
2556 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2557 (add-hook 'post-command-hook
2558 #'python-shell-font-lock-post-command-hook nil
'local
)
2559 (add-hook 'kill-buffer-hook
2560 #'python-shell-font-lock-kill-buffer nil
'local
)
2561 (add-hook 'comint-output-filter-functions
2562 #'python-shell-font-lock-comint-output-filter-function
2565 (message "Shell font-lock is enabled"))))
2567 (defun python-shell-font-lock-turn-off (&optional msg
)
2568 "Turn off shell font-lock.
2569 With argument MSG show deactivation message."
2571 (python-shell-with-shell-buffer
2572 (python-shell-font-lock-kill-buffer)
2573 (when (python-util-comint-last-prompt)
2574 ;; Cleanup current fontification
2575 (remove-text-properties
2576 (cdr (python-util-comint-last-prompt))
2578 '(face nil font-lock-face nil
)))
2579 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2580 (remove-hook 'post-command-hook
2581 #'python-shell-font-lock-post-command-hook
'local
)
2582 (remove-hook 'kill-buffer-hook
2583 #'python-shell-font-lock-kill-buffer
'local
)
2584 (remove-hook 'comint-output-filter-functions
2585 #'python-shell-font-lock-comint-output-filter-function
2588 (message "Shell font-lock is disabled"))))
2590 (defun python-shell-font-lock-toggle (&optional msg
)
2591 "Toggle font-lock for shell.
2592 With argument MSG show activation/deactivation message."
2594 (python-shell-with-shell-buffer
2595 (set (make-local-variable 'python-shell-font-lock-enable
)
2596 (not python-shell-font-lock-enable
))
2597 (if python-shell-font-lock-enable
2598 (python-shell-font-lock-turn-on msg
)
2599 (python-shell-font-lock-turn-off msg
))
2600 python-shell-font-lock-enable
))
2602 ;; Used to hold user interactive overrides to
2603 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2604 ;; will be made buffer-local by `inferior-python-mode':
2605 (defvar python-shell--interpreter
)
2606 (defvar python-shell--interpreter-args
)
2608 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2609 "Major mode for Python inferior process.
2610 Runs a Python interpreter as a subprocess of Emacs, with Python
2611 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2612 and `python-shell-interpreter-args' control which Python
2613 interpreter is run. Variables
2614 `python-shell-prompt-regexp',
2615 `python-shell-prompt-output-regexp',
2616 `python-shell-prompt-block-regexp',
2617 `python-shell-font-lock-enable',
2618 `python-shell-completion-setup-code',
2619 `python-shell-completion-string-code',
2620 `python-eldoc-setup-code', `python-eldoc-string-code',
2621 `python-ffap-setup-code' and `python-ffap-string-code' can
2622 customize this mode for different Python interpreters.
2624 This mode resets `comint-output-filter-functions' locally, so you
2625 may want to re-add custom functions to it using the
2626 `inferior-python-mode-hook'.
2628 You can also add additional setup code to be run at
2629 initialization of the interpreter via `python-shell-setup-codes'
2632 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2633 (when python-shell--parent-buffer
2634 (python-util-clone-local-variables python-shell--parent-buffer
))
2635 ;; Users can interactively override default values for
2636 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2637 ;; when calling `run-python'. This ensures values let-bound in
2638 ;; `python-shell-make-comint' are locally set if needed.
2639 (set (make-local-variable 'python-shell-interpreter
)
2640 (or python-shell--interpreter python-shell-interpreter
))
2641 (set (make-local-variable 'python-shell-interpreter-args
)
2642 (or python-shell--interpreter-args python-shell-interpreter-args
))
2643 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2644 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2645 (python-shell-prompt-set-calculated-regexps)
2646 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2647 (set (make-local-variable 'comint-prompt-read-only
) t
)
2648 (setq mode-line-process
'(":%s"))
2649 (set (make-local-variable 'comint-output-filter-functions
)
2650 '(ansi-color-process-output
2651 python-pdbtrack-comint-output-filter-function
2652 python-comint-postoutput-scroll-to-bottom
))
2653 (set (make-local-variable 'compilation-error-regexp-alist
)
2654 python-shell-compilation-regexp-alist
)
2655 (add-hook 'completion-at-point-functions
2656 #'python-shell-completion-at-point nil
'local
)
2657 (define-key inferior-python-mode-map
"\t"
2658 'python-shell-completion-complete-or-indent
)
2659 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2660 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2661 (make-local-variable 'python-shell-internal-last-output
)
2662 (when python-shell-font-lock-enable
2663 (python-shell-font-lock-turn-on))
2664 (compilation-shell-minor-mode 1)
2665 (python-shell-accept-process-output
2666 (get-buffer-process (current-buffer))))
2668 (defun python-shell-make-comint (cmd proc-name
&optional show internal
)
2669 "Create a Python shell comint buffer.
2670 CMD is the Python command to be executed and PROC-NAME is the
2671 process name the comint buffer will get. After the comint buffer
2672 is created the `inferior-python-mode' is activated. When
2673 optional argument SHOW is non-nil the buffer is shown. When
2674 optional argument INTERNAL is non-nil this process is run on a
2675 buffer with a name that starts with a space, following the Emacs
2676 convention for temporary/internal buffers, and also makes sure
2677 the user is not queried for confirmation when the process is
2680 (python-shell-with-environment
2681 (let* ((proc-buffer-name
2682 (format (if (not internal
) "*%s*" " *%s*") proc-name
)))
2683 (when (not (comint-check-proc proc-buffer-name
))
2684 (let* ((cmdlist (split-string-and-unquote cmd
))
2685 (interpreter (car cmdlist
))
2686 (args (cdr cmdlist
))
2687 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2688 interpreter nil args
))
2689 (python-shell--parent-buffer (current-buffer))
2690 (process (get-buffer-process buffer
))
2691 ;; Users can override the interpreter and args
2692 ;; interactively when calling `run-python', let-binding
2693 ;; these allows to have the new right values in all
2694 ;; setup code that is done in `inferior-python-mode',
2695 ;; which is important, especially for prompt detection.
2696 (python-shell--interpreter interpreter
)
2697 (python-shell--interpreter-args
2698 (mapconcat #'identity args
" ")))
2699 (with-current-buffer buffer
2700 (inferior-python-mode))
2701 (when show
(display-buffer buffer
))
2702 (and internal
(set-process-query-on-exit-flag process nil
))))
2703 proc-buffer-name
))))
2706 (defun run-python (&optional cmd dedicated show
)
2707 "Run an inferior Python process.
2709 Argument CMD defaults to `python-shell-calculate-command' return
2710 value. When called interactively with `prefix-arg', it allows
2711 the user to edit such value and choose whether the interpreter
2712 should be DEDICATED for the current buffer. When numeric prefix
2713 arg is other than 0 or 4 do not SHOW.
2715 For a given buffer and same values of DEDICATED, if a process is
2716 already running for it, it will do nothing. This means that if
2717 the current buffer is using a global process, the user is still
2718 able to switch it to use a dedicated one.
2720 Runs the hook `inferior-python-mode-hook' after
2721 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2722 process buffer for a list of commands.)"
2724 (if current-prefix-arg
2726 (read-shell-command "Run Python: " (python-shell-calculate-command))
2727 (y-or-n-p "Make dedicated process? ")
2728 (= (prefix-numeric-value current-prefix-arg
) 4))
2729 (list (python-shell-calculate-command) nil t
)))
2731 (python-shell-make-comint
2732 (or cmd
(python-shell-calculate-command))
2733 (python-shell-get-process-name dedicated
) show
)))
2735 (defun run-python-internal ()
2736 "Run an inferior Internal Python process.
2737 Input and output via buffer named after
2738 `python-shell-internal-buffer-name' and what
2739 `python-shell-internal-get-process-name' returns.
2741 This new kind of shell is intended to be used for generic
2742 communication related to defined configurations; the main
2743 difference with global or dedicated shells is that these ones are
2744 attached to a configuration, not a buffer. This means that can
2745 be used for example to retrieve the sys.path and other stuff,
2746 without messing with user shells. Note that
2747 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2748 are set to nil for these shells, so setup codes are not sent at
2750 (let ((python-shell-font-lock-enable nil
)
2751 (inferior-python-mode-hook nil
))
2753 (python-shell-make-comint
2754 (python-shell-calculate-command)
2755 (python-shell-internal-get-process-name) nil t
))))
2757 (defun python-shell-get-buffer ()
2758 "Return inferior Python buffer for current buffer.
2759 If current buffer is in `inferior-python-mode', return it."
2760 (if (derived-mode-p 'inferior-python-mode
)
2762 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2763 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2764 (global-proc-name (python-shell-get-process-name nil
))
2765 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2766 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2767 (global-running (comint-check-proc global-proc-buffer-name
)))
2768 ;; Always prefer dedicated
2769 (or (and dedicated-running dedicated-proc-buffer-name
)
2770 (and global-running global-proc-buffer-name
)))))
2772 (defun python-shell-get-process ()
2773 "Return inferior Python process for current buffer."
2774 (get-buffer-process (python-shell-get-buffer)))
2776 (defun python-shell-get-process-or-error (&optional interactivep
)
2777 "Return inferior Python process for current buffer or signal error.
2778 When argument INTERACTIVEP is non-nil, use `user-error' instead
2779 of `error' with a user-friendly message."
2780 (or (python-shell-get-process)
2783 "Start a Python process first with ‘%s’ or ‘%s’."
2784 (substitute-command-keys "\\[run-python]")
2788 #'run-python overriding-local-map t
)))
2790 "No inferior Python process running."))))
2792 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2793 "Get or create an inferior Python process for current buffer and return it.
2794 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2795 are used to start the shell. If those arguments are not
2796 provided, `run-python' is called interactively and the user will
2797 be asked for their values."
2798 (let ((shell-process (python-shell-get-process)))
2799 (when (not shell-process
)
2801 ;; XXX: Refactor code such that calling `run-python'
2802 ;; interactively is not needed anymore.
2803 (call-interactively 'run-python
)
2804 (run-python cmd dedicated show
)))
2805 (or shell-process
(python-shell-get-process))))
2808 #'python-shell-get-or-create-process
2809 "Instead call `python-shell-get-process' and create one if returns nil."
2812 (defvar python-shell-internal-buffer nil
2813 "Current internal shell buffer for the current buffer.
2814 This is really not necessary at all for the code to work but it's
2815 there for compatibility with CEDET.")
2817 (defvar python-shell-internal-last-output nil
2818 "Last output captured by the internal shell.
2819 This is really not necessary at all for the code to work but it's
2820 there for compatibility with CEDET.")
2822 (defun python-shell-internal-get-or-create-process ()
2823 "Get or create an inferior Internal Python process."
2824 (let ((proc-name (python-shell-internal-get-process-name)))
2825 (if (process-live-p proc-name
)
2826 (get-process proc-name
)
2827 (run-python-internal))))
2829 (define-obsolete-function-alias
2830 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2832 (define-obsolete-variable-alias
2833 'python-buffer
'python-shell-internal-buffer
"24.3")
2835 (define-obsolete-variable-alias
2836 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2838 (defun python-shell--save-temp-file (string)
2839 (let* ((temporary-file-directory
2840 (if (file-remote-p default-directory
)
2841 (concat (file-remote-p default-directory
) "/tmp")
2842 temporary-file-directory
))
2843 (temp-file-name (make-temp-file "py"))
2844 (coding-system-for-write (python-info-encoding)))
2845 (with-temp-file temp-file-name
2847 (delete-trailing-whitespace))
2850 (defun python-shell-send-string (string &optional process msg
)
2851 "Send STRING to inferior Python PROCESS.
2852 When optional argument MSG is non-nil, forces display of a
2853 user-friendly message if there's no process running; defaults to
2854 t when called interactively."
2856 (list (read-string "Python command: ") nil t
))
2857 (let ((process (or process
(python-shell-get-process-or-error msg
))))
2858 (if (string-match ".\n+." string
) ;Multiline.
2859 (let* ((temp-file-name (python-shell--save-temp-file string
))
2860 (file-name (or (buffer-file-name) temp-file-name
)))
2861 (python-shell-send-file file-name process temp-file-name t
))
2862 (comint-send-string process string
)
2863 (when (or (not (string-match "\n\\'" string
))
2864 (string-match "\n[ \t].*\n?\\'" string
))
2865 (comint-send-string process
"\n")))))
2867 (defvar python-shell-output-filter-in-progress nil
)
2868 (defvar python-shell-output-filter-buffer nil
)
2870 (defun python-shell-output-filter (string)
2871 "Filter used in `python-shell-send-string-no-output' to grab output.
2872 STRING is the output received to this point from the process.
2873 This filter saves received output from the process in
2874 `python-shell-output-filter-buffer' and stops receiving it after
2875 detecting a prompt at the end of the buffer."
2877 string
(ansi-color-filter-apply string
)
2878 python-shell-output-filter-buffer
2879 (concat python-shell-output-filter-buffer string
))
2880 (when (python-shell-comint-end-of-output-p
2881 python-shell-output-filter-buffer
)
2882 ;; Output ends when `python-shell-output-filter-buffer' contains
2883 ;; the prompt attached at the end of it.
2884 (setq python-shell-output-filter-in-progress nil
2885 python-shell-output-filter-buffer
2886 (substring python-shell-output-filter-buffer
2887 0 (match-beginning 0)))
2889 python-shell--prompt-calculated-output-regexp
2890 python-shell-output-filter-buffer
)
2891 ;; Some shells, like IPython might append a prompt before the
2892 ;; output, clean that.
2893 (setq python-shell-output-filter-buffer
2894 (substring python-shell-output-filter-buffer
(match-end 0)))))
2897 (defun python-shell-send-string-no-output (string &optional process
)
2898 "Send STRING to PROCESS and inhibit output.
2900 (let ((process (or process
(python-shell-get-process-or-error)))
2901 (comint-preoutput-filter-functions
2902 '(python-shell-output-filter))
2903 (python-shell-output-filter-in-progress t
)
2907 (python-shell-send-string string process
)
2908 (while python-shell-output-filter-in-progress
2909 ;; `python-shell-output-filter' takes care of setting
2910 ;; `python-shell-output-filter-in-progress' to NIL after it
2911 ;; detects end of output.
2912 (accept-process-output process
))
2914 python-shell-output-filter-buffer
2915 (setq python-shell-output-filter-buffer nil
)))
2916 (with-current-buffer (process-buffer process
)
2917 (comint-interrupt-subjob)))))
2919 (defun python-shell-internal-send-string (string)
2920 "Send STRING to the Internal Python interpreter.
2921 Returns the output. See `python-shell-send-string-no-output'."
2922 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2923 ;; updated to support this new mode.
2924 (setq python-shell-internal-last-output
2925 (python-shell-send-string-no-output
2926 ;; Makes this function compatible with the old
2927 ;; python-send-receive. (At least for CEDET).
2928 (replace-regexp-in-string "_emacs_out +" "" string
)
2929 (python-shell-internal-get-or-create-process))))
2931 (define-obsolete-function-alias
2932 'python-send-receive
'python-shell-internal-send-string
"24.3")
2934 (define-obsolete-function-alias
2935 'python-send-string
'python-shell-internal-send-string
"24.3")
2937 (defun python-shell-buffer-substring (start end
&optional nomain
)
2938 "Send buffer substring from START to END formatted for shell.
2939 This is a wrapper over `buffer-substring' that takes care of
2940 different transformations for the code sent to be evaluated in
2942 1. When optional argument NOMAIN is non-nil everything under an
2943 \"if __name__ == '__main__'\" block will be removed.
2944 2. When a subregion of the buffer is sent, it takes care of
2945 appending extra empty lines so tracebacks are correct.
2946 3. When the region sent is a substring of the current buffer, a
2947 coding cookie is added.
2948 4. Wraps indented regions under an \"if True:\" block so the
2949 interpreter evaluates them correctly."
2950 (let* ((substring (buffer-substring-no-properties start end
))
2951 (starts-at-point-min-p (save-restriction
2953 (= (point-min) start
)))
2954 (encoding (python-info-encoding))
2955 (fillstr (when (not starts-at-point-min-p
)
2957 (format "# -*- coding: %s -*-\n" encoding
)
2959 ;; Subtract 2 because of the coding cookie.
2960 (- (line-number-at-pos start
) 2) ?
\n))))
2961 (toplevel-block-p (save-excursion
2963 (or (zerop (line-number-at-pos start
))
2965 (python-util-forward-comment 1)
2966 (zerop (current-indentation)))))))
2969 (if fillstr
(insert fillstr
))
2971 (goto-char (point-min))
2972 (when (not toplevel-block-p
)
2974 (delete-region (point) (line-end-position)))
2976 (let* ((if-name-main-start-end
2979 (when (python-nav-if-name-main)
2981 (progn (python-nav-forward-sexp-safe)
2982 ;; Include ending newline
2985 ;; Oh destructuring bind, how I miss you.
2986 (if-name-main-start (car if-name-main-start-end
))
2987 (if-name-main-end (cdr if-name-main-start-end
))
2988 (fillstr (make-string
2989 (- (line-number-at-pos if-name-main-end
)
2990 (line-number-at-pos if-name-main-start
)) ?
\n)))
2991 (when if-name-main-start-end
2992 (goto-char if-name-main-start
)
2993 (delete-region if-name-main-start if-name-main-end
)
2995 ;; Ensure there's only one coding cookie in the generated string.
2996 (goto-char (point-min))
2997 (when (looking-at-p (python-rx coding-cookie
))
2999 (when (looking-at-p (python-rx coding-cookie
))
3001 (line-beginning-position) (line-end-position))))
3002 (buffer-substring-no-properties (point-min) (point-max)))))
3004 (defun python-shell-send-region (start end
&optional send-main msg
)
3005 "Send the region delimited by START and END to inferior Python process.
3006 When optional argument SEND-MAIN is non-nil, allow execution of
3007 code inside blocks delimited by \"if __name__== '__main__':\".
3008 When called interactively SEND-MAIN defaults to nil, unless it's
3009 called with prefix argument. When optional argument MSG is
3010 non-nil, forces display of a user-friendly message if there's no
3011 process running; defaults to t when called interactively."
3013 (list (region-beginning) (region-end) current-prefix-arg t
))
3014 (let* ((string (python-shell-buffer-substring start end
(not send-main
)))
3015 (process (python-shell-get-process-or-error msg
))
3016 (original-string (buffer-substring-no-properties start end
))
3017 (_ (string-match "\\`\n*\\(.*\\)" original-string
)))
3018 (message "Sent: %s..." (match-string 1 original-string
))
3019 (python-shell-send-string string process
)))
3021 (defun python-shell-send-buffer (&optional send-main msg
)
3022 "Send the entire buffer to inferior Python process.
3023 When optional argument SEND-MAIN is non-nil, allow execution of
3024 code inside blocks delimited by \"if __name__== '__main__':\".
3025 When called interactively SEND-MAIN defaults to nil, unless it's
3026 called with prefix argument. When optional argument MSG is
3027 non-nil, forces display of a user-friendly message if there's no
3028 process running; defaults to t when called interactively."
3029 (interactive (list current-prefix-arg t
))
3032 (python-shell-send-region (point-min) (point-max) send-main msg
)))
3034 (defun python-shell-send-defun (&optional arg msg
)
3035 "Send the current defun to inferior Python process.
3036 When argument ARG is non-nil do not include decorators. When
3037 optional argument MSG is non-nil, forces display of a
3038 user-friendly message if there's no process running; defaults to
3039 t when called interactively."
3040 (interactive (list current-prefix-arg t
))
3042 (python-shell-send-region
3045 (while (and (or (python-nav-beginning-of-defun)
3046 (beginning-of-line 1))
3047 (> (current-indentation) 0)))
3049 (while (and (forward-line -
1)
3050 (looking-at (python-rx decorator
))))
3054 (or (python-nav-end-of-defun)
3060 (defun python-shell-send-file (file-name &optional process temp-file-name
3062 "Send FILE-NAME to inferior Python PROCESS.
3063 If TEMP-FILE-NAME is passed then that file is used for processing
3064 instead, while internally the shell will continue to use
3065 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
3066 TEMP-FILE-NAME is deleted after evaluation is performed. When
3067 optional argument MSG is non-nil, forces display of a
3068 user-friendly message if there's no process running; defaults to
3069 t when called interactively."
3072 (read-file-name "File to send: ") ; file-name
3074 nil
; temp-file-name
3077 (let* ((process (or process
(python-shell-get-process-or-error msg
)))
3078 (encoding (with-temp-buffer
3079 (insert-file-contents
3080 (or temp-file-name file-name
))
3081 (python-info-encoding)))
3082 (file-name (expand-file-name
3083 (or (file-remote-p file-name
'localname
)
3085 (temp-file-name (when temp-file-name
3087 (or (file-remote-p temp-file-name
'localname
)
3089 (python-shell-send-string
3092 "import codecs, os;"
3093 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
3094 "__code = __pyfile.read().encode('''%s''');"
3096 (when (and delete temp-file-name
)
3097 (format "os.remove('''%s''');" temp-file-name
))
3098 "exec(compile(__code, '''%s''', 'exec'));")
3099 (or temp-file-name file-name
) encoding encoding file-name
)
3102 (defun python-shell-switch-to-shell (&optional msg
)
3103 "Switch to inferior Python process buffer.
3104 When optional argument MSG is non-nil, forces display of a
3105 user-friendly message if there's no process running; defaults to
3106 t when called interactively."
3109 (process-buffer (python-shell-get-process-or-error msg
)) nil t
))
3111 (defun python-shell-send-setup-code ()
3112 "Send all setup code for shell.
3113 This function takes the list of setup code to send from the
3114 `python-shell-setup-codes' list."
3115 (let ((process (python-shell-get-process))
3119 (cond ((stringp elt
) elt
)
3120 ((symbolp elt
) (symbol-value elt
))
3122 python-shell-setup-codes
3124 "\n\nprint ('python.el: sent setup code')")))
3125 (python-shell-send-string code process
)
3126 (python-shell-accept-process-output process
)))
3128 (add-hook 'inferior-python-mode-hook
3129 #'python-shell-send-setup-code
)
3132 ;;; Shell completion
3134 (defcustom python-shell-completion-setup-code
3138 def __PYTHON_EL_get_completions(text):
3141 def __PYTHON_EL_get_completions(text):
3146 import builtins as __builtin__
3147 builtins = dir(__builtin__)
3149 is_ipython = ('__IPYTHON__' in builtins or
3150 '__IPYTHON__active' in builtins)
3151 splits = text.split()
3152 is_module = splits and splits[0] in ('from', 'import')
3154 if is_ipython and is_module:
3155 from IPython.core.completerlib import module_completion
3156 completions = module_completion(text.strip())
3157 elif is_ipython and '__IP' in builtins:
3158 completions = __IP.complete(text)
3159 elif is_ipython and 'get_ipython' in builtins:
3160 completions = get_ipython().Completer.all_completions(text)
3162 # Try to reuse current completer.
3163 completer = readline.get_completer()
3165 # importing rlcompleter sets the completer, use it as a
3166 # last resort to avoid breaking customizations.
3168 completer = readline.get_completer()
3171 completion = completer(text, i)
3175 completions.append(completion)
3179 "Code used to setup completion in inferior Python processes."
3183 (defcustom python-shell-completion-string-code
3184 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3185 "Python code used to get a string of completions separated by semicolons.
3186 The string passed to the function is the current python name or
3187 the full statement in the case of imports."
3191 (define-obsolete-variable-alias
3192 'python-shell-completion-module-string-code
3193 'python-shell-completion-string-code
3195 "Completion string code must also autocomplete modules.")
3197 (define-obsolete-variable-alias
3198 'python-shell-completion-pdb-string-code
3199 'python-shell-completion-string-code
3201 "Completion string code must work for (i)pdb.")
3203 (defcustom python-shell-completion-native-disabled-interpreters
3204 ;; PyPy's readline cannot handle some escape sequences yet.
3206 "List of disabled interpreters.
3207 When a match is found, native completion is disabled."
3208 :type
'(repeat string
))
3210 (defcustom python-shell-completion-native-enable t
3211 "Enable readline based native completion."
3214 (defcustom python-shell-completion-native-output-timeout
5.0
3215 "Time in seconds to wait for completion output before giving up."
3218 (defcustom python-shell-completion-native-try-output-timeout
1.0
3219 "Time in seconds to wait for *trying* native completion output."
3222 (defvar python-shell-completion-native-redirect-buffer
3223 " *Python completions redirect*"
3224 "Buffer to be used to redirect output of readline commands.")
3226 (defun python-shell-completion-native-interpreter-disabled-p ()
3227 "Return non-nil if interpreter has native completion disabled."
3228 (when python-shell-completion-native-disabled-interpreters
3230 (regexp-opt python-shell-completion-native-disabled-interpreters
)
3231 (file-name-nondirectory python-shell-interpreter
))))
3233 (defun python-shell-completion-native-try ()
3234 "Return non-nil if can trigger native completion."
3235 (let ((python-shell-completion-native-enable t
)
3236 (python-shell-completion-native-output-timeout
3237 python-shell-completion-native-try-output-timeout
))
3238 (python-shell-completion-native-get-completions
3239 (get-buffer-process (current-buffer))
3242 (defun python-shell-completion-native-setup ()
3243 "Try to setup native completion, return non-nil on success."
3244 (let ((process (python-shell-get-process)))
3245 (python-shell-send-string "
3246 def __PYTHON_EL_native_completion_setup():
3253 import builtins as __builtin__
3254 builtins = dir(__builtin__)
3255 is_ipython = ('__IPYTHON__' in builtins or
3256 '__IPYTHON__active' in builtins)
3257 class __PYTHON_EL_Completer:
3258 PYTHON_EL_WRAPPED = True
3259 def __init__(self, completer):
3260 self.completer = completer
3261 self.last_completion = None
3262 def __call__(self, text, state):
3264 # The first completion is always a dummy completion. This
3265 # ensures proper output for sole completions and a current
3266 # input safeguard when no completions are available.
3267 self.last_completion = None
3268 completion = '0__dummy_completion__'
3270 completion = self.completer(text, state - 1)
3273 # When no completions are available, two non-sharing
3274 # prefix strings are returned just to ensure output
3275 # while preventing changes to current input.
3276 completion = '1__dummy_completion__'
3277 elif self.last_completion != '~~~~__dummy_completion__':
3278 # This marks the end of output.
3279 completion = '~~~~__dummy_completion__'
3280 elif completion.endswith('('):
3281 # Remove parens on callables as it breaks completion on
3282 # arguments (e.g. str(Ari<tab>)).
3283 completion = completion[:-1]
3284 self.last_completion = completion
3286 completer = readline.get_completer()
3288 # Used as last resort to avoid breaking customizations.
3290 completer = readline.get_completer()
3291 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3292 # Wrap the existing completer function only once.
3293 new_completer = __PYTHON_EL_Completer(completer)
3295 readline.set_completer(new_completer)
3297 # Try both initializations to cope with all IPython versions.
3298 # This works fine for IPython 3.x but not for earlier:
3299 readline.set_completer(new_completer)
3300 # IPython<3 hacks readline such that `readline.set_completer`
3301 # won't work. This workaround injects the new completer
3302 # function into the existing instance directly:
3303 instance = getattr(completer, 'im_self', completer.__self__)
3304 instance.rlcomplete = new_completer
3305 if readline.__doc__ and 'libedit' in readline.__doc__:
3306 readline.parse_and_bind('bind ^I rl_complete')
3308 readline.parse_and_bind('tab: complete')
3309 # Require just one tab to send output.
3310 readline.parse_and_bind('set show-all-if-ambiguous on')
3311 print ('python.el: readline is available')
3313 print ('python.el: readline not available')
3314 __PYTHON_EL_native_completion_setup()"
3316 (python-shell-accept-process-output process
)
3317 (when (save-excursion
3319 (regexp-quote "python.el: readline is available") nil t
1))
3320 (python-shell-completion-native-try))))
3322 (defun python-shell-completion-native-turn-off (&optional msg
)
3323 "Turn off shell native completions.
3324 With argument MSG show deactivation message."
3326 (python-shell-with-shell-buffer
3327 (set (make-local-variable 'python-shell-completion-native-enable
) nil
)
3329 (message "Shell native completion is disabled, using fallback"))))
3331 (defun python-shell-completion-native-turn-on (&optional msg
)
3332 "Turn on shell native completions.
3333 With argument MSG show deactivation message."
3335 (python-shell-with-shell-buffer
3336 (set (make-local-variable 'python-shell-completion-native-enable
) t
)
3337 (python-shell-completion-native-turn-on-maybe msg
)))
3339 (defun python-shell-completion-native-turn-on-maybe (&optional msg
)
3340 "Turn on native completions if enabled and available.
3341 With argument MSG show activation/deactivation message."
3343 (python-shell-with-shell-buffer
3344 (when python-shell-completion-native-enable
3346 ((python-shell-completion-native-interpreter-disabled-p)
3347 (python-shell-completion-native-turn-off msg
))
3348 ((python-shell-completion-native-setup)
3350 (message "Shell native completion is enabled.")))
3352 '(python python-shell-completion-native-turn-on-maybe
)
3355 "Your `python-shell-interpreter' doesn't seem to "
3356 "support readline, yet `python-shell-completion-native' "
3357 (format "was t and %S is not part of the "
3358 (file-name-nondirectory python-shell-interpreter
))
3359 "`python-shell-completion-native-disabled-interpreters' "
3360 "list. Native completions have been disabled locally. "))
3361 (python-shell-completion-native-turn-off msg
))))))
3363 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3364 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3365 (python-shell-completion-native-turn-on-maybe t
))
3367 (add-hook 'inferior-python-mode-hook
3368 #'python-shell-completion-native-turn-on-maybe-with-msg
)
3370 (defun python-shell-completion-native-toggle (&optional msg
)
3371 "Toggle shell native completion.
3372 With argument MSG show activation/deactivation message."
3374 (python-shell-with-shell-buffer
3375 (if python-shell-completion-native-enable
3376 (python-shell-completion-native-turn-off msg
)
3377 (python-shell-completion-native-turn-on msg
))
3378 python-shell-completion-native-enable
))
3380 (defun python-shell-completion-native-get-completions (process import input
)
3381 "Get completions using native readline for PROCESS.
3382 When IMPORT is non-nil takes precedence over INPUT for
3384 (with-current-buffer (process-buffer process
)
3385 (when (and python-shell-completion-native-enable
3386 (python-util-comint-last-prompt)
3387 (>= (point) (cdr (python-util-comint-last-prompt))))
3388 (let* ((input (or import input
))
3389 (original-filter-fn (process-filter process
))
3390 (redirect-buffer (get-buffer-create
3391 python-shell-completion-native-redirect-buffer
))
3392 (separators (python-rx (or whitespace open-paren close-paren
)))
3394 (new-input (concat input trigger
))
3397 (+ (- (point-max) (comint-bol)) (length new-input
))))
3398 (delete-line-command (make-string input-length ?
\b))
3399 (input-to-send (concat new-input delete-line-command
)))
3400 ;; Ensure restoring the process filter, even if the user quits
3401 ;; or there's some other error.
3403 (with-current-buffer redirect-buffer
3404 ;; Cleanup the redirect buffer
3405 (delete-region (point-min) (point-max))
3406 ;; Mimic `comint-redirect-send-command', unfortunately it
3407 ;; can't be used here because it expects a newline in the
3408 ;; command and that's exactly what we are trying to avoid.
3409 (let ((comint-redirect-echo-input nil
)
3410 (comint-redirect-verbose nil
)
3411 (comint-redirect-perform-sanity-check nil
)
3412 (comint-redirect-insert-matching-regexp nil
)
3413 ;; Feed it some regex that will never match.
3414 (comint-redirect-finished-regexp "^\\'$")
3415 (comint-redirect-output-buffer redirect-buffer
)
3416 (current-time (float-time)))
3417 ;; Compatibility with Emacs 24.x. Comint changed and
3418 ;; now `comint-redirect-filter' gets 3 args. This
3419 ;; checks which version of `comint-redirect-filter' is
3420 ;; in use based on its args and uses `apply-partially'
3421 ;; to make it up for the 3 args case.
3423 (help-function-arglist 'comint-redirect-filter
)) 3)
3425 process
(apply-partially
3426 #'comint-redirect-filter original-filter-fn
))
3427 (set-process-filter process
#'comint-redirect-filter
))
3428 (process-send-string process input-to-send
)
3429 ;; Grab output until our dummy completion used as
3430 ;; output end marker is found. Output is accepted
3431 ;; *very* quickly to keep the shell super-responsive.
3432 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t
))
3433 (< (- (float-time) current-time
)
3434 python-shell-completion-native-output-timeout
))
3435 (accept-process-output process
0.01))
3436 (cl-remove-duplicates
3439 (string-match "__dummy_completion__" c
))
3441 (buffer-substring-no-properties
3442 (point-min) (point-max))
3445 (set-process-filter process original-filter-fn
))))))
3447 (defun python-shell-completion-get-completions (process import input
)
3448 "Do completion at point using PROCESS for IMPORT or INPUT.
3449 When IMPORT is non-nil takes precedence over INPUT for
3451 (with-current-buffer (process-buffer process
)
3453 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3454 (buffer-substring-no-properties
3455 (car prompt-boundaries
) (cdr prompt-boundaries
))))
3457 ;; Check whether a prompt matches a pdb string, an import
3458 ;; statement or just the standard prompt and use the
3459 ;; correct python-shell-completion-*-code string
3460 (cond ((and (string-match
3461 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
3462 ;; Since there are no guarantees the user will remain
3463 ;; in the same context where completion code was sent
3464 ;; (e.g. user steps into a function), safeguard
3465 ;; resending completion setup continuously.
3466 (concat python-shell-completion-setup-code
3467 "\nprint (" python-shell-completion-string-code
")"))
3469 python-shell--prompt-calculated-input-regexp prompt
)
3470 python-shell-completion-string-code
)
3472 (subject (or import input
)))
3473 (and completion-code
3474 (> (length input
) 0)
3476 (python-util-strip-string
3477 (python-shell-send-string-no-output
3478 (format completion-code subject
) process
))))
3479 (and (> (length completions
) 2)
3480 (split-string completions
3481 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
3483 (defun python-shell-completion-at-point (&optional process
)
3484 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3485 Optional argument PROCESS forces completions to be retrieved
3486 using that one instead of current buffer's process."
3487 (setq process
(or process
(get-buffer-process (current-buffer))))
3488 (let* ((line-start (if (derived-mode-p 'inferior-python-mode
)
3489 ;; Working on a shell buffer: use prompt end.
3490 (cdr (python-util-comint-last-prompt))
3491 (line-beginning-position)))
3493 (when (string-match-p
3494 (rx (* space
) word-start
(or "from" "import") word-end space
)
3495 (buffer-substring-no-properties line-start
(point)))
3496 (buffer-substring-no-properties line-start
(point))))
3499 (if (not (re-search-backward
3501 (or whitespace open-paren close-paren string-delimiter
))
3505 (forward-char (length (match-string-no-properties 0)))
3509 (if python-shell-completion-native-enable
3510 #'python-shell-completion-native-get-completions
3511 #'python-shell-completion-get-completions
)))
3513 (completion-table-dynamic
3516 process import-statement
)))))
3518 (define-obsolete-function-alias
3519 'python-shell-completion-complete-at-point
3520 'python-shell-completion-at-point
3523 (defun python-shell-completion-complete-or-indent ()
3524 "Complete or indent depending on the context.
3525 If content before pointer is all whitespace, indent.
3526 If not try to complete."
3528 (if (string-match "^[[:space:]]*$"
3529 (buffer-substring (comint-line-beginning-position)
3531 (indent-for-tab-command)
3532 (completion-at-point)))
3535 ;;; PDB Track integration
3537 (defcustom python-pdbtrack-activate t
3538 "Non-nil makes Python shell enable pdbtracking."
3543 (defcustom python-pdbtrack-stacktrace-info-regexp
3544 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3545 "Regular expression matching stacktrace information.
3546 Used to extract the current line and module being inspected."
3551 (defvar python-pdbtrack-tracked-buffer nil
3552 "Variable containing the value of the current tracked buffer.
3553 Never set this variable directly, use
3554 `python-pdbtrack-set-tracked-buffer' instead.")
3556 (defvar python-pdbtrack-buffers-to-kill nil
3557 "List of buffers to be deleted after tracking finishes.")
3559 (defun python-pdbtrack-set-tracked-buffer (file-name)
3560 "Set the buffer for FILE-NAME as the tracked buffer.
3561 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3562 Returns the tracked buffer."
3563 (let ((file-buffer (get-file-buffer
3564 (concat (file-remote-p default-directory
)
3567 (setq python-pdbtrack-tracked-buffer file-buffer
)
3568 (setq file-buffer
(find-file-noselect file-name
))
3569 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3570 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3573 (defun python-pdbtrack-comint-output-filter-function (output)
3574 "Move overlay arrow to current pdb line in tracked buffer.
3575 Argument OUTPUT is a string with the output from the comint process."
3576 (when (and python-pdbtrack-activate
(not (string= output
"")))
3577 (let* ((full-output (ansi-color-filter-apply
3578 (buffer-substring comint-last-input-end
(point-max))))
3582 (insert full-output
)
3583 ;; When the debugger encounters a pdb.set_trace()
3584 ;; command, it prints a single stack frame. Sometimes
3585 ;; it prints a bit of extra information about the
3586 ;; arguments of the present function. When ipdb
3587 ;; encounters an exception, it prints the _entire_ stack
3588 ;; trace. To handle all of these cases, we want to find
3589 ;; the _last_ stack frame printed in the most recent
3590 ;; batch of output, then jump to the corresponding
3591 ;; file/line number.
3592 (goto-char (point-max))
3593 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3594 (setq line-number
(string-to-number
3595 (match-string-no-properties 2)))
3596 (match-string-no-properties 1)))))
3597 (if (and file-name line-number
)
3598 (let* ((tracked-buffer
3599 (python-pdbtrack-set-tracked-buffer file-name
))
3600 (shell-buffer (current-buffer))
3601 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3602 (tracked-buffer-line-pos))
3603 (with-current-buffer tracked-buffer
3604 (set (make-local-variable 'overlay-arrow-string
) "=>")
3605 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3606 (setq tracked-buffer-line-pos
(progn
3607 (goto-char (point-min))
3608 (forward-line (1- line-number
))
3610 (when tracked-buffer-window
3612 tracked-buffer-window tracked-buffer-line-pos
))
3613 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3614 (pop-to-buffer tracked-buffer
)
3615 (switch-to-buffer-other-window shell-buffer
))
3616 (when python-pdbtrack-tracked-buffer
3617 (with-current-buffer python-pdbtrack-tracked-buffer
3618 (set-marker overlay-arrow-position nil
))
3619 (mapc #'(lambda (buffer)
3620 (ignore-errors (kill-buffer buffer
)))
3621 python-pdbtrack-buffers-to-kill
)
3622 (setq python-pdbtrack-tracked-buffer nil
3623 python-pdbtrack-buffers-to-kill nil
)))))
3627 ;;; Symbol completion
3629 (defun python-completion-at-point ()
3630 "Function for `completion-at-point-functions' in `python-mode'.
3631 For this to work as best as possible you should call
3632 `python-shell-send-buffer' from time to time so context in
3633 inferior Python process is updated properly."
3634 (let ((process (python-shell-get-process)))
3636 (python-shell-completion-at-point process
))))
3638 (define-obsolete-function-alias
3639 'python-completion-complete-at-point
3640 'python-completion-at-point
3646 (defcustom python-fill-comment-function
'python-fill-comment
3647 "Function to fill comments.
3648 This is the function used by `python-fill-paragraph' to
3653 (defcustom python-fill-string-function
'python-fill-string
3654 "Function to fill strings.
3655 This is the function used by `python-fill-paragraph' to
3660 (defcustom python-fill-decorator-function
'python-fill-decorator
3661 "Function to fill decorators.
3662 This is the function used by `python-fill-paragraph' to
3667 (defcustom python-fill-paren-function
'python-fill-paren
3668 "Function to fill parens.
3669 This is the function used by `python-fill-paragraph' to
3674 (defcustom python-fill-docstring-style
'pep-257
3675 "Style used to fill docstrings.
3676 This affects `python-fill-string' behavior with regards to
3677 triple quotes positioning.
3679 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3680 `symmetric', and nil. A value of nil won't care about quotes
3681 position and will treat docstrings a normal string, any other
3682 value may result in one of the following docstring styles:
3687 Process foo, return bar.
3691 Process foo, return bar.
3693 If processing fails throw ProcessingError.
3698 \"\"\"Process foo, return bar.\"\"\"
3701 Process foo, return bar.
3703 If processing fails throw ProcessingError.
3709 \"\"\"Process foo, return bar.\"\"\"
3711 \"\"\"Process foo, return bar.
3713 If processing fails throw ProcessingError.
3719 \"\"\"Process foo, return bar.\"\"\"
3721 \"\"\"Process foo, return bar.
3723 If processing fails throw ProcessingError.
3728 \"\"\"Process foo, return bar.\"\"\"
3731 Process foo, return bar.
3733 If processing fails throw ProcessingError.
3736 (const :tag
"Don't format docstrings" nil
)
3737 (const :tag
"Django's coding standards style." django
)
3738 (const :tag
"One newline and start and Two at end style." onetwo
)
3739 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3740 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3741 (const :tag
"Symmetric style." symmetric
))
3744 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3746 (defun python-fill-paragraph (&optional justify
)
3747 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3748 If any of the current line is in or at the end of a multi-line string,
3749 fill the string or the paragraph of it that point is in, preserving
3750 the string's indentation.
3751 Optional argument JUSTIFY defines if the paragraph should be justified."
3756 ((python-syntax-context 'comment
)
3757 (funcall python-fill-comment-function justify
))
3758 ;; Strings/Docstrings
3759 ((save-excursion (or (python-syntax-context 'string
)
3760 (equal (string-to-syntax "|")
3761 (syntax-after (point)))))
3762 (funcall python-fill-string-function justify
))
3764 ((equal (char-after (save-excursion
3765 (python-nav-beginning-of-statement))) ?
@)
3766 (funcall python-fill-decorator-function justify
))
3768 ((or (python-syntax-context 'paren
)
3769 (looking-at (python-rx open-paren
))
3771 (skip-syntax-forward "^(" (line-end-position))
3772 (looking-at (python-rx open-paren
))))
3773 (funcall python-fill-paren-function justify
))
3776 (defun python-fill-comment (&optional justify
)
3777 "Comment fill function for `python-fill-paragraph'.
3778 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3779 (fill-comment-paragraph justify
))
3781 (defun python-fill-string (&optional justify
)
3782 "String fill function for `python-fill-paragraph'.
3783 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3784 (let* ((str-start-pos
3787 (or (python-syntax-context 'string
)
3788 (and (equal (string-to-syntax "|")
3789 (syntax-after (point)))
3791 (num-quotes (python-syntax-count-quotes
3792 (char-after str-start-pos
) str-start-pos
))
3795 (goto-char (+ str-start-pos num-quotes
))
3796 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3797 (goto-char (point-max)))
3800 ;; Docstring styles may vary for oneliners and multi-liners.
3801 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3803 (pcase python-fill-docstring-style
3804 ;; delimiters-style is a cons cell with the form
3805 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3806 ;; is NIL means to not add any newlines for start or end
3807 ;; of docstring. See `python-fill-docstring-style' for a
3808 ;; graphic idea of each style.
3809 (`django
(cons 1 1))
3810 (`onetwo
(and multi-line-p
(cons 1 2)))
3811 (`pep-257
(and multi-line-p
(cons nil
2)))
3812 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3813 (`symmetric
(and multi-line-p
(cons 1 1)))))
3814 (fill-paragraph-function))
3816 (narrow-to-region str-start-pos str-end-pos
)
3817 (fill-paragraph justify
))
3819 (when (and (python-info-docstring-p) python-fill-docstring-style
)
3820 ;; Add the number of newlines indicated by the selected style
3821 ;; at the start of the docstring.
3822 (goto-char (+ str-start-pos num-quotes
))
3823 (delete-region (point) (progn
3824 (skip-syntax-forward "> ")
3826 (and (car delimiters-style
)
3827 (or (newline (car delimiters-style
)) t
)
3828 ;; Indent only if a newline is added.
3829 (indent-according-to-mode))
3830 ;; Add the number of newlines indicated by the selected style
3831 ;; at the end of the docstring.
3832 (goto-char (if (not (= str-end-pos
(point-max)))
3833 (- str-end-pos num-quotes
)
3835 (delete-region (point) (progn
3836 (skip-syntax-backward "> ")
3838 (and (cdr delimiters-style
)
3839 ;; Add newlines only if string ends.
3840 (not (= str-end-pos
(point-max)))
3841 (or (newline (cdr delimiters-style
)) t
)
3842 ;; Again indent only if a newline is added.
3843 (indent-according-to-mode))))) t
)
3845 (defun python-fill-decorator (&optional _justify
)
3846 "Decorator fill function for `python-fill-paragraph'.
3847 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3850 (defun python-fill-paren (&optional justify
)
3851 "Paren fill function for `python-fill-paragraph'.
3852 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3854 (narrow-to-region (progn
3855 (while (python-syntax-context 'paren
)
3856 (goto-char (1- (point))))
3857 (line-beginning-position))
3859 (when (not (python-syntax-context 'paren
))
3861 (when (not (python-syntax-context 'paren
))
3862 (skip-syntax-backward "^)")))
3863 (while (and (python-syntax-context 'paren
)
3865 (goto-char (1+ (point))))
3867 (let ((paragraph-start "\f\\|[ \t]*$")
3868 (paragraph-separate ",")
3869 (fill-paragraph-function))
3870 (goto-char (point-min))
3871 (fill-paragraph justify
))
3874 (python-indent-line)
3875 (goto-char (line-end-position))))
3881 (defcustom python-skeleton-autoinsert nil
3882 "Non-nil means template skeletons will be automagically inserted.
3883 This happens when pressing \"if<SPACE>\", for example, to prompt for
3889 (define-obsolete-variable-alias
3890 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3892 (defvar python-skeleton-available
'()
3893 "Internal list of available skeletons.")
3895 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3896 "Abbrev table for Python mode skeletons."
3898 ;; Allow / inside abbrevs.
3899 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3900 ;; Only expand in code.
3901 :enable-function
(lambda ()
3903 (not (python-syntax-comment-or-string-p))
3904 python-skeleton-autoinsert
)))
3906 (defmacro python-skeleton-define
(name doc
&rest skel
)
3907 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3908 The skeleton will be bound to python-skeleton-NAME and will
3909 be added to `python-mode-skeleton-abbrev-table'."
3910 (declare (indent 2))
3911 (let* ((name (symbol-name name
))
3912 (function-name (intern (concat "python-skeleton-" name
))))
3914 (define-abbrev python-mode-skeleton-abbrev-table
3915 ,name
"" ',function-name
:system t
)
3916 (setq python-skeleton-available
3917 (cons ',function-name python-skeleton-available
))
3918 (define-skeleton ,function-name
3920 (format "Insert %s statement." name
))
3923 (define-abbrev-table 'python-mode-abbrev-table
()
3924 "Abbrev table for Python mode."
3925 :parents
(list python-mode-skeleton-abbrev-table
))
3927 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3928 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3929 The skeleton will be bound to python-skeleton-NAME."
3930 (declare (indent 2))
3931 (let* ((name (symbol-name name
))
3932 (function-name (intern (concat "python-skeleton--" name
)))
3934 "Add '%s' clause? " name
)))
3937 `(< ,(format "%s:" name
) \n \n
3939 `(define-skeleton ,function-name
3941 (format "Auxiliary skeleton for %s statement." name
))
3943 (unless (y-or-n-p ,msg
)
3947 (python-define-auxiliary-skeleton else nil
)
3949 (python-define-auxiliary-skeleton except nil
)
3951 (python-define-auxiliary-skeleton finally nil
)
3953 (python-skeleton-define if nil
3957 ("other condition, %s: "
3961 '(python-skeleton--else) | ^
)
3963 (python-skeleton-define while nil
3967 '(python-skeleton--else) | ^
)
3969 (python-skeleton-define for nil
3973 '(python-skeleton--else) | ^
)
3975 (python-skeleton-define import nil
3976 "Import from module: "
3977 "from " str
& " " | -
5
3979 ("Identifier: " str
", ") -
2 \n _
)
3981 (python-skeleton-define try nil
3987 "except " str
":" \n
3990 '(python-skeleton--except)
3991 '(python-skeleton--else)
3992 '(python-skeleton--finally) | ^
)
3994 (python-skeleton-define def nil
3996 "def " str
"(" ("Parameter, %s: "
3997 (unless (equal ?\
( (char-before)) ", ")
3999 "\"\"\"" -
"\"\"\"" \n
4002 (python-skeleton-define class nil
4004 "class " str
"(" ("Inheritance, %s: "
4005 (unless (equal ?\
( (char-before)) ", ")
4009 "\"\"\"" -
"\"\"\"" \n
4012 (defun python-skeleton-add-menu-items ()
4013 "Add menu items to Python->Skeletons menu."
4014 (let ((skeletons (sort python-skeleton-available
'string
<)))
4015 (dolist (skeleton skeletons
)
4017 nil
'("Python" "Skeletons")
4019 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
4024 (defcustom python-ffap-setup-code
4025 "def __FFAP_get_module_path(module):
4028 path = __import__(module).__file__
4029 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
4034 "Python code to get a module path."
4038 (defcustom python-ffap-string-code
4039 "__FFAP_get_module_path('''%s''')\n"
4040 "Python code used to get a string with the path of a module."
4044 (defun python-ffap-module-path (module)
4045 "Function for `ffap-alist' to return path for MODULE."
4047 (and (derived-mode-p 'inferior-python-mode
)
4048 (get-buffer-process (current-buffer)))
4049 (python-shell-get-process))))
4053 (python-shell-send-string-no-output
4054 (format python-ffap-string-code module
) process
)))
4056 (substring-no-properties module-file
1 -
1))))))
4060 (eval-after-load "ffap"
4062 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
4063 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
4068 (defcustom python-check-command
4069 (or (executable-find "pyflakes")
4070 (executable-find "epylint")
4071 "install pyflakes, pylint or something else")
4072 "Command used to check a Python file."
4076 (defcustom python-check-buffer-name
4077 "*Python check: %s*"
4078 "Buffer name used for check commands."
4082 (defvar python-check-custom-command nil
4084 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
4085 (make-variable-buffer-local 'python-check-custom-command
)
4087 (defun python-check (command)
4088 "Check a Python file (default current buffer's file).
4089 Runs COMMAND, a shell command, as if by `compile'.
4090 See `python-check-command' for the default."
4092 (list (read-string "Check command: "
4093 (or python-check-custom-command
4094 (concat python-check-command
" "
4095 (shell-quote-argument
4097 (let ((name (buffer-file-name)))
4099 (file-name-nondirectory name
)))
4101 (setq python-check-custom-command command
)
4102 (save-some-buffers (not compilation-ask-about-save
) nil
)
4103 (python-shell-with-environment
4104 (compilation-start command nil
4106 (format python-check-buffer-name command
)))))
4111 (defcustom python-eldoc-setup-code
4112 "def __PYDOC_get_help(obj):
4116 str_type = basestring
4119 if isinstance(obj, str_type):
4120 obj = eval(obj, globals())
4121 doc = inspect.getdoc(obj)
4122 if not doc and callable(obj):
4124 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4125 target = obj.__init__
4131 args = inspect.formatargspec(
4132 *inspect.getargspec(target)
4135 doc = '{objtype} {name}{args}'.format(
4136 objtype=objtype, name=name, args=args
4139 doc = doc.splitlines()[0]
4143 "Python code to setup documentation retrieval."
4147 (defcustom python-eldoc-string-code
4148 "__PYDOC_get_help('''%s''')\n"
4149 "Python code used to get a string with the documentation of an object."
4153 (defun python-eldoc--get-symbol-at-point ()
4154 "Get the current symbol for eldoc.
4155 Returns the current symbol handling point within arguments."
4157 (let ((start (python-syntax-context 'paren
)))
4162 (memq (char-syntax (char-after)) '(?\ ?-
)))
4163 ;; Try to adjust to closest symbol if not in one.
4164 (python-util-forward-comment -
1)))
4165 (python-info-current-symbol t
)))
4167 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
4168 "Internal implementation to get documentation at point.
4169 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4170 returns will be used. If not FORCE-PROCESS is passed what
4171 `python-shell-get-process' returns is used."
4172 (let ((process (or force-process
(python-shell-get-process))))
4174 (let ((input (or force-input
4175 (python-eldoc--get-symbol-at-point))))
4177 ;; Prevent resizing the echo area when iPython is
4178 ;; enabled. Bug#18794.
4179 (python-util-strip-string
4180 (python-shell-send-string-no-output
4181 (format python-eldoc-string-code input
)
4184 (defun python-eldoc-function ()
4185 "`eldoc-documentation-function' for Python.
4186 For this to work as best as possible you should call
4187 `python-shell-send-buffer' from time to time so context in
4188 inferior Python process is updated properly."
4189 (python-eldoc--get-doc-at-point))
4191 (defun python-eldoc-at-point (symbol)
4192 "Get help on SYMBOL using `help'.
4193 Interactively, prompt for symbol."
4195 (let ((symbol (python-eldoc--get-symbol-at-point))
4196 (enable-recursive-minibuffers t
))
4197 (list (read-string (if symbol
4198 (format "Describe symbol (default %s): " symbol
)
4199 "Describe symbol: ")
4201 (message (python-eldoc--get-doc-at-point symbol
)))
4206 (defun python-hideshow-forward-sexp-function (arg)
4207 "Python specific `forward-sexp' function for `hs-minor-mode'.
4208 Argument ARG is ignored."
4209 arg
; Shut up, byte compiler.
4210 (python-nav-end-of-defun)
4211 (unless (python-info-current-line-empty-p)
4217 (defvar python-imenu-format-item-label-function
4218 'python-imenu-format-item-label
4219 "Imenu function used to format an item label.
4220 It must be a function with two arguments: TYPE and NAME.")
4222 (defvar python-imenu-format-parent-item-label-function
4223 'python-imenu-format-parent-item-label
4224 "Imenu function used to format a parent item label.
4225 It must be a function with two arguments: TYPE and NAME.")
4227 (defvar python-imenu-format-parent-item-jump-label-function
4228 'python-imenu-format-parent-item-jump-label
4229 "Imenu function used to format a parent jump item label.
4230 It must be a function with two arguments: TYPE and NAME.")
4232 (defun python-imenu-format-item-label (type name
)
4233 "Return Imenu label for single node using TYPE and NAME."
4234 (format "%s (%s)" name type
))
4236 (defun python-imenu-format-parent-item-label (type name
)
4237 "Return Imenu label for parent node using TYPE and NAME."
4238 (format "%s..." (python-imenu-format-item-label type name
)))
4240 (defun python-imenu-format-parent-item-jump-label (type _name
)
4241 "Return Imenu label for parent node jump using TYPE and NAME."
4242 (if (string= type
"class")
4243 "*class definition*"
4244 "*function definition*"))
4246 (defun python-imenu--put-parent (type name pos tree
)
4247 "Add the parent with TYPE, NAME and POS to TREE."
4249 (funcall python-imenu-format-item-label-function type name
))
4251 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
4254 (cons label
(cons (cons jump-label pos
) tree
)))))
4256 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
4257 "Recursively build the tree of nested definitions of a node.
4258 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4259 not be passed explicitly unless you know what you are doing."
4260 (setq min-indent
(or min-indent
0)
4261 prev-indent
(or prev-indent python-indent-offset
))
4262 (let* ((pos (python-nav-backward-defun))
4264 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
4265 (let ((split (split-string (match-string-no-properties 0))))
4266 (setq type
(car split
))
4269 (funcall python-imenu-format-item-label-function type name
)))
4270 (indent (current-indentation))
4271 (children-indent-limit (+ python-indent-offset min-indent
)))
4273 ;; Nothing found, probably near to bobp.
4275 ((<= indent min-indent
)
4276 ;; The current indentation points that this is a parent
4277 ;; node, add it to the tree and stop recursing.
4278 (python-imenu--put-parent type name pos tree
))
4280 (python-imenu--build-tree
4283 (if (<= indent children-indent-limit
)
4284 ;; This lies within the children indent offset range,
4285 ;; so it's a normal child of its parent (i.e., not
4286 ;; a child of a child).
4287 (cons (cons label pos
) tree
)
4288 ;; Oh no, a child of a child?! Fear not, we
4289 ;; know how to roll. We recursively parse these by
4290 ;; swapping prev-indent and min-indent plus adding this
4291 ;; newly found item to a fresh subtree. This works, I
4294 (python-imenu--build-tree
4295 prev-indent indent
(list (cons label pos
)))
4298 (defun python-imenu-create-index ()
4299 "Return tree Imenu alist for the current Python buffer.
4300 Change `python-imenu-format-item-label-function',
4301 `python-imenu-format-parent-item-label-function',
4302 `python-imenu-format-parent-item-jump-label-function' to
4303 customize how labels are formatted."
4304 (goto-char (point-max))
4307 (while (setq tree
(python-imenu--build-tree))
4308 (setq index
(cons tree index
)))
4311 (defun python-imenu-create-flat-index (&optional alist prefix
)
4312 "Return flat outline of the current Python buffer for Imenu.
4313 Optional argument ALIST is the tree to be flattened; when nil
4314 `python-imenu-build-index' is used with
4315 `python-imenu-format-parent-item-jump-label-function'
4316 `python-imenu-format-parent-item-label-function'
4317 `python-imenu-format-item-label-function' set to
4318 (lambda (type name) name)
4319 Optional argument PREFIX is used in recursive calls and should
4320 not be passed explicitly.
4327 (\"decorator\" . 173)
4330 (\"wrapped_f\" . 393))))
4336 (\"decorator\" . 173)
4337 (\"decorator.wrap\" . 353)
4338 (\"decorator.wrapped_f\" . 393))"
4339 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4344 (let ((name (if prefix
4345 (concat prefix
"." (car item
))
4348 (cond ((or (numberp pos
) (markerp pos
))
4349 (list (cons name pos
)))
4352 (cons name
(cdar pos
))
4353 (python-imenu-create-flat-index (cddr item
) name
))))))
4355 (let* ((fn (lambda (_type name
) name
))
4356 (python-imenu-format-item-label-function fn
)
4357 (python-imenu-format-parent-item-label-function fn
)
4358 (python-imenu-format-parent-item-jump-label-function fn
))
4359 (python-imenu-create-index))))))
4364 (defun python-info-current-defun (&optional include-type
)
4365 "Return name of surrounding function with Python compatible dotty syntax.
4366 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4367 This function can be used as the value of `add-log-current-defun-function'
4368 since it returns nil if point is not inside a defun."
4374 (starting-indentation (current-indentation))
4375 (starting-pos (point))
4380 (while (python-nav-beginning-of-defun 1)
4381 (when (save-match-data
4383 (or (not last-indent
)
4384 (< (current-indentation) last-indent
))
4388 ;; If this is the first run, we may add
4389 ;; the current defun at point.
4390 (setq first-run nil
)
4391 (goto-char starting-pos
)
4392 (python-nav-beginning-of-statement)
4393 (beginning-of-line 1)
4395 python-nav-beginning-of-defun-regexp
)))
4399 (+ (current-indentation)
4400 python-indent-offset
)))
4401 (if (< starting-indentation min-indent
)
4402 ;; If the starting indentation is not
4403 ;; within the min defun indent make the
4406 ;; Else go to the end of defun and add
4407 ;; up the current indentation to the
4409 (python-nav-end-of-defun)
4411 (if (>= (current-indentation) min-indent
)
4412 (1+ (current-indentation))
4414 (save-match-data (setq last-indent
(current-indentation)))
4415 (if (or (not include-type
) type
)
4416 (setq names
(cons (match-string-no-properties 1) names
))
4417 (let ((match (split-string (match-string-no-properties 0))))
4418 (setq type
(car match
))
4419 (setq names
(cons (cadr match
) names
)))))
4420 ;; Stop searching ASAP.
4421 (and (= (current-indentation) 0) (throw 'exit t
))))
4423 (concat (and type
(format "%s " type
))
4424 (mapconcat 'identity names
".")))))))
4426 (defun python-info-current-symbol (&optional replace-self
)
4427 "Return current symbol using dotty syntax.
4428 With optional argument REPLACE-SELF convert \"self\" to current
4431 (and (not (python-syntax-comment-or-string-p))
4432 (with-syntax-table python-dotty-syntax-table
4433 (let ((sym (symbol-at-point)))
4435 (substring-no-properties (symbol-name sym
))))))))
4437 (if (not replace-self
)
4439 (let ((current-defun (python-info-current-defun)))
4440 (if (not current-defun
)
4442 (replace-regexp-in-string
4443 (python-rx line-start word-start
"self" word-end ?.
)
4445 (mapconcat 'identity
4446 (butlast (split-string current-defun
"\\."))
4450 (defun python-info-statement-starts-block-p ()
4451 "Return non-nil if current statement opens a block."
4453 (python-nav-beginning-of-statement)
4454 (looking-at (python-rx block-start
))))
4456 (defun python-info-statement-ends-block-p ()
4457 "Return non-nil if point is at end of block."
4458 (let ((end-of-block-pos (save-excursion
4459 (python-nav-end-of-block)))
4460 (end-of-statement-pos (save-excursion
4461 (python-nav-end-of-statement))))
4462 (and end-of-block-pos end-of-statement-pos
4463 (= end-of-block-pos end-of-statement-pos
))))
4465 (defun python-info-beginning-of-statement-p ()
4466 "Return non-nil if point is at beginning of statement."
4467 (= (point) (save-excursion
4468 (python-nav-beginning-of-statement)
4471 (defun python-info-end-of-statement-p ()
4472 "Return non-nil if point is at end of statement."
4473 (= (point) (save-excursion
4474 (python-nav-end-of-statement)
4477 (defun python-info-beginning-of-block-p ()
4478 "Return non-nil if point is at beginning of block."
4479 (and (python-info-beginning-of-statement-p)
4480 (python-info-statement-starts-block-p)))
4482 (defun python-info-end-of-block-p ()
4483 "Return non-nil if point is at end of block."
4484 (and (python-info-end-of-statement-p)
4485 (python-info-statement-ends-block-p)))
4487 (define-obsolete-function-alias
4488 'python-info-closing-block
4489 'python-info-dedenter-opening-block-position
"24.4")
4491 (defun python-info-dedenter-opening-block-position ()
4492 "Return the point of the closest block the current line closes.
4493 Returns nil if point is not on a dedenter statement or no opening
4494 block can be detected. The latter case meaning current file is
4495 likely an invalid python file."
4496 (let ((positions (python-info-dedenter-opening-block-positions))
4497 (indentation (current-indentation))
4499 (while (and (not position
)
4502 (goto-char (car positions
))
4503 (if (<= (current-indentation) indentation
)
4504 (setq position
(car positions
))
4505 (setq positions
(cdr positions
)))))
4508 (defun python-info-dedenter-opening-block-positions ()
4509 "Return points of blocks the current line may close sorted by closer.
4510 Returns nil if point is not on a dedenter statement or no opening
4511 block can be detected. The latter case meaning current file is
4512 likely an invalid python file."
4514 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4516 (goto-char dedenter-pos
)
4517 (let* ((pairs '(("elif" "elif" "if")
4518 ("else" "if" "elif" "except" "for" "while")
4519 ("except" "except" "try")
4520 ("finally" "else" "except" "try")))
4521 (dedenter (match-string-no-properties 0))
4522 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
4523 (collected-indentations)
4526 (while (python-nav--syntactically
4528 (re-search-backward (python-rx block-start
) nil t
))
4530 (let ((indentation (current-indentation)))
4531 (when (and (not (memq indentation collected-indentations
))
4532 (or (not collected-indentations
)
4533 (< indentation
(apply #'min collected-indentations
))))
4534 (setq collected-indentations
4535 (cons indentation collected-indentations
))
4536 (when (member (match-string-no-properties 0)
4537 possible-opening-blocks
)
4538 (setq opening-blocks
(cons (point) opening-blocks
))))
4539 (when (zerop indentation
)
4540 (throw 'exit nil
)))))
4542 (nreverse opening-blocks
))))))
4544 (define-obsolete-function-alias
4545 'python-info-closing-block-message
4546 'python-info-dedenter-opening-block-message
"24.4")
4548 (defun python-info-dedenter-opening-block-message ()
4549 "Message the first line of the block the current statement closes."
4550 (let ((point (python-info-dedenter-opening-block-position)))
4554 (message "Closes %s" (save-excursion
4557 (point) (line-end-position))))))))
4559 (defun python-info-dedenter-statement-p ()
4560 "Return point if current statement is a dedenter.
4561 Sets `match-data' to the keyword that starts the dedenter
4564 (python-nav-beginning-of-statement)
4565 (when (and (not (python-syntax-context-type))
4566 (looking-at (python-rx dedenter
)))
4569 (defun python-info-line-ends-backslash-p (&optional line-number
)
4570 "Return non-nil if current line ends with backslash.
4571 With optional argument LINE-NUMBER, check that line instead."
4576 (python-util-goto-line line-number
))
4577 (while (and (not (eobp))
4578 (goto-char (line-end-position))
4579 (python-syntax-context 'paren
)
4580 (not (equal (char-before (point)) ?
\\)))
4582 (when (equal (char-before) ?
\\)
4585 (defun python-info-beginning-of-backslash (&optional line-number
)
4586 "Return the point where the backslashed line start.
4587 Optional argument LINE-NUMBER forces the line number to check against."
4592 (python-util-goto-line line-number
))
4593 (when (python-info-line-ends-backslash-p)
4594 (while (save-excursion
4595 (goto-char (line-beginning-position))
4596 (python-syntax-context 'paren
))
4598 (back-to-indentation)
4601 (defun python-info-continuation-line-p ()
4602 "Check if current line is continuation of another.
4603 When current line is continuation of another return the point
4604 where the continued line ends."
4608 (let* ((context-type (progn
4609 (back-to-indentation)
4610 (python-syntax-context-type)))
4611 (line-start (line-number-at-pos))
4612 (context-start (when context-type
4613 (python-syntax-context context-type
))))
4614 (cond ((equal context-type
'paren
)
4615 ;; Lines inside a paren are always a continuation line
4616 ;; (except the first one).
4617 (python-util-forward-comment -
1)
4619 ((member context-type
'(string comment
))
4620 ;; move forward an roll again
4621 (goto-char context-start
)
4622 (python-util-forward-comment)
4623 (python-info-continuation-line-p))
4625 ;; Not within a paren, string or comment, the only way
4626 ;; we are dealing with a continuation line is that
4627 ;; previous line contains a backslash, and this can
4628 ;; only be the previous line from current
4629 (back-to-indentation)
4630 (python-util-forward-comment -
1)
4631 (when (and (equal (1- line-start
) (line-number-at-pos))
4632 (python-info-line-ends-backslash-p))
4633 (point-marker))))))))
4635 (defun python-info-block-continuation-line-p ()
4636 "Return non-nil if current line is a continuation of a block."
4638 (when (python-info-continuation-line-p)
4640 (back-to-indentation)
4641 (when (looking-at (python-rx block-start
))
4644 (defun python-info-assignment-statement-p (&optional current-line-only
)
4645 "Check if current line is an assignment.
4646 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4647 continuations, just check the if current line is an assignment."
4650 (if current-line-only
4651 (back-to-indentation)
4652 (python-nav-beginning-of-statement))
4654 (re-search-forward (python-rx not-simple-operator
4656 (group not-simple-operator
))
4657 (line-end-position) t
)
4660 ;; The assignment operator should not be inside a string.
4661 (backward-char (length (match-string-no-properties 1)))
4662 (setq found
(not (python-syntax-context-type)))))
4664 (skip-syntax-forward " ")
4667 ;; TODO: rename to clarify this is only for the first continuation
4668 ;; line or remove it and move its body to `python-indent-context'.
4669 (defun python-info-assignment-continuation-line-p ()
4670 "Check if current line is the first continuation of an assignment.
4671 When current line is continuation of another with an assignment
4672 return the point of the first non-blank character after the
4675 (when (python-info-continuation-line-p)
4677 (python-info-assignment-statement-p t
))))
4679 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4680 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4681 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4683 (beginning-of-line 1)
4684 (looking-at python-nav-beginning-of-defun-regexp
))))
4686 (defun python-info-current-line-comment-p ()
4687 "Return non-nil if current line is a comment line."
4689 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4692 (defun python-info-current-line-empty-p ()
4693 "Return non-nil if current line is empty, ignoring whitespace."
4695 (beginning-of-line 1)
4697 (python-rx line-start
(* whitespace
)
4698 (group (* not-newline
))
4699 (* whitespace
) line-end
))
4700 (string-equal "" (match-string-no-properties 1))))
4702 (defun python-info-docstring-p (&optional syntax-ppss
)
4703 "Return non-nil if point is in a docstring.
4704 When optional argument SYNTAX-PPSS is given, use that instead of
4705 point's current `syntax-ppss'."
4706 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4708 (when (and syntax-ppss
(python-syntax-context 'string syntax-ppss
))
4709 (goto-char (nth 8 syntax-ppss
)))
4710 (python-nav-beginning-of-statement)
4712 (indentation (current-indentation))
4713 (backward-sexp-point)
4714 (re (concat "[uU]?[rR]?"
4715 (python-rx string-delimiter
))))
4717 (not (python-info-assignment-statement-p))
4719 ;; Allow up to two consecutive docstrings only.
4723 (while (save-excursion
4724 (python-nav-backward-sexp)
4725 (setq backward-sexp-point
(point))
4726 (and (= indentation
(current-indentation))
4727 (not (bobp)) ; Prevent infloop.
4729 (concat "[uU]?[rR]?"
4730 (python-rx string-delimiter
)))))
4731 ;; Previous sexp was a string, restore point.
4732 (goto-char backward-sexp-point
)
4735 (python-util-forward-comment -
1)
4736 (python-nav-beginning-of-statement)
4738 ((python-info-assignment-statement-p) t
)
4739 ((python-info-looking-at-beginning-of-defun))
4742 (defun python-info-encoding-from-cookie ()
4743 "Detect current buffer's encoding from its coding cookie.
4744 Returns the encoding as a symbol."
4745 (let ((first-two-lines
4749 (goto-char (point-min))
4751 (buffer-substring-no-properties
4754 (when (string-match (python-rx coding-cookie
) first-two-lines
)
4755 (intern (match-string-no-properties 1 first-two-lines
)))))
4757 (defun python-info-encoding ()
4758 "Return encoding for file.
4759 Try `python-info-encoding-from-cookie', if none is found then
4761 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4762 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4763 ;; in the worst case scenario python.el will make things work for
4764 ;; Python 2 files with unicode data and no encoding defined.
4765 (or (python-info-encoding-from-cookie)
4769 ;;; Utility functions
4771 (defun python-util-goto-line (line-number)
4772 "Move point to LINE-NUMBER."
4773 (goto-char (point-min))
4774 (forward-line (1- line-number
)))
4776 ;; Stolen from org-mode
4777 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
4778 "Clone local variables from FROM-BUFFER.
4779 Optional argument REGEXP selects variables to clone and defaults
4783 (and (symbolp (car pair
))
4784 (string-match (or regexp
"^python-")
4785 (symbol-name (car pair
)))
4786 (set (make-local-variable (car pair
))
4788 (buffer-local-variables from-buffer
)))
4790 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
4792 (defun python-util-comint-last-prompt ()
4793 "Return comint last prompt overlay start and end.
4794 This is for compatibility with Emacs < 24.4."
4795 (cond ((bound-and-true-p comint-last-prompt-overlay
)
4796 (cons (overlay-start comint-last-prompt-overlay
)
4797 (overlay-end comint-last-prompt-overlay
)))
4798 ((bound-and-true-p comint-last-prompt
)
4802 (defun python-util-forward-comment (&optional direction
)
4803 "Python mode specific version of `forward-comment'.
4804 Optional argument DIRECTION defines the direction to move to."
4805 (let ((comment-start (python-syntax-context 'comment
))
4806 (factor (if (< (or direction
0) 0)
4810 (goto-char comment-start
))
4811 (forward-comment factor
)))
4813 (defun python-util-list-directories (directory &optional predicate max-depth
)
4814 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4815 Argument PREDICATE defaults to `identity' and must be a function
4816 that takes one argument (a full path) and returns non-nil for
4817 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4818 searching when depth is reached, else don't limit."
4819 (let* ((dir (expand-file-name directory
))
4820 (dir-length (length dir
))
4821 (predicate (or predicate
#'identity
))
4822 (to-scan (list dir
))
4825 (let ((current-dir (car to-scan
)))
4826 (when (funcall predicate current-dir
)
4827 (setq tally
(cons current-dir tally
)))
4828 (setq to-scan
(append (cdr to-scan
)
4829 (python-util-list-files
4830 current-dir
#'file-directory-p
)
4832 (when (and max-depth
4834 (length (split-string
4835 (substring current-dir dir-length
)
4837 (setq to-scan nil
))))
4840 (defun python-util-list-files (dir &optional predicate
)
4841 "List files in DIR, filtering with PREDICATE.
4842 Argument PREDICATE defaults to `identity' and must be a function
4843 that takes one argument (a full path) and returns non-nil for
4845 (let ((dir-name (file-name-as-directory dir
)))
4847 (mapcar (lambda (file-name)
4848 (let ((full-file-name (expand-file-name file-name dir-name
)))
4850 (not (member file-name
'("." "..")))
4851 (funcall (or predicate
#'identity
) full-file-name
))
4852 (list full-file-name
))))
4853 (directory-files dir-name
)))))
4855 (defun python-util-list-packages (dir &optional max-depth
)
4856 "List packages in DIR, limited by MAX-DEPTH.
4857 When optional argument MAX-DEPTH is non-nil, stop searching when
4858 depth is reached, else don't limit."
4859 (let* ((dir (expand-file-name dir
))
4860 (parent-dir (file-name-directory
4861 (directory-file-name
4862 (file-name-directory
4863 (file-name-as-directory dir
)))))
4864 (subpath-length (length parent-dir
)))
4867 (replace-regexp-in-string
4868 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
4869 (python-util-list-directories
4870 (directory-file-name dir
)
4872 (file-exists-p (expand-file-name "__init__.py" dir
)))
4875 (defun python-util-popn (lst n
)
4876 "Return LST first N elements.
4877 N should be an integer, when negative its opposite is used.
4878 When N is bigger than the length of LST, the list is
4880 (let* ((n (min (abs n
)))
4886 (setq acc
(cons (car lst
) acc
)
4891 (defun python-util-strip-string (string)
4892 "Strip STRING whitespace and newlines from end and beginning."
4893 (replace-regexp-in-string
4894 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
4895 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
4899 (defun python-util-valid-regexp-p (regexp)
4900 "Return non-nil if REGEXP is valid."
4901 (ignore-errors (string-match regexp
"") t
))
4904 (defun python-electric-pair-string-delimiter ()
4905 (when (and electric-pair-mode
4906 (memq last-command-event
'(?
\" ?
\'))
4908 (while (eq (char-before (- (point) count
)) last-command-event
)
4911 (eq (char-after) last-command-event
))
4912 (save-excursion (insert (make-string 2 last-command-event
)))))
4914 (defvar electric-indent-inhibit
)
4917 (define-derived-mode python-mode prog-mode
"Python"
4918 "Major mode for editing Python files.
4920 \\{python-mode-map}"
4921 (set (make-local-variable 'tab-width
) 8)
4922 (set (make-local-variable 'indent-tabs-mode
) nil
)
4924 (set (make-local-variable 'comment-start
) "# ")
4925 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4927 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4928 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4930 (set (make-local-variable 'forward-sexp-function
)
4931 'python-nav-forward-sexp
)
4933 (set (make-local-variable 'font-lock-defaults
)
4934 '(python-font-lock-keywords
4936 (font-lock-syntactic-face-function
4937 . python-font-lock-syntactic-face-function
)))
4939 (set (make-local-variable 'syntax-propertize-function
)
4940 python-syntax-propertize-function
)
4942 (set (make-local-variable 'indent-line-function
)
4943 #'python-indent-line-function
)
4944 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4945 ;; Because indentation is not redundant, we cannot safely reindent code.
4946 (set (make-local-variable 'electric-indent-inhibit
) t
)
4947 (set (make-local-variable 'electric-indent-chars
)
4948 (cons ?
: electric-indent-chars
))
4950 ;; Add """ ... """ pairing to electric-pair-mode.
4951 (add-hook 'post-self-insert-hook
4952 #'python-electric-pair-string-delimiter
'append t
)
4954 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4955 (set (make-local-variable 'fill-paragraph-function
)
4956 #'python-fill-paragraph
)
4958 (set (make-local-variable 'beginning-of-defun-function
)
4959 #'python-nav-beginning-of-defun
)
4960 (set (make-local-variable 'end-of-defun-function
)
4961 #'python-nav-end-of-defun
)
4963 (add-hook 'completion-at-point-functions
4964 #'python-completion-at-point nil
'local
)
4966 (add-hook 'post-self-insert-hook
4967 #'python-indent-post-self-insert-function
'append
'local
)
4969 (set (make-local-variable 'imenu-create-index-function
)
4970 #'python-imenu-create-index
)
4972 (set (make-local-variable 'add-log-current-defun-function
)
4973 #'python-info-current-defun
)
4975 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4977 (set (make-local-variable 'skeleton-further-elements
)
4979 (< '(backward-delete-char-untabify (min python-indent-offset
4981 (^
'(- (1+ (current-indentation))))))
4983 (if (null eldoc-documentation-function
)
4985 (set (make-local-variable 'eldoc-documentation-function
)
4986 #'python-eldoc-function
)
4987 (add-function :before-until
(local 'eldoc-documentation-function
)
4988 #'python-eldoc-function
))
4991 'hs-special-modes-alist
4993 "\\s-*\\(?:def\\|class\\)\\>"
4994 ;; Use the empty string as end regexp so it doesn't default to
4995 ;; "\\s)". This way parens at end of defun are properly hidden.
4998 python-hideshow-forward-sexp-function
5001 (set (make-local-variable 'outline-regexp
)
5002 (python-rx (* space
) block-start
))
5003 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
5004 (set (make-local-variable 'outline-level
)
5006 "`outline-level' function for Python mode."
5007 (1+ (/ (current-indentation) python-indent-offset
))))
5009 (python-skeleton-add-menu-items)
5011 (make-local-variable 'python-shell-internal-buffer
)
5013 (when python-indent-guess-indent-offset
5014 (python-indent-guess-indent-offset)))
5021 ;; indent-tabs-mode: nil
5024 ;;; python.el ends here