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