Add and use function horizontal-scroll-bars-available-p.
[emacs.git] / lisp / progmodes / python.el
blobdc38966bcafd46f5ccef8ad414417b9b945d3f0e
1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2014 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.4
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 ;; If you are experiencing missing or delayed output in your shells,
98 ;; that's likely caused by your Operating System's pipe buffering
99 ;; (e.g. this is known to happen running CPython 3.3.4 in Windows 7.
100 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101 ;; fix this, using CPython's "-u" commandline argument or setting the
102 ;; "PYTHONUNBUFFERED" environment variable should help: See URL
103 ;; `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. Shell completion is implemented in such way that if you
123 ;; change the `python-shell-interpreter' it should be possible to
124 ;; integrate custom logic to calculate completions. To achieve this
125 ;; you just need to set `python-shell-completion-setup-code' and
126 ;; `python-shell-completion-string-code'. The default provided code,
127 ;; enables autocompletion for both CPython and IPython (and ideally
128 ;; any readline based Python shell). This code depends on the
129 ;; readline module, so if you are using some Operating System that
130 ;; bundles Python without it (like Windows), installing pyreadline
131 ;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
132 ;; suffice. To troubleshoot why you are not getting any completions
133 ;; you can try the following in your Python shell:
135 ;; >>> import readline, rlcompleter
137 ;; If you see an error, then you need to either install pyreadline or
138 ;; setup custom code that avoids that dependency.
140 ;; Shell virtualenv support: The shell also contains support for
141 ;; virtualenvs and other special environment modifications thanks to
142 ;; `python-shell-process-environment' and `python-shell-exec-path'.
143 ;; These two variables allows you to modify execution paths and
144 ;; environment variables to make easy for you to setup virtualenv rules
145 ;; or behavior modifications when running shells. Here is an example
146 ;; of how to make shell processes to be run using the /path/to/env/
147 ;; virtualenv:
149 ;; (setq python-shell-process-environment
150 ;; (list
151 ;; (format "PATH=%s" (mapconcat
152 ;; 'identity
153 ;; (reverse
154 ;; (cons (getenv "PATH")
155 ;; '("/path/to/env/bin/")))
156 ;; ":"))
157 ;; "VIRTUAL_ENV=/path/to/env/"))
158 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
160 ;; Since the above is cumbersome and can be programmatically
161 ;; calculated, the variable `python-shell-virtualenv-path' is
162 ;; provided. When this variable is set with the path of the
163 ;; virtualenv to use, `process-environment' and `exec-path' get proper
164 ;; values in order to run shells inside the specified virtualenv. So
165 ;; the following will achieve the same as the previous example:
167 ;; (setq python-shell-virtualenv-path "/path/to/env/")
169 ;; Also the `python-shell-extra-pythonpaths' variable have been
170 ;; introduced as simple way of adding paths to the PYTHONPATH without
171 ;; affecting existing values.
173 ;; Shell package support: you can enable a package in the current
174 ;; shell so that relative imports work properly using the
175 ;; `python-shell-package-enable' command.
177 ;; Shell syntax highlighting: when enabled current input in shell is
178 ;; highlighted. The variable `python-shell-font-lock-enable' controls
179 ;; activation of this feature globally when shells are started.
180 ;; Activation/deactivation can be also controlled on the fly via the
181 ;; `python-shell-font-lock-toggle' command.
183 ;; Pdb tracking: when you execute a block of code that contains some
184 ;; call to pdb (or ipdb) it will prompt the block of code and will
185 ;; follow the execution of pdb marking the current line with an arrow.
187 ;; Symbol completion: you can complete the symbol at point. It uses
188 ;; the shell completion in background so you should run
189 ;; `python-shell-send-buffer' from time to time to get better results.
191 ;; Skeletons: skeletons are provided for simple inserting of things like class,
192 ;; def, for, import, if, try, and while. These skeletons are
193 ;; integrated with abbrev. If you have `abbrev-mode' activated and
194 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
195 ;; the name of any of those defined and hit SPC, they will be
196 ;; automatically expanded. As an alternative you can use the defined
197 ;; skeleton commands: `python-skeleton-<foo>'.
199 ;; FFAP: You can find the filename for a given module when using ffap
200 ;; out of the box. This feature needs an inferior python shell
201 ;; running.
203 ;; Code check: Check the current file for errors with `python-check'
204 ;; using the program defined in `python-check-command'.
206 ;; Eldoc: returns documentation for object at point by using the
207 ;; inferior python subprocess to inspect its documentation. As you
208 ;; might guessed you should run `python-shell-send-buffer' from time
209 ;; to time to get better results too.
211 ;; Imenu: There are two index building functions to be used as
212 ;; `imenu-create-index-function': `python-imenu-create-index' (the
213 ;; default one, builds the alist in form of a tree) and
214 ;; `python-imenu-create-flat-index'. See also
215 ;; `python-imenu-format-item-label-function',
216 ;; `python-imenu-format-parent-item-label-function',
217 ;; `python-imenu-format-parent-item-jump-label-function' variables for
218 ;; changing the way labels are formatted in the tree version.
220 ;; If you used python-mode.el you probably will miss auto-indentation
221 ;; when inserting newlines. To achieve the same behavior you have
222 ;; two options:
224 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
226 ;; 2) Add the following hook in your .emacs:
228 ;; (add-hook 'python-mode-hook
229 ;; #'(lambda ()
230 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
232 ;; I'd recommend the first one since you'll get the same behavior for
233 ;; all modes out-of-the-box.
235 ;;; Installation:
237 ;; Add this to your .emacs:
239 ;; (add-to-list 'load-path "/folder/containing/file")
240 ;; (require 'python)
242 ;;; TODO:
244 ;;; Code:
246 (require 'ansi-color)
247 (require 'cl-lib)
248 (require 'comint)
249 (require 'json)
251 ;; Avoid compiler warnings
252 (defvar view-return-to-alist)
253 (defvar compilation-error-regexp-alist)
254 (defvar outline-heading-end-regexp)
256 (autoload 'comint-mode "comint")
258 ;;;###autoload
259 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
260 ;;;###autoload
261 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
263 (defgroup python nil
264 "Python Language's flying circus support for Emacs."
265 :group 'languages
266 :version "24.3"
267 :link '(emacs-commentary-link "python"))
270 ;;; Bindings
272 (defvar python-mode-map
273 (let ((map (make-sparse-keymap)))
274 ;; Movement
275 (define-key map [remap backward-sentence] 'python-nav-backward-block)
276 (define-key map [remap forward-sentence] 'python-nav-forward-block)
277 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
278 (define-key map "\C-c\C-j" 'imenu)
279 ;; Indent specific
280 (define-key map "\177" 'python-indent-dedent-line-backspace)
281 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
282 (define-key map "\C-c<" 'python-indent-shift-left)
283 (define-key map "\C-c>" 'python-indent-shift-right)
284 ;; Skeletons
285 (define-key map "\C-c\C-tc" 'python-skeleton-class)
286 (define-key map "\C-c\C-td" 'python-skeleton-def)
287 (define-key map "\C-c\C-tf" 'python-skeleton-for)
288 (define-key map "\C-c\C-ti" 'python-skeleton-if)
289 (define-key map "\C-c\C-tm" 'python-skeleton-import)
290 (define-key map "\C-c\C-tt" 'python-skeleton-try)
291 (define-key map "\C-c\C-tw" 'python-skeleton-while)
292 ;; Shell interaction
293 (define-key map "\C-c\C-p" 'run-python)
294 (define-key map "\C-c\C-s" 'python-shell-send-string)
295 (define-key map "\C-c\C-r" 'python-shell-send-region)
296 (define-key map "\C-\M-x" 'python-shell-send-defun)
297 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
298 (define-key map "\C-c\C-l" 'python-shell-send-file)
299 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
300 ;; Some util commands
301 (define-key map "\C-c\C-v" 'python-check)
302 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
303 ;; Utilities
304 (substitute-key-definition 'complete-symbol 'completion-at-point
305 map global-map)
306 (easy-menu-define python-menu map "Python Mode menu"
307 `("Python"
308 :help "Python-specific Features"
309 ["Shift region left" python-indent-shift-left :active mark-active
310 :help "Shift region left by a single indentation step"]
311 ["Shift region right" python-indent-shift-right :active mark-active
312 :help "Shift region right by a single indentation step"]
314 ["Start of def/class" beginning-of-defun
315 :help "Go to start of outermost definition around point"]
316 ["End of def/class" end-of-defun
317 :help "Go to end of definition around point"]
318 ["Mark def/class" mark-defun
319 :help "Mark outermost definition around point"]
320 ["Jump to def/class" imenu
321 :help "Jump to a class or function definition"]
322 "--"
323 ("Skeletons")
324 "---"
325 ["Start interpreter" run-python
326 :help "Run inferior Python process in a separate buffer"]
327 ["Switch to shell" python-shell-switch-to-shell
328 :help "Switch to running inferior Python process"]
329 ["Eval string" python-shell-send-string
330 :help "Eval string in inferior Python session"]
331 ["Eval buffer" python-shell-send-buffer
332 :help "Eval buffer in inferior Python session"]
333 ["Eval region" python-shell-send-region
334 :help "Eval region in inferior Python session"]
335 ["Eval defun" python-shell-send-defun
336 :help "Eval defun in inferior Python session"]
337 ["Eval file" python-shell-send-file
338 :help "Eval file in inferior Python session"]
339 ["Debugger" pdb :help "Run pdb under GUD"]
340 "----"
341 ["Check file" python-check
342 :help "Check file for errors"]
343 ["Help on symbol" python-eldoc-at-point
344 :help "Get help on symbol at point"]
345 ["Complete symbol" completion-at-point
346 :help "Complete symbol before point"]))
347 map)
348 "Keymap for `python-mode'.")
351 ;;; Python specialized rx
353 (eval-when-compile
354 (defconst python-rx-constituents
355 `((block-start . ,(rx symbol-start
356 (or "def" "class" "if" "elif" "else" "try"
357 "except" "finally" "for" "while" "with")
358 symbol-end))
359 (dedenter . ,(rx symbol-start
360 (or "elif" "else" "except" "finally")
361 symbol-end))
362 (block-ender . ,(rx symbol-start
364 "break" "continue" "pass" "raise" "return")
365 symbol-end))
366 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
367 (* (any word ?_))))
368 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
369 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
370 (+ space) "==" (+ space)
371 (any ?' ?\") "__main__" (any ?' ?\")
372 (* space) ?:))
373 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
374 (open-paren . ,(rx (or "{" "[" "(")))
375 (close-paren . ,(rx (or "}" "]" ")")))
376 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
377 ;; FIXME: rx should support (not simple-operator).
378 (not-simple-operator . ,(rx
379 (not
380 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
381 ;; FIXME: Use regexp-opt.
382 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
383 "=" "%" "**" "//" "<<" ">>" "<=" "!="
384 "==" ">=" "is" "not")))
385 ;; FIXME: Use regexp-opt.
386 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
387 ">>=" "<<=" "&=" "^=" "|=")))
388 (string-delimiter . ,(rx (and
389 ;; Match even number of backslashes.
390 (or (not (any ?\\ ?\' ?\")) point
391 ;; Quotes might be preceded by a escaped quote.
392 (and (or (not (any ?\\)) point) ?\\
393 (* ?\\ ?\\) (any ?\' ?\")))
394 (* ?\\ ?\\)
395 ;; Match single or triple quotes of any kind.
396 (group (or "\"" "\"\"\"" "'" "'''"))))))
397 "Additional Python specific sexps for `python-rx'")
399 (defmacro python-rx (&rest regexps)
400 "Python mode specialized rx macro.
401 This variant of `rx' supports common Python named REGEXPS."
402 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
403 (cond ((null regexps)
404 (error "No regexp"))
405 ((cdr regexps)
406 (rx-to-string `(and ,@regexps) t))
408 (rx-to-string (car regexps) t))))))
411 ;;; Font-lock and syntax
413 (eval-when-compile
414 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
415 (pcase type
416 (`'comment
417 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
418 (and (nth 4 ppss) (nth 8 ppss))))
419 (`'string
420 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
421 (and (nth 3 ppss) (nth 8 ppss))))
422 (`'paren
423 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
424 (_ form))))
426 (defun python-syntax-context (type &optional syntax-ppss)
427 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
428 TYPE can be `comment', `string' or `paren'. It returns the start
429 character address of the specified TYPE."
430 (declare (compiler-macro python-syntax--context-compiler-macro))
431 (let ((ppss (or syntax-ppss (syntax-ppss))))
432 (pcase type
433 (`comment (and (nth 4 ppss) (nth 8 ppss)))
434 (`string (and (nth 3 ppss) (nth 8 ppss)))
435 (`paren (nth 1 ppss))
436 (_ nil))))
438 (defun python-syntax-context-type (&optional syntax-ppss)
439 "Return the context type using SYNTAX-PPSS.
440 The type returned can be `comment', `string' or `paren'."
441 (let ((ppss (or syntax-ppss (syntax-ppss))))
442 (cond
443 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
444 ((nth 1 ppss) 'paren))))
446 (defsubst python-syntax-comment-or-string-p ()
447 "Return non-nil if point is inside 'comment or 'string."
448 (nth 8 (syntax-ppss)))
450 (define-obsolete-function-alias
451 'python-info-ppss-context #'python-syntax-context "24.3")
453 (define-obsolete-function-alias
454 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
456 (define-obsolete-function-alias
457 'python-info-ppss-comment-or-string-p
458 #'python-syntax-comment-or-string-p "24.3")
460 (defvar python-font-lock-keywords
461 ;; Keywords
462 `(,(rx symbol-start
464 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
465 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
466 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
467 "try"
468 ;; Python 2:
469 "print" "exec"
470 ;; Python 3:
471 ;; False, None, and True are listed as keywords on the Python 3
472 ;; documentation, but since they also qualify as constants they are
473 ;; fontified like that in order to keep font-lock consistent between
474 ;; Python versions.
475 "nonlocal"
476 ;; Extra:
477 "self")
478 symbol-end)
479 ;; functions
480 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
481 (1 font-lock-function-name-face))
482 ;; classes
483 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
484 (1 font-lock-type-face))
485 ;; Constants
486 (,(rx symbol-start
488 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
489 ;; copyright, license, credits, quit and exit are added by the site
490 ;; module and they are not intended to be used in programs
491 "copyright" "credits" "exit" "license" "quit")
492 symbol-end) . font-lock-constant-face)
493 ;; Decorators.
494 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
495 (0+ "." (1+ (or word ?_)))))
496 (1 font-lock-type-face))
497 ;; Builtin Exceptions
498 (,(rx symbol-start
500 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
501 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
502 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
503 "ImportError" "ImportWarning" "IndexError" "KeyError"
504 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
505 "NotImplementedError" "OSError" "OverflowError"
506 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
507 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
508 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
509 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
510 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
511 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
512 ;; Python 2:
513 "StandardError"
514 ;; Python 3:
515 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
516 "TabError")
517 symbol-end) . font-lock-type-face)
518 ;; Builtins
519 (,(rx symbol-start
521 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
522 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
523 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
524 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
525 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
526 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
527 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
528 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
529 "__import__"
530 ;; Python 2:
531 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
532 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
533 "intern"
534 ;; Python 3:
535 "ascii" "bytearray" "bytes" "exec"
536 ;; Extra:
537 "__all__" "__doc__" "__name__" "__package__")
538 symbol-end) . font-lock-builtin-face)
539 ;; assignments
540 ;; support for a = b = c = 5
541 (,(lambda (limit)
542 (let ((re (python-rx (group (+ (any word ?. ?_)))
543 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
544 assignment-operator))
545 (res nil))
546 (while (and (setq res (re-search-forward re limit t))
547 (or (python-syntax-context 'paren)
548 (equal (char-after (point-marker)) ?=))))
549 res))
550 (1 font-lock-variable-name-face nil nil))
551 ;; support for a, b, c = (1, 2, 3)
552 (,(lambda (limit)
553 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
554 (* ?, (* space) (+ (any word ?. ?_)) (* space))
555 ?, (* space) (+ (any word ?. ?_)) (* space)
556 assignment-operator))
557 (res nil))
558 (while (and (setq res (re-search-forward re limit t))
559 (goto-char (match-end 1))
560 (python-syntax-context 'paren)))
561 res))
562 (1 font-lock-variable-name-face nil nil))))
564 (defconst python-syntax-propertize-function
565 (syntax-propertize-rules
566 ((python-rx string-delimiter)
567 (0 (ignore (python-syntax-stringify))))))
569 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
570 "Count number of quotes around point (max is 3).
571 QUOTE-CHAR is the quote char to count. Optional argument POINT is
572 the point where scan starts (defaults to current point), and LIMIT
573 is used to limit the scan."
574 (let ((i 0))
575 (while (and (< i 3)
576 (or (not limit) (< (+ point i) limit))
577 (eq (char-after (+ point i)) quote-char))
578 (setq i (1+ i)))
581 (defun python-syntax-stringify ()
582 "Put `syntax-table' property correctly on single/triple quotes."
583 (let* ((num-quotes (length (match-string-no-properties 1)))
584 (ppss (prog2
585 (backward-char num-quotes)
586 (syntax-ppss)
587 (forward-char num-quotes)))
588 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
589 (quote-starting-pos (- (point) num-quotes))
590 (quote-ending-pos (point))
591 (num-closing-quotes
592 (and string-start
593 (python-syntax-count-quotes
594 (char-before) string-start quote-starting-pos))))
595 (cond ((and string-start (= num-closing-quotes 0))
596 ;; This set of quotes doesn't match the string starting
597 ;; kind. Do nothing.
598 nil)
599 ((not string-start)
600 ;; This set of quotes delimit the start of a string.
601 (put-text-property quote-starting-pos (1+ quote-starting-pos)
602 'syntax-table (string-to-syntax "|")))
603 ((= num-quotes num-closing-quotes)
604 ;; This set of quotes delimit the end of a string.
605 (put-text-property (1- quote-ending-pos) quote-ending-pos
606 'syntax-table (string-to-syntax "|")))
607 ((> num-quotes num-closing-quotes)
608 ;; This may only happen whenever a triple quote is closing
609 ;; a single quoted string. Add string delimiter syntax to
610 ;; all three quotes.
611 (put-text-property quote-starting-pos quote-ending-pos
612 'syntax-table (string-to-syntax "|"))))))
614 (defvar python-mode-syntax-table
615 (let ((table (make-syntax-table)))
616 ;; Give punctuation syntax to ASCII that normally has symbol
617 ;; syntax or has word syntax and isn't a letter.
618 (let ((symbol (string-to-syntax "_"))
619 (sst (standard-syntax-table)))
620 (dotimes (i 128)
621 (unless (= i ?_)
622 (if (equal symbol (aref sst i))
623 (modify-syntax-entry i "." table)))))
624 (modify-syntax-entry ?$ "." table)
625 (modify-syntax-entry ?% "." table)
626 ;; exceptions
627 (modify-syntax-entry ?# "<" table)
628 (modify-syntax-entry ?\n ">" table)
629 (modify-syntax-entry ?' "\"" table)
630 (modify-syntax-entry ?` "$" table)
631 table)
632 "Syntax table for Python files.")
634 (defvar python-dotty-syntax-table
635 (let ((table (make-syntax-table python-mode-syntax-table)))
636 (modify-syntax-entry ?. "w" table)
637 (modify-syntax-entry ?_ "w" table)
638 table)
639 "Dotty syntax table for Python files.
640 It makes underscores and dots word constituent chars.")
643 ;;; Indentation
645 (defcustom python-indent-offset 4
646 "Default indentation offset for Python."
647 :group 'python
648 :type 'integer
649 :safe 'integerp)
651 (defcustom python-indent-guess-indent-offset t
652 "Non-nil tells Python mode to guess `python-indent-offset' value."
653 :type 'boolean
654 :group 'python
655 :safe 'booleanp)
657 (defcustom python-indent-trigger-commands
658 '(indent-for-tab-command yas-expand yas/expand)
659 "Commands that might trigger a `python-indent-line' call."
660 :type '(repeat symbol)
661 :group 'python)
663 (define-obsolete-variable-alias
664 'python-indent 'python-indent-offset "24.3")
666 (define-obsolete-variable-alias
667 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
669 (defvar python-indent-current-level 0
670 "Current indentation level `python-indent-line-function' is using.")
672 (defvar python-indent-levels '(0)
673 "Levels of indentation available for `python-indent-line-function'.")
675 (defun python-indent-guess-indent-offset ()
676 "Guess and set `python-indent-offset' for the current buffer."
677 (interactive)
678 (save-excursion
679 (save-restriction
680 (widen)
681 (goto-char (point-min))
682 (let ((block-end))
683 (while (and (not block-end)
684 (re-search-forward
685 (python-rx line-start block-start) nil t))
686 (when (and
687 (not (python-syntax-context-type))
688 (progn
689 (goto-char (line-end-position))
690 (python-util-forward-comment -1)
691 (if (equal (char-before) ?:)
693 (forward-line 1)
694 (when (python-info-block-continuation-line-p)
695 (while (and (python-info-continuation-line-p)
696 (not (eobp)))
697 (forward-line 1))
698 (python-util-forward-comment -1)
699 (when (equal (char-before) ?:)
700 t)))))
701 (setq block-end (point-marker))))
702 (let ((indentation
703 (when block-end
704 (goto-char block-end)
705 (python-util-forward-comment)
706 (current-indentation))))
707 (if (and indentation (not (zerop indentation)))
708 (set (make-local-variable 'python-indent-offset) indentation)
709 (message "Can't guess python-indent-offset, using defaults: %s"
710 python-indent-offset)))))))
712 (defun python-indent-context ()
713 "Get information on indentation context.
714 Context information is returned with a cons with the form:
715 (STATUS . START)
717 Where status can be any of the following symbols:
719 * after-comment: When current line might continue a comment block
720 * inside-paren: If point in between (), {} or []
721 * inside-string: If point is inside a string
722 * after-backslash: Previous line ends in a backslash
723 * after-beginning-of-block: Point is after beginning of block
724 * after-line: Point is after normal line
725 * dedenter-statement: Point is on a dedenter statement.
726 * no-indent: Point is at beginning of buffer or other special case
727 START is the buffer position where the sexp starts."
728 (save-restriction
729 (widen)
730 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
731 (start))
732 (cons
733 (cond
734 ;; Beginning of buffer
735 ((save-excursion
736 (goto-char (line-beginning-position))
737 (bobp))
738 'no-indent)
739 ;; Comment continuation
740 ((save-excursion
741 (when (and
743 (python-info-current-line-comment-p)
744 (python-info-current-line-empty-p))
745 (progn
746 (forward-comment -1)
747 (python-info-current-line-comment-p)))
748 (setq start (point))
749 'after-comment)))
750 ;; Inside string
751 ((setq start (python-syntax-context 'string ppss))
752 'inside-string)
753 ;; Inside a paren
754 ((setq start (python-syntax-context 'paren ppss))
755 'inside-paren)
756 ;; After backslash
757 ((setq start (when (not (or (python-syntax-context 'string ppss)
758 (python-syntax-context 'comment ppss)))
759 (let ((line-beg-pos (line-number-at-pos)))
760 (python-info-line-ends-backslash-p
761 (1- line-beg-pos)))))
762 'after-backslash)
763 ;; After beginning of block
764 ((setq start (save-excursion
765 (when (progn
766 (back-to-indentation)
767 (python-util-forward-comment -1)
768 (equal (char-before) ?:))
769 ;; Move to the first block start that's not in within
770 ;; a string, comment or paren and that's not a
771 ;; continuation line.
772 (while (and (re-search-backward
773 (python-rx block-start) nil t)
775 (python-syntax-context-type)
776 (python-info-continuation-line-p))))
777 (when (looking-at (python-rx block-start))
778 (point-marker)))))
779 'after-beginning-of-block)
780 ((when (setq start (python-info-dedenter-statement-p))
781 'dedenter-statement))
782 ;; After normal line
783 ((setq start (save-excursion
784 (back-to-indentation)
785 (skip-chars-backward (rx (or whitespace ?\n)))
786 (python-nav-beginning-of-statement)
787 (point-marker)))
788 'after-line)
789 ;; Do not indent
790 (t 'no-indent))
791 start))))
793 (defun python-indent-calculate-indentation ()
794 "Calculate correct indentation offset for the current line."
795 (let* ((indentation-context (python-indent-context))
796 (context-status (car indentation-context))
797 (context-start (cdr indentation-context)))
798 (save-restriction
799 (widen)
800 (save-excursion
801 (pcase context-status
802 (`no-indent 0)
803 (`after-comment
804 (goto-char context-start)
805 (current-indentation))
806 ;; When point is after beginning of block just add one level
807 ;; of indentation relative to the context-start
808 (`after-beginning-of-block
809 (goto-char context-start)
810 (+ (current-indentation) python-indent-offset))
811 ;; When after a simple line just use previous line
812 ;; indentation.
813 (`after-line
814 (let* ((pair (save-excursion
815 (goto-char context-start)
816 (cons
817 (current-indentation)
818 (python-info-beginning-of-block-p))))
819 (context-indentation (car pair))
820 ;; TODO: Separate block enders into its own case.
821 (adjustment
822 (if (save-excursion
823 (python-util-forward-comment -1)
824 (python-nav-beginning-of-statement)
825 (looking-at (python-rx block-ender)))
826 python-indent-offset
827 0)))
828 (- context-indentation adjustment)))
829 ;; When point is on a dedenter statement, search for the
830 ;; opening block that corresponds to it and use its
831 ;; indentation. If no opening block is found just remove
832 ;; indentation as this is an invalid python file.
833 (`dedenter-statement
834 (let ((block-start-point
835 (python-info-dedenter-opening-block-position)))
836 (save-excursion
837 (if (not block-start-point)
839 (goto-char block-start-point)
840 (current-indentation)))))
841 ;; When inside of a string, do nothing. just use the current
842 ;; indentation. XXX: perhaps it would be a good idea to
843 ;; invoke standard text indentation here
844 (`inside-string
845 (goto-char context-start)
846 (current-indentation))
847 ;; After backslash we have several possibilities.
848 (`after-backslash
849 (cond
850 ;; Check if current line is a dot continuation. For this
851 ;; the current line must start with a dot and previous
852 ;; line must contain a dot too.
853 ((save-excursion
854 (back-to-indentation)
855 (when (looking-at "\\.")
856 ;; If after moving one line back point is inside a paren it
857 ;; needs to move back until it's not anymore
858 (while (prog2
859 (forward-line -1)
860 (and (not (bobp))
861 (python-syntax-context 'paren))))
862 (goto-char (line-end-position))
863 (while (and (re-search-backward
864 "\\." (line-beginning-position) t)
865 (python-syntax-context-type)))
866 (if (and (looking-at "\\.")
867 (not (python-syntax-context-type)))
868 ;; The indentation is the same column of the
869 ;; first matching dot that's not inside a
870 ;; comment, a string or a paren
871 (current-column)
872 ;; No dot found on previous line, just add another
873 ;; indentation level.
874 (+ (current-indentation) python-indent-offset)))))
875 ;; Check if prev line is a block continuation
876 ((let ((block-continuation-start
877 (python-info-block-continuation-line-p)))
878 (when block-continuation-start
879 ;; If block-continuation-start is set jump to that
880 ;; marker and use first column after the block start
881 ;; as indentation value.
882 (goto-char block-continuation-start)
883 (re-search-forward
884 (python-rx block-start (* space))
885 (line-end-position) t)
886 (current-column))))
887 ;; Check if current line is an assignment continuation
888 ((let ((assignment-continuation-start
889 (python-info-assignment-continuation-line-p)))
890 (when assignment-continuation-start
891 ;; If assignment-continuation is set jump to that
892 ;; marker and use first column after the assignment
893 ;; operator as indentation value.
894 (goto-char assignment-continuation-start)
895 (current-column))))
897 (forward-line -1)
898 (goto-char (python-info-beginning-of-backslash))
899 (if (save-excursion
900 (and
901 (forward-line -1)
902 (goto-char
903 (or (python-info-beginning-of-backslash) (point)))
904 (python-info-line-ends-backslash-p)))
905 ;; The two previous lines ended in a backslash so we must
906 ;; respect previous line indentation.
907 (current-indentation)
908 ;; What happens here is that we are dealing with the second
909 ;; line of a backslash continuation, in that case we just going
910 ;; to add one indentation level.
911 (+ (current-indentation) python-indent-offset)))))
912 ;; When inside a paren there's a need to handle nesting
913 ;; correctly
914 (`inside-paren
915 (cond
916 ;; If current line closes the outermost open paren use the
917 ;; current indentation of the context-start line.
918 ((save-excursion
919 (skip-syntax-forward "\s" (line-end-position))
920 (when (and (looking-at (regexp-opt '(")" "]" "}")))
921 (progn
922 (forward-char 1)
923 (not (python-syntax-context 'paren))))
924 (goto-char context-start)
925 (current-indentation))))
926 ;; If open paren is contained on a line by itself add another
927 ;; indentation level, else look for the first word after the
928 ;; opening paren and use it's column position as indentation
929 ;; level.
930 ((let* ((content-starts-in-newline)
931 (indent
932 (save-excursion
933 (if (setq content-starts-in-newline
934 (progn
935 (goto-char context-start)
936 (forward-char)
937 (save-restriction
938 (narrow-to-region
939 (line-beginning-position)
940 (line-end-position))
941 (python-util-forward-comment))
942 (looking-at "$")))
943 (+ (current-indentation) python-indent-offset)
944 (current-column)))))
945 ;; Adjustments
946 (cond
947 ;; If current line closes a nested open paren de-indent one
948 ;; level.
949 ((progn
950 (back-to-indentation)
951 (looking-at (regexp-opt '(")" "]" "}"))))
952 (- indent python-indent-offset))
953 ;; If the line of the opening paren that wraps the current
954 ;; line starts a block add another level of indentation to
955 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
956 ((save-excursion
957 (when (and content-starts-in-newline
958 (progn
959 (goto-char context-start)
960 (back-to-indentation)
961 (looking-at (python-rx block-start))))
962 (+ indent python-indent-offset))))
963 (t indent)))))))))))
965 (defun python-indent-calculate-levels ()
966 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
967 (if (not (python-info-dedenter-statement-p))
968 (let* ((indentation (python-indent-calculate-indentation))
969 (remainder (% indentation python-indent-offset))
970 (steps (/ (- indentation remainder) python-indent-offset)))
971 (setq python-indent-levels (list 0))
972 (dotimes (step steps)
973 (push (* python-indent-offset (1+ step)) python-indent-levels))
974 (when (not (eq 0 remainder))
975 (push (+ (* python-indent-offset steps) remainder) python-indent-levels)))
976 (setq python-indent-levels
978 (mapcar (lambda (pos)
979 (save-excursion
980 (goto-char pos)
981 (current-indentation)))
982 (python-info-dedenter-opening-block-positions))
983 (list 0))))
984 (setq python-indent-current-level (1- (length python-indent-levels))
985 python-indent-levels (nreverse python-indent-levels)))
987 (defun python-indent-toggle-levels ()
988 "Toggle `python-indent-current-level' over `python-indent-levels'."
989 (setq python-indent-current-level (1- python-indent-current-level))
990 (when (< python-indent-current-level 0)
991 (setq python-indent-current-level (1- (length python-indent-levels)))))
993 (defun python-indent-line (&optional force-toggle)
994 "Internal implementation of `python-indent-line-function'.
995 Uses the offset calculated in
996 `python-indent-calculate-indentation' and available levels
997 indicated by the variable `python-indent-levels' to set the
998 current indentation.
1000 When the variable `last-command' is equal to one of the symbols
1001 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
1002 non-nil it cycles levels indicated in the variable
1003 `python-indent-levels' by setting the current level in the
1004 variable `python-indent-current-level'.
1006 When the variable `last-command' is not equal to one of the
1007 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
1008 is nil it calculates possible indentation levels and saves them
1009 in the variable `python-indent-levels'. Afterwards it sets the
1010 variable `python-indent-current-level' correctly so offset is
1011 equal to
1012 (nth python-indent-current-level python-indent-levels)"
1014 (and (or (and (memq this-command python-indent-trigger-commands)
1015 (eq last-command this-command))
1016 force-toggle)
1017 (not (equal python-indent-levels '(0)))
1018 (or (python-indent-toggle-levels) t))
1019 (python-indent-calculate-levels))
1020 (let* ((starting-pos (point-marker))
1021 (indent-ending-position
1022 (+ (line-beginning-position) (current-indentation)))
1023 (follow-indentation-p
1024 (or (bolp)
1025 (and (<= (line-beginning-position) starting-pos)
1026 (>= indent-ending-position starting-pos))))
1027 (next-indent (nth python-indent-current-level python-indent-levels)))
1028 (unless (= next-indent (current-indentation))
1029 (beginning-of-line)
1030 (delete-horizontal-space)
1031 (indent-to next-indent)
1032 (goto-char starting-pos))
1033 (and follow-indentation-p (back-to-indentation)))
1034 (python-info-dedenter-opening-block-message))
1036 (defun python-indent-line-function ()
1037 "`indent-line-function' for Python mode.
1038 See `python-indent-line' for details."
1039 (python-indent-line))
1041 (defun python-indent-dedent-line ()
1042 "De-indent current line."
1043 (interactive "*")
1044 (when (and (not (python-syntax-comment-or-string-p))
1045 (<= (point-marker) (save-excursion
1046 (back-to-indentation)
1047 (point-marker)))
1048 (> (current-column) 0))
1049 (python-indent-line t)
1052 (defun python-indent-dedent-line-backspace (arg)
1053 "De-indent current line.
1054 Argument ARG is passed to `backward-delete-char-untabify' when
1055 point is not in between the indentation."
1056 (interactive "*p")
1057 (when (not (python-indent-dedent-line))
1058 (backward-delete-char-untabify arg)))
1059 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1061 (defun python-indent-region (start end)
1062 "Indent a Python region automagically.
1064 Called from a program, START and END specify the region to indent."
1065 (let ((deactivate-mark nil))
1066 (save-excursion
1067 (goto-char end)
1068 (setq end (point-marker))
1069 (goto-char start)
1070 (or (bolp) (forward-line 1))
1071 (while (< (point) end)
1072 (or (and (bolp) (eolp))
1073 (let (word)
1074 (forward-line -1)
1075 (back-to-indentation)
1076 (setq word (current-word))
1077 (forward-line 1)
1078 (when (and word
1079 ;; Don't mess with strings, unless it's the
1080 ;; enclosing set of quotes.
1081 (or (not (python-syntax-context 'string))
1083 (syntax-after
1084 (+ (1- (point))
1085 (current-indentation)
1086 (python-syntax-count-quotes (char-after) (point))))
1087 (string-to-syntax "|"))))
1088 (beginning-of-line)
1089 (delete-horizontal-space)
1090 (indent-to (python-indent-calculate-indentation)))))
1091 (forward-line 1))
1092 (move-marker end nil))))
1094 (defun python-indent-shift-left (start end &optional count)
1095 "Shift lines contained in region START END by COUNT columns to the left.
1096 COUNT defaults to `python-indent-offset'. If region isn't
1097 active, the current line is shifted. The shifted region includes
1098 the lines in which START and END lie. An error is signaled if
1099 any lines in the region are indented less than COUNT columns."
1100 (interactive
1101 (if mark-active
1102 (list (region-beginning) (region-end) current-prefix-arg)
1103 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1104 (if count
1105 (setq count (prefix-numeric-value count))
1106 (setq count python-indent-offset))
1107 (when (> count 0)
1108 (let ((deactivate-mark nil))
1109 (save-excursion
1110 (goto-char start)
1111 (while (< (point) end)
1112 (if (and (< (current-indentation) count)
1113 (not (looking-at "[ \t]*$")))
1114 (user-error "Can't shift all lines enough"))
1115 (forward-line))
1116 (indent-rigidly start end (- count))))))
1118 (defun python-indent-shift-right (start end &optional count)
1119 "Shift lines contained in region START END by COUNT columns to the right.
1120 COUNT defaults to `python-indent-offset'. If region isn't
1121 active, the current line is shifted. The shifted region includes
1122 the lines in which START and END lie."
1123 (interactive
1124 (if mark-active
1125 (list (region-beginning) (region-end) current-prefix-arg)
1126 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1127 (let ((deactivate-mark nil))
1128 (setq count (if count (prefix-numeric-value count)
1129 python-indent-offset))
1130 (indent-rigidly start end count)))
1132 (defun python-indent-post-self-insert-function ()
1133 "Adjust indentation after insertion of some characters.
1134 This function is intended to be added to `post-self-insert-hook.'
1135 If a line renders a paren alone, after adding a char before it,
1136 the line will be re-indented automatically if needed."
1137 (when (and electric-indent-mode
1138 (eq (char-before) last-command-event))
1139 (cond
1140 ;; Electric indent inside parens
1141 ((and
1142 (not (bolp))
1143 (let ((paren-start (python-syntax-context 'paren)))
1144 ;; Check that point is inside parens.
1145 (when paren-start
1146 (not
1147 ;; Filter the case where input is happening in the same
1148 ;; line where the open paren is.
1149 (= (line-number-at-pos)
1150 (line-number-at-pos paren-start)))))
1151 ;; When content has been added before the closing paren or a
1152 ;; comma has been inserted, it's ok to do the trick.
1154 (memq (char-after) '(?\) ?\] ?\}))
1155 (eq (char-before) ?,)))
1156 (save-excursion
1157 (goto-char (line-beginning-position))
1158 (let ((indentation (python-indent-calculate-indentation)))
1159 (when (< (current-indentation) indentation)
1160 (indent-line-to indentation)))))
1161 ;; Electric colon
1162 ((and (eq ?: last-command-event)
1163 (memq ?: electric-indent-chars)
1164 (not current-prefix-arg)
1165 ;; Trigger electric colon only at end of line
1166 (eolp)
1167 ;; Avoid re-indenting on extra colon
1168 (not (equal ?: (char-before (1- (point)))))
1169 (not (python-syntax-comment-or-string-p))
1170 ;; Never re-indent at beginning of defun
1171 (not (save-excursion
1172 (python-nav-beginning-of-statement)
1173 (python-info-looking-at-beginning-of-defun))))
1174 (python-indent-line)))))
1177 ;;; Navigation
1179 (defvar python-nav-beginning-of-defun-regexp
1180 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1181 "Regexp matching class or function definition.
1182 The name of the defun should be grouped so it can be retrieved
1183 via `match-string'.")
1185 (defun python-nav--beginning-of-defun (&optional arg)
1186 "Internal implementation of `python-nav-beginning-of-defun'.
1187 With positive ARG search backwards, else search forwards."
1188 (when (or (null arg) (= arg 0)) (setq arg 1))
1189 (let* ((re-search-fn (if (> arg 0)
1190 #'re-search-backward
1191 #'re-search-forward))
1192 (line-beg-pos (line-beginning-position))
1193 (line-content-start (+ line-beg-pos (current-indentation)))
1194 (pos (point-marker))
1195 (beg-indentation
1196 (and (> arg 0)
1197 (save-excursion
1198 (while (and
1199 (not (python-info-looking-at-beginning-of-defun))
1200 (python-nav-backward-block)))
1201 (or (and (python-info-looking-at-beginning-of-defun)
1202 (+ (current-indentation) python-indent-offset))
1203 0))))
1204 (found
1205 (progn
1206 (when (and (< arg 0)
1207 (python-info-looking-at-beginning-of-defun))
1208 (end-of-line 1))
1209 (while (and (funcall re-search-fn
1210 python-nav-beginning-of-defun-regexp nil t)
1211 (or (python-syntax-context-type)
1212 ;; Handle nested defuns when moving
1213 ;; backwards by checking indentation.
1214 (and (> arg 0)
1215 (not (= (current-indentation) 0))
1216 (>= (current-indentation) beg-indentation)))))
1217 (and (python-info-looking-at-beginning-of-defun)
1218 (or (not (= (line-number-at-pos pos)
1219 (line-number-at-pos)))
1220 (and (>= (point) line-beg-pos)
1221 (<= (point) line-content-start)
1222 (> pos line-content-start)))))))
1223 (if found
1224 (or (beginning-of-line 1) t)
1225 (and (goto-char pos) nil))))
1227 (defun python-nav-beginning-of-defun (&optional arg)
1228 "Move point to `beginning-of-defun'.
1229 With positive ARG search backwards else search forward.
1230 ARG nil or 0 defaults to 1. When searching backwards,
1231 nested defuns are handled with care depending on current
1232 point position. Return non-nil if point is moved to
1233 `beginning-of-defun'."
1234 (when (or (null arg) (= arg 0)) (setq arg 1))
1235 (let ((found))
1236 (while (and (not (= arg 0))
1237 (let ((keep-searching-p
1238 (python-nav--beginning-of-defun arg)))
1239 (when (and keep-searching-p (null found))
1240 (setq found t))
1241 keep-searching-p))
1242 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1243 found))
1245 (defun python-nav-end-of-defun ()
1246 "Move point to the end of def or class.
1247 Returns nil if point is not in a def or class."
1248 (interactive)
1249 (let ((beg-defun-indent)
1250 (beg-pos (point)))
1251 (when (or (python-info-looking-at-beginning-of-defun)
1252 (python-nav-beginning-of-defun 1)
1253 (python-nav-beginning-of-defun -1))
1254 (setq beg-defun-indent (current-indentation))
1255 (while (progn
1256 (python-nav-end-of-statement)
1257 (python-util-forward-comment 1)
1258 (and (> (current-indentation) beg-defun-indent)
1259 (not (eobp)))))
1260 (python-util-forward-comment -1)
1261 (forward-line 1)
1262 ;; Ensure point moves forward.
1263 (and (> beg-pos (point)) (goto-char beg-pos)))))
1265 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1266 "Move point using FN avoiding places with specific context.
1267 FN must take no arguments. POSCOMPFN is a two arguments function
1268 used to compare current and previous point after it is moved
1269 using FN, this is normally a less-than or greater-than
1270 comparison. Optional argument CONTEXTFN defaults to
1271 `python-syntax-context-type' and is used for checking current
1272 point context, it must return a non-nil value if this point must
1273 be skipped."
1274 (let ((contextfn (or contextfn 'python-syntax-context-type))
1275 (start-pos (point-marker))
1276 (prev-pos))
1277 (catch 'found
1278 (while t
1279 (let* ((newpos
1280 (and (funcall fn) (point-marker)))
1281 (context (funcall contextfn)))
1282 (cond ((and (not context) newpos
1283 (or (and (not prev-pos) newpos)
1284 (and prev-pos newpos
1285 (funcall poscompfn newpos prev-pos))))
1286 (throw 'found (point-marker)))
1287 ((and newpos context)
1288 (setq prev-pos (point)))
1289 (t (when (not newpos) (goto-char start-pos))
1290 (throw 'found nil))))))))
1292 (defun python-nav--forward-defun (arg)
1293 "Internal implementation of python-nav-{backward,forward}-defun.
1294 Uses ARG to define which function to call, and how many times
1295 repeat it."
1296 (let ((found))
1297 (while (and (> arg 0)
1298 (setq found
1299 (python-nav--syntactically
1300 (lambda ()
1301 (re-search-forward
1302 python-nav-beginning-of-defun-regexp nil t))
1303 '>)))
1304 (setq arg (1- arg)))
1305 (while (and (< arg 0)
1306 (setq found
1307 (python-nav--syntactically
1308 (lambda ()
1309 (re-search-backward
1310 python-nav-beginning-of-defun-regexp nil t))
1311 '<)))
1312 (setq arg (1+ arg)))
1313 found))
1315 (defun python-nav-backward-defun (&optional arg)
1316 "Navigate to closer defun backward ARG times.
1317 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1318 nested definitions."
1319 (interactive "^p")
1320 (python-nav--forward-defun (- (or arg 1))))
1322 (defun python-nav-forward-defun (&optional arg)
1323 "Navigate to closer defun forward ARG times.
1324 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1325 nested definitions."
1326 (interactive "^p")
1327 (python-nav--forward-defun (or arg 1)))
1329 (defun python-nav-beginning-of-statement ()
1330 "Move to start of current statement."
1331 (interactive "^")
1332 (back-to-indentation)
1333 (let* ((ppss (syntax-ppss))
1334 (context-point
1336 (python-syntax-context 'paren ppss)
1337 (python-syntax-context 'string ppss))))
1338 (cond ((bobp))
1339 (context-point
1340 (goto-char context-point)
1341 (python-nav-beginning-of-statement))
1342 ((save-excursion
1343 (forward-line -1)
1344 (python-info-line-ends-backslash-p))
1345 (forward-line -1)
1346 (python-nav-beginning-of-statement))))
1347 (point-marker))
1349 (defun python-nav-end-of-statement (&optional noend)
1350 "Move to end of current statement.
1351 Optional argument NOEND is internal and makes the logic to not
1352 jump to the end of line when moving forward searching for the end
1353 of the statement."
1354 (interactive "^")
1355 (let (string-start bs-pos)
1356 (while (and (or noend (goto-char (line-end-position)))
1357 (not (eobp))
1358 (cond ((setq string-start (python-syntax-context 'string))
1359 (goto-char string-start)
1360 (if (python-syntax-context 'paren)
1361 ;; Ended up inside a paren, roll again.
1362 (python-nav-end-of-statement t)
1363 ;; This is not inside a paren, move to the
1364 ;; end of this string.
1365 (goto-char (+ (point)
1366 (python-syntax-count-quotes
1367 (char-after (point)) (point))))
1368 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1369 (goto-char (point-max)))))
1370 ((python-syntax-context 'paren)
1371 ;; The statement won't end before we've escaped
1372 ;; at least one level of parenthesis.
1373 (condition-case err
1374 (goto-char (scan-lists (point) 1 -1))
1375 (scan-error (goto-char (nth 3 err)))))
1376 ((setq bs-pos (python-info-line-ends-backslash-p))
1377 (goto-char bs-pos)
1378 (forward-line 1))))))
1379 (point-marker))
1381 (defun python-nav-backward-statement (&optional arg)
1382 "Move backward to previous statement.
1383 With ARG, repeat. See `python-nav-forward-statement'."
1384 (interactive "^p")
1385 (or arg (setq arg 1))
1386 (python-nav-forward-statement (- arg)))
1388 (defun python-nav-forward-statement (&optional arg)
1389 "Move forward to next statement.
1390 With ARG, repeat. With negative argument, move ARG times
1391 backward to previous statement."
1392 (interactive "^p")
1393 (or arg (setq arg 1))
1394 (while (> arg 0)
1395 (python-nav-end-of-statement)
1396 (python-util-forward-comment)
1397 (python-nav-beginning-of-statement)
1398 (setq arg (1- arg)))
1399 (while (< arg 0)
1400 (python-nav-beginning-of-statement)
1401 (python-util-forward-comment -1)
1402 (python-nav-beginning-of-statement)
1403 (setq arg (1+ arg))))
1405 (defun python-nav-beginning-of-block ()
1406 "Move to start of current block."
1407 (interactive "^")
1408 (let ((starting-pos (point)))
1409 (if (progn
1410 (python-nav-beginning-of-statement)
1411 (looking-at (python-rx block-start)))
1412 (point-marker)
1413 ;; Go to first line beginning a statement
1414 (while (and (not (bobp))
1415 (or (and (python-nav-beginning-of-statement) nil)
1416 (python-info-current-line-comment-p)
1417 (python-info-current-line-empty-p)))
1418 (forward-line -1))
1419 (let ((block-matching-indent
1420 (- (current-indentation) python-indent-offset)))
1421 (while
1422 (and (python-nav-backward-block)
1423 (> (current-indentation) block-matching-indent)))
1424 (if (and (looking-at (python-rx block-start))
1425 (= (current-indentation) block-matching-indent))
1426 (point-marker)
1427 (and (goto-char starting-pos) nil))))))
1429 (defun python-nav-end-of-block ()
1430 "Move to end of current block."
1431 (interactive "^")
1432 (when (python-nav-beginning-of-block)
1433 (let ((block-indentation (current-indentation)))
1434 (python-nav-end-of-statement)
1435 (while (and (forward-line 1)
1436 (not (eobp))
1437 (or (and (> (current-indentation) block-indentation)
1438 (or (python-nav-end-of-statement) t))
1439 (python-info-current-line-comment-p)
1440 (python-info-current-line-empty-p))))
1441 (python-util-forward-comment -1)
1442 (point-marker))))
1444 (defun python-nav-backward-block (&optional arg)
1445 "Move backward to previous block of code.
1446 With ARG, repeat. See `python-nav-forward-block'."
1447 (interactive "^p")
1448 (or arg (setq arg 1))
1449 (python-nav-forward-block (- arg)))
1451 (defun python-nav-forward-block (&optional arg)
1452 "Move forward to next block of code.
1453 With ARG, repeat. With negative argument, move ARG times
1454 backward to previous block."
1455 (interactive "^p")
1456 (or arg (setq arg 1))
1457 (let ((block-start-regexp
1458 (python-rx line-start (* whitespace) block-start))
1459 (starting-pos (point)))
1460 (while (> arg 0)
1461 (python-nav-end-of-statement)
1462 (while (and
1463 (re-search-forward block-start-regexp nil t)
1464 (python-syntax-context-type)))
1465 (setq arg (1- arg)))
1466 (while (< arg 0)
1467 (python-nav-beginning-of-statement)
1468 (while (and
1469 (re-search-backward block-start-regexp nil t)
1470 (python-syntax-context-type)))
1471 (setq arg (1+ arg)))
1472 (python-nav-beginning-of-statement)
1473 (if (not (looking-at (python-rx block-start)))
1474 (and (goto-char starting-pos) nil)
1475 (and (not (= (point) starting-pos)) (point-marker)))))
1477 (defun python-nav--lisp-forward-sexp (&optional arg)
1478 "Standard version `forward-sexp'.
1479 It ignores completely the value of `forward-sexp-function' by
1480 setting it to nil before calling `forward-sexp'. With positive
1481 ARG move forward only one sexp, else move backwards."
1482 (let ((forward-sexp-function)
1483 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1484 (forward-sexp arg)))
1486 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1487 "Safe version of standard `forward-sexp'.
1488 When at end of sexp (i.e. looking at a opening/closing paren)
1489 skips it instead of throwing an error. With positive ARG move
1490 forward only one sexp, else move backwards."
1491 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1492 (paren-regexp
1493 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1494 (search-fn
1495 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1496 (condition-case nil
1497 (python-nav--lisp-forward-sexp arg)
1498 (error
1499 (while (and (funcall search-fn paren-regexp nil t)
1500 (python-syntax-context 'paren)))))))
1502 (defun python-nav--forward-sexp (&optional dir safe)
1503 "Move to forward sexp.
1504 With positive optional argument DIR direction move forward, else
1505 backwards. When optional argument SAFE is non-nil do not throw
1506 errors when at end of sexp, skip it instead."
1507 (setq dir (or dir 1))
1508 (unless (= dir 0)
1509 (let* ((forward-p (if (> dir 0)
1510 (and (setq dir 1) t)
1511 (and (setq dir -1) nil)))
1512 (context-type (python-syntax-context-type)))
1513 (cond
1514 ((memq context-type '(string comment))
1515 ;; Inside of a string, get out of it.
1516 (let ((forward-sexp-function))
1517 (forward-sexp dir)))
1518 ((or (eq context-type 'paren)
1519 (and forward-p (looking-at (python-rx open-paren)))
1520 (and (not forward-p)
1521 (eq (syntax-class (syntax-after (1- (point))))
1522 (car (string-to-syntax ")")))))
1523 ;; Inside a paren or looking at it, lisp knows what to do.
1524 (if safe
1525 (python-nav--lisp-forward-sexp-safe dir)
1526 (python-nav--lisp-forward-sexp dir)))
1528 ;; This part handles the lispy feel of
1529 ;; `python-nav-forward-sexp'. Knowing everything about the
1530 ;; current context and the context of the next sexp tries to
1531 ;; follow the lisp sexp motion commands in a symmetric manner.
1532 (let* ((context
1533 (cond
1534 ((python-info-beginning-of-block-p) 'block-start)
1535 ((python-info-end-of-block-p) 'block-end)
1536 ((python-info-beginning-of-statement-p) 'statement-start)
1537 ((python-info-end-of-statement-p) 'statement-end)))
1538 (next-sexp-pos
1539 (save-excursion
1540 (if safe
1541 (python-nav--lisp-forward-sexp-safe dir)
1542 (python-nav--lisp-forward-sexp dir))
1543 (point)))
1544 (next-sexp-context
1545 (save-excursion
1546 (goto-char next-sexp-pos)
1547 (cond
1548 ((python-info-beginning-of-block-p) 'block-start)
1549 ((python-info-end-of-block-p) 'block-end)
1550 ((python-info-beginning-of-statement-p) 'statement-start)
1551 ((python-info-end-of-statement-p) 'statement-end)
1552 ((python-info-statement-starts-block-p) 'starts-block)
1553 ((python-info-statement-ends-block-p) 'ends-block)))))
1554 (if forward-p
1555 (cond ((and (not (eobp))
1556 (python-info-current-line-empty-p))
1557 (python-util-forward-comment dir)
1558 (python-nav--forward-sexp dir))
1559 ((eq context 'block-start)
1560 (python-nav-end-of-block))
1561 ((eq context 'statement-start)
1562 (python-nav-end-of-statement))
1563 ((and (memq context '(statement-end block-end))
1564 (eq next-sexp-context 'ends-block))
1565 (goto-char next-sexp-pos)
1566 (python-nav-end-of-block))
1567 ((and (memq context '(statement-end block-end))
1568 (eq next-sexp-context 'starts-block))
1569 (goto-char next-sexp-pos)
1570 (python-nav-end-of-block))
1571 ((memq context '(statement-end block-end))
1572 (goto-char next-sexp-pos)
1573 (python-nav-end-of-statement))
1574 (t (goto-char next-sexp-pos)))
1575 (cond ((and (not (bobp))
1576 (python-info-current-line-empty-p))
1577 (python-util-forward-comment dir)
1578 (python-nav--forward-sexp dir))
1579 ((eq context 'block-end)
1580 (python-nav-beginning-of-block))
1581 ((eq context 'statement-end)
1582 (python-nav-beginning-of-statement))
1583 ((and (memq context '(statement-start block-start))
1584 (eq next-sexp-context 'starts-block))
1585 (goto-char next-sexp-pos)
1586 (python-nav-beginning-of-block))
1587 ((and (memq context '(statement-start block-start))
1588 (eq next-sexp-context 'ends-block))
1589 (goto-char next-sexp-pos)
1590 (python-nav-beginning-of-block))
1591 ((memq context '(statement-start block-start))
1592 (goto-char next-sexp-pos)
1593 (python-nav-beginning-of-statement))
1594 (t (goto-char next-sexp-pos))))))))))
1596 (defun python-nav-forward-sexp (&optional arg)
1597 "Move forward across expressions.
1598 With ARG, do it that many times. Negative arg -N means move
1599 backward N times."
1600 (interactive "^p")
1601 (or arg (setq arg 1))
1602 (while (> arg 0)
1603 (python-nav--forward-sexp 1)
1604 (setq arg (1- arg)))
1605 (while (< arg 0)
1606 (python-nav--forward-sexp -1)
1607 (setq arg (1+ arg))))
1609 (defun python-nav-backward-sexp (&optional arg)
1610 "Move backward across expressions.
1611 With ARG, do it that many times. Negative arg -N means move
1612 forward N times."
1613 (interactive "^p")
1614 (or arg (setq arg 1))
1615 (python-nav-forward-sexp (- arg)))
1617 (defun python-nav-forward-sexp-safe (&optional arg)
1618 "Move forward safely across expressions.
1619 With ARG, do it that many times. Negative arg -N means move
1620 backward N times."
1621 (interactive "^p")
1622 (or arg (setq arg 1))
1623 (while (> arg 0)
1624 (python-nav--forward-sexp 1 t)
1625 (setq arg (1- arg)))
1626 (while (< arg 0)
1627 (python-nav--forward-sexp -1 t)
1628 (setq arg (1+ arg))))
1630 (defun python-nav-backward-sexp-safe (&optional arg)
1631 "Move backward safely across expressions.
1632 With ARG, do it that many times. Negative arg -N means move
1633 forward N times."
1634 (interactive "^p")
1635 (or arg (setq arg 1))
1636 (python-nav-forward-sexp-safe (- arg)))
1638 (defun python-nav--up-list (&optional dir)
1639 "Internal implementation of `python-nav-up-list'.
1640 DIR is always 1 or -1 and comes sanitized from
1641 `python-nav-up-list' calls."
1642 (let ((context (python-syntax-context-type))
1643 (forward-p (> dir 0)))
1644 (cond
1645 ((memq context '(string comment)))
1646 ((eq context 'paren)
1647 (let ((forward-sexp-function))
1648 (up-list dir)))
1649 ((and forward-p (python-info-end-of-block-p))
1650 (let ((parent-end-pos
1651 (save-excursion
1652 (let ((indentation (and
1653 (python-nav-beginning-of-block)
1654 (current-indentation))))
1655 (while (and indentation
1656 (> indentation 0)
1657 (>= (current-indentation) indentation)
1658 (python-nav-backward-block)))
1659 (python-nav-end-of-block)))))
1660 (and (> (or parent-end-pos (point)) (point))
1661 (goto-char parent-end-pos))))
1662 (forward-p (python-nav-end-of-block))
1663 ((and (not forward-p)
1664 (> (current-indentation) 0)
1665 (python-info-beginning-of-block-p))
1666 (let ((prev-block-pos
1667 (save-excursion
1668 (let ((indentation (current-indentation)))
1669 (while (and (python-nav-backward-block)
1670 (>= (current-indentation) indentation))))
1671 (point))))
1672 (and (> (point) prev-block-pos)
1673 (goto-char prev-block-pos))))
1674 ((not forward-p) (python-nav-beginning-of-block)))))
1676 (defun python-nav-up-list (&optional arg)
1677 "Move forward out of one level of parentheses (or blocks).
1678 With ARG, do this that many times.
1679 A negative argument means move backward but still to a less deep spot.
1680 This command assumes point is not in a string or comment."
1681 (interactive "^p")
1682 (or arg (setq arg 1))
1683 (while (> arg 0)
1684 (python-nav--up-list 1)
1685 (setq arg (1- arg)))
1686 (while (< arg 0)
1687 (python-nav--up-list -1)
1688 (setq arg (1+ arg))))
1690 (defun python-nav-backward-up-list (&optional arg)
1691 "Move backward out of one level of parentheses (or blocks).
1692 With ARG, do this that many times.
1693 A negative argument means move forward but still to a less deep spot.
1694 This command assumes point is not in a string or comment."
1695 (interactive "^p")
1696 (or arg (setq arg 1))
1697 (python-nav-up-list (- arg)))
1699 (defun python-nav-if-name-main ()
1700 "Move point at the beginning the __main__ block.
1701 When \"if __name__ == '__main__':\" is found returns its
1702 position, else returns nil."
1703 (interactive)
1704 (let ((point (point))
1705 (found (catch 'found
1706 (goto-char (point-min))
1707 (while (re-search-forward
1708 (python-rx line-start
1709 "if" (+ space)
1710 "__name__" (+ space)
1711 "==" (+ space)
1712 (group-n 1 (or ?\" ?\'))
1713 "__main__" (backref 1) (* space) ":")
1714 nil t)
1715 (when (not (python-syntax-context-type))
1716 (beginning-of-line)
1717 (throw 'found t))))))
1718 (if found
1719 (point)
1720 (ignore (goto-char point)))))
1723 ;;; Shell integration
1725 (defcustom python-shell-buffer-name "Python"
1726 "Default buffer name for Python interpreter."
1727 :type 'string
1728 :group 'python
1729 :safe 'stringp)
1731 (defcustom python-shell-interpreter "python"
1732 "Default Python interpreter for shell."
1733 :type 'string
1734 :group 'python)
1736 (defcustom python-shell-internal-buffer-name "Python Internal"
1737 "Default buffer name for the Internal Python interpreter."
1738 :type 'string
1739 :group 'python
1740 :safe 'stringp)
1742 (defcustom python-shell-interpreter-args "-i"
1743 "Default arguments for the Python interpreter."
1744 :type 'string
1745 :group 'python)
1747 (defcustom python-shell-interpreter-interactive-arg "-i"
1748 "Interpreter argument to force it to run interactively."
1749 :type 'string
1750 :version "24.4")
1752 (defcustom python-shell-prompt-detect-enabled t
1753 "Non-nil enables autodetection of interpreter prompts."
1754 :type 'boolean
1755 :safe 'booleanp
1756 :version "24.4")
1758 (defcustom python-shell-prompt-detect-failure-warning t
1759 "Non-nil enables warnings when detection of prompts fail."
1760 :type 'boolean
1761 :safe 'booleanp
1762 :version "24.4")
1764 (defcustom python-shell-prompt-input-regexps
1765 '(">>> " "\\.\\.\\. " ; Python
1766 "In \\[[0-9]+\\]: " ; IPython
1767 " \\.\\.\\.: " ; IPython
1768 ;; Using ipdb outside IPython may fail to cleanup and leave static
1769 ;; IPython prompts activated, this adds some safeguard for that.
1770 "In : " "\\.\\.\\.: ")
1771 "List of regular expressions matching input prompts."
1772 :type '(repeat string)
1773 :version "24.4")
1775 (defcustom python-shell-prompt-output-regexps
1776 '("" ; Python
1777 "Out\\[[0-9]+\\]: " ; IPython
1778 "Out :") ; ipdb safeguard
1779 "List of regular expressions matching output prompts."
1780 :type '(repeat string)
1781 :version "24.4")
1783 (defcustom python-shell-prompt-regexp ">>> "
1784 "Regular expression matching top level input prompt of Python shell.
1785 It should not contain a caret (^) at the beginning."
1786 :type 'string)
1788 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1789 "Regular expression matching block input prompt of Python shell.
1790 It should not contain a caret (^) at the beginning."
1791 :type 'string)
1793 (defcustom python-shell-prompt-output-regexp ""
1794 "Regular expression matching output prompt of Python shell.
1795 It should not contain a caret (^) at the beginning."
1796 :type 'string)
1798 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1799 "Regular expression matching pdb input prompt of Python shell.
1800 It should not contain a caret (^) at the beginning."
1801 :type 'string)
1803 (define-obsolete-variable-alias
1804 'python-shell-enable-font-lock 'python-shell-font-lock-enable "24.5")
1806 (defcustom python-shell-font-lock-enable t
1807 "Should syntax highlighting be enabled in the Python shell buffer?
1808 Restart the Python shell after changing this variable for it to take effect."
1809 :type 'boolean
1810 :group 'python
1811 :safe 'booleanp)
1813 (defcustom python-shell-process-environment nil
1814 "List of environment variables for Python shell.
1815 This variable follows the same rules as `process-environment'
1816 since it merges with it before the process creation routines are
1817 called. When this variable is nil, the Python shell is run with
1818 the default `process-environment'."
1819 :type '(repeat string)
1820 :group 'python
1821 :safe 'listp)
1823 (defcustom python-shell-extra-pythonpaths nil
1824 "List of extra pythonpaths for Python shell.
1825 The values of this variable are added to the existing value of
1826 PYTHONPATH in the `process-environment' variable."
1827 :type '(repeat string)
1828 :group 'python
1829 :safe 'listp)
1831 (defcustom python-shell-exec-path nil
1832 "List of path to search for binaries.
1833 This variable follows the same rules as `exec-path' since it
1834 merges with it before the process creation routines are called.
1835 When this variable is nil, the Python shell is run with the
1836 default `exec-path'."
1837 :type '(repeat string)
1838 :group 'python
1839 :safe 'listp)
1841 (defcustom python-shell-virtualenv-path nil
1842 "Path to virtualenv root.
1843 This variable, when set to a string, makes the values stored in
1844 `python-shell-process-environment' and `python-shell-exec-path'
1845 to be modified properly so shells are started with the specified
1846 virtualenv."
1847 :type '(choice (const nil) string)
1848 :group 'python
1849 :safe 'stringp)
1851 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1852 python-ffap-setup-code
1853 python-eldoc-setup-code)
1854 "List of code run by `python-shell-send-setup-codes'."
1855 :type '(repeat symbol)
1856 :group 'python
1857 :safe 'listp)
1859 (defcustom python-shell-compilation-regexp-alist
1860 `((,(rx line-start (1+ (any " \t")) "File \""
1861 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1862 "\", line " (group (1+ digit)))
1863 1 2)
1864 (,(rx " in file " (group (1+ not-newline)) " on line "
1865 (group (1+ digit)))
1866 1 2)
1867 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1868 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1869 1 2))
1870 "`compilation-error-regexp-alist' for inferior Python."
1871 :type '(alist string)
1872 :group 'python)
1874 (defvar python-shell--prompt-calculated-input-regexp nil
1875 "Calculated input prompt regexp for inferior python shell.
1876 Do not set this variable directly, instead use
1877 `python-shell-prompt-set-calculated-regexps'.")
1879 (defvar python-shell--prompt-calculated-output-regexp nil
1880 "Calculated output prompt regexp for inferior python shell.
1881 Do not set this variable directly, instead use
1882 `python-shell-set-prompt-regexp'.")
1884 (defun python-shell-prompt-detect ()
1885 "Detect prompts for the current `python-shell-interpreter'.
1886 When prompts can be retrieved successfully from the
1887 `python-shell-interpreter' run with
1888 `python-shell-interpreter-interactive-arg', returns a list of
1889 three elements, where the first two are input prompts and the
1890 last one is an output prompt. When no prompts can be detected
1891 and `python-shell-prompt-detect-failure-warning' is non-nil,
1892 shows a warning with instructions to avoid hangs and returns nil.
1893 When `python-shell-prompt-detect-enabled' is nil avoids any
1894 detection and just returns nil."
1895 (when python-shell-prompt-detect-enabled
1896 (let* ((process-environment (python-shell-calculate-process-environment))
1897 (exec-path (python-shell-calculate-exec-path))
1898 (code (concat
1899 "import sys\n"
1900 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1901 ;; JSON is built manually for compatibility
1902 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1903 "print (ps_json)\n"
1904 "sys.exit(0)\n"))
1905 (output
1906 (with-temp-buffer
1907 ;; TODO: improve error handling by using
1908 ;; `condition-case' and displaying the error message to
1909 ;; the user in the no-prompts warning.
1910 (ignore-errors
1911 (let ((code-file (python-shell--save-temp-file code)))
1912 ;; Use `process-file' as it is remote-host friendly.
1913 (process-file
1914 python-shell-interpreter
1915 code-file
1916 '(t nil)
1918 python-shell-interpreter-interactive-arg)
1919 ;; Try to cleanup
1920 (delete-file code-file)))
1921 (buffer-string)))
1922 (prompts
1923 (catch 'prompts
1924 (dolist (line (split-string output "\n" t))
1925 (let ((res
1926 ;; Check if current line is a valid JSON array
1927 (and (string= (substring line 0 2) "[\"")
1928 (ignore-errors
1929 ;; Return prompts as a list, not vector
1930 (append (json-read-from-string line) nil)))))
1931 ;; The list must contain 3 strings, where the first
1932 ;; is the input prompt, the second is the block
1933 ;; prompt and the last one is the output prompt. The
1934 ;; input prompt is the only one that can't be empty.
1935 (when (and (= (length res) 3)
1936 (cl-every #'stringp res)
1937 (not (string= (car res) "")))
1938 (throw 'prompts res))))
1939 nil)))
1940 (when (and (not prompts)
1941 python-shell-prompt-detect-failure-warning)
1942 (lwarn
1943 '(python python-shell-prompt-regexp)
1944 :warning
1945 (concat
1946 "Python shell prompts cannot be detected.\n"
1947 "If your emacs session hangs when starting python shells\n"
1948 "recover with `keyboard-quit' and then try fixing the\n"
1949 "interactive flag for your interpreter by adjusting the\n"
1950 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1951 "matching shell prompts in the directory-local friendly vars:\n"
1952 " + `python-shell-prompt-regexp'\n"
1953 " + `python-shell-prompt-block-regexp'\n"
1954 " + `python-shell-prompt-output-regexp'\n"
1955 "Or alternatively in:\n"
1956 " + `python-shell-prompt-input-regexps'\n"
1957 " + `python-shell-prompt-output-regexps'")))
1958 prompts)))
1960 (defun python-shell-prompt-validate-regexps ()
1961 "Validate all user provided regexps for prompts.
1962 Signals `user-error' if any of these vars contain invalid
1963 regexps: `python-shell-prompt-regexp',
1964 `python-shell-prompt-block-regexp',
1965 `python-shell-prompt-pdb-regexp',
1966 `python-shell-prompt-output-regexp',
1967 `python-shell-prompt-input-regexps',
1968 `python-shell-prompt-output-regexps'."
1969 (dolist (symbol (list 'python-shell-prompt-input-regexps
1970 'python-shell-prompt-output-regexps
1971 'python-shell-prompt-regexp
1972 'python-shell-prompt-block-regexp
1973 'python-shell-prompt-pdb-regexp
1974 'python-shell-prompt-output-regexp))
1975 (dolist (regexp (let ((regexps (symbol-value symbol)))
1976 (if (listp regexps)
1977 regexps
1978 (list regexps))))
1979 (when (not (python-util-valid-regexp-p regexp))
1980 (user-error "Invalid regexp %s in `%s'"
1981 regexp symbol)))))
1983 (defun python-shell-prompt-set-calculated-regexps ()
1984 "Detect and set input and output prompt regexps.
1985 Build and set the values for `python-shell-input-prompt-regexp'
1986 and `python-shell-output-prompt-regexp' using the values from
1987 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
1988 `python-shell-prompt-pdb-regexp',
1989 `python-shell-prompt-output-regexp',
1990 `python-shell-prompt-input-regexps',
1991 `python-shell-prompt-output-regexps' and detected prompts from
1992 `python-shell-prompt-detect'."
1993 (when (not (and python-shell--prompt-calculated-input-regexp
1994 python-shell--prompt-calculated-output-regexp))
1995 (let* ((detected-prompts (python-shell-prompt-detect))
1996 (input-prompts nil)
1997 (output-prompts nil)
1998 (build-regexp
1999 (lambda (prompts)
2000 (concat "^\\("
2001 (mapconcat #'identity
2002 (sort prompts
2003 (lambda (a b)
2004 (let ((length-a (length a))
2005 (length-b (length b)))
2006 (if (= length-a length-b)
2007 (string< a b)
2008 (> (length a) (length b))))))
2009 "\\|")
2010 "\\)"))))
2011 ;; Validate ALL regexps
2012 (python-shell-prompt-validate-regexps)
2013 ;; Collect all user defined input prompts
2014 (dolist (prompt (append python-shell-prompt-input-regexps
2015 (list python-shell-prompt-regexp
2016 python-shell-prompt-block-regexp
2017 python-shell-prompt-pdb-regexp)))
2018 (cl-pushnew prompt input-prompts :test #'string=))
2019 ;; Collect all user defined output prompts
2020 (dolist (prompt (cons python-shell-prompt-output-regexp
2021 python-shell-prompt-output-regexps))
2022 (cl-pushnew prompt output-prompts :test #'string=))
2023 ;; Collect detected prompts if any
2024 (when detected-prompts
2025 (dolist (prompt (butlast detected-prompts))
2026 (setq prompt (regexp-quote prompt))
2027 (cl-pushnew prompt input-prompts :test #'string=))
2028 (cl-pushnew (regexp-quote
2029 (car (last detected-prompts)))
2030 output-prompts :test #'string=))
2031 ;; Set input and output prompt regexps from collected prompts
2032 (setq python-shell--prompt-calculated-input-regexp
2033 (funcall build-regexp input-prompts)
2034 python-shell--prompt-calculated-output-regexp
2035 (funcall build-regexp output-prompts)))))
2037 (defun python-shell-get-process-name (dedicated)
2038 "Calculate the appropriate process name for inferior Python process.
2039 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2040 returns a string with the form
2041 `python-shell-buffer-name'[variable `buffer-file-name'] else
2042 returns the value of `python-shell-buffer-name'."
2043 (let ((process-name
2044 (if (and dedicated
2045 buffer-file-name)
2046 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
2047 (format "%s" python-shell-buffer-name))))
2048 process-name))
2050 (defun python-shell-internal-get-process-name ()
2051 "Calculate the appropriate process name for Internal Python process.
2052 The name is calculated from `python-shell-global-buffer-name' and
2053 a hash of all relevant global shell settings in order to ensure
2054 uniqueness for different types of configurations."
2055 (format "%s [%s]"
2056 python-shell-internal-buffer-name
2057 (md5
2058 (concat
2059 python-shell-interpreter
2060 python-shell-interpreter-args
2061 python-shell--prompt-calculated-input-regexp
2062 python-shell--prompt-calculated-output-regexp
2063 (mapconcat #'symbol-value python-shell-setup-codes "")
2064 (mapconcat #'identity python-shell-process-environment "")
2065 (mapconcat #'identity python-shell-extra-pythonpaths "")
2066 (mapconcat #'identity python-shell-exec-path "")
2067 (or python-shell-virtualenv-path "")
2068 (mapconcat #'identity python-shell-exec-path "")))))
2070 (defun python-shell-parse-command () ;FIXME: why name it "parse"?
2071 "Calculate the string used to execute the inferior Python process."
2072 ;; FIXME: process-environment doesn't seem to be used anywhere within
2073 ;; this let.
2074 (let ((process-environment (python-shell-calculate-process-environment))
2075 (exec-path (python-shell-calculate-exec-path)))
2076 (format "%s %s"
2077 ;; FIXME: Why executable-find?
2078 (executable-find python-shell-interpreter)
2079 python-shell-interpreter-args)))
2081 (defun python-new-pythonpath ()
2082 "Calculate the new PYTHONPATH value from `python-shell-extra-pythonpaths'."
2083 (let ((pythonpath (getenv "PYTHONPATH"))
2084 (extra (mapconcat 'identity
2085 python-shell-extra-pythonpaths
2086 path-separator)))
2087 (if pythonpath
2088 (concat extra path-separator pythonpath)
2089 extra)))
2091 (defun python-shell-calculate-process-environment ()
2092 "Calculate process environment given `python-shell-virtualenv-path'."
2093 (let ((process-environment (append
2094 python-shell-process-environment
2095 process-environment nil))
2096 (virtualenv (if python-shell-virtualenv-path
2097 (directory-file-name python-shell-virtualenv-path)
2098 nil)))
2099 (when python-shell-extra-pythonpaths
2100 (setenv "PYTHONPATH" (python-new-pythonpath)))
2101 (if (not virtualenv)
2102 process-environment
2103 (setenv "PYTHONHOME" nil)
2104 (setenv "PATH" (format "%s/bin%s%s"
2105 virtualenv path-separator
2106 (or (getenv "PATH") "")))
2107 (setenv "VIRTUAL_ENV" virtualenv))
2108 process-environment))
2110 (defun python-shell-calculate-exec-path ()
2111 "Calculate exec path given `python-shell-virtualenv-path'."
2112 (let ((path (append python-shell-exec-path
2113 exec-path nil))) ;FIXME: Why nil?
2114 (if (not python-shell-virtualenv-path)
2115 path
2116 (cons (expand-file-name "bin" python-shell-virtualenv-path)
2117 path))))
2119 (defvar python-shell--package-depth 10)
2121 (defun python-shell-package-enable (directory package)
2122 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2123 (interactive
2124 (let* ((dir (expand-file-name
2125 (read-directory-name
2126 "Package root: "
2127 (file-name-directory
2128 (or (buffer-file-name) default-directory)))))
2129 (name (completing-read
2130 "Package: "
2131 (python-util-list-packages
2132 dir python-shell--package-depth))))
2133 (list dir name)))
2134 (python-shell-send-string
2135 (format
2136 (concat
2137 "import os.path;import sys;"
2138 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2139 "__package__ = '''%s''';"
2140 "import %s")
2141 directory package package)
2142 (python-shell-get-process)))
2144 (defun python-shell-accept-process-output (process &optional timeout regexp)
2145 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2146 Optional argument TIMEOUT is the timeout argument to
2147 `accept-process-output' calls. Optional argument REGEXP
2148 overrides the regexp to match the end of output, defaults to
2149 `comint-prompt-regexp.'. Returns non-nil when output was
2150 properly captured.
2152 This utility is useful in situations where the output may be
2153 received in chunks, since `accept-process-output' gives no
2154 guarantees they will be grabbed in a single call. An example use
2155 case for this would be the CPython shell start-up, where the
2156 banner and the initial prompt are received separetely."
2157 (let ((regexp (or regexp comint-prompt-regexp)))
2158 (catch 'found
2159 (while t
2160 (when (not (accept-process-output process timeout))
2161 (throw 'found nil))
2162 (when (looking-back regexp)
2163 (throw 'found t))))))
2165 (defun python-shell-comint-end-of-output-p (output)
2166 "Return non-nil if OUTPUT is ends with input prompt."
2167 (string-match
2168 ;; XXX: It seems on OSX an extra carriage return is attached
2169 ;; at the end of output, this handles that too.
2170 (concat
2171 "\r?\n?"
2172 ;; Remove initial caret from calculated regexp
2173 (replace-regexp-in-string
2174 (rx string-start ?^) ""
2175 python-shell--prompt-calculated-input-regexp)
2176 (rx eos))
2177 output))
2179 (define-obsolete-function-alias
2180 'python-comint-output-filter-function
2181 'ansi-color-filter-apply
2182 "24.5")
2184 (defun python-comint-postoutput-scroll-to-bottom (output)
2185 "Faster version of `comint-postoutput-scroll-to-bottom'.
2186 Avoids `recenter' calls until OUTPUT is completely sent."
2187 (when (and (not (string= "" output))
2188 (python-shell-comint-end-of-output-p
2189 (ansi-color-filter-apply output)))
2190 (comint-postoutput-scroll-to-bottom output))
2191 output)
2193 (defvar python-shell--parent-buffer nil)
2195 (defmacro python-shell-with-shell-buffer (&rest body)
2196 "Execute the forms in BODY with the shell buffer temporarily current.
2197 Signals an error if no shell buffer is available for current buffer."
2198 (declare (indent 0) (debug t))
2199 (let ((shell-buffer (make-symbol "shell-buffer")))
2200 `(let ((,shell-buffer (python-shell-get-buffer)))
2201 (when (not ,shell-buffer)
2202 (error "No inferior Python buffer available."))
2203 (with-current-buffer ,shell-buffer
2204 ,@body))))
2206 (defvar python-shell--font-lock-buffer nil)
2208 (defun python-shell-font-lock-get-or-create-buffer ()
2209 "Get or create a font-lock buffer for current inferior process."
2210 (python-shell-with-shell-buffer
2211 (if python-shell--font-lock-buffer
2212 python-shell--font-lock-buffer
2213 (let ((process-name
2214 (process-name (get-buffer-process (current-buffer)))))
2215 (generate-new-buffer
2216 (format "*%s-font-lock*" process-name))))))
2218 (defun python-shell-font-lock-kill-buffer ()
2219 "Kill the font-lock buffer safely."
2220 (python-shell-with-shell-buffer
2221 (when (and python-shell--font-lock-buffer
2222 (buffer-live-p python-shell--font-lock-buffer))
2223 (kill-buffer python-shell--font-lock-buffer)
2224 (when (eq major-mode 'inferior-python-mode)
2225 (setq python-shell--font-lock-buffer nil)))))
2227 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2228 "Execute the forms in BODY in the font-lock buffer.
2229 The value returned is the value of the last form in BODY. See
2230 also `with-current-buffer'."
2231 (declare (indent 0) (debug t))
2232 `(python-shell-with-shell-buffer
2233 (save-current-buffer
2234 (when (not (and python-shell--font-lock-buffer
2235 (get-buffer python-shell--font-lock-buffer)))
2236 (setq python-shell--font-lock-buffer
2237 (python-shell-font-lock-get-or-create-buffer)))
2238 (set-buffer python-shell--font-lock-buffer)
2239 (set (make-local-variable 'delay-mode-hooks) t)
2240 (let ((python-indent-guess-indent-offset nil))
2241 (when (not (eq major-mode 'python-mode))
2242 (python-mode))
2243 ,@body))))
2245 (defun python-shell-font-lock-cleanup-buffer ()
2246 "Cleanup the font-lock buffer.
2247 Provided as a command because this might be handy if something
2248 goes wrong and syntax highlighting in the shell gets messed up."
2249 (interactive)
2250 (python-shell-with-shell-buffer
2251 (python-shell-font-lock-with-font-lock-buffer
2252 (delete-region (point-min) (point-max)))))
2254 (defun python-shell-font-lock-comint-output-filter-function (output)
2255 "Clean up the font-lock buffer after any OUTPUT."
2256 (when (and (not (string= "" output))
2257 ;; Is end of output and is not just a prompt.
2258 (not (member
2259 (python-shell-comint-end-of-output-p
2260 (ansi-color-filter-apply output))
2261 '(nil 0))))
2262 ;; If output is other than an input prompt then "real" output has
2263 ;; been received and the font-lock buffer must be cleaned up.
2264 (python-shell-font-lock-cleanup-buffer))
2265 output)
2267 (defun python-shell-font-lock-post-command-hook ()
2268 "Fontifies current line in shell buffer."
2269 (if (eq this-command 'comint-send-input)
2270 ;; Add a newline when user sends input as this may be a block.
2271 (python-shell-font-lock-with-font-lock-buffer
2272 (goto-char (line-end-position))
2273 (newline))
2274 (when (and (python-util-comint-last-prompt)
2275 (> (point) (cdr (python-util-comint-last-prompt))))
2276 (let ((input (buffer-substring-no-properties
2277 (cdr (python-util-comint-last-prompt)) (point-max)))
2278 (old-input (python-shell-font-lock-with-font-lock-buffer
2279 (buffer-substring-no-properties
2280 (line-beginning-position) (point-max))))
2281 (current-point (point))
2282 (buffer-undo-list t))
2283 ;; When input hasn't changed, do nothing.
2284 (when (not (string= input old-input))
2285 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2286 (insert
2287 (python-shell-font-lock-with-font-lock-buffer
2288 (delete-region (line-beginning-position)
2289 (line-end-position))
2290 (insert input)
2291 ;; Ensure buffer is fontified, keeping it
2292 ;; compatible with Emacs < 24.4.
2293 (if (fboundp 'font-lock-ensure)
2294 (funcall 'font-lock-ensure)
2295 (font-lock-default-fontify-buffer))
2296 ;; Replace FACE text properties with FONT-LOCK-FACE so
2297 ;; they are not overwritten by comint buffer's font lock.
2298 (python-util-text-properties-replace-name
2299 'face 'font-lock-face)
2300 (buffer-substring (line-beginning-position)
2301 (line-end-position))))
2302 (goto-char current-point))))))
2304 (defun python-shell-font-lock-turn-on (&optional msg)
2305 "Turn on shell font-lock.
2306 With argument MSG show activation message."
2307 (interactive "p")
2308 (python-shell-with-shell-buffer
2309 (python-shell-font-lock-kill-buffer)
2310 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2311 (add-hook 'post-command-hook
2312 #'python-shell-font-lock-post-command-hook nil 'local)
2313 (add-hook 'kill-buffer-hook
2314 #'python-shell-font-lock-kill-buffer nil 'local)
2315 (add-hook 'comint-output-filter-functions
2316 #'python-shell-font-lock-comint-output-filter-function
2317 'append 'local)
2318 (when msg
2319 (message "Shell font-lock is enabled"))))
2321 (defun python-shell-font-lock-turn-off (&optional msg)
2322 "Turn off shell font-lock.
2323 With argument MSG show deactivation message."
2324 (interactive "p")
2325 (python-shell-with-shell-buffer
2326 (python-shell-font-lock-kill-buffer)
2327 (when (python-util-comint-last-prompt)
2328 ;; Cleanup current fontification
2329 (remove-text-properties
2330 (cdr (python-util-comint-last-prompt))
2331 (line-end-position)
2332 '(face nil font-lock-face nil)))
2333 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2334 (remove-hook 'post-command-hook
2335 #'python-shell-font-lock-post-command-hook'local)
2336 (remove-hook 'kill-buffer-hook
2337 #'python-shell-font-lock-kill-buffer 'local)
2338 (remove-hook 'comint-output-filter-functions
2339 #'python-shell-font-lock-comint-output-filter-function
2340 'local)
2341 (when msg
2342 (message "Shell font-lock is disabled"))))
2344 (defun python-shell-font-lock-toggle (&optional msg)
2345 "Toggle font-lock for shell.
2346 With argument MSG show activation/deactivation message."
2347 (interactive "p")
2348 (python-shell-with-shell-buffer
2349 (set (make-local-variable 'python-shell-font-lock-enable)
2350 (not python-shell-font-lock-enable))
2351 (if python-shell-font-lock-enable
2352 (python-shell-font-lock-turn-on msg)
2353 (python-shell-font-lock-turn-off msg))
2354 python-shell-font-lock-enable))
2356 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2357 "Major mode for Python inferior process.
2358 Runs a Python interpreter as a subprocess of Emacs, with Python
2359 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2360 and `python-shell-interpreter-args' control which Python
2361 interpreter is run. Variables
2362 `python-shell-prompt-regexp',
2363 `python-shell-prompt-output-regexp',
2364 `python-shell-prompt-block-regexp',
2365 `python-shell-font-lock-enable',
2366 `python-shell-completion-setup-code',
2367 `python-shell-completion-string-code',
2368 `python-eldoc-setup-code', `python-eldoc-string-code',
2369 `python-ffap-setup-code' and `python-ffap-string-code' can
2370 customize this mode for different Python interpreters.
2372 This mode resets `comint-output-filter-functions' locally, so you
2373 may want to re-add custom functions to it using the
2374 `inferior-python-mode-hook'.
2376 You can also add additional setup code to be run at
2377 initialization of the interpreter via `python-shell-setup-codes'
2378 variable.
2380 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2381 (let ((interpreter python-shell-interpreter)
2382 (args python-shell-interpreter-args))
2383 (when python-shell--parent-buffer
2384 (python-util-clone-local-variables python-shell--parent-buffer))
2385 ;; Users can override default values for these vars when calling
2386 ;; `run-python'. This ensures new values let-bound in
2387 ;; `python-shell-make-comint' are locally set.
2388 (set (make-local-variable 'python-shell-interpreter) interpreter)
2389 (set (make-local-variable 'python-shell-interpreter-args) args))
2390 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2391 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2392 (python-shell-prompt-set-calculated-regexps)
2393 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
2394 comint-prompt-read-only t)
2395 (setq mode-line-process '(":%s"))
2396 (set (make-local-variable 'comint-output-filter-functions)
2397 '(ansi-color-process-output
2398 python-pdbtrack-comint-output-filter-function
2399 python-comint-postoutput-scroll-to-bottom))
2400 (set (make-local-variable 'compilation-error-regexp-alist)
2401 python-shell-compilation-regexp-alist)
2402 (define-key inferior-python-mode-map [remap complete-symbol]
2403 'completion-at-point)
2404 (add-hook 'completion-at-point-functions
2405 'python-shell-completion-at-point nil 'local)
2406 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
2407 'python-shell-completion-at-point)
2408 (define-key inferior-python-mode-map "\t"
2409 'python-shell-completion-complete-or-indent)
2410 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2411 (make-local-variable 'python-pdbtrack-tracked-buffer)
2412 (make-local-variable 'python-shell-internal-last-output)
2413 (when python-shell-font-lock-enable
2414 (python-shell-font-lock-turn-on))
2415 (compilation-shell-minor-mode 1)
2416 (python-shell-accept-process-output
2417 (get-buffer-process (current-buffer))))
2419 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
2420 "Create a Python shell comint buffer.
2421 CMD is the Python command to be executed and PROC-NAME is the
2422 process name the comint buffer will get. After the comint buffer
2423 is created the `inferior-python-mode' is activated. When
2424 optional argument POP is non-nil the buffer is shown. When
2425 optional argument INTERNAL is non-nil this process is run on a
2426 buffer with a name that starts with a space, following the Emacs
2427 convention for temporary/internal buffers, and also makes sure
2428 the user is not queried for confirmation when the process is
2429 killed."
2430 (save-excursion
2431 (let* ((proc-buffer-name
2432 (format (if (not internal) "*%s*" " *%s*") proc-name))
2433 (process-environment (python-shell-calculate-process-environment))
2434 (exec-path (python-shell-calculate-exec-path)))
2435 (when (not (comint-check-proc proc-buffer-name))
2436 (let* ((cmdlist (split-string-and-unquote cmd))
2437 (interpreter (car cmdlist))
2438 (args (cdr cmdlist))
2439 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2440 interpreter nil args))
2441 (python-shell--parent-buffer (current-buffer))
2442 (process (get-buffer-process buffer))
2443 ;; As the user may have overridden default values for
2444 ;; these vars on `run-python', let-binding them allows
2445 ;; to have the new right values in all setup code
2446 ;; that's is done in `inferior-python-mode', which is
2447 ;; important, especially for prompt detection.
2448 (python-shell-interpreter interpreter)
2449 (python-shell-interpreter-args
2450 (mapconcat #'identity args " ")))
2451 (with-current-buffer buffer
2452 (inferior-python-mode))
2453 (and pop (pop-to-buffer buffer t))
2454 (and internal (set-process-query-on-exit-flag process nil))))
2455 proc-buffer-name)))
2457 ;;;###autoload
2458 (defun run-python (cmd &optional dedicated show)
2459 "Run an inferior Python process.
2460 Input and output via buffer named after
2461 `python-shell-buffer-name'. If there is a process already
2462 running in that buffer, just switch to it.
2464 With argument, allows you to define CMD so you can edit the
2465 command used to call the interpreter and define DEDICATED, so a
2466 dedicated process for the current buffer is open. When numeric
2467 prefix arg is other than 0 or 4 do not SHOW.
2469 Runs the hook `inferior-python-mode-hook' after
2470 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2471 process buffer for a list of commands.)"
2472 (interactive
2473 (if current-prefix-arg
2474 (list
2475 (read-shell-command "Run Python: " (python-shell-parse-command))
2476 (y-or-n-p "Make dedicated process? ")
2477 (= (prefix-numeric-value current-prefix-arg) 4))
2478 (list (python-shell-parse-command) nil t)))
2479 (python-shell-make-comint
2480 cmd (python-shell-get-process-name dedicated) show)
2481 dedicated)
2483 (defun run-python-internal ()
2484 "Run an inferior Internal Python process.
2485 Input and output via buffer named after
2486 `python-shell-internal-buffer-name' and what
2487 `python-shell-internal-get-process-name' returns.
2489 This new kind of shell is intended to be used for generic
2490 communication related to defined configurations; the main
2491 difference with global or dedicated shells is that these ones are
2492 attached to a configuration, not a buffer. This means that can
2493 be used for example to retrieve the sys.path and other stuff,
2494 without messing with user shells. Note that
2495 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2496 are set to nil for these shells, so setup codes are not sent at
2497 startup."
2498 (let ((python-shell-font-lock-enable nil)
2499 (inferior-python-mode-hook nil))
2500 (get-buffer-process
2501 (python-shell-make-comint
2502 (python-shell-parse-command)
2503 (python-shell-internal-get-process-name) nil t))))
2505 (defun python-shell-get-buffer ()
2506 "Return inferior Python buffer for current buffer.
2507 If current buffer is in `inferior-python-mode', return it."
2508 (if (eq major-mode 'inferior-python-mode)
2509 (current-buffer)
2510 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2511 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2512 (global-proc-name (python-shell-get-process-name nil))
2513 (global-proc-buffer-name (format "*%s*" global-proc-name))
2514 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2515 (global-running (comint-check-proc global-proc-buffer-name)))
2516 ;; Always prefer dedicated
2517 (or (and dedicated-running dedicated-proc-buffer-name)
2518 (and global-running global-proc-buffer-name)))))
2520 (defun python-shell-get-process ()
2521 "Return inferior Python process for current buffer."
2522 (get-buffer-process (python-shell-get-buffer)))
2524 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2525 "Get or create an inferior Python process for current buffer and return it.
2526 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2527 are used to start the shell. If those arguments are not
2528 provided, `run-python' is called interactively and the user will
2529 be asked for their values."
2530 (let ((shell-process (python-shell-get-process)))
2531 (when (not shell-process)
2532 (if (not cmd)
2533 ;; XXX: Refactor code such that calling `run-python'
2534 ;; interactively is not needed anymore.
2535 (call-interactively 'run-python)
2536 (run-python cmd dedicated show)))
2537 (or shell-process (python-shell-get-process))))
2539 (defvar python-shell-internal-buffer nil
2540 "Current internal shell buffer for the current buffer.
2541 This is really not necessary at all for the code to work but it's
2542 there for compatibility with CEDET.")
2544 (defvar python-shell-internal-last-output nil
2545 "Last output captured by the internal shell.
2546 This is really not necessary at all for the code to work but it's
2547 there for compatibility with CEDET.")
2549 (defun python-shell-internal-get-or-create-process ()
2550 "Get or create an inferior Internal Python process."
2551 (let* ((proc-name (python-shell-internal-get-process-name))
2552 (proc-buffer-name (format " *%s*" proc-name)))
2553 (when (not (process-live-p proc-name))
2554 (run-python-internal)
2555 (setq python-shell-internal-buffer proc-buffer-name))
2556 (get-buffer-process proc-buffer-name)))
2558 (define-obsolete-function-alias
2559 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2561 (define-obsolete-variable-alias
2562 'python-buffer 'python-shell-internal-buffer "24.3")
2564 (define-obsolete-variable-alias
2565 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2567 (defun python-shell--save-temp-file (string)
2568 (let* ((temporary-file-directory
2569 (if (file-remote-p default-directory)
2570 (concat (file-remote-p default-directory) "/tmp")
2571 temporary-file-directory))
2572 (temp-file-name (make-temp-file "py"))
2573 (coding-system-for-write 'utf-8))
2574 (with-temp-file temp-file-name
2575 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2576 (insert string)
2577 (delete-trailing-whitespace))
2578 temp-file-name))
2580 (defun python-shell-send-string (string &optional process)
2581 "Send STRING to inferior Python PROCESS."
2582 (interactive "sPython command: ")
2583 (let ((process (or process (python-shell-get-or-create-process))))
2584 (if (string-match ".\n+." string) ;Multiline.
2585 (let* ((temp-file-name (python-shell--save-temp-file string)))
2586 (python-shell-send-file temp-file-name process temp-file-name t))
2587 (comint-send-string process string)
2588 (when (or (not (string-match "\n\\'" string))
2589 (string-match "\n[ \t].*\n?\\'" string))
2590 (comint-send-string process "\n")))))
2592 (defvar python-shell-output-filter-in-progress nil)
2593 (defvar python-shell-output-filter-buffer nil)
2595 (defun python-shell-output-filter (string)
2596 "Filter used in `python-shell-send-string-no-output' to grab output.
2597 STRING is the output received to this point from the process.
2598 This filter saves received output from the process in
2599 `python-shell-output-filter-buffer' and stops receiving it after
2600 detecting a prompt at the end of the buffer."
2601 (setq
2602 string (ansi-color-filter-apply string)
2603 python-shell-output-filter-buffer
2604 (concat python-shell-output-filter-buffer string))
2605 (when (python-shell-comint-end-of-output-p
2606 python-shell-output-filter-buffer)
2607 ;; Output ends when `python-shell-output-filter-buffer' contains
2608 ;; the prompt attached at the end of it.
2609 (setq python-shell-output-filter-in-progress nil
2610 python-shell-output-filter-buffer
2611 (substring python-shell-output-filter-buffer
2612 0 (match-beginning 0)))
2613 (when (string-match
2614 python-shell--prompt-calculated-output-regexp
2615 python-shell-output-filter-buffer)
2616 ;; Some shells, like IPython might append a prompt before the
2617 ;; output, clean that.
2618 (setq python-shell-output-filter-buffer
2619 (substring python-shell-output-filter-buffer (match-end 0)))))
2622 (defun python-shell-send-string-no-output (string &optional process)
2623 "Send STRING to PROCESS and inhibit output.
2624 Return the output."
2625 (let ((process (or process (python-shell-get-or-create-process)))
2626 (comint-preoutput-filter-functions
2627 '(python-shell-output-filter))
2628 (python-shell-output-filter-in-progress t)
2629 (inhibit-quit t))
2631 (with-local-quit
2632 (python-shell-send-string string process)
2633 (while python-shell-output-filter-in-progress
2634 ;; `python-shell-output-filter' takes care of setting
2635 ;; `python-shell-output-filter-in-progress' to NIL after it
2636 ;; detects end of output.
2637 (accept-process-output process))
2638 (prog1
2639 python-shell-output-filter-buffer
2640 (setq python-shell-output-filter-buffer nil)))
2641 (with-current-buffer (process-buffer process)
2642 (comint-interrupt-subjob)))))
2644 (defun python-shell-internal-send-string (string)
2645 "Send STRING to the Internal Python interpreter.
2646 Returns the output. See `python-shell-send-string-no-output'."
2647 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2648 ;; updated to support this new mode.
2649 (setq python-shell-internal-last-output
2650 (python-shell-send-string-no-output
2651 ;; Makes this function compatible with the old
2652 ;; python-send-receive. (At least for CEDET).
2653 (replace-regexp-in-string "_emacs_out +" "" string)
2654 (python-shell-internal-get-or-create-process))))
2656 (define-obsolete-function-alias
2657 'python-send-receive 'python-shell-internal-send-string "24.3")
2659 (define-obsolete-function-alias
2660 'python-send-string 'python-shell-internal-send-string "24.3")
2662 (defvar python--use-fake-loc nil
2663 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2664 If nil, regions of text are prepended by the corresponding number of empty
2665 lines and Python is told to output error messages referring to the whole
2666 source file.")
2668 (defun python-shell-buffer-substring (start end &optional nomain)
2669 "Send buffer substring from START to END formatted for shell.
2670 This is a wrapper over `buffer-substring' that takes care of
2671 different transformations for the code sent to be evaluated in
2672 the python shell:
2673 1. When optional argument NOMAIN is non-nil everything under an
2674 \"if __name__ == '__main__'\" block will be removed.
2675 2. When a subregion of the buffer is sent, it takes care of
2676 appending extra empty lines so tracebacks are correct.
2677 3. Wraps indented regions under an \"if True:\" block so the
2678 interpreter evaluates them correctly."
2679 (let ((substring (buffer-substring-no-properties start end))
2680 (fillstr (unless python--use-fake-loc
2681 (make-string (1- (line-number-at-pos start)) ?\n)))
2682 (toplevel-block-p (save-excursion
2683 (goto-char start)
2684 (or (zerop (line-number-at-pos start))
2685 (progn
2686 (python-util-forward-comment 1)
2687 (zerop (current-indentation)))))))
2688 (with-temp-buffer
2689 (python-mode)
2690 (if fillstr (insert fillstr))
2691 (insert substring)
2692 (goto-char (point-min))
2693 (unless python--use-fake-loc
2694 ;; python-shell--save-temp-file adds an extra coding line, which would
2695 ;; throw off the line-counts, so let's try to compensate here.
2696 (if (looking-at "[ \t]*[#\n]")
2697 (delete-region (point) (line-beginning-position 2))))
2698 (when (not toplevel-block-p)
2699 (insert "if True:")
2700 (delete-region (point) (line-end-position)))
2701 (when nomain
2702 (let* ((if-name-main-start-end
2703 (and nomain
2704 (save-excursion
2705 (when (python-nav-if-name-main)
2706 (cons (point)
2707 (progn (python-nav-forward-sexp-safe)
2708 (point)))))))
2709 ;; Oh destructuring bind, how I miss you.
2710 (if-name-main-start (car if-name-main-start-end))
2711 (if-name-main-end (cdr if-name-main-start-end)))
2712 (when if-name-main-start-end
2713 (goto-char if-name-main-start)
2714 (delete-region if-name-main-start if-name-main-end)
2715 (insert
2716 (make-string
2717 (- (line-number-at-pos if-name-main-end)
2718 (line-number-at-pos if-name-main-start)) ?\n)))))
2719 (buffer-substring-no-properties (point-min) (point-max)))))
2721 (declare-function compilation-fake-loc "compile"
2722 (marker file &optional line col))
2724 (defun python-shell-send-region (start end &optional nomain)
2725 "Send the region delimited by START and END to inferior Python process."
2726 (interactive "r")
2727 (let* ((python--use-fake-loc
2728 (or python--use-fake-loc (not buffer-file-name)))
2729 (string (python-shell-buffer-substring start end nomain))
2730 (process (python-shell-get-or-create-process))
2731 (_ (string-match "\\`\n*\\(.*\\)" string)))
2732 (message "Sent: %s..." (match-string 1 string))
2733 (let* ((temp-file-name (python-shell--save-temp-file string))
2734 (file-name (or (buffer-file-name) temp-file-name)))
2735 (python-shell-send-file file-name process temp-file-name t)
2736 (unless python--use-fake-loc
2737 (with-current-buffer (process-buffer process)
2738 (compilation-fake-loc (copy-marker start) temp-file-name
2739 2)) ;; Not 1, because of the added coding line.
2740 ))))
2742 (defun python-shell-send-buffer (&optional arg)
2743 "Send the entire buffer to inferior Python process.
2744 With prefix ARG allow execution of code inside blocks delimited
2745 by \"if __name__== '__main__':\"."
2746 (interactive "P")
2747 (save-restriction
2748 (widen)
2749 (python-shell-send-region (point-min) (point-max) (not arg))))
2751 (defun python-shell-send-defun (arg)
2752 "Send the current defun to inferior Python process.
2753 When argument ARG is non-nil do not include decorators."
2754 (interactive "P")
2755 (save-excursion
2756 (python-shell-send-region
2757 (progn
2758 (end-of-line 1)
2759 (while (and (or (python-nav-beginning-of-defun)
2760 (beginning-of-line 1))
2761 (> (current-indentation) 0)))
2762 (when (not arg)
2763 (while (and (forward-line -1)
2764 (looking-at (python-rx decorator))))
2765 (forward-line 1))
2766 (point-marker))
2767 (progn
2768 (or (python-nav-end-of-defun)
2769 (end-of-line 1))
2770 (point-marker)))))
2772 (defun python-shell-send-file (file-name &optional process temp-file-name
2773 delete)
2774 "Send FILE-NAME to inferior Python PROCESS.
2775 If TEMP-FILE-NAME is passed then that file is used for processing
2776 instead, while internally the shell will continue to use FILE-NAME.
2777 If DELETE is non-nil, delete the file afterwards."
2778 (interactive "fFile to send: ")
2779 (let* ((process (or process (python-shell-get-or-create-process)))
2780 (temp-file-name (when temp-file-name
2781 (expand-file-name
2782 (or (file-remote-p temp-file-name 'localname)
2783 temp-file-name))))
2784 (file-name (or (when file-name
2785 (expand-file-name
2786 (or (file-remote-p file-name 'localname)
2787 file-name)))
2788 temp-file-name)))
2789 (when (not file-name)
2790 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2791 (python-shell-send-string
2792 (format
2793 (concat "__pyfile = open('''%s''');"
2794 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2795 "__pyfile.close()%s")
2796 (or temp-file-name file-name) file-name
2797 (if delete (format "; import os; os.remove('''%s''')"
2798 (or temp-file-name file-name))
2799 ""))
2800 process)))
2802 (defun python-shell-switch-to-shell ()
2803 "Switch to inferior Python process buffer."
2804 (interactive)
2805 (process-buffer (python-shell-get-or-create-process)) t)
2807 (defun python-shell-send-setup-code ()
2808 "Send all setup code for shell.
2809 This function takes the list of setup code to send from the
2810 `python-shell-setup-codes' list."
2811 (let ((process (python-shell-get-process))
2812 (code (concat
2813 (mapconcat
2814 (lambda (elt)
2815 (cond ((stringp elt) elt)
2816 ((symbolp elt) (symbol-value elt))
2817 (t "")))
2818 python-shell-setup-codes
2819 "\n\n")
2820 "\n\nprint ('python.el: sent setup code')")))
2821 (python-shell-send-string code process)
2822 (python-shell-accept-process-output process)))
2824 (add-hook 'inferior-python-mode-hook
2825 #'python-shell-send-setup-code)
2828 ;;; Shell completion
2830 (defcustom python-shell-completion-setup-code
2831 "try:
2832 import readline, rlcompleter
2833 except ImportError:
2834 def __PYTHON_EL_get_completions(text):
2835 return []
2836 else:
2837 def __PYTHON_EL_get_completions(text):
2838 completions = []
2839 try:
2840 splits = text.split()
2841 is_module = splits and splits[0] in ('from', 'import')
2842 is_ipython = getattr(
2843 __builtins__, '__IPYTHON__',
2844 getattr(__builtins__, '__IPYTHON__active', False))
2845 if is_module:
2846 from IPython.core.completerlib import module_completion
2847 completions = module_completion(text.strip())
2848 elif is_ipython and getattr(__builtins__, '__IP', None):
2849 completions = __IP.complete(text)
2850 elif is_ipython and getattr(__builtins__, 'get_ipython', None):
2851 completions = get_ipython().Completer.all_completions(text)
2852 else:
2853 i = 0
2854 while True:
2855 res = readline.get_completer()(text, i)
2856 if not res:
2857 break
2858 i += 1
2859 completions.append(res)
2860 except:
2861 pass
2862 return completions"
2863 "Code used to setup completion in inferior Python processes."
2864 :type 'string
2865 :group 'python)
2867 (defcustom python-shell-completion-string-code
2868 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2869 "Python code used to get a string of completions separated by semicolons.
2870 The string passed to the function is the current python name or
2871 the full statement in the case of imports."
2872 :type 'string
2873 :group 'python)
2875 (define-obsolete-variable-alias
2876 'python-shell-completion-module-string-code
2877 'python-shell-completion-string-code
2878 "24.4"
2879 "Completion string code must also autocomplete modules.")
2881 (define-obsolete-variable-alias
2882 'python-shell-completion-pdb-string-code
2883 'python-shell-completion-string-code
2884 "24.5"
2885 "Completion string code must work for (i)pdb.")
2887 (defun python-shell-completion-get-completions (process import input)
2888 "Do completion at point using PROCESS for IMPORT or INPUT.
2889 When IMPORT is non-nil takes precedence over INPUT for
2890 completion."
2891 (let* ((prompt
2892 (with-current-buffer (process-buffer process)
2893 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2894 (buffer-substring-no-properties
2895 (car prompt-boundaries) (cdr prompt-boundaries)))))
2896 (completion-code
2897 ;; Check whether a prompt matches a pdb string, an import
2898 ;; statement or just the standard prompt and use the
2899 ;; correct python-shell-completion-*-code string
2900 (cond ((and (string-match
2901 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2902 ;; Since there are no guarantees the user will remain
2903 ;; in the same context where completion code was sent
2904 ;; (e.g. user steps into a function), safeguard
2905 ;; resending completion setup continuously.
2906 (concat python-shell-completion-setup-code
2907 "\nprint (" python-shell-completion-string-code ")"))
2908 ((string-match
2909 python-shell--prompt-calculated-input-regexp prompt)
2910 python-shell-completion-string-code)
2911 (t nil)))
2912 (subject (or import input)))
2913 (and completion-code
2914 (> (length input) 0)
2915 (with-current-buffer (process-buffer process)
2916 (let ((completions
2917 (python-util-strip-string
2918 (python-shell-send-string-no-output
2919 (format completion-code subject) process))))
2920 (and (> (length completions) 2)
2921 (split-string completions
2922 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2924 (defun python-shell-completion-at-point (&optional process)
2925 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2926 Optional argument PROCESS forces completions to be retrieved
2927 using that one instead of current buffer's process."
2928 (setq process (or process (get-buffer-process (current-buffer))))
2929 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2930 (import-statement
2931 (when (string-match-p
2932 (rx (* space) word-start (or "from" "import") word-end space)
2933 (buffer-substring-no-properties last-prompt-end (point)))
2934 (buffer-substring-no-properties last-prompt-end (point))))
2935 (start
2936 (save-excursion
2937 (if (not (re-search-backward
2938 (python-rx
2939 (or whitespace open-paren close-paren string-delimiter))
2940 last-prompt-end
2941 t 1))
2942 last-prompt-end
2943 (forward-char (length (match-string-no-properties 0)))
2944 (point))))
2945 (end (point)))
2946 (list start end
2947 (completion-table-dynamic
2948 (apply-partially
2949 #'python-shell-completion-get-completions
2950 process import-statement)))))
2952 (define-obsolete-function-alias
2953 'python-shell-completion-complete-at-point
2954 'python-shell-completion-at-point
2955 "24.5")
2957 (defun python-shell-completion-complete-or-indent ()
2958 "Complete or indent depending on the context.
2959 If content before pointer is all whitespace, indent.
2960 If not try to complete."
2961 (interactive)
2962 (if (string-match "^[[:space:]]*$"
2963 (buffer-substring (comint-line-beginning-position)
2964 (point-marker)))
2965 (indent-for-tab-command)
2966 (completion-at-point)))
2969 ;;; PDB Track integration
2971 (defcustom python-pdbtrack-activate t
2972 "Non-nil makes Python shell enable pdbtracking."
2973 :type 'boolean
2974 :group 'python
2975 :safe 'booleanp)
2977 (defcustom python-pdbtrack-stacktrace-info-regexp
2978 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2979 "Regular expression matching stacktrace information.
2980 Used to extract the current line and module being inspected."
2981 :type 'string
2982 :group 'python
2983 :safe 'stringp)
2985 (defvar python-pdbtrack-tracked-buffer nil
2986 "Variable containing the value of the current tracked buffer.
2987 Never set this variable directly, use
2988 `python-pdbtrack-set-tracked-buffer' instead.")
2990 (defvar python-pdbtrack-buffers-to-kill nil
2991 "List of buffers to be deleted after tracking finishes.")
2993 (defun python-pdbtrack-set-tracked-buffer (file-name)
2994 "Set the buffer for FILE-NAME as the tracked buffer.
2995 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2996 Returns the tracked buffer."
2997 (let ((file-buffer (get-file-buffer
2998 (concat (file-remote-p default-directory)
2999 file-name))))
3000 (if file-buffer
3001 (setq python-pdbtrack-tracked-buffer file-buffer)
3002 (setq file-buffer (find-file-noselect file-name))
3003 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3004 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3005 file-buffer))
3007 (defun python-pdbtrack-comint-output-filter-function (output)
3008 "Move overlay arrow to current pdb line in tracked buffer.
3009 Argument OUTPUT is a string with the output from the comint process."
3010 (when (and python-pdbtrack-activate (not (string= output "")))
3011 (let* ((full-output (ansi-color-filter-apply
3012 (buffer-substring comint-last-input-end (point-max))))
3013 (line-number)
3014 (file-name
3015 (with-temp-buffer
3016 (insert full-output)
3017 ;; When the debugger encounters a pdb.set_trace()
3018 ;; command, it prints a single stack frame. Sometimes
3019 ;; it prints a bit of extra information about the
3020 ;; arguments of the present function. When ipdb
3021 ;; encounters an exception, it prints the _entire_ stack
3022 ;; trace. To handle all of these cases, we want to find
3023 ;; the _last_ stack frame printed in the most recent
3024 ;; batch of output, then jump to the corresponding
3025 ;; file/line number.
3026 (goto-char (point-max))
3027 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3028 (setq line-number (string-to-number
3029 (match-string-no-properties 2)))
3030 (match-string-no-properties 1)))))
3031 (if (and file-name line-number)
3032 (let* ((tracked-buffer
3033 (python-pdbtrack-set-tracked-buffer file-name))
3034 (shell-buffer (current-buffer))
3035 (tracked-buffer-window (get-buffer-window tracked-buffer))
3036 (tracked-buffer-line-pos))
3037 (with-current-buffer tracked-buffer
3038 (set (make-local-variable 'overlay-arrow-string) "=>")
3039 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3040 (setq tracked-buffer-line-pos (progn
3041 (goto-char (point-min))
3042 (forward-line (1- line-number))
3043 (point-marker)))
3044 (when tracked-buffer-window
3045 (set-window-point
3046 tracked-buffer-window tracked-buffer-line-pos))
3047 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3048 (pop-to-buffer tracked-buffer)
3049 (switch-to-buffer-other-window shell-buffer))
3050 (when python-pdbtrack-tracked-buffer
3051 (with-current-buffer python-pdbtrack-tracked-buffer
3052 (set-marker overlay-arrow-position nil))
3053 (mapc #'(lambda (buffer)
3054 (ignore-errors (kill-buffer buffer)))
3055 python-pdbtrack-buffers-to-kill)
3056 (setq python-pdbtrack-tracked-buffer nil
3057 python-pdbtrack-buffers-to-kill nil)))))
3058 output)
3061 ;;; Symbol completion
3063 (defun python-completion-at-point ()
3064 "Function for `completion-at-point-functions' in `python-mode'.
3065 For this to work as best as possible you should call
3066 `python-shell-send-buffer' from time to time so context in
3067 inferior Python process is updated properly."
3068 (let ((process (python-shell-get-process)))
3069 (when process
3070 (python-shell-completion-at-point process))))
3072 (define-obsolete-function-alias
3073 'python-completion-complete-at-point
3074 'python-completion-at-point
3075 "24.5")
3078 ;;; Fill paragraph
3080 (defcustom python-fill-comment-function 'python-fill-comment
3081 "Function to fill comments.
3082 This is the function used by `python-fill-paragraph' to
3083 fill comments."
3084 :type 'symbol
3085 :group 'python)
3087 (defcustom python-fill-string-function 'python-fill-string
3088 "Function to fill strings.
3089 This is the function used by `python-fill-paragraph' to
3090 fill strings."
3091 :type 'symbol
3092 :group 'python)
3094 (defcustom python-fill-decorator-function 'python-fill-decorator
3095 "Function to fill decorators.
3096 This is the function used by `python-fill-paragraph' to
3097 fill decorators."
3098 :type 'symbol
3099 :group 'python)
3101 (defcustom python-fill-paren-function 'python-fill-paren
3102 "Function to fill parens.
3103 This is the function used by `python-fill-paragraph' to
3104 fill parens."
3105 :type 'symbol
3106 :group 'python)
3108 (defcustom python-fill-docstring-style 'pep-257
3109 "Style used to fill docstrings.
3110 This affects `python-fill-string' behavior with regards to
3111 triple quotes positioning.
3113 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3114 `symmetric', and nil. A value of nil won't care about quotes
3115 position and will treat docstrings a normal string, any other
3116 value may result in one of the following docstring styles:
3118 `django':
3120 \"\"\"
3121 Process foo, return bar.
3122 \"\"\"
3124 \"\"\"
3125 Process foo, return bar.
3127 If processing fails throw ProcessingError.
3128 \"\"\"
3130 `onetwo':
3132 \"\"\"Process foo, return bar.\"\"\"
3134 \"\"\"
3135 Process foo, return bar.
3137 If processing fails throw ProcessingError.
3139 \"\"\"
3141 `pep-257':
3143 \"\"\"Process foo, return bar.\"\"\"
3145 \"\"\"Process foo, return bar.
3147 If processing fails throw ProcessingError.
3149 \"\"\"
3151 `pep-257-nn':
3153 \"\"\"Process foo, return bar.\"\"\"
3155 \"\"\"Process foo, return bar.
3157 If processing fails throw ProcessingError.
3158 \"\"\"
3160 `symmetric':
3162 \"\"\"Process foo, return bar.\"\"\"
3164 \"\"\"
3165 Process foo, return bar.
3167 If processing fails throw ProcessingError.
3168 \"\"\""
3169 :type '(choice
3170 (const :tag "Don't format docstrings" nil)
3171 (const :tag "Django's coding standards style." django)
3172 (const :tag "One newline and start and Two at end style." onetwo)
3173 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3174 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3175 (const :tag "Symmetric style." symmetric))
3176 :group 'python
3177 :safe (lambda (val)
3178 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3180 (defun python-fill-paragraph (&optional justify)
3181 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3182 If any of the current line is in or at the end of a multi-line string,
3183 fill the string or the paragraph of it that point is in, preserving
3184 the string's indentation.
3185 Optional argument JUSTIFY defines if the paragraph should be justified."
3186 (interactive "P")
3187 (save-excursion
3188 (cond
3189 ;; Comments
3190 ((python-syntax-context 'comment)
3191 (funcall python-fill-comment-function justify))
3192 ;; Strings/Docstrings
3193 ((save-excursion (or (python-syntax-context 'string)
3194 (equal (string-to-syntax "|")
3195 (syntax-after (point)))))
3196 (funcall python-fill-string-function justify))
3197 ;; Decorators
3198 ((equal (char-after (save-excursion
3199 (python-nav-beginning-of-statement))) ?@)
3200 (funcall python-fill-decorator-function justify))
3201 ;; Parens
3202 ((or (python-syntax-context 'paren)
3203 (looking-at (python-rx open-paren))
3204 (save-excursion
3205 (skip-syntax-forward "^(" (line-end-position))
3206 (looking-at (python-rx open-paren))))
3207 (funcall python-fill-paren-function justify))
3208 (t t))))
3210 (defun python-fill-comment (&optional justify)
3211 "Comment fill function for `python-fill-paragraph'.
3212 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3213 (fill-comment-paragraph justify))
3215 (defun python-fill-string (&optional justify)
3216 "String fill function for `python-fill-paragraph'.
3217 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3218 (let* ((str-start-pos
3219 (set-marker
3220 (make-marker)
3221 (or (python-syntax-context 'string)
3222 (and (equal (string-to-syntax "|")
3223 (syntax-after (point)))
3224 (point)))))
3225 (num-quotes (python-syntax-count-quotes
3226 (char-after str-start-pos) str-start-pos))
3227 (str-end-pos
3228 (save-excursion
3229 (goto-char (+ str-start-pos num-quotes))
3230 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3231 (goto-char (point-max)))
3232 (point-marker)))
3233 (multi-line-p
3234 ;; Docstring styles may vary for oneliners and multi-liners.
3235 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3236 (delimiters-style
3237 (pcase python-fill-docstring-style
3238 ;; delimiters-style is a cons cell with the form
3239 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3240 ;; is NIL means to not add any newlines for start or end
3241 ;; of docstring. See `python-fill-docstring-style' for a
3242 ;; graphic idea of each style.
3243 (`django (cons 1 1))
3244 (`onetwo (and multi-line-p (cons 1 2)))
3245 (`pep-257 (and multi-line-p (cons nil 2)))
3246 (`pep-257-nn (and multi-line-p (cons nil 1)))
3247 (`symmetric (and multi-line-p (cons 1 1)))))
3248 (docstring-p (save-excursion
3249 ;; Consider docstrings those strings which
3250 ;; start on a line by themselves.
3251 (python-nav-beginning-of-statement)
3252 (and (= (point) str-start-pos))))
3253 (fill-paragraph-function))
3254 (save-restriction
3255 (narrow-to-region str-start-pos str-end-pos)
3256 (fill-paragraph justify))
3257 (save-excursion
3258 (when (and docstring-p python-fill-docstring-style)
3259 ;; Add the number of newlines indicated by the selected style
3260 ;; at the start of the docstring.
3261 (goto-char (+ str-start-pos num-quotes))
3262 (delete-region (point) (progn
3263 (skip-syntax-forward "> ")
3264 (point)))
3265 (and (car delimiters-style)
3266 (or (newline (car delimiters-style)) t)
3267 ;; Indent only if a newline is added.
3268 (indent-according-to-mode))
3269 ;; Add the number of newlines indicated by the selected style
3270 ;; at the end of the docstring.
3271 (goto-char (if (not (= str-end-pos (point-max)))
3272 (- str-end-pos num-quotes)
3273 str-end-pos))
3274 (delete-region (point) (progn
3275 (skip-syntax-backward "> ")
3276 (point)))
3277 (and (cdr delimiters-style)
3278 ;; Add newlines only if string ends.
3279 (not (= str-end-pos (point-max)))
3280 (or (newline (cdr delimiters-style)) t)
3281 ;; Again indent only if a newline is added.
3282 (indent-according-to-mode))))) t)
3284 (defun python-fill-decorator (&optional _justify)
3285 "Decorator fill function for `python-fill-paragraph'.
3286 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3289 (defun python-fill-paren (&optional justify)
3290 "Paren fill function for `python-fill-paragraph'.
3291 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3292 (save-restriction
3293 (narrow-to-region (progn
3294 (while (python-syntax-context 'paren)
3295 (goto-char (1- (point-marker))))
3296 (point-marker)
3297 (line-beginning-position))
3298 (progn
3299 (when (not (python-syntax-context 'paren))
3300 (end-of-line)
3301 (when (not (python-syntax-context 'paren))
3302 (skip-syntax-backward "^)")))
3303 (while (python-syntax-context 'paren)
3304 (goto-char (1+ (point-marker))))
3305 (point-marker)))
3306 (let ((paragraph-start "\f\\|[ \t]*$")
3307 (paragraph-separate ",")
3308 (fill-paragraph-function))
3309 (goto-char (point-min))
3310 (fill-paragraph justify))
3311 (while (not (eobp))
3312 (forward-line 1)
3313 (python-indent-line)
3314 (goto-char (line-end-position)))) t)
3317 ;;; Skeletons
3319 (defcustom python-skeleton-autoinsert nil
3320 "Non-nil means template skeletons will be automagically inserted.
3321 This happens when pressing \"if<SPACE>\", for example, to prompt for
3322 the if condition."
3323 :type 'boolean
3324 :group 'python
3325 :safe 'booleanp)
3327 (define-obsolete-variable-alias
3328 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3330 (defvar python-skeleton-available '()
3331 "Internal list of available skeletons.")
3333 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3334 "Abbrev table for Python mode skeletons."
3335 :case-fixed t
3336 ;; Allow / inside abbrevs.
3337 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3338 ;; Only expand in code.
3339 :enable-function (lambda ()
3340 (and
3341 (not (python-syntax-comment-or-string-p))
3342 python-skeleton-autoinsert)))
3344 (defmacro python-skeleton-define (name doc &rest skel)
3345 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3346 The skeleton will be bound to python-skeleton-NAME and will
3347 be added to `python-mode-skeleton-abbrev-table'."
3348 (declare (indent 2))
3349 (let* ((name (symbol-name name))
3350 (function-name (intern (concat "python-skeleton-" name))))
3351 `(progn
3352 (define-abbrev python-mode-skeleton-abbrev-table
3353 ,name "" ',function-name :system t)
3354 (setq python-skeleton-available
3355 (cons ',function-name python-skeleton-available))
3356 (define-skeleton ,function-name
3357 ,(or doc
3358 (format "Insert %s statement." name))
3359 ,@skel))))
3361 (define-abbrev-table 'python-mode-abbrev-table ()
3362 "Abbrev table for Python mode."
3363 :parents (list python-mode-skeleton-abbrev-table))
3365 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3366 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3367 The skeleton will be bound to python-skeleton-NAME."
3368 (declare (indent 2))
3369 (let* ((name (symbol-name name))
3370 (function-name (intern (concat "python-skeleton--" name)))
3371 (msg (format
3372 "Add '%s' clause? " name)))
3373 (when (not skel)
3374 (setq skel
3375 `(< ,(format "%s:" name) \n \n
3376 > _ \n)))
3377 `(define-skeleton ,function-name
3378 ,(or doc
3379 (format "Auxiliary skeleton for %s statement." name))
3381 (unless (y-or-n-p ,msg)
3382 (signal 'quit t))
3383 ,@skel)))
3385 (python-define-auxiliary-skeleton else nil)
3387 (python-define-auxiliary-skeleton except nil)
3389 (python-define-auxiliary-skeleton finally nil)
3391 (python-skeleton-define if nil
3392 "Condition: "
3393 "if " str ":" \n
3394 _ \n
3395 ("other condition, %s: "
3397 "elif " str ":" \n
3398 > _ \n nil)
3399 '(python-skeleton--else) | ^)
3401 (python-skeleton-define while nil
3402 "Condition: "
3403 "while " str ":" \n
3404 > _ \n
3405 '(python-skeleton--else) | ^)
3407 (python-skeleton-define for nil
3408 "Iteration spec: "
3409 "for " str ":" \n
3410 > _ \n
3411 '(python-skeleton--else) | ^)
3413 (python-skeleton-define import nil
3414 "Import from module: "
3415 "from " str & " " | -5
3416 "import "
3417 ("Identifier: " str ", ") -2 \n _)
3419 (python-skeleton-define try nil
3421 "try:" \n
3422 > _ \n
3423 ("Exception, %s: "
3425 "except " str ":" \n
3426 > _ \n nil)
3427 resume:
3428 '(python-skeleton--except)
3429 '(python-skeleton--else)
3430 '(python-skeleton--finally) | ^)
3432 (python-skeleton-define def nil
3433 "Function name: "
3434 "def " str "(" ("Parameter, %s: "
3435 (unless (equal ?\( (char-before)) ", ")
3436 str) "):" \n
3437 "\"\"\"" - "\"\"\"" \n
3438 > _ \n)
3440 (python-skeleton-define class nil
3441 "Class name: "
3442 "class " str "(" ("Inheritance, %s: "
3443 (unless (equal ?\( (char-before)) ", ")
3444 str)
3445 & ")" | -1
3446 ":" \n
3447 "\"\"\"" - "\"\"\"" \n
3448 > _ \n)
3450 (defun python-skeleton-add-menu-items ()
3451 "Add menu items to Python->Skeletons menu."
3452 (let ((skeletons (sort python-skeleton-available 'string<)))
3453 (dolist (skeleton skeletons)
3454 (easy-menu-add-item
3455 nil '("Python" "Skeletons")
3456 `[,(format
3457 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3458 ,skeleton t]))))
3460 ;;; FFAP
3462 (defcustom python-ffap-setup-code
3463 "def __FFAP_get_module_path(module):
3464 try:
3465 import os
3466 path = __import__(module).__file__
3467 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3468 path = path[:-1]
3469 return path
3470 except:
3471 return ''"
3472 "Python code to get a module path."
3473 :type 'string
3474 :group 'python)
3476 (defcustom python-ffap-string-code
3477 "__FFAP_get_module_path('''%s''')\n"
3478 "Python code used to get a string with the path of a module."
3479 :type 'string
3480 :group 'python)
3482 (defun python-ffap-module-path (module)
3483 "Function for `ffap-alist' to return path for MODULE."
3484 (let ((process (or
3485 (and (eq major-mode 'inferior-python-mode)
3486 (get-buffer-process (current-buffer)))
3487 (python-shell-get-process))))
3488 (if (not process)
3490 (let ((module-file
3491 (python-shell-send-string-no-output
3492 (format python-ffap-string-code module) process)))
3493 (when module-file
3494 (substring-no-properties module-file 1 -1))))))
3496 (defvar ffap-alist)
3498 (eval-after-load "ffap"
3499 '(progn
3500 (push '(python-mode . python-ffap-module-path) ffap-alist)
3501 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3504 ;;; Code check
3506 (defcustom python-check-command
3507 "pyflakes"
3508 "Command used to check a Python file."
3509 :type 'string
3510 :group 'python)
3512 (defcustom python-check-buffer-name
3513 "*Python check: %s*"
3514 "Buffer name used for check commands."
3515 :type 'string
3516 :group 'python)
3518 (defvar python-check-custom-command nil
3519 "Internal use.")
3521 (defun python-check (command)
3522 "Check a Python file (default current buffer's file).
3523 Runs COMMAND, a shell command, as if by `compile'.
3524 See `python-check-command' for the default."
3525 (interactive
3526 (list (read-string "Check command: "
3527 (or python-check-custom-command
3528 (concat python-check-command " "
3529 (shell-quote-argument
3531 (let ((name (buffer-file-name)))
3532 (and name
3533 (file-name-nondirectory name)))
3534 "")))))))
3535 (setq python-check-custom-command command)
3536 (save-some-buffers (not compilation-ask-about-save) nil)
3537 (let ((process-environment (python-shell-calculate-process-environment))
3538 (exec-path (python-shell-calculate-exec-path)))
3539 (compilation-start command nil
3540 (lambda (_modename)
3541 (format python-check-buffer-name command)))))
3544 ;;; Eldoc
3546 (defcustom python-eldoc-setup-code
3547 "def __PYDOC_get_help(obj):
3548 try:
3549 import inspect
3550 if hasattr(obj, 'startswith'):
3551 obj = eval(obj, globals())
3552 doc = inspect.getdoc(obj)
3553 if not doc and callable(obj):
3554 target = None
3555 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3556 target = obj.__init__
3557 objtype = 'class'
3558 else:
3559 target = obj
3560 objtype = 'def'
3561 if target:
3562 args = inspect.formatargspec(
3563 *inspect.getargspec(target)
3565 name = obj.__name__
3566 doc = '{objtype} {name}{args}'.format(
3567 objtype=objtype, name=name, args=args
3569 else:
3570 doc = doc.splitlines()[0]
3571 except:
3572 doc = ''
3573 try:
3574 exec('print doc')
3575 except SyntaxError:
3576 print(doc)"
3577 "Python code to setup documentation retrieval."
3578 :type 'string
3579 :group 'python)
3581 (defcustom python-eldoc-string-code
3582 "__PYDOC_get_help('''%s''')\n"
3583 "Python code used to get a string with the documentation of an object."
3584 :type 'string
3585 :group 'python)
3587 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3588 "Internal implementation to get documentation at point.
3589 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3590 returns will be used. If not FORCE-PROCESS is passed what
3591 `python-shell-get-process' returns is used."
3592 (let ((process (or force-process (python-shell-get-process))))
3593 (when process
3594 (let ((input (or force-input
3595 (python-info-current-symbol t))))
3596 (and input
3597 (python-shell-send-string-no-output
3598 (format python-eldoc-string-code input)
3599 process))))))
3601 (defun python-eldoc-function ()
3602 "`eldoc-documentation-function' for Python.
3603 For this to work as best as possible you should call
3604 `python-shell-send-buffer' from time to time so context in
3605 inferior Python process is updated properly."
3606 (python-eldoc--get-doc-at-point))
3608 (defun python-eldoc-at-point (symbol)
3609 "Get help on SYMBOL using `help'.
3610 Interactively, prompt for symbol."
3611 (interactive
3612 (let ((symbol (python-info-current-symbol t))
3613 (enable-recursive-minibuffers t))
3614 (list (read-string (if symbol
3615 (format "Describe symbol (default %s): " symbol)
3616 "Describe symbol: ")
3617 nil nil symbol))))
3618 (message (python-eldoc--get-doc-at-point symbol)))
3621 ;;; Imenu
3623 (defvar python-imenu-format-item-label-function
3624 'python-imenu-format-item-label
3625 "Imenu function used to format an item label.
3626 It must be a function with two arguments: TYPE and NAME.")
3628 (defvar python-imenu-format-parent-item-label-function
3629 'python-imenu-format-parent-item-label
3630 "Imenu function used to format a parent item label.
3631 It must be a function with two arguments: TYPE and NAME.")
3633 (defvar python-imenu-format-parent-item-jump-label-function
3634 'python-imenu-format-parent-item-jump-label
3635 "Imenu function used to format a parent jump item label.
3636 It must be a function with two arguments: TYPE and NAME.")
3638 (defun python-imenu-format-item-label (type name)
3639 "Return Imenu label for single node using TYPE and NAME."
3640 (format "%s (%s)" name type))
3642 (defun python-imenu-format-parent-item-label (type name)
3643 "Return Imenu label for parent node using TYPE and NAME."
3644 (format "%s..." (python-imenu-format-item-label type name)))
3646 (defun python-imenu-format-parent-item-jump-label (type _name)
3647 "Return Imenu label for parent node jump using TYPE and NAME."
3648 (if (string= type "class")
3649 "*class definition*"
3650 "*function definition*"))
3652 (defun python-imenu--put-parent (type name pos tree)
3653 "Add the parent with TYPE, NAME and POS to TREE."
3654 (let ((label
3655 (funcall python-imenu-format-item-label-function type name))
3656 (jump-label
3657 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3658 (if (not tree)
3659 (cons label pos)
3660 (cons label (cons (cons jump-label pos) tree)))))
3662 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3663 "Recursively build the tree of nested definitions of a node.
3664 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3665 not be passed explicitly unless you know what you are doing."
3666 (setq min-indent (or min-indent 0)
3667 prev-indent (or prev-indent python-indent-offset))
3668 (let* ((pos (python-nav-backward-defun))
3669 (type)
3670 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3671 (let ((split (split-string (match-string-no-properties 0))))
3672 (setq type (car split))
3673 (cadr split))))
3674 (label (when name
3675 (funcall python-imenu-format-item-label-function type name)))
3676 (indent (current-indentation))
3677 (children-indent-limit (+ python-indent-offset min-indent)))
3678 (cond ((not pos)
3679 ;; Nothing found, probably near to bobp.
3680 nil)
3681 ((<= indent min-indent)
3682 ;; The current indentation points that this is a parent
3683 ;; node, add it to the tree and stop recursing.
3684 (python-imenu--put-parent type name pos tree))
3686 (python-imenu--build-tree
3687 min-indent
3688 indent
3689 (if (<= indent children-indent-limit)
3690 ;; This lies within the children indent offset range,
3691 ;; so it's a normal child of its parent (i.e., not
3692 ;; a child of a child).
3693 (cons (cons label pos) tree)
3694 ;; Oh no, a child of a child?! Fear not, we
3695 ;; know how to roll. We recursively parse these by
3696 ;; swapping prev-indent and min-indent plus adding this
3697 ;; newly found item to a fresh subtree. This works, I
3698 ;; promise.
3699 (cons
3700 (python-imenu--build-tree
3701 prev-indent indent (list (cons label pos)))
3702 tree)))))))
3704 (defun python-imenu-create-index ()
3705 "Return tree Imenu alist for the current Python buffer.
3706 Change `python-imenu-format-item-label-function',
3707 `python-imenu-format-parent-item-label-function',
3708 `python-imenu-format-parent-item-jump-label-function' to
3709 customize how labels are formatted."
3710 (goto-char (point-max))
3711 (let ((index)
3712 (tree))
3713 (while (setq tree (python-imenu--build-tree))
3714 (setq index (cons tree index)))
3715 index))
3717 (defun python-imenu-create-flat-index (&optional alist prefix)
3718 "Return flat outline of the current Python buffer for Imenu.
3719 Optional argument ALIST is the tree to be flattened; when nil
3720 `python-imenu-build-index' is used with
3721 `python-imenu-format-parent-item-jump-label-function'
3722 `python-imenu-format-parent-item-label-function'
3723 `python-imenu-format-item-label-function' set to
3724 (lambda (type name) name)
3725 Optional argument PREFIX is used in recursive calls and should
3726 not be passed explicitly.
3728 Converts this:
3730 ((\"Foo\" . 103)
3731 (\"Bar\" . 138)
3732 (\"decorator\"
3733 (\"decorator\" . 173)
3734 (\"wrap\"
3735 (\"wrap\" . 353)
3736 (\"wrapped_f\" . 393))))
3738 To this:
3740 ((\"Foo\" . 103)
3741 (\"Bar\" . 138)
3742 (\"decorator\" . 173)
3743 (\"decorator.wrap\" . 353)
3744 (\"decorator.wrapped_f\" . 393))"
3745 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3746 (apply
3747 'nconc
3748 (mapcar
3749 (lambda (item)
3750 (let ((name (if prefix
3751 (concat prefix "." (car item))
3752 (car item)))
3753 (pos (cdr item)))
3754 (cond ((or (numberp pos) (markerp pos))
3755 (list (cons name pos)))
3756 ((listp pos)
3757 (cons
3758 (cons name (cdar pos))
3759 (python-imenu-create-flat-index (cddr item) name))))))
3760 (or alist
3761 (let* ((fn (lambda (_type name) name))
3762 (python-imenu-format-item-label-function fn)
3763 (python-imenu-format-parent-item-label-function fn)
3764 (python-imenu-format-parent-item-jump-label-function fn))
3765 (python-imenu-create-index))))))
3768 ;;; Misc helpers
3770 (defun python-info-current-defun (&optional include-type)
3771 "Return name of surrounding function with Python compatible dotty syntax.
3772 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3773 This function can be used as the value of `add-log-current-defun-function'
3774 since it returns nil if point is not inside a defun."
3775 (save-restriction
3776 (widen)
3777 (save-excursion
3778 (end-of-line 1)
3779 (let ((names)
3780 (starting-indentation (current-indentation))
3781 (starting-pos (point))
3782 (first-run t)
3783 (last-indent)
3784 (type))
3785 (catch 'exit
3786 (while (python-nav-beginning-of-defun 1)
3787 (when (save-match-data
3788 (and
3789 (or (not last-indent)
3790 (< (current-indentation) last-indent))
3792 (and first-run
3793 (save-excursion
3794 ;; If this is the first run, we may add
3795 ;; the current defun at point.
3796 (setq first-run nil)
3797 (goto-char starting-pos)
3798 (python-nav-beginning-of-statement)
3799 (beginning-of-line 1)
3800 (looking-at-p
3801 python-nav-beginning-of-defun-regexp)))
3802 (< starting-pos
3803 (save-excursion
3804 (let ((min-indent
3805 (+ (current-indentation)
3806 python-indent-offset)))
3807 (if (< starting-indentation min-indent)
3808 ;; If the starting indentation is not
3809 ;; within the min defun indent make the
3810 ;; check fail.
3811 starting-pos
3812 ;; Else go to the end of defun and add
3813 ;; up the current indentation to the
3814 ;; ending position.
3815 (python-nav-end-of-defun)
3816 (+ (point)
3817 (if (>= (current-indentation) min-indent)
3818 (1+ (current-indentation))
3819 0)))))))))
3820 (save-match-data (setq last-indent (current-indentation)))
3821 (if (or (not include-type) type)
3822 (setq names (cons (match-string-no-properties 1) names))
3823 (let ((match (split-string (match-string-no-properties 0))))
3824 (setq type (car match))
3825 (setq names (cons (cadr match) names)))))
3826 ;; Stop searching ASAP.
3827 (and (= (current-indentation) 0) (throw 'exit t))))
3828 (and names
3829 (concat (and type (format "%s " type))
3830 (mapconcat 'identity names ".")))))))
3832 (defun python-info-current-symbol (&optional replace-self)
3833 "Return current symbol using dotty syntax.
3834 With optional argument REPLACE-SELF convert \"self\" to current
3835 parent defun name."
3836 (let ((name
3837 (and (not (python-syntax-comment-or-string-p))
3838 (with-syntax-table python-dotty-syntax-table
3839 (let ((sym (symbol-at-point)))
3840 (and sym
3841 (substring-no-properties (symbol-name sym))))))))
3842 (when name
3843 (if (not replace-self)
3844 name
3845 (let ((current-defun (python-info-current-defun)))
3846 (if (not current-defun)
3847 name
3848 (replace-regexp-in-string
3849 (python-rx line-start word-start "self" word-end ?.)
3850 (concat
3851 (mapconcat 'identity
3852 (butlast (split-string current-defun "\\."))
3853 ".") ".")
3854 name)))))))
3856 (defun python-info-statement-starts-block-p ()
3857 "Return non-nil if current statement opens a block."
3858 (save-excursion
3859 (python-nav-beginning-of-statement)
3860 (looking-at (python-rx block-start))))
3862 (defun python-info-statement-ends-block-p ()
3863 "Return non-nil if point is at end of block."
3864 (let ((end-of-block-pos (save-excursion
3865 (python-nav-end-of-block)))
3866 (end-of-statement-pos (save-excursion
3867 (python-nav-end-of-statement))))
3868 (and end-of-block-pos end-of-statement-pos
3869 (= end-of-block-pos end-of-statement-pos))))
3871 (defun python-info-beginning-of-statement-p ()
3872 "Return non-nil if point is at beginning of statement."
3873 (= (point) (save-excursion
3874 (python-nav-beginning-of-statement)
3875 (point))))
3877 (defun python-info-end-of-statement-p ()
3878 "Return non-nil if point is at end of statement."
3879 (= (point) (save-excursion
3880 (python-nav-end-of-statement)
3881 (point))))
3883 (defun python-info-beginning-of-block-p ()
3884 "Return non-nil if point is at beginning of block."
3885 (and (python-info-beginning-of-statement-p)
3886 (python-info-statement-starts-block-p)))
3888 (defun python-info-end-of-block-p ()
3889 "Return non-nil if point is at end of block."
3890 (and (python-info-end-of-statement-p)
3891 (python-info-statement-ends-block-p)))
3893 (define-obsolete-function-alias
3894 'python-info-closing-block
3895 'python-info-dedenter-opening-block-position "24.4")
3897 (defun python-info-dedenter-opening-block-position ()
3898 "Return the point of the closest block the current line closes.
3899 Returns nil if point is not on a dedenter statement or no opening
3900 block can be detected. The latter case meaning current file is
3901 likely an invalid python file."
3902 (let ((positions (python-info-dedenter-opening-block-positions))
3903 (indentation (current-indentation))
3904 (position))
3905 (while (and (not position)
3906 positions)
3907 (save-excursion
3908 (goto-char (car positions))
3909 (if (<= (current-indentation) indentation)
3910 (setq position (car positions))
3911 (setq positions (cdr positions)))))
3912 position))
3914 (defun python-info-dedenter-opening-block-positions ()
3915 "Return points of blocks the current line may close sorted by closer.
3916 Returns nil if point is not on a dedenter statement or no opening
3917 block can be detected. The latter case meaning current file is
3918 likely an invalid python file."
3919 (save-excursion
3920 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3921 (when dedenter-pos
3922 (goto-char dedenter-pos)
3923 (let* ((pairs '(("elif" "elif" "if")
3924 ("else" "if" "elif" "except" "for" "while")
3925 ("except" "except" "try")
3926 ("finally" "else" "except" "try")))
3927 (dedenter (match-string-no-properties 0))
3928 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
3929 (collected-indentations)
3930 (opening-blocks))
3931 (catch 'exit
3932 (while (python-nav--syntactically
3933 (lambda ()
3934 (re-search-backward (python-rx block-start) nil t))
3935 #'<)
3936 (let ((indentation (current-indentation)))
3937 (when (and (not (memq indentation collected-indentations))
3938 (or (not collected-indentations)
3939 (< indentation (apply #'min collected-indentations))))
3940 (setq collected-indentations
3941 (cons indentation collected-indentations))
3942 (when (member (match-string-no-properties 0)
3943 possible-opening-blocks)
3944 (setq opening-blocks (cons (point) opening-blocks))))
3945 (when (zerop indentation)
3946 (throw 'exit nil)))))
3947 ;; sort by closer
3948 (nreverse opening-blocks))))))
3950 (define-obsolete-function-alias
3951 'python-info-closing-block-message
3952 'python-info-dedenter-opening-block-message "24.4")
3954 (defun python-info-dedenter-opening-block-message ()
3955 "Message the first line of the block the current statement closes."
3956 (let ((point (python-info-dedenter-opening-block-position)))
3957 (when point
3958 (save-restriction
3959 (widen)
3960 (message "Closes %s" (save-excursion
3961 (goto-char point)
3962 (buffer-substring
3963 (point) (line-end-position))))))))
3965 (defun python-info-dedenter-statement-p ()
3966 "Return point if current statement is a dedenter.
3967 Sets `match-data' to the keyword that starts the dedenter
3968 statement."
3969 (save-excursion
3970 (python-nav-beginning-of-statement)
3971 (when (and (not (python-syntax-context-type))
3972 (looking-at (python-rx dedenter)))
3973 (point))))
3975 (defun python-info-line-ends-backslash-p (&optional line-number)
3976 "Return non-nil if current line ends with backslash.
3977 With optional argument LINE-NUMBER, check that line instead."
3978 (save-excursion
3979 (save-restriction
3980 (widen)
3981 (when line-number
3982 (python-util-goto-line line-number))
3983 (while (and (not (eobp))
3984 (goto-char (line-end-position))
3985 (python-syntax-context 'paren)
3986 (not (equal (char-before (point)) ?\\)))
3987 (forward-line 1))
3988 (when (equal (char-before) ?\\)
3989 (point-marker)))))
3991 (defun python-info-beginning-of-backslash (&optional line-number)
3992 "Return the point where the backslashed line start.
3993 Optional argument LINE-NUMBER forces the line number to check against."
3994 (save-excursion
3995 (save-restriction
3996 (widen)
3997 (when line-number
3998 (python-util-goto-line line-number))
3999 (when (python-info-line-ends-backslash-p)
4000 (while (save-excursion
4001 (goto-char (line-beginning-position))
4002 (python-syntax-context 'paren))
4003 (forward-line -1))
4004 (back-to-indentation)
4005 (point-marker)))))
4007 (defun python-info-continuation-line-p ()
4008 "Check if current line is continuation of another.
4009 When current line is continuation of another return the point
4010 where the continued line ends."
4011 (save-excursion
4012 (save-restriction
4013 (widen)
4014 (let* ((context-type (progn
4015 (back-to-indentation)
4016 (python-syntax-context-type)))
4017 (line-start (line-number-at-pos))
4018 (context-start (when context-type
4019 (python-syntax-context context-type))))
4020 (cond ((equal context-type 'paren)
4021 ;; Lines inside a paren are always a continuation line
4022 ;; (except the first one).
4023 (python-util-forward-comment -1)
4024 (point-marker))
4025 ((member context-type '(string comment))
4026 ;; move forward an roll again
4027 (goto-char context-start)
4028 (python-util-forward-comment)
4029 (python-info-continuation-line-p))
4031 ;; Not within a paren, string or comment, the only way
4032 ;; we are dealing with a continuation line is that
4033 ;; previous line contains a backslash, and this can
4034 ;; only be the previous line from current
4035 (back-to-indentation)
4036 (python-util-forward-comment -1)
4037 (when (and (equal (1- line-start) (line-number-at-pos))
4038 (python-info-line-ends-backslash-p))
4039 (point-marker))))))))
4041 (defun python-info-block-continuation-line-p ()
4042 "Return non-nil if current line is a continuation of a block."
4043 (save-excursion
4044 (when (python-info-continuation-line-p)
4045 (forward-line -1)
4046 (back-to-indentation)
4047 (when (looking-at (python-rx block-start))
4048 (point-marker)))))
4050 (defun python-info-assignment-continuation-line-p ()
4051 "Check if current line is a continuation of an assignment.
4052 When current line is continuation of another with an assignment
4053 return the point of the first non-blank character after the
4054 operator."
4055 (save-excursion
4056 (when (python-info-continuation-line-p)
4057 (forward-line -1)
4058 (back-to-indentation)
4059 (when (and (not (looking-at (python-rx block-start)))
4060 (and (re-search-forward (python-rx not-simple-operator
4061 assignment-operator
4062 not-simple-operator)
4063 (line-end-position) t)
4064 (not (python-syntax-context-type))))
4065 (skip-syntax-forward "\s")
4066 (point-marker)))))
4068 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4069 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4070 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4071 (save-excursion
4072 (beginning-of-line 1)
4073 (looking-at python-nav-beginning-of-defun-regexp))))
4075 (defun python-info-current-line-comment-p ()
4076 "Return non-nil if current line is a comment line."
4077 (char-equal
4078 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4079 ?#))
4081 (defun python-info-current-line-empty-p ()
4082 "Return non-nil if current line is empty, ignoring whitespace."
4083 (save-excursion
4084 (beginning-of-line 1)
4085 (looking-at
4086 (python-rx line-start (* whitespace)
4087 (group (* not-newline))
4088 (* whitespace) line-end))
4089 (string-equal "" (match-string-no-properties 1))))
4092 ;;; Utility functions
4094 (defun python-util-goto-line (line-number)
4095 "Move point to LINE-NUMBER."
4096 (goto-char (point-min))
4097 (forward-line (1- line-number)))
4099 ;; Stolen from org-mode
4100 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4101 "Clone local variables from FROM-BUFFER.
4102 Optional argument REGEXP selects variables to clone and defaults
4103 to \"^python-\"."
4104 (mapc
4105 (lambda (pair)
4106 (and (symbolp (car pair))
4107 (string-match (or regexp "^python-")
4108 (symbol-name (car pair)))
4109 (set (make-local-variable (car pair))
4110 (cdr pair))))
4111 (buffer-local-variables from-buffer)))
4113 (defvar comint-last-prompt-overlay) ; Shut up, bytecompiler
4115 (defun python-util-comint-last-prompt ()
4116 "Return comint last prompt overlay start and end.
4117 This is for compatibility with Emacs < 24.4."
4118 (cond ((bound-and-true-p comint-last-prompt-overlay)
4119 (cons (overlay-start comint-last-prompt-overlay)
4120 (overlay-end comint-last-prompt-overlay)))
4121 ((bound-and-true-p comint-last-prompt)
4122 comint-last-prompt)
4123 (t nil)))
4125 (defun python-util-forward-comment (&optional direction)
4126 "Python mode specific version of `forward-comment'.
4127 Optional argument DIRECTION defines the direction to move to."
4128 (let ((comment-start (python-syntax-context 'comment))
4129 (factor (if (< (or direction 0) 0)
4130 -99999
4131 99999)))
4132 (when comment-start
4133 (goto-char comment-start))
4134 (forward-comment factor)))
4136 (defun python-util-list-directories (directory &optional predicate max-depth)
4137 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4138 Argument PREDICATE defaults to `identity' and must be a function
4139 that takes one argument (a full path) and returns non-nil for
4140 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4141 searching when depth is reached, else don't limit."
4142 (let* ((dir (expand-file-name directory))
4143 (dir-length (length dir))
4144 (predicate (or predicate #'identity))
4145 (to-scan (list dir))
4146 (tally nil))
4147 (while to-scan
4148 (let ((current-dir (car to-scan)))
4149 (when (funcall predicate current-dir)
4150 (setq tally (cons current-dir tally)))
4151 (setq to-scan (append (cdr to-scan)
4152 (python-util-list-files
4153 current-dir #'file-directory-p)
4154 nil))
4155 (when (and max-depth
4156 (<= max-depth
4157 (length (split-string
4158 (substring current-dir dir-length)
4159 "/\\|\\\\" t))))
4160 (setq to-scan nil))))
4161 (nreverse tally)))
4163 (defun python-util-list-files (dir &optional predicate)
4164 "List files in DIR, filtering with PREDICATE.
4165 Argument PREDICATE defaults to `identity' and must be a function
4166 that takes one argument (a full path) and returns non-nil for
4167 allowed files."
4168 (let ((dir-name (file-name-as-directory dir)))
4169 (apply #'nconc
4170 (mapcar (lambda (file-name)
4171 (let ((full-file-name (expand-file-name file-name dir-name)))
4172 (when (and
4173 (not (member file-name '("." "..")))
4174 (funcall (or predicate #'identity) full-file-name))
4175 (list full-file-name))))
4176 (directory-files dir-name)))))
4178 (defun python-util-list-packages (dir &optional max-depth)
4179 "List packages in DIR, limited by MAX-DEPTH.
4180 When optional argument MAX-DEPTH is non-nil, stop searching when
4181 depth is reached, else don't limit."
4182 (let* ((dir (expand-file-name dir))
4183 (parent-dir (file-name-directory
4184 (directory-file-name
4185 (file-name-directory
4186 (file-name-as-directory dir)))))
4187 (subpath-length (length parent-dir)))
4188 (mapcar
4189 (lambda (file-name)
4190 (replace-regexp-in-string
4191 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4192 (python-util-list-directories
4193 (directory-file-name dir)
4194 (lambda (dir)
4195 (file-exists-p (expand-file-name "__init__.py" dir)))
4196 max-depth))))
4198 (defun python-util-popn (lst n)
4199 "Return LST first N elements.
4200 N should be an integer, when negative its opposite is used.
4201 When N is bigger than the length of LST, the list is
4202 returned as is."
4203 (let* ((n (min (abs n)))
4204 (len (length lst))
4205 (acc))
4206 (if (> n len)
4208 (while (< 0 n)
4209 (setq acc (cons (car lst) acc)
4210 lst (cdr lst)
4211 n (1- n)))
4212 (reverse acc))))
4214 (defun python-util-text-properties-replace-name
4215 (from to &optional start end)
4216 "Replace properties named FROM to TO, keeping its value.
4217 Arguments START and END narrow the buffer region to work on."
4218 (save-excursion
4219 (goto-char (or start (point-min)))
4220 (while (not (eobp))
4221 (let ((plist (text-properties-at (point)))
4222 (next-change (or (next-property-change (point) (current-buffer))
4223 (or end (point-max)))))
4224 (when (plist-get plist from)
4225 (let* ((face (plist-get plist from))
4226 (plist (plist-put plist from nil))
4227 (plist (plist-put plist to face)))
4228 (set-text-properties (point) next-change plist (current-buffer))))
4229 (goto-char next-change)))))
4231 (defun python-util-strip-string (string)
4232 "Strip STRING whitespace and newlines from end and beginning."
4233 (replace-regexp-in-string
4234 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4235 (: (* (any whitespace ?\r ?\n)) string-end)))
4237 string))
4239 (defun python-util-valid-regexp-p (regexp)
4240 "Return non-nil if REGEXP is valid."
4241 (ignore-errors (string-match regexp "") t))
4244 (defun python-electric-pair-string-delimiter ()
4245 (when (and electric-pair-mode
4246 (memq last-command-event '(?\" ?\'))
4247 (let ((count 0))
4248 (while (eq (char-before (- (point) count)) last-command-event)
4249 (cl-incf count))
4250 (= count 3))
4251 (eq (char-after) last-command-event))
4252 (save-excursion (insert (make-string 2 last-command-event)))))
4254 (defvar electric-indent-inhibit)
4256 ;;;###autoload
4257 (define-derived-mode python-mode prog-mode "Python"
4258 "Major mode for editing Python files.
4260 \\{python-mode-map}"
4261 (set (make-local-variable 'tab-width) 8)
4262 (set (make-local-variable 'indent-tabs-mode) nil)
4264 (set (make-local-variable 'comment-start) "# ")
4265 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4267 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4268 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4270 (set (make-local-variable 'forward-sexp-function)
4271 'python-nav-forward-sexp)
4273 (set (make-local-variable 'font-lock-defaults)
4274 '(python-font-lock-keywords nil nil nil nil))
4276 (set (make-local-variable 'syntax-propertize-function)
4277 python-syntax-propertize-function)
4279 (set (make-local-variable 'indent-line-function)
4280 #'python-indent-line-function)
4281 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4282 ;; Because indentation is not redundant, we cannot safely reindent code.
4283 (setq-local electric-indent-inhibit t)
4284 (setq-local electric-indent-chars (cons ?: electric-indent-chars))
4286 ;; Add """ ... """ pairing to electric-pair-mode.
4287 (add-hook 'post-self-insert-hook
4288 #'python-electric-pair-string-delimiter 'append t)
4290 (set (make-local-variable 'paragraph-start) "\\s-*$")
4291 (set (make-local-variable 'fill-paragraph-function)
4292 #'python-fill-paragraph)
4294 (set (make-local-variable 'beginning-of-defun-function)
4295 #'python-nav-beginning-of-defun)
4296 (set (make-local-variable 'end-of-defun-function)
4297 #'python-nav-end-of-defun)
4299 (add-hook 'completion-at-point-functions
4300 #'python-completion-at-point nil 'local)
4302 (add-hook 'post-self-insert-hook
4303 #'python-indent-post-self-insert-function 'append 'local)
4305 (set (make-local-variable 'imenu-create-index-function)
4306 #'python-imenu-create-index)
4308 (set (make-local-variable 'add-log-current-defun-function)
4309 #'python-info-current-defun)
4311 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4313 (set (make-local-variable 'skeleton-further-elements)
4314 '((abbrev-mode nil)
4315 (< '(backward-delete-char-untabify (min python-indent-offset
4316 (current-column))))
4317 (^ '(- (1+ (current-indentation))))))
4319 (set (make-local-variable 'eldoc-documentation-function)
4320 #'python-eldoc-function)
4322 (add-to-list 'hs-special-modes-alist
4323 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
4324 ,(lambda (_arg)
4325 (python-nav-end-of-defun)) nil))
4327 (set (make-local-variable 'outline-regexp)
4328 (python-rx (* space) block-start))
4329 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4330 (set (make-local-variable 'outline-level)
4331 #'(lambda ()
4332 "`outline-level' function for Python mode."
4333 (1+ (/ (current-indentation) python-indent-offset))))
4335 (python-skeleton-add-menu-items)
4337 (make-local-variable 'python-shell-internal-buffer)
4339 (when python-indent-guess-indent-offset
4340 (python-indent-guess-indent-offset)))
4343 (provide 'python)
4345 ;; Local Variables:
4346 ;; coding: utf-8
4347 ;; indent-tabs-mode: nil
4348 ;; End:
4350 ;;; python.el ends here