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