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