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