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