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