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