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