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