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