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