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