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