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