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