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