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