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