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