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