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
))
2271 (when (looking-back regexp
(point-min))
2272 (throw 'found t
))))))
2274 (defun python-shell-comint-end-of-output-p (output)
2275 "Return non-nil if OUTPUT is ends with input prompt."
2277 ;; XXX: It seems on OSX an extra carriage return is attached
2278 ;; at the end of output, this handles that too.
2281 ;; Remove initial caret from calculated regexp
2282 (replace-regexp-in-string
2283 (rx string-start ?^
) ""
2284 python-shell--prompt-calculated-input-regexp
)
2288 (define-obsolete-function-alias
2289 'python-comint-output-filter-function
2290 'ansi-color-filter-apply
2293 (defun python-comint-postoutput-scroll-to-bottom (output)
2294 "Faster version of `comint-postoutput-scroll-to-bottom'.
2295 Avoids `recenter' calls until OUTPUT is completely sent."
2296 (when (and (not (string= "" output
))
2297 (python-shell-comint-end-of-output-p
2298 (ansi-color-filter-apply output
)))
2299 (comint-postoutput-scroll-to-bottom output
))
2302 (defvar python-shell--parent-buffer nil
)
2304 (defmacro python-shell-with-shell-buffer
(&rest body
)
2305 "Execute the forms in BODY with the shell buffer temporarily current.
2306 Signals an error if no shell buffer is available for current buffer."
2307 (declare (indent 0) (debug t
))
2308 (let ((shell-process (make-symbol "shell-process")))
2309 `(let ((,shell-process
(python-shell-get-process-or-error)))
2310 (with-current-buffer (process-buffer ,shell-process
)
2313 (defvar python-shell--font-lock-buffer nil
)
2315 (defun python-shell-font-lock-get-or-create-buffer ()
2316 "Get or create a font-lock buffer for current inferior process."
2317 (python-shell-with-shell-buffer
2318 (if python-shell--font-lock-buffer
2319 python-shell--font-lock-buffer
2321 (process-name (get-buffer-process (current-buffer)))))
2322 (generate-new-buffer
2323 (format " *%s-font-lock*" process-name
))))))
2325 (defun python-shell-font-lock-kill-buffer ()
2326 "Kill the font-lock buffer safely."
2327 (when (and python-shell--font-lock-buffer
2328 (buffer-live-p python-shell--font-lock-buffer
))
2329 (kill-buffer python-shell--font-lock-buffer
)
2330 (when (derived-mode-p 'inferior-python-mode
)
2331 (setq python-shell--font-lock-buffer nil
))))
2333 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2334 "Execute the forms in BODY in the font-lock buffer.
2335 The value returned is the value of the last form in BODY. See
2336 also `with-current-buffer'."
2337 (declare (indent 0) (debug t
))
2338 `(python-shell-with-shell-buffer
2339 (save-current-buffer
2340 (when (not (and python-shell--font-lock-buffer
2341 (get-buffer python-shell--font-lock-buffer
)))
2342 (setq python-shell--font-lock-buffer
2343 (python-shell-font-lock-get-or-create-buffer)))
2344 (set-buffer python-shell--font-lock-buffer
)
2345 (when (not font-lock-mode
)
2347 (set (make-local-variable 'delay-mode-hooks
) t
)
2348 (let ((python-indent-guess-indent-offset nil
))
2349 (when (not (derived-mode-p 'python-mode
))
2353 (defun python-shell-font-lock-cleanup-buffer ()
2354 "Cleanup the font-lock buffer.
2355 Provided as a command because this might be handy if something
2356 goes wrong and syntax highlighting in the shell gets messed up."
2358 (python-shell-with-shell-buffer
2359 (python-shell-font-lock-with-font-lock-buffer
2362 (defun python-shell-font-lock-comint-output-filter-function (output)
2363 "Clean up the font-lock buffer after any OUTPUT."
2364 (if (and (not (string= "" output
))
2365 ;; Is end of output and is not just a prompt.
2367 (python-shell-comint-end-of-output-p
2368 (ansi-color-filter-apply output
))
2370 ;; If output is other than an input prompt then "real" output has
2371 ;; been received and the font-lock buffer must be cleaned up.
2372 (python-shell-font-lock-cleanup-buffer)
2373 ;; Otherwise just add a newline.
2374 (python-shell-font-lock-with-font-lock-buffer
2375 (goto-char (point-max))
2379 (defun python-shell-font-lock-post-command-hook ()
2380 "Fontifies current line in shell buffer."
2381 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2382 (when (and prompt-end
(> (point) prompt-end
)
2383 (process-live-p (get-buffer-process (current-buffer))))
2384 (let* ((input (buffer-substring-no-properties
2385 prompt-end
(point-max)))
2386 (deactivate-mark nil
)
2387 (start-pos prompt-end
)
2388 (buffer-undo-list t
)
2389 (font-lock-buffer-pos nil
)
2391 (python-shell-font-lock-with-font-lock-buffer
2392 (delete-region (line-beginning-position)
2394 (setq font-lock-buffer-pos
(point))
2396 ;; Ensure buffer is fontified, keeping it
2397 ;; compatible with Emacs < 24.4.
2398 (if (fboundp 'font-lock-ensure
)
2399 (funcall 'font-lock-ensure
)
2400 (font-lock-default-fontify-buffer))
2401 (buffer-substring font-lock-buffer-pos
2403 (replacement-length (length replacement
))
2405 ;; Inject text properties to get input fontified.
2406 (while (not (= i replacement-length
))
2407 (let* ((plist (text-properties-at i replacement
))
2408 (next-change (or (next-property-change i replacement
)
2409 replacement-length
))
2410 (plist (let ((face (plist-get plist
'face
)))
2413 ;; Replace FACE text properties with
2414 ;; FONT-LOCK-FACE so input is fontified.
2415 (plist-put plist
'face nil
)
2416 (plist-put plist
'font-lock-face face
)))))
2417 (set-text-properties
2418 (+ start-pos i
) (+ start-pos next-change
) plist
)
2419 (setq i next-change
)))))))
2421 (defun python-shell-font-lock-turn-on (&optional msg
)
2422 "Turn on shell font-lock.
2423 With argument MSG show activation message."
2425 (python-shell-with-shell-buffer
2426 (python-shell-font-lock-kill-buffer)
2427 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2428 (add-hook 'post-command-hook
2429 #'python-shell-font-lock-post-command-hook nil
'local
)
2430 (add-hook 'kill-buffer-hook
2431 #'python-shell-font-lock-kill-buffer nil
'local
)
2432 (add-hook 'comint-output-filter-functions
2433 #'python-shell-font-lock-comint-output-filter-function
2436 (message "Shell font-lock is enabled"))))
2438 (defun python-shell-font-lock-turn-off (&optional msg
)
2439 "Turn off shell font-lock.
2440 With argument MSG show deactivation message."
2442 (python-shell-with-shell-buffer
2443 (python-shell-font-lock-kill-buffer)
2444 (when (python-util-comint-last-prompt)
2445 ;; Cleanup current fontification
2446 (remove-text-properties
2447 (cdr (python-util-comint-last-prompt))
2449 '(face nil font-lock-face nil
)))
2450 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2451 (remove-hook 'post-command-hook
2452 #'python-shell-font-lock-post-command-hook
'local
)
2453 (remove-hook 'kill-buffer-hook
2454 #'python-shell-font-lock-kill-buffer
'local
)
2455 (remove-hook 'comint-output-filter-functions
2456 #'python-shell-font-lock-comint-output-filter-function
2459 (message "Shell font-lock is disabled"))))
2461 (defun python-shell-font-lock-toggle (&optional msg
)
2462 "Toggle font-lock for shell.
2463 With argument MSG show activation/deactivation message."
2465 (python-shell-with-shell-buffer
2466 (set (make-local-variable 'python-shell-font-lock-enable
)
2467 (not python-shell-font-lock-enable
))
2468 (if python-shell-font-lock-enable
2469 (python-shell-font-lock-turn-on msg
)
2470 (python-shell-font-lock-turn-off msg
))
2471 python-shell-font-lock-enable
))
2473 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2474 "Major mode for Python inferior process.
2475 Runs a Python interpreter as a subprocess of Emacs, with Python
2476 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2477 and `python-shell-interpreter-args' control which Python
2478 interpreter is run. Variables
2479 `python-shell-prompt-regexp',
2480 `python-shell-prompt-output-regexp',
2481 `python-shell-prompt-block-regexp',
2482 `python-shell-font-lock-enable',
2483 `python-shell-completion-setup-code',
2484 `python-shell-completion-string-code',
2485 `python-eldoc-setup-code', `python-eldoc-string-code',
2486 `python-ffap-setup-code' and `python-ffap-string-code' can
2487 customize this mode for different Python interpreters.
2489 This mode resets `comint-output-filter-functions' locally, so you
2490 may want to re-add custom functions to it using the
2491 `inferior-python-mode-hook'.
2493 You can also add additional setup code to be run at
2494 initialization of the interpreter via `python-shell-setup-codes'
2497 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2498 (let ((interpreter python-shell-interpreter
)
2499 (args python-shell-interpreter-args
))
2500 (when python-shell--parent-buffer
2501 (python-util-clone-local-variables python-shell--parent-buffer
))
2502 ;; Users can override default values for these vars when calling
2503 ;; `run-python'. This ensures new values let-bound in
2504 ;; `python-shell-make-comint' are locally set.
2505 (set (make-local-variable 'python-shell-interpreter
) interpreter
)
2506 (set (make-local-variable 'python-shell-interpreter-args
) args
))
2507 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2508 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2509 (python-shell-prompt-set-calculated-regexps)
2510 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2511 (set (make-local-variable 'comint-prompt-read-only
) t
)
2512 (setq mode-line-process
'(":%s"))
2513 (set (make-local-variable 'comint-output-filter-functions
)
2514 '(ansi-color-process-output
2515 python-pdbtrack-comint-output-filter-function
2516 python-comint-postoutput-scroll-to-bottom
))
2517 (set (make-local-variable 'compilation-error-regexp-alist
)
2518 python-shell-compilation-regexp-alist
)
2519 (add-hook 'completion-at-point-functions
2520 #'python-shell-completion-at-point nil
'local
)
2521 (define-key inferior-python-mode-map
"\t"
2522 'python-shell-completion-complete-or-indent
)
2523 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2524 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2525 (make-local-variable 'python-shell-internal-last-output
)
2526 (when python-shell-font-lock-enable
2527 (python-shell-font-lock-turn-on))
2528 (compilation-shell-minor-mode 1)
2529 (python-shell-accept-process-output
2530 (get-buffer-process (current-buffer))))
2532 (defun python-shell-make-comint (cmd proc-name
&optional show internal
)
2533 "Create a Python shell comint buffer.
2534 CMD is the Python command to be executed and PROC-NAME is the
2535 process name the comint buffer will get. After the comint buffer
2536 is created the `inferior-python-mode' is activated. When
2537 optional argument SHOW is non-nil the buffer is shown. When
2538 optional argument INTERNAL is non-nil this process is run on a
2539 buffer with a name that starts with a space, following the Emacs
2540 convention for temporary/internal buffers, and also makes sure
2541 the user is not queried for confirmation when the process is
2544 (let* ((proc-buffer-name
2545 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
2546 (process-environment (python-shell-calculate-process-environment))
2547 (exec-path (python-shell-calculate-exec-path)))
2548 (when (not (comint-check-proc proc-buffer-name
))
2549 (let* ((cmdlist (split-string-and-unquote cmd
))
2550 (interpreter (car cmdlist
))
2551 (args (cdr cmdlist
))
2552 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2553 interpreter nil args
))
2554 (python-shell--parent-buffer (current-buffer))
2555 (process (get-buffer-process buffer
))
2556 ;; As the user may have overridden default values for
2557 ;; these vars on `run-python', let-binding them allows
2558 ;; to have the new right values in all setup code
2559 ;; that's is done in `inferior-python-mode', which is
2560 ;; important, especially for prompt detection.
2561 (python-shell-interpreter interpreter
)
2562 (python-shell-interpreter-args
2563 (mapconcat #'identity args
" ")))
2564 (with-current-buffer buffer
2565 (inferior-python-mode))
2566 (when show
(display-buffer buffer
))
2567 (and internal
(set-process-query-on-exit-flag process nil
))))
2571 (defun run-python (&optional cmd dedicated show
)
2572 "Run an inferior Python process.
2574 Argument CMD defaults to `python-shell-calculate-command' return
2575 value. When called interactively with `prefix-arg', it allows
2576 the user to edit such value and choose whether the interpreter
2577 should be DEDICATED for the current buffer. When numeric prefix
2578 arg is other than 0 or 4 do not SHOW.
2580 For a given buffer and same values of DEDICATED, if a process is
2581 already running for it, it will do nothing. This means that if
2582 the current buffer is using a global process, the user is still
2583 able to switch it to use a dedicated one.
2585 Runs the hook `inferior-python-mode-hook' after
2586 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2587 process buffer for a list of commands.)"
2589 (if current-prefix-arg
2591 (read-shell-command "Run Python: " (python-shell-calculate-command))
2592 (y-or-n-p "Make dedicated process? ")
2593 (= (prefix-numeric-value current-prefix-arg
) 4))
2594 (list (python-shell-calculate-command) nil t
)))
2596 (python-shell-make-comint
2597 (or cmd
(python-shell-calculate-command))
2598 (python-shell-get-process-name dedicated
) show
)))
2600 (defun run-python-internal ()
2601 "Run an inferior Internal Python process.
2602 Input and output via buffer named after
2603 `python-shell-internal-buffer-name' and what
2604 `python-shell-internal-get-process-name' returns.
2606 This new kind of shell is intended to be used for generic
2607 communication related to defined configurations; the main
2608 difference with global or dedicated shells is that these ones are
2609 attached to a configuration, not a buffer. This means that can
2610 be used for example to retrieve the sys.path and other stuff,
2611 without messing with user shells. Note that
2612 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2613 are set to nil for these shells, so setup codes are not sent at
2615 (let ((python-shell-font-lock-enable nil
)
2616 (inferior-python-mode-hook nil
))
2618 (python-shell-make-comint
2619 (python-shell-calculate-command)
2620 (python-shell-internal-get-process-name) nil t
))))
2622 (defun python-shell-get-buffer ()
2623 "Return inferior Python buffer for current buffer.
2624 If current buffer is in `inferior-python-mode', return it."
2625 (if (derived-mode-p 'inferior-python-mode
)
2627 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2628 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2629 (global-proc-name (python-shell-get-process-name nil
))
2630 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2631 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2632 (global-running (comint-check-proc global-proc-buffer-name
)))
2633 ;; Always prefer dedicated
2634 (or (and dedicated-running dedicated-proc-buffer-name
)
2635 (and global-running global-proc-buffer-name
)))))
2637 (defun python-shell-get-process ()
2638 "Return inferior Python process for current buffer."
2639 (get-buffer-process (python-shell-get-buffer)))
2641 (defun python-shell-get-process-or-error (&optional interactivep
)
2642 "Return inferior Python process for current buffer or signal error.
2643 When argument INTERACTIVEP is non-nil, use `user-error' instead
2644 of `error' with a user-friendly message."
2645 (or (python-shell-get-process)
2648 "Start a Python process first with `M-x run-python' or `%s'."
2652 #'run-python overriding-local-map t
)))
2654 "No inferior Python process running."))))
2656 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2657 "Get or create an inferior Python process for current buffer and return it.
2658 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2659 are used to start the shell. If those arguments are not
2660 provided, `run-python' is called interactively and the user will
2661 be asked for their values."
2662 (let ((shell-process (python-shell-get-process)))
2663 (when (not shell-process
)
2665 ;; XXX: Refactor code such that calling `run-python'
2666 ;; interactively is not needed anymore.
2667 (call-interactively 'run-python
)
2668 (run-python cmd dedicated show
)))
2669 (or shell-process
(python-shell-get-process))))
2672 #'python-shell-get-or-create-process
2673 "Instead call `python-shell-get-process' and create one if returns nil."
2676 (defvar python-shell-internal-buffer nil
2677 "Current internal shell buffer for the current buffer.
2678 This is really not necessary at all for the code to work but it's
2679 there for compatibility with CEDET.")
2681 (defvar python-shell-internal-last-output nil
2682 "Last output captured by the internal shell.
2683 This is really not necessary at all for the code to work but it's
2684 there for compatibility with CEDET.")
2686 (defun python-shell-internal-get-or-create-process ()
2687 "Get or create an inferior Internal Python process."
2688 (let ((proc-name (python-shell-internal-get-process-name)))
2689 (if (process-live-p proc-name
)
2690 (get-process proc-name
)
2691 (run-python-internal))))
2693 (define-obsolete-function-alias
2694 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2696 (define-obsolete-variable-alias
2697 'python-buffer
'python-shell-internal-buffer
"24.3")
2699 (define-obsolete-variable-alias
2700 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2702 (defun python-shell--save-temp-file (string)
2703 (let* ((temporary-file-directory
2704 (if (file-remote-p default-directory
)
2705 (concat (file-remote-p default-directory
) "/tmp")
2706 temporary-file-directory
))
2707 (temp-file-name (make-temp-file "py"))
2708 (coding-system-for-write (python-info-encoding)))
2709 (with-temp-file temp-file-name
2711 (delete-trailing-whitespace))
2714 (defun python-shell-send-string (string &optional process msg
)
2715 "Send STRING to inferior Python PROCESS.
2716 When optional argument MSG is non-nil, forces display of a
2717 user-friendly message if there's no process running; defaults to
2718 t when called interactively."
2720 (list (read-string "Python command: ") nil t
))
2721 (let ((process (or process
(python-shell-get-process-or-error msg
))))
2722 (if (string-match ".\n+." string
) ;Multiline.
2723 (let* ((temp-file-name (python-shell--save-temp-file string
))
2724 (file-name (or (buffer-file-name) temp-file-name
)))
2725 (python-shell-send-file file-name process temp-file-name t
))
2726 (comint-send-string process string
)
2727 (when (or (not (string-match "\n\\'" string
))
2728 (string-match "\n[ \t].*\n?\\'" string
))
2729 (comint-send-string process
"\n")))))
2731 (defvar python-shell-output-filter-in-progress nil
)
2732 (defvar python-shell-output-filter-buffer nil
)
2734 (defun python-shell-output-filter (string)
2735 "Filter used in `python-shell-send-string-no-output' to grab output.
2736 STRING is the output received to this point from the process.
2737 This filter saves received output from the process in
2738 `python-shell-output-filter-buffer' and stops receiving it after
2739 detecting a prompt at the end of the buffer."
2741 string
(ansi-color-filter-apply string
)
2742 python-shell-output-filter-buffer
2743 (concat python-shell-output-filter-buffer string
))
2744 (when (python-shell-comint-end-of-output-p
2745 python-shell-output-filter-buffer
)
2746 ;; Output ends when `python-shell-output-filter-buffer' contains
2747 ;; the prompt attached at the end of it.
2748 (setq python-shell-output-filter-in-progress nil
2749 python-shell-output-filter-buffer
2750 (substring python-shell-output-filter-buffer
2751 0 (match-beginning 0)))
2753 python-shell--prompt-calculated-output-regexp
2754 python-shell-output-filter-buffer
)
2755 ;; Some shells, like IPython might append a prompt before the
2756 ;; output, clean that.
2757 (setq python-shell-output-filter-buffer
2758 (substring python-shell-output-filter-buffer
(match-end 0)))))
2761 (defun python-shell-send-string-no-output (string &optional process
)
2762 "Send STRING to PROCESS and inhibit output.
2764 (let ((process (or process
(python-shell-get-process-or-error)))
2765 (comint-preoutput-filter-functions
2766 '(python-shell-output-filter))
2767 (python-shell-output-filter-in-progress t
)
2771 (python-shell-send-string string process
)
2772 (while python-shell-output-filter-in-progress
2773 ;; `python-shell-output-filter' takes care of setting
2774 ;; `python-shell-output-filter-in-progress' to NIL after it
2775 ;; detects end of output.
2776 (accept-process-output process
))
2778 python-shell-output-filter-buffer
2779 (setq python-shell-output-filter-buffer nil
)))
2780 (with-current-buffer (process-buffer process
)
2781 (comint-interrupt-subjob)))))
2783 (defun python-shell-internal-send-string (string)
2784 "Send STRING to the Internal Python interpreter.
2785 Returns the output. See `python-shell-send-string-no-output'."
2786 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2787 ;; updated to support this new mode.
2788 (setq python-shell-internal-last-output
2789 (python-shell-send-string-no-output
2790 ;; Makes this function compatible with the old
2791 ;; python-send-receive. (At least for CEDET).
2792 (replace-regexp-in-string "_emacs_out +" "" string
)
2793 (python-shell-internal-get-or-create-process))))
2795 (define-obsolete-function-alias
2796 'python-send-receive
'python-shell-internal-send-string
"24.3")
2798 (define-obsolete-function-alias
2799 'python-send-string
'python-shell-internal-send-string
"24.3")
2801 (defun python-shell-buffer-substring (start end
&optional nomain
)
2802 "Send buffer substring from START to END formatted for shell.
2803 This is a wrapper over `buffer-substring' that takes care of
2804 different transformations for the code sent to be evaluated in
2806 1. When optional argument NOMAIN is non-nil everything under an
2807 \"if __name__ == '__main__'\" block will be removed.
2808 2. When a subregion of the buffer is sent, it takes care of
2809 appending extra empty lines so tracebacks are correct.
2810 3. When the region sent is a substring of the current buffer, a
2811 coding cookie is added.
2812 4. Wraps indented regions under an \"if True:\" block so the
2813 interpreter evaluates them correctly."
2814 (let* ((substring (buffer-substring-no-properties start end
))
2815 (starts-at-point-min-p (save-restriction
2817 (= (point-min) start
)))
2818 (encoding (python-info-encoding))
2819 (fillstr (when (not starts-at-point-min-p
)
2821 (format "# -*- coding: %s -*-\n" encoding
)
2823 ;; Subtract 2 because of the coding cookie.
2824 (- (line-number-at-pos start
) 2) ?
\n))))
2825 (toplevel-block-p (save-excursion
2827 (or (zerop (line-number-at-pos start
))
2829 (python-util-forward-comment 1)
2830 (zerop (current-indentation)))))))
2833 (if fillstr
(insert fillstr
))
2835 (goto-char (point-min))
2836 (when (not toplevel-block-p
)
2838 (delete-region (point) (line-end-position)))
2840 (let* ((if-name-main-start-end
2843 (when (python-nav-if-name-main)
2845 (progn (python-nav-forward-sexp-safe)
2846 ;; Include ending newline
2849 ;; Oh destructuring bind, how I miss you.
2850 (if-name-main-start (car if-name-main-start-end
))
2851 (if-name-main-end (cdr if-name-main-start-end
))
2852 (fillstr (make-string
2853 (- (line-number-at-pos if-name-main-end
)
2854 (line-number-at-pos if-name-main-start
)) ?
\n)))
2855 (when if-name-main-start-end
2856 (goto-char if-name-main-start
)
2857 (delete-region if-name-main-start if-name-main-end
)
2859 ;; Ensure there's only one coding cookie in the generated string.
2860 (goto-char (point-min))
2861 (when (looking-at-p (python-rx coding-cookie
))
2863 (when (looking-at-p (python-rx coding-cookie
))
2865 (line-beginning-position) (line-end-position))))
2866 (buffer-substring-no-properties (point-min) (point-max)))))
2868 (defun python-shell-send-region (start end
&optional send-main msg
)
2869 "Send the region delimited by START and END to inferior Python process.
2870 When optional argument SEND-MAIN is non-nil, allow execution of
2871 code inside blocks delimited by \"if __name__== '__main__':\".
2872 When called interactively SEND-MAIN defaults to nil, unless it's
2873 called with prefix argument. When optional argument MSG is
2874 non-nil, forces display of a user-friendly message if there's no
2875 process running; defaults to t when called interactively."
2877 (list (region-beginning) (region-end) current-prefix-arg t
))
2878 (let* ((string (python-shell-buffer-substring start end
(not send-main
)))
2879 (process (python-shell-get-process-or-error msg
))
2880 (original-string (buffer-substring-no-properties start end
))
2881 (_ (string-match "\\`\n*\\(.*\\)" original-string
)))
2882 (message "Sent: %s..." (match-string 1 original-string
))
2883 (python-shell-send-string string process
)))
2885 (defun python-shell-send-buffer (&optional send-main msg
)
2886 "Send the entire buffer to inferior Python process.
2887 When optional argument SEND-MAIN is non-nil, allow execution of
2888 code inside blocks delimited by \"if __name__== '__main__':\".
2889 When called interactively SEND-MAIN defaults to nil, unless it's
2890 called with prefix argument. When optional argument MSG is
2891 non-nil, forces display of a user-friendly message if there's no
2892 process running; defaults to t when called interactively."
2893 (interactive (list current-prefix-arg t
))
2896 (python-shell-send-region (point-min) (point-max) send-main msg
)))
2898 (defun python-shell-send-defun (&optional arg msg
)
2899 "Send the current defun to inferior Python process.
2900 When argument ARG is non-nil do not include decorators. When
2901 optional argument MSG is non-nil, forces display of a
2902 user-friendly message if there's no process running; defaults to
2903 t when called interactively."
2904 (interactive (list current-prefix-arg t
))
2906 (python-shell-send-region
2909 (while (and (or (python-nav-beginning-of-defun)
2910 (beginning-of-line 1))
2911 (> (current-indentation) 0)))
2913 (while (and (forward-line -
1)
2914 (looking-at (python-rx decorator
))))
2918 (or (python-nav-end-of-defun)
2924 (defun python-shell-send-file (file-name &optional process temp-file-name
2926 "Send FILE-NAME to inferior Python PROCESS.
2927 If TEMP-FILE-NAME is passed then that file is used for processing
2928 instead, while internally the shell will continue to use
2929 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
2930 TEMP-FILE-NAME is deleted after evaluation is performed. When
2931 optional argument MSG is non-nil, forces display of a
2932 user-friendly message if there's no process running; defaults to
2933 t when called interactively."
2936 (read-file-name "File to send: ") ; file-name
2938 nil
; temp-file-name
2941 (let* ((process (or process
(python-shell-get-process-or-error msg
)))
2942 (encoding (with-temp-buffer
2943 (insert-file-contents
2944 (or temp-file-name file-name
))
2945 (python-info-encoding)))
2946 (file-name (expand-file-name
2947 (or (file-remote-p file-name
'localname
)
2949 (temp-file-name (when temp-file-name
2951 (or (file-remote-p temp-file-name
'localname
)
2953 (python-shell-send-string
2956 "import codecs, os;"
2957 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
2958 "__code = __pyfile.read().encode('''%s''');"
2960 (when (and delete temp-file-name
)
2961 (format "os.remove('''%s''');" temp-file-name
))
2962 "exec(compile(__code, '''%s''', 'exec'));")
2963 (or temp-file-name file-name
) encoding encoding file-name
)
2966 (defun python-shell-switch-to-shell (&optional msg
)
2967 "Switch to inferior Python process buffer.
2968 When optional argument MSG is non-nil, forces display of a
2969 user-friendly message if there's no process running; defaults to
2970 t when called interactively."
2973 (process-buffer (python-shell-get-process-or-error msg
)) nil t
))
2975 (defun python-shell-send-setup-code ()
2976 "Send all setup code for shell.
2977 This function takes the list of setup code to send from the
2978 `python-shell-setup-codes' list."
2979 (let ((process (python-shell-get-process))
2983 (cond ((stringp elt
) elt
)
2984 ((symbolp elt
) (symbol-value elt
))
2986 python-shell-setup-codes
2988 "\n\nprint ('python.el: sent setup code')")))
2989 (python-shell-send-string code process
)
2990 (python-shell-accept-process-output process
)))
2992 (add-hook 'inferior-python-mode-hook
2993 #'python-shell-send-setup-code
)
2996 ;;; Shell completion
2998 (defcustom python-shell-completion-setup-code
3002 def __PYTHON_EL_get_completions(text):
3005 def __PYTHON_EL_get_completions(text):
3010 import builtins as __builtin__
3011 builtins = dir(__builtin__)
3013 is_ipython = ('__IPYTHON__' in builtins or
3014 '__IPYTHON__active' in builtins)
3015 splits = text.split()
3016 is_module = splits and splits[0] in ('from', 'import')
3018 if is_ipython and is_module:
3019 from IPython.core.completerlib import module_completion
3020 completions = module_completion(text.strip())
3021 elif is_ipython and '__IP' in builtins:
3022 completions = __IP.complete(text)
3023 elif is_ipython and 'get_ipython' in builtins:
3024 completions = get_ipython().Completer.all_completions(text)
3026 # Try to reuse current completer.
3027 completer = readline.get_completer()
3029 # importing rlcompleter sets the completer, use it as a
3030 # last resort to avoid breaking customizations.
3032 completer = readline.get_completer()
3035 completion = completer(text, i)
3039 completions.append(completion)
3043 "Code used to setup completion in inferior Python processes."
3047 (defcustom python-shell-completion-string-code
3048 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3049 "Python code used to get a string of completions separated by semicolons.
3050 The string passed to the function is the current python name or
3051 the full statement in the case of imports."
3055 (define-obsolete-variable-alias
3056 'python-shell-completion-module-string-code
3057 'python-shell-completion-string-code
3059 "Completion string code must also autocomplete modules.")
3061 (define-obsolete-variable-alias
3062 'python-shell-completion-pdb-string-code
3063 'python-shell-completion-string-code
3065 "Completion string code must work for (i)pdb.")
3067 (defcustom python-shell-completion-native-disabled-interpreters
3068 ;; PyPy's readline cannot handle some escape sequences yet.
3070 "List of disabled interpreters.
3071 When a match is found, native completion is disabled."
3072 :type
'(repeat string
))
3074 (defcustom python-shell-completion-native-enable t
3075 "Enable readline based native completion."
3078 (defcustom python-shell-completion-native-output-timeout
5.0
3079 "Time in seconds to wait for completion output before giving up."
3082 (defcustom python-shell-completion-native-try-output-timeout
1.0
3083 "Time in seconds to wait for *trying* native completion output."
3086 (defvar python-shell-completion-native-redirect-buffer
3087 " *Python completions redirect*"
3088 "Buffer to be used to redirect output of readline commands.")
3090 (defun python-shell-completion-native-interpreter-disabled-p ()
3091 "Return non-nil if interpreter has native completion disabled."
3092 (when python-shell-completion-native-disabled-interpreters
3094 (regexp-opt python-shell-completion-native-disabled-interpreters
)
3095 (file-name-nondirectory python-shell-interpreter
))))
3097 (defun python-shell-completion-native-try ()
3098 "Return non-nil if can trigger native completion."
3099 (let ((python-shell-completion-native-enable t
)
3100 (python-shell-completion-native-output-timeout
3101 python-shell-completion-native-try-output-timeout
))
3102 (python-shell-completion-native-get-completions
3103 (get-buffer-process (current-buffer))
3106 (defun python-shell-completion-native-setup ()
3107 "Try to setup native completion, return non-nil on success."
3108 (let ((process (python-shell-get-process)))
3109 (python-shell-send-string "
3110 def __PYTHON_EL_native_completion_setup():
3117 import builtins as __builtin__
3118 builtins = dir(__builtin__)
3119 is_ipython = ('__IPYTHON__' in builtins or
3120 '__IPYTHON__active' in builtins)
3121 class __PYTHON_EL_Completer:
3122 PYTHON_EL_WRAPPED = True
3123 def __init__(self, completer):
3124 self.completer = completer
3125 self.last_completion = None
3126 def __call__(self, text, state):
3128 # The first completion is always a dummy completion. This
3129 # ensures proper output for sole completions and a current
3130 # input safeguard when no completions are available.
3131 self.last_completion = None
3132 completion = '0__dummy_completion__'
3134 completion = self.completer(text, state - 1)
3137 # When no completions are available, two non-sharing
3138 # prefix strings are returned just to ensure output
3139 # while preventing changes to current input.
3140 completion = '1__dummy_completion__'
3141 elif self.last_completion != '~~~~__dummy_completion__':
3142 # This marks the end of output.
3143 completion = '~~~~__dummy_completion__'
3144 elif completion.endswith('('):
3145 # Remove parens on callables as it breaks completion on
3146 # arguments (e.g. str(Ari<tab>)).
3147 completion = completion[:-1]
3148 self.last_completion = completion
3150 completer = readline.get_completer()
3152 # Used as last resort to avoid breaking customizations.
3154 completer = readline.get_completer()
3155 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3156 # Wrap the existing completer function only once.
3157 new_completer = __PYTHON_EL_Completer(completer)
3159 readline.set_completer(new_completer)
3161 # IPython hacks readline such that `readline.set_completer`
3162 # won't work. This workaround injects the new completer
3163 # function into the existing instance directly.
3164 instance = getattr(completer, 'im_self', completer.__self__)
3165 instance.rlcomplete = new_completer
3166 if readline.__doc__ and 'libedit' in readline.__doc__:
3167 readline.parse_and_bind('bind ^I rl_complete')
3169 readline.parse_and_bind('tab: complete')
3170 # Require just one tab to send output.
3171 readline.parse_and_bind('set show-all-if-ambiguous on')
3172 print ('python.el: readline is available')
3174 print ('python.el: readline not available')
3175 __PYTHON_EL_native_completion_setup()"
3177 (python-shell-accept-process-output process
)
3178 (when (save-excursion
3180 (regexp-quote "python.el: readline is available") nil t
1))
3181 (python-shell-completion-native-try))))
3183 (defun python-shell-completion-native-turn-off (&optional msg
)
3184 "Turn off shell native completions.
3185 With argument MSG show deactivation message."
3187 (python-shell-with-shell-buffer
3188 (set (make-local-variable 'python-shell-completion-native-enable
) nil
)
3190 (message "Shell native completion is disabled, using fallback"))))
3192 (defun python-shell-completion-native-turn-on (&optional msg
)
3193 "Turn on shell native completions.
3194 With argument MSG show deactivation message."
3196 (python-shell-with-shell-buffer
3197 (set (make-local-variable 'python-shell-completion-native-enable
) t
)
3198 (python-shell-completion-native-turn-on-maybe msg
)))
3200 (defun python-shell-completion-native-turn-on-maybe (&optional msg
)
3201 "Turn on native completions if enabled and available.
3202 With argument MSG show activation/deactivation message."
3204 (python-shell-with-shell-buffer
3205 (when python-shell-completion-native-enable
3207 ((python-shell-completion-native-interpreter-disabled-p)
3208 (python-shell-completion-native-turn-off msg
))
3209 ((python-shell-completion-native-setup)
3211 (message "Shell native completion is enabled.")))
3213 '(python python-shell-completion-native-turn-on-maybe
)
3216 "Your `python-shell-interpreter' doesn't seem to "
3217 "support readline, yet `python-shell-completion-native' "
3218 (format "was `t' and %S is not part of the "
3219 (file-name-nondirectory python-shell-interpreter
))
3220 "`python-shell-completion-native-disabled-interpreters' "
3221 "list. Native completions have been disabled locally. "))
3222 (python-shell-completion-native-turn-off msg
))))))
3224 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3225 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3226 (python-shell-completion-native-turn-on-maybe t
))
3228 (add-hook 'inferior-python-mode-hook
3229 #'python-shell-completion-native-turn-on-maybe-with-msg
)
3231 (defun python-shell-completion-native-toggle (&optional msg
)
3232 "Toggle shell native completion.
3233 With argument MSG show activation/deactivation message."
3235 (python-shell-with-shell-buffer
3236 (if python-shell-completion-native-enable
3237 (python-shell-completion-native-turn-off msg
)
3238 (python-shell-completion-native-turn-on msg
))
3239 python-shell-completion-native-enable
))
3241 (defun python-shell-completion-native-get-completions (process import input
)
3242 "Get completions using native readline for PROCESS.
3243 When IMPORT is non-nil takes precedence over INPUT for
3245 (with-current-buffer (process-buffer process
)
3246 (when (and python-shell-completion-native-enable
3247 (python-util-comint-last-prompt)
3248 (>= (point) (cdr (python-util-comint-last-prompt))))
3249 (let* ((input (or import input
))
3250 (original-filter-fn (process-filter process
))
3251 (redirect-buffer (get-buffer-create
3252 python-shell-completion-native-redirect-buffer
))
3253 (separators (python-rx (or whitespace open-paren close-paren
)))
3255 (new-input (concat input trigger
))
3258 (+ (- (point-max) (comint-bol)) (length new-input
))))
3259 (delete-line-command (make-string input-length ?
\b))
3260 (input-to-send (concat new-input delete-line-command
)))
3261 ;; Ensure restoring the process filter, even if the user quits
3262 ;; or there's some other error.
3264 (with-current-buffer redirect-buffer
3265 ;; Cleanup the redirect buffer
3266 (delete-region (point-min) (point-max))
3267 ;; Mimic `comint-redirect-send-command', unfortunately it
3268 ;; can't be used here because it expects a newline in the
3269 ;; command and that's exactly what we are trying to avoid.
3270 (let ((comint-redirect-echo-input nil
)
3271 (comint-redirect-verbose nil
)
3272 (comint-redirect-perform-sanity-check nil
)
3273 (comint-redirect-insert-matching-regexp nil
)
3274 ;; Feed it some regex that will never match.
3275 (comint-redirect-finished-regexp "^\\'$")
3276 (comint-redirect-output-buffer redirect-buffer
)
3277 (current-time (float-time)))
3278 ;; Compatibility with Emacs 24.x. Comint changed and
3279 ;; now `comint-redirect-filter' gets 3 args. This
3280 ;; checks which version of `comint-redirect-filter' is
3281 ;; in use based on its args and uses `apply-partially'
3282 ;; to make it up for the 3 args case.
3284 (help-function-arglist 'comint-redirect-filter
)) 3)
3286 process
(apply-partially
3287 #'comint-redirect-filter original-filter-fn
))
3288 (set-process-filter process
#'comint-redirect-filter
))
3289 (process-send-string process input-to-send
)
3290 ;; Grab output until our dummy completion used as
3291 ;; output end marker is found. Output is accepted
3292 ;; *very* quickly to keep the shell super-responsive.
3293 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t
))
3294 (< (- current-time
(float-time))
3295 python-shell-completion-native-output-timeout
))
3296 (accept-process-output process
0.01))
3297 (cl-remove-duplicates
3300 (string-match "__dummy_completion__" c
))
3302 (buffer-substring-no-properties
3303 (point-min) (point-max))
3306 (set-process-filter process original-filter-fn
))))))
3308 (defun python-shell-completion-get-completions (process import input
)
3309 "Do completion at point using PROCESS for IMPORT or INPUT.
3310 When IMPORT is non-nil takes precedence over INPUT for
3312 (with-current-buffer (process-buffer process
)
3314 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3315 (buffer-substring-no-properties
3316 (car prompt-boundaries
) (cdr prompt-boundaries
))))
3318 ;; Check whether a prompt matches a pdb string, an import
3319 ;; statement or just the standard prompt and use the
3320 ;; correct python-shell-completion-*-code string
3321 (cond ((and (string-match
3322 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
3323 ;; Since there are no guarantees the user will remain
3324 ;; in the same context where completion code was sent
3325 ;; (e.g. user steps into a function), safeguard
3326 ;; resending completion setup continuously.
3327 (concat python-shell-completion-setup-code
3328 "\nprint (" python-shell-completion-string-code
")"))
3330 python-shell--prompt-calculated-input-regexp prompt
)
3331 python-shell-completion-string-code
)
3333 (subject (or import input
)))
3334 (and completion-code
3335 (> (length input
) 0)
3337 (python-util-strip-string
3338 (python-shell-send-string-no-output
3339 (format completion-code subject
) process
))))
3340 (and (> (length completions
) 2)
3341 (split-string completions
3342 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
3344 (defun python-shell-completion-at-point (&optional process
)
3345 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3346 Optional argument PROCESS forces completions to be retrieved
3347 using that one instead of current buffer's process."
3348 (setq process
(or process
(get-buffer-process (current-buffer))))
3349 (let* ((line-start (if (derived-mode-p 'inferior-python-mode
)
3350 ;; Working on a shell buffer: use prompt end.
3351 (cdr (python-util-comint-last-prompt))
3352 (line-beginning-position)))
3354 (when (string-match-p
3355 (rx (* space
) word-start
(or "from" "import") word-end space
)
3356 (buffer-substring-no-properties line-start
(point)))
3357 (buffer-substring-no-properties line-start
(point))))
3360 (if (not (re-search-backward
3362 (or whitespace open-paren close-paren string-delimiter
))
3366 (forward-char (length (match-string-no-properties 0)))
3370 (if python-shell-completion-native-enable
3371 #'python-shell-completion-native-get-completions
3372 #'python-shell-completion-get-completions
)))
3374 (completion-table-dynamic
3377 process import-statement
)))))
3379 (define-obsolete-function-alias
3380 'python-shell-completion-complete-at-point
3381 'python-shell-completion-at-point
3384 (defun python-shell-completion-complete-or-indent ()
3385 "Complete or indent depending on the context.
3386 If content before pointer is all whitespace, indent.
3387 If not try to complete."
3389 (if (string-match "^[[:space:]]*$"
3390 (buffer-substring (comint-line-beginning-position)
3392 (indent-for-tab-command)
3393 (completion-at-point)))
3396 ;;; PDB Track integration
3398 (defcustom python-pdbtrack-activate t
3399 "Non-nil makes Python shell enable pdbtracking."
3404 (defcustom python-pdbtrack-stacktrace-info-regexp
3405 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3406 "Regular expression matching stacktrace information.
3407 Used to extract the current line and module being inspected."
3412 (defvar python-pdbtrack-tracked-buffer nil
3413 "Variable containing the value of the current tracked buffer.
3414 Never set this variable directly, use
3415 `python-pdbtrack-set-tracked-buffer' instead.")
3417 (defvar python-pdbtrack-buffers-to-kill nil
3418 "List of buffers to be deleted after tracking finishes.")
3420 (defun python-pdbtrack-set-tracked-buffer (file-name)
3421 "Set the buffer for FILE-NAME as the tracked buffer.
3422 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3423 Returns the tracked buffer."
3424 (let ((file-buffer (get-file-buffer
3425 (concat (file-remote-p default-directory
)
3428 (setq python-pdbtrack-tracked-buffer file-buffer
)
3429 (setq file-buffer
(find-file-noselect file-name
))
3430 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3431 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3434 (defun python-pdbtrack-comint-output-filter-function (output)
3435 "Move overlay arrow to current pdb line in tracked buffer.
3436 Argument OUTPUT is a string with the output from the comint process."
3437 (when (and python-pdbtrack-activate
(not (string= output
"")))
3438 (let* ((full-output (ansi-color-filter-apply
3439 (buffer-substring comint-last-input-end
(point-max))))
3443 (insert full-output
)
3444 ;; When the debugger encounters a pdb.set_trace()
3445 ;; command, it prints a single stack frame. Sometimes
3446 ;; it prints a bit of extra information about the
3447 ;; arguments of the present function. When ipdb
3448 ;; encounters an exception, it prints the _entire_ stack
3449 ;; trace. To handle all of these cases, we want to find
3450 ;; the _last_ stack frame printed in the most recent
3451 ;; batch of output, then jump to the corresponding
3452 ;; file/line number.
3453 (goto-char (point-max))
3454 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3455 (setq line-number
(string-to-number
3456 (match-string-no-properties 2)))
3457 (match-string-no-properties 1)))))
3458 (if (and file-name line-number
)
3459 (let* ((tracked-buffer
3460 (python-pdbtrack-set-tracked-buffer file-name
))
3461 (shell-buffer (current-buffer))
3462 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3463 (tracked-buffer-line-pos))
3464 (with-current-buffer tracked-buffer
3465 (set (make-local-variable 'overlay-arrow-string
) "=>")
3466 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3467 (setq tracked-buffer-line-pos
(progn
3468 (goto-char (point-min))
3469 (forward-line (1- line-number
))
3471 (when tracked-buffer-window
3473 tracked-buffer-window tracked-buffer-line-pos
))
3474 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3475 (pop-to-buffer tracked-buffer
)
3476 (switch-to-buffer-other-window shell-buffer
))
3477 (when python-pdbtrack-tracked-buffer
3478 (with-current-buffer python-pdbtrack-tracked-buffer
3479 (set-marker overlay-arrow-position nil
))
3480 (mapc #'(lambda (buffer)
3481 (ignore-errors (kill-buffer buffer
)))
3482 python-pdbtrack-buffers-to-kill
)
3483 (setq python-pdbtrack-tracked-buffer nil
3484 python-pdbtrack-buffers-to-kill nil
)))))
3488 ;;; Symbol completion
3490 (defun python-completion-at-point ()
3491 "Function for `completion-at-point-functions' in `python-mode'.
3492 For this to work as best as possible you should call
3493 `python-shell-send-buffer' from time to time so context in
3494 inferior Python process is updated properly."
3495 (let ((process (python-shell-get-process)))
3497 (python-shell-completion-at-point process
))))
3499 (define-obsolete-function-alias
3500 'python-completion-complete-at-point
3501 'python-completion-at-point
3507 (defcustom python-fill-comment-function
'python-fill-comment
3508 "Function to fill comments.
3509 This is the function used by `python-fill-paragraph' to
3514 (defcustom python-fill-string-function
'python-fill-string
3515 "Function to fill strings.
3516 This is the function used by `python-fill-paragraph' to
3521 (defcustom python-fill-decorator-function
'python-fill-decorator
3522 "Function to fill decorators.
3523 This is the function used by `python-fill-paragraph' to
3528 (defcustom python-fill-paren-function
'python-fill-paren
3529 "Function to fill parens.
3530 This is the function used by `python-fill-paragraph' to
3535 (defcustom python-fill-docstring-style
'pep-257
3536 "Style used to fill docstrings.
3537 This affects `python-fill-string' behavior with regards to
3538 triple quotes positioning.
3540 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3541 `symmetric', and nil. A value of nil won't care about quotes
3542 position and will treat docstrings a normal string, any other
3543 value may result in one of the following docstring styles:
3548 Process foo, return bar.
3552 Process foo, return bar.
3554 If processing fails throw ProcessingError.
3559 \"\"\"Process foo, return bar.\"\"\"
3562 Process foo, return bar.
3564 If processing fails throw ProcessingError.
3570 \"\"\"Process foo, return bar.\"\"\"
3572 \"\"\"Process foo, return bar.
3574 If processing fails throw ProcessingError.
3580 \"\"\"Process foo, return bar.\"\"\"
3582 \"\"\"Process foo, return bar.
3584 If processing fails throw ProcessingError.
3589 \"\"\"Process foo, return bar.\"\"\"
3592 Process foo, return bar.
3594 If processing fails throw ProcessingError.
3597 (const :tag
"Don't format docstrings" nil
)
3598 (const :tag
"Django's coding standards style." django
)
3599 (const :tag
"One newline and start and Two at end style." onetwo
)
3600 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3601 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3602 (const :tag
"Symmetric style." symmetric
))
3605 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3607 (defun python-fill-paragraph (&optional justify
)
3608 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3609 If any of the current line is in or at the end of a multi-line string,
3610 fill the string or the paragraph of it that point is in, preserving
3611 the string's indentation.
3612 Optional argument JUSTIFY defines if the paragraph should be justified."
3617 ((python-syntax-context 'comment
)
3618 (funcall python-fill-comment-function justify
))
3619 ;; Strings/Docstrings
3620 ((save-excursion (or (python-syntax-context 'string
)
3621 (equal (string-to-syntax "|")
3622 (syntax-after (point)))))
3623 (funcall python-fill-string-function justify
))
3625 ((equal (char-after (save-excursion
3626 (python-nav-beginning-of-statement))) ?
@)
3627 (funcall python-fill-decorator-function justify
))
3629 ((or (python-syntax-context 'paren
)
3630 (looking-at (python-rx open-paren
))
3632 (skip-syntax-forward "^(" (line-end-position))
3633 (looking-at (python-rx open-paren
))))
3634 (funcall python-fill-paren-function justify
))
3637 (defun python-fill-comment (&optional justify
)
3638 "Comment fill function for `python-fill-paragraph'.
3639 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3640 (fill-comment-paragraph justify
))
3642 (defun python-fill-string (&optional justify
)
3643 "String fill function for `python-fill-paragraph'.
3644 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3645 (let* ((str-start-pos
3648 (or (python-syntax-context 'string
)
3649 (and (equal (string-to-syntax "|")
3650 (syntax-after (point)))
3652 (num-quotes (python-syntax-count-quotes
3653 (char-after str-start-pos
) str-start-pos
))
3656 (goto-char (+ str-start-pos num-quotes
))
3657 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3658 (goto-char (point-max)))
3661 ;; Docstring styles may vary for oneliners and multi-liners.
3662 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3664 (pcase python-fill-docstring-style
3665 ;; delimiters-style is a cons cell with the form
3666 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3667 ;; is NIL means to not add any newlines for start or end
3668 ;; of docstring. See `python-fill-docstring-style' for a
3669 ;; graphic idea of each style.
3670 (`django
(cons 1 1))
3671 (`onetwo
(and multi-line-p
(cons 1 2)))
3672 (`pep-257
(and multi-line-p
(cons nil
2)))
3673 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3674 (`symmetric
(and multi-line-p
(cons 1 1)))))
3675 (fill-paragraph-function))
3677 (narrow-to-region str-start-pos str-end-pos
)
3678 (fill-paragraph justify
))
3680 (when (and (python-info-docstring-p) python-fill-docstring-style
)
3681 ;; Add the number of newlines indicated by the selected style
3682 ;; at the start of the docstring.
3683 (goto-char (+ str-start-pos num-quotes
))
3684 (delete-region (point) (progn
3685 (skip-syntax-forward "> ")
3687 (and (car delimiters-style
)
3688 (or (newline (car delimiters-style
)) t
)
3689 ;; Indent only if a newline is added.
3690 (indent-according-to-mode))
3691 ;; Add the number of newlines indicated by the selected style
3692 ;; at the end of the docstring.
3693 (goto-char (if (not (= str-end-pos
(point-max)))
3694 (- str-end-pos num-quotes
)
3696 (delete-region (point) (progn
3697 (skip-syntax-backward "> ")
3699 (and (cdr delimiters-style
)
3700 ;; Add newlines only if string ends.
3701 (not (= str-end-pos
(point-max)))
3702 (or (newline (cdr delimiters-style
)) t
)
3703 ;; Again indent only if a newline is added.
3704 (indent-according-to-mode))))) t
)
3706 (defun python-fill-decorator (&optional _justify
)
3707 "Decorator fill function for `python-fill-paragraph'.
3708 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3711 (defun python-fill-paren (&optional justify
)
3712 "Paren fill function for `python-fill-paragraph'.
3713 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3715 (narrow-to-region (progn
3716 (while (python-syntax-context 'paren
)
3717 (goto-char (1- (point))))
3718 (line-beginning-position))
3720 (when (not (python-syntax-context 'paren
))
3722 (when (not (python-syntax-context 'paren
))
3723 (skip-syntax-backward "^)")))
3724 (while (and (python-syntax-context 'paren
)
3726 (goto-char (1+ (point))))
3728 (let ((paragraph-start "\f\\|[ \t]*$")
3729 (paragraph-separate ",")
3730 (fill-paragraph-function))
3731 (goto-char (point-min))
3732 (fill-paragraph justify
))
3735 (python-indent-line)
3736 (goto-char (line-end-position))))
3742 (defcustom python-skeleton-autoinsert nil
3743 "Non-nil means template skeletons will be automagically inserted.
3744 This happens when pressing \"if<SPACE>\", for example, to prompt for
3750 (define-obsolete-variable-alias
3751 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3753 (defvar python-skeleton-available
'()
3754 "Internal list of available skeletons.")
3756 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3757 "Abbrev table for Python mode skeletons."
3759 ;; Allow / inside abbrevs.
3760 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3761 ;; Only expand in code.
3762 :enable-function
(lambda ()
3764 (not (python-syntax-comment-or-string-p))
3765 python-skeleton-autoinsert
)))
3767 (defmacro python-skeleton-define
(name doc
&rest skel
)
3768 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3769 The skeleton will be bound to python-skeleton-NAME and will
3770 be added to `python-mode-skeleton-abbrev-table'."
3771 (declare (indent 2))
3772 (let* ((name (symbol-name name
))
3773 (function-name (intern (concat "python-skeleton-" name
))))
3775 (define-abbrev python-mode-skeleton-abbrev-table
3776 ,name
"" ',function-name
:system t
)
3777 (setq python-skeleton-available
3778 (cons ',function-name python-skeleton-available
))
3779 (define-skeleton ,function-name
3781 (format "Insert %s statement." name
))
3784 (define-abbrev-table 'python-mode-abbrev-table
()
3785 "Abbrev table for Python mode."
3786 :parents
(list python-mode-skeleton-abbrev-table
))
3788 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3789 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3790 The skeleton will be bound to python-skeleton-NAME."
3791 (declare (indent 2))
3792 (let* ((name (symbol-name name
))
3793 (function-name (intern (concat "python-skeleton--" name
)))
3795 "Add '%s' clause? " name
)))
3798 `(< ,(format "%s:" name
) \n \n
3800 `(define-skeleton ,function-name
3802 (format "Auxiliary skeleton for %s statement." name
))
3804 (unless (y-or-n-p ,msg
)
3808 (python-define-auxiliary-skeleton else nil
)
3810 (python-define-auxiliary-skeleton except nil
)
3812 (python-define-auxiliary-skeleton finally nil
)
3814 (python-skeleton-define if nil
3818 ("other condition, %s: "
3822 '(python-skeleton--else) | ^
)
3824 (python-skeleton-define while nil
3828 '(python-skeleton--else) | ^
)
3830 (python-skeleton-define for nil
3834 '(python-skeleton--else) | ^
)
3836 (python-skeleton-define import nil
3837 "Import from module: "
3838 "from " str
& " " | -
5
3840 ("Identifier: " str
", ") -
2 \n _
)
3842 (python-skeleton-define try nil
3848 "except " str
":" \n
3851 '(python-skeleton--except)
3852 '(python-skeleton--else)
3853 '(python-skeleton--finally) | ^
)
3855 (python-skeleton-define def nil
3857 "def " str
"(" ("Parameter, %s: "
3858 (unless (equal ?\
( (char-before)) ", ")
3860 "\"\"\"" -
"\"\"\"" \n
3863 (python-skeleton-define class nil
3865 "class " str
"(" ("Inheritance, %s: "
3866 (unless (equal ?\
( (char-before)) ", ")
3870 "\"\"\"" -
"\"\"\"" \n
3873 (defun python-skeleton-add-menu-items ()
3874 "Add menu items to Python->Skeletons menu."
3875 (let ((skeletons (sort python-skeleton-available
'string
<)))
3876 (dolist (skeleton skeletons
)
3878 nil
'("Python" "Skeletons")
3880 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3885 (defcustom python-ffap-setup-code
3886 "def __FFAP_get_module_path(module):
3889 path = __import__(module).__file__
3890 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3895 "Python code to get a module path."
3899 (defcustom python-ffap-string-code
3900 "__FFAP_get_module_path('''%s''')\n"
3901 "Python code used to get a string with the path of a module."
3905 (defun python-ffap-module-path (module)
3906 "Function for `ffap-alist' to return path for MODULE."
3908 (and (derived-mode-p 'inferior-python-mode
)
3909 (get-buffer-process (current-buffer)))
3910 (python-shell-get-process))))
3914 (python-shell-send-string-no-output
3915 (format python-ffap-string-code module
) process
)))
3917 (substring-no-properties module-file
1 -
1))))))
3921 (eval-after-load "ffap"
3923 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3924 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3929 (defcustom python-check-command
3930 (or (executable-find "pyflakes")
3931 (executable-find "epylint")
3932 "install pyflakes, pylint or something else")
3933 "Command used to check a Python file."
3937 (defcustom python-check-buffer-name
3938 "*Python check: %s*"
3939 "Buffer name used for check commands."
3943 (defvar python-check-custom-command nil
3945 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
3946 (make-variable-buffer-local 'python-check-custom-command
)
3948 (defun python-check (command)
3949 "Check a Python file (default current buffer's file).
3950 Runs COMMAND, a shell command, as if by `compile'.
3951 See `python-check-command' for the default."
3953 (list (read-string "Check command: "
3954 (or python-check-custom-command
3955 (concat python-check-command
" "
3956 (shell-quote-argument
3958 (let ((name (buffer-file-name)))
3960 (file-name-nondirectory name
)))
3962 (setq python-check-custom-command command
)
3963 (save-some-buffers (not compilation-ask-about-save
) nil
)
3964 (let ((process-environment (python-shell-calculate-process-environment))
3965 (exec-path (python-shell-calculate-exec-path)))
3966 (compilation-start command nil
3968 (format python-check-buffer-name command
)))))
3973 (defcustom python-eldoc-setup-code
3974 "def __PYDOC_get_help(obj):
3978 str_type = basestring
3981 if isinstance(obj, str_type):
3982 obj = eval(obj, globals())
3983 doc = inspect.getdoc(obj)
3984 if not doc and callable(obj):
3986 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3987 target = obj.__init__
3993 args = inspect.formatargspec(
3994 *inspect.getargspec(target)
3997 doc = '{objtype} {name}{args}'.format(
3998 objtype=objtype, name=name, args=args
4001 doc = doc.splitlines()[0]
4005 "Python code to setup documentation retrieval."
4009 (defcustom python-eldoc-string-code
4010 "__PYDOC_get_help('''%s''')\n"
4011 "Python code used to get a string with the documentation of an object."
4015 (defun python-eldoc--get-symbol-at-point ()
4016 "Get the current symbol for eldoc.
4017 Returns the current symbol handling point within arguments."
4019 (let ((start (python-syntax-context 'paren
)))
4024 (memq (char-syntax (char-after)) '(?\ ?-
)))
4025 ;; Try to adjust to closest symbol if not in one.
4026 (python-util-forward-comment -
1)))
4027 (python-info-current-symbol t
)))
4029 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
4030 "Internal implementation to get documentation at point.
4031 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4032 returns will be used. If not FORCE-PROCESS is passed what
4033 `python-shell-get-process' returns is used."
4034 (let ((process (or force-process
(python-shell-get-process))))
4036 (let ((input (or force-input
4037 (python-eldoc--get-symbol-at-point))))
4039 ;; Prevent resizing the echo area when iPython is
4040 ;; enabled. Bug#18794.
4041 (python-util-strip-string
4042 (python-shell-send-string-no-output
4043 (format python-eldoc-string-code input
)
4046 (defun python-eldoc-function ()
4047 "`eldoc-documentation-function' for Python.
4048 For this to work as best as possible you should call
4049 `python-shell-send-buffer' from time to time so context in
4050 inferior Python process is updated properly."
4051 (python-eldoc--get-doc-at-point))
4053 (defun python-eldoc-at-point (symbol)
4054 "Get help on SYMBOL using `help'.
4055 Interactively, prompt for symbol."
4057 (let ((symbol (python-eldoc--get-symbol-at-point))
4058 (enable-recursive-minibuffers t
))
4059 (list (read-string (if symbol
4060 (format "Describe symbol (default %s): " symbol
)
4061 "Describe symbol: ")
4063 (message (python-eldoc--get-doc-at-point symbol
)))
4068 (defun python-hideshow-forward-sexp-function (arg)
4069 "Python specific `forward-sexp' function for `hs-minor-mode'.
4070 Argument ARG is ignored."
4071 arg
; Shut up, byte compiler.
4072 (python-nav-end-of-defun)
4073 (unless (python-info-current-line-empty-p)
4079 (defvar python-imenu-format-item-label-function
4080 'python-imenu-format-item-label
4081 "Imenu function used to format an item label.
4082 It must be a function with two arguments: TYPE and NAME.")
4084 (defvar python-imenu-format-parent-item-label-function
4085 'python-imenu-format-parent-item-label
4086 "Imenu function used to format a parent item label.
4087 It must be a function with two arguments: TYPE and NAME.")
4089 (defvar python-imenu-format-parent-item-jump-label-function
4090 'python-imenu-format-parent-item-jump-label
4091 "Imenu function used to format a parent jump item label.
4092 It must be a function with two arguments: TYPE and NAME.")
4094 (defun python-imenu-format-item-label (type name
)
4095 "Return Imenu label for single node using TYPE and NAME."
4096 (format "%s (%s)" name type
))
4098 (defun python-imenu-format-parent-item-label (type name
)
4099 "Return Imenu label for parent node using TYPE and NAME."
4100 (format "%s..." (python-imenu-format-item-label type name
)))
4102 (defun python-imenu-format-parent-item-jump-label (type _name
)
4103 "Return Imenu label for parent node jump using TYPE and NAME."
4104 (if (string= type
"class")
4105 "*class definition*"
4106 "*function definition*"))
4108 (defun python-imenu--put-parent (type name pos tree
)
4109 "Add the parent with TYPE, NAME and POS to TREE."
4111 (funcall python-imenu-format-item-label-function type name
))
4113 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
4116 (cons label
(cons (cons jump-label pos
) tree
)))))
4118 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
4119 "Recursively build the tree of nested definitions of a node.
4120 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4121 not be passed explicitly unless you know what you are doing."
4122 (setq min-indent
(or min-indent
0)
4123 prev-indent
(or prev-indent python-indent-offset
))
4124 (let* ((pos (python-nav-backward-defun))
4126 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
4127 (let ((split (split-string (match-string-no-properties 0))))
4128 (setq type
(car split
))
4131 (funcall python-imenu-format-item-label-function type name
)))
4132 (indent (current-indentation))
4133 (children-indent-limit (+ python-indent-offset min-indent
)))
4135 ;; Nothing found, probably near to bobp.
4137 ((<= indent min-indent
)
4138 ;; The current indentation points that this is a parent
4139 ;; node, add it to the tree and stop recursing.
4140 (python-imenu--put-parent type name pos tree
))
4142 (python-imenu--build-tree
4145 (if (<= indent children-indent-limit
)
4146 ;; This lies within the children indent offset range,
4147 ;; so it's a normal child of its parent (i.e., not
4148 ;; a child of a child).
4149 (cons (cons label pos
) tree
)
4150 ;; Oh no, a child of a child?! Fear not, we
4151 ;; know how to roll. We recursively parse these by
4152 ;; swapping prev-indent and min-indent plus adding this
4153 ;; newly found item to a fresh subtree. This works, I
4156 (python-imenu--build-tree
4157 prev-indent indent
(list (cons label pos
)))
4160 (defun python-imenu-create-index ()
4161 "Return tree Imenu alist for the current Python buffer.
4162 Change `python-imenu-format-item-label-function',
4163 `python-imenu-format-parent-item-label-function',
4164 `python-imenu-format-parent-item-jump-label-function' to
4165 customize how labels are formatted."
4166 (goto-char (point-max))
4169 (while (setq tree
(python-imenu--build-tree))
4170 (setq index
(cons tree index
)))
4173 (defun python-imenu-create-flat-index (&optional alist prefix
)
4174 "Return flat outline of the current Python buffer for Imenu.
4175 Optional argument ALIST is the tree to be flattened; when nil
4176 `python-imenu-build-index' is used with
4177 `python-imenu-format-parent-item-jump-label-function'
4178 `python-imenu-format-parent-item-label-function'
4179 `python-imenu-format-item-label-function' set to
4180 (lambda (type name) name)
4181 Optional argument PREFIX is used in recursive calls and should
4182 not be passed explicitly.
4189 (\"decorator\" . 173)
4192 (\"wrapped_f\" . 393))))
4198 (\"decorator\" . 173)
4199 (\"decorator.wrap\" . 353)
4200 (\"decorator.wrapped_f\" . 393))"
4201 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4206 (let ((name (if prefix
4207 (concat prefix
"." (car item
))
4210 (cond ((or (numberp pos
) (markerp pos
))
4211 (list (cons name pos
)))
4214 (cons name
(cdar pos
))
4215 (python-imenu-create-flat-index (cddr item
) name
))))))
4217 (let* ((fn (lambda (_type name
) name
))
4218 (python-imenu-format-item-label-function fn
)
4219 (python-imenu-format-parent-item-label-function fn
)
4220 (python-imenu-format-parent-item-jump-label-function fn
))
4221 (python-imenu-create-index))))))
4226 (defun python-info-current-defun (&optional include-type
)
4227 "Return name of surrounding function with Python compatible dotty syntax.
4228 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4229 This function can be used as the value of `add-log-current-defun-function'
4230 since it returns nil if point is not inside a defun."
4236 (starting-indentation (current-indentation))
4237 (starting-pos (point))
4242 (while (python-nav-beginning-of-defun 1)
4243 (when (save-match-data
4245 (or (not last-indent
)
4246 (< (current-indentation) last-indent
))
4250 ;; If this is the first run, we may add
4251 ;; the current defun at point.
4252 (setq first-run nil
)
4253 (goto-char starting-pos
)
4254 (python-nav-beginning-of-statement)
4255 (beginning-of-line 1)
4257 python-nav-beginning-of-defun-regexp
)))
4261 (+ (current-indentation)
4262 python-indent-offset
)))
4263 (if (< starting-indentation min-indent
)
4264 ;; If the starting indentation is not
4265 ;; within the min defun indent make the
4268 ;; Else go to the end of defun and add
4269 ;; up the current indentation to the
4271 (python-nav-end-of-defun)
4273 (if (>= (current-indentation) min-indent
)
4274 (1+ (current-indentation))
4276 (save-match-data (setq last-indent
(current-indentation)))
4277 (if (or (not include-type
) type
)
4278 (setq names
(cons (match-string-no-properties 1) names
))
4279 (let ((match (split-string (match-string-no-properties 0))))
4280 (setq type
(car match
))
4281 (setq names
(cons (cadr match
) names
)))))
4282 ;; Stop searching ASAP.
4283 (and (= (current-indentation) 0) (throw 'exit t
))))
4285 (concat (and type
(format "%s " type
))
4286 (mapconcat 'identity names
".")))))))
4288 (defun python-info-current-symbol (&optional replace-self
)
4289 "Return current symbol using dotty syntax.
4290 With optional argument REPLACE-SELF convert \"self\" to current
4293 (and (not (python-syntax-comment-or-string-p))
4294 (with-syntax-table python-dotty-syntax-table
4295 (let ((sym (symbol-at-point)))
4297 (substring-no-properties (symbol-name sym
))))))))
4299 (if (not replace-self
)
4301 (let ((current-defun (python-info-current-defun)))
4302 (if (not current-defun
)
4304 (replace-regexp-in-string
4305 (python-rx line-start word-start
"self" word-end ?.
)
4307 (mapconcat 'identity
4308 (butlast (split-string current-defun
"\\."))
4312 (defun python-info-statement-starts-block-p ()
4313 "Return non-nil if current statement opens a block."
4315 (python-nav-beginning-of-statement)
4316 (looking-at (python-rx block-start
))))
4318 (defun python-info-statement-ends-block-p ()
4319 "Return non-nil if point is at end of block."
4320 (let ((end-of-block-pos (save-excursion
4321 (python-nav-end-of-block)))
4322 (end-of-statement-pos (save-excursion
4323 (python-nav-end-of-statement))))
4324 (and end-of-block-pos end-of-statement-pos
4325 (= end-of-block-pos end-of-statement-pos
))))
4327 (defun python-info-beginning-of-statement-p ()
4328 "Return non-nil if point is at beginning of statement."
4329 (= (point) (save-excursion
4330 (python-nav-beginning-of-statement)
4333 (defun python-info-end-of-statement-p ()
4334 "Return non-nil if point is at end of statement."
4335 (= (point) (save-excursion
4336 (python-nav-end-of-statement)
4339 (defun python-info-beginning-of-block-p ()
4340 "Return non-nil if point is at beginning of block."
4341 (and (python-info-beginning-of-statement-p)
4342 (python-info-statement-starts-block-p)))
4344 (defun python-info-end-of-block-p ()
4345 "Return non-nil if point is at end of block."
4346 (and (python-info-end-of-statement-p)
4347 (python-info-statement-ends-block-p)))
4349 (define-obsolete-function-alias
4350 'python-info-closing-block
4351 'python-info-dedenter-opening-block-position
"24.4")
4353 (defun python-info-dedenter-opening-block-position ()
4354 "Return the point of the closest block the current line closes.
4355 Returns nil if point is not on a dedenter statement or no opening
4356 block can be detected. The latter case meaning current file is
4357 likely an invalid python file."
4358 (let ((positions (python-info-dedenter-opening-block-positions))
4359 (indentation (current-indentation))
4361 (while (and (not position
)
4364 (goto-char (car positions
))
4365 (if (<= (current-indentation) indentation
)
4366 (setq position
(car positions
))
4367 (setq positions
(cdr positions
)))))
4370 (defun python-info-dedenter-opening-block-positions ()
4371 "Return points of blocks the current line may close sorted by closer.
4372 Returns nil if point is not on a dedenter statement or no opening
4373 block can be detected. The latter case meaning current file is
4374 likely an invalid python file."
4376 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4378 (goto-char dedenter-pos
)
4379 (let* ((pairs '(("elif" "elif" "if")
4380 ("else" "if" "elif" "except" "for" "while")
4381 ("except" "except" "try")
4382 ("finally" "else" "except" "try")))
4383 (dedenter (match-string-no-properties 0))
4384 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
4385 (collected-indentations)
4388 (while (python-nav--syntactically
4390 (re-search-backward (python-rx block-start
) nil t
))
4392 (let ((indentation (current-indentation)))
4393 (when (and (not (memq indentation collected-indentations
))
4394 (or (not collected-indentations
)
4395 (< indentation
(apply #'min collected-indentations
))))
4396 (setq collected-indentations
4397 (cons indentation collected-indentations
))
4398 (when (member (match-string-no-properties 0)
4399 possible-opening-blocks
)
4400 (setq opening-blocks
(cons (point) opening-blocks
))))
4401 (when (zerop indentation
)
4402 (throw 'exit nil
)))))
4404 (nreverse opening-blocks
))))))
4406 (define-obsolete-function-alias
4407 'python-info-closing-block-message
4408 'python-info-dedenter-opening-block-message
"24.4")
4410 (defun python-info-dedenter-opening-block-message ()
4411 "Message the first line of the block the current statement closes."
4412 (let ((point (python-info-dedenter-opening-block-position)))
4416 (message "Closes %s" (save-excursion
4419 (point) (line-end-position))))))))
4421 (defun python-info-dedenter-statement-p ()
4422 "Return point if current statement is a dedenter.
4423 Sets `match-data' to the keyword that starts the dedenter
4426 (python-nav-beginning-of-statement)
4427 (when (and (not (python-syntax-context-type))
4428 (looking-at (python-rx dedenter
)))
4431 (defun python-info-line-ends-backslash-p (&optional line-number
)
4432 "Return non-nil if current line ends with backslash.
4433 With optional argument LINE-NUMBER, check that line instead."
4438 (python-util-goto-line line-number
))
4439 (while (and (not (eobp))
4440 (goto-char (line-end-position))
4441 (python-syntax-context 'paren
)
4442 (not (equal (char-before (point)) ?
\\)))
4444 (when (equal (char-before) ?
\\)
4447 (defun python-info-beginning-of-backslash (&optional line-number
)
4448 "Return the point where the backslashed line start.
4449 Optional argument LINE-NUMBER forces the line number to check against."
4454 (python-util-goto-line line-number
))
4455 (when (python-info-line-ends-backslash-p)
4456 (while (save-excursion
4457 (goto-char (line-beginning-position))
4458 (python-syntax-context 'paren
))
4460 (back-to-indentation)
4463 (defun python-info-continuation-line-p ()
4464 "Check if current line is continuation of another.
4465 When current line is continuation of another return the point
4466 where the continued line ends."
4470 (let* ((context-type (progn
4471 (back-to-indentation)
4472 (python-syntax-context-type)))
4473 (line-start (line-number-at-pos))
4474 (context-start (when context-type
4475 (python-syntax-context context-type
))))
4476 (cond ((equal context-type
'paren
)
4477 ;; Lines inside a paren are always a continuation line
4478 ;; (except the first one).
4479 (python-util-forward-comment -
1)
4481 ((member context-type
'(string comment
))
4482 ;; move forward an roll again
4483 (goto-char context-start
)
4484 (python-util-forward-comment)
4485 (python-info-continuation-line-p))
4487 ;; Not within a paren, string or comment, the only way
4488 ;; we are dealing with a continuation line is that
4489 ;; previous line contains a backslash, and this can
4490 ;; only be the previous line from current
4491 (back-to-indentation)
4492 (python-util-forward-comment -
1)
4493 (when (and (equal (1- line-start
) (line-number-at-pos))
4494 (python-info-line-ends-backslash-p))
4495 (point-marker))))))))
4497 (defun python-info-block-continuation-line-p ()
4498 "Return non-nil if current line is a continuation of a block."
4500 (when (python-info-continuation-line-p)
4502 (back-to-indentation)
4503 (when (looking-at (python-rx block-start
))
4506 (defun python-info-assignment-statement-p (&optional current-line-only
)
4507 "Check if current line is an assignment.
4508 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4509 continuations, just check the if current line is an assignment."
4512 (if current-line-only
4513 (back-to-indentation)
4514 (python-nav-beginning-of-statement))
4516 (re-search-forward (python-rx not-simple-operator
4518 (group not-simple-operator
))
4519 (line-end-position) t
)
4522 ;; The assignment operator should not be inside a string.
4523 (backward-char (length (match-string-no-properties 1)))
4524 (setq found
(not (python-syntax-context-type)))))
4526 (skip-syntax-forward " ")
4529 ;; TODO: rename to clarify this is only for the first continuation
4530 ;; line or remove it and move its body to `python-indent-context'.
4531 (defun python-info-assignment-continuation-line-p ()
4532 "Check if current line is the first continuation of an assignment.
4533 When current line is continuation of another with an assignment
4534 return the point of the first non-blank character after the
4537 (when (python-info-continuation-line-p)
4539 (python-info-assignment-statement-p t
))))
4541 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4542 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4543 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4545 (beginning-of-line 1)
4546 (looking-at python-nav-beginning-of-defun-regexp
))))
4548 (defun python-info-current-line-comment-p ()
4549 "Return non-nil if current line is a comment line."
4551 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4554 (defun python-info-current-line-empty-p ()
4555 "Return non-nil if current line is empty, ignoring whitespace."
4557 (beginning-of-line 1)
4559 (python-rx line-start
(* whitespace
)
4560 (group (* not-newline
))
4561 (* whitespace
) line-end
))
4562 (string-equal "" (match-string-no-properties 1))))
4564 (defun python-info-docstring-p (&optional syntax-ppss
)
4565 "Return non-nil if point is in a docstring.
4566 When optional argument SYNTAX-PPSS is given, use that instead of
4567 point's current `syntax-ppss'."
4568 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4570 (when (and syntax-ppss
(python-syntax-context 'string syntax-ppss
))
4571 (goto-char (nth 8 syntax-ppss
)))
4572 (python-nav-beginning-of-statement)
4574 (indentation (current-indentation))
4575 (backward-sexp-point)
4576 (re (concat "[uU]?[rR]?"
4577 (python-rx string-delimiter
))))
4579 (not (python-info-assignment-statement-p))
4581 ;; Allow up to two consecutive docstrings only.
4585 (while (save-excursion
4586 (python-nav-backward-sexp)
4587 (setq backward-sexp-point
(point))
4588 (and (= indentation
(current-indentation))
4589 (not (bobp)) ; Prevent infloop.
4591 (concat "[uU]?[rR]?"
4592 (python-rx string-delimiter
)))))
4593 ;; Previous sexp was a string, restore point.
4594 (goto-char backward-sexp-point
)
4597 (python-util-forward-comment -
1)
4598 (python-nav-beginning-of-statement)
4600 ((python-info-assignment-statement-p) t
)
4601 ((python-info-looking-at-beginning-of-defun))
4604 (defun python-info-encoding-from-cookie ()
4605 "Detect current buffer's encoding from its coding cookie.
4606 Returns the encoding as a symbol."
4607 (let ((first-two-lines
4611 (goto-char (point-min))
4613 (buffer-substring-no-properties
4616 (when (string-match (python-rx coding-cookie
) first-two-lines
)
4617 (intern (match-string-no-properties 1 first-two-lines
)))))
4619 (defun python-info-encoding ()
4620 "Return encoding for file.
4621 Try `python-info-encoding-from-cookie', if none is found then
4623 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4624 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4625 ;; in the worst case scenario python.el will make things work for
4626 ;; Python 2 files with unicode data and no encoding defined.
4627 (or (python-info-encoding-from-cookie)
4631 ;;; Utility functions
4633 (defun python-util-goto-line (line-number)
4634 "Move point to LINE-NUMBER."
4635 (goto-char (point-min))
4636 (forward-line (1- line-number
)))
4638 ;; Stolen from org-mode
4639 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
4640 "Clone local variables from FROM-BUFFER.
4641 Optional argument REGEXP selects variables to clone and defaults
4645 (and (symbolp (car pair
))
4646 (string-match (or regexp
"^python-")
4647 (symbol-name (car pair
)))
4648 (set (make-local-variable (car pair
))
4650 (buffer-local-variables from-buffer
)))
4652 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
4654 (defun python-util-comint-last-prompt ()
4655 "Return comint last prompt overlay start and end.
4656 This is for compatibility with Emacs < 24.4."
4657 (cond ((bound-and-true-p comint-last-prompt-overlay
)
4658 (cons (overlay-start comint-last-prompt-overlay
)
4659 (overlay-end comint-last-prompt-overlay
)))
4660 ((bound-and-true-p comint-last-prompt
)
4664 (defun python-util-forward-comment (&optional direction
)
4665 "Python mode specific version of `forward-comment'.
4666 Optional argument DIRECTION defines the direction to move to."
4667 (let ((comment-start (python-syntax-context 'comment
))
4668 (factor (if (< (or direction
0) 0)
4672 (goto-char comment-start
))
4673 (forward-comment factor
)))
4675 (defun python-util-list-directories (directory &optional predicate max-depth
)
4676 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4677 Argument PREDICATE defaults to `identity' and must be a function
4678 that takes one argument (a full path) and returns non-nil for
4679 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4680 searching when depth is reached, else don't limit."
4681 (let* ((dir (expand-file-name directory
))
4682 (dir-length (length dir
))
4683 (predicate (or predicate
#'identity
))
4684 (to-scan (list dir
))
4687 (let ((current-dir (car to-scan
)))
4688 (when (funcall predicate current-dir
)
4689 (setq tally
(cons current-dir tally
)))
4690 (setq to-scan
(append (cdr to-scan
)
4691 (python-util-list-files
4692 current-dir
#'file-directory-p
)
4694 (when (and max-depth
4696 (length (split-string
4697 (substring current-dir dir-length
)
4699 (setq to-scan nil
))))
4702 (defun python-util-list-files (dir &optional predicate
)
4703 "List files in DIR, filtering with PREDICATE.
4704 Argument PREDICATE defaults to `identity' and must be a function
4705 that takes one argument (a full path) and returns non-nil for
4707 (let ((dir-name (file-name-as-directory dir
)))
4709 (mapcar (lambda (file-name)
4710 (let ((full-file-name (expand-file-name file-name dir-name
)))
4712 (not (member file-name
'("." "..")))
4713 (funcall (or predicate
#'identity
) full-file-name
))
4714 (list full-file-name
))))
4715 (directory-files dir-name
)))))
4717 (defun python-util-list-packages (dir &optional max-depth
)
4718 "List packages in DIR, limited by MAX-DEPTH.
4719 When optional argument MAX-DEPTH is non-nil, stop searching when
4720 depth is reached, else don't limit."
4721 (let* ((dir (expand-file-name dir
))
4722 (parent-dir (file-name-directory
4723 (directory-file-name
4724 (file-name-directory
4725 (file-name-as-directory dir
)))))
4726 (subpath-length (length parent-dir
)))
4729 (replace-regexp-in-string
4730 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
4731 (python-util-list-directories
4732 (directory-file-name dir
)
4734 (file-exists-p (expand-file-name "__init__.py" dir
)))
4737 (defun python-util-popn (lst n
)
4738 "Return LST first N elements.
4739 N should be an integer, when negative its opposite is used.
4740 When N is bigger than the length of LST, the list is
4742 (let* ((n (min (abs n
)))
4748 (setq acc
(cons (car lst
) acc
)
4753 (defun python-util-strip-string (string)
4754 "Strip STRING whitespace and newlines from end and beginning."
4755 (replace-regexp-in-string
4756 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
4757 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
4761 (defun python-util-valid-regexp-p (regexp)
4762 "Return non-nil if REGEXP is valid."
4763 (ignore-errors (string-match regexp
"") t
))
4766 (defun python-electric-pair-string-delimiter ()
4767 (when (and electric-pair-mode
4768 (memq last-command-event
'(?
\" ?
\'))
4770 (while (eq (char-before (- (point) count
)) last-command-event
)
4773 (eq (char-after) last-command-event
))
4774 (save-excursion (insert (make-string 2 last-command-event
)))))
4776 (defvar electric-indent-inhibit
)
4779 (define-derived-mode python-mode prog-mode
"Python"
4780 "Major mode for editing Python files.
4782 \\{python-mode-map}"
4783 (set (make-local-variable 'tab-width
) 8)
4784 (set (make-local-variable 'indent-tabs-mode
) nil
)
4786 (set (make-local-variable 'comment-start
) "# ")
4787 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4789 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4790 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4792 (set (make-local-variable 'forward-sexp-function
)
4793 'python-nav-forward-sexp
)
4795 (set (make-local-variable 'font-lock-defaults
)
4796 '(python-font-lock-keywords
4798 (font-lock-syntactic-face-function
4799 . python-font-lock-syntactic-face-function
)))
4801 (set (make-local-variable 'syntax-propertize-function
)
4802 python-syntax-propertize-function
)
4804 (set (make-local-variable 'indent-line-function
)
4805 #'python-indent-line-function
)
4806 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4807 ;; Because indentation is not redundant, we cannot safely reindent code.
4808 (set (make-local-variable 'electric-indent-inhibit
) t
)
4809 (set (make-local-variable 'electric-indent-chars
)
4810 (cons ?
: electric-indent-chars
))
4812 ;; Add """ ... """ pairing to electric-pair-mode.
4813 (add-hook 'post-self-insert-hook
4814 #'python-electric-pair-string-delimiter
'append t
)
4816 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4817 (set (make-local-variable 'fill-paragraph-function
)
4818 #'python-fill-paragraph
)
4820 (set (make-local-variable 'beginning-of-defun-function
)
4821 #'python-nav-beginning-of-defun
)
4822 (set (make-local-variable 'end-of-defun-function
)
4823 #'python-nav-end-of-defun
)
4825 (add-hook 'completion-at-point-functions
4826 #'python-completion-at-point nil
'local
)
4828 (add-hook 'post-self-insert-hook
4829 #'python-indent-post-self-insert-function
'append
'local
)
4831 (set (make-local-variable 'imenu-create-index-function
)
4832 #'python-imenu-create-index
)
4834 (set (make-local-variable 'add-log-current-defun-function
)
4835 #'python-info-current-defun
)
4837 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4839 (set (make-local-variable 'skeleton-further-elements
)
4841 (< '(backward-delete-char-untabify (min python-indent-offset
4843 (^
'(- (1+ (current-indentation))))))
4845 (if (null eldoc-documentation-function
)
4847 (set (make-local-variable 'eldoc-documentation-function
)
4848 #'python-eldoc-function
)
4849 (add-function :before-until
(local 'eldoc-documentation-function
)
4850 #'python-eldoc-function
))
4853 'hs-special-modes-alist
4855 "\\s-*\\(?:def\\|class\\)\\>"
4856 ;; Use the empty string as end regexp so it doesn't default to
4857 ;; "\\s)". This way parens at end of defun are properly hidden.
4860 python-hideshow-forward-sexp-function
4863 (set (make-local-variable 'outline-regexp
)
4864 (python-rx (* space
) block-start
))
4865 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
4866 (set (make-local-variable 'outline-level
)
4868 "`outline-level' function for Python mode."
4869 (1+ (/ (current-indentation) python-indent-offset
))))
4871 (python-skeleton-add-menu-items)
4873 (make-local-variable 'python-shell-internal-buffer
)
4875 (when python-indent-guess-indent-offset
4876 (python-indent-guess-indent-offset)))
4883 ;; indent-tabs-mode: nil
4886 ;;; python.el ends here