]> code.delx.au - gnu-emacs/blob - lisp/progmodes/python.el
python.el: Fix local/remote shell environment setup
[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 (make-symbol "remote-p")))
2064 `(let* ((,remote-p (file-remote-p default-directory))
2065 (process-environment
2066 (if ,remote-p
2067 process-environment
2068 (python-shell-calculate-process-environment)))
2069 (tramp-remote-process-environment
2070 (if ,remote-p
2071 (python-shell-calculate-process-environment)
2072 tramp-remote-process-environment))
2073 (exec-path
2074 (if ,remote-p
2075 exec-path
2076 (python-shell-calculate-exec-path)))
2077 (tramp-remote-path
2078 (if ,remote-p
2079 (python-shell-calculate-exec-path)
2080 tramp-remote-path)))
2081 ,(macroexp-progn body))))
2082
2083 (defvar python-shell--prompt-calculated-input-regexp nil
2084 "Calculated input prompt regexp for inferior python shell.
2085 Do not set this variable directly, instead use
2086 `python-shell-prompt-set-calculated-regexps'.")
2087
2088 (defvar python-shell--prompt-calculated-output-regexp nil
2089 "Calculated output prompt regexp for inferior python shell.
2090 Do not set this variable directly, instead use
2091 `python-shell-set-prompt-regexp'.")
2092
2093 (defun python-shell-prompt-detect ()
2094 "Detect prompts for the current `python-shell-interpreter'.
2095 When prompts can be retrieved successfully from the
2096 `python-shell-interpreter' run with
2097 `python-shell-interpreter-interactive-arg', returns a list of
2098 three elements, where the first two are input prompts and the
2099 last one is an output prompt. When no prompts can be detected
2100 and `python-shell-prompt-detect-failure-warning' is non-nil,
2101 shows a warning with instructions to avoid hangs and returns nil.
2102 When `python-shell-prompt-detect-enabled' is nil avoids any
2103 detection and just returns nil."
2104 (when python-shell-prompt-detect-enabled
2105 (python-shell-with-environment
2106 (let* ((code (concat
2107 "import sys\n"
2108 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
2109 ;; JSON is built manually for compatibility
2110 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
2111 "print (ps_json)\n"
2112 "sys.exit(0)\n"))
2113 (output
2114 (with-temp-buffer
2115 ;; TODO: improve error handling by using
2116 ;; `condition-case' and displaying the error message to
2117 ;; the user in the no-prompts warning.
2118 (ignore-errors
2119 (let ((code-file (python-shell--save-temp-file code)))
2120 ;; Use `process-file' as it is remote-host friendly.
2121 (process-file
2122 python-shell-interpreter
2123 code-file
2124 '(t nil)
2125 nil
2126 python-shell-interpreter-interactive-arg)
2127 ;; Try to cleanup
2128 (delete-file code-file)))
2129 (buffer-string)))
2130 (prompts
2131 (catch 'prompts
2132 (dolist (line (split-string output "\n" t))
2133 (let ((res
2134 ;; Check if current line is a valid JSON array
2135 (and (string= (substring line 0 2) "[\"")
2136 (ignore-errors
2137 ;; Return prompts as a list, not vector
2138 (append (json-read-from-string line) nil)))))
2139 ;; The list must contain 3 strings, where the first
2140 ;; is the input prompt, the second is the block
2141 ;; prompt and the last one is the output prompt. The
2142 ;; input prompt is the only one that can't be empty.
2143 (when (and (= (length res) 3)
2144 (cl-every #'stringp res)
2145 (not (string= (car res) "")))
2146 (throw 'prompts res))))
2147 nil)))
2148 (when (and (not prompts)
2149 python-shell-prompt-detect-failure-warning)
2150 (lwarn
2151 '(python python-shell-prompt-regexp)
2152 :warning
2153 (concat
2154 "Python shell prompts cannot be detected.\n"
2155 "If your emacs session hangs when starting python shells\n"
2156 "recover with `keyboard-quit' and then try fixing the\n"
2157 "interactive flag for your interpreter by adjusting the\n"
2158 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2159 "matching shell prompts in the directory-local friendly vars:\n"
2160 " + `python-shell-prompt-regexp'\n"
2161 " + `python-shell-prompt-block-regexp'\n"
2162 " + `python-shell-prompt-output-regexp'\n"
2163 "Or alternatively in:\n"
2164 " + `python-shell-prompt-input-regexps'\n"
2165 " + `python-shell-prompt-output-regexps'")))
2166 prompts))))
2167
2168 (defun python-shell-prompt-validate-regexps ()
2169 "Validate all user provided regexps for prompts.
2170 Signals `user-error' if any of these vars contain invalid
2171 regexps: `python-shell-prompt-regexp',
2172 `python-shell-prompt-block-regexp',
2173 `python-shell-prompt-pdb-regexp',
2174 `python-shell-prompt-output-regexp',
2175 `python-shell-prompt-input-regexps',
2176 `python-shell-prompt-output-regexps'."
2177 (dolist (symbol (list 'python-shell-prompt-input-regexps
2178 'python-shell-prompt-output-regexps
2179 'python-shell-prompt-regexp
2180 'python-shell-prompt-block-regexp
2181 'python-shell-prompt-pdb-regexp
2182 'python-shell-prompt-output-regexp))
2183 (dolist (regexp (let ((regexps (symbol-value symbol)))
2184 (if (listp regexps)
2185 regexps
2186 (list regexps))))
2187 (when (not (python-util-valid-regexp-p regexp))
2188 (user-error "Invalid regexp %s in `%s'"
2189 regexp symbol)))))
2190
2191 (defun python-shell-prompt-set-calculated-regexps ()
2192 "Detect and set input and output prompt regexps.
2193 Build and set the values for `python-shell-input-prompt-regexp'
2194 and `python-shell-output-prompt-regexp' using the values from
2195 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2196 `python-shell-prompt-pdb-regexp',
2197 `python-shell-prompt-output-regexp',
2198 `python-shell-prompt-input-regexps',
2199 `python-shell-prompt-output-regexps' and detected prompts from
2200 `python-shell-prompt-detect'."
2201 (when (not (and python-shell--prompt-calculated-input-regexp
2202 python-shell--prompt-calculated-output-regexp))
2203 (let* ((detected-prompts (python-shell-prompt-detect))
2204 (input-prompts nil)
2205 (output-prompts nil)
2206 (build-regexp
2207 (lambda (prompts)
2208 (concat "^\\("
2209 (mapconcat #'identity
2210 (sort prompts
2211 (lambda (a b)
2212 (let ((length-a (length a))
2213 (length-b (length b)))
2214 (if (= length-a length-b)
2215 (string< a b)
2216 (> (length a) (length b))))))
2217 "\\|")
2218 "\\)"))))
2219 ;; Validate ALL regexps
2220 (python-shell-prompt-validate-regexps)
2221 ;; Collect all user defined input prompts
2222 (dolist (prompt (append python-shell-prompt-input-regexps
2223 (list python-shell-prompt-regexp
2224 python-shell-prompt-block-regexp
2225 python-shell-prompt-pdb-regexp)))
2226 (cl-pushnew prompt input-prompts :test #'string=))
2227 ;; Collect all user defined output prompts
2228 (dolist (prompt (cons python-shell-prompt-output-regexp
2229 python-shell-prompt-output-regexps))
2230 (cl-pushnew prompt output-prompts :test #'string=))
2231 ;; Collect detected prompts if any
2232 (when detected-prompts
2233 (dolist (prompt (butlast detected-prompts))
2234 (setq prompt (regexp-quote prompt))
2235 (cl-pushnew prompt input-prompts :test #'string=))
2236 (cl-pushnew (regexp-quote
2237 (car (last detected-prompts)))
2238 output-prompts :test #'string=))
2239 ;; Set input and output prompt regexps from collected prompts
2240 (setq python-shell--prompt-calculated-input-regexp
2241 (funcall build-regexp input-prompts)
2242 python-shell--prompt-calculated-output-regexp
2243 (funcall build-regexp output-prompts)))))
2244
2245 (defun python-shell-get-process-name (dedicated)
2246 "Calculate the appropriate process name for inferior Python process.
2247 If DEDICATED is t returns a string with the form
2248 `python-shell-buffer-name'[`buffer-name'] else returns the value
2249 of `python-shell-buffer-name'."
2250 (if dedicated
2251 (format "%s[%s]" python-shell-buffer-name (buffer-name))
2252 python-shell-buffer-name))
2253
2254 (defun python-shell-internal-get-process-name ()
2255 "Calculate the appropriate process name for Internal Python process.
2256 The name is calculated from `python-shell-global-buffer-name' and
2257 the `buffer-name'."
2258 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name)))
2259
2260 (defun python-shell-calculate-command ()
2261 "Calculate the string used to execute the inferior Python process."
2262 (python-shell-with-environment
2263 ;; `exec-path' gets tweaked so that virtualenv's specific
2264 ;; `python-shell-interpreter' absolute path can be found by
2265 ;; `executable-find'.
2266 (format "%s %s"
2267 (shell-quote-argument python-shell-interpreter)
2268 python-shell-interpreter-args)))
2269
2270 (define-obsolete-function-alias
2271 'python-shell-parse-command
2272 #'python-shell-calculate-command "25.1")
2273
2274 (defun python-shell-calculate-pythonpath ()
2275 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2276 (let ((pythonpath (getenv "PYTHONPATH"))
2277 (extra (mapconcat 'identity
2278 python-shell-extra-pythonpaths
2279 path-separator)))
2280 (if pythonpath
2281 (concat extra path-separator pythonpath)
2282 extra)))
2283
2284 (defvar python-shell--package-depth 10)
2285
2286 (defun python-shell-package-enable (directory package)
2287 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2288 (interactive
2289 (let* ((dir (expand-file-name
2290 (read-directory-name
2291 "Package root: "
2292 (file-name-directory
2293 (or (buffer-file-name) default-directory)))))
2294 (name (completing-read
2295 "Package: "
2296 (python-util-list-packages
2297 dir python-shell--package-depth))))
2298 (list dir name)))
2299 (python-shell-send-string
2300 (format
2301 (concat
2302 "import os.path;import sys;"
2303 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2304 "__package__ = '''%s''';"
2305 "import %s")
2306 directory package package)
2307 (python-shell-get-process)))
2308
2309 (defun python-shell-accept-process-output (process &optional timeout regexp)
2310 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2311 Optional argument TIMEOUT is the timeout argument to
2312 `accept-process-output' calls. Optional argument REGEXP
2313 overrides the regexp to match the end of output, defaults to
2314 `comint-prompt-regexp.'. Returns non-nil when output was
2315 properly captured.
2316
2317 This utility is useful in situations where the output may be
2318 received in chunks, since `accept-process-output' gives no
2319 guarantees they will be grabbed in a single call. An example use
2320 case for this would be the CPython shell start-up, where the
2321 banner and the initial prompt are received separately."
2322 (let ((regexp (or regexp comint-prompt-regexp)))
2323 (catch 'found
2324 (while t
2325 (when (not (accept-process-output process timeout))
2326 (throw 'found nil))
2327 (when (looking-back
2328 regexp (car (python-util-comint-last-prompt)))
2329 (throw 'found t))))))
2330
2331 (defun python-shell-comint-end-of-output-p (output)
2332 "Return non-nil if OUTPUT is ends with input prompt."
2333 (string-match
2334 ;; XXX: It seems on OSX an extra carriage return is attached
2335 ;; at the end of output, this handles that too.
2336 (concat
2337 "\r?\n?"
2338 ;; Remove initial caret from calculated regexp
2339 (replace-regexp-in-string
2340 (rx string-start ?^) ""
2341 python-shell--prompt-calculated-input-regexp)
2342 (rx eos))
2343 output))
2344
2345 (define-obsolete-function-alias
2346 'python-comint-output-filter-function
2347 'ansi-color-filter-apply
2348 "25.1")
2349
2350 (defun python-comint-postoutput-scroll-to-bottom (output)
2351 "Faster version of `comint-postoutput-scroll-to-bottom'.
2352 Avoids `recenter' calls until OUTPUT is completely sent."
2353 (when (and (not (string= "" output))
2354 (python-shell-comint-end-of-output-p
2355 (ansi-color-filter-apply output)))
2356 (comint-postoutput-scroll-to-bottom output))
2357 output)
2358
2359 (defvar python-shell--parent-buffer nil)
2360
2361 (defmacro python-shell-with-shell-buffer (&rest body)
2362 "Execute the forms in BODY with the shell buffer temporarily current.
2363 Signals an error if no shell buffer is available for current buffer."
2364 (declare (indent 0) (debug t))
2365 (let ((shell-process (make-symbol "shell-process")))
2366 `(let ((,shell-process (python-shell-get-process-or-error)))
2367 (with-current-buffer (process-buffer ,shell-process)
2368 ,@body))))
2369
2370 (defvar python-shell--font-lock-buffer nil)
2371
2372 (defun python-shell-font-lock-get-or-create-buffer ()
2373 "Get or create a font-lock buffer for current inferior process."
2374 (python-shell-with-shell-buffer
2375 (if python-shell--font-lock-buffer
2376 python-shell--font-lock-buffer
2377 (let ((process-name
2378 (process-name (get-buffer-process (current-buffer)))))
2379 (generate-new-buffer
2380 (format " *%s-font-lock*" process-name))))))
2381
2382 (defun python-shell-font-lock-kill-buffer ()
2383 "Kill the font-lock buffer safely."
2384 (when (and python-shell--font-lock-buffer
2385 (buffer-live-p python-shell--font-lock-buffer))
2386 (kill-buffer python-shell--font-lock-buffer)
2387 (when (derived-mode-p 'inferior-python-mode)
2388 (setq python-shell--font-lock-buffer nil))))
2389
2390 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2391 "Execute the forms in BODY in the font-lock buffer.
2392 The value returned is the value of the last form in BODY. See
2393 also `with-current-buffer'."
2394 (declare (indent 0) (debug t))
2395 `(python-shell-with-shell-buffer
2396 (save-current-buffer
2397 (when (not (and python-shell--font-lock-buffer
2398 (get-buffer python-shell--font-lock-buffer)))
2399 (setq python-shell--font-lock-buffer
2400 (python-shell-font-lock-get-or-create-buffer)))
2401 (set-buffer python-shell--font-lock-buffer)
2402 (when (not font-lock-mode)
2403 (font-lock-mode 1))
2404 (set (make-local-variable 'delay-mode-hooks) t)
2405 (let ((python-indent-guess-indent-offset nil))
2406 (when (not (derived-mode-p 'python-mode))
2407 (python-mode))
2408 ,@body))))
2409
2410 (defun python-shell-font-lock-cleanup-buffer ()
2411 "Cleanup the font-lock buffer.
2412 Provided as a command because this might be handy if something
2413 goes wrong and syntax highlighting in the shell gets messed up."
2414 (interactive)
2415 (python-shell-with-shell-buffer
2416 (python-shell-font-lock-with-font-lock-buffer
2417 (erase-buffer))))
2418
2419 (defun python-shell-font-lock-comint-output-filter-function (output)
2420 "Clean up the font-lock buffer after any OUTPUT."
2421 (if (and (not (string= "" output))
2422 ;; Is end of output and is not just a prompt.
2423 (not (member
2424 (python-shell-comint-end-of-output-p
2425 (ansi-color-filter-apply output))
2426 '(nil 0))))
2427 ;; If output is other than an input prompt then "real" output has
2428 ;; been received and the font-lock buffer must be cleaned up.
2429 (python-shell-font-lock-cleanup-buffer)
2430 ;; Otherwise just add a newline.
2431 (python-shell-font-lock-with-font-lock-buffer
2432 (goto-char (point-max))
2433 (newline)))
2434 output)
2435
2436 (defun python-shell-font-lock-post-command-hook ()
2437 "Fontifies current line in shell buffer."
2438 (let ((prompt-end (cdr (python-util-comint-last-prompt))))
2439 (when (and prompt-end (> (point) prompt-end)
2440 (process-live-p (get-buffer-process (current-buffer))))
2441 (let* ((input (buffer-substring-no-properties
2442 prompt-end (point-max)))
2443 (deactivate-mark nil)
2444 (start-pos prompt-end)
2445 (buffer-undo-list t)
2446 (font-lock-buffer-pos nil)
2447 (replacement
2448 (python-shell-font-lock-with-font-lock-buffer
2449 (delete-region (line-beginning-position)
2450 (point-max))
2451 (setq font-lock-buffer-pos (point))
2452 (insert input)
2453 ;; Ensure buffer is fontified, keeping it
2454 ;; compatible with Emacs < 24.4.
2455 (if (fboundp 'font-lock-ensure)
2456 (funcall 'font-lock-ensure)
2457 (font-lock-default-fontify-buffer))
2458 (buffer-substring font-lock-buffer-pos
2459 (point-max))))
2460 (replacement-length (length replacement))
2461 (i 0))
2462 ;; Inject text properties to get input fontified.
2463 (while (not (= i replacement-length))
2464 (let* ((plist (text-properties-at i replacement))
2465 (next-change (or (next-property-change i replacement)
2466 replacement-length))
2467 (plist (let ((face (plist-get plist 'face)))
2468 (if (not face)
2469 plist
2470 ;; Replace FACE text properties with
2471 ;; FONT-LOCK-FACE so input is fontified.
2472 (plist-put plist 'face nil)
2473 (plist-put plist 'font-lock-face face)))))
2474 (set-text-properties
2475 (+ start-pos i) (+ start-pos next-change) plist)
2476 (setq i next-change)))))))
2477
2478 (defun python-shell-font-lock-turn-on (&optional msg)
2479 "Turn on shell font-lock.
2480 With argument MSG show activation message."
2481 (interactive "p")
2482 (python-shell-with-shell-buffer
2483 (python-shell-font-lock-kill-buffer)
2484 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2485 (add-hook 'post-command-hook
2486 #'python-shell-font-lock-post-command-hook nil 'local)
2487 (add-hook 'kill-buffer-hook
2488 #'python-shell-font-lock-kill-buffer nil 'local)
2489 (add-hook 'comint-output-filter-functions
2490 #'python-shell-font-lock-comint-output-filter-function
2491 'append 'local)
2492 (when msg
2493 (message "Shell font-lock is enabled"))))
2494
2495 (defun python-shell-font-lock-turn-off (&optional msg)
2496 "Turn off shell font-lock.
2497 With argument MSG show deactivation message."
2498 (interactive "p")
2499 (python-shell-with-shell-buffer
2500 (python-shell-font-lock-kill-buffer)
2501 (when (python-util-comint-last-prompt)
2502 ;; Cleanup current fontification
2503 (remove-text-properties
2504 (cdr (python-util-comint-last-prompt))
2505 (line-end-position)
2506 '(face nil font-lock-face nil)))
2507 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2508 (remove-hook 'post-command-hook
2509 #'python-shell-font-lock-post-command-hook 'local)
2510 (remove-hook 'kill-buffer-hook
2511 #'python-shell-font-lock-kill-buffer 'local)
2512 (remove-hook 'comint-output-filter-functions
2513 #'python-shell-font-lock-comint-output-filter-function
2514 'local)
2515 (when msg
2516 (message "Shell font-lock is disabled"))))
2517
2518 (defun python-shell-font-lock-toggle (&optional msg)
2519 "Toggle font-lock for shell.
2520 With argument MSG show activation/deactivation message."
2521 (interactive "p")
2522 (python-shell-with-shell-buffer
2523 (set (make-local-variable 'python-shell-font-lock-enable)
2524 (not python-shell-font-lock-enable))
2525 (if python-shell-font-lock-enable
2526 (python-shell-font-lock-turn-on msg)
2527 (python-shell-font-lock-turn-off msg))
2528 python-shell-font-lock-enable))
2529
2530 ;; Used to hold user interactive overrides to
2531 ;; `python-shell-interpreter' and `python-shell-interpreter-args' that
2532 ;; will be made buffer-local by `inferior-python-mode':
2533 (defvar python-shell--interpreter)
2534 (defvar python-shell--interpreter-args)
2535
2536 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2537 "Major mode for Python inferior process.
2538 Runs a Python interpreter as a subprocess of Emacs, with Python
2539 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2540 and `python-shell-interpreter-args' control which Python
2541 interpreter is run. Variables
2542 `python-shell-prompt-regexp',
2543 `python-shell-prompt-output-regexp',
2544 `python-shell-prompt-block-regexp',
2545 `python-shell-font-lock-enable',
2546 `python-shell-completion-setup-code',
2547 `python-shell-completion-string-code',
2548 `python-eldoc-setup-code', `python-eldoc-string-code',
2549 `python-ffap-setup-code' and `python-ffap-string-code' can
2550 customize this mode for different Python interpreters.
2551
2552 This mode resets `comint-output-filter-functions' locally, so you
2553 may want to re-add custom functions to it using the
2554 `inferior-python-mode-hook'.
2555
2556 You can also add additional setup code to be run at
2557 initialization of the interpreter via `python-shell-setup-codes'
2558 variable.
2559
2560 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2561 (when python-shell--parent-buffer
2562 (python-util-clone-local-variables python-shell--parent-buffer))
2563 ;; Users can interactively override default values for
2564 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
2565 ;; when calling `run-python'. This ensures values let-bound in
2566 ;; `python-shell-make-comint' are locally set if needed.
2567 (set (make-local-variable 'python-shell-interpreter)
2568 (or python-shell--interpreter python-shell-interpreter))
2569 (set (make-local-variable 'python-shell-interpreter-args)
2570 (or python-shell--interpreter-args python-shell-interpreter-args))
2571 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2572 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2573 (python-shell-prompt-set-calculated-regexps)
2574 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2575 (set (make-local-variable 'comint-prompt-read-only) t)
2576 (setq mode-line-process '(":%s"))
2577 (set (make-local-variable 'comint-output-filter-functions)
2578 '(ansi-color-process-output
2579 python-pdbtrack-comint-output-filter-function
2580 python-comint-postoutput-scroll-to-bottom))
2581 (set (make-local-variable 'compilation-error-regexp-alist)
2582 python-shell-compilation-regexp-alist)
2583 (add-hook 'completion-at-point-functions
2584 #'python-shell-completion-at-point nil 'local)
2585 (define-key inferior-python-mode-map "\t"
2586 'python-shell-completion-complete-or-indent)
2587 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2588 (make-local-variable 'python-pdbtrack-tracked-buffer)
2589 (make-local-variable 'python-shell-internal-last-output)
2590 (when python-shell-font-lock-enable
2591 (python-shell-font-lock-turn-on))
2592 (compilation-shell-minor-mode 1)
2593 (python-shell-accept-process-output
2594 (get-buffer-process (current-buffer))))
2595
2596 (defun python-shell-make-comint (cmd proc-name &optional show internal)
2597 "Create a Python shell comint buffer.
2598 CMD is the Python command to be executed and PROC-NAME is the
2599 process name the comint buffer will get. After the comint buffer
2600 is created the `inferior-python-mode' is activated. When
2601 optional argument SHOW is non-nil the buffer is shown. When
2602 optional argument INTERNAL is non-nil this process is run on a
2603 buffer with a name that starts with a space, following the Emacs
2604 convention for temporary/internal buffers, and also makes sure
2605 the user is not queried for confirmation when the process is
2606 killed."
2607 (save-excursion
2608 (python-shell-with-environment
2609 (let* ((proc-buffer-name
2610 (format (if (not internal) "*%s*" " *%s*") proc-name)))
2611 (when (not (comint-check-proc proc-buffer-name))
2612 (let* ((cmdlist (split-string-and-unquote cmd))
2613 (interpreter (car cmdlist))
2614 (args (cdr cmdlist))
2615 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2616 interpreter nil args))
2617 (python-shell--parent-buffer (current-buffer))
2618 (process (get-buffer-process buffer))
2619 ;; Users can override the interpreter and args
2620 ;; interactively when calling `run-python', let-binding
2621 ;; these allows to have the new right values in all
2622 ;; setup code that is done in `inferior-python-mode',
2623 ;; which is important, especially for prompt detection.
2624 (python-shell--interpreter interpreter)
2625 (python-shell--interpreter-args
2626 (mapconcat #'identity args " ")))
2627 (with-current-buffer buffer
2628 (inferior-python-mode))
2629 (when show (display-buffer buffer))
2630 (and internal (set-process-query-on-exit-flag process nil))))
2631 proc-buffer-name))))
2632
2633 ;;;###autoload
2634 (defun run-python (&optional cmd dedicated show)
2635 "Run an inferior Python process.
2636
2637 Argument CMD defaults to `python-shell-calculate-command' return
2638 value. When called interactively with `prefix-arg', it allows
2639 the user to edit such value and choose whether the interpreter
2640 should be DEDICATED for the current buffer. When numeric prefix
2641 arg is other than 0 or 4 do not SHOW.
2642
2643 For a given buffer and same values of DEDICATED, if a process is
2644 already running for it, it will do nothing. This means that if
2645 the current buffer is using a global process, the user is still
2646 able to switch it to use a dedicated one.
2647
2648 Runs the hook `inferior-python-mode-hook' after
2649 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2650 process buffer for a list of commands.)"
2651 (interactive
2652 (if current-prefix-arg
2653 (list
2654 (read-shell-command "Run Python: " (python-shell-calculate-command))
2655 (y-or-n-p "Make dedicated process? ")
2656 (= (prefix-numeric-value current-prefix-arg) 4))
2657 (list (python-shell-calculate-command) nil t)))
2658 (get-buffer-process
2659 (python-shell-make-comint
2660 (or cmd (python-shell-calculate-command))
2661 (python-shell-get-process-name dedicated) show)))
2662
2663 (defun run-python-internal ()
2664 "Run an inferior Internal Python process.
2665 Input and output via buffer named after
2666 `python-shell-internal-buffer-name' and what
2667 `python-shell-internal-get-process-name' returns.
2668
2669 This new kind of shell is intended to be used for generic
2670 communication related to defined configurations; the main
2671 difference with global or dedicated shells is that these ones are
2672 attached to a configuration, not a buffer. This means that can
2673 be used for example to retrieve the sys.path and other stuff,
2674 without messing with user shells. Note that
2675 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2676 are set to nil for these shells, so setup codes are not sent at
2677 startup."
2678 (let ((python-shell-font-lock-enable nil)
2679 (inferior-python-mode-hook nil))
2680 (get-buffer-process
2681 (python-shell-make-comint
2682 (python-shell-calculate-command)
2683 (python-shell-internal-get-process-name) nil t))))
2684
2685 (defun python-shell-get-buffer ()
2686 "Return inferior Python buffer for current buffer.
2687 If current buffer is in `inferior-python-mode', return it."
2688 (if (derived-mode-p 'inferior-python-mode)
2689 (current-buffer)
2690 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2691 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2692 (global-proc-name (python-shell-get-process-name nil))
2693 (global-proc-buffer-name (format "*%s*" global-proc-name))
2694 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2695 (global-running (comint-check-proc global-proc-buffer-name)))
2696 ;; Always prefer dedicated
2697 (or (and dedicated-running dedicated-proc-buffer-name)
2698 (and global-running global-proc-buffer-name)))))
2699
2700 (defun python-shell-get-process ()
2701 "Return inferior Python process for current buffer."
2702 (get-buffer-process (python-shell-get-buffer)))
2703
2704 (defun python-shell-get-process-or-error (&optional interactivep)
2705 "Return inferior Python process for current buffer or signal error.
2706 When argument INTERACTIVEP is non-nil, use `user-error' instead
2707 of `error' with a user-friendly message."
2708 (or (python-shell-get-process)
2709 (if interactivep
2710 (user-error
2711 "Start a Python process first with `M-x run-python' or `%s'."
2712 ;; Get the binding.
2713 (key-description
2714 (where-is-internal
2715 #'run-python overriding-local-map t)))
2716 (error
2717 "No inferior Python process running."))))
2718
2719 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2720 "Get or create an inferior Python process for current buffer and return it.
2721 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2722 are used to start the shell. If those arguments are not
2723 provided, `run-python' is called interactively and the user will
2724 be asked for their values."
2725 (let ((shell-process (python-shell-get-process)))
2726 (when (not shell-process)
2727 (if (not cmd)
2728 ;; XXX: Refactor code such that calling `run-python'
2729 ;; interactively is not needed anymore.
2730 (call-interactively 'run-python)
2731 (run-python cmd dedicated show)))
2732 (or shell-process (python-shell-get-process))))
2733
2734 (make-obsolete
2735 #'python-shell-get-or-create-process
2736 "Instead call `python-shell-get-process' and create one if returns nil."
2737 "25.1")
2738
2739 (defvar python-shell-internal-buffer nil
2740 "Current internal shell buffer for the current buffer.
2741 This is really not necessary at all for the code to work but it's
2742 there for compatibility with CEDET.")
2743
2744 (defvar python-shell-internal-last-output nil
2745 "Last output captured by the internal shell.
2746 This is really not necessary at all for the code to work but it's
2747 there for compatibility with CEDET.")
2748
2749 (defun python-shell-internal-get-or-create-process ()
2750 "Get or create an inferior Internal Python process."
2751 (let ((proc-name (python-shell-internal-get-process-name)))
2752 (if (process-live-p proc-name)
2753 (get-process proc-name)
2754 (run-python-internal))))
2755
2756 (define-obsolete-function-alias
2757 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2758
2759 (define-obsolete-variable-alias
2760 'python-buffer 'python-shell-internal-buffer "24.3")
2761
2762 (define-obsolete-variable-alias
2763 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2764
2765 (defun python-shell--save-temp-file (string)
2766 (let* ((temporary-file-directory
2767 (if (file-remote-p default-directory)
2768 (concat (file-remote-p default-directory) "/tmp")
2769 temporary-file-directory))
2770 (temp-file-name (make-temp-file "py"))
2771 (coding-system-for-write (python-info-encoding)))
2772 (with-temp-file temp-file-name
2773 (insert string)
2774 (delete-trailing-whitespace))
2775 temp-file-name))
2776
2777 (defun python-shell-send-string (string &optional process msg)
2778 "Send STRING to inferior Python PROCESS.
2779 When optional argument MSG is non-nil, forces display of a
2780 user-friendly message if there's no process running; defaults to
2781 t when called interactively."
2782 (interactive
2783 (list (read-string "Python command: ") nil t))
2784 (let ((process (or process (python-shell-get-process-or-error msg))))
2785 (if (string-match ".\n+." string) ;Multiline.
2786 (let* ((temp-file-name (python-shell--save-temp-file string))
2787 (file-name (or (buffer-file-name) temp-file-name)))
2788 (python-shell-send-file file-name process temp-file-name t))
2789 (comint-send-string process string)
2790 (when (or (not (string-match "\n\\'" string))
2791 (string-match "\n[ \t].*\n?\\'" string))
2792 (comint-send-string process "\n")))))
2793
2794 (defvar python-shell-output-filter-in-progress nil)
2795 (defvar python-shell-output-filter-buffer nil)
2796
2797 (defun python-shell-output-filter (string)
2798 "Filter used in `python-shell-send-string-no-output' to grab output.
2799 STRING is the output received to this point from the process.
2800 This filter saves received output from the process in
2801 `python-shell-output-filter-buffer' and stops receiving it after
2802 detecting a prompt at the end of the buffer."
2803 (setq
2804 string (ansi-color-filter-apply string)
2805 python-shell-output-filter-buffer
2806 (concat python-shell-output-filter-buffer string))
2807 (when (python-shell-comint-end-of-output-p
2808 python-shell-output-filter-buffer)
2809 ;; Output ends when `python-shell-output-filter-buffer' contains
2810 ;; the prompt attached at the end of it.
2811 (setq python-shell-output-filter-in-progress nil
2812 python-shell-output-filter-buffer
2813 (substring python-shell-output-filter-buffer
2814 0 (match-beginning 0)))
2815 (when (string-match
2816 python-shell--prompt-calculated-output-regexp
2817 python-shell-output-filter-buffer)
2818 ;; Some shells, like IPython might append a prompt before the
2819 ;; output, clean that.
2820 (setq python-shell-output-filter-buffer
2821 (substring python-shell-output-filter-buffer (match-end 0)))))
2822 "")
2823
2824 (defun python-shell-send-string-no-output (string &optional process)
2825 "Send STRING to PROCESS and inhibit output.
2826 Return the output."
2827 (let ((process (or process (python-shell-get-process-or-error)))
2828 (comint-preoutput-filter-functions
2829 '(python-shell-output-filter))
2830 (python-shell-output-filter-in-progress t)
2831 (inhibit-quit t))
2832 (or
2833 (with-local-quit
2834 (python-shell-send-string string process)
2835 (while python-shell-output-filter-in-progress
2836 ;; `python-shell-output-filter' takes care of setting
2837 ;; `python-shell-output-filter-in-progress' to NIL after it
2838 ;; detects end of output.
2839 (accept-process-output process))
2840 (prog1
2841 python-shell-output-filter-buffer
2842 (setq python-shell-output-filter-buffer nil)))
2843 (with-current-buffer (process-buffer process)
2844 (comint-interrupt-subjob)))))
2845
2846 (defun python-shell-internal-send-string (string)
2847 "Send STRING to the Internal Python interpreter.
2848 Returns the output. See `python-shell-send-string-no-output'."
2849 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2850 ;; updated to support this new mode.
2851 (setq python-shell-internal-last-output
2852 (python-shell-send-string-no-output
2853 ;; Makes this function compatible with the old
2854 ;; python-send-receive. (At least for CEDET).
2855 (replace-regexp-in-string "_emacs_out +" "" string)
2856 (python-shell-internal-get-or-create-process))))
2857
2858 (define-obsolete-function-alias
2859 'python-send-receive 'python-shell-internal-send-string "24.3")
2860
2861 (define-obsolete-function-alias
2862 'python-send-string 'python-shell-internal-send-string "24.3")
2863
2864 (defun python-shell-buffer-substring (start end &optional nomain)
2865 "Send buffer substring from START to END formatted for shell.
2866 This is a wrapper over `buffer-substring' that takes care of
2867 different transformations for the code sent to be evaluated in
2868 the python shell:
2869 1. When optional argument NOMAIN is non-nil everything under an
2870 \"if __name__ == '__main__'\" block will be removed.
2871 2. When a subregion of the buffer is sent, it takes care of
2872 appending extra empty lines so tracebacks are correct.
2873 3. When the region sent is a substring of the current buffer, a
2874 coding cookie is added.
2875 4. Wraps indented regions under an \"if True:\" block so the
2876 interpreter evaluates them correctly."
2877 (let* ((substring (buffer-substring-no-properties start end))
2878 (starts-at-point-min-p (save-restriction
2879 (widen)
2880 (= (point-min) start)))
2881 (encoding (python-info-encoding))
2882 (fillstr (when (not starts-at-point-min-p)
2883 (concat
2884 (format "# -*- coding: %s -*-\n" encoding)
2885 (make-string
2886 ;; Subtract 2 because of the coding cookie.
2887 (- (line-number-at-pos start) 2) ?\n))))
2888 (toplevel-block-p (save-excursion
2889 (goto-char start)
2890 (or (zerop (line-number-at-pos start))
2891 (progn
2892 (python-util-forward-comment 1)
2893 (zerop (current-indentation)))))))
2894 (with-temp-buffer
2895 (python-mode)
2896 (if fillstr (insert fillstr))
2897 (insert substring)
2898 (goto-char (point-min))
2899 (when (not toplevel-block-p)
2900 (insert "if True:")
2901 (delete-region (point) (line-end-position)))
2902 (when nomain
2903 (let* ((if-name-main-start-end
2904 (and nomain
2905 (save-excursion
2906 (when (python-nav-if-name-main)
2907 (cons (point)
2908 (progn (python-nav-forward-sexp-safe)
2909 ;; Include ending newline
2910 (forward-line 1)
2911 (point)))))))
2912 ;; Oh destructuring bind, how I miss you.
2913 (if-name-main-start (car if-name-main-start-end))
2914 (if-name-main-end (cdr if-name-main-start-end))
2915 (fillstr (make-string
2916 (- (line-number-at-pos if-name-main-end)
2917 (line-number-at-pos if-name-main-start)) ?\n)))
2918 (when if-name-main-start-end
2919 (goto-char if-name-main-start)
2920 (delete-region if-name-main-start if-name-main-end)
2921 (insert fillstr))))
2922 ;; Ensure there's only one coding cookie in the generated string.
2923 (goto-char (point-min))
2924 (when (looking-at-p (python-rx coding-cookie))
2925 (forward-line 1)
2926 (when (looking-at-p (python-rx coding-cookie))
2927 (delete-region
2928 (line-beginning-position) (line-end-position))))
2929 (buffer-substring-no-properties (point-min) (point-max)))))
2930
2931 (defun python-shell-send-region (start end &optional send-main msg)
2932 "Send the region delimited by START and END to inferior Python process.
2933 When optional argument SEND-MAIN is non-nil, allow execution of
2934 code inside blocks delimited by \"if __name__== '__main__':\".
2935 When called interactively SEND-MAIN defaults to nil, unless it's
2936 called with prefix argument. When optional argument MSG is
2937 non-nil, forces display of a user-friendly message if there's no
2938 process running; defaults to t when called interactively."
2939 (interactive
2940 (list (region-beginning) (region-end) current-prefix-arg t))
2941 (let* ((string (python-shell-buffer-substring start end (not send-main)))
2942 (process (python-shell-get-process-or-error msg))
2943 (original-string (buffer-substring-no-properties start end))
2944 (_ (string-match "\\`\n*\\(.*\\)" original-string)))
2945 (message "Sent: %s..." (match-string 1 original-string))
2946 (python-shell-send-string string process)))
2947
2948 (defun python-shell-send-buffer (&optional send-main msg)
2949 "Send the entire buffer to inferior Python process.
2950 When optional argument SEND-MAIN is non-nil, allow execution of
2951 code inside blocks delimited by \"if __name__== '__main__':\".
2952 When called interactively SEND-MAIN defaults to nil, unless it's
2953 called with prefix argument. When optional argument MSG is
2954 non-nil, forces display of a user-friendly message if there's no
2955 process running; defaults to t when called interactively."
2956 (interactive (list current-prefix-arg t))
2957 (save-restriction
2958 (widen)
2959 (python-shell-send-region (point-min) (point-max) send-main msg)))
2960
2961 (defun python-shell-send-defun (&optional arg msg)
2962 "Send the current defun to inferior Python process.
2963 When argument ARG is non-nil do not include decorators. When
2964 optional argument MSG is non-nil, forces display of a
2965 user-friendly message if there's no process running; defaults to
2966 t when called interactively."
2967 (interactive (list current-prefix-arg t))
2968 (save-excursion
2969 (python-shell-send-region
2970 (progn
2971 (end-of-line 1)
2972 (while (and (or (python-nav-beginning-of-defun)
2973 (beginning-of-line 1))
2974 (> (current-indentation) 0)))
2975 (when (not arg)
2976 (while (and (forward-line -1)
2977 (looking-at (python-rx decorator))))
2978 (forward-line 1))
2979 (point-marker))
2980 (progn
2981 (or (python-nav-end-of-defun)
2982 (end-of-line 1))
2983 (point-marker))
2984 nil ;; noop
2985 msg)))
2986
2987 (defun python-shell-send-file (file-name &optional process temp-file-name
2988 delete msg)
2989 "Send FILE-NAME to inferior Python PROCESS.
2990 If TEMP-FILE-NAME is passed then that file is used for processing
2991 instead, while internally the shell will continue to use
2992 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
2993 TEMP-FILE-NAME is deleted after evaluation is performed. When
2994 optional argument MSG is non-nil, forces display of a
2995 user-friendly message if there's no process running; defaults to
2996 t when called interactively."
2997 (interactive
2998 (list
2999 (read-file-name "File to send: ") ; file-name
3000 nil ; process
3001 nil ; temp-file-name
3002 nil ; delete
3003 t)) ; msg
3004 (let* ((process (or process (python-shell-get-process-or-error msg)))
3005 (encoding (with-temp-buffer
3006 (insert-file-contents
3007 (or temp-file-name file-name))
3008 (python-info-encoding)))
3009 (file-name (expand-file-name
3010 (or (file-remote-p file-name 'localname)
3011 file-name)))
3012 (temp-file-name (when temp-file-name
3013 (expand-file-name
3014 (or (file-remote-p temp-file-name 'localname)
3015 temp-file-name)))))
3016 (python-shell-send-string
3017 (format
3018 (concat
3019 "import codecs, os;"
3020 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
3021 "__code = __pyfile.read().encode('''%s''');"
3022 "__pyfile.close();"
3023 (when (and delete temp-file-name)
3024 (format "os.remove('''%s''');" temp-file-name))
3025 "exec(compile(__code, '''%s''', 'exec'));")
3026 (or temp-file-name file-name) encoding encoding file-name)
3027 process)))
3028
3029 (defun python-shell-switch-to-shell (&optional msg)
3030 "Switch to inferior Python process buffer.
3031 When optional argument MSG is non-nil, forces display of a
3032 user-friendly message if there's no process running; defaults to
3033 t when called interactively."
3034 (interactive "p")
3035 (pop-to-buffer
3036 (process-buffer (python-shell-get-process-or-error msg)) nil t))
3037
3038 (defun python-shell-send-setup-code ()
3039 "Send all setup code for shell.
3040 This function takes the list of setup code to send from the
3041 `python-shell-setup-codes' list."
3042 (let ((process (python-shell-get-process))
3043 (code (concat
3044 (mapconcat
3045 (lambda (elt)
3046 (cond ((stringp elt) elt)
3047 ((symbolp elt) (symbol-value elt))
3048 (t "")))
3049 python-shell-setup-codes
3050 "\n\n")
3051 "\n\nprint ('python.el: sent setup code')")))
3052 (python-shell-send-string code process)
3053 (python-shell-accept-process-output process)))
3054
3055 (add-hook 'inferior-python-mode-hook
3056 #'python-shell-send-setup-code)
3057
3058 \f
3059 ;;; Shell completion
3060
3061 (defcustom python-shell-completion-setup-code
3062 "try:
3063 import readline
3064 except:
3065 def __PYTHON_EL_get_completions(text):
3066 return []
3067 else:
3068 def __PYTHON_EL_get_completions(text):
3069 try:
3070 import __builtin__
3071 except ImportError:
3072 # Python 3
3073 import builtins as __builtin__
3074 builtins = dir(__builtin__)
3075 completions = []
3076 is_ipython = ('__IPYTHON__' in builtins or
3077 '__IPYTHON__active' in builtins)
3078 splits = text.split()
3079 is_module = splits and splits[0] in ('from', 'import')
3080 try:
3081 if is_ipython and is_module:
3082 from IPython.core.completerlib import module_completion
3083 completions = module_completion(text.strip())
3084 elif is_ipython and '__IP' in builtins:
3085 completions = __IP.complete(text)
3086 elif is_ipython and 'get_ipython' in builtins:
3087 completions = get_ipython().Completer.all_completions(text)
3088 else:
3089 # Try to reuse current completer.
3090 completer = readline.get_completer()
3091 if not completer:
3092 # importing rlcompleter sets the completer, use it as a
3093 # last resort to avoid breaking customizations.
3094 import rlcompleter
3095 completer = readline.get_completer()
3096 i = 0
3097 while True:
3098 completion = completer(text, i)
3099 if not completion:
3100 break
3101 i += 1
3102 completions.append(completion)
3103 except:
3104 pass
3105 return completions"
3106 "Code used to setup completion in inferior Python processes."
3107 :type 'string
3108 :group 'python)
3109
3110 (defcustom python-shell-completion-string-code
3111 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
3112 "Python code used to get a string of completions separated by semicolons.
3113 The string passed to the function is the current python name or
3114 the full statement in the case of imports."
3115 :type 'string
3116 :group 'python)
3117
3118 (define-obsolete-variable-alias
3119 'python-shell-completion-module-string-code
3120 'python-shell-completion-string-code
3121 "24.4"
3122 "Completion string code must also autocomplete modules.")
3123
3124 (define-obsolete-variable-alias
3125 'python-shell-completion-pdb-string-code
3126 'python-shell-completion-string-code
3127 "25.1"
3128 "Completion string code must work for (i)pdb.")
3129
3130 (defcustom python-shell-completion-native-disabled-interpreters
3131 ;; PyPy's readline cannot handle some escape sequences yet.
3132 (list "pypy")
3133 "List of disabled interpreters.
3134 When a match is found, native completion is disabled."
3135 :type '(repeat string))
3136
3137 (defcustom python-shell-completion-native-enable t
3138 "Enable readline based native completion."
3139 :type 'boolean)
3140
3141 (defcustom python-shell-completion-native-output-timeout 5.0
3142 "Time in seconds to wait for completion output before giving up."
3143 :type 'float)
3144
3145 (defcustom python-shell-completion-native-try-output-timeout 1.0
3146 "Time in seconds to wait for *trying* native completion output."
3147 :type 'float)
3148
3149 (defvar python-shell-completion-native-redirect-buffer
3150 " *Python completions redirect*"
3151 "Buffer to be used to redirect output of readline commands.")
3152
3153 (defun python-shell-completion-native-interpreter-disabled-p ()
3154 "Return non-nil if interpreter has native completion disabled."
3155 (when python-shell-completion-native-disabled-interpreters
3156 (string-match
3157 (regexp-opt python-shell-completion-native-disabled-interpreters)
3158 (file-name-nondirectory python-shell-interpreter))))
3159
3160 (defun python-shell-completion-native-try ()
3161 "Return non-nil if can trigger native completion."
3162 (let ((python-shell-completion-native-enable t)
3163 (python-shell-completion-native-output-timeout
3164 python-shell-completion-native-try-output-timeout))
3165 (python-shell-completion-native-get-completions
3166 (get-buffer-process (current-buffer))
3167 nil "int")))
3168
3169 (defun python-shell-completion-native-setup ()
3170 "Try to setup native completion, return non-nil on success."
3171 (let ((process (python-shell-get-process)))
3172 (python-shell-send-string "
3173 def __PYTHON_EL_native_completion_setup():
3174 try:
3175 import readline
3176 try:
3177 import __builtin__
3178 except ImportError:
3179 # Python 3
3180 import builtins as __builtin__
3181 builtins = dir(__builtin__)
3182 is_ipython = ('__IPYTHON__' in builtins or
3183 '__IPYTHON__active' in builtins)
3184 class __PYTHON_EL_Completer:
3185 PYTHON_EL_WRAPPED = True
3186 def __init__(self, completer):
3187 self.completer = completer
3188 self.last_completion = None
3189 def __call__(self, text, state):
3190 if state == 0:
3191 # The first completion is always a dummy completion. This
3192 # ensures proper output for sole completions and a current
3193 # input safeguard when no completions are available.
3194 self.last_completion = None
3195 completion = '0__dummy_completion__'
3196 else:
3197 completion = self.completer(text, state - 1)
3198 if not completion:
3199 if state == 1:
3200 # When no completions are available, two non-sharing
3201 # prefix strings are returned just to ensure output
3202 # while preventing changes to current input.
3203 completion = '1__dummy_completion__'
3204 elif self.last_completion != '~~~~__dummy_completion__':
3205 # This marks the end of output.
3206 completion = '~~~~__dummy_completion__'
3207 elif completion.endswith('('):
3208 # Remove parens on callables as it breaks completion on
3209 # arguments (e.g. str(Ari<tab>)).
3210 completion = completion[:-1]
3211 self.last_completion = completion
3212 return completion
3213 completer = readline.get_completer()
3214 if not completer:
3215 # Used as last resort to avoid breaking customizations.
3216 import rlcompleter
3217 completer = readline.get_completer()
3218 if completer and not getattr(completer, 'PYTHON_EL_WRAPPED', False):
3219 # Wrap the existing completer function only once.
3220 new_completer = __PYTHON_EL_Completer(completer)
3221 if not is_ipython:
3222 readline.set_completer(new_completer)
3223 else:
3224 # Try both initializations to cope with all IPython versions.
3225 # This works fine for IPython 3.x but not for earlier:
3226 readline.set_completer(new_completer)
3227 # IPython<3 hacks readline such that `readline.set_completer`
3228 # won't work. This workaround injects the new completer
3229 # function into the existing instance directly:
3230 instance = getattr(completer, 'im_self', completer.__self__)
3231 instance.rlcomplete = new_completer
3232 if readline.__doc__ and 'libedit' in readline.__doc__:
3233 readline.parse_and_bind('bind ^I rl_complete')
3234 else:
3235 readline.parse_and_bind('tab: complete')
3236 # Require just one tab to send output.
3237 readline.parse_and_bind('set show-all-if-ambiguous on')
3238 print ('python.el: readline is available')
3239 except IOError:
3240 print ('python.el: readline not available')
3241 __PYTHON_EL_native_completion_setup()"
3242 process)
3243 (python-shell-accept-process-output process)
3244 (when (save-excursion
3245 (re-search-backward
3246 (regexp-quote "python.el: readline is available") nil t 1))
3247 (python-shell-completion-native-try))))
3248
3249 (defun python-shell-completion-native-turn-off (&optional msg)
3250 "Turn off shell native completions.
3251 With argument MSG show deactivation message."
3252 (interactive "p")
3253 (python-shell-with-shell-buffer
3254 (set (make-local-variable 'python-shell-completion-native-enable) nil)
3255 (when msg
3256 (message "Shell native completion is disabled, using fallback"))))
3257
3258 (defun python-shell-completion-native-turn-on (&optional msg)
3259 "Turn on shell native completions.
3260 With argument MSG show deactivation message."
3261 (interactive "p")
3262 (python-shell-with-shell-buffer
3263 (set (make-local-variable 'python-shell-completion-native-enable) t)
3264 (python-shell-completion-native-turn-on-maybe msg)))
3265
3266 (defun python-shell-completion-native-turn-on-maybe (&optional msg)
3267 "Turn on native completions if enabled and available.
3268 With argument MSG show activation/deactivation message."
3269 (interactive "p")
3270 (python-shell-with-shell-buffer
3271 (when python-shell-completion-native-enable
3272 (cond
3273 ((python-shell-completion-native-interpreter-disabled-p)
3274 (python-shell-completion-native-turn-off msg))
3275 ((python-shell-completion-native-setup)
3276 (when msg
3277 (message "Shell native completion is enabled.")))
3278 (t (lwarn
3279 '(python python-shell-completion-native-turn-on-maybe)
3280 :warning
3281 (concat
3282 "Your `python-shell-interpreter' doesn't seem to "
3283 "support readline, yet `python-shell-completion-native' "
3284 (format "was t and %S is not part of the "
3285 (file-name-nondirectory python-shell-interpreter))
3286 "`python-shell-completion-native-disabled-interpreters' "
3287 "list. Native completions have been disabled locally. "))
3288 (python-shell-completion-native-turn-off msg))))))
3289
3290 (defun python-shell-completion-native-turn-on-maybe-with-msg ()
3291 "Like `python-shell-completion-native-turn-on-maybe' but force messages."
3292 (python-shell-completion-native-turn-on-maybe t))
3293
3294 (add-hook 'inferior-python-mode-hook
3295 #'python-shell-completion-native-turn-on-maybe-with-msg)
3296
3297 (defun python-shell-completion-native-toggle (&optional msg)
3298 "Toggle shell native completion.
3299 With argument MSG show activation/deactivation message."
3300 (interactive "p")
3301 (python-shell-with-shell-buffer
3302 (if python-shell-completion-native-enable
3303 (python-shell-completion-native-turn-off msg)
3304 (python-shell-completion-native-turn-on msg))
3305 python-shell-completion-native-enable))
3306
3307 (defun python-shell-completion-native-get-completions (process import input)
3308 "Get completions using native readline for PROCESS.
3309 When IMPORT is non-nil takes precedence over INPUT for
3310 completion."
3311 (with-current-buffer (process-buffer process)
3312 (when (and python-shell-completion-native-enable
3313 (python-util-comint-last-prompt)
3314 (>= (point) (cdr (python-util-comint-last-prompt))))
3315 (let* ((input (or import input))
3316 (original-filter-fn (process-filter process))
3317 (redirect-buffer (get-buffer-create
3318 python-shell-completion-native-redirect-buffer))
3319 (separators (python-rx (or whitespace open-paren close-paren)))
3320 (trigger "\t")
3321 (new-input (concat input trigger))
3322 (input-length
3323 (save-excursion
3324 (+ (- (point-max) (comint-bol)) (length new-input))))
3325 (delete-line-command (make-string input-length ?\b))
3326 (input-to-send (concat new-input delete-line-command)))
3327 ;; Ensure restoring the process filter, even if the user quits
3328 ;; or there's some other error.
3329 (unwind-protect
3330 (with-current-buffer redirect-buffer
3331 ;; Cleanup the redirect buffer
3332 (delete-region (point-min) (point-max))
3333 ;; Mimic `comint-redirect-send-command', unfortunately it
3334 ;; can't be used here because it expects a newline in the
3335 ;; command and that's exactly what we are trying to avoid.
3336 (let ((comint-redirect-echo-input nil)
3337 (comint-redirect-verbose nil)
3338 (comint-redirect-perform-sanity-check nil)
3339 (comint-redirect-insert-matching-regexp nil)
3340 ;; Feed it some regex that will never match.
3341 (comint-redirect-finished-regexp "^\\'$")
3342 (comint-redirect-output-buffer redirect-buffer)
3343 (current-time (float-time)))
3344 ;; Compatibility with Emacs 24.x. Comint changed and
3345 ;; now `comint-redirect-filter' gets 3 args. This
3346 ;; checks which version of `comint-redirect-filter' is
3347 ;; in use based on its args and uses `apply-partially'
3348 ;; to make it up for the 3 args case.
3349 (if (= (length
3350 (help-function-arglist 'comint-redirect-filter)) 3)
3351 (set-process-filter
3352 process (apply-partially
3353 #'comint-redirect-filter original-filter-fn))
3354 (set-process-filter process #'comint-redirect-filter))
3355 (process-send-string process input-to-send)
3356 ;; Grab output until our dummy completion used as
3357 ;; output end marker is found. Output is accepted
3358 ;; *very* quickly to keep the shell super-responsive.
3359 (while (and (not (re-search-backward "~~~~__dummy_completion__" nil t))
3360 (< (- (float-time) current-time)
3361 python-shell-completion-native-output-timeout))
3362 (accept-process-output process 0.01))
3363 (cl-remove-duplicates
3364 (cl-remove-if
3365 (lambda (c)
3366 (string-match "__dummy_completion__" c))
3367 (split-string
3368 (buffer-substring-no-properties
3369 (point-min) (point-max))
3370 separators t))
3371 :test #'string=)))
3372 (set-process-filter process original-filter-fn))))))
3373
3374 (defun python-shell-completion-get-completions (process import input)
3375 "Do completion at point using PROCESS for IMPORT or INPUT.
3376 When IMPORT is non-nil takes precedence over INPUT for
3377 completion."
3378 (with-current-buffer (process-buffer process)
3379 (let* ((prompt
3380 (let ((prompt-boundaries (python-util-comint-last-prompt)))
3381 (buffer-substring-no-properties
3382 (car prompt-boundaries) (cdr prompt-boundaries))))
3383 (completion-code
3384 ;; Check whether a prompt matches a pdb string, an import
3385 ;; statement or just the standard prompt and use the
3386 ;; correct python-shell-completion-*-code string
3387 (cond ((and (string-match
3388 (concat "^" python-shell-prompt-pdb-regexp) prompt))
3389 ;; Since there are no guarantees the user will remain
3390 ;; in the same context where completion code was sent
3391 ;; (e.g. user steps into a function), safeguard
3392 ;; resending completion setup continuously.
3393 (concat python-shell-completion-setup-code
3394 "\nprint (" python-shell-completion-string-code ")"))
3395 ((string-match
3396 python-shell--prompt-calculated-input-regexp prompt)
3397 python-shell-completion-string-code)
3398 (t nil)))
3399 (subject (or import input)))
3400 (and completion-code
3401 (> (length input) 0)
3402 (let ((completions
3403 (python-util-strip-string
3404 (python-shell-send-string-no-output
3405 (format completion-code subject) process))))
3406 (and (> (length completions) 2)
3407 (split-string completions
3408 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
3409
3410 (defun python-shell-completion-at-point (&optional process)
3411 "Function for `completion-at-point-functions' in `inferior-python-mode'.
3412 Optional argument PROCESS forces completions to be retrieved
3413 using that one instead of current buffer's process."
3414 (setq process (or process (get-buffer-process (current-buffer))))
3415 (let* ((line-start (if (derived-mode-p 'inferior-python-mode)
3416 ;; Working on a shell buffer: use prompt end.
3417 (cdr (python-util-comint-last-prompt))
3418 (line-beginning-position)))
3419 (import-statement
3420 (when (string-match-p
3421 (rx (* space) word-start (or "from" "import") word-end space)
3422 (buffer-substring-no-properties line-start (point)))
3423 (buffer-substring-no-properties line-start (point))))
3424 (start
3425 (save-excursion
3426 (if (not (re-search-backward
3427 (python-rx
3428 (or whitespace open-paren close-paren string-delimiter))
3429 line-start
3430 t 1))
3431 line-start
3432 (forward-char (length (match-string-no-properties 0)))
3433 (point))))
3434 (end (point))
3435 (completion-fn
3436 (if python-shell-completion-native-enable
3437 #'python-shell-completion-native-get-completions
3438 #'python-shell-completion-get-completions)))
3439 (list start end
3440 (completion-table-dynamic
3441 (apply-partially
3442 completion-fn
3443 process import-statement)))))
3444
3445 (define-obsolete-function-alias
3446 'python-shell-completion-complete-at-point
3447 'python-shell-completion-at-point
3448 "25.1")
3449
3450 (defun python-shell-completion-complete-or-indent ()
3451 "Complete or indent depending on the context.
3452 If content before pointer is all whitespace, indent.
3453 If not try to complete."
3454 (interactive)
3455 (if (string-match "^[[:space:]]*$"
3456 (buffer-substring (comint-line-beginning-position)
3457 (point)))
3458 (indent-for-tab-command)
3459 (completion-at-point)))
3460
3461 \f
3462 ;;; PDB Track integration
3463
3464 (defcustom python-pdbtrack-activate t
3465 "Non-nil makes Python shell enable pdbtracking."
3466 :type 'boolean
3467 :group 'python
3468 :safe 'booleanp)
3469
3470 (defcustom python-pdbtrack-stacktrace-info-regexp
3471 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3472 "Regular expression matching stacktrace information.
3473 Used to extract the current line and module being inspected."
3474 :type 'string
3475 :group 'python
3476 :safe 'stringp)
3477
3478 (defvar python-pdbtrack-tracked-buffer nil
3479 "Variable containing the value of the current tracked buffer.
3480 Never set this variable directly, use
3481 `python-pdbtrack-set-tracked-buffer' instead.")
3482
3483 (defvar python-pdbtrack-buffers-to-kill nil
3484 "List of buffers to be deleted after tracking finishes.")
3485
3486 (defun python-pdbtrack-set-tracked-buffer (file-name)
3487 "Set the buffer for FILE-NAME as the tracked buffer.
3488 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3489 Returns the tracked buffer."
3490 (let ((file-buffer (get-file-buffer
3491 (concat (file-remote-p default-directory)
3492 file-name))))
3493 (if file-buffer
3494 (setq python-pdbtrack-tracked-buffer file-buffer)
3495 (setq file-buffer (find-file-noselect file-name))
3496 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3497 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3498 file-buffer))
3499
3500 (defun python-pdbtrack-comint-output-filter-function (output)
3501 "Move overlay arrow to current pdb line in tracked buffer.
3502 Argument OUTPUT is a string with the output from the comint process."
3503 (when (and python-pdbtrack-activate (not (string= output "")))
3504 (let* ((full-output (ansi-color-filter-apply
3505 (buffer-substring comint-last-input-end (point-max))))
3506 (line-number)
3507 (file-name
3508 (with-temp-buffer
3509 (insert full-output)
3510 ;; When the debugger encounters a pdb.set_trace()
3511 ;; command, it prints a single stack frame. Sometimes
3512 ;; it prints a bit of extra information about the
3513 ;; arguments of the present function. When ipdb
3514 ;; encounters an exception, it prints the _entire_ stack
3515 ;; trace. To handle all of these cases, we want to find
3516 ;; the _last_ stack frame printed in the most recent
3517 ;; batch of output, then jump to the corresponding
3518 ;; file/line number.
3519 (goto-char (point-max))
3520 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3521 (setq line-number (string-to-number
3522 (match-string-no-properties 2)))
3523 (match-string-no-properties 1)))))
3524 (if (and file-name line-number)
3525 (let* ((tracked-buffer
3526 (python-pdbtrack-set-tracked-buffer file-name))
3527 (shell-buffer (current-buffer))
3528 (tracked-buffer-window (get-buffer-window tracked-buffer))
3529 (tracked-buffer-line-pos))
3530 (with-current-buffer tracked-buffer
3531 (set (make-local-variable 'overlay-arrow-string) "=>")
3532 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3533 (setq tracked-buffer-line-pos (progn
3534 (goto-char (point-min))
3535 (forward-line (1- line-number))
3536 (point-marker)))
3537 (when tracked-buffer-window
3538 (set-window-point
3539 tracked-buffer-window tracked-buffer-line-pos))
3540 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3541 (pop-to-buffer tracked-buffer)
3542 (switch-to-buffer-other-window shell-buffer))
3543 (when python-pdbtrack-tracked-buffer
3544 (with-current-buffer python-pdbtrack-tracked-buffer
3545 (set-marker overlay-arrow-position nil))
3546 (mapc #'(lambda (buffer)
3547 (ignore-errors (kill-buffer buffer)))
3548 python-pdbtrack-buffers-to-kill)
3549 (setq python-pdbtrack-tracked-buffer nil
3550 python-pdbtrack-buffers-to-kill nil)))))
3551 output)
3552
3553 \f
3554 ;;; Symbol completion
3555
3556 (defun python-completion-at-point ()
3557 "Function for `completion-at-point-functions' in `python-mode'.
3558 For this to work as best as possible you should call
3559 `python-shell-send-buffer' from time to time so context in
3560 inferior Python process is updated properly."
3561 (let ((process (python-shell-get-process)))
3562 (when process
3563 (python-shell-completion-at-point process))))
3564
3565 (define-obsolete-function-alias
3566 'python-completion-complete-at-point
3567 'python-completion-at-point
3568 "25.1")
3569
3570 \f
3571 ;;; Fill paragraph
3572
3573 (defcustom python-fill-comment-function 'python-fill-comment
3574 "Function to fill comments.
3575 This is the function used by `python-fill-paragraph' to
3576 fill comments."
3577 :type 'symbol
3578 :group 'python)
3579
3580 (defcustom python-fill-string-function 'python-fill-string
3581 "Function to fill strings.
3582 This is the function used by `python-fill-paragraph' to
3583 fill strings."
3584 :type 'symbol
3585 :group 'python)
3586
3587 (defcustom python-fill-decorator-function 'python-fill-decorator
3588 "Function to fill decorators.
3589 This is the function used by `python-fill-paragraph' to
3590 fill decorators."
3591 :type 'symbol
3592 :group 'python)
3593
3594 (defcustom python-fill-paren-function 'python-fill-paren
3595 "Function to fill parens.
3596 This is the function used by `python-fill-paragraph' to
3597 fill parens."
3598 :type 'symbol
3599 :group 'python)
3600
3601 (defcustom python-fill-docstring-style 'pep-257
3602 "Style used to fill docstrings.
3603 This affects `python-fill-string' behavior with regards to
3604 triple quotes positioning.
3605
3606 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3607 `symmetric', and nil. A value of nil won't care about quotes
3608 position and will treat docstrings a normal string, any other
3609 value may result in one of the following docstring styles:
3610
3611 `django':
3612
3613 \"\"\"
3614 Process foo, return bar.
3615 \"\"\"
3616
3617 \"\"\"
3618 Process foo, return bar.
3619
3620 If processing fails throw ProcessingError.
3621 \"\"\"
3622
3623 `onetwo':
3624
3625 \"\"\"Process foo, return bar.\"\"\"
3626
3627 \"\"\"
3628 Process foo, return bar.
3629
3630 If processing fails throw ProcessingError.
3631
3632 \"\"\"
3633
3634 `pep-257':
3635
3636 \"\"\"Process foo, return bar.\"\"\"
3637
3638 \"\"\"Process foo, return bar.
3639
3640 If processing fails throw ProcessingError.
3641
3642 \"\"\"
3643
3644 `pep-257-nn':
3645
3646 \"\"\"Process foo, return bar.\"\"\"
3647
3648 \"\"\"Process foo, return bar.
3649
3650 If processing fails throw ProcessingError.
3651 \"\"\"
3652
3653 `symmetric':
3654
3655 \"\"\"Process foo, return bar.\"\"\"
3656
3657 \"\"\"
3658 Process foo, return bar.
3659
3660 If processing fails throw ProcessingError.
3661 \"\"\""
3662 :type '(choice
3663 (const :tag "Don't format docstrings" nil)
3664 (const :tag "Django's coding standards style." django)
3665 (const :tag "One newline and start and Two at end style." onetwo)
3666 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3667 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3668 (const :tag "Symmetric style." symmetric))
3669 :group 'python
3670 :safe (lambda (val)
3671 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3672
3673 (defun python-fill-paragraph (&optional justify)
3674 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3675 If any of the current line is in or at the end of a multi-line string,
3676 fill the string or the paragraph of it that point is in, preserving
3677 the string's indentation.
3678 Optional argument JUSTIFY defines if the paragraph should be justified."
3679 (interactive "P")
3680 (save-excursion
3681 (cond
3682 ;; Comments
3683 ((python-syntax-context 'comment)
3684 (funcall python-fill-comment-function justify))
3685 ;; Strings/Docstrings
3686 ((save-excursion (or (python-syntax-context 'string)
3687 (equal (string-to-syntax "|")
3688 (syntax-after (point)))))
3689 (funcall python-fill-string-function justify))
3690 ;; Decorators
3691 ((equal (char-after (save-excursion
3692 (python-nav-beginning-of-statement))) ?@)
3693 (funcall python-fill-decorator-function justify))
3694 ;; Parens
3695 ((or (python-syntax-context 'paren)
3696 (looking-at (python-rx open-paren))
3697 (save-excursion
3698 (skip-syntax-forward "^(" (line-end-position))
3699 (looking-at (python-rx open-paren))))
3700 (funcall python-fill-paren-function justify))
3701 (t t))))
3702
3703 (defun python-fill-comment (&optional justify)
3704 "Comment fill function for `python-fill-paragraph'.
3705 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3706 (fill-comment-paragraph justify))
3707
3708 (defun python-fill-string (&optional justify)
3709 "String fill function for `python-fill-paragraph'.
3710 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3711 (let* ((str-start-pos
3712 (set-marker
3713 (make-marker)
3714 (or (python-syntax-context 'string)
3715 (and (equal (string-to-syntax "|")
3716 (syntax-after (point)))
3717 (point)))))
3718 (num-quotes (python-syntax-count-quotes
3719 (char-after str-start-pos) str-start-pos))
3720 (str-end-pos
3721 (save-excursion
3722 (goto-char (+ str-start-pos num-quotes))
3723 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3724 (goto-char (point-max)))
3725 (point-marker)))
3726 (multi-line-p
3727 ;; Docstring styles may vary for oneliners and multi-liners.
3728 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3729 (delimiters-style
3730 (pcase python-fill-docstring-style
3731 ;; delimiters-style is a cons cell with the form
3732 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3733 ;; is NIL means to not add any newlines for start or end
3734 ;; of docstring. See `python-fill-docstring-style' for a
3735 ;; graphic idea of each style.
3736 (`django (cons 1 1))
3737 (`onetwo (and multi-line-p (cons 1 2)))
3738 (`pep-257 (and multi-line-p (cons nil 2)))
3739 (`pep-257-nn (and multi-line-p (cons nil 1)))
3740 (`symmetric (and multi-line-p (cons 1 1)))))
3741 (fill-paragraph-function))
3742 (save-restriction
3743 (narrow-to-region str-start-pos str-end-pos)
3744 (fill-paragraph justify))
3745 (save-excursion
3746 (when (and (python-info-docstring-p) python-fill-docstring-style)
3747 ;; Add the number of newlines indicated by the selected style
3748 ;; at the start of the docstring.
3749 (goto-char (+ str-start-pos num-quotes))
3750 (delete-region (point) (progn
3751 (skip-syntax-forward "> ")
3752 (point)))
3753 (and (car delimiters-style)
3754 (or (newline (car delimiters-style)) t)
3755 ;; Indent only if a newline is added.
3756 (indent-according-to-mode))
3757 ;; Add the number of newlines indicated by the selected style
3758 ;; at the end of the docstring.
3759 (goto-char (if (not (= str-end-pos (point-max)))
3760 (- str-end-pos num-quotes)
3761 str-end-pos))
3762 (delete-region (point) (progn
3763 (skip-syntax-backward "> ")
3764 (point)))
3765 (and (cdr delimiters-style)
3766 ;; Add newlines only if string ends.
3767 (not (= str-end-pos (point-max)))
3768 (or (newline (cdr delimiters-style)) t)
3769 ;; Again indent only if a newline is added.
3770 (indent-according-to-mode))))) t)
3771
3772 (defun python-fill-decorator (&optional _justify)
3773 "Decorator fill function for `python-fill-paragraph'.
3774 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3775 t)
3776
3777 (defun python-fill-paren (&optional justify)
3778 "Paren fill function for `python-fill-paragraph'.
3779 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3780 (save-restriction
3781 (narrow-to-region (progn
3782 (while (python-syntax-context 'paren)
3783 (goto-char (1- (point))))
3784 (line-beginning-position))
3785 (progn
3786 (when (not (python-syntax-context 'paren))
3787 (end-of-line)
3788 (when (not (python-syntax-context 'paren))
3789 (skip-syntax-backward "^)")))
3790 (while (and (python-syntax-context 'paren)
3791 (not (eobp)))
3792 (goto-char (1+ (point))))
3793 (point)))
3794 (let ((paragraph-start "\f\\|[ \t]*$")
3795 (paragraph-separate ",")
3796 (fill-paragraph-function))
3797 (goto-char (point-min))
3798 (fill-paragraph justify))
3799 (while (not (eobp))
3800 (forward-line 1)
3801 (python-indent-line)
3802 (goto-char (line-end-position))))
3803 t)
3804
3805 \f
3806 ;;; Skeletons
3807
3808 (defcustom python-skeleton-autoinsert nil
3809 "Non-nil means template skeletons will be automagically inserted.
3810 This happens when pressing \"if<SPACE>\", for example, to prompt for
3811 the if condition."
3812 :type 'boolean
3813 :group 'python
3814 :safe 'booleanp)
3815
3816 (define-obsolete-variable-alias
3817 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3818
3819 (defvar python-skeleton-available '()
3820 "Internal list of available skeletons.")
3821
3822 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3823 "Abbrev table for Python mode skeletons."
3824 :case-fixed t
3825 ;; Allow / inside abbrevs.
3826 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3827 ;; Only expand in code.
3828 :enable-function (lambda ()
3829 (and
3830 (not (python-syntax-comment-or-string-p))
3831 python-skeleton-autoinsert)))
3832
3833 (defmacro python-skeleton-define (name doc &rest skel)
3834 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3835 The skeleton will be bound to python-skeleton-NAME and will
3836 be added to `python-mode-skeleton-abbrev-table'."
3837 (declare (indent 2))
3838 (let* ((name (symbol-name name))
3839 (function-name (intern (concat "python-skeleton-" name))))
3840 `(progn
3841 (define-abbrev python-mode-skeleton-abbrev-table
3842 ,name "" ',function-name :system t)
3843 (setq python-skeleton-available
3844 (cons ',function-name python-skeleton-available))
3845 (define-skeleton ,function-name
3846 ,(or doc
3847 (format "Insert %s statement." name))
3848 ,@skel))))
3849
3850 (define-abbrev-table 'python-mode-abbrev-table ()
3851 "Abbrev table for Python mode."
3852 :parents (list python-mode-skeleton-abbrev-table))
3853
3854 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3855 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3856 The skeleton will be bound to python-skeleton-NAME."
3857 (declare (indent 2))
3858 (let* ((name (symbol-name name))
3859 (function-name (intern (concat "python-skeleton--" name)))
3860 (msg (format
3861 "Add '%s' clause? " name)))
3862 (when (not skel)
3863 (setq skel
3864 `(< ,(format "%s:" name) \n \n
3865 > _ \n)))
3866 `(define-skeleton ,function-name
3867 ,(or doc
3868 (format "Auxiliary skeleton for %s statement." name))
3869 nil
3870 (unless (y-or-n-p ,msg)
3871 (signal 'quit t))
3872 ,@skel)))
3873
3874 (python-define-auxiliary-skeleton else nil)
3875
3876 (python-define-auxiliary-skeleton except nil)
3877
3878 (python-define-auxiliary-skeleton finally nil)
3879
3880 (python-skeleton-define if nil
3881 "Condition: "
3882 "if " str ":" \n
3883 _ \n
3884 ("other condition, %s: "
3885 <
3886 "elif " str ":" \n
3887 > _ \n nil)
3888 '(python-skeleton--else) | ^)
3889
3890 (python-skeleton-define while nil
3891 "Condition: "
3892 "while " str ":" \n
3893 > _ \n
3894 '(python-skeleton--else) | ^)
3895
3896 (python-skeleton-define for nil
3897 "Iteration spec: "
3898 "for " str ":" \n
3899 > _ \n
3900 '(python-skeleton--else) | ^)
3901
3902 (python-skeleton-define import nil
3903 "Import from module: "
3904 "from " str & " " | -5
3905 "import "
3906 ("Identifier: " str ", ") -2 \n _)
3907
3908 (python-skeleton-define try nil
3909 nil
3910 "try:" \n
3911 > _ \n
3912 ("Exception, %s: "
3913 <
3914 "except " str ":" \n
3915 > _ \n nil)
3916 resume:
3917 '(python-skeleton--except)
3918 '(python-skeleton--else)
3919 '(python-skeleton--finally) | ^)
3920
3921 (python-skeleton-define def nil
3922 "Function name: "
3923 "def " str "(" ("Parameter, %s: "
3924 (unless (equal ?\( (char-before)) ", ")
3925 str) "):" \n
3926 "\"\"\"" - "\"\"\"" \n
3927 > _ \n)
3928
3929 (python-skeleton-define class nil
3930 "Class name: "
3931 "class " str "(" ("Inheritance, %s: "
3932 (unless (equal ?\( (char-before)) ", ")
3933 str)
3934 & ")" | -1
3935 ":" \n
3936 "\"\"\"" - "\"\"\"" \n
3937 > _ \n)
3938
3939 (defun python-skeleton-add-menu-items ()
3940 "Add menu items to Python->Skeletons menu."
3941 (let ((skeletons (sort python-skeleton-available 'string<)))
3942 (dolist (skeleton skeletons)
3943 (easy-menu-add-item
3944 nil '("Python" "Skeletons")
3945 `[,(format
3946 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3947 ,skeleton t]))))
3948 \f
3949 ;;; FFAP
3950
3951 (defcustom python-ffap-setup-code
3952 "def __FFAP_get_module_path(module):
3953 try:
3954 import os
3955 path = __import__(module).__file__
3956 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3957 path = path[:-1]
3958 return path
3959 except:
3960 return ''"
3961 "Python code to get a module path."
3962 :type 'string
3963 :group 'python)
3964
3965 (defcustom python-ffap-string-code
3966 "__FFAP_get_module_path('''%s''')\n"
3967 "Python code used to get a string with the path of a module."
3968 :type 'string
3969 :group 'python)
3970
3971 (defun python-ffap-module-path (module)
3972 "Function for `ffap-alist' to return path for MODULE."
3973 (let ((process (or
3974 (and (derived-mode-p 'inferior-python-mode)
3975 (get-buffer-process (current-buffer)))
3976 (python-shell-get-process))))
3977 (if (not process)
3978 nil
3979 (let ((module-file
3980 (python-shell-send-string-no-output
3981 (format python-ffap-string-code module) process)))
3982 (when module-file
3983 (substring-no-properties module-file 1 -1))))))
3984
3985 (defvar ffap-alist)
3986
3987 (eval-after-load "ffap"
3988 '(progn
3989 (push '(python-mode . python-ffap-module-path) ffap-alist)
3990 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3991
3992 \f
3993 ;;; Code check
3994
3995 (defcustom python-check-command
3996 (or (executable-find "pyflakes")
3997 (executable-find "epylint")
3998 "install pyflakes, pylint or something else")
3999 "Command used to check a Python file."
4000 :type 'string
4001 :group 'python)
4002
4003 (defcustom python-check-buffer-name
4004 "*Python check: %s*"
4005 "Buffer name used for check commands."
4006 :type 'string
4007 :group 'python)
4008
4009 (defvar python-check-custom-command nil
4010 "Internal use.")
4011 ;; XXX: Avoid `defvar-local' for compat with Emacs<24.3
4012 (make-variable-buffer-local 'python-check-custom-command)
4013
4014 (defun python-check (command)
4015 "Check a Python file (default current buffer's file).
4016 Runs COMMAND, a shell command, as if by `compile'.
4017 See `python-check-command' for the default."
4018 (interactive
4019 (list (read-string "Check command: "
4020 (or python-check-custom-command
4021 (concat python-check-command " "
4022 (shell-quote-argument
4023 (or
4024 (let ((name (buffer-file-name)))
4025 (and name
4026 (file-name-nondirectory name)))
4027 "")))))))
4028 (setq python-check-custom-command command)
4029 (save-some-buffers (not compilation-ask-about-save) nil)
4030 (python-shell-with-environment
4031 (compilation-start command nil
4032 (lambda (_modename)
4033 (format python-check-buffer-name command)))))
4034
4035 \f
4036 ;;; Eldoc
4037
4038 (defcustom python-eldoc-setup-code
4039 "def __PYDOC_get_help(obj):
4040 try:
4041 import inspect
4042 try:
4043 str_type = basestring
4044 except NameError:
4045 str_type = str
4046 if isinstance(obj, str_type):
4047 obj = eval(obj, globals())
4048 doc = inspect.getdoc(obj)
4049 if not doc and callable(obj):
4050 target = None
4051 if inspect.isclass(obj) and hasattr(obj, '__init__'):
4052 target = obj.__init__
4053 objtype = 'class'
4054 else:
4055 target = obj
4056 objtype = 'def'
4057 if target:
4058 args = inspect.formatargspec(
4059 *inspect.getargspec(target)
4060 )
4061 name = obj.__name__
4062 doc = '{objtype} {name}{args}'.format(
4063 objtype=objtype, name=name, args=args
4064 )
4065 else:
4066 doc = doc.splitlines()[0]
4067 except:
4068 doc = ''
4069 print (doc)"
4070 "Python code to setup documentation retrieval."
4071 :type 'string
4072 :group 'python)
4073
4074 (defcustom python-eldoc-string-code
4075 "__PYDOC_get_help('''%s''')\n"
4076 "Python code used to get a string with the documentation of an object."
4077 :type 'string
4078 :group 'python)
4079
4080 (defun python-eldoc--get-symbol-at-point ()
4081 "Get the current symbol for eldoc.
4082 Returns the current symbol handling point within arguments."
4083 (save-excursion
4084 (let ((start (python-syntax-context 'paren)))
4085 (when start
4086 (goto-char start))
4087 (when (or start
4088 (eobp)
4089 (memq (char-syntax (char-after)) '(?\ ?-)))
4090 ;; Try to adjust to closest symbol if not in one.
4091 (python-util-forward-comment -1)))
4092 (python-info-current-symbol t)))
4093
4094 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
4095 "Internal implementation to get documentation at point.
4096 If not FORCE-INPUT is passed then what `python-eldoc--get-symbol-at-point'
4097 returns will be used. If not FORCE-PROCESS is passed what
4098 `python-shell-get-process' returns is used."
4099 (let ((process (or force-process (python-shell-get-process))))
4100 (when process
4101 (let ((input (or force-input
4102 (python-eldoc--get-symbol-at-point))))
4103 (and input
4104 ;; Prevent resizing the echo area when iPython is
4105 ;; enabled. Bug#18794.
4106 (python-util-strip-string
4107 (python-shell-send-string-no-output
4108 (format python-eldoc-string-code input)
4109 process)))))))
4110
4111 (defun python-eldoc-function ()
4112 "`eldoc-documentation-function' for Python.
4113 For this to work as best as possible you should call
4114 `python-shell-send-buffer' from time to time so context in
4115 inferior Python process is updated properly."
4116 (python-eldoc--get-doc-at-point))
4117
4118 (defun python-eldoc-at-point (symbol)
4119 "Get help on SYMBOL using `help'.
4120 Interactively, prompt for symbol."
4121 (interactive
4122 (let ((symbol (python-eldoc--get-symbol-at-point))
4123 (enable-recursive-minibuffers t))
4124 (list (read-string (if symbol
4125 (format "Describe symbol (default %s): " symbol)
4126 "Describe symbol: ")
4127 nil nil symbol))))
4128 (message (python-eldoc--get-doc-at-point symbol)))
4129
4130 \f
4131 ;;; Hideshow
4132
4133 (defun python-hideshow-forward-sexp-function (arg)
4134 "Python specific `forward-sexp' function for `hs-minor-mode'.
4135 Argument ARG is ignored."
4136 arg ; Shut up, byte compiler.
4137 (python-nav-end-of-defun)
4138 (unless (python-info-current-line-empty-p)
4139 (backward-char)))
4140
4141 \f
4142 ;;; Imenu
4143
4144 (defvar python-imenu-format-item-label-function
4145 'python-imenu-format-item-label
4146 "Imenu function used to format an item label.
4147 It must be a function with two arguments: TYPE and NAME.")
4148
4149 (defvar python-imenu-format-parent-item-label-function
4150 'python-imenu-format-parent-item-label
4151 "Imenu function used to format a parent item label.
4152 It must be a function with two arguments: TYPE and NAME.")
4153
4154 (defvar python-imenu-format-parent-item-jump-label-function
4155 'python-imenu-format-parent-item-jump-label
4156 "Imenu function used to format a parent jump item label.
4157 It must be a function with two arguments: TYPE and NAME.")
4158
4159 (defun python-imenu-format-item-label (type name)
4160 "Return Imenu label for single node using TYPE and NAME."
4161 (format "%s (%s)" name type))
4162
4163 (defun python-imenu-format-parent-item-label (type name)
4164 "Return Imenu label for parent node using TYPE and NAME."
4165 (format "%s..." (python-imenu-format-item-label type name)))
4166
4167 (defun python-imenu-format-parent-item-jump-label (type _name)
4168 "Return Imenu label for parent node jump using TYPE and NAME."
4169 (if (string= type "class")
4170 "*class definition*"
4171 "*function definition*"))
4172
4173 (defun python-imenu--put-parent (type name pos tree)
4174 "Add the parent with TYPE, NAME and POS to TREE."
4175 (let ((label
4176 (funcall python-imenu-format-item-label-function type name))
4177 (jump-label
4178 (funcall python-imenu-format-parent-item-jump-label-function type name)))
4179 (if (not tree)
4180 (cons label pos)
4181 (cons label (cons (cons jump-label pos) tree)))))
4182
4183 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
4184 "Recursively build the tree of nested definitions of a node.
4185 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
4186 not be passed explicitly unless you know what you are doing."
4187 (setq min-indent (or min-indent 0)
4188 prev-indent (or prev-indent python-indent-offset))
4189 (let* ((pos (python-nav-backward-defun))
4190 (type)
4191 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
4192 (let ((split (split-string (match-string-no-properties 0))))
4193 (setq type (car split))
4194 (cadr split))))
4195 (label (when name
4196 (funcall python-imenu-format-item-label-function type name)))
4197 (indent (current-indentation))
4198 (children-indent-limit (+ python-indent-offset min-indent)))
4199 (cond ((not pos)
4200 ;; Nothing found, probably near to bobp.
4201 nil)
4202 ((<= indent min-indent)
4203 ;; The current indentation points that this is a parent
4204 ;; node, add it to the tree and stop recursing.
4205 (python-imenu--put-parent type name pos tree))
4206 (t
4207 (python-imenu--build-tree
4208 min-indent
4209 indent
4210 (if (<= indent children-indent-limit)
4211 ;; This lies within the children indent offset range,
4212 ;; so it's a normal child of its parent (i.e., not
4213 ;; a child of a child).
4214 (cons (cons label pos) tree)
4215 ;; Oh no, a child of a child?! Fear not, we
4216 ;; know how to roll. We recursively parse these by
4217 ;; swapping prev-indent and min-indent plus adding this
4218 ;; newly found item to a fresh subtree. This works, I
4219 ;; promise.
4220 (cons
4221 (python-imenu--build-tree
4222 prev-indent indent (list (cons label pos)))
4223 tree)))))))
4224
4225 (defun python-imenu-create-index ()
4226 "Return tree Imenu alist for the current Python buffer.
4227 Change `python-imenu-format-item-label-function',
4228 `python-imenu-format-parent-item-label-function',
4229 `python-imenu-format-parent-item-jump-label-function' to
4230 customize how labels are formatted."
4231 (goto-char (point-max))
4232 (let ((index)
4233 (tree))
4234 (while (setq tree (python-imenu--build-tree))
4235 (setq index (cons tree index)))
4236 index))
4237
4238 (defun python-imenu-create-flat-index (&optional alist prefix)
4239 "Return flat outline of the current Python buffer for Imenu.
4240 Optional argument ALIST is the tree to be flattened; when nil
4241 `python-imenu-build-index' is used with
4242 `python-imenu-format-parent-item-jump-label-function'
4243 `python-imenu-format-parent-item-label-function'
4244 `python-imenu-format-item-label-function' set to
4245 (lambda (type name) name)
4246 Optional argument PREFIX is used in recursive calls and should
4247 not be passed explicitly.
4248
4249 Converts this:
4250
4251 ((\"Foo\" . 103)
4252 (\"Bar\" . 138)
4253 (\"decorator\"
4254 (\"decorator\" . 173)
4255 (\"wrap\"
4256 (\"wrap\" . 353)
4257 (\"wrapped_f\" . 393))))
4258
4259 To this:
4260
4261 ((\"Foo\" . 103)
4262 (\"Bar\" . 138)
4263 (\"decorator\" . 173)
4264 (\"decorator.wrap\" . 353)
4265 (\"decorator.wrapped_f\" . 393))"
4266 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
4267 (apply
4268 'nconc
4269 (mapcar
4270 (lambda (item)
4271 (let ((name (if prefix
4272 (concat prefix "." (car item))
4273 (car item)))
4274 (pos (cdr item)))
4275 (cond ((or (numberp pos) (markerp pos))
4276 (list (cons name pos)))
4277 ((listp pos)
4278 (cons
4279 (cons name (cdar pos))
4280 (python-imenu-create-flat-index (cddr item) name))))))
4281 (or alist
4282 (let* ((fn (lambda (_type name) name))
4283 (python-imenu-format-item-label-function fn)
4284 (python-imenu-format-parent-item-label-function fn)
4285 (python-imenu-format-parent-item-jump-label-function fn))
4286 (python-imenu-create-index))))))
4287
4288 \f
4289 ;;; Misc helpers
4290
4291 (defun python-info-current-defun (&optional include-type)
4292 "Return name of surrounding function with Python compatible dotty syntax.
4293 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
4294 This function can be used as the value of `add-log-current-defun-function'
4295 since it returns nil if point is not inside a defun."
4296 (save-restriction
4297 (prog-widen)
4298 (save-excursion
4299 (end-of-line 1)
4300 (let ((names)
4301 (starting-indentation (current-indentation))
4302 (starting-pos (point))
4303 (first-run t)
4304 (last-indent)
4305 (type))
4306 (catch 'exit
4307 (while (python-nav-beginning-of-defun 1)
4308 (when (save-match-data
4309 (and
4310 (or (not last-indent)
4311 (< (current-indentation) last-indent))
4312 (or
4313 (and first-run
4314 (save-excursion
4315 ;; If this is the first run, we may add
4316 ;; the current defun at point.
4317 (setq first-run nil)
4318 (goto-char starting-pos)
4319 (python-nav-beginning-of-statement)
4320 (beginning-of-line 1)
4321 (looking-at-p
4322 python-nav-beginning-of-defun-regexp)))
4323 (< starting-pos
4324 (save-excursion
4325 (let ((min-indent
4326 (+ (current-indentation)
4327 python-indent-offset)))
4328 (if (< starting-indentation min-indent)
4329 ;; If the starting indentation is not
4330 ;; within the min defun indent make the
4331 ;; check fail.
4332 starting-pos
4333 ;; Else go to the end of defun and add
4334 ;; up the current indentation to the
4335 ;; ending position.
4336 (python-nav-end-of-defun)
4337 (+ (point)
4338 (if (>= (current-indentation) min-indent)
4339 (1+ (current-indentation))
4340 0)))))))))
4341 (save-match-data (setq last-indent (current-indentation)))
4342 (if (or (not include-type) type)
4343 (setq names (cons (match-string-no-properties 1) names))
4344 (let ((match (split-string (match-string-no-properties 0))))
4345 (setq type (car match))
4346 (setq names (cons (cadr match) names)))))
4347 ;; Stop searching ASAP.
4348 (and (= (current-indentation) 0) (throw 'exit t))))
4349 (and names
4350 (concat (and type (format "%s " type))
4351 (mapconcat 'identity names ".")))))))
4352
4353 (defun python-info-current-symbol (&optional replace-self)
4354 "Return current symbol using dotty syntax.
4355 With optional argument REPLACE-SELF convert \"self\" to current
4356 parent defun name."
4357 (let ((name
4358 (and (not (python-syntax-comment-or-string-p))
4359 (with-syntax-table python-dotty-syntax-table
4360 (let ((sym (symbol-at-point)))
4361 (and sym
4362 (substring-no-properties (symbol-name sym))))))))
4363 (when name
4364 (if (not replace-self)
4365 name
4366 (let ((current-defun (python-info-current-defun)))
4367 (if (not current-defun)
4368 name
4369 (replace-regexp-in-string
4370 (python-rx line-start word-start "self" word-end ?.)
4371 (concat
4372 (mapconcat 'identity
4373 (butlast (split-string current-defun "\\."))
4374 ".") ".")
4375 name)))))))
4376
4377 (defun python-info-statement-starts-block-p ()
4378 "Return non-nil if current statement opens a block."
4379 (save-excursion
4380 (python-nav-beginning-of-statement)
4381 (looking-at (python-rx block-start))))
4382
4383 (defun python-info-statement-ends-block-p ()
4384 "Return non-nil if point is at end of block."
4385 (let ((end-of-block-pos (save-excursion
4386 (python-nav-end-of-block)))
4387 (end-of-statement-pos (save-excursion
4388 (python-nav-end-of-statement))))
4389 (and end-of-block-pos end-of-statement-pos
4390 (= end-of-block-pos end-of-statement-pos))))
4391
4392 (defun python-info-beginning-of-statement-p ()
4393 "Return non-nil if point is at beginning of statement."
4394 (= (point) (save-excursion
4395 (python-nav-beginning-of-statement)
4396 (point))))
4397
4398 (defun python-info-end-of-statement-p ()
4399 "Return non-nil if point is at end of statement."
4400 (= (point) (save-excursion
4401 (python-nav-end-of-statement)
4402 (point))))
4403
4404 (defun python-info-beginning-of-block-p ()
4405 "Return non-nil if point is at beginning of block."
4406 (and (python-info-beginning-of-statement-p)
4407 (python-info-statement-starts-block-p)))
4408
4409 (defun python-info-end-of-block-p ()
4410 "Return non-nil if point is at end of block."
4411 (and (python-info-end-of-statement-p)
4412 (python-info-statement-ends-block-p)))
4413
4414 (define-obsolete-function-alias
4415 'python-info-closing-block
4416 'python-info-dedenter-opening-block-position "24.4")
4417
4418 (defun python-info-dedenter-opening-block-position ()
4419 "Return the point of the closest block the current line closes.
4420 Returns nil if point is not on a dedenter statement or no opening
4421 block can be detected. The latter case meaning current file is
4422 likely an invalid python file."
4423 (let ((positions (python-info-dedenter-opening-block-positions))
4424 (indentation (current-indentation))
4425 (position))
4426 (while (and (not position)
4427 positions)
4428 (save-excursion
4429 (goto-char (car positions))
4430 (if (<= (current-indentation) indentation)
4431 (setq position (car positions))
4432 (setq positions (cdr positions)))))
4433 position))
4434
4435 (defun python-info-dedenter-opening-block-positions ()
4436 "Return points of blocks the current line may close sorted by closer.
4437 Returns nil if point is not on a dedenter statement or no opening
4438 block can be detected. The latter case meaning current file is
4439 likely an invalid python file."
4440 (save-excursion
4441 (let ((dedenter-pos (python-info-dedenter-statement-p)))
4442 (when dedenter-pos
4443 (goto-char dedenter-pos)
4444 (let* ((pairs '(("elif" "elif" "if")
4445 ("else" "if" "elif" "except" "for" "while")
4446 ("except" "except" "try")
4447 ("finally" "else" "except" "try")))
4448 (dedenter (match-string-no-properties 0))
4449 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
4450 (collected-indentations)
4451 (opening-blocks))
4452 (catch 'exit
4453 (while (python-nav--syntactically
4454 (lambda ()
4455 (re-search-backward (python-rx block-start) nil t))
4456 #'<)
4457 (let ((indentation (current-indentation)))
4458 (when (and (not (memq indentation collected-indentations))
4459 (or (not collected-indentations)
4460 (< indentation (apply #'min collected-indentations))))
4461 (setq collected-indentations
4462 (cons indentation collected-indentations))
4463 (when (member (match-string-no-properties 0)
4464 possible-opening-blocks)
4465 (setq opening-blocks (cons (point) opening-blocks))))
4466 (when (zerop indentation)
4467 (throw 'exit nil)))))
4468 ;; sort by closer
4469 (nreverse opening-blocks))))))
4470
4471 (define-obsolete-function-alias
4472 'python-info-closing-block-message
4473 'python-info-dedenter-opening-block-message "24.4")
4474
4475 (defun python-info-dedenter-opening-block-message ()
4476 "Message the first line of the block the current statement closes."
4477 (let ((point (python-info-dedenter-opening-block-position)))
4478 (when point
4479 (save-restriction
4480 (prog-widen)
4481 (message "Closes %s" (save-excursion
4482 (goto-char point)
4483 (buffer-substring
4484 (point) (line-end-position))))))))
4485
4486 (defun python-info-dedenter-statement-p ()
4487 "Return point if current statement is a dedenter.
4488 Sets `match-data' to the keyword that starts the dedenter
4489 statement."
4490 (save-excursion
4491 (python-nav-beginning-of-statement)
4492 (when (and (not (python-syntax-context-type))
4493 (looking-at (python-rx dedenter)))
4494 (point))))
4495
4496 (defun python-info-line-ends-backslash-p (&optional line-number)
4497 "Return non-nil if current line ends with backslash.
4498 With optional argument LINE-NUMBER, check that line instead."
4499 (save-excursion
4500 (save-restriction
4501 (prog-widen)
4502 (when line-number
4503 (python-util-goto-line line-number))
4504 (while (and (not (eobp))
4505 (goto-char (line-end-position))
4506 (python-syntax-context 'paren)
4507 (not (equal (char-before (point)) ?\\)))
4508 (forward-line 1))
4509 (when (equal (char-before) ?\\)
4510 (point-marker)))))
4511
4512 (defun python-info-beginning-of-backslash (&optional line-number)
4513 "Return the point where the backslashed line start.
4514 Optional argument LINE-NUMBER forces the line number to check against."
4515 (save-excursion
4516 (save-restriction
4517 (prog-widen)
4518 (when line-number
4519 (python-util-goto-line line-number))
4520 (when (python-info-line-ends-backslash-p)
4521 (while (save-excursion
4522 (goto-char (line-beginning-position))
4523 (python-syntax-context 'paren))
4524 (forward-line -1))
4525 (back-to-indentation)
4526 (point-marker)))))
4527
4528 (defun python-info-continuation-line-p ()
4529 "Check if current line is continuation of another.
4530 When current line is continuation of another return the point
4531 where the continued line ends."
4532 (save-excursion
4533 (save-restriction
4534 (prog-widen)
4535 (let* ((context-type (progn
4536 (back-to-indentation)
4537 (python-syntax-context-type)))
4538 (line-start (line-number-at-pos))
4539 (context-start (when context-type
4540 (python-syntax-context context-type))))
4541 (cond ((equal context-type 'paren)
4542 ;; Lines inside a paren are always a continuation line
4543 ;; (except the first one).
4544 (python-util-forward-comment -1)
4545 (point-marker))
4546 ((member context-type '(string comment))
4547 ;; move forward an roll again
4548 (goto-char context-start)
4549 (python-util-forward-comment)
4550 (python-info-continuation-line-p))
4551 (t
4552 ;; Not within a paren, string or comment, the only way
4553 ;; we are dealing with a continuation line is that
4554 ;; previous line contains a backslash, and this can
4555 ;; only be the previous line from current
4556 (back-to-indentation)
4557 (python-util-forward-comment -1)
4558 (when (and (equal (1- line-start) (line-number-at-pos))
4559 (python-info-line-ends-backslash-p))
4560 (point-marker))))))))
4561
4562 (defun python-info-block-continuation-line-p ()
4563 "Return non-nil if current line is a continuation of a block."
4564 (save-excursion
4565 (when (python-info-continuation-line-p)
4566 (forward-line -1)
4567 (back-to-indentation)
4568 (when (looking-at (python-rx block-start))
4569 (point-marker)))))
4570
4571 (defun python-info-assignment-statement-p (&optional current-line-only)
4572 "Check if current line is an assignment.
4573 With argument CURRENT-LINE-ONLY is non-nil, don't follow any
4574 continuations, just check the if current line is an assignment."
4575 (save-excursion
4576 (let ((found nil))
4577 (if current-line-only
4578 (back-to-indentation)
4579 (python-nav-beginning-of-statement))
4580 (while (and
4581 (re-search-forward (python-rx not-simple-operator
4582 assignment-operator
4583 (group not-simple-operator))
4584 (line-end-position) t)
4585 (not found))
4586 (save-excursion
4587 ;; The assignment operator should not be inside a string.
4588 (backward-char (length (match-string-no-properties 1)))
4589 (setq found (not (python-syntax-context-type)))))
4590 (when found
4591 (skip-syntax-forward " ")
4592 (point-marker)))))
4593
4594 ;; TODO: rename to clarify this is only for the first continuation
4595 ;; line or remove it and move its body to `python-indent-context'.
4596 (defun python-info-assignment-continuation-line-p ()
4597 "Check if current line is the first continuation of an assignment.
4598 When current line is continuation of another with an assignment
4599 return the point of the first non-blank character after the
4600 operator."
4601 (save-excursion
4602 (when (python-info-continuation-line-p)
4603 (forward-line -1)
4604 (python-info-assignment-statement-p t))))
4605
4606 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4607 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4608 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4609 (save-excursion
4610 (beginning-of-line 1)
4611 (looking-at python-nav-beginning-of-defun-regexp))))
4612
4613 (defun python-info-current-line-comment-p ()
4614 "Return non-nil if current line is a comment line."
4615 (char-equal
4616 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4617 ?#))
4618
4619 (defun python-info-current-line-empty-p ()
4620 "Return non-nil if current line is empty, ignoring whitespace."
4621 (save-excursion
4622 (beginning-of-line 1)
4623 (looking-at
4624 (python-rx line-start (* whitespace)
4625 (group (* not-newline))
4626 (* whitespace) line-end))
4627 (string-equal "" (match-string-no-properties 1))))
4628
4629 (defun python-info-docstring-p (&optional syntax-ppss)
4630 "Return non-nil if point is in a docstring.
4631 When optional argument SYNTAX-PPSS is given, use that instead of
4632 point's current `syntax-ppss'."
4633 ;;; https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
4634 (save-excursion
4635 (when (and syntax-ppss (python-syntax-context 'string syntax-ppss))
4636 (goto-char (nth 8 syntax-ppss)))
4637 (python-nav-beginning-of-statement)
4638 (let ((counter 1)
4639 (indentation (current-indentation))
4640 (backward-sexp-point)
4641 (re (concat "[uU]?[rR]?"
4642 (python-rx string-delimiter))))
4643 (when (and
4644 (not (python-info-assignment-statement-p))
4645 (looking-at-p re)
4646 ;; Allow up to two consecutive docstrings only.
4647 (>=
4648 2
4649 (progn
4650 (while (save-excursion
4651 (python-nav-backward-sexp)
4652 (setq backward-sexp-point (point))
4653 (and (= indentation (current-indentation))
4654 (not (bobp)) ; Prevent infloop.
4655 (looking-at-p
4656 (concat "[uU]?[rR]?"
4657 (python-rx string-delimiter)))))
4658 ;; Previous sexp was a string, restore point.
4659 (goto-char backward-sexp-point)
4660 (cl-incf counter))
4661 counter)))
4662 (python-util-forward-comment -1)
4663 (python-nav-beginning-of-statement)
4664 (cond ((bobp))
4665 ((python-info-assignment-statement-p) t)
4666 ((python-info-looking-at-beginning-of-defun))
4667 (t nil))))))
4668
4669 (defun python-info-encoding-from-cookie ()
4670 "Detect current buffer's encoding from its coding cookie.
4671 Returns the encoding as a symbol."
4672 (let ((first-two-lines
4673 (save-excursion
4674 (save-restriction
4675 (widen)
4676 (goto-char (point-min))
4677 (forward-line 2)
4678 (buffer-substring-no-properties
4679 (point)
4680 (point-min))))))
4681 (when (string-match (python-rx coding-cookie) first-two-lines)
4682 (intern (match-string-no-properties 1 first-two-lines)))))
4683
4684 (defun python-info-encoding ()
4685 "Return encoding for file.
4686 Try `python-info-encoding-from-cookie', if none is found then
4687 default to utf-8."
4688 ;; If no encoding is defined, then it's safe to use UTF-8: Python 2
4689 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4690 ;; in the worst case scenario python.el will make things work for
4691 ;; Python 2 files with unicode data and no encoding defined.
4692 (or (python-info-encoding-from-cookie)
4693 'utf-8))
4694
4695 \f
4696 ;;; Utility functions
4697
4698 (defun python-util-goto-line (line-number)
4699 "Move point to LINE-NUMBER."
4700 (goto-char (point-min))
4701 (forward-line (1- line-number)))
4702
4703 ;; Stolen from org-mode
4704 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4705 "Clone local variables from FROM-BUFFER.
4706 Optional argument REGEXP selects variables to clone and defaults
4707 to \"^python-\"."
4708 (mapc
4709 (lambda (pair)
4710 (and (symbolp (car pair))
4711 (string-match (or regexp "^python-")
4712 (symbol-name (car pair)))
4713 (set (make-local-variable (car pair))
4714 (cdr pair))))
4715 (buffer-local-variables from-buffer)))
4716
4717 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4718
4719 (defun python-util-comint-last-prompt ()
4720 "Return comint last prompt overlay start and end.
4721 This is for compatibility with Emacs < 24.4."
4722 (cond ((bound-and-true-p comint-last-prompt-overlay)
4723 (cons (overlay-start comint-last-prompt-overlay)
4724 (overlay-end comint-last-prompt-overlay)))
4725 ((bound-and-true-p comint-last-prompt)
4726 comint-last-prompt)
4727 (t nil)))
4728
4729 (defun python-util-forward-comment (&optional direction)
4730 "Python mode specific version of `forward-comment'.
4731 Optional argument DIRECTION defines the direction to move to."
4732 (let ((comment-start (python-syntax-context 'comment))
4733 (factor (if (< (or direction 0) 0)
4734 -99999
4735 99999)))
4736 (when comment-start
4737 (goto-char comment-start))
4738 (forward-comment factor)))
4739
4740 (defun python-util-list-directories (directory &optional predicate max-depth)
4741 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4742 Argument PREDICATE defaults to `identity' and must be a function
4743 that takes one argument (a full path) and returns non-nil for
4744 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4745 searching when depth is reached, else don't limit."
4746 (let* ((dir (expand-file-name directory))
4747 (dir-length (length dir))
4748 (predicate (or predicate #'identity))
4749 (to-scan (list dir))
4750 (tally nil))
4751 (while to-scan
4752 (let ((current-dir (car to-scan)))
4753 (when (funcall predicate current-dir)
4754 (setq tally (cons current-dir tally)))
4755 (setq to-scan (append (cdr to-scan)
4756 (python-util-list-files
4757 current-dir #'file-directory-p)
4758 nil))
4759 (when (and max-depth
4760 (<= max-depth
4761 (length (split-string
4762 (substring current-dir dir-length)
4763 "/\\|\\\\" t))))
4764 (setq to-scan nil))))
4765 (nreverse tally)))
4766
4767 (defun python-util-list-files (dir &optional predicate)
4768 "List files in DIR, filtering with PREDICATE.
4769 Argument PREDICATE defaults to `identity' and must be a function
4770 that takes one argument (a full path) and returns non-nil for
4771 allowed files."
4772 (let ((dir-name (file-name-as-directory dir)))
4773 (apply #'nconc
4774 (mapcar (lambda (file-name)
4775 (let ((full-file-name (expand-file-name file-name dir-name)))
4776 (when (and
4777 (not (member file-name '("." "..")))
4778 (funcall (or predicate #'identity) full-file-name))
4779 (list full-file-name))))
4780 (directory-files dir-name)))))
4781
4782 (defun python-util-list-packages (dir &optional max-depth)
4783 "List packages in DIR, limited by MAX-DEPTH.
4784 When optional argument MAX-DEPTH is non-nil, stop searching when
4785 depth is reached, else don't limit."
4786 (let* ((dir (expand-file-name dir))
4787 (parent-dir (file-name-directory
4788 (directory-file-name
4789 (file-name-directory
4790 (file-name-as-directory dir)))))
4791 (subpath-length (length parent-dir)))
4792 (mapcar
4793 (lambda (file-name)
4794 (replace-regexp-in-string
4795 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4796 (python-util-list-directories
4797 (directory-file-name dir)
4798 (lambda (dir)
4799 (file-exists-p (expand-file-name "__init__.py" dir)))
4800 max-depth))))
4801
4802 (defun python-util-popn (lst n)
4803 "Return LST first N elements.
4804 N should be an integer, when negative its opposite is used.
4805 When N is bigger than the length of LST, the list is
4806 returned as is."
4807 (let* ((n (min (abs n)))
4808 (len (length lst))
4809 (acc))
4810 (if (> n len)
4811 lst
4812 (while (< 0 n)
4813 (setq acc (cons (car lst) acc)
4814 lst (cdr lst)
4815 n (1- n)))
4816 (reverse acc))))
4817
4818 (defun python-util-strip-string (string)
4819 "Strip STRING whitespace and newlines from end and beginning."
4820 (replace-regexp-in-string
4821 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4822 (: (* (any whitespace ?\r ?\n)) string-end)))
4823 ""
4824 string))
4825
4826 (defun python-util-valid-regexp-p (regexp)
4827 "Return non-nil if REGEXP is valid."
4828 (ignore-errors (string-match regexp "") t))
4829
4830 \f
4831 (defun python-electric-pair-string-delimiter ()
4832 (when (and electric-pair-mode
4833 (memq last-command-event '(?\" ?\'))
4834 (let ((count 0))
4835 (while (eq (char-before (- (point) count)) last-command-event)
4836 (cl-incf count))
4837 (= count 3))
4838 (eq (char-after) last-command-event))
4839 (save-excursion (insert (make-string 2 last-command-event)))))
4840
4841 (defvar electric-indent-inhibit)
4842
4843 ;;;###autoload
4844 (define-derived-mode python-mode prog-mode "Python"
4845 "Major mode for editing Python files.
4846
4847 \\{python-mode-map}"
4848 (set (make-local-variable 'tab-width) 8)
4849 (set (make-local-variable 'indent-tabs-mode) nil)
4850
4851 (set (make-local-variable 'comment-start) "# ")
4852 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4853
4854 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4855 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4856
4857 (set (make-local-variable 'forward-sexp-function)
4858 'python-nav-forward-sexp)
4859
4860 (set (make-local-variable 'font-lock-defaults)
4861 '(python-font-lock-keywords
4862 nil nil nil nil
4863 (font-lock-syntactic-face-function
4864 . python-font-lock-syntactic-face-function)))
4865
4866 (set (make-local-variable 'syntax-propertize-function)
4867 python-syntax-propertize-function)
4868
4869 (set (make-local-variable 'indent-line-function)
4870 #'python-indent-line-function)
4871 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4872 ;; Because indentation is not redundant, we cannot safely reindent code.
4873 (set (make-local-variable 'electric-indent-inhibit) t)
4874 (set (make-local-variable 'electric-indent-chars)
4875 (cons ?: electric-indent-chars))
4876
4877 ;; Add """ ... """ pairing to electric-pair-mode.
4878 (add-hook 'post-self-insert-hook
4879 #'python-electric-pair-string-delimiter 'append t)
4880
4881 (set (make-local-variable 'paragraph-start) "\\s-*$")
4882 (set (make-local-variable 'fill-paragraph-function)
4883 #'python-fill-paragraph)
4884
4885 (set (make-local-variable 'beginning-of-defun-function)
4886 #'python-nav-beginning-of-defun)
4887 (set (make-local-variable 'end-of-defun-function)
4888 #'python-nav-end-of-defun)
4889
4890 (add-hook 'completion-at-point-functions
4891 #'python-completion-at-point nil 'local)
4892
4893 (add-hook 'post-self-insert-hook
4894 #'python-indent-post-self-insert-function 'append 'local)
4895
4896 (set (make-local-variable 'imenu-create-index-function)
4897 #'python-imenu-create-index)
4898
4899 (set (make-local-variable 'add-log-current-defun-function)
4900 #'python-info-current-defun)
4901
4902 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4903
4904 (set (make-local-variable 'skeleton-further-elements)
4905 '((abbrev-mode nil)
4906 (< '(backward-delete-char-untabify (min python-indent-offset
4907 (current-column))))
4908 (^ '(- (1+ (current-indentation))))))
4909
4910 (if (null eldoc-documentation-function)
4911 ;; Emacs<25
4912 (set (make-local-variable 'eldoc-documentation-function)
4913 #'python-eldoc-function)
4914 (add-function :before-until (local 'eldoc-documentation-function)
4915 #'python-eldoc-function))
4916
4917 (add-to-list
4918 'hs-special-modes-alist
4919 `(python-mode
4920 "\\s-*\\(?:def\\|class\\)\\>"
4921 ;; Use the empty string as end regexp so it doesn't default to
4922 ;; "\\s)". This way parens at end of defun are properly hidden.
4923 ""
4924 "#"
4925 python-hideshow-forward-sexp-function
4926 nil))
4927
4928 (set (make-local-variable 'outline-regexp)
4929 (python-rx (* space) block-start))
4930 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4931 (set (make-local-variable 'outline-level)
4932 #'(lambda ()
4933 "`outline-level' function for Python mode."
4934 (1+ (/ (current-indentation) python-indent-offset))))
4935
4936 (python-skeleton-add-menu-items)
4937
4938 (make-local-variable 'python-shell-internal-buffer)
4939
4940 (when python-indent-guess-indent-offset
4941 (python-indent-guess-indent-offset)))
4942
4943
4944 (provide 'python)
4945
4946 ;; Local Variables:
4947 ;; coding: utf-8
4948 ;; indent-tabs-mode: nil
4949 ;; End:
4950
4951 ;;; python.el ends here