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