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