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