1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2015 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Maintainer: emacs-devel@gnu.org
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Shell
35 ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
36 ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows opening Python shells
66 ;; inside Emacs and executing any block of code of your current buffer
67 ;; in that inferior Python process.
69 ;; Besides that only the standard CPython (2.x and 3.x) shell and
70 ;; IPython are officially supported out of the box, the interaction
71 ;; should support any other readline based Python shells as well
72 ;; (e.g. Jython and PyPy have been reported to work). You can change
73 ;; your default interpreter and commandline arguments by setting the
74 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
75 ;; variables. This example enables IPython globally:
77 ;; (setq python-shell-interpreter "ipython"
78 ;; python-shell-interpreter-args "-i")
80 ;; Using the "console" subcommand to start IPython in server-client
81 ;; mode is known to fail intermittently due a bug on IPython itself
82 ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
83 ;; There seems to be a race condition in the IPython server (A.K.A
84 ;; kernel) when code is sent while it is still initializing, sometimes
85 ;; causing the shell to get stalled. With that said, if an IPython
86 ;; kernel is already running, "console --existing" seems to work fine.
88 ;; Running IPython on Windows needs more tweaking. The way you should
89 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
90 ;; is as follows (of course you need to modify the paths according to
93 ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
94 ;; python-shell-interpreter-args
95 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
97 ;; Missing or delayed output used to happen due to differences between
98 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
99 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
100 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
101 ;; controls whether `python-shell-calculate-process-environment'
102 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
103 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
105 ;; The interaction relies upon having prompts for input (e.g. ">>> "
106 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
107 ;; IPython) detected properly. Failing that Emacs may hang but, in
108 ;; the case that happens, you can recover with \\[keyboard-quit]. To
109 ;; avoid this issue, a two-step prompt autodetection mechanism is
110 ;; provided: the first step is manual and consists of a collection of
111 ;; regular expressions matching common prompts for Python shells
112 ;; stored in `python-shell-prompt-input-regexps' and
113 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
114 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
115 ;; `python-shell-prompt-output-regexp' which are appended to the
116 ;; former automatically when a shell spawns; the second step is
117 ;; automatic and depends on the `python-shell-prompt-detect' helper
118 ;; function. See its docstring for details on global variables that
119 ;; modify its behavior.
121 ;; Shell completion: hitting tab will try to complete the current
122 ;; word. The two built-in mechanisms depend on Python's readline
123 ;; module: the "native" completion is tried first and is activated
124 ;; when `python-shell-completion-native-enable' is non-nil, the
125 ;; current `python-shell-interpreter' is not a member of the
126 ;; `python-shell-completion-native-disabled-interpreters' variable and
127 ;; `python-shell-completion-native-setup' succeeds; the "fallback" or
128 ;; "legacy" mechanism works by executing Python code in the background
129 ;; and enables auto-completion for shells that do not support
130 ;; receiving escape sequences (with some limitations, i.e. completion
131 ;; in blocks does not work). The code executed for the "fallback"
132 ;; completion can be found in `python-shell-completion-setup-code' and
133 ;; `python-shell-completion-string-code' variables. Their default
134 ;; values enable completion for both CPython and IPython, and probably
135 ;; any readline based shell (it's known to work with PyPy). If your
136 ;; Python installation lacks readline (like CPython for Windows),
137 ;; installing pyreadline (URL `http://ipython.org/pyreadline.html')
138 ;; should suffice. To troubleshoot why you are not getting any
139 ;; completions, you can try the following in your Python shell:
141 ;; >>> import readline, rlcompleter
143 ;; If you see an error, then you need to either install pyreadline or
144 ;; setup custom code that avoids that dependency.
146 ;; Shell virtualenv support: The shell also contains support for
147 ;; virtualenvs and other special environment modifications thanks to
148 ;; `python-shell-process-environment' and `python-shell-exec-path'.
149 ;; These two variables allows you to modify execution paths and
150 ;; environment variables to make easy for you to setup virtualenv rules
151 ;; or behavior modifications when running shells. Here is an example
152 ;; of how to make shell processes to be run using the /path/to/env/
155 ;; (setq python-shell-process-environment
157 ;; (format "PATH=%s" (mapconcat
160 ;; (cons (getenv "PATH")
161 ;; '("/path/to/env/bin/")))
163 ;; "VIRTUAL_ENV=/path/to/env/"))
164 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
166 ;; Since the above is cumbersome and can be programmatically
167 ;; calculated, the variable `python-shell-virtualenv-root' is
168 ;; provided. When this variable is set with the path of the
169 ;; virtualenv to use, `process-environment' and `exec-path' get proper
170 ;; values in order to run shells inside the specified virtualenv. So
171 ;; the following will achieve the same as the previous example:
173 ;; (setq python-shell-virtualenv-root "/path/to/env/")
175 ;; Also the `python-shell-extra-pythonpaths' variable have been
176 ;; introduced as simple way of adding paths to the PYTHONPATH without
177 ;; affecting existing values.
179 ;; Shell package support: you can enable a package in the current
180 ;; shell so that relative imports work properly using the
181 ;; `python-shell-package-enable' command.
183 ;; Shell syntax highlighting: when enabled current input in shell is
184 ;; highlighted. The variable `python-shell-font-lock-enable' controls
185 ;; activation of this feature globally when shells are started.
186 ;; Activation/deactivation can be also controlled on the fly via the
187 ;; `python-shell-font-lock-toggle' command.
189 ;; Pdb tracking: when you execute a block of code that contains some
190 ;; call to pdb (or ipdb) it will prompt the block of code and will
191 ;; follow the execution of pdb marking the current line with an arrow.
193 ;; Symbol completion: you can complete the symbol at point. It uses
194 ;; the shell completion in background so you should run
195 ;; `python-shell-send-buffer' from time to time to get better results.
197 ;; Skeletons: skeletons are provided for simple inserting of things like class,
198 ;; def, for, import, if, try, and while. These skeletons are
199 ;; integrated with abbrev. If you have `abbrev-mode' activated and
200 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
201 ;; the name of any of those defined and hit SPC, they will be
202 ;; automatically expanded. As an alternative you can use the defined
203 ;; skeleton commands: `python-skeleton-<foo>'.
205 ;; FFAP: You can find the filename for a given module when using ffap
206 ;; out of the box. This feature needs an inferior python shell
209 ;; Code check: Check the current file for errors with `python-check'
210 ;; using the program defined in `python-check-command'.
212 ;; Eldoc: returns documentation for object at point by using the
213 ;; inferior python subprocess to inspect its documentation. As you
214 ;; might guessed you should run `python-shell-send-buffer' from time
215 ;; to time to get better results too.
217 ;; Imenu: There are two index building functions to be used as
218 ;; `imenu-create-index-function': `python-imenu-create-index' (the
219 ;; default one, builds the alist in form of a tree) and
220 ;; `python-imenu-create-flat-index'. See also
221 ;; `python-imenu-format-item-label-function',
222 ;; `python-imenu-format-parent-item-label-function',
223 ;; `python-imenu-format-parent-item-jump-label-function' variables for
224 ;; changing the way labels are formatted in the tree version.
226 ;; If you used python-mode.el you may miss auto-indentation when
227 ;; inserting newlines. To achieve the same behavior you have two
230 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
231 ;; default) and use RET. If this mode is disabled use
232 ;; `newline-and-indent', bound to C-j.
234 ;; 2) Add the following hook in your .emacs:
236 ;; (add-hook 'python-mode-hook
238 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
240 ;; I'd recommend the first one since you'll get the same behavior for
241 ;; all modes out-of-the-box.
245 ;; Add this to your .emacs:
247 ;; (add-to-list 'load-path "/folder/containing/file")
254 (require 'ansi-color
)
259 ;; Avoid compiler warnings
260 (defvar view-return-to-alist
)
261 (defvar compilation-error-regexp-alist
)
262 (defvar outline-heading-end-regexp
)
264 (autoload 'comint-mode
"comint")
265 (autoload 'help-function-arglist
"help-fns")
268 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
270 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
273 "Python Language's flying circus support for Emacs."
276 :link
'(emacs-commentary-link "python"))
281 (defvar python-mode-map
282 (let ((map (make-sparse-keymap)))
284 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
285 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
286 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
287 (define-key map
"\C-c\C-j" 'imenu
)
289 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
290 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
291 (define-key map
"\C-c<" 'python-indent-shift-left
)
292 (define-key map
"\C-c>" 'python-indent-shift-right
)
294 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
295 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
296 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
297 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
298 (define-key map
"\C-c\C-tm" 'python-skeleton-import
)
299 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
300 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
302 (define-key map
"\C-c\C-p" 'run-python
)
303 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
304 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
305 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
306 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
307 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
308 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
309 ;; Some util commands
310 (define-key map
"\C-c\C-v" 'python-check
)
311 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
313 (substitute-key-definition 'complete-symbol
'completion-at-point
315 (easy-menu-define python-menu map
"Python Mode menu"
317 :help
"Python-specific Features"
318 ["Shift region left" python-indent-shift-left
:active mark-active
319 :help
"Shift region left by a single indentation step"]
320 ["Shift region right" python-indent-shift-right
:active mark-active
321 :help
"Shift region right by a single indentation step"]
323 ["Start of def/class" beginning-of-defun
324 :help
"Go to start of outermost definition around point"]
325 ["End of def/class" end-of-defun
326 :help
"Go to end of definition around point"]
327 ["Mark def/class" mark-defun
328 :help
"Mark outermost definition around point"]
329 ["Jump to def/class" imenu
330 :help
"Jump to a class or function definition"]
334 ["Start interpreter" run-python
335 :help
"Run inferior Python process in a separate buffer"]
336 ["Switch to shell" python-shell-switch-to-shell
337 :help
"Switch to running inferior Python process"]
338 ["Eval string" python-shell-send-string
339 :help
"Eval string in inferior Python session"]
340 ["Eval buffer" python-shell-send-buffer
341 :help
"Eval buffer in inferior Python session"]
342 ["Eval region" python-shell-send-region
343 :help
"Eval region in inferior Python session"]
344 ["Eval defun" python-shell-send-defun
345 :help
"Eval defun in inferior Python session"]
346 ["Eval file" python-shell-send-file
347 :help
"Eval file in inferior Python session"]
348 ["Debugger" pdb
:help
"Run pdb under GUD"]
350 ["Check file" python-check
351 :help
"Check file for errors"]
352 ["Help on symbol" python-eldoc-at-point
353 :help
"Get help on symbol at point"]
354 ["Complete symbol" completion-at-point
355 :help
"Complete symbol before point"]))
357 "Keymap for `python-mode'.")
360 ;;; Python specialized rx
363 (defconst python-rx-constituents
364 `((block-start .
,(rx symbol-start
365 (or "def" "class" "if" "elif" "else" "try"
366 "except" "finally" "for" "while" "with")
368 (dedenter .
,(rx symbol-start
369 (or "elif" "else" "except" "finally")
371 (block-ender .
,(rx symbol-start
373 "break" "continue" "pass" "raise" "return")
375 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
377 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
378 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
379 (+ space
) "==" (+ space
)
380 (any ?
' ?
\") "__main__" (any ?
' ?
\")
382 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
383 (open-paren .
,(rx (or "{" "[" "(")))
384 (close-paren .
,(rx (or "}" "]" ")")))
385 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
386 ;; FIXME: rx should support (not simple-operator).
387 (not-simple-operator .
,(rx
389 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
390 ;; FIXME: Use regexp-opt.
391 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
392 "=" "%" "**" "//" "<<" ">>" "<=" "!="
393 "==" ">=" "is" "not")))
394 ;; FIXME: Use regexp-opt.
395 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
396 ">>=" "<<=" "&=" "^=" "|=")))
397 (string-delimiter .
,(rx (and
398 ;; Match even number of backslashes.
399 (or (not (any ?
\\ ?
\' ?
\")) point
400 ;; Quotes might be preceded by a escaped quote.
401 (and (or (not (any ?
\\)) point
) ?
\\
402 (* ?
\\ ?
\\) (any ?
\' ?
\")))
404 ;; Match single or triple quotes of any kind.
405 (group (or "\"" "\"\"\"" "'" "'''")))))
406 (coding-cookie .
,(rx line-start ?
# (* space
)
408 ;; # coding=<encoding name>
409 (: "coding" (or ?
: ?
=) (* space
) (group-n 1 (+ (or word ?-
))))
410 ;; # -*- coding: <encoding name> -*-
411 (: "-*-" (* space
) "coding:" (* space
)
412 (group-n 1 (+ (or word ?-
))) (* space
) "-*-")
413 ;; # vim: set fileencoding=<encoding name> :
414 (: "vim:" (* space
) "set" (+ space
)
415 "fileencoding" (* space
) ?
= (* space
)
416 (group-n 1 (+ (or word ?-
))) (* space
) ":")))))
417 "Additional Python specific sexps for `python-rx'")
419 (defmacro python-rx
(&rest regexps
)
420 "Python mode specialized rx macro.
421 This variant of `rx' supports common Python named REGEXPS."
422 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
423 (cond ((null regexps
)
426 (rx-to-string `(and ,@regexps
) t
))
428 (rx-to-string (car regexps
) t
))))))
431 ;;; Font-lock and syntax
434 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
437 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
438 (and (nth 4 ppss
) (nth 8 ppss
))))
440 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
441 (and (nth 3 ppss
) (nth 8 ppss
))))
443 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
446 (defun python-syntax-context (type &optional syntax-ppss
)
447 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
448 TYPE can be `comment', `string' or `paren'. It returns the start
449 character address of the specified TYPE."
450 (declare (compiler-macro python-syntax--context-compiler-macro
))
451 (let ((ppss (or syntax-ppss
(syntax-ppss))))
453 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
454 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
455 (`paren
(nth 1 ppss
))
458 (defun python-syntax-context-type (&optional syntax-ppss
)
459 "Return the context type using SYNTAX-PPSS.
460 The type returned can be `comment', `string' or `paren'."
461 (let ((ppss (or syntax-ppss
(syntax-ppss))))
463 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
464 ((nth 1 ppss
) 'paren
))))
466 (defsubst python-syntax-comment-or-string-p
(&optional ppss
)
467 "Return non-nil if PPSS is inside 'comment or 'string."
468 (nth 8 (or ppss
(syntax-ppss))))
470 (defsubst python-syntax-closing-paren-p
()
471 "Return non-nil if char after point is a closing paren."
472 (= (syntax-class (syntax-after (point)))
473 (syntax-class (string-to-syntax ")"))))
475 (define-obsolete-function-alias
476 'python-info-ppss-context
#'python-syntax-context
"24.3")
478 (define-obsolete-function-alias
479 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
481 (define-obsolete-function-alias
482 'python-info-ppss-comment-or-string-p
483 #'python-syntax-comment-or-string-p
"24.3")
485 (defun python-font-lock-syntactic-face-function (state)
486 "Return syntactic face given STATE."
488 (if (python-info-docstring-p state
)
490 font-lock-string-face
)
491 font-lock-comment-face
))
493 (defvar python-font-lock-keywords
497 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
498 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
499 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
504 ;; False, None, and True are listed as keywords on the Python 3
505 ;; documentation, but since they also qualify as constants they are
506 ;; fontified like that in order to keep font-lock consistent between
513 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
514 (1 font-lock-function-name-face
))
516 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
517 (1 font-lock-type-face
))
521 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
522 ;; copyright, license, credits, quit and exit are added by the site
523 ;; module and they are not intended to be used in programs
524 "copyright" "credits" "exit" "license" "quit")
525 symbol-end
) . font-lock-constant-face
)
527 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
528 (0+ "." (1+ (or word ?_
)))))
529 (1 font-lock-type-face
))
530 ;; Builtin Exceptions
533 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
534 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
535 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
536 "ImportError" "ImportWarning" "IndexError" "KeyError"
537 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
538 "NotImplementedError" "OSError" "OverflowError"
539 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
540 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
541 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
542 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
543 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
544 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
548 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
550 symbol-end
) . font-lock-type-face
)
554 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
555 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
556 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
557 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
558 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
559 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
560 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
561 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
564 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
565 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
568 "ascii" "bytearray" "bytes" "exec"
570 "__all__" "__doc__" "__name__" "__package__")
571 symbol-end
) . font-lock-builtin-face
)
573 ;; support for a = b = c = 5
575 (let ((re (python-rx (group (+ (any word ?. ?_
)))
576 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
577 assignment-operator
))
579 (while (and (setq res
(re-search-forward re limit t
))
580 (or (python-syntax-context 'paren
)
581 (equal (char-after (point)) ?
=))))
583 (1 font-lock-variable-name-face nil nil
))
584 ;; support for a, b, c = (1, 2, 3)
586 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
587 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
588 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
589 assignment-operator
))
591 (while (and (setq res
(re-search-forward re limit t
))
592 (goto-char (match-end 1))
593 (python-syntax-context 'paren
)))
595 (1 font-lock-variable-name-face nil nil
))))
597 (defconst python-syntax-propertize-function
598 (syntax-propertize-rules
599 ((python-rx string-delimiter
)
600 (0 (ignore (python-syntax-stringify))))))
602 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
603 "Count number of quotes around point (max is 3).
604 QUOTE-CHAR is the quote char to count. Optional argument POINT is
605 the point where scan starts (defaults to current point), and LIMIT
606 is used to limit the scan."
609 (or (not limit
) (< (+ point i
) limit
))
610 (eq (char-after (+ point i
)) quote-char
))
614 (defun python-syntax-stringify ()
615 "Put `syntax-table' property correctly on single/triple quotes."
616 (let* ((num-quotes (length (match-string-no-properties 1)))
618 (backward-char num-quotes
)
620 (forward-char num-quotes
)))
621 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
622 (quote-starting-pos (- (point) num-quotes
))
623 (quote-ending-pos (point))
626 (python-syntax-count-quotes
627 (char-before) string-start quote-starting-pos
))))
628 (cond ((and string-start
(= num-closing-quotes
0))
629 ;; This set of quotes doesn't match the string starting
633 ;; This set of quotes delimit the start of a string.
634 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
635 'syntax-table
(string-to-syntax "|")))
636 ((= num-quotes num-closing-quotes
)
637 ;; This set of quotes delimit the end of a string.
638 (put-text-property (1- quote-ending-pos
) quote-ending-pos
639 'syntax-table
(string-to-syntax "|")))
640 ((> num-quotes num-closing-quotes
)
641 ;; This may only happen whenever a triple quote is closing
642 ;; a single quoted string. Add string delimiter syntax to
644 (put-text-property quote-starting-pos quote-ending-pos
645 'syntax-table
(string-to-syntax "|"))))))
647 (defvar python-mode-syntax-table
648 (let ((table (make-syntax-table)))
649 ;; Give punctuation syntax to ASCII that normally has symbol
650 ;; syntax or has word syntax and isn't a letter.
651 (let ((symbol (string-to-syntax "_"))
652 (sst (standard-syntax-table)))
655 (if (equal symbol
(aref sst i
))
656 (modify-syntax-entry i
"." table
)))))
657 (modify-syntax-entry ?$
"." table
)
658 (modify-syntax-entry ?%
"." table
)
660 (modify-syntax-entry ?
# "<" table
)
661 (modify-syntax-entry ?
\n ">" table
)
662 (modify-syntax-entry ?
' "\"" table
)
663 (modify-syntax-entry ?
` "$" table
)
665 "Syntax table for Python files.")
667 (defvar python-dotty-syntax-table
668 (let ((table (make-syntax-table python-mode-syntax-table
)))
669 (modify-syntax-entry ?.
"w" table
)
670 (modify-syntax-entry ?_
"w" table
)
672 "Dotty syntax table for Python files.
673 It makes underscores and dots word constituent chars.")
678 (defcustom python-indent-offset
4
679 "Default indentation offset for Python."
684 (defcustom python-indent-guess-indent-offset t
685 "Non-nil tells Python mode to guess `python-indent-offset' value."
690 (defcustom python-indent-guess-indent-offset-verbose t
691 "Non-nil means to emit a warning when indentation guessing fails."
696 (defcustom python-indent-trigger-commands
697 '(indent-for-tab-command yas-expand yas
/expand
)
698 "Commands that might trigger a `python-indent-line' call."
699 :type
'(repeat symbol
)
702 (define-obsolete-variable-alias
703 'python-indent
'python-indent-offset
"24.3")
705 (define-obsolete-variable-alias
706 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
708 (defvar python-indent-current-level
0
709 "Deprecated var available for compatibility.")
711 (defvar python-indent-levels
'(0)
712 "Deprecated var available for compatibility.")
714 (make-obsolete-variable
715 'python-indent-current-level
716 "The indentation API changed to avoid global state.
717 The function `python-indent-calculate-levels' does not use it
718 anymore. If you were defadvising it and or depended on this
719 variable for indentation customizations, refactor your code to
720 work on `python-indent-calculate-indentation' instead."
723 (make-obsolete-variable
724 'python-indent-levels
725 "The indentation API changed to avoid global state.
726 The function `python-indent-calculate-levels' does not use it
727 anymore. If you were defadvising it and or depended on this
728 variable for indentation customizations, refactor your code to
729 work on `python-indent-calculate-indentation' instead."
732 (defun python-indent-guess-indent-offset ()
733 "Guess and set `python-indent-offset' for the current buffer."
738 (goto-char (point-min))
740 (while (and (not block-end
)
742 (python-rx line-start block-start
) nil t
))
744 (not (python-syntax-context-type))
746 (goto-char (line-end-position))
747 (python-util-forward-comment -
1)
748 (if (equal (char-before) ?
:)
751 (when (python-info-block-continuation-line-p)
752 (while (and (python-info-continuation-line-p)
755 (python-util-forward-comment -
1)
756 (when (equal (char-before) ?
:)
758 (setq block-end
(point-marker))))
761 (goto-char block-end
)
762 (python-util-forward-comment)
763 (current-indentation))))
764 (if (and indentation
(not (zerop indentation
)))
765 (set (make-local-variable 'python-indent-offset
) indentation
)
766 (when python-indent-guess-indent-offset-verbose
767 (message "Can't guess python-indent-offset, using defaults: %s"
768 python-indent-offset
))))))))
770 (defun python-indent-context ()
771 "Get information about the current indentation context.
772 Context is returned in a cons with the form (STATUS . START).
774 STATUS can be one of the following:
780 - Point is after a comment line.
781 - START is the position of the \"#\" character.
783 - Point is inside string.
784 - START is the position of the first quote that starts it.
786 - No possible indentation case matches.
787 - START is always zero.
790 - Fallback case when point is inside paren.
791 - START is the first non space char position *after* the open paren.
792 :inside-paren-at-closing-nested-paren
793 - Point is on a line that contains a nested paren closer.
794 - START is the position of the open paren it closes.
795 :inside-paren-at-closing-paren
796 - Point is on a line that contains a paren closer.
797 - START is the position of the open paren.
798 :inside-paren-newline-start
799 - Point is inside a paren with items starting in their own line.
800 - START is the position of the open paren.
801 :inside-paren-newline-start-from-block
802 - Point is inside a paren with items starting in their own line
804 - START is the position of the open paren.
807 - Fallback case when point is after backslash.
808 - START is the char after the position of the backslash.
809 :after-backslash-assignment-continuation
810 - Point is after a backslashed assignment.
811 - START is the char after the position of the backslash.
812 :after-backslash-block-continuation
813 - Point is after a backslashed block continuation.
814 - START is the char after the position of the backslash.
815 :after-backslash-dotted-continuation
816 - Point is after a backslashed dotted continuation. Previous
817 line must contain a dot to align with.
818 - START is the char after the position of the backslash.
819 :after-backslash-first-line
820 - First line following a backslashed continuation.
821 - START is the char after the position of the backslash.
824 - Point is after a line containing a block ender.
825 - START is the position where the ender starts.
827 - Point is after a line starting a block.
828 - START is the position where the block starts.
830 - Point is after a simple line.
831 - START is the position where the previous line starts.
832 :at-dedenter-block-start
833 - Point is on a line starting a dedenter block.
834 - START is the position where the dedenter block starts."
837 (let ((ppss (save-excursion
841 ;; Beginning of buffer.
842 ((= (line-number-at-pos) 1)
845 ((let ((start (python-syntax-context 'string ppss
)))
847 (cons (if (python-info-docstring-p)
849 :inside-string
) start
))))
851 ((let* ((start (python-syntax-context 'paren ppss
))
858 (= (line-number-at-pos)
860 (python-util-forward-comment)
861 (line-number-at-pos))))))))
864 ;; Current line only holds the closing paren.
866 (skip-syntax-forward " ")
867 (when (and (python-syntax-closing-paren-p)
870 (not (python-syntax-context 'paren
))))
871 (cons :inside-paren-at-closing-paren start
))))
872 ;; Current line only holds a closing paren for nested.
874 (back-to-indentation)
875 (python-syntax-closing-paren-p))
876 (cons :inside-paren-at-closing-nested-paren start
))
877 ;; This line starts from a opening block in its own line.
883 (back-to-indentation)
884 (looking-at (python-rx block-start
))))
886 :inside-paren-newline-start-from-block start
))))
888 (cons :inside-paren-newline-start start
))
890 (t (cons :inside-paren
892 (goto-char (1+ start
))
893 (skip-syntax-forward "(" 1)
894 (skip-syntax-forward " ")
897 ((let ((start (when (not (python-syntax-comment-or-string-p ppss
))
898 (python-info-line-ends-backslash-p
899 (1- (line-number-at-pos))))))
902 ;; Continuation of dotted expression.
904 (back-to-indentation)
905 (when (eq (char-after) ?\.
)
906 ;; Move point back until it's not inside a paren.
910 (python-syntax-context 'paren
))))
911 (goto-char (line-end-position))
912 (while (and (search-backward
913 "." (line-beginning-position) t
)
914 (python-syntax-context-type)))
915 ;; Ensure previous statement has dot to align with.
916 (when (and (eq (char-after) ?\.
)
917 (not (python-syntax-context-type)))
918 (cons :after-backslash-dotted-continuation
(point))))))
919 ;; Continuation of block definition.
920 ((let ((block-continuation-start
921 (python-info-block-continuation-line-p)))
922 (when block-continuation-start
924 (goto-char block-continuation-start
)
926 (python-rx block-start
(* space
))
927 (line-end-position) t
)
928 (cons :after-backslash-block-continuation
(point))))))
929 ;; Continuation of assignment.
930 ((let ((assignment-continuation-start
931 (python-info-assignment-continuation-line-p)))
932 (when assignment-continuation-start
934 (goto-char assignment-continuation-start
)
935 (cons :after-backslash-assignment-continuation
(point))))))
936 ;; First line after backslash continuation start.
939 (when (or (= (line-number-at-pos) 1)
940 (not (python-info-beginning-of-backslash
941 (1- (line-number-at-pos)))))
942 (cons :after-backslash-first-line start
))))
944 (t (cons :after-backslash start
))))))
945 ;; After beginning of block.
946 ((let ((start (save-excursion
947 (back-to-indentation)
948 (python-util-forward-comment -
1)
949 (when (equal (char-before) ?
:)
950 (python-nav-beginning-of-block)))))
952 (cons :after-block-start start
))))
953 ;; At dedenter statement.
954 ((let ((start (python-info-dedenter-statement-p)))
956 (cons :at-dedenter-block-start start
))))
957 ;; After normal line, comment or ender (default case).
959 (back-to-indentation)
960 (skip-chars-backward " \t\n")
961 (python-nav-beginning-of-statement)
963 (cond ((python-info-current-line-comment-p)
966 (goto-char (line-end-position))
967 (python-util-forward-comment -
1)
968 (python-nav-beginning-of-statement)
969 (looking-at (python-rx block-ender
)))
974 (defun python-indent--calculate-indentation ()
975 "Internal implementation of `python-indent-calculate-indentation'.
976 May return an integer for the maximum possible indentation at
977 current context or a list of integers. The latter case is only
978 happening for :at-dedenter-block-start context since the
979 possibilities can be narrowed to specific indentation points."
983 (pcase (python-indent-context)
984 (`(:no-indent .
,_
) 0)
989 :inside-paren-at-closing-paren
990 :inside-paren-at-closing-nested-paren
) .
,start
)
991 ;; Copy previous indentation.
993 (current-indentation))
994 (`(:inside-docstring .
,start
)
995 (let* ((line-indentation (current-indentation))
998 (current-indentation))))
999 (max line-indentation base-indent
)))
1000 (`(,(or :after-block-start
1001 :after-backslash-first-line
1002 :inside-paren-newline-start
) .
,start
)
1003 ;; Add one indentation level.
1005 (+ (current-indentation) python-indent-offset
))
1006 (`(,(or :inside-paren
1007 :after-backslash-block-continuation
1008 :after-backslash-assignment-continuation
1009 :after-backslash-dotted-continuation
) .
,start
)
1010 ;; Use the column given by the context.
1013 (`(:after-block-end .
,start
)
1014 ;; Subtract one indentation level.
1016 (- (current-indentation) python-indent-offset
))
1017 (`(:at-dedenter-block-start .
,_
)
1018 ;; List all possible indentation levels from opening blocks.
1019 (let ((opening-block-start-points
1020 (python-info-dedenter-opening-block-positions)))
1021 (if (not opening-block-start-points
)
1022 0 ; if not found default to first column
1023 (mapcar (lambda (pos)
1026 (current-indentation)))
1027 opening-block-start-points
))))
1028 (`(,(or :inside-paren-newline-start-from-block
) .
,start
)
1029 ;; Add two indentation levels to make the suite stand out.
1031 (+ (current-indentation) (* python-indent-offset
2)))))))
1033 (defun python-indent--calculate-levels (indentation)
1034 "Calculate levels list given INDENTATION.
1035 Argument INDENTATION can either be an integer or a list of
1036 integers. Levels are returned in ascending order, and in the
1037 case INDENTATION is a list, this order is enforced."
1038 (if (listp indentation
)
1039 (sort (copy-sequence indentation
) #'<)
1040 (let* ((remainder (% indentation python-indent-offset
))
1041 (steps (/ (- indentation remainder
) python-indent-offset
))
1042 (levels (mapcar (lambda (step)
1043 (* python-indent-offset step
))
1044 (number-sequence steps
0 -
1))))
1046 (if (not (zerop remainder
))
1047 (cons indentation levels
)
1050 (defun python-indent--previous-level (levels indentation
)
1051 "Return previous level from LEVELS relative to INDENTATION."
1052 (let* ((levels (sort (copy-sequence levels
) #'>))
1053 (default (car levels
)))
1055 (dolist (level levels
)
1056 (when (funcall #'< level indentation
)
1057 (throw 'return level
)))
1060 (defun python-indent-calculate-indentation (&optional previous
)
1061 "Calculate indentation.
1062 Get indentation of PREVIOUS level when argument is non-nil.
1063 Return the max level of the cycle when indentation reaches the
1065 (let* ((indentation (python-indent--calculate-indentation))
1066 (levels (python-indent--calculate-levels indentation
)))
1068 (python-indent--previous-level levels
(current-indentation))
1070 (apply #'max levels
)
1073 (defun python-indent-line (&optional previous
)
1074 "Internal implementation of `python-indent-line-function'.
1075 Use the PREVIOUS level when argument is non-nil, otherwise indent
1076 to the maximum available level. When indentation is the minimum
1077 possible and PREVIOUS is non-nil, cycle back to the maximum
1079 (let ((follow-indentation-p
1080 ;; Check if point is within indentation.
1081 (and (<= (line-beginning-position) (point))
1082 (>= (+ (line-beginning-position)
1083 (current-indentation))
1087 (python-indent-calculate-indentation previous
))
1088 (python-info-dedenter-opening-block-message))
1089 (when follow-indentation-p
1090 (back-to-indentation))))
1092 (defun python-indent-calculate-levels ()
1093 "Return possible indentation levels."
1094 (python-indent--calculate-levels
1095 (python-indent--calculate-indentation)))
1097 (defun python-indent-line-function ()
1098 "`indent-line-function' for Python mode.
1099 When the variable `last-command' is equal to one of the symbols
1100 inside `python-indent-trigger-commands' it cycles possible
1101 indentation levels from right to left."
1103 (and (memq this-command python-indent-trigger-commands
)
1104 (eq last-command this-command
))))
1106 (defun python-indent-dedent-line ()
1107 "De-indent current line."
1109 (when (and (not (bolp))
1110 (not (python-syntax-comment-or-string-p))
1111 (= (current-indentation) (current-column)))
1112 (python-indent-line t
)
1115 (defun python-indent-dedent-line-backspace (arg)
1116 "De-indent current line.
1117 Argument ARG is passed to `backward-delete-char-untabify' when
1118 point is not in between the indentation."
1120 (unless (python-indent-dedent-line)
1121 (backward-delete-char-untabify arg
)))
1123 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1125 (defun python-indent-region (start end
)
1126 "Indent a Python region automagically.
1128 Called from a program, START and END specify the region to indent."
1129 (let ((deactivate-mark nil
))
1132 (setq end
(point-marker))
1134 (or (bolp) (forward-line 1))
1135 (while (< (point) end
)
1136 (or (and (bolp) (eolp))
1138 ;; Skip if previous line is empty or a comment.
1140 (let ((line-is-comment-p
1141 (python-info-current-line-comment-p)))
1144 (or (and (python-info-current-line-comment-p)
1145 ;; Unless this line is a comment too.
1146 (not line-is-comment-p
))
1147 (python-info-current-line-empty-p)))))
1148 ;; Don't mess with strings, unless it's the
1149 ;; enclosing set of quotes or a docstring.
1150 (or (not (python-syntax-context 'string
))
1154 (current-indentation)
1155 (python-syntax-count-quotes (char-after) (point))))
1156 (string-to-syntax "|"))
1157 (python-info-docstring-p))
1158 ;; Skip if current line is a block start, a
1159 ;; dedenter or block ender.
1161 (back-to-indentation)
1164 (or block-start dedenter block-ender
))))))
1165 (python-indent-line)))
1167 (move-marker end nil
))))
1169 (defun python-indent-shift-left (start end
&optional count
)
1170 "Shift lines contained in region START END by COUNT columns to the left.
1171 COUNT defaults to `python-indent-offset'. If region isn't
1172 active, the current line is shifted. The shifted region includes
1173 the lines in which START and END lie. An error is signaled if
1174 any lines in the region are indented less than COUNT columns."
1177 (list (region-beginning) (region-end) current-prefix-arg
)
1178 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1180 (setq count
(prefix-numeric-value count
))
1181 (setq count python-indent-offset
))
1183 (let ((deactivate-mark nil
))
1186 (while (< (point) end
)
1187 (if (and (< (current-indentation) count
)
1188 (not (looking-at "[ \t]*$")))
1189 (user-error "Can't shift all lines enough"))
1191 (indent-rigidly start end
(- count
))))))
1193 (defun python-indent-shift-right (start end
&optional count
)
1194 "Shift lines contained in region START END by COUNT columns to the right.
1195 COUNT defaults to `python-indent-offset'. If region isn't
1196 active, the current line is shifted. The shifted region includes
1197 the lines in which START and END lie."
1200 (list (region-beginning) (region-end) current-prefix-arg
)
1201 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1202 (let ((deactivate-mark nil
))
1203 (setq count
(if count
(prefix-numeric-value count
)
1204 python-indent-offset
))
1205 (indent-rigidly start end count
)))
1207 (defun python-indent-post-self-insert-function ()
1208 "Adjust indentation after insertion of some characters.
1209 This function is intended to be added to `post-self-insert-hook.'
1210 If a line renders a paren alone, after adding a char before it,
1211 the line will be re-indented automatically if needed."
1212 (when (and electric-indent-mode
1213 (eq (char-before) last-command-event
))
1215 ;; Electric indent inside parens
1218 (let ((paren-start (python-syntax-context 'paren
)))
1219 ;; Check that point is inside parens.
1222 ;; Filter the case where input is happening in the same
1223 ;; line where the open paren is.
1224 (= (line-number-at-pos)
1225 (line-number-at-pos paren-start
)))))
1226 ;; When content has been added before the closing paren or a
1227 ;; comma has been inserted, it's ok to do the trick.
1229 (memq (char-after) '(?\
) ?\
] ?\
}))
1230 (eq (char-before) ?
,)))
1232 (goto-char (line-beginning-position))
1233 (let ((indentation (python-indent-calculate-indentation)))
1234 (when (and (numberp indentation
) (< (current-indentation) indentation
))
1235 (indent-line-to indentation
)))))
1237 ((and (eq ?
: last-command-event
)
1238 (memq ?
: electric-indent-chars
)
1239 (not current-prefix-arg
)
1240 ;; Trigger electric colon only at end of line
1242 ;; Avoid re-indenting on extra colon
1243 (not (equal ?
: (char-before (1- (point)))))
1244 (not (python-syntax-comment-or-string-p)))
1245 ;; Just re-indent dedenters
1246 (let ((dedenter-pos (python-info-dedenter-statement-p))
1247 (current-pos (point)))
1250 (goto-char dedenter-pos
)
1251 (python-indent-line)
1252 (unless (= (line-number-at-pos dedenter-pos
)
1253 (line-number-at-pos current-pos
))
1254 ;; Reindent region if this is a multiline statement
1255 (python-indent-region dedenter-pos current-pos
)))))))))
1260 (defvar python-nav-beginning-of-defun-regexp
1261 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1262 "Regexp matching class or function definition.
1263 The name of the defun should be grouped so it can be retrieved
1264 via `match-string'.")
1266 (defun python-nav--beginning-of-defun (&optional arg
)
1267 "Internal implementation of `python-nav-beginning-of-defun'.
1268 With positive ARG search backwards, else search forwards."
1269 (when (or (null arg
) (= arg
0)) (setq arg
1))
1270 (let* ((re-search-fn (if (> arg
0)
1271 #'re-search-backward
1272 #'re-search-forward
))
1273 (line-beg-pos (line-beginning-position))
1274 (line-content-start (+ line-beg-pos
(current-indentation)))
1275 (pos (point-marker))
1280 (not (python-info-looking-at-beginning-of-defun))
1281 (python-nav-backward-block)))
1282 (or (and (python-info-looking-at-beginning-of-defun)
1283 (+ (current-indentation) python-indent-offset
))
1287 (when (and (< arg
0)
1288 (python-info-looking-at-beginning-of-defun))
1290 (while (and (funcall re-search-fn
1291 python-nav-beginning-of-defun-regexp nil t
)
1292 (or (python-syntax-context-type)
1293 ;; Handle nested defuns when moving
1294 ;; backwards by checking indentation.
1296 (not (= (current-indentation) 0))
1297 (>= (current-indentation) beg-indentation
)))))
1298 (and (python-info-looking-at-beginning-of-defun)
1299 (or (not (= (line-number-at-pos pos
)
1300 (line-number-at-pos)))
1301 (and (>= (point) line-beg-pos
)
1302 (<= (point) line-content-start
)
1303 (> pos line-content-start
)))))))
1305 (or (beginning-of-line 1) t
)
1306 (and (goto-char pos
) nil
))))
1308 (defun python-nav-beginning-of-defun (&optional arg
)
1309 "Move point to `beginning-of-defun'.
1310 With positive ARG search backwards else search forward.
1311 ARG nil or 0 defaults to 1. When searching backwards,
1312 nested defuns are handled with care depending on current
1313 point position. Return non-nil if point is moved to
1314 `beginning-of-defun'."
1315 (when (or (null arg
) (= arg
0)) (setq arg
1))
1317 (while (and (not (= arg
0))
1318 (let ((keep-searching-p
1319 (python-nav--beginning-of-defun arg)))
1320 (when (and keep-searching-p
(null found
))
1323 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1326 (defun python-nav-end-of-defun ()
1327 "Move point to the end of def or class.
1328 Returns nil if point is not in a def or class."
1330 (let ((beg-defun-indent)
1332 (when (or (python-info-looking-at-beginning-of-defun)
1333 (python-nav-beginning-of-defun 1)
1334 (python-nav-beginning-of-defun -1))
1335 (setq beg-defun-indent
(current-indentation))
1337 (python-nav-end-of-statement)
1338 (python-util-forward-comment 1)
1339 (and (> (current-indentation) beg-defun-indent
)
1341 (python-util-forward-comment -
1)
1343 ;; Ensure point moves forward.
1344 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1346 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1347 "Move point using FN avoiding places with specific context.
1348 FN must take no arguments. POSCOMPFN is a two arguments function
1349 used to compare current and previous point after it is moved
1350 using FN, this is normally a less-than or greater-than
1351 comparison. Optional argument CONTEXTFN defaults to
1352 `python-syntax-context-type' and is used for checking current
1353 point context, it must return a non-nil value if this point must
1355 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1356 (start-pos (point-marker))
1361 (and (funcall fn
) (point-marker)))
1362 (context (funcall contextfn
)))
1363 (cond ((and (not context
) newpos
1364 (or (and (not prev-pos
) newpos
)
1365 (and prev-pos newpos
1366 (funcall poscompfn newpos prev-pos
))))
1367 (throw 'found
(point-marker)))
1368 ((and newpos context
)
1369 (setq prev-pos
(point)))
1370 (t (when (not newpos
) (goto-char start-pos
))
1371 (throw 'found nil
))))))))
1373 (defun python-nav--forward-defun (arg)
1374 "Internal implementation of python-nav-{backward,forward}-defun.
1375 Uses ARG to define which function to call, and how many times
1378 (while (and (> arg
0)
1380 (python-nav--syntactically
1383 python-nav-beginning-of-defun-regexp nil t
))
1385 (setq arg
(1- arg
)))
1386 (while (and (< arg
0)
1388 (python-nav--syntactically
1391 python-nav-beginning-of-defun-regexp nil t
))
1393 (setq arg
(1+ arg
)))
1396 (defun python-nav-backward-defun (&optional arg
)
1397 "Navigate to closer defun backward ARG times.
1398 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1399 nested definitions."
1401 (python-nav--forward-defun (- (or arg
1))))
1403 (defun python-nav-forward-defun (&optional arg
)
1404 "Navigate to closer defun forward ARG times.
1405 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1406 nested definitions."
1408 (python-nav--forward-defun (or arg
1)))
1410 (defun python-nav-beginning-of-statement ()
1411 "Move to start of current statement."
1413 (back-to-indentation)
1414 (let* ((ppss (syntax-ppss))
1417 (python-syntax-context 'paren ppss
)
1418 (python-syntax-context 'string ppss
))))
1421 (goto-char context-point
)
1422 (python-nav-beginning-of-statement))
1425 (python-info-line-ends-backslash-p))
1427 (python-nav-beginning-of-statement))))
1430 (defun python-nav-end-of-statement (&optional noend
)
1431 "Move to end of current statement.
1432 Optional argument NOEND is internal and makes the logic to not
1433 jump to the end of line when moving forward searching for the end
1436 (let (string-start bs-pos
)
1437 (while (and (or noend
(goto-char (line-end-position)))
1439 (cond ((setq string-start
(python-syntax-context 'string
))
1440 (goto-char string-start
)
1441 (if (python-syntax-context 'paren
)
1442 ;; Ended up inside a paren, roll again.
1443 (python-nav-end-of-statement t
)
1444 ;; This is not inside a paren, move to the
1445 ;; end of this string.
1446 (goto-char (+ (point)
1447 (python-syntax-count-quotes
1448 (char-after (point)) (point))))
1449 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1450 (goto-char (point-max)))))
1451 ((python-syntax-context 'paren
)
1452 ;; The statement won't end before we've escaped
1453 ;; at least one level of parenthesis.
1455 (goto-char (scan-lists (point) 1 -
1))
1456 (scan-error (goto-char (nth 3 err
)))))
1457 ((setq bs-pos
(python-info-line-ends-backslash-p))
1459 (forward-line 1))))))
1462 (defun python-nav-backward-statement (&optional arg
)
1463 "Move backward to previous statement.
1464 With ARG, repeat. See `python-nav-forward-statement'."
1466 (or arg
(setq arg
1))
1467 (python-nav-forward-statement (- arg
)))
1469 (defun python-nav-forward-statement (&optional arg
)
1470 "Move forward to next statement.
1471 With ARG, repeat. With negative argument, move ARG times
1472 backward to previous statement."
1474 (or arg
(setq arg
1))
1476 (python-nav-end-of-statement)
1477 (python-util-forward-comment)
1478 (python-nav-beginning-of-statement)
1479 (setq arg
(1- arg
)))
1481 (python-nav-beginning-of-statement)
1482 (python-util-forward-comment -
1)
1483 (python-nav-beginning-of-statement)
1484 (setq arg
(1+ arg
))))
1486 (defun python-nav-beginning-of-block ()
1487 "Move to start of current block."
1489 (let ((starting-pos (point)))
1491 (python-nav-beginning-of-statement)
1492 (looking-at (python-rx block-start
)))
1494 ;; Go to first line beginning a statement
1495 (while (and (not (bobp))
1496 (or (and (python-nav-beginning-of-statement) nil
)
1497 (python-info-current-line-comment-p)
1498 (python-info-current-line-empty-p)))
1500 (let ((block-matching-indent
1501 (- (current-indentation) python-indent-offset
)))
1503 (and (python-nav-backward-block)
1504 (> (current-indentation) block-matching-indent
)))
1505 (if (and (looking-at (python-rx block-start
))
1506 (= (current-indentation) block-matching-indent
))
1508 (and (goto-char starting-pos
) nil
))))))
1510 (defun python-nav-end-of-block ()
1511 "Move to end of current block."
1513 (when (python-nav-beginning-of-block)
1514 (let ((block-indentation (current-indentation)))
1515 (python-nav-end-of-statement)
1516 (while (and (forward-line 1)
1518 (or (and (> (current-indentation) block-indentation
)
1519 (or (python-nav-end-of-statement) t
))
1520 (python-info-current-line-comment-p)
1521 (python-info-current-line-empty-p))))
1522 (python-util-forward-comment -
1)
1525 (defun python-nav-backward-block (&optional arg
)
1526 "Move backward to previous block of code.
1527 With ARG, repeat. See `python-nav-forward-block'."
1529 (or arg
(setq arg
1))
1530 (python-nav-forward-block (- arg
)))
1532 (defun python-nav-forward-block (&optional arg
)
1533 "Move forward to next block of code.
1534 With ARG, repeat. With negative argument, move ARG times
1535 backward to previous block."
1537 (or arg
(setq arg
1))
1538 (let ((block-start-regexp
1539 (python-rx line-start
(* whitespace
) block-start
))
1540 (starting-pos (point)))
1542 (python-nav-end-of-statement)
1544 (re-search-forward block-start-regexp nil t
)
1545 (python-syntax-context-type)))
1546 (setq arg
(1- arg
)))
1548 (python-nav-beginning-of-statement)
1550 (re-search-backward block-start-regexp nil t
)
1551 (python-syntax-context-type)))
1552 (setq arg
(1+ arg
)))
1553 (python-nav-beginning-of-statement)
1554 (if (not (looking-at (python-rx block-start
)))
1555 (and (goto-char starting-pos
) nil
)
1556 (and (not (= (point) starting-pos
)) (point-marker)))))
1558 (defun python-nav--lisp-forward-sexp (&optional arg
)
1559 "Standard version `forward-sexp'.
1560 It ignores completely the value of `forward-sexp-function' by
1561 setting it to nil before calling `forward-sexp'. With positive
1562 ARG move forward only one sexp, else move backwards."
1563 (let ((forward-sexp-function)
1564 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1565 (forward-sexp arg
)))
1567 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1568 "Safe version of standard `forward-sexp'.
1569 When at end of sexp (i.e. looking at a opening/closing paren)
1570 skips it instead of throwing an error. With positive ARG move
1571 forward only one sexp, else move backwards."
1572 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1574 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1576 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1578 (python-nav--lisp-forward-sexp arg
)
1580 (while (and (funcall search-fn paren-regexp nil t
)
1581 (python-syntax-context 'paren
)))))))
1583 (defun python-nav--forward-sexp (&optional dir safe skip-parens-p
)
1584 "Move to forward sexp.
1585 With positive optional argument DIR direction move forward, else
1586 backwards. When optional argument SAFE is non-nil do not throw
1587 errors when at end of sexp, skip it instead. With optional
1588 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1589 expressions when looking at them in either direction."
1590 (setq dir
(or dir
1))
1592 (let* ((forward-p (if (> dir
0)
1593 (and (setq dir
1) t
)
1594 (and (setq dir -
1) nil
)))
1595 (context-type (python-syntax-context-type)))
1597 ((memq context-type
'(string comment
))
1598 ;; Inside of a string, get out of it.
1599 (let ((forward-sexp-function))
1600 (forward-sexp dir
)))
1601 ((and (not skip-parens-p
)
1602 (or (eq context-type
'paren
)
1604 (eq (syntax-class (syntax-after (point)))
1605 (car (string-to-syntax "(")))
1606 (eq (syntax-class (syntax-after (1- (point))))
1607 (car (string-to-syntax ")"))))))
1608 ;; Inside a paren or looking at it, lisp knows what to do.
1610 (python-nav--lisp-forward-sexp-safe dir
)
1611 (python-nav--lisp-forward-sexp dir
)))
1613 ;; This part handles the lispy feel of
1614 ;; `python-nav-forward-sexp'. Knowing everything about the
1615 ;; current context and the context of the next sexp tries to
1616 ;; follow the lisp sexp motion commands in a symmetric manner.
1619 ((python-info-beginning-of-block-p) 'block-start
)
1620 ((python-info-end-of-block-p) 'block-end
)
1621 ((python-info-beginning-of-statement-p) 'statement-start
)
1622 ((python-info-end-of-statement-p) 'statement-end
)))
1626 (python-nav--lisp-forward-sexp-safe dir
)
1627 (python-nav--lisp-forward-sexp dir
))
1631 (goto-char next-sexp-pos
)
1633 ((python-info-beginning-of-block-p) 'block-start
)
1634 ((python-info-end-of-block-p) 'block-end
)
1635 ((python-info-beginning-of-statement-p) 'statement-start
)
1636 ((python-info-end-of-statement-p) 'statement-end
)
1637 ((python-info-statement-starts-block-p) 'starts-block
)
1638 ((python-info-statement-ends-block-p) 'ends-block
)))))
1640 (cond ((and (not (eobp))
1641 (python-info-current-line-empty-p))
1642 (python-util-forward-comment dir
)
1643 (python-nav--forward-sexp dir safe skip-parens-p
))
1644 ((eq context
'block-start
)
1645 (python-nav-end-of-block))
1646 ((eq context
'statement-start
)
1647 (python-nav-end-of-statement))
1648 ((and (memq context
'(statement-end block-end
))
1649 (eq next-sexp-context
'ends-block
))
1650 (goto-char next-sexp-pos
)
1651 (python-nav-end-of-block))
1652 ((and (memq context
'(statement-end block-end
))
1653 (eq next-sexp-context
'starts-block
))
1654 (goto-char next-sexp-pos
)
1655 (python-nav-end-of-block))
1656 ((memq context
'(statement-end block-end
))
1657 (goto-char next-sexp-pos
)
1658 (python-nav-end-of-statement))
1659 (t (goto-char next-sexp-pos
)))
1660 (cond ((and (not (bobp))
1661 (python-info-current-line-empty-p))
1662 (python-util-forward-comment dir
)
1663 (python-nav--forward-sexp dir safe skip-parens-p
))
1664 ((eq context
'block-end
)
1665 (python-nav-beginning-of-block))
1666 ((eq context
'statement-end
)
1667 (python-nav-beginning-of-statement))
1668 ((and (memq context
'(statement-start block-start
))
1669 (eq next-sexp-context
'starts-block
))
1670 (goto-char next-sexp-pos
)
1671 (python-nav-beginning-of-block))
1672 ((and (memq context
'(statement-start block-start
))
1673 (eq next-sexp-context
'ends-block
))
1674 (goto-char next-sexp-pos
)
1675 (python-nav-beginning-of-block))
1676 ((memq context
'(statement-start block-start
))
1677 (goto-char next-sexp-pos
)
1678 (python-nav-beginning-of-statement))
1679 (t (goto-char next-sexp-pos
))))))))))
1681 (defun python-nav-forward-sexp (&optional arg safe skip-parens-p
)
1682 "Move forward across expressions.
1683 With ARG, do it that many times. Negative arg -N means move
1684 backward N times. When optional argument SAFE is non-nil do not
1685 throw errors when at end of sexp, skip it instead. With optional
1686 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1687 expressions when looking at them in either direction (forced to t
1688 in interactive calls)."
1690 (or arg
(setq arg
1))
1691 ;; Do not follow parens on interactive calls. This hack to detect
1692 ;; if the function was called interactively copes with the way
1693 ;; `forward-sexp' works by calling `forward-sexp-function', losing
1694 ;; interactive detection by checking `current-prefix-arg'. The
1695 ;; reason to make this distinction is that lisp functions like
1696 ;; `blink-matching-open' get confused causing issues like the one in
1697 ;; Bug#16191. With this approach the user gets a symmetric behavior
1698 ;; when working interactively while called functions expecting
1699 ;; paren-based sexp motion work just fine.
1703 (memq real-this-command
1705 #'forward-sexp
#'backward-sexp
1706 #'python-nav-forward-sexp
#'python-nav-backward-sexp
1707 #'python-nav-forward-sexp-safe
#'python-nav-backward-sexp
))))
1709 (python-nav--forward-sexp 1 safe skip-parens-p
)
1710 (setq arg
(1- arg
)))
1712 (python-nav--forward-sexp -
1 safe skip-parens-p
)
1713 (setq arg
(1+ arg
))))
1715 (defun python-nav-backward-sexp (&optional arg safe skip-parens-p
)
1716 "Move backward across expressions.
1717 With ARG, do it that many times. Negative arg -N means move
1718 forward N times. When optional argument SAFE is non-nil do not
1719 throw errors when at end of sexp, skip it instead. With optional
1720 argument SKIP-PARENS-P force sexp motion to ignore parenthesized
1721 expressions when looking at them in either direction (forced to t
1722 in interactive calls)."
1724 (or arg
(setq arg
1))
1725 (python-nav-forward-sexp (- arg
) safe skip-parens-p
))
1727 (defun python-nav-forward-sexp-safe (&optional arg skip-parens-p
)
1728 "Move forward safely across expressions.
1729 With ARG, do it that many times. Negative arg -N means move
1730 backward N times. With optional argument SKIP-PARENS-P force
1731 sexp motion to ignore parenthesized expressions when looking at
1732 them in either direction (forced to t in interactive calls)."
1734 (python-nav-forward-sexp arg t skip-parens-p
))
1736 (defun python-nav-backward-sexp-safe (&optional arg skip-parens-p
)
1737 "Move backward safely across expressions.
1738 With ARG, do it that many times. Negative arg -N means move
1739 forward N times. With optional argument SKIP-PARENS-P force sexp
1740 motion to ignore parenthesized expressions when looking at them in
1741 either direction (forced to t in interactive calls)."
1743 (python-nav-backward-sexp arg t skip-parens-p
))
1745 (defun python-nav--up-list (&optional dir
)
1746 "Internal implementation of `python-nav-up-list'.
1747 DIR is always 1 or -1 and comes sanitized from
1748 `python-nav-up-list' calls."
1749 (let ((context (python-syntax-context-type))
1750 (forward-p (> dir
0)))
1752 ((memq context
'(string comment
)))
1753 ((eq context
'paren
)
1754 (let ((forward-sexp-function))
1756 ((and forward-p
(python-info-end-of-block-p))
1757 (let ((parent-end-pos
1759 (let ((indentation (and
1760 (python-nav-beginning-of-block)
1761 (current-indentation))))
1762 (while (and indentation
1764 (>= (current-indentation) indentation
)
1765 (python-nav-backward-block)))
1766 (python-nav-end-of-block)))))
1767 (and (> (or parent-end-pos
(point)) (point))
1768 (goto-char parent-end-pos
))))
1769 (forward-p (python-nav-end-of-block))
1770 ((and (not forward-p
)
1771 (> (current-indentation) 0)
1772 (python-info-beginning-of-block-p))
1773 (let ((prev-block-pos
1775 (let ((indentation (current-indentation)))
1776 (while (and (python-nav-backward-block)
1777 (>= (current-indentation) indentation
))))
1779 (and (> (point) prev-block-pos
)
1780 (goto-char prev-block-pos
))))
1781 ((not forward-p
) (python-nav-beginning-of-block)))))
1783 (defun python-nav-up-list (&optional arg
)
1784 "Move forward out of one level of parentheses (or blocks).
1785 With ARG, do this that many times.
1786 A negative argument means move backward but still to a less deep spot.
1787 This command assumes point is not in a string or comment."
1789 (or arg
(setq arg
1))
1791 (python-nav--up-list 1)
1792 (setq arg
(1- arg
)))
1794 (python-nav--up-list -
1)
1795 (setq arg
(1+ arg
))))
1797 (defun python-nav-backward-up-list (&optional arg
)
1798 "Move backward out of one level of parentheses (or blocks).
1799 With ARG, do this that many times.
1800 A negative argument means move forward but still to a less deep spot.
1801 This command assumes point is not in a string or comment."
1803 (or arg
(setq arg
1))
1804 (python-nav-up-list (- arg
)))
1806 (defun python-nav-if-name-main ()
1807 "Move point at the beginning the __main__ block.
1808 When \"if __name__ == '__main__':\" is found returns its
1809 position, else returns nil."
1811 (let ((point (point))
1812 (found (catch 'found
1813 (goto-char (point-min))
1814 (while (re-search-forward
1815 (python-rx line-start
1817 "__name__" (+ space
)
1819 (group-n 1 (or ?
\" ?
\'))
1820 "__main__" (backref 1) (* space
) ":")
1822 (when (not (python-syntax-context-type))
1824 (throw 'found t
))))))
1827 (ignore (goto-char point
)))))
1830 ;;; Shell integration
1832 (defcustom python-shell-buffer-name
"Python"
1833 "Default buffer name for Python interpreter."
1838 (defcustom python-shell-interpreter
"python"
1839 "Default Python interpreter for shell."
1843 (defcustom python-shell-internal-buffer-name
"Python Internal"
1844 "Default buffer name for the Internal Python interpreter."
1849 (defcustom python-shell-interpreter-args
"-i"
1850 "Default arguments for the Python interpreter."
1854 (defcustom python-shell-interpreter-interactive-arg
"-i"
1855 "Interpreter argument to force it to run interactively."
1859 (defcustom python-shell-prompt-detect-enabled t
1860 "Non-nil enables autodetection of interpreter prompts."
1865 (defcustom python-shell-prompt-detect-failure-warning t
1866 "Non-nil enables warnings when detection of prompts fail."
1871 (defcustom python-shell-prompt-input-regexps
1872 '(">>> " "\\.\\.\\. " ; Python
1873 "In \\[[0-9]+\\]: " ; IPython
1874 " \\.\\.\\.: " ; IPython
1875 ;; Using ipdb outside IPython may fail to cleanup and leave static
1876 ;; IPython prompts activated, this adds some safeguard for that.
1877 "In : " "\\.\\.\\.: ")
1878 "List of regular expressions matching input prompts."
1879 :type
'(repeat string
)
1882 (defcustom python-shell-prompt-output-regexps
1884 "Out\\[[0-9]+\\]: " ; IPython
1885 "Out :") ; ipdb safeguard
1886 "List of regular expressions matching output prompts."
1887 :type
'(repeat string
)
1890 (defcustom python-shell-prompt-regexp
">>> "
1891 "Regular expression matching top level input prompt of Python shell.
1892 It should not contain a caret (^) at the beginning."
1895 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1896 "Regular expression matching block input prompt of Python shell.
1897 It should not contain a caret (^) at the beginning."
1900 (defcustom python-shell-prompt-output-regexp
""
1901 "Regular expression matching output prompt of Python shell.
1902 It should not contain a caret (^) at the beginning."
1905 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1906 "Regular expression matching pdb input prompt of Python shell.
1907 It should not contain a caret (^) at the beginning."
1910 (define-obsolete-variable-alias
1911 'python-shell-enable-font-lock
'python-shell-font-lock-enable
"25.1")
1913 (defcustom python-shell-font-lock-enable t
1914 "Should syntax highlighting be enabled in the Python shell buffer?
1915 Restart the Python shell after changing this variable for it to take effect."
1920 (defcustom python-shell-unbuffered t
1921 "Should shell output be unbuffered?.
1922 When non-nil, this may prevent delayed and missing output in the
1923 Python shell. See commentary for details."
1928 (defcustom python-shell-process-environment nil
1929 "List of environment variables for Python shell.
1930 This variable follows the same rules as `process-environment'
1931 since it merges with it before the process creation routines are
1932 called. When this variable is nil, the Python shell is run with
1933 the default `process-environment'."
1934 :type
'(repeat string
)
1938 (defcustom python-shell-extra-pythonpaths nil
1939 "List of extra pythonpaths for Python shell.
1940 The values of this variable are added to the existing value of
1941 PYTHONPATH in the `process-environment' variable."
1942 :type
'(repeat string
)
1946 (defcustom python-shell-exec-path nil
1947 "List of path to search for binaries.
1948 This variable follows the same rules as `exec-path' since it
1949 merges with it before the process creation routines are called.
1950 When this variable is nil, the Python shell is run with the
1951 default `exec-path'."
1952 :type
'(repeat string
)
1956 (defcustom python-shell-virtualenv-root nil
1957 "Path to virtualenv root.
1958 This variable, when set to a string, makes the values stored in
1959 `python-shell-process-environment' and `python-shell-exec-path'
1960 to be modified properly so shells are started with the specified
1962 :type
'(choice (const nil
) string
)
1966 (define-obsolete-variable-alias
1967 'python-shell-virtualenv-path
'python-shell-virtualenv-root
"25.1")
1969 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1970 python-ffap-setup-code
1971 python-eldoc-setup-code
)
1972 "List of code run by `python-shell-send-setup-codes'."
1973 :type
'(repeat symbol
)
1977 (defcustom python-shell-compilation-regexp-alist
1978 `((,(rx line-start
(1+ (any " \t")) "File \""
1979 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1980 "\", line " (group (1+ digit
)))
1982 (,(rx " in file " (group (1+ not-newline
)) " on line "
1985 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1986 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1988 "`compilation-error-regexp-alist' for inferior Python."
1989 :type
'(alist string
)
1992 (defvar python-shell--prompt-calculated-input-regexp nil
1993 "Calculated input prompt regexp for inferior python shell.
1994 Do not set this variable directly, instead use
1995 `python-shell-prompt-set-calculated-regexps'.")
1997 (defvar python-shell--prompt-calculated-output-regexp nil
1998 "Calculated output prompt regexp for inferior python shell.
1999 Do not set this variable directly, instead use
2000 `python-shell-set-prompt-regexp'.")
2002 (defun python-shell-prompt-detect ()
2003 "Detect prompts for the current `python-shell-interpreter'.
2004 When prompts can be retrieved successfully from the
2005 `python-shell-interpreter' run with
2006 `python-shell-interpreter-interactive-arg', returns a list of
2007 three elements, where the first two are input prompts and the
2008 last one is an output prompt. When no prompts can be detected
2009 and `python-shell-prompt-detect-failure-warning' is non-nil,
2010 shows a warning with instructions to avoid hangs and returns nil.
2011 When `python-shell-prompt-detect-enabled' is nil avoids any
2012 detection and just returns nil."
2013 (when python-shell-prompt-detect-enabled
2014 (let* ((process-environment (python-shell-calculate-process-environment))
2015 (exec-path (python-shell-calculate-exec-path))
2018 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2019 ;; JSON is built manually for compatibility
2020 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2025 ;; TODO: improve error handling by using
2026 ;; `condition-case' and displaying the error message to
2027 ;; the user in the no-prompts warning.
2029 (let ((code-file (python-shell--save-temp-file code
)))
2030 ;; Use `process-file' as it is remote-host friendly.
2032 python-shell-interpreter
2036 python-shell-interpreter-interactive-arg
)
2038 (delete-file code-file
)))
2042 (dolist (line (split-string output
"\n" t
))
2044 ;; Check if current line is a valid JSON array
2045 (and (string= (substring line
0 2) "[\"")
2047 ;; Return prompts as a list, not vector
2048 (append (json-read-from-string line
) nil
)))))
2049 ;; The list must contain 3 strings, where the first
2050 ;; is the input prompt, the second is the block
2051 ;; prompt and the last one is the output prompt. The
2052 ;; input prompt is the only one that can't be empty.
2053 (when (and (= (length res
) 3)
2054 (cl-every #'stringp res
)
2055 (not (string= (car res
) "")))
2056 (throw 'prompts res
))))
2058 (when (and (not prompts
)
2059 python-shell-prompt-detect-failure-warning
)
2061 '(python python-shell-prompt-regexp
)
2064 "Python shell prompts cannot be detected.\n"
2065 "If your emacs session hangs when starting python shells\n"
2066 "recover with `keyboard-quit' and then try fixing the\n"
2067 "interactive flag for your interpreter by adjusting the\n"
2068 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2069 "matching shell prompts in the directory-local friendly vars:\n"
2070 " + `python-shell-prompt-regexp'\n"
2071 " + `python-shell-prompt-block-regexp'\n"
2072 " + `python-shell-prompt-output-regexp'\n"
2073 "Or alternatively in:\n"
2074 " + `python-shell-prompt-input-regexps'\n"
2075 " + `python-shell-prompt-output-regexps'")))
2078 (defun python-shell-prompt-validate-regexps ()
2079 "Validate all user provided regexps for prompts.
2080 Signals `user-error' if any of these vars contain invalid
2081 regexps: `python-shell-prompt-regexp',
2082 `python-shell-prompt-block-regexp',
2083 `python-shell-prompt-pdb-regexp',
2084 `python-shell-prompt-output-regexp',
2085 `python-shell-prompt-input-regexps',
2086 `python-shell-prompt-output-regexps'."
2087 (dolist (symbol (list 'python-shell-prompt-input-regexps
2088 'python-shell-prompt-output-regexps
2089 'python-shell-prompt-regexp
2090 'python-shell-prompt-block-regexp
2091 'python-shell-prompt-pdb-regexp
2092 'python-shell-prompt-output-regexp
))
2093 (dolist (regexp (let ((regexps (symbol-value symbol
)))
2097 (when (not (python-util-valid-regexp-p regexp
))
2098 (user-error "Invalid regexp %s in `%s'"
2101 (defun python-shell-prompt-set-calculated-regexps ()
2102 "Detect and set input and output prompt regexps.
2103 Build and set the values for `python-shell-input-prompt-regexp'
2104 and `python-shell-output-prompt-regexp' using the values from
2105 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2106 `python-shell-prompt-pdb-regexp',
2107 `python-shell-prompt-output-regexp',
2108 `python-shell-prompt-input-regexps',
2109 `python-shell-prompt-output-regexps' and detected prompts from
2110 `python-shell-prompt-detect'."
2111 (when (not (and python-shell--prompt-calculated-input-regexp
2112 python-shell--prompt-calculated-output-regexp
))
2113 (let* ((detected-prompts (python-shell-prompt-detect))
2115 (output-prompts nil
)
2119 (mapconcat #'identity
2122 (let ((length-a (length a
))
2123 (length-b (length b
)))
2124 (if (= length-a length-b
)
2126 (> (length a
) (length b
))))))
2129 ;; Validate ALL regexps
2130 (python-shell-prompt-validate-regexps)
2131 ;; Collect all user defined input prompts
2132 (dolist (prompt (append python-shell-prompt-input-regexps
2133 (list python-shell-prompt-regexp
2134 python-shell-prompt-block-regexp
2135 python-shell-prompt-pdb-regexp
)))
2136 (cl-pushnew prompt input-prompts
:test
#'string
=))
2137 ;; Collect all user defined output prompts
2138 (dolist (prompt (cons python-shell-prompt-output-regexp
2139 python-shell-prompt-output-regexps
))
2140 (cl-pushnew prompt output-prompts
:test
#'string
=))
2141 ;; Collect detected prompts if any
2142 (when detected-prompts
2143 (dolist (prompt (butlast detected-prompts
))
2144 (setq prompt
(regexp-quote prompt
))
2145 (cl-pushnew prompt input-prompts
:test
#'string
=))
2146 (cl-pushnew (regexp-quote
2147 (car (last detected-prompts
)))
2148 output-prompts
:test
#'string
=))
2149 ;; Set input and output prompt regexps from collected prompts
2150 (setq python-shell--prompt-calculated-input-regexp
2151 (funcall build-regexp input-prompts
)
2152 python-shell--prompt-calculated-output-regexp
2153 (funcall build-regexp output-prompts
)))))
2155 (defun python-shell-get-process-name (dedicated)
2156 "Calculate the appropriate process name for inferior Python process.
2157 If DEDICATED is t returns a string with the form
2158 `python-shell-buffer-name'[`buffer-name'] else returns the value
2159 of `python-shell-buffer-name'."
2161 (format "%s[%s]" python-shell-buffer-name
(buffer-name))
2162 python-shell-buffer-name
))
2164 (defun python-shell-internal-get-process-name ()
2165 "Calculate the appropriate process name for Internal Python process.
2166 The name is calculated from `python-shell-global-buffer-name' and
2168 (format "%s[%s]" python-shell-internal-buffer-name
(buffer-name)))
2170 (defun python-shell-calculate-command ()
2171 "Calculate the string used to execute the inferior Python process."
2172 (let ((exec-path (python-shell-calculate-exec-path)))
2173 ;; `exec-path' gets tweaked so that virtualenv's specific
2174 ;; `python-shell-interpreter' absolute path can be found by
2175 ;; `executable-find'.
2177 ;; FIXME: Why executable-find?
2178 (shell-quote-argument
2179 (executable-find python-shell-interpreter
))
2180 python-shell-interpreter-args
)))
2182 (define-obsolete-function-alias
2183 'python-shell-parse-command
2184 #'python-shell-calculate-command
"25.1")
2186 (defun python-shell-calculate-pythonpath ()
2187 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2188 (let ((pythonpath (getenv "PYTHONPATH"))
2189 (extra (mapconcat 'identity
2190 python-shell-extra-pythonpaths
2193 (concat extra path-separator pythonpath
)
2196 (defun python-shell-calculate-process-environment ()
2197 "Calculate process environment given `python-shell-virtualenv-root'."
2198 (let ((process-environment (append
2199 python-shell-process-environment
2200 process-environment nil
))
2201 (virtualenv (if python-shell-virtualenv-root
2202 (directory-file-name python-shell-virtualenv-root
)
2204 (when python-shell-unbuffered
2205 (setenv "PYTHONUNBUFFERED" "1"))
2206 (when python-shell-extra-pythonpaths
2207 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2208 (if (not virtualenv
)
2210 (setenv "PYTHONHOME" nil
)
2211 (setenv "PATH" (format "%s/bin%s%s"
2212 virtualenv path-separator
2213 (or (getenv "PATH") "")))
2214 (setenv "VIRTUAL_ENV" virtualenv
))
2215 process-environment
))
2217 (defun python-shell-calculate-exec-path ()
2218 "Calculate exec path given `python-shell-virtualenv-root'."
2220 ;; Use nil as the tail so that the list is a full copy,
2221 ;; this is a paranoid safeguard for side-effects.
2222 python-shell-exec-path exec-path nil
)))
2223 (if (not python-shell-virtualenv-root
)
2225 (cons (expand-file-name "bin" python-shell-virtualenv-root
)
2228 (defvar python-shell--package-depth
10)
2230 (defun python-shell-package-enable (directory package
)
2231 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2233 (let* ((dir (expand-file-name
2234 (read-directory-name
2236 (file-name-directory
2237 (or (buffer-file-name) default-directory
)))))
2238 (name (completing-read
2240 (python-util-list-packages
2241 dir python-shell--package-depth
))))
2243 (python-shell-send-string
2246 "import os.path;import sys;"
2247 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2248 "__package__ = '''%s''';"
2250 directory package package
)
2251 (python-shell-get-process)))
2253 (defun python-shell-accept-process-output (process &optional timeout regexp
)
2254 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2255 Optional argument TIMEOUT is the timeout argument to
2256 `accept-process-output' calls. Optional argument REGEXP
2257 overrides the regexp to match the end of output, defaults to
2258 `comint-prompt-regexp.'. Returns non-nil when output was
2261 This utility is useful in situations where the output may be
2262 received in chunks, since `accept-process-output' gives no
2263 guarantees they will be grabbed in a single call. An example use
2264 case for this would be the CPython shell start-up, where the
2265 banner and the initial prompt are received separately."
2266 (let ((regexp (or regexp comint-prompt-regexp
)))
2269 (when (not (accept-process-output process timeout
))
2272 regexp
(car (python-util-comint-last-prompt)))
2273 (throw 'found t
))))))
2275 (defun python-shell-comint-end-of-output-p (output)
2276 "Return non-nil if OUTPUT is ends with input prompt."
2278 ;; XXX: It seems on OSX an extra carriage return is attached
2279 ;; at the end of output, this handles that too.
2282 ;; Remove initial caret from calculated regexp
2283 (replace-regexp-in-string
2284 (rx string-start ?^
) ""
2285 python-shell--prompt-calculated-input-regexp
)
2289 (define-obsolete-function-alias
2290 'python-comint-output-filter-function
2291 'ansi-color-filter-apply
2294 (defun python-comint-postoutput-scroll-to-bottom (output)
2295 "Faster version of `comint-postoutput-scroll-to-bottom'.
2296 Avoids `recenter' calls until OUTPUT is completely sent."
2297 (when (and (not (string= "" output
))
2298 (python-shell-comint-end-of-output-p
2299 (ansi-color-filter-apply output
)))
2300 (comint-postoutput-scroll-to-bottom output
))
2303 (defvar python-shell--parent-buffer nil
)
2305 (defmacro python-shell-with-shell-buffer
(&rest body
)
2306 "Execute the forms in BODY with the shell buffer temporarily current.
2307 Signals an error if no shell buffer is available for current buffer."
2308 (declare (indent 0) (debug t
))
2309 (let ((shell-process (make-symbol "shell-process")))
2310 `(let ((,shell-process
(python-shell-get-process-or-error)))
2311 (with-current-buffer (process-buffer ,shell-process
)
2314 (defvar python-shell--font-lock-buffer nil
)
2316 (defun python-shell-font-lock-get-or-create-buffer ()
2317 "Get or create a font-lock buffer for current inferior process."
2318 (python-shell-with-shell-buffer
2319 (if python-shell--font-lock-buffer
2320 python-shell--font-lock-buffer
2322 (process-name (get-buffer-process (current-buffer)))))
2323 (generate-new-buffer
2324 (format " *%s-font-lock*" process-name
))))))
2326 (defun python-shell-font-lock-kill-buffer ()
2327 "Kill the font-lock buffer safely."
2328 (when (and python-shell--font-lock-buffer
2329 (buffer-live-p python-shell--font-lock-buffer
))
2330 (kill-buffer python-shell--font-lock-buffer
)
2331 (when (derived-mode-p 'inferior-python-mode
)
2332 (setq python-shell--font-lock-buffer nil
))))
2334 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2335 "Execute the forms in BODY in the font-lock buffer.
2336 The value returned is the value of the last form in BODY. See
2337 also `with-current-buffer'."
2338 (declare (indent 0) (debug t
))
2339 `(python-shell-with-shell-buffer
2340 (save-current-buffer
2341 (when (not (and python-shell--font-lock-buffer
2342 (get-buffer python-shell--font-lock-buffer
)))
2343 (setq python-shell--font-lock-buffer
2344 (python-shell-font-lock-get-or-create-buffer)))
2345 (set-buffer python-shell--font-lock-buffer
)
2346 (when (not font-lock-mode
)
2348 (set (make-local-variable 'delay-mode-hooks
) t
)
2349 (let ((python-indent-guess-indent-offset nil
))
2350 (when (not (derived-mode-p 'python-mode
))
2354 (defun python-shell-font-lock-cleanup-buffer ()
2355 "Cleanup the font-lock buffer.
2356 Provided as a command because this might be handy if something
2357 goes wrong and syntax highlighting in the shell gets messed up."
2359 (python-shell-with-shell-buffer
2360 (python-shell-font-lock-with-font-lock-buffer
2363 (defun python-shell-font-lock-comint-output-filter-function (output)
2364 "Clean up the font-lock buffer after any OUTPUT."
2365 (if (and (not (string= "" output
))
2366 ;; Is end of output and is not just a prompt.
2368 (python-shell-comint-end-of-output-p
2369 (ansi-color-filter-apply output
))
2371 ;; If output is other than an input prompt then "real" output has
2372 ;; been received and the font-lock buffer must be cleaned up.
2373 (python-shell-font-lock-cleanup-buffer)
2374 ;; Otherwise just add a newline.
2375 (python-shell-font-lock-with-font-lock-buffer
2376 (goto-char (point-max))
2380 (defun python-shell-font-lock-post-command-hook ()
2381 "Fontifies current line in shell buffer."
2382 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2383 (when (and prompt-end
(> (point) prompt-end
)
2384 (process-live-p (get-buffer-process (current-buffer))))
2385 (let* ((input (buffer-substring-no-properties
2386 prompt-end
(point-max)))
2387 (deactivate-mark nil
)
2388 (start-pos prompt-end
)
2389 (buffer-undo-list t
)
2390 (font-lock-buffer-pos nil
)
2392 (python-shell-font-lock-with-font-lock-buffer
2393 (delete-region (line-beginning-position)
2395 (setq font-lock-buffer-pos
(point))
2397 ;; Ensure buffer is fontified, keeping it
2398 ;; compatible with Emacs < 24.4.
2399 (if (fboundp 'font-lock-ensure
)
2400 (funcall 'font-lock-ensure
)
2401 (font-lock-default-fontify-buffer))
2402 (buffer-substring font-lock-buffer-pos
2404 (replacement-length (length replacement
))
2406 ;; Inject text properties to get input fontified.
2407 (while (not (= i replacement-length
))
2408 (let* ((plist (text-properties-at i replacement
))
2409 (next-change (or (next-property-change i replacement
)
2410 replacement-length
))
2411 (plist (let ((face (plist-get plist
'face
)))
2414 ;; Replace FACE text properties with
2415 ;; FONT-LOCK-FACE so input is fontified.
2416 (plist-put plist
'face nil
)
2417 (plist-put plist
'font-lock-face face
)))))
2418 (set-text-properties
2419 (+ start-pos i
) (+ start-pos next-change
) plist
)
2420 (setq i next-change
)))))))
2422 (defun python-shell-font-lock-turn-on (&optional msg
)
2423 "Turn on shell font-lock.
2424 With argument MSG show activation message."
2426 (python-shell-with-shell-buffer
2427 (python-shell-font-lock-kill-buffer)
2428 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2429 (add-hook 'post-command-hook
2430 #'python-shell-font-lock-post-command-hook nil
'local
)
2431 (add-hook 'kill-buffer-hook
2432 #'python-shell-font-lock-kill-buffer nil
'local
)
2433 (add-hook 'comint-output-filter-functions
2434 #'python-shell-font-lock-comint-output-filter-function
2437 (message "Shell font-lock is enabled"))))
2439 (defun python-shell-font-lock-turn-off (&optional msg
)
2440 "Turn off shell font-lock.
2441 With argument MSG show deactivation message."
2443 (python-shell-with-shell-buffer
2444 (python-shell-font-lock-kill-buffer)
2445 (when (python-util-comint-last-prompt)
2446 ;; Cleanup current fontification
2447 (remove-text-properties
2448 (cdr (python-util-comint-last-prompt))
2450 '(face nil font-lock-face nil
)))
2451 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2452 (remove-hook 'post-command-hook
2453 #'python-shell-font-lock-post-command-hook
'local
)
2454 (remove-hook 'kill-buffer-hook
2455 #'python-shell-font-lock-kill-buffer
'local
)
2456 (remove-hook 'comint-output-filter-functions
2457 #'python-shell-font-lock-comint-output-filter-function
2460 (message "Shell font-lock is disabled"))))
2462 (defun python-shell-font-lock-toggle (&optional msg
)
2463 "Toggle font-lock for shell.
2464 With argument MSG show activation/deactivation message."
2466 (python-shell-with-shell-buffer
2467 (set (make-local-variable 'python-shell-font-lock-enable
)
2468 (not python-shell-font-lock-enable
))
2469 (if python-shell-font-lock-enable
2470 (python-shell-font-lock-turn-on msg
)
2471 (python-shell-font-lock-turn-off msg
))
2472 python-shell-font-lock-enable
))
2474 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2475 "Major mode for Python inferior process.
2476 Runs a Python interpreter as a subprocess of Emacs, with Python
2477 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2478 and `python-shell-interpreter-args' control which Python
2479 interpreter is run. Variables
2480 `python-shell-prompt-regexp',
2481 `python-shell-prompt-output-regexp',
2482 `python-shell-prompt-block-regexp',
2483 `python-shell-font-lock-enable',
2484 `python-shell-completion-setup-code',
2485 `python-shell-completion-string-code',
2486 `python-eldoc-setup-code', `python-eldoc-string-code',
2487 `python-ffap-setup-code' and `python-ffap-string-code' can
2488 customize this mode for different Python interpreters.
2490 This mode resets `comint-output-filter-functions' locally, so you
2491 may want to re-add custom functions to it using the
2492 `inferior-python-mode-hook'.
2494 You can also add additional setup code to be run at
2495 initialization of the interpreter via `python-shell-setup-codes'
2498 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2499 (let ((interpreter python-shell-interpreter
)
2500 (args python-shell-interpreter-args
))
2501 (when python-shell--parent-buffer
2502 (python-util-clone-local-variables python-shell--parent-buffer
))
2503 ;; Users can override default values for these vars when calling
2504 ;; `run-python'. This ensures new values let-bound in
2505 ;; `python-shell-make-comint' are locally set.
2506 (set (make-local-variable 'python-shell-interpreter
) interpreter
)
2507 (set (make-local-variable 'python-shell-interpreter-args
) args
))
2508 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2509 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2510 (python-shell-prompt-set-calculated-regexps)
2511 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2512 (set (make-local-variable 'comint-prompt-read-only
) t
)
2513 (setq mode-line-process
'(":%s"))
2514 (set (make-local-variable 'comint-output-filter-functions
)
2515 '(ansi-color-process-output
2516 python-pdbtrack-comint-output-filter-function
2517 python-comint-postoutput-scroll-to-bottom
))
2518 (set (make-local-variable 'compilation-error-regexp-alist
)
2519 python-shell-compilation-regexp-alist
)
2520 (add-hook 'completion-at-point-functions
2521 #'python-shell-completion-at-point nil
'local
)
2522 (define-key inferior-python-mode-map
"\t"
2523 'python-shell-completion-complete-or-indent
)
2524 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2525 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2526 (make-local-variable 'python-shell-internal-last-output
)
2527 (when python-shell-font-lock-enable
2528 (python-shell-font-lock-turn-on))
2529 (compilation-shell-minor-mode 1)
2530 (python-shell-accept-process-output
2531 (get-buffer-process (current-buffer))))
2533 (defun python-shell-make-comint (cmd proc-name
&optional show internal
)
2534 "Create a Python shell comint buffer.
2535 CMD is the Python command to be executed and PROC-NAME is the
2536 process name the comint buffer will get. After the comint buffer
2537 is created the `inferior-python-mode' is activated. When
2538 optional argument SHOW is non-nil the buffer is shown. When
2539 optional argument INTERNAL is non-nil this process is run on a
2540 buffer with a name that starts with a space, following the Emacs
2541 convention for temporary/internal buffers, and also makes sure
2542 the user is not queried for confirmation when the process is
2545 (let* ((proc-buffer-name
2546 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
2547 (process-environment (python-shell-calculate-process-environment))
2548 (exec-path (python-shell-calculate-exec-path)))
2549 (when (not (comint-check-proc proc-buffer-name
))
2550 (let* ((cmdlist (split-string-and-unquote cmd
))
2551 (interpreter (car cmdlist
))
2552 (args (cdr cmdlist
))
2553 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2554 interpreter nil args
))
2555 (python-shell--parent-buffer (current-buffer))
2556 (process (get-buffer-process buffer
))
2557 ;; As the user may have overridden default values for
2558 ;; these vars on `run-python', let-binding them allows
2559 ;; to have the new right values in all setup code
2560 ;; that's is done in `inferior-python-mode', which is
2561 ;; important, especially for prompt detection.
2562 (python-shell-interpreter interpreter
)
2563 (python-shell-interpreter-args
2564 (mapconcat #'identity args
" ")))
2565 (with-current-buffer buffer
2566 (inferior-python-mode))
2567 (when show
(display-buffer buffer
))
2568 (and internal
(set-process-query-on-exit-flag process nil
))))
2572 (defun run-python (&optional cmd dedicated show
)
2573 "Run an inferior Python process.
2575 Argument CMD defaults to `python-shell-calculate-command' return
2576 value. When called interactively with `prefix-arg', it allows
2577 the user to edit such value and choose whether the interpreter
2578 should be DEDICATED for the current buffer. When numeric prefix
2579 arg is other than 0 or 4 do not SHOW.
2581 For a given buffer and same values of DEDICATED, if a process is
2582 already running for it, it will do nothing. This means that if
2583 the current buffer is using a global process, the user is still
2584 able to switch it to use a dedicated one.
2586 Runs the hook `inferior-python-mode-hook' after
2587 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2588 process buffer for a list of commands.)"
2590 (if current-prefix-arg
2592 (read-shell-command "Run Python: " (python-shell-calculate-command))
2593 (y-or-n-p "Make dedicated process? ")
2594 (= (prefix-numeric-value current-prefix-arg
) 4))
2595 (list (python-shell-calculate-command) nil t
)))
2597 (python-shell-make-comint
2598 (or cmd
(python-shell-calculate-command))
2599 (python-shell-get-process-name dedicated
) show
)))
2601 (defun run-python-internal ()
2602 "Run an inferior Internal Python process.
2603 Input and output via buffer named after
2604 `python-shell-internal-buffer-name' and what
2605 `python-shell-internal-get-process-name' returns.
2607 This new kind of shell is intended to be used for generic
2608 communication related to defined configurations; the main
2609 difference with global or dedicated shells is that these ones are
2610 attached to a configuration, not a buffer. This means that can
2611 be used for example to retrieve the sys.path and other stuff,
2612 without messing with user shells. Note that
2613 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2614 are set to nil for these shells, so setup codes are not sent at
2616 (let ((python-shell-font-lock-enable nil
)
2617 (inferior-python-mode-hook nil
))
2619 (python-shell-make-comint
2620 (python-shell-calculate-command)
2621 (python-shell-internal-get-process-name) nil t
))))
2623 (defun python-shell-get-buffer ()
2624 "Return inferior Python buffer for current buffer.
2625 If current buffer is in `inferior-python-mode', return it."
2626 (if (derived-mode-p 'inferior-python-mode
)
2628 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2629 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2630 (global-proc-name (python-shell-get-process-name nil
))
2631 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2632 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2633 (global-running (comint-check-proc global-proc-buffer-name
)))
2634 ;; Always prefer dedicated
2635 (or (and dedicated-running dedicated-proc-buffer-name
)
2636 (and global-running global-proc-buffer-name
)))))
2638 (defun python-shell-get-process ()
2639 "Return inferior Python process for current buffer."
2640 (get-buffer-process (python-shell-get-buffer)))
2642 (defun python-shell-get-process-or-error (&optional interactivep
)
2643 "Return inferior Python process for current buffer or signal error.
2644 When argument INTERACTIVEP is non-nil, use `user-error' instead
2645 of `error' with a user-friendly message."
2646 (or (python-shell-get-process)
2649 "Start a Python process first with `M-x run-python' or `%s'."
2653 #'run-python overriding-local-map t
)))
2655 "No inferior Python process running."))))
2657 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2658 "Get or create an inferior Python process for current buffer and return it.
2659 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2660 are used to start the shell. If those arguments are not
2661 provided, `run-python' is called interactively and the user will
2662 be asked for their values."
2663 (let ((shell-process (python-shell-get-process)))
2664 (when (not shell-process
)
2666 ;; XXX: Refactor code such that calling `run-python'
2667 ;; interactively is not needed anymore.
2668 (call-interactively 'run-python
)
2669 (run-python cmd dedicated show
)))
2670 (or shell-process
(python-shell-get-process))))
2673 #'python-shell-get-or-create-process
2674 "Instead call `python-shell-get-process' and create one if returns nil."
2677 (defvar python-shell-internal-buffer nil
2678 "Current internal shell buffer for the current buffer.
2679 This is really not necessary at all for the code to work but it's
2680 there for compatibility with CEDET.")
2682 (defvar python-shell-internal-last-output nil
2683 "Last output captured by the internal shell.
2684 This is really not necessary at all for the code to work but it's
2685 there for compatibility with CEDET.")
2687 (defun python-shell-internal-get-or-create-process ()
2688 "Get or create an inferior Internal Python process."
2689 (let ((proc-name (python-shell-internal-get-process-name)))
2690 (if (process-live-p proc-name
)
2691 (get-process proc-name
)
2692 (run-python-internal))))
2694 (define-obsolete-function-alias
2695 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2697 (define-obsolete-variable-alias
2698 'python-buffer
'python-shell-internal-buffer
"24.3")
2700 (define-obsolete-variable-alias
2701 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2703 (defun python-shell--save-temp-file (string)
2704 (let* ((temporary-file-directory
2705 (if (file-remote-p default-directory
)
2706 (concat (file-remote-p default-directory
) "/tmp")
2707 temporary-file-directory
))
2708 (temp-file-name (make-temp-file "py"))
2709 (coding-system-for-write (python-info-encoding)))
2710 (with-temp-file temp-file-name
2712 (delete-trailing-whitespace))
2715 (defun python-shell-send-string (string &optional process msg
)
2716 "Send STRING to inferior Python PROCESS.
2717 When optional argument MSG is non-nil, forces display of a
2718 user-friendly message if there's no process running; defaults to
2719 t when called interactively."
2721 (list (read-string "Python command: ") nil t
))
2722 (let ((process (or process
(python-shell-get-process-or-error msg
))))
2723 (if (string-match ".\n+." string
) ;Multiline.
2724 (let* ((temp-file-name (python-shell--save-temp-file string
))
2725 (file-name (or (buffer-file-name) temp-file-name
)))
2726 (python-shell-send-file file-name process temp-file-name t
))
2727 (comint-send-string process string
)
2728 (when (or (not (string-match "\n\\'" string
))
2729 (string-match "\n[ \t].*\n?\\'" string
))
2730 (comint-send-string process
"\n")))))
2732 (defvar python-shell-output-filter-in-progress nil
)
2733 (defvar python-shell-output-filter-buffer nil
)
2735 (defun python-shell-output-filter (string)
2736 "Filter used in `python-shell-send-string-no-output' to grab output.
2737 STRING is the output received to this point from the process.
2738 This filter saves received output from the process in
2739 `python-shell-output-filter-buffer' and stops receiving it after
2740 detecting a prompt at the end of the buffer."
2742 string
(ansi-color-filter-apply string
)
2743 python-shell-output-filter-buffer
2744 (concat python-shell-output-filter-buffer string
))
2745 (when (python-shell-comint-end-of-output-p
2746 python-shell-output-filter-buffer
)
2747 ;; Output ends when `python-shell-output-filter-buffer' contains
2748 ;; the prompt attached at the end of it.
2749 (setq python-shell-output-filter-in-progress nil
2750 python-shell-output-filter-buffer
2751 (substring python-shell-output-filter-buffer
2752 0 (match-beginning 0)))
2754 python-shell--prompt-calculated-output-regexp
2755 python-shell-output-filter-buffer
)
2756 ;; Some shells, like IPython might append a prompt before the
2757 ;; output, clean that.
2758 (setq python-shell-output-filter-buffer
2759 (substring python-shell-output-filter-buffer
(match-end 0)))))
2762 (defun python-shell-send-string-no-output (string &optional process
)
2763 "Send STRING to PROCESS and inhibit output.
2765 (let ((process (or process
(python-shell-get-process-or-error)))
2766 (comint-preoutput-filter-functions
2767 '(python-shell-output-filter))
2768 (python-shell-output-filter-in-progress t
)
2772 (python-shell-send-string string process
)
2773 (while python-shell-output-filter-in-progress
2774 ;; `python-shell-output-filter' takes care of setting
2775 ;; `python-shell-output-filter-in-progress' to NIL after it
2776 ;; detects end of output.
2777 (accept-process-output process
))
2779 python-shell-output-filter-buffer
2780 (setq python-shell-output-filter-buffer nil
)))
2781 (with-current-buffer (process-buffer process
)
2782 (comint-interrupt-subjob)))))
2784 (defun python-shell-internal-send-string (string)
2785 "Send STRING to the Internal Python interpreter.
2786 Returns the output. See `python-shell-send-string-no-output'."
2787 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2788 ;; updated to support this new mode.
2789 (setq python-shell-internal-last-output
2790 (python-shell-send-string-no-output
2791 ;; Makes this function compatible with the old
2792 ;; python-send-receive. (At least for CEDET).
2793 (replace-regexp-in-string "_emacs_out +" "" string
)
2794 (python-shell-internal-get-or-create-process))))
2796 (define-obsolete-function-alias
2797 'python-send-receive
'python-shell-internal-send-string
"24.3")
2799 (define-obsolete-function-alias
2800 'python-send-string
'python-shell-internal-send-string
"24.3")
2802 (defun python-shell-buffer-substring (start end
&optional nomain
)
2803 "Send buffer substring from START to END formatted for shell.
2804 This is a wrapper over `buffer-substring' that takes care of
2805 different transformations for the code sent to be evaluated in
2807 1. When optional argument NOMAIN is non-nil everything under an
2808 \"if __name__ == '__main__'\" block will be removed.
2809 2. When a subregion of the buffer is sent, it takes care of
2810 appending extra empty lines so tracebacks are correct.
2811 3. When the region sent is a substring of the current buffer, a
2812 coding cookie is added.
2813 4. Wraps indented regions under an \"if True:\" block so the
2814 interpreter evaluates them correctly."
2815 (let* ((substring (buffer-substring-no-properties start end
))
2816 (starts-at-point-min-p (save-restriction
2818 (= (point-min) start
)))
2819 (encoding (python-info-encoding))
2820 (fillstr (when (not starts-at-point-min-p
)
2822 (format "# -*- coding: %s -*-\n" encoding
)
2824 ;; Subtract 2 because of the coding cookie.
2825 (- (line-number-at-pos start
) 2) ?
\n))))
2826 (toplevel-block-p (save-excursion
2828 (or (zerop (line-number-at-pos start
))
2830 (python-util-forward-comment 1)
2831 (zerop (current-indentation)))))))
2834 (if fillstr
(insert fillstr
))
2836 (goto-char (point-min))
2837 (when (not toplevel-block-p
)
2839 (delete-region (point) (line-end-position)))
2841 (let* ((if-name-main-start-end
2844 (when (python-nav-if-name-main)
2846 (progn (python-nav-forward-sexp-safe)
2847 ;; Include ending newline
2850 ;; Oh destructuring bind, how I miss you.
2851 (if-name-main-start (car if-name-main-start-end
))
2852 (if-name-main-end (cdr if-name-main-start-end
))
2853 (fillstr (make-string
2854 (- (line-number-at-pos if-name-main-end
)
2855 (line-number-at-pos if-name-main-start
)) ?
\n)))
2856 (when if-name-main-start-end
2857 (goto-char if-name-main-start
)
2858 (delete-region if-name-main-start if-name-main-end
)
2860 ;; Ensure there's only one coding cookie in the generated string.
2861 (goto-char (point-min))
2862 (when (looking-at-p (python-rx coding-cookie
))
2864 (when (looking-at-p (python-rx coding-cookie
))
2866 (line-beginning-position) (line-end-position))))
2867 (buffer-substring-no-properties (point-min) (point-max)))))
2869 (defun python-shell-send-region (start end
&optional send-main msg
)
2870 "Send the region delimited by START and END to inferior Python process.
2871 When optional argument SEND-MAIN is non-nil, allow execution of
2872 code inside blocks delimited by \"if __name__== '__main__':\".
2873 When called interactively SEND-MAIN defaults to nil, unless it's
2874 called with prefix argument. When optional argument MSG is
2875 non-nil, forces display of a user-friendly message if there's no
2876 process running; defaults to t when called interactively."
2878 (list (region-beginning) (region-end) current-prefix-arg t
))
2879 (let* ((string (python-shell-buffer-substring start end
(not send-main
)))
2880 (process (python-shell-get-process-or-error msg
))
2881 (original-string (buffer-substring-no-properties start end
))
2882 (_ (string-match "\\`\n*\\(.*\\)" original-string
)))
2883 (message "Sent: %s..." (match-string 1 original-string
))
2884 (python-shell-send-string string process
)))
2886 (defun python-shell-send-buffer (&optional send-main msg
)
2887 "Send the entire buffer to inferior Python process.
2888 When optional argument SEND-MAIN is non-nil, allow execution of
2889 code inside blocks delimited by \"if __name__== '__main__':\".
2890 When called interactively SEND-MAIN defaults to nil, unless it's
2891 called with prefix argument. When optional argument MSG is
2892 non-nil, forces display of a user-friendly message if there's no
2893 process running; defaults to t when called interactively."
2894 (interactive (list current-prefix-arg t
))
2897 (python-shell-send-region (point-min) (point-max) send-main msg
)))
2899 (defun python-shell-send-defun (&optional arg msg
)
2900 "Send the current defun to inferior Python process.
2901 When argument ARG is non-nil do not include decorators. When
2902 optional argument MSG is non-nil, forces display of a
2903 user-friendly message if there's no process running; defaults to
2904 t when called interactively."
2905 (interactive (list current-prefix-arg t
))
2907 (python-shell-send-region
2910 (while (and (or (python-nav-beginning-of-defun)
2911 (beginning-of-line 1))
2912 (> (current-indentation) 0)))
2914 (while (and (forward-line -
1)
2915 (looking-at (python-rx decorator
))))
2919 (or (python-nav-end-of-defun)
2925 (defun python-shell-send-file (file-name &optional process temp-file-name
2927 "Send FILE-NAME to inferior Python PROCESS.
2928 If TEMP-FILE-NAME is passed then that file is used for processing
2929 instead, while internally the shell will continue to use
2930 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
2931 TEMP-FILE-NAME is deleted after evaluation is performed. When
2932 optional argument MSG is non-nil, forces display of a
2933 user-friendly message if there's no process running; defaults to
2934 t when called interactively."
2937 (read-file-name "File to send: ") ; file-name
2939 nil
; temp-file-name
2942 (let* ((process (or process
(python-shell-get-process-or-error msg
)))
2943 (encoding (with-temp-buffer
2944 (insert-file-contents
2945 (or temp-file-name file-name
))
2946 (python-info-encoding)))
2947 (file-name (expand-file-name
2948 (or (file-remote-p file-name
'localname
)
2950 (temp-file-name (when temp-file-name
2952 (or (file-remote-p temp-file-name
'localname
)
2954 (python-shell-send-string
2957 "import codecs, os;"
2958 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
2959 "__code = __pyfile.read().encode('''%s''');"
2961 (when (and delete temp-file-name
)
2962 (format "os.remove('''%s''');" temp-file-name
))
2963 "exec(compile(__code, '''%s''', 'exec'));")
2964 (or temp-file-name file-name
) encoding encoding file-name
)
2967 (defun python-shell-switch-to-shell (&optional msg
)
2968 "Switch to inferior Python process buffer.
2969 When optional argument MSG is non-nil, forces display of a
2970 user-friendly message if there's no process running; defaults to
2971 t when called interactively."
2974 (process-buffer (python-shell-get-process-or-error msg
)) nil t
))
2976 (defun python-shell-send-setup-code ()
2977 "Send all setup code for shell.
2978 This function takes the list of setup code to send from the
2979 `python-shell-setup-codes' list."
2980 (let ((process (python-shell-get-process))
2984 (cond ((stringp elt
) elt
)
2985 ((symbolp elt
) (symbol-value elt
))
2987 python-shell-setup-codes
2989 "\n\nprint ('python.el: sent setup code')")))
2990 (python-shell-send-string code process
)
2991 (python-shell-accept-process-output process
)))
2993 (add-hook 'inferior-python-mode-hook
2994 #'python-shell-send-setup-code
)
2997 ;;; Shell completion
2999 (defcustom python-shell-completion-setup-code
3003 def __PYTHON_EL_get_completions(text):
3006 def __PYTHON_EL_get_completions(text):
3011 import builtins as __builtin__
3012 builtins = dir(__builtin__)
3014 is_ipython = ('__IPYTHON__' in builtins or
3015 '__IPYTHON__active' in builtins)
3016 splits = text.split()
3017 is_module = splits and splits[0] in ('from', 'import')
3019 if is_ipython and is_module:
3020 from IPython.core.completerlib import module_completion
3021 completions = module_completion(text.strip())
3022 elif is_ipython and '__IP' in builtins:
3023 completions = __IP.complete(text)
3024 elif is_ipython and 'get_ipython' in builtins:
3025 completions = get_ipython().Completer.all_completions(text)
3027 # Try to reuse current completer.
3028 completer = readline.get_completer()
3030 # importing rlcompleter sets the completer, use it as a
3031 # last resort to avoid breaking customizations.
3033 completer = readline.get_completer()
3036 completion = completer(text, i)
3040 completions.append(completion)
3044 "Code used to setup completion in inferior Python processes."
3048 (defcustom python-shell-completion-string-code
3049 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3050 "Python code used to get a string of completions separated by semicolons.
3051 The string passed to the function is the current python name or
3052 the full statement in the case of imports."
3056 (define-obsolete-variable-alias
3057 'python-shell-completion-module-string-code
3058 'python-shell-completion-string-code
3060 "Completion string code must also autocomplete modules.")
3062 (define-obsolete-variable-alias
3063 'python-shell-completion-pdb-string-code
3064 'python-shell-completion-string-code
3066 "Completion string code must work for (i)pdb.")
3068 (defcustom python-shell-completion-native-disabled-interpreters
3069 ;; PyPy's readline cannot handle some escape sequences yet.
3071 "List of disabled interpreters.
3072 When a match is found, native completion is disabled."
3073 :type
'(repeat string
))
3075 (defcustom python-shell-completion-native-enable t
3076 "Enable readline based native completion."
3079 (defcustom python-shell-completion-native-output-timeout
5.0
3080 "Time in seconds to wait for completion output before giving up."
3083 (defcustom python-shell-completion-native-try-output-timeout
1.0
3084 "Time in seconds to wait for *trying* native completion output."
3087 (defvar python-shell-completion-native-redirect-buffer
3088 " *Python completions redirect*"
3089 "Buffer to be used to redirect output of readline commands.")
3091 (defun python-shell-completion-native-interpreter-disabled-p ()
3092 "Return non-nil if interpreter has native completion disabled."
3093 (when python-shell-completion-native-disabled-interpreters
3095 (regexp-opt python-shell-completion-native-disabled-interpreters
)
3096 (file-name-nondirectory python-shell-interpreter
))))
3098 (defun python-shell-completion-native-try ()
3099 "Return non-nil if can trigger native completion."
3100 (let ((python-shell-completion-native-enable t
)
3101 (python-shell-completion-native-output-timeout
3102 python-shell-completion-native-try-output-timeout
))
3103 (python-shell-completion-native-get-completions
3104 (get-buffer-process (current-buffer))
3107 (defun python-shell-completion-native-setup ()
3108 "Try to setup native completion, return non-nil on success."
3109 (let ((process (python-shell-get-process)))
3110 (python-shell-send-string "
3111 def __PYTHON_EL_native_completion_setup():
3118 import builtins as __builtin__
3119 builtins = dir(__builtin__)
3120 is_ipython = ('__IPYTHON__' in builtins or
3121 '__IPYTHON__active' in builtins)
3122 class __PYTHON_EL_Completer:
3123 PYTHON_EL_WRAPPED = True
3124 def __init__(self, completer):
3125 self.completer = completer
3126 self.last_completion = None
3127 def __call__(self, text, state):
3129 # The first completion is always a dummy completion. This
3130 # ensures proper output for sole completions and a current
3131 # input safeguard when no completions are available.
3132 self.last_completion = None
3133 completion = '0__dummy_completion__'
3135 completion = self.completer(text, state - 1)
3138 # When no completions are available, two non-sharing
3139 # prefix strings are returned just to ensure output
3140 # while preventing changes to current input.
3141 completion = '1__dummy_completion__'
3142 elif self.last_completion != '~~~~__dummy_completion__':
3143 # This marks the end of output.
3144 completion = '~~~~__dummy_completion__'
3145 elif completion.endswith('('):
3146 # Remove parens on callables as it breaks completion on
3147 # arguments (e.g. str(Ari<tab>)).
3148 completion = completion[:-1]
3149 self.last_completion = completion
3151 completer = readline.get_completer()
3153 # Used as last resort to avoid breaking customizations.
3155 completer = readline.get_completer()
3156 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3157 # Wrap the existing completer function only once.
3158 new_completer = __PYTHON_EL_Completer(completer)
3160 readline.set_completer(new_completer)
3162 # IPython hacks readline such that `readline.set_completer`
3163 # won't work. This workaround injects the new completer
3164 # function into the existing instance directly.
3165 instance = getattr(completer, 'im_self', completer.__self__)
3166 instance.rlcomplete = new_completer
3167 if readline.__doc__ and 'libedit' in readline.__doc__:
3168 readline.parse_and_bind('bind ^I rl_complete')
3170 readline.parse_and_bind('tab: complete')
3171 # Require just one tab to send output.
3172 readline.parse_and_bind('set show-all-if-ambiguous on')
3173 print ('python.el: readline is available')
3175 print ('python.el: readline not available')
3176 __PYTHON_EL_native_completion_setup()"
3178 (python-shell-accept-process-output process
)
3179 (when (save-excursion
3181 (regexp-quote "python.el: readline is available") nil t
1))
3182 (python-shell-completion-native-try))))
3184 (defun python-shell-completion-native-turn-off (&optional msg
)
3185 "Turn off shell native completions.
3186 With argument MSG show deactivation message."
3188 (python-shell-with-shell-buffer
3189 (set (make-local-variable 'python-shell-completion-native-enable
) nil
)
3191 (message "Shell native completion is disabled, using fallback"))))
3193 (defun python-shell-completion-native-turn-on (&optional msg
)
3194 "Turn on shell native completions.
3195 With argument MSG show deactivation message."
3197 (python-shell-with-shell-buffer
3198 (set (make-local-variable 'python-shell-completion-native-enable
) t
)
3199 (python-shell-completion-native-turn-on-maybe msg
)))
3201 (defun python-shell-completion-native-turn-on-maybe (&optional msg
)
3202 "Turn on native completions if enabled and available.
3203 With argument MSG show activation/deactivation message."
3205 (python-shell-with-shell-buffer
3206 (when python-shell-completion-native-enable
3208 ((python-shell-completion-native-interpreter-disabled-p)
3209 (python-shell-completion-native-turn-off msg
))
3210 ((python-shell-completion-native-setup)
3212 (message "Shell native completion is enabled.")))
3214 '(python python-shell-completion-native-turn-on-maybe
)
3217 "Your `python-shell-interpreter' doesn't seem to "
3218 "support readline, yet `python-shell-completion-native' "
3219 (format "was `t' and %S is not part of the "
3220 (file-name-nondirectory python-shell-interpreter
))
3221 "`python-shell-completion-native-disabled-interpreters' "
3222 "list. Native completions have been disabled locally. "))
3223 (python-shell-completion-native-turn-off msg
))))))
3225 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3226 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3227 (python-shell-completion-native-turn-on-maybe t
))
3229 (add-hook 'inferior-python-mode-hook
3230 #'python-shell-completion-native-turn-on-maybe-with-msg
)
3232 (defun python-shell-completion-native-toggle (&optional msg
)
3233 "Toggle shell native completion.
3234 With argument MSG show activation/deactivation message."
3236 (python-shell-with-shell-buffer
3237 (if python-shell-completion-native-enable
3238 (python-shell-completion-native-turn-off msg
)
3239 (python-shell-completion-native-turn-on msg
))
3240 python-shell-completion-native-enable
))
3242 (defun python-shell-completion-native-get-completions (process import input
)
3243 "Get completions using native readline for PROCESS.
3244 When IMPORT is non-nil takes precedence over INPUT for
3246 (with-current-buffer (process-buffer process
)
3247 (when (and python-shell-completion-native-enable
3248 (python-util-comint-last-prompt)
3249 (>= (point) (cdr (python-util-comint-last-prompt))))
3250 (let* ((input (or import input
))
3251 (original-filter-fn (process-filter process
))
3252 (redirect-buffer (get-buffer-create
3253 python-shell-completion-native-redirect-buffer
))
3254 (separators (python-rx (or whitespace open-paren close-paren
)))
3256 (new-input (concat input trigger
))
3259 (+ (- (point-max) (comint-bol)) (length new-input
))))
3260 (delete-line-command (make-string input-length ?
\b))
3261 (input-to-send (concat new-input delete-line-command
)))
3262 ;; Ensure restoring the process filter, even if the user quits
3263 ;; or there's some other error.
3265 (with-current-buffer redirect-buffer
3266 ;; Cleanup the redirect buffer
3267 (delete-region (point-min) (point-max))
3268 ;; Mimic `comint-redirect-send-command', unfortunately it
3269 ;; can't be used here because it expects a newline in the
3270 ;; command and that's exactly what we are trying to avoid.
3271 (let ((comint-redirect-echo-input nil
)
3272 (comint-redirect-verbose nil
)
3273 (comint-redirect-perform-sanity-check nil
)
3274 (comint-redirect-insert-matching-regexp nil
)
3275 ;; Feed it some regex that will never match.
3276 (comint-redirect-finished-regexp "^\\'$")
3277 (comint-redirect-output-buffer redirect-buffer
)
3278 (current-time (float-time)))
3279 ;; Compatibility with Emacs 24.x. Comint changed and
3280 ;; now `comint-redirect-filter' gets 3 args. This
3281 ;; checks which version of `comint-redirect-filter' is
3282 ;; in use based on its args and uses `apply-partially'
3283 ;; to make it up for the 3 args case.
3285 (help-function-arglist 'comint-redirect-filter
)) 3)
3287 process
(apply-partially
3288 #'comint-redirect-filter original-filter-fn
))
3289 (set-process-filter process
#'comint-redirect-filter
))
3290 (process-send-string process input-to-send
)
3291 ;; Grab output until our dummy completion used as
3292 ;; output end marker is found. Output is accepted
3293 ;; *very* quickly to keep the shell super-responsive.
3294 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t
))
3295 (< (- current-time
(float-time))
3296 python-shell-completion-native-output-timeout
))
3297 (accept-process-output process
0.01))
3298 (cl-remove-duplicates
3301 (string-match "__dummy_completion__" c
))
3303 (buffer-substring-no-properties
3304 (point-min) (point-max))
3307 (set-process-filter process original-filter-fn
))))))
3309 (defun python-shell-completion-get-completions (process import input
)
3310 "Do completion at point using PROCESS for IMPORT or INPUT.
3311 When IMPORT is non-nil takes precedence over INPUT for
3313 (with-current-buffer (process-buffer process
)
3315 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3316 (buffer-substring-no-properties
3317 (car prompt-boundaries
) (cdr prompt-boundaries
))))
3319 ;; Check whether a prompt matches a pdb string, an import
3320 ;; statement or just the standard prompt and use the
3321 ;; correct python-shell-completion-*-code string
3322 (cond ((and (string-match
3323 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
3324 ;; Since there are no guarantees the user will remain
3325 ;; in the same context where completion code was sent
3326 ;; (e.g. user steps into a function), safeguard
3327 ;; resending completion setup continuously.
3328 (concat python-shell-completion-setup-code
3329 "\nprint (" python-shell-completion-string-code
")"))
3331 python-shell--prompt-calculated-input-regexp prompt
)
3332 python-shell-completion-string-code
)
3334 (subject (or import input
)))
3335 (and completion-code
3336 (> (length input
) 0)
3338 (python-util-strip-string
3339 (python-shell-send-string-no-output
3340 (format completion-code subject
) process
))))
3341 (and (> (length completions
) 2)
3342 (split-string completions
3343 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
3345 (defun python-shell-completion-at-point (&optional process
)
3346 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3347 Optional argument PROCESS forces completions to be retrieved
3348 using that one instead of current buffer's process."
3349 (setq process
(or process
(get-buffer-process (current-buffer))))
3350 (let* ((line-start (if (derived-mode-p 'inferior-python-mode
)
3351 ;; Working on a shell buffer: use prompt end.
3352 (cdr (python-util-comint-last-prompt))
3353 (line-beginning-position)))
3355 (when (string-match-p
3356 (rx (* space
) word-start
(or "from" "import") word-end space
)
3357 (buffer-substring-no-properties line-start
(point)))
3358 (buffer-substring-no-properties line-start
(point))))
3361 (if (not (re-search-backward
3363 (or whitespace open-paren close-paren string-delimiter
))
3367 (forward-char (length (match-string-no-properties 0)))
3371 (if python-shell-completion-native-enable
3372 #'python-shell-completion-native-get-completions
3373 #'python-shell-completion-get-completions
)))
3375 (completion-table-dynamic
3378 process import-statement
)))))
3380 (define-obsolete-function-alias
3381 'python-shell-completion-complete-at-point
3382 'python-shell-completion-at-point
3385 (defun python-shell-completion-complete-or-indent ()
3386 "Complete or indent depending on the context.
3387 If content before pointer is all whitespace, indent.
3388 If not try to complete."
3390 (if (string-match "^[[:space:]]*$"
3391 (buffer-substring (comint-line-beginning-position)
3393 (indent-for-tab-command)
3394 (completion-at-point)))
3397 ;;; PDB Track integration
3399 (defcustom python-pdbtrack-activate t
3400 "Non-nil makes Python shell enable pdbtracking."
3405 (defcustom python-pdbtrack-stacktrace-info-regexp
3406 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3407 "Regular expression matching stacktrace information.
3408 Used to extract the current line and module being inspected."
3413 (defvar python-pdbtrack-tracked-buffer nil
3414 "Variable containing the value of the current tracked buffer.
3415 Never set this variable directly, use
3416 `python-pdbtrack-set-tracked-buffer' instead.")
3418 (defvar python-pdbtrack-buffers-to-kill nil
3419 "List of buffers to be deleted after tracking finishes.")
3421 (defun python-pdbtrack-set-tracked-buffer (file-name)
3422 "Set the buffer for FILE-NAME as the tracked buffer.
3423 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3424 Returns the tracked buffer."
3425 (let ((file-buffer (get-file-buffer
3426 (concat (file-remote-p default-directory
)
3429 (setq python-pdbtrack-tracked-buffer file-buffer
)
3430 (setq file-buffer
(find-file-noselect file-name
))
3431 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3432 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3435 (defun python-pdbtrack-comint-output-filter-function (output)
3436 "Move overlay arrow to current pdb line in tracked buffer.
3437 Argument OUTPUT is a string with the output from the comint process."
3438 (when (and python-pdbtrack-activate
(not (string= output
"")))
3439 (let* ((full-output (ansi-color-filter-apply
3440 (buffer-substring comint-last-input-end
(point-max))))
3444 (insert full-output
)
3445 ;; When the debugger encounters a pdb.set_trace()
3446 ;; command, it prints a single stack frame. Sometimes
3447 ;; it prints a bit of extra information about the
3448 ;; arguments of the present function. When ipdb
3449 ;; encounters an exception, it prints the _entire_ stack
3450 ;; trace. To handle all of these cases, we want to find
3451 ;; the _last_ stack frame printed in the most recent
3452 ;; batch of output, then jump to the corresponding
3453 ;; file/line number.
3454 (goto-char (point-max))
3455 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3456 (setq line-number
(string-to-number
3457 (match-string-no-properties 2)))
3458 (match-string-no-properties 1)))))
3459 (if (and file-name line-number
)
3460 (let* ((tracked-buffer
3461 (python-pdbtrack-set-tracked-buffer file-name
))
3462 (shell-buffer (current-buffer))
3463 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3464 (tracked-buffer-line-pos))
3465 (with-current-buffer tracked-buffer
3466 (set (make-local-variable 'overlay-arrow-string
) "=>")
3467 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3468 (setq tracked-buffer-line-pos
(progn
3469 (goto-char (point-min))
3470 (forward-line (1- line-number
))
3472 (when tracked-buffer-window
3474 tracked-buffer-window tracked-buffer-line-pos
))
3475 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3476 (pop-to-buffer tracked-buffer
)
3477 (switch-to-buffer-other-window shell-buffer
))
3478 (when python-pdbtrack-tracked-buffer
3479 (with-current-buffer python-pdbtrack-tracked-buffer
3480 (set-marker overlay-arrow-position nil
))
3481 (mapc #'(lambda (buffer)
3482 (ignore-errors (kill-buffer buffer
)))
3483 python-pdbtrack-buffers-to-kill
)
3484 (setq python-pdbtrack-tracked-buffer nil
3485 python-pdbtrack-buffers-to-kill nil
)))))
3489 ;;; Symbol completion
3491 (defun python-completion-at-point ()
3492 "Function for `completion-at-point-functions' in `python-mode'.
3493 For this to work as best as possible you should call
3494 `python-shell-send-buffer' from time to time so context in
3495 inferior Python process is updated properly."
3496 (let ((process (python-shell-get-process)))
3498 (python-shell-completion-at-point process
))))
3500 (define-obsolete-function-alias
3501 'python-completion-complete-at-point
3502 'python-completion-at-point
3508 (defcustom python-fill-comment-function
'python-fill-comment
3509 "Function to fill comments.
3510 This is the function used by `python-fill-paragraph' to
3515 (defcustom python-fill-string-function
'python-fill-string
3516 "Function to fill strings.
3517 This is the function used by `python-fill-paragraph' to
3522 (defcustom python-fill-decorator-function
'python-fill-decorator
3523 "Function to fill decorators.
3524 This is the function used by `python-fill-paragraph' to
3529 (defcustom python-fill-paren-function
'python-fill-paren
3530 "Function to fill parens.
3531 This is the function used by `python-fill-paragraph' to
3536 (defcustom python-fill-docstring-style
'pep-257
3537 "Style used to fill docstrings.
3538 This affects `python-fill-string' behavior with regards to
3539 triple quotes positioning.
3541 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3542 `symmetric', and nil. A value of nil won't care about quotes
3543 position and will treat docstrings a normal string, any other
3544 value may result in one of the following docstring styles:
3549 Process foo, return bar.
3553 Process foo, return bar.
3555 If processing fails throw ProcessingError.
3560 \"\"\"Process foo, return bar.\"\"\"
3563 Process foo, return bar.
3565 If processing fails throw ProcessingError.
3571 \"\"\"Process foo, return bar.\"\"\"
3573 \"\"\"Process foo, return bar.
3575 If processing fails throw ProcessingError.
3581 \"\"\"Process foo, return bar.\"\"\"
3583 \"\"\"Process foo, return bar.
3585 If processing fails throw ProcessingError.
3590 \"\"\"Process foo, return bar.\"\"\"
3593 Process foo, return bar.
3595 If processing fails throw ProcessingError.
3598 (const :tag
"Don't format docstrings" nil
)
3599 (const :tag
"Django's coding standards style." django
)
3600 (const :tag
"One newline and start and Two at end style." onetwo
)
3601 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3602 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3603 (const :tag
"Symmetric style." symmetric
))
3606 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3608 (defun python-fill-paragraph (&optional justify
)
3609 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3610 If any of the current line is in or at the end of a multi-line string,
3611 fill the string or the paragraph of it that point is in, preserving
3612 the string's indentation.
3613 Optional argument JUSTIFY defines if the paragraph should be justified."
3618 ((python-syntax-context 'comment
)
3619 (funcall python-fill-comment-function justify
))
3620 ;; Strings/Docstrings
3621 ((save-excursion (or (python-syntax-context 'string
)
3622 (equal (string-to-syntax "|")
3623 (syntax-after (point)))))
3624 (funcall python-fill-string-function justify
))
3626 ((equal (char-after (save-excursion
3627 (python-nav-beginning-of-statement))) ?
@)
3628 (funcall python-fill-decorator-function justify
))
3630 ((or (python-syntax-context 'paren
)
3631 (looking-at (python-rx open-paren
))
3633 (skip-syntax-forward "^(" (line-end-position))
3634 (looking-at (python-rx open-paren
))))
3635 (funcall python-fill-paren-function justify
))
3638 (defun python-fill-comment (&optional justify
)
3639 "Comment fill function for `python-fill-paragraph'.
3640 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3641 (fill-comment-paragraph justify
))
3643 (defun python-fill-string (&optional justify
)
3644 "String fill function for `python-fill-paragraph'.
3645 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3646 (let* ((str-start-pos
3649 (or (python-syntax-context 'string
)
3650 (and (equal (string-to-syntax "|")
3651 (syntax-after (point)))
3653 (num-quotes (python-syntax-count-quotes
3654 (char-after str-start-pos
) str-start-pos
))
3657 (goto-char (+ str-start-pos num-quotes
))
3658 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3659 (goto-char (point-max)))
3662 ;; Docstring styles may vary for oneliners and multi-liners.
3663 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3665 (pcase python-fill-docstring-style
3666 ;; delimiters-style is a cons cell with the form
3667 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3668 ;; is NIL means to not add any newlines for start or end
3669 ;; of docstring. See `python-fill-docstring-style' for a
3670 ;; graphic idea of each style.
3671 (`django
(cons 1 1))
3672 (`onetwo
(and multi-line-p
(cons 1 2)))
3673 (`pep-257
(and multi-line-p
(cons nil
2)))
3674 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3675 (`symmetric
(and multi-line-p
(cons 1 1)))))
3676 (fill-paragraph-function))
3678 (narrow-to-region str-start-pos str-end-pos
)
3679 (fill-paragraph justify
))
3681 (when (and (python-info-docstring-p) python-fill-docstring-style
)
3682 ;; Add the number of newlines indicated by the selected style
3683 ;; at the start of the docstring.
3684 (goto-char (+ str-start-pos num-quotes
))
3685 (delete-region (point) (progn
3686 (skip-syntax-forward "> ")
3688 (and (car delimiters-style
)
3689 (or (newline (car delimiters-style
)) t
)
3690 ;; Indent only if a newline is added.
3691 (indent-according-to-mode))
3692 ;; Add the number of newlines indicated by the selected style
3693 ;; at the end of the docstring.
3694 (goto-char (if (not (= str-end-pos
(point-max)))
3695 (- str-end-pos num-quotes
)
3697 (delete-region (point) (progn
3698 (skip-syntax-backward "> ")
3700 (and (cdr delimiters-style
)
3701 ;; Add newlines only if string ends.
3702 (not (= str-end-pos
(point-max)))
3703 (or (newline (cdr delimiters-style
)) t
)
3704 ;; Again indent only if a newline is added.
3705 (indent-according-to-mode))))) t
)
3707 (defun python-fill-decorator (&optional _justify
)
3708 "Decorator fill function for `python-fill-paragraph'.
3709 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3712 (defun python-fill-paren (&optional justify
)
3713 "Paren fill function for `python-fill-paragraph'.
3714 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3716 (narrow-to-region (progn
3717 (while (python-syntax-context 'paren
)
3718 (goto-char (1- (point))))
3719 (line-beginning-position))
3721 (when (not (python-syntax-context 'paren
))
3723 (when (not (python-syntax-context 'paren
))
3724 (skip-syntax-backward "^)")))
3725 (while (and (python-syntax-context 'paren
)
3727 (goto-char (1+ (point))))
3729 (let ((paragraph-start "\f\\|[ \t]*$")
3730 (paragraph-separate ",")
3731 (fill-paragraph-function))
3732 (goto-char (point-min))
3733 (fill-paragraph justify
))
3736 (python-indent-line)
3737 (goto-char (line-end-position))))
3743 (defcustom python-skeleton-autoinsert nil
3744 "Non-nil means template skeletons will be automagically inserted.
3745 This happens when pressing \"if<SPACE>\", for example, to prompt for
3751 (define-obsolete-variable-alias
3752 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3754 (defvar python-skeleton-available
'()
3755 "Internal list of available skeletons.")
3757 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3758 "Abbrev table for Python mode skeletons."
3760 ;; Allow / inside abbrevs.
3761 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3762 ;; Only expand in code.
3763 :enable-function
(lambda ()
3765 (not (python-syntax-comment-or-string-p))
3766 python-skeleton-autoinsert
)))
3768 (defmacro python-skeleton-define
(name doc
&rest skel
)
3769 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3770 The skeleton will be bound to python-skeleton-NAME and will
3771 be added to `python-mode-skeleton-abbrev-table'."
3772 (declare (indent 2))
3773 (let* ((name (symbol-name name
))
3774 (function-name (intern (concat "python-skeleton-" name
))))
3776 (define-abbrev python-mode-skeleton-abbrev-table
3777 ,name
"" ',function-name
:system t
)
3778 (setq python-skeleton-available
3779 (cons ',function-name python-skeleton-available
))
3780 (define-skeleton ,function-name
3782 (format "Insert %s statement." name
))
3785 (define-abbrev-table 'python-mode-abbrev-table
()
3786 "Abbrev table for Python mode."
3787 :parents
(list python-mode-skeleton-abbrev-table
))
3789 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3790 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3791 The skeleton will be bound to python-skeleton-NAME."
3792 (declare (indent 2))
3793 (let* ((name (symbol-name name
))
3794 (function-name (intern (concat "python-skeleton--" name
)))
3796 "Add '%s' clause? " name
)))
3799 `(< ,(format "%s:" name
) \n \n
3801 `(define-skeleton ,function-name
3803 (format "Auxiliary skeleton for %s statement." name
))
3805 (unless (y-or-n-p ,msg
)
3809 (python-define-auxiliary-skeleton else nil
)
3811 (python-define-auxiliary-skeleton except nil
)
3813 (python-define-auxiliary-skeleton finally nil
)
3815 (python-skeleton-define if nil
3819 ("other condition, %s: "
3823 '(python-skeleton--else) | ^
)
3825 (python-skeleton-define while nil
3829 '(python-skeleton--else) | ^
)
3831 (python-skeleton-define for nil
3835 '(python-skeleton--else) | ^
)
3837 (python-skeleton-define import nil
3838 "Import from module: "
3839 "from " str
& " " | -
5
3841 ("Identifier: " str
", ") -
2 \n _
)
3843 (python-skeleton-define try nil
3849 "except " str
":" \n
3852 '(python-skeleton--except)
3853 '(python-skeleton--else)
3854 '(python-skeleton--finally) | ^
)
3856 (python-skeleton-define def nil
3858 "def " str
"(" ("Parameter, %s: "
3859 (unless (equal ?\
( (char-before)) ", ")
3861 "\"\"\"" -
"\"\"\"" \n
3864 (python-skeleton-define class nil
3866 "class " str
"(" ("Inheritance, %s: "
3867 (unless (equal ?\
( (char-before)) ", ")
3871 "\"\"\"" -
"\"\"\"" \n
3874 (defun python-skeleton-add-menu-items ()
3875 "Add menu items to Python->Skeletons menu."
3876 (let ((skeletons (sort python-skeleton-available
'string
<)))
3877 (dolist (skeleton skeletons
)
3879 nil
'("Python" "Skeletons")
3881 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3886 (defcustom python-ffap-setup-code
3887 "def __FFAP_get_module_path(module):
3890 path = __import__(module).__file__
3891 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3896 "Python code to get a module path."
3900 (defcustom python-ffap-string-code
3901 "__FFAP_get_module_path('''%s''')\n"
3902 "Python code used to get a string with the path of a module."
3906 (defun python-ffap-module-path (module)
3907 "Function for `ffap-alist' to return path for MODULE."
3909 (and (derived-mode-p 'inferior-python-mode
)
3910 (get-buffer-process (current-buffer)))
3911 (python-shell-get-process))))
3915 (python-shell-send-string-no-output
3916 (format python-ffap-string-code module
) process
)))
3918 (substring-no-properties module-file
1 -
1))))))
3922 (eval-after-load "ffap"
3924 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3925 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3930 (defcustom python-check-command
3931 (or (executable-find "pyflakes")
3932 (executable-find "epylint")
3933 "install pyflakes, pylint or something else")
3934 "Command used to check a Python file."
3938 (defcustom python-check-buffer-name
3939 "*Python check: %s*"
3940 "Buffer name used for check commands."
3944 (defvar python-check-custom-command nil
3946 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
3947 (make-variable-buffer-local 'python-check-custom-command
)
3949 (defun python-check (command)
3950 "Check a Python file (default current buffer's file).
3951 Runs COMMAND, a shell command, as if by `compile'.
3952 See `python-check-command' for the default."
3954 (list (read-string "Check command: "
3955 (or python-check-custom-command
3956 (concat python-check-command
" "
3957 (shell-quote-argument
3959 (let ((name (buffer-file-name)))
3961 (file-name-nondirectory name
)))
3963 (setq python-check-custom-command command
)
3964 (save-some-buffers (not compilation-ask-about-save
) nil
)
3965 (let ((process-environment (python-shell-calculate-process-environment))
3966 (exec-path (python-shell-calculate-exec-path)))
3967 (compilation-start command nil
3969 (format python-check-buffer-name command
)))))
3974 (defcustom python-eldoc-setup-code
3975 "def __PYDOC_get_help(obj):
3979 str_type = basestring
3982 if isinstance(obj, str_type):
3983 obj = eval(obj, globals())
3984 doc = inspect.getdoc(obj)
3985 if not doc and callable(obj):
3987 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3988 target = obj.__init__
3994 args = inspect.formatargspec(
3995 *inspect.getargspec(target)
3998 doc = '{objtype} {name}{args}'.format(
3999 objtype=objtype, name=name, args=args
4002 doc = doc.splitlines()[0]
4006 "Python code to setup documentation retrieval."
4010 (defcustom python-eldoc-string-code
4011 "__PYDOC_get_help('''%s''')\n"
4012 "Python code used to get a string with the documentation of an object."
4016 (defun python-eldoc--get-symbol-at-point ()
4017 "Get the current symbol for eldoc.
4018 Returns the current symbol handling point within arguments."
4020 (let ((start (python-syntax-context 'paren
)))
4025 (memq (char-syntax (char-after)) '(?\ ?-
)))
4026 ;; Try to adjust to closest symbol if not in one.
4027 (python-util-forward-comment -
1)))
4028 (python-info-current-symbol t
)))
4030 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
4031 "Internal implementation to get documentation at point.
4032 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4033 returns will be used. If not FORCE-PROCESS is passed what
4034 `python-shell-get-process' returns is used."
4035 (let ((process (or force-process
(python-shell-get-process))))
4037 (let ((input (or force-input
4038 (python-eldoc--get-symbol-at-point))))
4040 ;; Prevent resizing the echo area when iPython is
4041 ;; enabled. Bug#18794.
4042 (python-util-strip-string
4043 (python-shell-send-string-no-output
4044 (format python-eldoc-string-code input
)
4047 (defun python-eldoc-function ()
4048 "`eldoc-documentation-function' for Python.
4049 For this to work as best as possible you should call
4050 `python-shell-send-buffer' from time to time so context in
4051 inferior Python process is updated properly."
4052 (python-eldoc--get-doc-at-point))
4054 (defun python-eldoc-at-point (symbol)
4055 "Get help on SYMBOL using `help'.
4056 Interactively, prompt for symbol."
4058 (let ((symbol (python-eldoc--get-symbol-at-point))
4059 (enable-recursive-minibuffers t
))
4060 (list (read-string (if symbol
4061 (format "Describe symbol (default %s): " symbol
)
4062 "Describe symbol: ")
4064 (message (python-eldoc--get-doc-at-point symbol
)))
4069 (defun python-hideshow-forward-sexp-function (arg)
4070 "Python specific `forward-sexp' function for `hs-minor-mode'.
4071 Argument ARG is ignored."
4072 arg
; Shut up, byte compiler.
4073 (python-nav-end-of-defun)
4074 (unless (python-info-current-line-empty-p)
4080 (defvar python-imenu-format-item-label-function
4081 'python-imenu-format-item-label
4082 "Imenu function used to format an item label.
4083 It must be a function with two arguments: TYPE and NAME.")
4085 (defvar python-imenu-format-parent-item-label-function
4086 'python-imenu-format-parent-item-label
4087 "Imenu function used to format a parent item label.
4088 It must be a function with two arguments: TYPE and NAME.")
4090 (defvar python-imenu-format-parent-item-jump-label-function
4091 'python-imenu-format-parent-item-jump-label
4092 "Imenu function used to format a parent jump item label.
4093 It must be a function with two arguments: TYPE and NAME.")
4095 (defun python-imenu-format-item-label (type name
)
4096 "Return Imenu label for single node using TYPE and NAME."
4097 (format "%s (%s)" name type
))
4099 (defun python-imenu-format-parent-item-label (type name
)
4100 "Return Imenu label for parent node using TYPE and NAME."
4101 (format "%s..." (python-imenu-format-item-label type name
)))
4103 (defun python-imenu-format-parent-item-jump-label (type _name
)
4104 "Return Imenu label for parent node jump using TYPE and NAME."
4105 (if (string= type
"class")
4106 "*class definition*"
4107 "*function definition*"))
4109 (defun python-imenu--put-parent (type name pos tree
)
4110 "Add the parent with TYPE, NAME and POS to TREE."
4112 (funcall python-imenu-format-item-label-function type name
))
4114 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
4117 (cons label
(cons (cons jump-label pos
) tree
)))))
4119 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
4120 "Recursively build the tree of nested definitions of a node.
4121 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4122 not be passed explicitly unless you know what you are doing."
4123 (setq min-indent
(or min-indent
0)
4124 prev-indent
(or prev-indent python-indent-offset
))
4125 (let* ((pos (python-nav-backward-defun))
4127 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
4128 (let ((split (split-string (match-string-no-properties 0))))
4129 (setq type
(car split
))
4132 (funcall python-imenu-format-item-label-function type name
)))
4133 (indent (current-indentation))
4134 (children-indent-limit (+ python-indent-offset min-indent
)))
4136 ;; Nothing found, probably near to bobp.
4138 ((<= indent min-indent
)
4139 ;; The current indentation points that this is a parent
4140 ;; node, add it to the tree and stop recursing.
4141 (python-imenu--put-parent type name pos tree
))
4143 (python-imenu--build-tree
4146 (if (<= indent children-indent-limit
)
4147 ;; This lies within the children indent offset range,
4148 ;; so it's a normal child of its parent (i.e., not
4149 ;; a child of a child).
4150 (cons (cons label pos
) tree
)
4151 ;; Oh no, a child of a child?! Fear not, we
4152 ;; know how to roll. We recursively parse these by
4153 ;; swapping prev-indent and min-indent plus adding this
4154 ;; newly found item to a fresh subtree. This works, I
4157 (python-imenu--build-tree
4158 prev-indent indent
(list (cons label pos
)))
4161 (defun python-imenu-create-index ()
4162 "Return tree Imenu alist for the current Python buffer.
4163 Change `python-imenu-format-item-label-function',
4164 `python-imenu-format-parent-item-label-function',
4165 `python-imenu-format-parent-item-jump-label-function' to
4166 customize how labels are formatted."
4167 (goto-char (point-max))
4170 (while (setq tree
(python-imenu--build-tree))
4171 (setq index
(cons tree index
)))
4174 (defun python-imenu-create-flat-index (&optional alist prefix
)
4175 "Return flat outline of the current Python buffer for Imenu.
4176 Optional argument ALIST is the tree to be flattened; when nil
4177 `python-imenu-build-index' is used with
4178 `python-imenu-format-parent-item-jump-label-function'
4179 `python-imenu-format-parent-item-label-function'
4180 `python-imenu-format-item-label-function' set to
4181 (lambda (type name) name)
4182 Optional argument PREFIX is used in recursive calls and should
4183 not be passed explicitly.
4190 (\"decorator\" . 173)
4193 (\"wrapped_f\" . 393))))
4199 (\"decorator\" . 173)
4200 (\"decorator.wrap\" . 353)
4201 (\"decorator.wrapped_f\" . 393))"
4202 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4207 (let ((name (if prefix
4208 (concat prefix
"." (car item
))
4211 (cond ((or (numberp pos
) (markerp pos
))
4212 (list (cons name pos
)))
4215 (cons name
(cdar pos
))
4216 (python-imenu-create-flat-index (cddr item
) name
))))))
4218 (let* ((fn (lambda (_type name
) name
))
4219 (python-imenu-format-item-label-function fn
)
4220 (python-imenu-format-parent-item-label-function fn
)
4221 (python-imenu-format-parent-item-jump-label-function fn
))
4222 (python-imenu-create-index))))))
4227 (defun python-info-current-defun (&optional include-type
)
4228 "Return name of surrounding function with Python compatible dotty syntax.
4229 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4230 This function can be used as the value of `add-log-current-defun-function'
4231 since it returns nil if point is not inside a defun."
4237 (starting-indentation (current-indentation))
4238 (starting-pos (point))
4243 (while (python-nav-beginning-of-defun 1)
4244 (when (save-match-data
4246 (or (not last-indent
)
4247 (< (current-indentation) last-indent
))
4251 ;; If this is the first run, we may add
4252 ;; the current defun at point.
4253 (setq first-run nil
)
4254 (goto-char starting-pos
)
4255 (python-nav-beginning-of-statement)
4256 (beginning-of-line 1)
4258 python-nav-beginning-of-defun-regexp
)))
4262 (+ (current-indentation)
4263 python-indent-offset
)))
4264 (if (< starting-indentation min-indent
)
4265 ;; If the starting indentation is not
4266 ;; within the min defun indent make the
4269 ;; Else go to the end of defun and add
4270 ;; up the current indentation to the
4272 (python-nav-end-of-defun)
4274 (if (>= (current-indentation) min-indent
)
4275 (1+ (current-indentation))
4277 (save-match-data (setq last-indent
(current-indentation)))
4278 (if (or (not include-type
) type
)
4279 (setq names
(cons (match-string-no-properties 1) names
))
4280 (let ((match (split-string (match-string-no-properties 0))))
4281 (setq type
(car match
))
4282 (setq names
(cons (cadr match
) names
)))))
4283 ;; Stop searching ASAP.
4284 (and (= (current-indentation) 0) (throw 'exit t
))))
4286 (concat (and type
(format "%s " type
))
4287 (mapconcat 'identity names
".")))))))
4289 (defun python-info-current-symbol (&optional replace-self
)
4290 "Return current symbol using dotty syntax.
4291 With optional argument REPLACE-SELF convert \"self\" to current
4294 (and (not (python-syntax-comment-or-string-p))
4295 (with-syntax-table python-dotty-syntax-table
4296 (let ((sym (symbol-at-point)))
4298 (substring-no-properties (symbol-name sym
))))))))
4300 (if (not replace-self
)
4302 (let ((current-defun (python-info-current-defun)))
4303 (if (not current-defun
)
4305 (replace-regexp-in-string
4306 (python-rx line-start word-start
"self" word-end ?.
)
4308 (mapconcat 'identity
4309 (butlast (split-string current-defun
"\\."))
4313 (defun python-info-statement-starts-block-p ()
4314 "Return non-nil if current statement opens a block."
4316 (python-nav-beginning-of-statement)
4317 (looking-at (python-rx block-start
))))
4319 (defun python-info-statement-ends-block-p ()
4320 "Return non-nil if point is at end of block."
4321 (let ((end-of-block-pos (save-excursion
4322 (python-nav-end-of-block)))
4323 (end-of-statement-pos (save-excursion
4324 (python-nav-end-of-statement))))
4325 (and end-of-block-pos end-of-statement-pos
4326 (= end-of-block-pos end-of-statement-pos
))))
4328 (defun python-info-beginning-of-statement-p ()
4329 "Return non-nil if point is at beginning of statement."
4330 (= (point) (save-excursion
4331 (python-nav-beginning-of-statement)
4334 (defun python-info-end-of-statement-p ()
4335 "Return non-nil if point is at end of statement."
4336 (= (point) (save-excursion
4337 (python-nav-end-of-statement)
4340 (defun python-info-beginning-of-block-p ()
4341 "Return non-nil if point is at beginning of block."
4342 (and (python-info-beginning-of-statement-p)
4343 (python-info-statement-starts-block-p)))
4345 (defun python-info-end-of-block-p ()
4346 "Return non-nil if point is at end of block."
4347 (and (python-info-end-of-statement-p)
4348 (python-info-statement-ends-block-p)))
4350 (define-obsolete-function-alias
4351 'python-info-closing-block
4352 'python-info-dedenter-opening-block-position
"24.4")
4354 (defun python-info-dedenter-opening-block-position ()
4355 "Return the point of the closest block the current line closes.
4356 Returns nil if point is not on a dedenter statement or no opening
4357 block can be detected. The latter case meaning current file is
4358 likely an invalid python file."
4359 (let ((positions (python-info-dedenter-opening-block-positions))
4360 (indentation (current-indentation))
4362 (while (and (not position
)
4365 (goto-char (car positions
))
4366 (if (<= (current-indentation) indentation
)
4367 (setq position
(car positions
))
4368 (setq positions
(cdr positions
)))))
4371 (defun python-info-dedenter-opening-block-positions ()
4372 "Return points of blocks the current line may close sorted by closer.
4373 Returns nil if point is not on a dedenter statement or no opening
4374 block can be detected. The latter case meaning current file is
4375 likely an invalid python file."
4377 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4379 (goto-char dedenter-pos
)
4380 (let* ((pairs '(("elif" "elif" "if")
4381 ("else" "if" "elif" "except" "for" "while")
4382 ("except" "except" "try")
4383 ("finally" "else" "except" "try")))
4384 (dedenter (match-string-no-properties 0))
4385 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
4386 (collected-indentations)
4389 (while (python-nav--syntactically
4391 (re-search-backward (python-rx block-start
) nil t
))
4393 (let ((indentation (current-indentation)))
4394 (when (and (not (memq indentation collected-indentations
))
4395 (or (not collected-indentations
)
4396 (< indentation
(apply #'min collected-indentations
))))
4397 (setq collected-indentations
4398 (cons indentation collected-indentations
))
4399 (when (member (match-string-no-properties 0)
4400 possible-opening-blocks
)
4401 (setq opening-blocks
(cons (point) opening-blocks
))))
4402 (when (zerop indentation
)
4403 (throw 'exit nil
)))))
4405 (nreverse opening-blocks
))))))
4407 (define-obsolete-function-alias
4408 'python-info-closing-block-message
4409 'python-info-dedenter-opening-block-message
"24.4")
4411 (defun python-info-dedenter-opening-block-message ()
4412 "Message the first line of the block the current statement closes."
4413 (let ((point (python-info-dedenter-opening-block-position)))
4417 (message "Closes %s" (save-excursion
4420 (point) (line-end-position))))))))
4422 (defun python-info-dedenter-statement-p ()
4423 "Return point if current statement is a dedenter.
4424 Sets `match-data' to the keyword that starts the dedenter
4427 (python-nav-beginning-of-statement)
4428 (when (and (not (python-syntax-context-type))
4429 (looking-at (python-rx dedenter
)))
4432 (defun python-info-line-ends-backslash-p (&optional line-number
)
4433 "Return non-nil if current line ends with backslash.
4434 With optional argument LINE-NUMBER, check that line instead."
4439 (python-util-goto-line line-number
))
4440 (while (and (not (eobp))
4441 (goto-char (line-end-position))
4442 (python-syntax-context 'paren
)
4443 (not (equal (char-before (point)) ?
\\)))
4445 (when (equal (char-before) ?
\\)
4448 (defun python-info-beginning-of-backslash (&optional line-number
)
4449 "Return the point where the backslashed line start.
4450 Optional argument LINE-NUMBER forces the line number to check against."
4455 (python-util-goto-line line-number
))
4456 (when (python-info-line-ends-backslash-p)
4457 (while (save-excursion
4458 (goto-char (line-beginning-position))
4459 (python-syntax-context 'paren
))
4461 (back-to-indentation)
4464 (defun python-info-continuation-line-p ()
4465 "Check if current line is continuation of another.
4466 When current line is continuation of another return the point
4467 where the continued line ends."
4471 (let* ((context-type (progn
4472 (back-to-indentation)
4473 (python-syntax-context-type)))
4474 (line-start (line-number-at-pos))
4475 (context-start (when context-type
4476 (python-syntax-context context-type
))))
4477 (cond ((equal context-type
'paren
)
4478 ;; Lines inside a paren are always a continuation line
4479 ;; (except the first one).
4480 (python-util-forward-comment -
1)
4482 ((member context-type
'(string comment
))
4483 ;; move forward an roll again
4484 (goto-char context-start
)
4485 (python-util-forward-comment)
4486 (python-info-continuation-line-p))
4488 ;; Not within a paren, string or comment, the only way
4489 ;; we are dealing with a continuation line is that
4490 ;; previous line contains a backslash, and this can
4491 ;; only be the previous line from current
4492 (back-to-indentation)
4493 (python-util-forward-comment -
1)
4494 (when (and (equal (1- line-start
) (line-number-at-pos))
4495 (python-info-line-ends-backslash-p))
4496 (point-marker))))))))
4498 (defun python-info-block-continuation-line-p ()
4499 "Return non-nil if current line is a continuation of a block."
4501 (when (python-info-continuation-line-p)
4503 (back-to-indentation)
4504 (when (looking-at (python-rx block-start
))
4507 (defun python-info-assignment-statement-p (&optional current-line-only
)
4508 "Check if current line is an assignment.
4509 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4510 continuations, just check the if current line is an assignment."
4513 (if current-line-only
4514 (back-to-indentation)
4515 (python-nav-beginning-of-statement))
4517 (re-search-forward (python-rx not-simple-operator
4519 (group not-simple-operator
))
4520 (line-end-position) t
)
4523 ;; The assignment operator should not be inside a string.
4524 (backward-char (length (match-string-no-properties 1)))
4525 (setq found
(not (python-syntax-context-type)))))
4527 (skip-syntax-forward " ")
4530 ;; TODO: rename to clarify this is only for the first continuation
4531 ;; line or remove it and move its body to `python-indent-context'.
4532 (defun python-info-assignment-continuation-line-p ()
4533 "Check if current line is the first continuation of an assignment.
4534 When current line is continuation of another with an assignment
4535 return the point of the first non-blank character after the
4538 (when (python-info-continuation-line-p)
4540 (python-info-assignment-statement-p t
))))
4542 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4543 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4544 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4546 (beginning-of-line 1)
4547 (looking-at python-nav-beginning-of-defun-regexp
))))
4549 (defun python-info-current-line-comment-p ()
4550 "Return non-nil if current line is a comment line."
4552 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4555 (defun python-info-current-line-empty-p ()
4556 "Return non-nil if current line is empty, ignoring whitespace."
4558 (beginning-of-line 1)
4560 (python-rx line-start
(* whitespace
)
4561 (group (* not-newline
))
4562 (* whitespace
) line-end
))
4563 (string-equal "" (match-string-no-properties 1))))
4565 (defun python-info-docstring-p (&optional syntax-ppss
)
4566 "Return non-nil if point is in a docstring.
4567 When optional argument SYNTAX-PPSS is given, use that instead of
4568 point's current `syntax-ppss'."
4569 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4571 (when (and syntax-ppss
(python-syntax-context 'string syntax-ppss
))
4572 (goto-char (nth 8 syntax-ppss
)))
4573 (python-nav-beginning-of-statement)
4575 (indentation (current-indentation))
4576 (backward-sexp-point)
4577 (re (concat "[uU]?[rR]?"
4578 (python-rx string-delimiter
))))
4580 (not (python-info-assignment-statement-p))
4582 ;; Allow up to two consecutive docstrings only.
4586 (while (save-excursion
4587 (python-nav-backward-sexp)
4588 (setq backward-sexp-point
(point))
4589 (and (= indentation
(current-indentation))
4590 (not (bobp)) ; Prevent infloop.
4592 (concat "[uU]?[rR]?"
4593 (python-rx string-delimiter
)))))
4594 ;; Previous sexp was a string, restore point.
4595 (goto-char backward-sexp-point
)
4598 (python-util-forward-comment -
1)
4599 (python-nav-beginning-of-statement)
4601 ((python-info-assignment-statement-p) t
)
4602 ((python-info-looking-at-beginning-of-defun))
4605 (defun python-info-encoding-from-cookie ()
4606 "Detect current buffer's encoding from its coding cookie.
4607 Returns the encoding as a symbol."
4608 (let ((first-two-lines
4612 (goto-char (point-min))
4614 (buffer-substring-no-properties
4617 (when (string-match (python-rx coding-cookie
) first-two-lines
)
4618 (intern (match-string-no-properties 1 first-two-lines
)))))
4620 (defun python-info-encoding ()
4621 "Return encoding for file.
4622 Try `python-info-encoding-from-cookie', if none is found then
4624 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4625 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4626 ;; in the worst case scenario python.el will make things work for
4627 ;; Python 2 files with unicode data and no encoding defined.
4628 (or (python-info-encoding-from-cookie)
4632 ;;; Utility functions
4634 (defun python-util-goto-line (line-number)
4635 "Move point to LINE-NUMBER."
4636 (goto-char (point-min))
4637 (forward-line (1- line-number
)))
4639 ;; Stolen from org-mode
4640 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
4641 "Clone local variables from FROM-BUFFER.
4642 Optional argument REGEXP selects variables to clone and defaults
4646 (and (symbolp (car pair
))
4647 (string-match (or regexp
"^python-")
4648 (symbol-name (car pair
)))
4649 (set (make-local-variable (car pair
))
4651 (buffer-local-variables from-buffer
)))
4653 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
4655 (defun python-util-comint-last-prompt ()
4656 "Return comint last prompt overlay start and end.
4657 This is for compatibility with Emacs < 24.4."
4658 (cond ((bound-and-true-p comint-last-prompt-overlay
)
4659 (cons (overlay-start comint-last-prompt-overlay
)
4660 (overlay-end comint-last-prompt-overlay
)))
4661 ((bound-and-true-p comint-last-prompt
)
4665 (defun python-util-forward-comment (&optional direction
)
4666 "Python mode specific version of `forward-comment'.
4667 Optional argument DIRECTION defines the direction to move to."
4668 (let ((comment-start (python-syntax-context 'comment
))
4669 (factor (if (< (or direction
0) 0)
4673 (goto-char comment-start
))
4674 (forward-comment factor
)))
4676 (defun python-util-list-directories (directory &optional predicate max-depth
)
4677 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4678 Argument PREDICATE defaults to `identity' and must be a function
4679 that takes one argument (a full path) and returns non-nil for
4680 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4681 searching when depth is reached, else don't limit."
4682 (let* ((dir (expand-file-name directory
))
4683 (dir-length (length dir
))
4684 (predicate (or predicate
#'identity
))
4685 (to-scan (list dir
))
4688 (let ((current-dir (car to-scan
)))
4689 (when (funcall predicate current-dir
)
4690 (setq tally
(cons current-dir tally
)))
4691 (setq to-scan
(append (cdr to-scan
)
4692 (python-util-list-files
4693 current-dir
#'file-directory-p
)
4695 (when (and max-depth
4697 (length (split-string
4698 (substring current-dir dir-length
)
4700 (setq to-scan nil
))))
4703 (defun python-util-list-files (dir &optional predicate
)
4704 "List files in DIR, filtering with PREDICATE.
4705 Argument PREDICATE defaults to `identity' and must be a function
4706 that takes one argument (a full path) and returns non-nil for
4708 (let ((dir-name (file-name-as-directory dir
)))
4710 (mapcar (lambda (file-name)
4711 (let ((full-file-name (expand-file-name file-name dir-name
)))
4713 (not (member file-name
'("." "..")))
4714 (funcall (or predicate
#'identity
) full-file-name
))
4715 (list full-file-name
))))
4716 (directory-files dir-name
)))))
4718 (defun python-util-list-packages (dir &optional max-depth
)
4719 "List packages in DIR, limited by MAX-DEPTH.
4720 When optional argument MAX-DEPTH is non-nil, stop searching when
4721 depth is reached, else don't limit."
4722 (let* ((dir (expand-file-name dir
))
4723 (parent-dir (file-name-directory
4724 (directory-file-name
4725 (file-name-directory
4726 (file-name-as-directory dir
)))))
4727 (subpath-length (length parent-dir
)))
4730 (replace-regexp-in-string
4731 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
4732 (python-util-list-directories
4733 (directory-file-name dir
)
4735 (file-exists-p (expand-file-name "__init__.py" dir
)))
4738 (defun python-util-popn (lst n
)
4739 "Return LST first N elements.
4740 N should be an integer, when negative its opposite is used.
4741 When N is bigger than the length of LST, the list is
4743 (let* ((n (min (abs n
)))
4749 (setq acc
(cons (car lst
) acc
)
4754 (defun python-util-strip-string (string)
4755 "Strip STRING whitespace and newlines from end and beginning."
4756 (replace-regexp-in-string
4757 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
4758 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
4762 (defun python-util-valid-regexp-p (regexp)
4763 "Return non-nil if REGEXP is valid."
4764 (ignore-errors (string-match regexp
"") t
))
4767 (defun python-electric-pair-string-delimiter ()
4768 (when (and electric-pair-mode
4769 (memq last-command-event
'(?
\" ?
\'))
4771 (while (eq (char-before (- (point) count
)) last-command-event
)
4774 (eq (char-after) last-command-event
))
4775 (save-excursion (insert (make-string 2 last-command-event
)))))
4777 (defvar electric-indent-inhibit
)
4780 (define-derived-mode python-mode prog-mode
"Python"
4781 "Major mode for editing Python files.
4783 \\{python-mode-map}"
4784 (set (make-local-variable 'tab-width
) 8)
4785 (set (make-local-variable 'indent-tabs-mode
) nil
)
4787 (set (make-local-variable 'comment-start
) "# ")
4788 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4790 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4791 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4793 (set (make-local-variable 'forward-sexp-function
)
4794 'python-nav-forward-sexp
)
4796 (set (make-local-variable 'font-lock-defaults
)
4797 '(python-font-lock-keywords
4799 (font-lock-syntactic-face-function
4800 . python-font-lock-syntactic-face-function
)))
4802 (set (make-local-variable 'syntax-propertize-function
)
4803 python-syntax-propertize-function
)
4805 (set (make-local-variable 'indent-line-function
)
4806 #'python-indent-line-function
)
4807 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4808 ;; Because indentation is not redundant, we cannot safely reindent code.
4809 (set (make-local-variable 'electric-indent-inhibit
) t
)
4810 (set (make-local-variable 'electric-indent-chars
)
4811 (cons ?
: electric-indent-chars
))
4813 ;; Add """ ... """ pairing to electric-pair-mode.
4814 (add-hook 'post-self-insert-hook
4815 #'python-electric-pair-string-delimiter
'append t
)
4817 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4818 (set (make-local-variable 'fill-paragraph-function
)
4819 #'python-fill-paragraph
)
4821 (set (make-local-variable 'beginning-of-defun-function
)
4822 #'python-nav-beginning-of-defun
)
4823 (set (make-local-variable 'end-of-defun-function
)
4824 #'python-nav-end-of-defun
)
4826 (add-hook 'completion-at-point-functions
4827 #'python-completion-at-point nil
'local
)
4829 (add-hook 'post-self-insert-hook
4830 #'python-indent-post-self-insert-function
'append
'local
)
4832 (set (make-local-variable 'imenu-create-index-function
)
4833 #'python-imenu-create-index
)
4835 (set (make-local-variable 'add-log-current-defun-function
)
4836 #'python-info-current-defun
)
4838 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4840 (set (make-local-variable 'skeleton-further-elements
)
4842 (< '(backward-delete-char-untabify (min python-indent-offset
4844 (^
'(- (1+ (current-indentation))))))
4846 (if (null eldoc-documentation-function
)
4848 (set (make-local-variable 'eldoc-documentation-function
)
4849 #'python-eldoc-function
)
4850 (add-function :before-until
(local 'eldoc-documentation-function
)
4851 #'python-eldoc-function
))
4854 'hs-special-modes-alist
4856 "\\s-*\\(?:def\\|class\\)\\>"
4857 ;; Use the empty string as end regexp so it doesn't default to
4858 ;; "\\s)". This way parens at end of defun are properly hidden.
4861 python-hideshow-forward-sexp-function
4864 (set (make-local-variable 'outline-regexp
)
4865 (python-rx (* space
) block-start
))
4866 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
4867 (set (make-local-variable 'outline-level
)
4869 "`outline-level' function for Python mode."
4870 (1+ (/ (current-indentation) python-indent-offset
))))
4872 (python-skeleton-add-menu-items)
4874 (make-local-variable 'python-shell-internal-buffer
)
4876 (when python-indent-guess-indent-offset
4877 (python-indent-guess-indent-offset)))
4884 ;; indent-tabs-mode: nil
4887 ;;; python.el ends here