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
8 ;; Maintainer: emacs-devel@gnu.org
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/>.
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,
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows opening Python shells
66 ;; inside Emacs and executing any block of code of your current buffer
67 ;; in that inferior Python process.
69 ;; Besides that only the standard CPython (2.x and 3.x) shell and
70 ;; IPython are officially supported out of the box, the interaction
71 ;; should support any other readline based Python shells as well
72 ;; (e.g. Jython and Pypy have been reported to work). You can change
73 ;; your default interpreter and commandline arguments by setting the
74 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
75 ;; variables. This example enables IPython globally:
77 ;; (setq python-shell-interpreter "ipython"
78 ;; python-shell-interpreter-args "-i")
80 ;; Using the "console" subcommand to start IPython in server-client
81 ;; mode is known to fail intermittently due a bug on IPython itself
82 ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
83 ;; There seems to be a race condition in the IPython server (A.K.A
84 ;; kernel) when code is sent while it is still initializing, sometimes
85 ;; causing the shell to get stalled. With that said, if an IPython
86 ;; kernel is already running, "console --existing" seems to work fine.
88 ;; Running IPython on Windows needs more tweaking. The way you should
89 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
90 ;; is as follows (of course you need to modify the paths according to
93 ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
94 ;; python-shell-interpreter-args
95 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
97 ;; If you are experiencing missing or delayed output in your shells,
98 ;; that's likely caused by your Operating System's pipe buffering
99 ;; (e.g. this is known to happen running CPython 3.3.4 in Windows 7.
100 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101 ;; fix this, using CPython's "-u" commandline argument or setting the
102 ;; "PYTHONUNBUFFERED" environment variable should help: See URL
103 ;; `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
105 ;; The interaction relies upon having prompts for input (e.g. ">>> "
106 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
107 ;; IPython) detected properly. Failing that Emacs may hang but, in
108 ;; the case that happens, you can recover with \\[keyboard-quit]. To
109 ;; avoid this issue, a two-step prompt autodetection mechanism is
110 ;; provided: the first step is manual and consists of a collection of
111 ;; regular expressions matching common prompts for Python shells
112 ;; stored in `python-shell-prompt-input-regexps' and
113 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
114 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
115 ;; `python-shell-prompt-output-regexp' which are appended to the
116 ;; former automatically when a shell spawns; the second step is
117 ;; automatic and depends on the `python-shell-prompt-detect' helper
118 ;; function. See its docstring for details on global variables that
119 ;; modify its behavior.
121 ;; Shell completion: hitting tab will try to complete the current
122 ;; word. Shell completion is implemented in such way that if you
123 ;; change the `python-shell-interpreter' it should be possible to
124 ;; integrate custom logic to calculate completions. To achieve this
125 ;; you just need to set `python-shell-completion-setup-code' and
126 ;; `python-shell-completion-string-code'. The default provided code,
127 ;; enables autocompletion for both CPython and IPython (and ideally
128 ;; any readline based Python shell). This code depends on the
129 ;; readline module, so if you are using some Operating System that
130 ;; bundles Python without it (like Windows), installing pyreadline
131 ;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
132 ;; suffice. To troubleshoot why you are not getting any completions
133 ;; you can try the following in your Python shell:
135 ;; >>> import readline, rlcompleter
137 ;; If you see an error, then you need to either install pyreadline or
138 ;; setup custom code that avoids that dependency.
140 ;; Shell virtualenv support: The shell also contains support for
141 ;; virtualenvs and other special environment modifications thanks to
142 ;; `python-shell-process-environment' and `python-shell-exec-path'.
143 ;; These two variables allows you to modify execution paths and
144 ;; environment variables to make easy for you to setup virtualenv rules
145 ;; or behavior modifications when running shells. Here is an example
146 ;; of how to make shell processes to be run using the /path/to/env/
149 ;; (setq python-shell-process-environment
151 ;; (format "PATH=%s" (mapconcat
154 ;; (cons (getenv "PATH")
155 ;; '("/path/to/env/bin/")))
157 ;; "VIRTUAL_ENV=/path/to/env/"))
158 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
160 ;; Since the above is cumbersome and can be programmatically
161 ;; calculated, the variable `python-shell-virtualenv-path' is
162 ;; provided. When this variable is set with the path of the
163 ;; virtualenv to use, `process-environment' and `exec-path' get proper
164 ;; values in order to run shells inside the specified virtualenv. So
165 ;; the following will achieve the same as the previous example:
167 ;; (setq python-shell-virtualenv-path "/path/to/env/")
169 ;; Also the `python-shell-extra-pythonpaths' variable have been
170 ;; introduced as simple way of adding paths to the PYTHONPATH without
171 ;; affecting existing values.
173 ;; Pdb tracking: when you execute a block of code that contains some
174 ;; call to pdb (or ipdb) it will prompt the block of code and will
175 ;; follow the execution of pdb marking the current line with an arrow.
177 ;; Symbol completion: you can complete the symbol at point. It uses
178 ;; the shell completion in background so you should run
179 ;; `python-shell-send-buffer' from time to time to get better results.
181 ;; Skeletons: skeletons are provided for simple inserting of things like class,
182 ;; def, for, import, if, try, and while. These skeletons are
183 ;; integrated with abbrev. If you have `abbrev-mode' activated and
184 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
185 ;; the name of any of those defined and hit SPC, they will be
186 ;; automatically expanded. As an alternative you can use the defined
187 ;; skeleton commands: `python-skeleton-<foo>'.
189 ;; FFAP: You can find the filename for a given module when using ffap
190 ;; out of the box. This feature needs an inferior python shell
193 ;; Code check: Check the current file for errors with `python-check'
194 ;; using the program defined in `python-check-command'.
196 ;; Eldoc: returns documentation for object at point by using the
197 ;; inferior python subprocess to inspect its documentation. As you
198 ;; might guessed you should run `python-shell-send-buffer' from time
199 ;; to time to get better results too.
201 ;; Imenu: There are two index building functions to be used as
202 ;; `imenu-create-index-function': `python-imenu-create-index' (the
203 ;; default one, builds the alist in form of a tree) and
204 ;; `python-imenu-create-flat-index'. See also
205 ;; `python-imenu-format-item-label-function',
206 ;; `python-imenu-format-parent-item-label-function',
207 ;; `python-imenu-format-parent-item-jump-label-function' variables for
208 ;; changing the way labels are formatted in the tree version.
210 ;; If you used python-mode.el you probably will miss auto-indentation
211 ;; when inserting newlines. To achieve the same behavior you have
214 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
216 ;; 2) Add the following hook in your .emacs:
218 ;; (add-hook 'python-mode-hook
220 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
222 ;; I'd recommend the first one since you'll get the same behavior for
223 ;; all modes out-of-the-box.
227 ;; Add this to your .emacs:
229 ;; (add-to-list 'load-path "/folder/containing/file")
236 (require 'ansi-color)
241 ;; Avoid compiler warnings
242 (defvar view-return-to-alist)
243 (defvar compilation-error-regexp-alist)
244 (defvar outline-heading-end-regexp)
246 (autoload 'comint-mode "comint")
249 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
251 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
254 "Python Language's flying circus support for Emacs."
257 :link '(emacs-commentary-link "python"))
262 (defvar python-mode-map
263 (let ((map (make-sparse-keymap)))
265 (define-key map [remap backward-sentence] 'python-nav-backward-block)
266 (define-key map [remap forward-sentence] 'python-nav-forward-block)
267 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
268 (define-key map "\C-c\C-j" 'imenu)
270 (define-key map "\177" 'python-indent-dedent-line-backspace)
271 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
272 (define-key map "\C-c<" 'python-indent-shift-left)
273 (define-key map "\C-c>" 'python-indent-shift-right)
275 (define-key map "\C-c\C-tc" 'python-skeleton-class)
276 (define-key map "\C-c\C-td" 'python-skeleton-def)
277 (define-key map "\C-c\C-tf" 'python-skeleton-for)
278 (define-key map "\C-c\C-ti" 'python-skeleton-if)
279 (define-key map "\C-c\C-tm" 'python-skeleton-import)
280 (define-key map "\C-c\C-tt" 'python-skeleton-try)
281 (define-key map "\C-c\C-tw" 'python-skeleton-while)
283 (define-key map "\C-c\C-p" 'run-python)
284 (define-key map "\C-c\C-s" 'python-shell-send-string)
285 (define-key map "\C-c\C-r" 'python-shell-send-region)
286 (define-key map "\C-\M-x" 'python-shell-send-defun)
287 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
288 (define-key map "\C-c\C-l" 'python-shell-send-file)
289 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
290 ;; Some util commands
291 (define-key map "\C-c\C-v" 'python-check)
292 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
294 (substitute-key-definition 'complete-symbol 'completion-at-point
296 (easy-menu-define python-menu map "Python Mode menu"
298 :help "Python-specific Features"
299 ["Shift region left" python-indent-shift-left :active mark-active
300 :help "Shift region left by a single indentation step"]
301 ["Shift region right" python-indent-shift-right :active mark-active
302 :help "Shift region right by a single indentation step"]
304 ["Start of def/class" beginning-of-defun
305 :help "Go to start of outermost definition around point"]
306 ["End of def/class" end-of-defun
307 :help "Go to end of definition around point"]
308 ["Mark def/class" mark-defun
309 :help "Mark outermost definition around point"]
310 ["Jump to def/class" imenu
311 :help "Jump to a class or function definition"]
315 ["Start interpreter" run-python
316 :help "Run inferior Python process in a separate buffer"]
317 ["Switch to shell" python-shell-switch-to-shell
318 :help "Switch to running inferior Python process"]
319 ["Eval string" python-shell-send-string
320 :help "Eval string in inferior Python session"]
321 ["Eval buffer" python-shell-send-buffer
322 :help "Eval buffer in inferior Python session"]
323 ["Eval region" python-shell-send-region
324 :help "Eval region in inferior Python session"]
325 ["Eval defun" python-shell-send-defun
326 :help "Eval defun in inferior Python session"]
327 ["Eval file" python-shell-send-file
328 :help "Eval file in inferior Python session"]
329 ["Debugger" pdb :help "Run pdb under GUD"]
331 ["Check file" python-check
332 :help "Check file for errors"]
333 ["Help on symbol" python-eldoc-at-point
334 :help "Get help on symbol at point"]
335 ["Complete symbol" completion-at-point
336 :help "Complete symbol before point"]))
338 "Keymap for `python-mode'.")
341 ;;; Python specialized rx
344 (defconst python-rx-constituents
345 `((block-start . ,(rx symbol-start
346 (or "def" "class" "if" "elif" "else" "try"
347 "except" "finally" "for" "while" "with")
349 (dedenter . ,(rx symbol-start
350 (or "elif" "else" "except" "finally")
352 (block-ender . ,(rx symbol-start
354 "break" "continue" "pass" "raise" "return")
356 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
358 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
359 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
360 (+ space) "==" (+ space)
361 (any ?' ?\") "__main__" (any ?' ?\")
363 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
364 (open-paren . ,(rx (or "{" "[" "(")))
365 (close-paren . ,(rx (or "}" "]" ")")))
366 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
367 ;; FIXME: rx should support (not simple-operator).
368 (not-simple-operator . ,(rx
370 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
371 ;; FIXME: Use regexp-opt.
372 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
373 "=" "%" "**" "//" "<<" ">>" "<=" "!="
374 "==" ">=" "is" "not")))
375 ;; FIXME: Use regexp-opt.
376 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
377 ">>=" "<<=" "&=" "^=" "|=")))
378 (string-delimiter . ,(rx (and
379 ;; Match even number of backslashes.
380 (or (not (any ?\\ ?\' ?\")) point
381 ;; Quotes might be preceded by a escaped quote.
382 (and (or (not (any ?\\)) point) ?\\
383 (* ?\\ ?\\) (any ?\' ?\")))
385 ;; Match single or triple quotes of any kind.
386 (group (or "\"" "\"\"\"" "'" "'''"))))))
387 "Additional Python specific sexps for `python-rx'")
389 (defmacro python-rx (&rest regexps)
390 "Python mode specialized rx macro.
391 This variant of `rx' supports common Python named REGEXPS."
392 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
393 (cond ((null regexps)
396 (rx-to-string `(and ,@regexps) t))
398 (rx-to-string (car regexps) t))))))
401 ;;; Font-lock and syntax
404 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
407 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
408 (and (nth 4 ppss) (nth 8 ppss))))
410 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
411 (and (nth 3 ppss) (nth 8 ppss))))
413 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
416 (defun python-syntax-context (type &optional syntax-ppss)
417 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
418 TYPE can be `comment', `string' or `paren'. It returns the start
419 character address of the specified TYPE."
420 (declare (compiler-macro python-syntax--context-compiler-macro))
421 (let ((ppss (or syntax-ppss (syntax-ppss))))
423 (`comment (and (nth 4 ppss) (nth 8 ppss)))
424 (`string (and (nth 3 ppss) (nth 8 ppss)))
425 (`paren (nth 1 ppss))
428 (defun python-syntax-context-type (&optional syntax-ppss)
429 "Return the context type using SYNTAX-PPSS.
430 The type returned can be `comment', `string' or `paren'."
431 (let ((ppss (or syntax-ppss (syntax-ppss))))
433 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
434 ((nth 1 ppss) 'paren))))
436 (defsubst python-syntax-comment-or-string-p ()
437 "Return non-nil if point is inside 'comment or 'string."
438 (nth 8 (syntax-ppss)))
440 (define-obsolete-function-alias
441 'python-info-ppss-context #'python-syntax-context "24.3")
443 (define-obsolete-function-alias
444 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
446 (define-obsolete-function-alias
447 'python-info-ppss-comment-or-string-p
448 #'python-syntax-comment-or-string-p "24.3")
450 (defvar python-font-lock-keywords
454 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
455 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
456 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
461 ;; False, None, and True are listed as keywords on the Python 3
462 ;; documentation, but since they also qualify as constants they are
463 ;; fontified like that in order to keep font-lock consistent between
470 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
471 (1 font-lock-function-name-face))
473 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
474 (1 font-lock-type-face))
478 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
479 ;; copyright, license, credits, quit and exit are added by the site
480 ;; module and they are not intended to be used in programs
481 "copyright" "credits" "exit" "license" "quit")
482 symbol-end) . font-lock-constant-face)
484 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
485 (0+ "." (1+ (or word ?_)))))
486 (1 font-lock-type-face))
487 ;; Builtin Exceptions
490 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
491 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
492 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
493 "ImportError" "ImportWarning" "IndexError" "KeyError"
494 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
495 "NotImplementedError" "OSError" "OverflowError"
496 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
497 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
498 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
499 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
500 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
501 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
505 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
507 symbol-end) . font-lock-type-face)
511 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
512 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
513 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
514 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
515 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
516 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
517 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
518 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
521 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
522 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
525 "ascii" "bytearray" "bytes" "exec"
527 "__all__" "__doc__" "__name__" "__package__")
528 symbol-end) . font-lock-builtin-face)
530 ;; support for a = b = c = 5
532 (let ((re (python-rx (group (+ (any word ?. ?_)))
533 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
534 assignment-operator))
536 (while (and (setq res (re-search-forward re limit t))
537 (or (python-syntax-context 'paren)
538 (equal (char-after (point-marker)) ?=))))
540 (1 font-lock-variable-name-face nil nil))
541 ;; support for a, b, c = (1, 2, 3)
543 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
544 (* ?, (* space) (+ (any word ?. ?_)) (* space))
545 ?, (* space) (+ (any word ?. ?_)) (* space)
546 assignment-operator))
548 (while (and (setq res (re-search-forward re limit t))
549 (goto-char (match-end 1))
550 (python-syntax-context 'paren)))
552 (1 font-lock-variable-name-face nil nil))))
554 (defconst python-syntax-propertize-function
555 (syntax-propertize-rules
556 ((python-rx string-delimiter)
557 (0 (ignore (python-syntax-stringify))))))
559 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
560 "Count number of quotes around point (max is 3).
561 QUOTE-CHAR is the quote char to count. Optional argument POINT is
562 the point where scan starts (defaults to current point), and LIMIT
563 is used to limit the scan."
566 (or (not limit) (< (+ point i) limit))
567 (eq (char-after (+ point i)) quote-char))
571 (defun python-syntax-stringify ()
572 "Put `syntax-table' property correctly on single/triple quotes."
573 (let* ((num-quotes (length (match-string-no-properties 1)))
575 (backward-char num-quotes)
577 (forward-char num-quotes)))
578 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
579 (quote-starting-pos (- (point) num-quotes))
580 (quote-ending-pos (point))
583 (python-syntax-count-quotes
584 (char-before) string-start quote-starting-pos))))
585 (cond ((and string-start (= num-closing-quotes 0))
586 ;; This set of quotes doesn't match the string starting
590 ;; This set of quotes delimit the start of a string.
591 (put-text-property quote-starting-pos (1+ quote-starting-pos)
592 'syntax-table (string-to-syntax "|")))
593 ((= num-quotes num-closing-quotes)
594 ;; This set of quotes delimit the end of a string.
595 (put-text-property (1- quote-ending-pos) quote-ending-pos
596 'syntax-table (string-to-syntax "|")))
597 ((> num-quotes num-closing-quotes)
598 ;; This may only happen whenever a triple quote is closing
599 ;; a single quoted string. Add string delimiter syntax to
601 (put-text-property quote-starting-pos quote-ending-pos
602 'syntax-table (string-to-syntax "|"))))))
604 (defvar python-mode-syntax-table
605 (let ((table (make-syntax-table)))
606 ;; Give punctuation syntax to ASCII that normally has symbol
607 ;; syntax or has word syntax and isn't a letter.
608 (let ((symbol (string-to-syntax "_"))
609 (sst (standard-syntax-table)))
612 (if (equal symbol (aref sst i))
613 (modify-syntax-entry i "." table)))))
614 (modify-syntax-entry ?$ "." table)
615 (modify-syntax-entry ?% "." table)
617 (modify-syntax-entry ?# "<" table)
618 (modify-syntax-entry ?\n ">" table)
619 (modify-syntax-entry ?' "\"" table)
620 (modify-syntax-entry ?` "$" table)
622 "Syntax table for Python files.")
624 (defvar python-dotty-syntax-table
625 (let ((table (make-syntax-table python-mode-syntax-table)))
626 (modify-syntax-entry ?. "w" table)
627 (modify-syntax-entry ?_ "w" table)
629 "Dotty syntax table for Python files.
630 It makes underscores and dots word constituent chars.")
635 (defcustom python-indent-offset 4
636 "Default indentation offset for Python."
641 (defcustom python-indent-guess-indent-offset t
642 "Non-nil tells Python mode to guess `python-indent-offset' value."
647 (defcustom python-indent-trigger-commands
648 '(indent-for-tab-command yas-expand yas/expand)
649 "Commands that might trigger a `python-indent-line' call."
650 :type '(repeat symbol)
653 (define-obsolete-variable-alias
654 'python-indent 'python-indent-offset "24.3")
656 (define-obsolete-variable-alias
657 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
659 (defvar python-indent-current-level 0
660 "Current indentation level `python-indent-line-function' is using.")
662 (defvar python-indent-levels '(0)
663 "Levels of indentation available for `python-indent-line-function'.")
665 (defun python-indent-guess-indent-offset ()
666 "Guess and set `python-indent-offset' for the current buffer."
671 (goto-char (point-min))
673 (while (and (not block-end)
675 (python-rx line-start block-start) nil t))
677 (not (python-syntax-context-type))
679 (goto-char (line-end-position))
680 (python-util-forward-comment -1)
681 (if (equal (char-before) ?:)
684 (when (python-info-block-continuation-line-p)
685 (while (and (python-info-continuation-line-p)
688 (python-util-forward-comment -1)
689 (when (equal (char-before) ?:)
691 (setq block-end (point-marker))))
694 (goto-char block-end)
695 (python-util-forward-comment)
696 (current-indentation))))
697 (if (and indentation (not (zerop indentation)))
698 (set (make-local-variable 'python-indent-offset) indentation)
699 (message "Can't guess python-indent-offset, using defaults: %s"
700 python-indent-offset)))))))
702 (defun python-indent-context ()
703 "Get information on indentation context.
704 Context information is returned with a cons with the form:
707 Where status can be any of the following symbols:
709 * after-comment: When current line might continue a comment block
710 * inside-paren: If point in between (), {} or []
711 * inside-string: If point is inside a string
712 * after-backslash: Previous line ends in a backslash
713 * after-beginning-of-block: Point is after beginning of block
714 * after-line: Point is after normal line
715 * dedenter-statement: Point is on a dedenter statement.
716 * no-indent: Point is at beginning of buffer or other special case
717 START is the buffer position where the sexp starts."
720 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
724 ;; Beginning of buffer
726 (goto-char (line-beginning-position))
729 ;; Comment continuation
733 (python-info-current-line-comment-p)
734 (python-info-current-line-empty-p))
737 (python-info-current-line-comment-p)))
741 ((setq start (python-syntax-context 'string ppss))
744 ((setq start (python-syntax-context 'paren ppss))
747 ((setq start (when (not (or (python-syntax-context 'string ppss)
748 (python-syntax-context 'comment ppss)))
749 (let ((line-beg-pos (line-number-at-pos)))
750 (python-info-line-ends-backslash-p
751 (1- line-beg-pos)))))
753 ;; After beginning of block
754 ((setq start (save-excursion
756 (back-to-indentation)
757 (python-util-forward-comment -1)
758 (equal (char-before) ?:))
759 ;; Move to the first block start that's not in within
760 ;; a string, comment or paren and that's not a
761 ;; continuation line.
762 (while (and (re-search-backward
763 (python-rx block-start) nil t)
765 (python-syntax-context-type)
766 (python-info-continuation-line-p))))
767 (when (looking-at (python-rx block-start))
769 'after-beginning-of-block)
770 ((when (setq start (python-info-dedenter-statement-p))
771 'dedenter-statement))
773 ((setq start (save-excursion
774 (back-to-indentation)
775 (skip-chars-backward (rx (or whitespace ?\n)))
776 (python-nav-beginning-of-statement)
783 (defun python-indent-calculate-indentation ()
784 "Calculate correct indentation offset for the current line."
785 (let* ((indentation-context (python-indent-context))
786 (context-status (car indentation-context))
787 (context-start (cdr indentation-context)))
791 (pcase context-status
794 (goto-char context-start)
795 (current-indentation))
796 ;; When point is after beginning of block just add one level
797 ;; of indentation relative to the context-start
798 (`after-beginning-of-block
799 (goto-char context-start)
800 (+ (current-indentation) python-indent-offset))
801 ;; When after a simple line just use previous line
804 (let* ((pair (save-excursion
805 (goto-char context-start)
807 (current-indentation)
808 (python-info-beginning-of-block-p))))
809 (context-indentation (car pair))
810 ;; TODO: Separate block enders into its own case.
813 (python-util-forward-comment -1)
814 (python-nav-beginning-of-statement)
815 (looking-at (python-rx block-ender)))
818 (- context-indentation adjustment)))
819 ;; When point is on a dedenter statement, search for the
820 ;; opening block that corresponds to it and use its
821 ;; indentation. If no opening block is found just remove
822 ;; indentation as this is an invalid python file.
824 (let ((block-start-point
825 (python-info-dedenter-opening-block-position)))
827 (if (not block-start-point)
829 (goto-char block-start-point)
830 (current-indentation)))))
831 ;; When inside of a string, do nothing. just use the current
832 ;; indentation. XXX: perhaps it would be a good idea to
833 ;; invoke standard text indentation here
835 (goto-char context-start)
836 (current-indentation))
837 ;; After backslash we have several possibilities.
840 ;; Check if current line is a dot continuation. For this
841 ;; the current line must start with a dot and previous
842 ;; line must contain a dot too.
844 (back-to-indentation)
845 (when (looking-at "\\.")
846 ;; If after moving one line back point is inside a paren it
847 ;; needs to move back until it's not anymore
851 (python-syntax-context 'paren))))
852 (goto-char (line-end-position))
853 (while (and (re-search-backward
854 "\\." (line-beginning-position) t)
855 (python-syntax-context-type)))
856 (if (and (looking-at "\\.")
857 (not (python-syntax-context-type)))
858 ;; The indentation is the same column of the
859 ;; first matching dot that's not inside a
860 ;; comment, a string or a paren
862 ;; No dot found on previous line, just add another
863 ;; indentation level.
864 (+ (current-indentation) python-indent-offset)))))
865 ;; Check if prev line is a block continuation
866 ((let ((block-continuation-start
867 (python-info-block-continuation-line-p)))
868 (when block-continuation-start
869 ;; If block-continuation-start is set jump to that
870 ;; marker and use first column after the block start
871 ;; as indentation value.
872 (goto-char block-continuation-start)
874 (python-rx block-start (* space))
875 (line-end-position) t)
877 ;; Check if current line is an assignment continuation
878 ((let ((assignment-continuation-start
879 (python-info-assignment-continuation-line-p)))
880 (when assignment-continuation-start
881 ;; If assignment-continuation is set jump to that
882 ;; marker and use first column after the assignment
883 ;; operator as indentation value.
884 (goto-char assignment-continuation-start)
888 (goto-char (python-info-beginning-of-backslash))
893 (or (python-info-beginning-of-backslash) (point)))
894 (python-info-line-ends-backslash-p)))
895 ;; The two previous lines ended in a backslash so we must
896 ;; respect previous line indentation.
897 (current-indentation)
898 ;; What happens here is that we are dealing with the second
899 ;; line of a backslash continuation, in that case we just going
900 ;; to add one indentation level.
901 (+ (current-indentation) python-indent-offset)))))
902 ;; When inside a paren there's a need to handle nesting
906 ;; If current line closes the outermost open paren use the
907 ;; current indentation of the context-start line.
909 (skip-syntax-forward "\s" (line-end-position))
910 (when (and (looking-at (regexp-opt '(")" "]" "}")))
913 (not (python-syntax-context 'paren))))
914 (goto-char context-start)
915 (current-indentation))))
916 ;; If open paren is contained on a line by itself add another
917 ;; indentation level, else look for the first word after the
918 ;; opening paren and use it's column position as indentation
920 ((let* ((content-starts-in-newline)
923 (if (setq content-starts-in-newline
925 (goto-char context-start)
929 (line-beginning-position)
931 (python-util-forward-comment))
933 (+ (current-indentation) python-indent-offset)
937 ;; If current line closes a nested open paren de-indent one
940 (back-to-indentation)
941 (looking-at (regexp-opt '(")" "]" "}"))))
942 (- indent python-indent-offset))
943 ;; If the line of the opening paren that wraps the current
944 ;; line starts a block add another level of indentation to
945 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
947 (when (and content-starts-in-newline
949 (goto-char context-start)
950 (back-to-indentation)
951 (looking-at (python-rx block-start))))
952 (+ indent python-indent-offset))))
955 (defun python-indent-calculate-levels ()
956 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
957 (if (not (python-info-dedenter-statement-p))
958 (let* ((indentation (python-indent-calculate-indentation))
959 (remainder (% indentation python-indent-offset))
960 (steps (/ (- indentation remainder) python-indent-offset)))
961 (setq python-indent-levels (list 0))
962 (dotimes (step steps)
963 (push (* python-indent-offset (1+ step)) python-indent-levels))
964 (when (not (eq 0 remainder))
965 (push (+ (* python-indent-offset steps) remainder) python-indent-levels)))
966 (setq python-indent-levels
968 (mapcar (lambda (pos)
971 (current-indentation)))
972 (python-info-dedenter-opening-block-positions))
974 (setq python-indent-current-level (1- (length python-indent-levels))
975 python-indent-levels (nreverse python-indent-levels)))
977 (defun python-indent-toggle-levels ()
978 "Toggle `python-indent-current-level' over `python-indent-levels'."
979 (setq python-indent-current-level (1- python-indent-current-level))
980 (when (< python-indent-current-level 0)
981 (setq python-indent-current-level (1- (length python-indent-levels)))))
983 (defun python-indent-line (&optional force-toggle)
984 "Internal implementation of `python-indent-line-function'.
985 Uses the offset calculated in
986 `python-indent-calculate-indentation' and available levels
987 indicated by the variable `python-indent-levels' to set the
990 When the variable `last-command' is equal to one of the symbols
991 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
992 non-nil it cycles levels indicated in the variable
993 `python-indent-levels' by setting the current level in the
994 variable `python-indent-current-level'.
996 When the variable `last-command' is not equal to one of the
997 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
998 is nil it calculates possible indentation levels and saves them
999 in the variable `python-indent-levels'. Afterwards it sets the
1000 variable `python-indent-current-level' correctly so offset is
1002 (nth python-indent-current-level python-indent-levels)"
1004 (and (or (and (memq this-command python-indent-trigger-commands)
1005 (eq last-command this-command))
1007 (not (equal python-indent-levels '(0)))
1008 (or (python-indent-toggle-levels) t))
1009 (python-indent-calculate-levels))
1010 (let* ((starting-pos (point-marker))
1011 (indent-ending-position
1012 (+ (line-beginning-position) (current-indentation)))
1013 (follow-indentation-p
1015 (and (<= (line-beginning-position) starting-pos)
1016 (>= indent-ending-position starting-pos))))
1017 (next-indent (nth python-indent-current-level python-indent-levels)))
1018 (unless (= next-indent (current-indentation))
1020 (delete-horizontal-space)
1021 (indent-to next-indent)
1022 (goto-char starting-pos))
1023 (and follow-indentation-p (back-to-indentation)))
1024 (python-info-dedenter-opening-block-message))
1026 (defun python-indent-line-function ()
1027 "`indent-line-function' for Python mode.
1028 See `python-indent-line' for details."
1029 (python-indent-line))
1031 (defun python-indent-dedent-line ()
1032 "De-indent current line."
1034 (when (and (not (python-syntax-comment-or-string-p))
1035 (<= (point-marker) (save-excursion
1036 (back-to-indentation)
1038 (> (current-column) 0))
1039 (python-indent-line t)
1042 (defun python-indent-dedent-line-backspace (arg)
1043 "De-indent current line.
1044 Argument ARG is passed to `backward-delete-char-untabify' when
1045 point is not in between the indentation."
1047 (when (not (python-indent-dedent-line))
1048 (backward-delete-char-untabify arg)))
1049 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1051 (defun python-indent-region (start end)
1052 "Indent a Python region automagically.
1054 Called from a program, START and END specify the region to indent."
1055 (let ((deactivate-mark nil))
1058 (setq end (point-marker))
1060 (or (bolp) (forward-line 1))
1061 (while (< (point) end)
1062 (or (and (bolp) (eolp))
1065 (back-to-indentation)
1066 (setq word (current-word))
1069 ;; Don't mess with strings, unless it's the
1070 ;; enclosing set of quotes.
1071 (or (not (python-syntax-context 'string))
1075 (current-indentation)
1076 (python-syntax-count-quotes (char-after) (point))))
1077 (string-to-syntax "|"))))
1079 (delete-horizontal-space)
1080 (indent-to (python-indent-calculate-indentation)))))
1082 (move-marker end nil))))
1084 (defun python-indent-shift-left (start end &optional count)
1085 "Shift lines contained in region START END by COUNT columns to the left.
1086 COUNT defaults to `python-indent-offset'. If region isn't
1087 active, the current line is shifted. The shifted region includes
1088 the lines in which START and END lie. An error is signaled if
1089 any lines in the region are indented less than COUNT columns."
1092 (list (region-beginning) (region-end) current-prefix-arg)
1093 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1095 (setq count (prefix-numeric-value count))
1096 (setq count python-indent-offset))
1098 (let ((deactivate-mark nil))
1101 (while (< (point) end)
1102 (if (and (< (current-indentation) count)
1103 (not (looking-at "[ \t]*$")))
1104 (error "Can't shift all lines enough"))
1106 (indent-rigidly start end (- count))))))
1108 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1110 (defun python-indent-shift-right (start end &optional count)
1111 "Shift lines contained in region START END by COUNT columns to the right.
1112 COUNT defaults to `python-indent-offset'. If region isn't
1113 active, the current line is shifted. The shifted region includes
1114 the lines in which START and END lie."
1117 (list (region-beginning) (region-end) current-prefix-arg)
1118 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1119 (let ((deactivate-mark nil))
1120 (setq count (if count (prefix-numeric-value count)
1121 python-indent-offset))
1122 (indent-rigidly start end count)))
1124 (defun python-indent-post-self-insert-function ()
1125 "Adjust indentation after insertion of some characters.
1126 This function is intended to be added to `post-self-insert-hook.'
1127 If a line renders a paren alone, after adding a char before it,
1128 the line will be re-indented automatically if needed."
1129 (when (and electric-indent-mode
1130 (eq (char-before) last-command-event))
1132 ;; Electric indent inside parens
1135 (let ((paren-start (python-syntax-context 'paren)))
1136 ;; Check that point is inside parens.
1139 ;; Filter the case where input is happening in the same
1140 ;; line where the open paren is.
1141 (= (line-number-at-pos)
1142 (line-number-at-pos paren-start)))))
1143 ;; When content has been added before the closing paren or a
1144 ;; comma has been inserted, it's ok to do the trick.
1146 (memq (char-after) '(?\) ?\] ?\}))
1147 (eq (char-before) ?,)))
1149 (goto-char (line-beginning-position))
1150 (let ((indentation (python-indent-calculate-indentation)))
1151 (when (< (current-indentation) indentation)
1152 (indent-line-to indentation)))))
1154 ((and (eq ?: last-command-event)
1155 (memq ?: electric-indent-chars)
1156 (not current-prefix-arg)
1158 (not (equal ?: (char-before (1- (point)))))
1159 (not (python-syntax-comment-or-string-p)))
1160 (python-indent-line)))))
1165 (defvar python-nav-beginning-of-defun-regexp
1166 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1167 "Regexp matching class or function definition.
1168 The name of the defun should be grouped so it can be retrieved
1169 via `match-string'.")
1171 (defun python-nav--beginning-of-defun (&optional arg)
1172 "Internal implementation of `python-nav-beginning-of-defun'.
1173 With positive ARG search backwards, else search forwards."
1174 (when (or (null arg) (= arg 0)) (setq arg 1))
1175 (let* ((re-search-fn (if (> arg 0)
1176 #'re-search-backward
1177 #'re-search-forward))
1178 (line-beg-pos (line-beginning-position))
1179 (line-content-start (+ line-beg-pos (current-indentation)))
1180 (pos (point-marker))
1185 (not (python-info-looking-at-beginning-of-defun))
1186 (python-nav-backward-block)))
1187 (or (and (python-info-looking-at-beginning-of-defun)
1188 (+ (current-indentation) python-indent-offset))
1192 (when (and (< arg 0)
1193 (python-info-looking-at-beginning-of-defun))
1195 (while (and (funcall re-search-fn
1196 python-nav-beginning-of-defun-regexp nil t)
1197 (or (python-syntax-context-type)
1198 ;; Handle nested defuns when moving
1199 ;; backwards by checking indentation.
1201 (not (= (current-indentation) 0))
1202 (>= (current-indentation) beg-indentation)))))
1203 (and (python-info-looking-at-beginning-of-defun)
1204 (or (not (= (line-number-at-pos pos)
1205 (line-number-at-pos)))
1206 (and (>= (point) line-beg-pos)
1207 (<= (point) line-content-start)
1208 (> pos line-content-start)))))))
1210 (or (beginning-of-line 1) t)
1211 (and (goto-char pos) nil))))
1213 (defun python-nav-beginning-of-defun (&optional arg)
1214 "Move point to `beginning-of-defun'.
1215 With positive ARG search backwards else search forward.
1216 ARG nil or 0 defaults to 1. When searching backwards,
1217 nested defuns are handled with care depending on current
1218 point position. Return non-nil if point is moved to
1219 `beginning-of-defun'."
1220 (when (or (null arg) (= arg 0)) (setq arg 1))
1222 (while (and (not (= arg 0))
1223 (let ((keep-searching-p
1224 (python-nav--beginning-of-defun arg)))
1225 (when (and keep-searching-p (null found))
1228 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1231 (defun python-nav-end-of-defun ()
1232 "Move point to the end of def or class.
1233 Returns nil if point is not in a def or class."
1235 (let ((beg-defun-indent)
1237 (when (or (python-info-looking-at-beginning-of-defun)
1238 (python-nav-beginning-of-defun 1)
1239 (python-nav-beginning-of-defun -1))
1240 (setq beg-defun-indent (current-indentation))
1242 (python-nav-end-of-statement)
1243 (python-util-forward-comment 1)
1244 (and (> (current-indentation) beg-defun-indent)
1246 (python-util-forward-comment -1)
1248 ;; Ensure point moves forward.
1249 (and (> beg-pos (point)) (goto-char beg-pos)))))
1251 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1252 "Move point using FN avoiding places with specific context.
1253 FN must take no arguments. POSCOMPFN is a two arguments function
1254 used to compare current and previous point after it is moved
1255 using FN, this is normally a less-than or greater-than
1256 comparison. Optional argument CONTEXTFN defaults to
1257 `python-syntax-context-type' and is used for checking current
1258 point context, it must return a non-nil value if this point must
1260 (let ((contextfn (or contextfn 'python-syntax-context-type))
1261 (start-pos (point-marker))
1266 (and (funcall fn) (point-marker)))
1267 (context (funcall contextfn)))
1268 (cond ((and (not context) newpos
1269 (or (and (not prev-pos) newpos)
1270 (and prev-pos newpos
1271 (funcall poscompfn newpos prev-pos))))
1272 (throw 'found (point-marker)))
1273 ((and newpos context)
1274 (setq prev-pos (point)))
1275 (t (when (not newpos) (goto-char start-pos))
1276 (throw 'found nil))))))))
1278 (defun python-nav--forward-defun (arg)
1279 "Internal implementation of python-nav-{backward,forward}-defun.
1280 Uses ARG to define which function to call, and how many times
1283 (while (and (> arg 0)
1285 (python-nav--syntactically
1288 python-nav-beginning-of-defun-regexp nil t))
1290 (setq arg (1- arg)))
1291 (while (and (< arg 0)
1293 (python-nav--syntactically
1296 python-nav-beginning-of-defun-regexp nil t))
1298 (setq arg (1+ arg)))
1301 (defun python-nav-backward-defun (&optional arg)
1302 "Navigate to closer defun backward ARG times.
1303 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1304 nested definitions."
1306 (python-nav--forward-defun (- (or arg 1))))
1308 (defun python-nav-forward-defun (&optional arg)
1309 "Navigate to closer defun forward ARG times.
1310 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1311 nested definitions."
1313 (python-nav--forward-defun (or arg 1)))
1315 (defun python-nav-beginning-of-statement ()
1316 "Move to start of current statement."
1318 (back-to-indentation)
1319 (let* ((ppss (syntax-ppss))
1322 (python-syntax-context 'paren ppss)
1323 (python-syntax-context 'string ppss))))
1326 (goto-char context-point)
1327 (python-nav-beginning-of-statement))
1330 (python-info-line-ends-backslash-p))
1332 (python-nav-beginning-of-statement))))
1335 (defun python-nav-end-of-statement (&optional noend)
1336 "Move to end of current statement.
1337 Optional argument NOEND is internal and makes the logic to not
1338 jump to the end of line when moving forward searching for the end
1341 (let (string-start bs-pos)
1342 (while (and (or noend (goto-char (line-end-position)))
1344 (cond ((setq string-start (python-syntax-context 'string))
1345 (goto-char string-start)
1346 (if (python-syntax-context 'paren)
1347 ;; Ended up inside a paren, roll again.
1348 (python-nav-end-of-statement t)
1349 ;; This is not inside a paren, move to the
1350 ;; end of this string.
1351 (goto-char (+ (point)
1352 (python-syntax-count-quotes
1353 (char-after (point)) (point))))
1354 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1355 (goto-char (point-max)))))
1356 ((python-syntax-context 'paren)
1357 ;; The statement won't end before we've escaped
1358 ;; at least one level of parenthesis.
1360 (goto-char (scan-lists (point) 1 -1))
1361 (scan-error (goto-char (nth 3 err)))))
1362 ((setq bs-pos (python-info-line-ends-backslash-p))
1364 (forward-line 1))))))
1367 (defun python-nav-backward-statement (&optional arg)
1368 "Move backward to previous statement.
1369 With ARG, repeat. See `python-nav-forward-statement'."
1371 (or arg (setq arg 1))
1372 (python-nav-forward-statement (- arg)))
1374 (defun python-nav-forward-statement (&optional arg)
1375 "Move forward to next statement.
1376 With ARG, repeat. With negative argument, move ARG times
1377 backward to previous statement."
1379 (or arg (setq arg 1))
1381 (python-nav-end-of-statement)
1382 (python-util-forward-comment)
1383 (python-nav-beginning-of-statement)
1384 (setq arg (1- arg)))
1386 (python-nav-beginning-of-statement)
1387 (python-util-forward-comment -1)
1388 (python-nav-beginning-of-statement)
1389 (setq arg (1+ arg))))
1391 (defun python-nav-beginning-of-block ()
1392 "Move to start of current block."
1394 (let ((starting-pos (point)))
1396 (python-nav-beginning-of-statement)
1397 (looking-at (python-rx block-start)))
1399 ;; Go to first line beginning a statement
1400 (while (and (not (bobp))
1401 (or (and (python-nav-beginning-of-statement) nil)
1402 (python-info-current-line-comment-p)
1403 (python-info-current-line-empty-p)))
1405 (let ((block-matching-indent
1406 (- (current-indentation) python-indent-offset)))
1408 (and (python-nav-backward-block)
1409 (> (current-indentation) block-matching-indent)))
1410 (if (and (looking-at (python-rx block-start))
1411 (= (current-indentation) block-matching-indent))
1413 (and (goto-char starting-pos) nil))))))
1415 (defun python-nav-end-of-block ()
1416 "Move to end of current block."
1418 (when (python-nav-beginning-of-block)
1419 (let ((block-indentation (current-indentation)))
1420 (python-nav-end-of-statement)
1421 (while (and (forward-line 1)
1423 (or (and (> (current-indentation) block-indentation)
1424 (or (python-nav-end-of-statement) t))
1425 (python-info-current-line-comment-p)
1426 (python-info-current-line-empty-p))))
1427 (python-util-forward-comment -1)
1430 (defun python-nav-backward-block (&optional arg)
1431 "Move backward to previous block of code.
1432 With ARG, repeat. See `python-nav-forward-block'."
1434 (or arg (setq arg 1))
1435 (python-nav-forward-block (- arg)))
1437 (defun python-nav-forward-block (&optional arg)
1438 "Move forward to next block of code.
1439 With ARG, repeat. With negative argument, move ARG times
1440 backward to previous block."
1442 (or arg (setq arg 1))
1443 (let ((block-start-regexp
1444 (python-rx line-start (* whitespace) block-start))
1445 (starting-pos (point)))
1447 (python-nav-end-of-statement)
1449 (re-search-forward block-start-regexp nil t)
1450 (python-syntax-context-type)))
1451 (setq arg (1- arg)))
1453 (python-nav-beginning-of-statement)
1455 (re-search-backward block-start-regexp nil t)
1456 (python-syntax-context-type)))
1457 (setq arg (1+ arg)))
1458 (python-nav-beginning-of-statement)
1459 (if (not (looking-at (python-rx block-start)))
1460 (and (goto-char starting-pos) nil)
1461 (and (not (= (point) starting-pos)) (point-marker)))))
1463 (defun python-nav--lisp-forward-sexp (&optional arg)
1464 "Standard version `forward-sexp'.
1465 It ignores completely the value of `forward-sexp-function' by
1466 setting it to nil before calling `forward-sexp'. With positive
1467 ARG move forward only one sexp, else move backwards."
1468 (let ((forward-sexp-function)
1469 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1470 (forward-sexp arg)))
1472 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1473 "Safe version of standard `forward-sexp'.
1474 When at end of sexp (i.e. looking at a opening/closing paren)
1475 skips it instead of throwing an error. With positive ARG move
1476 forward only one sexp, else move backwards."
1477 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1479 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1481 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1483 (python-nav--lisp-forward-sexp arg)
1485 (while (and (funcall search-fn paren-regexp nil t)
1486 (python-syntax-context 'paren)))))))
1488 (defun python-nav--forward-sexp (&optional dir safe)
1489 "Move to forward sexp.
1490 With positive optional argument DIR direction move forward, else
1491 backwards. When optional argument SAFE is non-nil do not throw
1492 errors when at end of sexp, skip it instead."
1493 (setq dir (or dir 1))
1495 (let* ((forward-p (if (> dir 0)
1496 (and (setq dir 1) t)
1497 (and (setq dir -1) nil)))
1498 (context-type (python-syntax-context-type)))
1500 ((memq context-type '(string comment))
1501 ;; Inside of a string, get out of it.
1502 (let ((forward-sexp-function))
1503 (forward-sexp dir)))
1504 ((or (eq context-type 'paren)
1505 (and forward-p (looking-at (python-rx open-paren)))
1506 (and (not forward-p)
1507 (eq (syntax-class (syntax-after (1- (point))))
1508 (car (string-to-syntax ")")))))
1509 ;; Inside a paren or looking at it, lisp knows what to do.
1511 (python-nav--lisp-forward-sexp-safe dir)
1512 (python-nav--lisp-forward-sexp dir)))
1514 ;; This part handles the lispy feel of
1515 ;; `python-nav-forward-sexp'. Knowing everything about the
1516 ;; current context and the context of the next sexp tries to
1517 ;; follow the lisp sexp motion commands in a symmetric manner.
1520 ((python-info-beginning-of-block-p) 'block-start)
1521 ((python-info-end-of-block-p) 'block-end)
1522 ((python-info-beginning-of-statement-p) 'statement-start)
1523 ((python-info-end-of-statement-p) 'statement-end)))
1527 (python-nav--lisp-forward-sexp-safe dir)
1528 (python-nav--lisp-forward-sexp dir))
1532 (goto-char next-sexp-pos)
1534 ((python-info-beginning-of-block-p) 'block-start)
1535 ((python-info-end-of-block-p) 'block-end)
1536 ((python-info-beginning-of-statement-p) 'statement-start)
1537 ((python-info-end-of-statement-p) 'statement-end)
1538 ((python-info-statement-starts-block-p) 'starts-block)
1539 ((python-info-statement-ends-block-p) 'ends-block)))))
1541 (cond ((and (not (eobp))
1542 (python-info-current-line-empty-p))
1543 (python-util-forward-comment dir)
1544 (python-nav--forward-sexp dir))
1545 ((eq context 'block-start)
1546 (python-nav-end-of-block))
1547 ((eq context 'statement-start)
1548 (python-nav-end-of-statement))
1549 ((and (memq context '(statement-end block-end))
1550 (eq next-sexp-context 'ends-block))
1551 (goto-char next-sexp-pos)
1552 (python-nav-end-of-block))
1553 ((and (memq context '(statement-end block-end))
1554 (eq next-sexp-context 'starts-block))
1555 (goto-char next-sexp-pos)
1556 (python-nav-end-of-block))
1557 ((memq context '(statement-end block-end))
1558 (goto-char next-sexp-pos)
1559 (python-nav-end-of-statement))
1560 (t (goto-char next-sexp-pos)))
1561 (cond ((and (not (bobp))
1562 (python-info-current-line-empty-p))
1563 (python-util-forward-comment dir)
1564 (python-nav--forward-sexp dir))
1565 ((eq context 'block-end)
1566 (python-nav-beginning-of-block))
1567 ((eq context 'statement-end)
1568 (python-nav-beginning-of-statement))
1569 ((and (memq context '(statement-start block-start))
1570 (eq next-sexp-context 'starts-block))
1571 (goto-char next-sexp-pos)
1572 (python-nav-beginning-of-block))
1573 ((and (memq context '(statement-start block-start))
1574 (eq next-sexp-context 'ends-block))
1575 (goto-char next-sexp-pos)
1576 (python-nav-beginning-of-block))
1577 ((memq context '(statement-start block-start))
1578 (goto-char next-sexp-pos)
1579 (python-nav-beginning-of-statement))
1580 (t (goto-char next-sexp-pos))))))))))
1582 (defun python-nav-forward-sexp (&optional arg)
1583 "Move forward across expressions.
1584 With ARG, do it that many times. Negative arg -N means move
1587 (or arg (setq arg 1))
1589 (python-nav--forward-sexp 1)
1590 (setq arg (1- arg)))
1592 (python-nav--forward-sexp -1)
1593 (setq arg (1+ arg))))
1595 (defun python-nav-backward-sexp (&optional arg)
1596 "Move backward across expressions.
1597 With ARG, do it that many times. Negative arg -N means move
1600 (or arg (setq arg 1))
1601 (python-nav-forward-sexp (- arg)))
1603 (defun python-nav-forward-sexp-safe (&optional arg)
1604 "Move forward safely across expressions.
1605 With ARG, do it that many times. Negative arg -N means move
1608 (or arg (setq arg 1))
1610 (python-nav--forward-sexp 1 t)
1611 (setq arg (1- arg)))
1613 (python-nav--forward-sexp -1 t)
1614 (setq arg (1+ arg))))
1616 (defun python-nav-backward-sexp-safe (&optional arg)
1617 "Move backward safely across expressions.
1618 With ARG, do it that many times. Negative arg -N means move
1621 (or arg (setq arg 1))
1622 (python-nav-forward-sexp-safe (- arg)))
1624 (defun python-nav--up-list (&optional dir)
1625 "Internal implementation of `python-nav-up-list'.
1626 DIR is always 1 or -1 and comes sanitized from
1627 `python-nav-up-list' calls."
1628 (let ((context (python-syntax-context-type))
1629 (forward-p (> dir 0)))
1631 ((memq context '(string comment)))
1632 ((eq context 'paren)
1633 (let ((forward-sexp-function))
1635 ((and forward-p (python-info-end-of-block-p))
1636 (let ((parent-end-pos
1638 (let ((indentation (and
1639 (python-nav-beginning-of-block)
1640 (current-indentation))))
1641 (while (and indentation
1643 (>= (current-indentation) indentation)
1644 (python-nav-backward-block)))
1645 (python-nav-end-of-block)))))
1646 (and (> (or parent-end-pos (point)) (point))
1647 (goto-char parent-end-pos))))
1648 (forward-p (python-nav-end-of-block))
1649 ((and (not forward-p)
1650 (> (current-indentation) 0)
1651 (python-info-beginning-of-block-p))
1652 (let ((prev-block-pos
1654 (let ((indentation (current-indentation)))
1655 (while (and (python-nav-backward-block)
1656 (>= (current-indentation) indentation))))
1658 (and (> (point) prev-block-pos)
1659 (goto-char prev-block-pos))))
1660 ((not forward-p) (python-nav-beginning-of-block)))))
1662 (defun python-nav-up-list (&optional arg)
1663 "Move forward out of one level of parentheses (or blocks).
1664 With ARG, do this that many times.
1665 A negative argument means move backward but still to a less deep spot.
1666 This command assumes point is not in a string or comment."
1668 (or arg (setq arg 1))
1670 (python-nav--up-list 1)
1671 (setq arg (1- arg)))
1673 (python-nav--up-list -1)
1674 (setq arg (1+ arg))))
1676 (defun python-nav-backward-up-list (&optional arg)
1677 "Move backward out of one level of parentheses (or blocks).
1678 With ARG, do this that many times.
1679 A negative argument means move forward but still to a less deep spot.
1680 This command assumes point is not in a string or comment."
1682 (or arg (setq arg 1))
1683 (python-nav-up-list (- arg)))
1685 (defun python-nav-if-name-main ()
1686 "Move point at the beginning the __main__ block.
1687 When \"if __name__ == '__main__':\" is found returns its
1688 position, else returns nil."
1690 (let ((point (point))
1691 (found (catch 'found
1692 (goto-char (point-min))
1693 (while (re-search-forward
1694 (python-rx line-start
1696 "__name__" (+ space)
1698 (group-n 1 (or ?\" ?\'))
1699 "__main__" (backref 1) (* space) ":")
1701 (when (not (python-syntax-context-type))
1703 (throw 'found t))))))
1706 (ignore (goto-char point)))))
1709 ;;; Shell integration
1711 (defcustom python-shell-buffer-name "Python"
1712 "Default buffer name for Python interpreter."
1717 (defcustom python-shell-interpreter "python"
1718 "Default Python interpreter for shell."
1722 (defcustom python-shell-internal-buffer-name "Python Internal"
1723 "Default buffer name for the Internal Python interpreter."
1728 (defcustom python-shell-interpreter-args "-i"
1729 "Default arguments for the Python interpreter."
1733 (defcustom python-shell-interpreter-interactive-arg "-i"
1734 "Interpreter argument to force it to run interactively."
1738 (defcustom python-shell-prompt-detect-enabled t
1739 "Non-nil enables autodetection of interpreter prompts."
1744 (defcustom python-shell-prompt-detect-failure-warning t
1745 "Non-nil enables warnings when detection of prompts fail."
1750 (defcustom python-shell-prompt-input-regexps
1751 '(">>> " "\\.\\.\\. " ; Python
1752 "In \\[[0-9]+\\]: " ; IPython
1753 ;; Using ipdb outside IPython may fail to cleanup and leave static
1754 ;; IPython prompts activated, this adds some safeguard for that.
1755 "In : " "\\.\\.\\.: ")
1756 "List of regular expressions matching input prompts."
1757 :type '(repeat string)
1760 (defcustom python-shell-prompt-output-regexps
1762 "Out\\[[0-9]+\\]: " ; IPython
1763 "Out :") ; ipdb safeguard
1764 "List of regular expressions matching output prompts."
1765 :type '(repeat string)
1768 (defcustom python-shell-prompt-regexp ">>> "
1769 "Regular expression matching top level input prompt of Python shell.
1770 It should not contain a caret (^) at the beginning."
1773 (defcustom python-shell-prompt-block-regexp "\\.\\.\\. "
1774 "Regular expression matching block input prompt of Python shell.
1775 It should not contain a caret (^) at the beginning."
1778 (defcustom python-shell-prompt-output-regexp ""
1779 "Regular expression matching output prompt of Python shell.
1780 It should not contain a caret (^) at the beginning."
1783 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1784 "Regular expression matching pdb input prompt of Python shell.
1785 It should not contain a caret (^) at the beginning."
1788 (defcustom python-shell-enable-font-lock t
1789 "Should syntax highlighting be enabled in the Python shell buffer?
1790 Restart the Python shell after changing this variable for it to take effect."
1795 (defcustom python-shell-process-environment nil
1796 "List of environment variables for Python shell.
1797 This variable follows the same rules as `process-environment'
1798 since it merges with it before the process creation routines are
1799 called. When this variable is nil, the Python shell is run with
1800 the default `process-environment'."
1801 :type '(repeat string)
1805 (defcustom python-shell-extra-pythonpaths nil
1806 "List of extra pythonpaths for Python shell.
1807 The values of this variable are added to the existing value of
1808 PYTHONPATH in the `process-environment' variable."
1809 :type '(repeat string)
1813 (defcustom python-shell-exec-path nil
1814 "List of path to search for binaries.
1815 This variable follows the same rules as `exec-path' since it
1816 merges with it before the process creation routines are called.
1817 When this variable is nil, the Python shell is run with the
1818 default `exec-path'."
1819 :type '(repeat string)
1823 (defcustom python-shell-virtualenv-path nil
1824 "Path to virtualenv root.
1825 This variable, when set to a string, makes the values stored in
1826 `python-shell-process-environment' and `python-shell-exec-path'
1827 to be modified properly so shells are started with the specified
1829 :type '(choice (const nil) string)
1833 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1834 python-ffap-setup-code
1835 python-eldoc-setup-code)
1836 "List of code run by `python-shell-send-setup-codes'."
1837 :type '(repeat symbol)
1841 (defcustom python-shell-compilation-regexp-alist
1842 `((,(rx line-start (1+ (any " \t")) "File \""
1843 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1844 "\", line " (group (1+ digit)))
1846 (,(rx " in file " (group (1+ not-newline)) " on line "
1849 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1850 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1852 "`compilation-error-regexp-alist' for inferior Python."
1853 :type '(alist string)
1856 (defvar python-shell--prompt-calculated-input-regexp nil
1857 "Calculated input prompt regexp for inferior python shell.
1858 Do not set this variable directly, instead use
1859 `python-shell-prompt-set-calculated-regexps'.")
1861 (defvar python-shell--prompt-calculated-output-regexp nil
1862 "Calculated output prompt regexp for inferior python shell.
1863 Do not set this variable directly, instead use
1864 `python-shell-set-prompt-regexp'.")
1866 (defun python-shell-prompt-detect ()
1867 "Detect prompts for the current `python-shell-interpreter'.
1868 When prompts can be retrieved successfully from the
1869 `python-shell-interpreter' run with
1870 `python-shell-interpreter-interactive-arg', returns a list of
1871 three elements, where the first two are input prompts and the
1872 last one is an output prompt. When no prompts can be detected
1873 and `python-shell-prompt-detect-failure-warning' is non-nil,
1874 shows a warning with instructions to avoid hangs and returns nil.
1875 When `python-shell-prompt-detect-enabled' is nil avoids any
1876 detection and just returns nil."
1877 (when python-shell-prompt-detect-enabled
1878 (let* ((process-environment (python-shell-calculate-process-environment))
1879 (exec-path (python-shell-calculate-exec-path))
1882 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1883 ;; JSON is built manually for compatibility
1884 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1889 ;; TODO: improve error handling by using
1890 ;; `condition-case' and displaying the error message to
1891 ;; the user in the no-prompts warning.
1893 (let ((code-file (python-shell--save-temp-file code)))
1894 ;; Use `process-file' as it is remote-host friendly.
1896 (executable-find python-shell-interpreter)
1900 python-shell-interpreter-interactive-arg)
1902 (delete-file code-file)))
1906 (dolist (line (split-string output "\n" t))
1908 ;; Check if current line is a valid JSON array
1909 (and (string= (substring line 0 2) "[\"")
1911 ;; Return prompts as a list, not vector
1912 (append (json-read-from-string line) nil)))))
1913 ;; The list must contain 3 strings, where the first
1914 ;; is the input prompt, the second is the block
1915 ;; prompt and the last one is the output prompt. The
1916 ;; input prompt is the only one that can't be empty.
1917 (when (and (= (length res) 3)
1918 (cl-every #'stringp res)
1919 (not (string= (car res) "")))
1920 (throw 'prompts res))))
1922 (when (and (not prompts)
1923 python-shell-prompt-detect-failure-warning)
1926 "Python shell prompts cannot be detected.\n"
1927 "If your emacs session hangs when starting python shells\n"
1928 "recover with `keyboard-quit' and then try fixing the\n"
1929 "interactive flag for your interpreter by adjusting the\n"
1930 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1931 "matching shell prompts in the directory-local friendly vars:\n"
1932 " + `python-shell-prompt-regexp'\n"
1933 " + `python-shell-prompt-block-regexp'\n"
1934 " + `python-shell-prompt-output-regexp'\n"
1935 "Or alternatively in:\n"
1936 " + `python-shell-prompt-input-regexps'\n"
1937 " + `python-shell-prompt-output-regexps'")))
1940 (defun python-shell-prompt-validate-regexps ()
1941 "Validate all user provided regexps for prompts.
1942 Signals `user-error' if any of these vars contain invalid
1943 regexps: `python-shell-prompt-regexp',
1944 `python-shell-prompt-block-regexp',
1945 `python-shell-prompt-pdb-regexp',
1946 `python-shell-prompt-output-regexp',
1947 `python-shell-prompt-input-regexps',
1948 `python-shell-prompt-output-regexps'."
1949 (dolist (symbol (list 'python-shell-prompt-input-regexps
1950 'python-shell-prompt-output-regexps
1951 'python-shell-prompt-regexp
1952 'python-shell-prompt-block-regexp
1953 'python-shell-prompt-pdb-regexp
1954 'python-shell-prompt-output-regexp))
1955 (dolist (regexp (let ((regexps (symbol-value symbol)))
1959 (when (not (python-util-valid-regexp-p regexp))
1960 (user-error "Invalid regexp %s in `%s'"
1963 (defun python-shell-prompt-set-calculated-regexps ()
1964 "Detect and set input and output prompt regexps.
1965 Build and set the values for `python-shell-input-prompt-regexp'
1966 and `python-shell-output-prompt-regexp' using the values from
1967 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
1968 `python-shell-prompt-pdb-regexp',
1969 `python-shell-prompt-output-regexp',
1970 `python-shell-prompt-input-regexps',
1971 `python-shell-prompt-output-regexps' and detected prompts from
1972 `python-shell-prompt-detect'."
1973 (when (not (and python-shell--prompt-calculated-input-regexp
1974 python-shell--prompt-calculated-output-regexp))
1975 (let* ((detected-prompts (python-shell-prompt-detect))
1977 (output-prompts nil)
1981 (mapconcat #'identity
1984 (let ((length-a (length a))
1985 (length-b (length b)))
1986 (if (= length-a length-b)
1988 (> (length a) (length b))))))
1991 ;; Validate ALL regexps
1992 (python-shell-prompt-validate-regexps)
1993 ;; Collect all user defined input prompts
1994 (dolist (prompt (append python-shell-prompt-input-regexps
1995 (list python-shell-prompt-regexp
1996 python-shell-prompt-block-regexp
1997 python-shell-prompt-pdb-regexp)))
1998 (cl-pushnew prompt input-prompts :test #'string=))
1999 ;; Collect all user defined output prompts
2000 (dolist (prompt (cons python-shell-prompt-output-regexp
2001 python-shell-prompt-output-regexps))
2002 (cl-pushnew prompt output-prompts :test #'string=))
2003 ;; Collect detected prompts if any
2004 (when detected-prompts
2005 (dolist (prompt (butlast detected-prompts))
2006 (setq prompt (regexp-quote prompt))
2007 (cl-pushnew prompt input-prompts :test #'string=))
2008 (cl-pushnew (regexp-quote
2009 (car (last detected-prompts)))
2010 output-prompts :test #'string=))
2011 ;; Set input and output prompt regexps from collected prompts
2012 (setq python-shell--prompt-calculated-input-regexp
2013 (funcall build-regexp input-prompts)
2014 python-shell--prompt-calculated-output-regexp
2015 (funcall build-regexp output-prompts)))))
2017 (defun python-shell-get-process-name (dedicated)
2018 "Calculate the appropriate process name for inferior Python process.
2019 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2020 returns a string with the form
2021 `python-shell-buffer-name'[variable `buffer-file-name'] else
2022 returns the value of `python-shell-buffer-name'."
2026 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
2027 (format "%s" python-shell-buffer-name))))
2030 (defun python-shell-internal-get-process-name ()
2031 "Calculate the appropriate process name for Internal Python process.
2032 The name is calculated from `python-shell-global-buffer-name' and
2033 a hash of all relevant global shell settings in order to ensure
2034 uniqueness for different types of configurations."
2036 python-shell-internal-buffer-name
2039 python-shell-interpreter
2040 python-shell-interpreter-args
2041 python-shell--prompt-calculated-input-regexp
2042 python-shell--prompt-calculated-output-regexp
2043 (mapconcat #'symbol-value python-shell-setup-codes "")
2044 (mapconcat #'identity python-shell-process-environment "")
2045 (mapconcat #'identity python-shell-extra-pythonpaths "")
2046 (mapconcat #'identity python-shell-exec-path "")
2047 (or python-shell-virtualenv-path "")
2048 (mapconcat #'identity python-shell-exec-path "")))))
2050 (defun python-shell-parse-command ()
2051 "Calculate the string used to execute the inferior Python process."
2052 (let ((process-environment (python-shell-calculate-process-environment))
2053 (exec-path (python-shell-calculate-exec-path)))
2055 (executable-find python-shell-interpreter)
2056 python-shell-interpreter-args)))
2058 (defun python-shell-calculate-process-environment ()
2059 "Calculate process environment given `python-shell-virtualenv-path'."
2060 (let ((process-environment (append
2061 python-shell-process-environment
2062 process-environment nil))
2063 (virtualenv (if python-shell-virtualenv-path
2064 (directory-file-name python-shell-virtualenv-path)
2066 (when python-shell-extra-pythonpaths
2067 (setenv "PYTHONPATH"
2069 (mapconcat 'identity
2070 python-shell-extra-pythonpaths
2073 (or (getenv "PYTHONPATH") ""))))
2074 (if (not virtualenv)
2076 (setenv "PYTHONHOME" nil)
2077 (setenv "PATH" (format "%s/bin%s%s"
2078 virtualenv path-separator
2079 (or (getenv "PATH") "")))
2080 (setenv "VIRTUAL_ENV" virtualenv))
2081 process-environment))
2083 (defun python-shell-calculate-exec-path ()
2084 "Calculate exec path given `python-shell-virtualenv-path'."
2085 (let ((path (append python-shell-exec-path
2087 (if (not python-shell-virtualenv-path)
2089 (cons (format "%s/bin"
2090 (directory-file-name python-shell-virtualenv-path))
2093 (defun python-comint-output-filter-function (output)
2094 "Hook run after content is put into comint buffer.
2095 OUTPUT is a string with the contents of the buffer."
2096 (ansi-color-filter-apply output))
2098 (defvar python-shell--parent-buffer nil)
2100 (defvar python-shell-output-syntax-table
2101 (let ((table (make-syntax-table python-dotty-syntax-table)))
2102 (modify-syntax-entry ?\' "." table)
2103 (modify-syntax-entry ?\" "." table)
2104 (modify-syntax-entry ?\( "." table)
2105 (modify-syntax-entry ?\[ "." table)
2106 (modify-syntax-entry ?\{ "." table)
2107 (modify-syntax-entry ?\) "." table)
2108 (modify-syntax-entry ?\] "." table)
2109 (modify-syntax-entry ?\} "." table)
2111 "Syntax table for shell output.
2112 It makes parens and quotes be treated as punctuation chars.")
2114 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2115 "Major mode for Python inferior process.
2116 Runs a Python interpreter as a subprocess of Emacs, with Python
2117 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2118 and `python-shell-interpreter-args' control which Python
2119 interpreter is run. Variables
2120 `python-shell-prompt-regexp',
2121 `python-shell-prompt-output-regexp',
2122 `python-shell-prompt-block-regexp',
2123 `python-shell-enable-font-lock',
2124 `python-shell-completion-setup-code',
2125 `python-shell-completion-string-code',
2126 `python-shell-completion-module-string-code',
2127 `python-eldoc-setup-code', `python-eldoc-string-code',
2128 `python-ffap-setup-code' and `python-ffap-string-code' can
2129 customize this mode for different Python interpreters.
2131 You can also add additional setup code to be run at
2132 initialization of the interpreter via `python-shell-setup-codes'
2135 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2136 (let ((interpreter python-shell-interpreter)
2137 (args python-shell-interpreter-args))
2138 (when python-shell--parent-buffer
2139 (python-util-clone-local-variables python-shell--parent-buffer))
2140 ;; Users can override default values for these vars when calling
2141 ;; `run-python'. This ensures new values let-bound in
2142 ;; `python-shell-make-comint' are locally set.
2143 (set (make-local-variable 'python-shell-interpreter) interpreter)
2144 (set (make-local-variable 'python-shell-interpreter-args) args))
2145 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2146 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2147 (python-shell-prompt-set-calculated-regexps)
2148 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp)
2149 (setq mode-line-process '(":%s"))
2150 (make-local-variable 'comint-output-filter-functions)
2151 (add-hook 'comint-output-filter-functions
2152 'python-comint-output-filter-function)
2153 (add-hook 'comint-output-filter-functions
2154 'python-pdbtrack-comint-output-filter-function)
2155 (set (make-local-variable 'compilation-error-regexp-alist)
2156 python-shell-compilation-regexp-alist)
2157 (define-key inferior-python-mode-map [remap complete-symbol]
2158 'completion-at-point)
2159 (add-hook 'completion-at-point-functions
2160 'python-shell-completion-complete-at-point nil 'local)
2161 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
2162 'python-shell-completion-complete-at-point)
2163 (define-key inferior-python-mode-map "\t"
2164 'python-shell-completion-complete-or-indent)
2165 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2166 (make-local-variable 'python-pdbtrack-tracked-buffer)
2167 (make-local-variable 'python-shell-internal-last-output)
2168 (when python-shell-enable-font-lock
2169 (set-syntax-table python-mode-syntax-table)
2170 (set (make-local-variable 'font-lock-defaults)
2171 '(python-font-lock-keywords nil nil nil nil))
2172 (set (make-local-variable 'syntax-propertize-function)
2174 ;; XXX: Unfortunately eval is needed here to make use of the
2175 ;; dynamic value of `comint-prompt-regexp'.
2176 `(syntax-propertize-rules
2177 (,comint-prompt-regexp
2180 comint-last-input-start end 'syntax-table
2181 python-shell-output-syntax-table)
2182 ;; XXX: This might look weird, but it is the easiest
2183 ;; way to ensure font lock gets cleaned up before the
2184 ;; current prompt, which is needed for unclosed
2185 ;; strings to not mess up with current input.
2186 (font-lock-unfontify-region comint-last-input-start end))))
2187 (,(python-rx string-delimiter)
2189 (and (not (eq (get-text-property start 'field) 'output))
2190 (python-syntax-stringify)))))))))
2191 (compilation-shell-minor-mode 1))
2193 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
2194 "Create a Python shell comint buffer.
2195 CMD is the Python command to be executed and PROC-NAME is the
2196 process name the comint buffer will get. After the comint buffer
2197 is created the `inferior-python-mode' is activated. When
2198 optional argument POP is non-nil the buffer is shown. When
2199 optional argument INTERNAL is non-nil this process is run on a
2200 buffer with a name that starts with a space, following the Emacs
2201 convention for temporary/internal buffers, and also makes sure
2202 the user is not queried for confirmation when the process is
2205 (let* ((proc-buffer-name
2206 (format (if (not internal) "*%s*" " *%s*") proc-name))
2207 (process-environment (python-shell-calculate-process-environment))
2208 (exec-path (python-shell-calculate-exec-path)))
2209 (when (not (comint-check-proc proc-buffer-name))
2210 (let* ((cmdlist (split-string-and-unquote cmd))
2211 (interpreter (car cmdlist))
2212 (args (cdr cmdlist))
2213 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2214 interpreter nil args))
2215 (python-shell--parent-buffer (current-buffer))
2216 (process (get-buffer-process buffer))
2217 ;; As the user may have overriden default values for
2218 ;; these vars on `run-python', let-binding them allows
2219 ;; to have the new right values in all setup code
2220 ;; that's is done in `inferior-python-mode', which is
2221 ;; important, especially for prompt detection.
2222 (python-shell-interpreter interpreter)
2223 (python-shell-interpreter-args
2224 (mapconcat #'identity args " ")))
2225 (with-current-buffer buffer
2226 (inferior-python-mode))
2227 (accept-process-output process)
2228 (and pop (pop-to-buffer buffer t))
2229 (and internal (set-process-query-on-exit-flag process nil))))
2233 (defun run-python (cmd &optional dedicated show)
2234 "Run an inferior Python process.
2235 Input and output via buffer named after
2236 `python-shell-buffer-name'. If there is a process already
2237 running in that buffer, just switch to it.
2239 With argument, allows you to define CMD so you can edit the
2240 command used to call the interpreter and define DEDICATED, so a
2241 dedicated process for the current buffer is open. When numeric
2242 prefix arg is other than 0 or 4 do not SHOW.
2244 Runs the hook `inferior-python-mode-hook' after
2245 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2246 process buffer for a list of commands.)"
2248 (if current-prefix-arg
2250 (read-shell-command "Run Python: " (python-shell-parse-command))
2251 (y-or-n-p "Make dedicated process? ")
2252 (= (prefix-numeric-value current-prefix-arg) 4))
2253 (list (python-shell-parse-command) nil t)))
2254 (python-shell-make-comint
2255 cmd (python-shell-get-process-name dedicated) show)
2258 (defun run-python-internal ()
2259 "Run an inferior Internal Python process.
2260 Input and output via buffer named after
2261 `python-shell-internal-buffer-name' and what
2262 `python-shell-internal-get-process-name' returns.
2264 This new kind of shell is intended to be used for generic
2265 communication related to defined configurations; the main
2266 difference with global or dedicated shells is that these ones are
2267 attached to a configuration, not a buffer. This means that can
2268 be used for example to retrieve the sys.path and other stuff,
2269 without messing with user shells. Note that
2270 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
2271 are set to nil for these shells, so setup codes are not sent at
2273 (let ((python-shell-enable-font-lock nil)
2274 (inferior-python-mode-hook nil))
2276 (python-shell-make-comint
2277 (python-shell-parse-command)
2278 (python-shell-internal-get-process-name) nil t))))
2280 (defun python-shell-get-buffer ()
2281 "Return inferior Python buffer for current buffer."
2282 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2283 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2284 (global-proc-name (python-shell-get-process-name nil))
2285 (global-proc-buffer-name (format "*%s*" global-proc-name))
2286 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2287 (global-running (comint-check-proc global-proc-buffer-name)))
2288 ;; Always prefer dedicated
2289 (or (and dedicated-running dedicated-proc-buffer-name)
2290 (and global-running global-proc-buffer-name))))
2292 (defun python-shell-get-process ()
2293 "Return inferior Python process for current buffer."
2294 (get-buffer-process (python-shell-get-buffer)))
2296 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2297 "Get or create an inferior Python process for current buffer and return it.
2298 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2299 are used to start the shell. If those arguments are not
2300 provided, `run-python' is called interactively and the user will
2301 be asked for their values."
2302 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2303 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2304 (global-proc-name (python-shell-get-process-name nil))
2305 (global-proc-buffer-name (format "*%s*" global-proc-name))
2306 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2307 (global-running (comint-check-proc global-proc-buffer-name)))
2308 (when (and (not dedicated-running) (not global-running))
2310 ;; XXX: Refactor code such that calling `run-python'
2311 ;; interactively is not needed anymore.
2312 (call-interactively 'run-python)
2313 (run-python cmd dedicated show))
2314 (setq dedicated-running t)
2315 (setq global-running t)))
2316 ;; Always prefer dedicated
2317 (get-buffer-process (if dedicated-running
2318 dedicated-proc-buffer-name
2319 global-proc-buffer-name))))
2321 (defvar python-shell-internal-buffer nil
2322 "Current internal shell buffer for the current buffer.
2323 This is really not necessary at all for the code to work but it's
2324 there for compatibility with CEDET.")
2326 (defvar python-shell-internal-last-output nil
2327 "Last output captured by the internal shell.
2328 This is really not necessary at all for the code to work but it's
2329 there for compatibility with CEDET.")
2331 (defun python-shell-internal-get-or-create-process ()
2332 "Get or create an inferior Internal Python process."
2333 (let* ((proc-name (python-shell-internal-get-process-name))
2334 (proc-buffer-name (format " *%s*" proc-name)))
2335 (when (not (process-live-p proc-name))
2336 (run-python-internal)
2337 (setq python-shell-internal-buffer proc-buffer-name)
2338 ;; XXX: Why is this `sit-for' needed?
2339 ;; `python-shell-make-comint' calls `accept-process-output'
2340 ;; already but it is not helping to get proper output on
2341 ;; 'gnu/linux when the internal shell process is not running and
2342 ;; a call to `python-shell-internal-send-string' is issued.
2344 (get-buffer-process proc-buffer-name)))
2346 (define-obsolete-function-alias
2347 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2349 (define-obsolete-variable-alias
2350 'python-buffer 'python-shell-internal-buffer "24.3")
2352 (define-obsolete-variable-alias
2353 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2355 (defun python-shell--save-temp-file (string)
2356 (let* ((temporary-file-directory
2357 (if (file-remote-p default-directory)
2358 (concat (file-remote-p default-directory) "/tmp")
2359 temporary-file-directory))
2360 (temp-file-name (make-temp-file "py"))
2361 (coding-system-for-write 'utf-8))
2362 (with-temp-file temp-file-name
2363 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2365 (delete-trailing-whitespace))
2368 (defun python-shell-send-string (string &optional process)
2369 "Send STRING to inferior Python PROCESS."
2370 (interactive "sPython command: ")
2371 (let ((process (or process (python-shell-get-or-create-process))))
2372 (if (string-match ".\n+." string) ;Multiline.
2373 (let* ((temp-file-name (python-shell--save-temp-file string)))
2374 (python-shell-send-file temp-file-name process temp-file-name t))
2375 (comint-send-string process string)
2376 (when (or (not (string-match "\n\\'" string))
2377 (string-match "\n[ \t].*\n?\\'" string))
2378 (comint-send-string process "\n")))))
2380 (defvar python-shell-output-filter-in-progress nil)
2381 (defvar python-shell-output-filter-buffer nil)
2383 (defun python-shell-output-filter (string)
2384 "Filter used in `python-shell-send-string-no-output' to grab output.
2385 STRING is the output received to this point from the process.
2386 This filter saves received output from the process in
2387 `python-shell-output-filter-buffer' and stops receiving it after
2388 detecting a prompt at the end of the buffer."
2390 string (ansi-color-filter-apply string)
2391 python-shell-output-filter-buffer
2392 (concat python-shell-output-filter-buffer string))
2394 ;; XXX: It seems on OSX an extra carriage return is attached
2395 ;; at the end of output, this handles that too.
2398 ;; Remove initial caret from calculated regexp
2399 (replace-regexp-in-string
2400 (rx string-start ?^) ""
2401 python-shell--prompt-calculated-input-regexp)
2403 python-shell-output-filter-buffer)
2404 ;; Output ends when `python-shell-output-filter-buffer' contains
2405 ;; the prompt attached at the end of it.
2406 (setq python-shell-output-filter-in-progress nil
2407 python-shell-output-filter-buffer
2408 (substring python-shell-output-filter-buffer
2409 0 (match-beginning 0)))
2411 python-shell--prompt-calculated-output-regexp
2412 python-shell-output-filter-buffer)
2413 ;; Some shells, like IPython might append a prompt before the
2414 ;; output, clean that.
2415 (setq python-shell-output-filter-buffer
2416 (substring python-shell-output-filter-buffer (match-end 0)))))
2419 (defun python-shell-send-string-no-output (string &optional process)
2420 "Send STRING to PROCESS and inhibit output.
2422 (let ((process (or process (python-shell-get-or-create-process)))
2423 (comint-preoutput-filter-functions
2424 '(python-shell-output-filter))
2425 (python-shell-output-filter-in-progress t)
2429 (python-shell-send-string string process)
2430 (while python-shell-output-filter-in-progress
2431 ;; `python-shell-output-filter' takes care of setting
2432 ;; `python-shell-output-filter-in-progress' to NIL after it
2433 ;; detects end of output.
2434 (accept-process-output process))
2436 python-shell-output-filter-buffer
2437 (setq python-shell-output-filter-buffer nil)))
2438 (with-current-buffer (process-buffer process)
2439 (comint-interrupt-subjob)))))
2441 (defun python-shell-internal-send-string (string)
2442 "Send STRING to the Internal Python interpreter.
2443 Returns the output. See `python-shell-send-string-no-output'."
2444 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2445 ;; updated to support this new mode.
2446 (setq python-shell-internal-last-output
2447 (python-shell-send-string-no-output
2448 ;; Makes this function compatible with the old
2449 ;; python-send-receive. (At least for CEDET).
2450 (replace-regexp-in-string "_emacs_out +" "" string)
2451 (python-shell-internal-get-or-create-process))))
2453 (define-obsolete-function-alias
2454 'python-send-receive 'python-shell-internal-send-string "24.3")
2456 (define-obsolete-function-alias
2457 'python-send-string 'python-shell-internal-send-string "24.3")
2459 (defvar python--use-fake-loc nil
2460 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2461 If nil, regions of text are prepended by the corresponding number of empty
2462 lines and Python is told to output error messages referring to the whole
2465 (defun python-shell-buffer-substring (start end &optional nomain)
2466 "Send buffer substring from START to END formatted for shell.
2467 This is a wrapper over `buffer-substring' that takes care of
2468 different transformations for the code sent to be evaluated in
2470 1. When optional argument NOMAIN is non-nil everything under an
2471 \"if __name__ == '__main__'\" block will be removed.
2472 2. When a subregion of the buffer is sent, it takes care of
2473 appending extra empty lines so tracebacks are correct.
2474 3. Wraps indented regions under an \"if True:\" block so the
2475 interpreter evaluates them correctly."
2476 (let ((substring (buffer-substring-no-properties start end))
2477 (fillstr (unless python--use-fake-loc
2478 (make-string (1- (line-number-at-pos start)) ?\n)))
2479 (toplevel-block-p (save-excursion
2481 (or (zerop (line-number-at-pos start))
2483 (python-util-forward-comment 1)
2484 (zerop (current-indentation)))))))
2487 (if fillstr (insert fillstr))
2489 (goto-char (point-min))
2490 (unless python--use-fake-loc
2491 ;; python-shell--save-temp-file adds an extra coding line, which would
2492 ;; throw off the line-counts, so let's try to compensate here.
2493 (if (looking-at "[ \t]*[#\n]")
2494 (delete-region (point) (line-beginning-position 2))))
2495 (when (not toplevel-block-p)
2497 (delete-region (point) (line-end-position)))
2499 (let* ((if-name-main-start-end
2502 (when (python-nav-if-name-main)
2504 (progn (python-nav-forward-sexp-safe)
2506 ;; Oh destructuring bind, how I miss you.
2507 (if-name-main-start (car if-name-main-start-end))
2508 (if-name-main-end (cdr if-name-main-start-end)))
2509 (when if-name-main-start-end
2510 (goto-char if-name-main-start)
2511 (delete-region if-name-main-start if-name-main-end)
2514 (- (line-number-at-pos if-name-main-end)
2515 (line-number-at-pos if-name-main-start)) ?\n)))))
2516 (buffer-substring-no-properties (point-min) (point-max)))))
2518 (declare-function compilation-fake-loc "compile"
2519 (marker file &optional line col))
2521 (defun python-shell-send-region (start end &optional nomain)
2522 "Send the region delimited by START and END to inferior Python process."
2524 (let* ((python--use-fake-loc
2525 (or python--use-fake-loc (not buffer-file-name)))
2526 (string (python-shell-buffer-substring start end nomain))
2527 (process (python-shell-get-or-create-process))
2528 (_ (string-match "\\`\n*\\(.*\\)" string)))
2529 (message "Sent: %s..." (match-string 1 string))
2530 (let* ((temp-file-name (python-shell--save-temp-file string))
2531 (file-name (or (buffer-file-name) temp-file-name)))
2532 (python-shell-send-file file-name process temp-file-name t)
2533 (unless python--use-fake-loc
2534 (with-current-buffer (process-buffer process)
2535 (compilation-fake-loc (copy-marker start) temp-file-name
2536 2)) ;; Not 1, because of the added coding line.
2539 (defun python-shell-send-buffer (&optional arg)
2540 "Send the entire buffer to inferior Python process.
2541 With prefix ARG allow execution of code inside blocks delimited
2542 by \"if __name__== '__main__':\"."
2546 (python-shell-send-region (point-min) (point-max) (not arg))))
2548 (defun python-shell-send-defun (arg)
2549 "Send the current defun to inferior Python process.
2550 When argument ARG is non-nil do not include decorators."
2553 (python-shell-send-region
2556 (while (and (or (python-nav-beginning-of-defun)
2557 (beginning-of-line 1))
2558 (> (current-indentation) 0)))
2560 (while (and (forward-line -1)
2561 (looking-at (python-rx decorator))))
2565 (or (python-nav-end-of-defun)
2569 (defun python-shell-send-file (file-name &optional process temp-file-name
2571 "Send FILE-NAME to inferior Python PROCESS.
2572 If TEMP-FILE-NAME is passed then that file is used for processing
2573 instead, while internally the shell will continue to use FILE-NAME.
2574 If DELETE is non-nil, delete the file afterwards."
2575 (interactive "fFile to send: ")
2576 (let* ((process (or process (python-shell-get-or-create-process)))
2577 (temp-file-name (when temp-file-name
2579 (or (file-remote-p temp-file-name 'localname)
2581 (file-name (or (when file-name
2583 (or (file-remote-p file-name 'localname)
2586 (when (not file-name)
2587 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2588 (python-shell-send-string
2590 (concat "__pyfile = open('''%s''');"
2591 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2592 "__pyfile.close()%s")
2593 (or temp-file-name file-name) file-name
2594 (if delete (format "; import os; os.remove('''%s''')"
2595 (or temp-file-name file-name))
2599 (defun python-shell-switch-to-shell ()
2600 "Switch to inferior Python process buffer."
2602 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2604 (defun python-shell-send-setup-code ()
2605 "Send all setup code for shell.
2606 This function takes the list of setup code to send from the
2607 `python-shell-setup-codes' list."
2608 (let ((process (get-buffer-process (current-buffer))))
2609 (dolist (code python-shell-setup-codes)
2611 (message "Sent %s" code)
2612 (python-shell-send-string
2613 (symbol-value code) process)))))
2615 (add-hook 'inferior-python-mode-hook
2616 #'python-shell-send-setup-code)
2619 ;;; Shell completion
2621 (defcustom python-shell-completion-setup-code
2623 import readline, rlcompleter
2625 def __PYTHON_EL_get_completions(text):
2628 def __PYTHON_EL_get_completions(text):
2631 splits = text.split()
2632 is_module = splits and splits[0] in ('from', 'import')
2633 is_ipython = getattr(
2634 __builtins__, '__IPYTHON__',
2635 getattr(__builtins__, '__IPYTHON__active', False))
2637 from IPython.core.completerlib import module_completion
2638 completions = module_completion(text.strip())
2639 elif is_ipython and getattr(__builtins__, '__IP', None):
2640 completions = __IP.complete(text)
2641 elif is_ipython and getattr(__builtins__, 'get_ipython', None):
2642 completions = get_ipython().Completer.all_completions(text)
2646 res = readline.get_completer()(text, i)
2650 completions.append(res)
2654 "Code used to setup completion in inferior Python processes."
2658 (defcustom python-shell-completion-string-code
2659 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2660 "Python code used to get a string of completions separated by semicolons.
2661 The string passed to the function is the current python name or
2662 the full statement in the case of imports."
2666 (define-obsolete-variable-alias
2667 'python-shell-completion-module-string-code
2668 'python-shell-completion-string-code
2670 "Completion string code must also autocomplete modules.")
2672 (defcustom python-shell-completion-pdb-string-code
2673 "';'.join(globals().keys() + locals().keys())"
2674 "Python code used to get completions separated by semicolons for [i]pdb."
2678 (defun python-shell-completion-get-completions (process line input)
2679 "Do completion at point for PROCESS.
2680 LINE is used to detect the context on how to complete given INPUT."
2682 ;; Get last prompt of the inferior process buffer (this
2683 ;; intentionally avoids using `comint-last-prompt' because
2684 ;; of incompatibilities with Emacs 24.x).
2685 (with-current-buffer (process-buffer process)
2687 (buffer-substring-no-properties
2688 (- (point) (length line))
2690 (re-search-backward "^")
2691 (python-util-forward-comment)
2694 ;; Check whether a prompt matches a pdb string, an import
2695 ;; statement or just the standard prompt and use the
2696 ;; correct python-shell-completion-*-code string
2697 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2699 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2700 python-shell-completion-pdb-string-code)
2702 python-shell--prompt-calculated-input-regexp prompt)
2703 python-shell-completion-string-code)
2707 (python-rx (+ space) (or "from" "import") space)
2711 (and completion-code
2712 (> (length input) 0)
2713 (with-current-buffer (process-buffer process)
2715 (python-util-strip-string
2716 (python-shell-send-string-no-output
2717 (format completion-code input) process))))
2718 (and (> (length completions) 2)
2719 (split-string completions
2720 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2722 (defun python-shell-completion-complete-at-point (&optional process)
2723 "Perform completion at point in inferior Python.
2724 Optional argument PROCESS forces completions to be retrieved
2725 using that one instead of current buffer's process."
2726 (setq process (or process (get-buffer-process (current-buffer))))
2729 (with-syntax-table python-dotty-syntax-table
2730 (let* ((paren-depth (car (syntax-ppss)))
2731 (syntax-string "w_")
2732 (syntax-list (string-to-syntax syntax-string)))
2733 ;; Stop scanning for the beginning of the completion
2734 ;; subject after the char before point matches a
2737 (car (syntax-after (1- (point)))) syntax-list)
2738 (skip-syntax-backward syntax-string)
2739 (when (or (equal (char-before) ?\))
2740 (equal (char-before) ?\"))
2743 ;; honor initial paren depth
2744 (> (car (syntax-ppss)) paren-depth)
2745 (python-syntax-context 'string))
2750 (completion-table-dynamic
2752 #'python-shell-completion-get-completions
2753 process (buffer-substring-no-properties
2754 (line-beginning-position) end))))))
2756 (defun python-shell-completion-complete-or-indent ()
2757 "Complete or indent depending on the context.
2758 If content before pointer is all whitespace, indent.
2759 If not try to complete."
2761 (if (string-match "^[[:space:]]*$"
2762 (buffer-substring (comint-line-beginning-position)
2764 (indent-for-tab-command)
2765 (completion-at-point)))
2768 ;;; PDB Track integration
2770 (defcustom python-pdbtrack-activate t
2771 "Non-nil makes Python shell enable pdbtracking."
2776 (defcustom python-pdbtrack-stacktrace-info-regexp
2777 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2778 "Regular expression matching stacktrace information.
2779 Used to extract the current line and module being inspected."
2784 (defvar python-pdbtrack-tracked-buffer nil
2785 "Variable containing the value of the current tracked buffer.
2786 Never set this variable directly, use
2787 `python-pdbtrack-set-tracked-buffer' instead.")
2789 (defvar python-pdbtrack-buffers-to-kill nil
2790 "List of buffers to be deleted after tracking finishes.")
2792 (defun python-pdbtrack-set-tracked-buffer (file-name)
2793 "Set the buffer for FILE-NAME as the tracked buffer.
2794 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2795 Returns the tracked buffer."
2796 (let ((file-buffer (get-file-buffer
2797 (concat (file-remote-p default-directory)
2800 (setq python-pdbtrack-tracked-buffer file-buffer)
2801 (setq file-buffer (find-file-noselect file-name))
2802 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2803 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2806 (defun python-pdbtrack-comint-output-filter-function (output)
2807 "Move overlay arrow to current pdb line in tracked buffer.
2808 Argument OUTPUT is a string with the output from the comint process."
2809 (when (and python-pdbtrack-activate (not (string= output "")))
2810 (let* ((full-output (ansi-color-filter-apply
2811 (buffer-substring comint-last-input-end (point-max))))
2815 (insert full-output)
2816 ;; When the debugger encounters a pdb.set_trace()
2817 ;; command, it prints a single stack frame. Sometimes
2818 ;; it prints a bit of extra information about the
2819 ;; arguments of the present function. When ipdb
2820 ;; encounters an exception, it prints the _entire_ stack
2821 ;; trace. To handle all of these cases, we want to find
2822 ;; the _last_ stack frame printed in the most recent
2823 ;; batch of output, then jump to the corresponding
2824 ;; file/line number.
2825 (goto-char (point-max))
2826 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
2827 (setq line-number (string-to-number
2828 (match-string-no-properties 2)))
2829 (match-string-no-properties 1)))))
2830 (if (and file-name line-number)
2831 (let* ((tracked-buffer
2832 (python-pdbtrack-set-tracked-buffer file-name))
2833 (shell-buffer (current-buffer))
2834 (tracked-buffer-window (get-buffer-window tracked-buffer))
2835 (tracked-buffer-line-pos))
2836 (with-current-buffer tracked-buffer
2837 (set (make-local-variable 'overlay-arrow-string) "=>")
2838 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2839 (setq tracked-buffer-line-pos (progn
2840 (goto-char (point-min))
2841 (forward-line (1- line-number))
2843 (when tracked-buffer-window
2845 tracked-buffer-window tracked-buffer-line-pos))
2846 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2847 (pop-to-buffer tracked-buffer)
2848 (switch-to-buffer-other-window shell-buffer))
2849 (when python-pdbtrack-tracked-buffer
2850 (with-current-buffer python-pdbtrack-tracked-buffer
2851 (set-marker overlay-arrow-position nil))
2852 (mapc #'(lambda (buffer)
2853 (ignore-errors (kill-buffer buffer)))
2854 python-pdbtrack-buffers-to-kill)
2855 (setq python-pdbtrack-tracked-buffer nil
2856 python-pdbtrack-buffers-to-kill nil)))))
2860 ;;; Symbol completion
2862 (defun python-completion-complete-at-point ()
2863 "Complete current symbol at point.
2864 For this to work as best as possible you should call
2865 `python-shell-send-buffer' from time to time so context in
2866 inferior Python process is updated properly."
2867 (let ((process (python-shell-get-process)))
2869 (error "Completion needs an inferior Python process running")
2870 (python-shell-completion-complete-at-point process))))
2872 (add-to-list 'debug-ignored-errors
2873 "^Completion needs an inferior Python process running.")
2878 (defcustom python-fill-comment-function 'python-fill-comment
2879 "Function to fill comments.
2880 This is the function used by `python-fill-paragraph' to
2885 (defcustom python-fill-string-function 'python-fill-string
2886 "Function to fill strings.
2887 This is the function used by `python-fill-paragraph' to
2892 (defcustom python-fill-decorator-function 'python-fill-decorator
2893 "Function to fill decorators.
2894 This is the function used by `python-fill-paragraph' to
2899 (defcustom python-fill-paren-function 'python-fill-paren
2900 "Function to fill parens.
2901 This is the function used by `python-fill-paragraph' to
2906 (defcustom python-fill-docstring-style 'pep-257
2907 "Style used to fill docstrings.
2908 This affects `python-fill-string' behavior with regards to
2909 triple quotes positioning.
2911 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
2912 `symmetric', and nil. A value of nil won't care about quotes
2913 position and will treat docstrings a normal string, any other
2914 value may result in one of the following docstring styles:
2919 Process foo, return bar.
2923 Process foo, return bar.
2925 If processing fails throw ProcessingError.
2930 \"\"\"Process foo, return bar.\"\"\"
2933 Process foo, return bar.
2935 If processing fails throw ProcessingError.
2941 \"\"\"Process foo, return bar.\"\"\"
2943 \"\"\"Process foo, return bar.
2945 If processing fails throw ProcessingError.
2951 \"\"\"Process foo, return bar.\"\"\"
2953 \"\"\"Process foo, return bar.
2955 If processing fails throw ProcessingError.
2960 \"\"\"Process foo, return bar.\"\"\"
2963 Process foo, return bar.
2965 If processing fails throw ProcessingError.
2968 (const :tag "Don't format docstrings" nil)
2969 (const :tag "Django's coding standards style." django)
2970 (const :tag "One newline and start and Two at end style." onetwo)
2971 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2972 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2973 (const :tag "Symmetric style." symmetric))
2976 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2978 (defun python-fill-paragraph (&optional justify)
2979 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2980 If any of the current line is in or at the end of a multi-line string,
2981 fill the string or the paragraph of it that point is in, preserving
2982 the string's indentation.
2983 Optional argument JUSTIFY defines if the paragraph should be justified."
2988 ((python-syntax-context 'comment)
2989 (funcall python-fill-comment-function justify))
2990 ;; Strings/Docstrings
2991 ((save-excursion (or (python-syntax-context 'string)
2992 (equal (string-to-syntax "|")
2993 (syntax-after (point)))))
2994 (funcall python-fill-string-function justify))
2996 ((equal (char-after (save-excursion
2997 (python-nav-beginning-of-statement))) ?@)
2998 (funcall python-fill-decorator-function justify))
3000 ((or (python-syntax-context 'paren)
3001 (looking-at (python-rx open-paren))
3003 (skip-syntax-forward "^(" (line-end-position))
3004 (looking-at (python-rx open-paren))))
3005 (funcall python-fill-paren-function justify))
3008 (defun python-fill-comment (&optional justify)
3009 "Comment fill function for `python-fill-paragraph'.
3010 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3011 (fill-comment-paragraph justify))
3013 (defun python-fill-string (&optional justify)
3014 "String fill function for `python-fill-paragraph'.
3015 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3016 (let* ((str-start-pos
3019 (or (python-syntax-context 'string)
3020 (and (equal (string-to-syntax "|")
3021 (syntax-after (point)))
3023 (num-quotes (python-syntax-count-quotes
3024 (char-after str-start-pos) str-start-pos))
3027 (goto-char (+ str-start-pos num-quotes))
3028 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3029 (goto-char (point-max)))
3032 ;; Docstring styles may vary for oneliners and multi-liners.
3033 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3035 (pcase python-fill-docstring-style
3036 ;; delimiters-style is a cons cell with the form
3037 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3038 ;; is NIL means to not add any newlines for start or end
3039 ;; of docstring. See `python-fill-docstring-style' for a
3040 ;; graphic idea of each style.
3041 (`django (cons 1 1))
3042 (`onetwo (and multi-line-p (cons 1 2)))
3043 (`pep-257 (and multi-line-p (cons nil 2)))
3044 (`pep-257-nn (and multi-line-p (cons nil 1)))
3045 (`symmetric (and multi-line-p (cons 1 1)))))
3046 (docstring-p (save-excursion
3047 ;; Consider docstrings those strings which
3048 ;; start on a line by themselves.
3049 (python-nav-beginning-of-statement)
3050 (and (= (point) str-start-pos))))
3051 (fill-paragraph-function))
3053 (narrow-to-region str-start-pos str-end-pos)
3054 (fill-paragraph justify))
3056 (when (and docstring-p python-fill-docstring-style)
3057 ;; Add the number of newlines indicated by the selected style
3058 ;; at the start of the docstring.
3059 (goto-char (+ str-start-pos num-quotes))
3060 (delete-region (point) (progn
3061 (skip-syntax-forward "> ")
3063 (and (car delimiters-style)
3064 (or (newline (car delimiters-style)) t)
3065 ;; Indent only if a newline is added.
3066 (indent-according-to-mode))
3067 ;; Add the number of newlines indicated by the selected style
3068 ;; at the end of the docstring.
3069 (goto-char (if (not (= str-end-pos (point-max)))
3070 (- str-end-pos num-quotes)
3072 (delete-region (point) (progn
3073 (skip-syntax-backward "> ")
3075 (and (cdr delimiters-style)
3076 ;; Add newlines only if string ends.
3077 (not (= str-end-pos (point-max)))
3078 (or (newline (cdr delimiters-style)) t)
3079 ;; Again indent only if a newline is added.
3080 (indent-according-to-mode))))) t)
3082 (defun python-fill-decorator (&optional _justify)
3083 "Decorator fill function for `python-fill-paragraph'.
3084 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3087 (defun python-fill-paren (&optional justify)
3088 "Paren fill function for `python-fill-paragraph'.
3089 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3091 (narrow-to-region (progn
3092 (while (python-syntax-context 'paren)
3093 (goto-char (1- (point-marker))))
3095 (line-beginning-position))
3097 (when (not (python-syntax-context 'paren))
3099 (when (not (python-syntax-context 'paren))
3100 (skip-syntax-backward "^)")))
3101 (while (python-syntax-context 'paren)
3102 (goto-char (1+ (point-marker))))
3104 (let ((paragraph-start "\f\\|[ \t]*$")
3105 (paragraph-separate ",")
3106 (fill-paragraph-function))
3107 (goto-char (point-min))
3108 (fill-paragraph justify))
3111 (python-indent-line)
3112 (goto-char (line-end-position)))) t)
3117 (defcustom python-skeleton-autoinsert nil
3118 "Non-nil means template skeletons will be automagically inserted.
3119 This happens when pressing \"if<SPACE>\", for example, to prompt for
3125 (define-obsolete-variable-alias
3126 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3128 (defvar python-skeleton-available '()
3129 "Internal list of available skeletons.")
3131 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3132 "Abbrev table for Python mode skeletons."
3134 ;; Allow / inside abbrevs.
3135 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3136 ;; Only expand in code.
3137 :enable-function (lambda ()
3139 (not (python-syntax-comment-or-string-p))
3140 python-skeleton-autoinsert)))
3142 (defmacro python-skeleton-define (name doc &rest skel)
3143 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3144 The skeleton will be bound to python-skeleton-NAME and will
3145 be added to `python-mode-skeleton-abbrev-table'."
3146 (declare (indent 2))
3147 (let* ((name (symbol-name name))
3148 (function-name (intern (concat "python-skeleton-" name))))
3150 (define-abbrev python-mode-skeleton-abbrev-table
3151 ,name "" ',function-name :system t)
3152 (setq python-skeleton-available
3153 (cons ',function-name python-skeleton-available))
3154 (define-skeleton ,function-name
3156 (format "Insert %s statement." name))
3159 (define-abbrev-table 'python-mode-abbrev-table ()
3160 "Abbrev table for Python mode."
3161 :parents (list python-mode-skeleton-abbrev-table))
3163 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3164 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3165 The skeleton will be bound to python-skeleton-NAME."
3166 (declare (indent 2))
3167 (let* ((name (symbol-name name))
3168 (function-name (intern (concat "python-skeleton--" name)))
3170 "Add '%s' clause? " name)))
3173 `(< ,(format "%s:" name) \n \n
3175 `(define-skeleton ,function-name
3177 (format "Auxiliary skeleton for %s statement." name))
3179 (unless (y-or-n-p ,msg)
3183 (python-define-auxiliary-skeleton else nil)
3185 (python-define-auxiliary-skeleton except nil)
3187 (python-define-auxiliary-skeleton finally nil)
3189 (python-skeleton-define if nil
3193 ("other condition, %s: "
3197 '(python-skeleton--else) | ^)
3199 (python-skeleton-define while nil
3203 '(python-skeleton--else) | ^)
3205 (python-skeleton-define for nil
3209 '(python-skeleton--else) | ^)
3211 (python-skeleton-define import nil
3212 "Import from module: "
3213 "from " str & " " | -5
3215 ("Identifier: " str ", ") -2 \n _)
3217 (python-skeleton-define try nil
3223 "except " str ":" \n
3226 '(python-skeleton--except)
3227 '(python-skeleton--else)
3228 '(python-skeleton--finally) | ^)
3230 (python-skeleton-define def nil
3232 "def " str "(" ("Parameter, %s: "
3233 (unless (equal ?\( (char-before)) ", ")
3235 "\"\"\"" - "\"\"\"" \n
3238 (python-skeleton-define class nil
3240 "class " str "(" ("Inheritance, %s: "
3241 (unless (equal ?\( (char-before)) ", ")
3245 "\"\"\"" - "\"\"\"" \n
3248 (defun python-skeleton-add-menu-items ()
3249 "Add menu items to Python->Skeletons menu."
3250 (let ((skeletons (sort python-skeleton-available 'string<)))
3251 (dolist (skeleton skeletons)
3253 nil '("Python" "Skeletons")
3255 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3260 (defcustom python-ffap-setup-code
3261 "def __FFAP_get_module_path(module):
3264 path = __import__(module).__file__
3265 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3270 "Python code to get a module path."
3274 (defcustom python-ffap-string-code
3275 "__FFAP_get_module_path('''%s''')\n"
3276 "Python code used to get a string with the path of a module."
3280 (defun python-ffap-module-path (module)
3281 "Function for `ffap-alist' to return path for MODULE."
3283 (and (eq major-mode 'inferior-python-mode)
3284 (get-buffer-process (current-buffer)))
3285 (python-shell-get-process))))
3289 (python-shell-send-string-no-output
3290 (format python-ffap-string-code module) process)))
3292 (substring-no-properties module-file 1 -1))))))
3296 (eval-after-load "ffap"
3298 (push '(python-mode . python-ffap-module-path) ffap-alist)
3299 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3304 (defcustom python-check-command
3306 "Command used to check a Python file."
3310 (defcustom python-check-buffer-name
3311 "*Python check: %s*"
3312 "Buffer name used for check commands."
3316 (defvar python-check-custom-command nil
3319 (defun python-check (command)
3320 "Check a Python file (default current buffer's file).
3321 Runs COMMAND, a shell command, as if by `compile'.
3322 See `python-check-command' for the default."
3324 (list (read-string "Check command: "
3325 (or python-check-custom-command
3326 (concat python-check-command " "
3327 (shell-quote-argument
3329 (let ((name (buffer-file-name)))
3331 (file-name-nondirectory name)))
3333 (setq python-check-custom-command command)
3334 (save-some-buffers (not compilation-ask-about-save) nil)
3335 (let ((process-environment (python-shell-calculate-process-environment))
3336 (exec-path (python-shell-calculate-exec-path)))
3337 (compilation-start command nil
3339 (format python-check-buffer-name command)))))
3344 (defcustom python-eldoc-setup-code
3345 "def __PYDOC_get_help(obj):
3348 if hasattr(obj, 'startswith'):
3349 obj = eval(obj, globals())
3350 doc = inspect.getdoc(obj)
3351 if not doc and callable(obj):
3353 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3354 target = obj.__init__
3360 args = inspect.formatargspec(
3361 *inspect.getargspec(target)
3364 doc = '{objtype} {name}{args}'.format(
3365 objtype=objtype, name=name, args=args
3368 doc = doc.splitlines()[0]
3375 "Python code to setup documentation retrieval."
3379 (defcustom python-eldoc-string-code
3380 "__PYDOC_get_help('''%s''')\n"
3381 "Python code used to get a string with the documentation of an object."
3385 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3386 "Internal implementation to get documentation at point.
3387 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3388 returns will be used. If not FORCE-PROCESS is passed what
3389 `python-shell-get-process' returns is used."
3390 (let ((process (or force-process (python-shell-get-process))))
3392 (error "Eldoc needs an inferior Python process running")
3393 (let ((input (or force-input
3394 (python-info-current-symbol t))))
3396 (python-shell-send-string-no-output
3397 (format python-eldoc-string-code input)
3400 (defun python-eldoc-function ()
3401 "`eldoc-documentation-function' for Python.
3402 For this to work as best as possible you should call
3403 `python-shell-send-buffer' from time to time so context in
3404 inferior Python process is updated properly."
3405 (python-eldoc--get-doc-at-point))
3407 (defun python-eldoc-at-point (symbol)
3408 "Get help on SYMBOL using `help'.
3409 Interactively, prompt for symbol."
3411 (let ((symbol (python-info-current-symbol t))
3412 (enable-recursive-minibuffers t))
3413 (list (read-string (if symbol
3414 (format "Describe symbol (default %s): " symbol)
3415 "Describe symbol: ")
3417 (message (python-eldoc--get-doc-at-point symbol)))
3419 (add-to-list 'debug-ignored-errors
3420 "^Eldoc needs an inferior Python process running.")
3425 (defvar python-imenu-format-item-label-function
3426 'python-imenu-format-item-label
3427 "Imenu function used to format an item label.
3428 It must be a function with two arguments: TYPE and NAME.")
3430 (defvar python-imenu-format-parent-item-label-function
3431 'python-imenu-format-parent-item-label
3432 "Imenu function used to format a parent item label.
3433 It must be a function with two arguments: TYPE and NAME.")
3435 (defvar python-imenu-format-parent-item-jump-label-function
3436 'python-imenu-format-parent-item-jump-label
3437 "Imenu function used to format a parent jump item label.
3438 It must be a function with two arguments: TYPE and NAME.")
3440 (defun python-imenu-format-item-label (type name)
3441 "Return Imenu label for single node using TYPE and NAME."
3442 (format "%s (%s)" name type))
3444 (defun python-imenu-format-parent-item-label (type name)
3445 "Return Imenu label for parent node using TYPE and NAME."
3446 (format "%s..." (python-imenu-format-item-label type name)))
3448 (defun python-imenu-format-parent-item-jump-label (type _name)
3449 "Return Imenu label for parent node jump using TYPE and NAME."
3450 (if (string= type "class")
3451 "*class definition*"
3452 "*function definition*"))
3454 (defun python-imenu--put-parent (type name pos tree)
3455 "Add the parent with TYPE, NAME and POS to TREE."
3457 (funcall python-imenu-format-item-label-function type name))
3459 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3462 (cons label (cons (cons jump-label pos) tree)))))
3464 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3465 "Recursively build the tree of nested definitions of a node.
3466 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3467 not be passed explicitly unless you know what you are doing."
3468 (setq min-indent (or min-indent 0)
3469 prev-indent (or prev-indent python-indent-offset))
3470 (let* ((pos (python-nav-backward-defun))
3472 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3473 (let ((split (split-string (match-string-no-properties 0))))
3474 (setq type (car split))
3477 (funcall python-imenu-format-item-label-function type name)))
3478 (indent (current-indentation))
3479 (children-indent-limit (+ python-indent-offset min-indent)))
3481 ;; Nothing found, probably near to bobp.
3483 ((<= indent min-indent)
3484 ;; The current indentation points that this is a parent
3485 ;; node, add it to the tree and stop recursing.
3486 (python-imenu--put-parent type name pos tree))
3488 (python-imenu--build-tree
3491 (if (<= indent children-indent-limit)
3492 ;; This lies within the children indent offset range,
3493 ;; so it's a normal child of its parent (i.e., not
3494 ;; a child of a child).
3495 (cons (cons label pos) tree)
3496 ;; Oh no, a child of a child?! Fear not, we
3497 ;; know how to roll. We recursively parse these by
3498 ;; swapping prev-indent and min-indent plus adding this
3499 ;; newly found item to a fresh subtree. This works, I
3502 (python-imenu--build-tree
3503 prev-indent indent (list (cons label pos)))
3506 (defun python-imenu-create-index ()
3507 "Return tree Imenu alist for the current Python buffer.
3508 Change `python-imenu-format-item-label-function',
3509 `python-imenu-format-parent-item-label-function',
3510 `python-imenu-format-parent-item-jump-label-function' to
3511 customize how labels are formatted."
3512 (goto-char (point-max))
3515 (while (setq tree (python-imenu--build-tree))
3516 (setq index (cons tree index)))
3519 (defun python-imenu-create-flat-index (&optional alist prefix)
3520 "Return flat outline of the current Python buffer for Imenu.
3521 Optional argument ALIST is the tree to be flattened; when nil
3522 `python-imenu-build-index' is used with
3523 `python-imenu-format-parent-item-jump-label-function'
3524 `python-imenu-format-parent-item-label-function'
3525 `python-imenu-format-item-label-function' set to
3526 (lambda (type name) name)
3527 Optional argument PREFIX is used in recursive calls and should
3528 not be passed explicitly.
3535 (\"decorator\" . 173)
3538 (\"wrapped_f\" . 393))))
3544 (\"decorator\" . 173)
3545 (\"decorator.wrap\" . 353)
3546 (\"decorator.wrapped_f\" . 393))"
3547 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3552 (let ((name (if prefix
3553 (concat prefix "." (car item))
3556 (cond ((or (numberp pos) (markerp pos))
3557 (list (cons name pos)))
3560 (cons name (cdar pos))
3561 (python-imenu-create-flat-index (cddr item) name))))))
3563 (let* ((fn (lambda (_type name) name))
3564 (python-imenu-format-item-label-function fn)
3565 (python-imenu-format-parent-item-label-function fn)
3566 (python-imenu-format-parent-item-jump-label-function fn))
3567 (python-imenu-create-index))))))
3572 (defun python-info-current-defun (&optional include-type)
3573 "Return name of surrounding function with Python compatible dotty syntax.
3574 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3575 This function can be used as the value of `add-log-current-defun-function'
3576 since it returns nil if point is not inside a defun."
3582 (starting-indentation (current-indentation))
3583 (starting-pos (point))
3588 (while (python-nav-beginning-of-defun 1)
3589 (when (save-match-data
3591 (or (not last-indent)
3592 (< (current-indentation) last-indent))
3596 ;; If this is the first run, we may add
3597 ;; the current defun at point.
3598 (setq first-run nil)
3599 (goto-char starting-pos)
3600 (python-nav-beginning-of-statement)
3601 (beginning-of-line 1)
3603 python-nav-beginning-of-defun-regexp)))
3607 (+ (current-indentation)
3608 python-indent-offset)))
3609 (if (< starting-indentation min-indent)
3610 ;; If the starting indentation is not
3611 ;; within the min defun indent make the
3614 ;; Else go to the end of defun and add
3615 ;; up the current indentation to the
3617 (python-nav-end-of-defun)
3619 (if (>= (current-indentation) min-indent)
3620 (1+ (current-indentation))
3622 (save-match-data (setq last-indent (current-indentation)))
3623 (if (or (not include-type) type)
3624 (setq names (cons (match-string-no-properties 1) names))
3625 (let ((match (split-string (match-string-no-properties 0))))
3626 (setq type (car match))
3627 (setq names (cons (cadr match) names)))))
3628 ;; Stop searching ASAP.
3629 (and (= (current-indentation) 0) (throw 'exit t))))
3631 (concat (and type (format "%s " type))
3632 (mapconcat 'identity names ".")))))))
3634 (defun python-info-current-symbol (&optional replace-self)
3635 "Return current symbol using dotty syntax.
3636 With optional argument REPLACE-SELF convert \"self\" to current
3639 (and (not (python-syntax-comment-or-string-p))
3640 (with-syntax-table python-dotty-syntax-table
3641 (let ((sym (symbol-at-point)))
3643 (substring-no-properties (symbol-name sym))))))))
3645 (if (not replace-self)
3647 (let ((current-defun (python-info-current-defun)))
3648 (if (not current-defun)
3650 (replace-regexp-in-string
3651 (python-rx line-start word-start "self" word-end ?.)
3653 (mapconcat 'identity
3654 (butlast (split-string current-defun "\\."))
3658 (defun python-info-statement-starts-block-p ()
3659 "Return non-nil if current statement opens a block."
3661 (python-nav-beginning-of-statement)
3662 (looking-at (python-rx block-start))))
3664 (defun python-info-statement-ends-block-p ()
3665 "Return non-nil if point is at end of block."
3666 (let ((end-of-block-pos (save-excursion
3667 (python-nav-end-of-block)))
3668 (end-of-statement-pos (save-excursion
3669 (python-nav-end-of-statement))))
3670 (and end-of-block-pos end-of-statement-pos
3671 (= end-of-block-pos end-of-statement-pos))))
3673 (defun python-info-beginning-of-statement-p ()
3674 "Return non-nil if point is at beginning of statement."
3675 (= (point) (save-excursion
3676 (python-nav-beginning-of-statement)
3679 (defun python-info-end-of-statement-p ()
3680 "Return non-nil if point is at end of statement."
3681 (= (point) (save-excursion
3682 (python-nav-end-of-statement)
3685 (defun python-info-beginning-of-block-p ()
3686 "Return non-nil if point is at beginning of block."
3687 (and (python-info-beginning-of-statement-p)
3688 (python-info-statement-starts-block-p)))
3690 (defun python-info-end-of-block-p ()
3691 "Return non-nil if point is at end of block."
3692 (and (python-info-end-of-statement-p)
3693 (python-info-statement-ends-block-p)))
3695 (define-obsolete-function-alias
3696 'python-info-closing-block
3697 'python-info-dedenter-opening-block-position "24.4")
3699 (defun python-info-dedenter-opening-block-position ()
3700 "Return the point of the closest block the current line closes.
3701 Returns nil if point is not on a dedenter statement or no opening
3702 block can be detected. The latter case meaning current file is
3703 likely an invalid python file."
3704 (let ((positions (python-info-dedenter-opening-block-positions))
3705 (indentation (current-indentation))
3707 (while (and (not position)
3710 (goto-char (car positions))
3711 (if (<= (current-indentation) indentation)
3712 (setq position (car positions))
3713 (setq positions (cdr positions)))))
3716 (defun python-info-dedenter-opening-block-positions ()
3717 "Return points of blocks the current line may close sorted by closer.
3718 Returns nil if point is not on a dedenter statement or no opening
3719 block can be detected. The latter case meaning current file is
3720 likely an invalid python file."
3722 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3724 (goto-char dedenter-pos)
3725 (let* ((pairs '(("elif" "elif" "if")
3726 ("else" "if" "elif" "except" "for" "while")
3727 ("except" "except" "try")
3728 ("finally" "else" "except" "try")))
3729 (dedenter (match-string-no-properties 0))
3730 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
3731 (collected-indentations)
3734 (while (python-nav--syntactically
3736 (re-search-backward (python-rx block-start) nil t))
3738 (let ((indentation (current-indentation)))
3739 (when (and (not (memq indentation collected-indentations))
3740 (or (not collected-indentations)
3741 (< indentation (apply #'min collected-indentations))))
3742 (setq collected-indentations
3743 (cons indentation collected-indentations))
3744 (when (member (match-string-no-properties 0)
3745 possible-opening-blocks)
3746 (setq opening-blocks (cons (point) opening-blocks))))
3747 (when (zerop indentation)
3748 (throw 'exit nil)))))
3750 (nreverse opening-blocks))))))
3752 (define-obsolete-function-alias
3753 'python-info-closing-block-message
3754 'python-info-dedenter-opening-block-message "24.4")
3756 (defun python-info-dedenter-opening-block-message ()
3757 "Message the first line of the block the current statement closes."
3758 (let ((point (python-info-dedenter-opening-block-position)))
3762 (message "Closes %s" (save-excursion
3765 (point) (line-end-position))))))))
3767 (defun python-info-dedenter-statement-p ()
3768 "Return point if current statement is a dedenter.
3769 Sets `match-data' to the keyword that starts the dedenter
3772 (python-nav-beginning-of-statement)
3773 (when (and (not (python-syntax-context-type))
3774 (looking-at (python-rx dedenter)))
3777 (defun python-info-line-ends-backslash-p (&optional line-number)
3778 "Return non-nil if current line ends with backslash.
3779 With optional argument LINE-NUMBER, check that line instead."
3784 (python-util-goto-line line-number))
3785 (while (and (not (eobp))
3786 (goto-char (line-end-position))
3787 (python-syntax-context 'paren)
3788 (not (equal (char-before (point)) ?\\)))
3790 (when (equal (char-before) ?\\)
3793 (defun python-info-beginning-of-backslash (&optional line-number)
3794 "Return the point where the backslashed line start.
3795 Optional argument LINE-NUMBER forces the line number to check against."
3800 (python-util-goto-line line-number))
3801 (when (python-info-line-ends-backslash-p)
3802 (while (save-excursion
3803 (goto-char (line-beginning-position))
3804 (python-syntax-context 'paren))
3806 (back-to-indentation)
3809 (defun python-info-continuation-line-p ()
3810 "Check if current line is continuation of another.
3811 When current line is continuation of another return the point
3812 where the continued line ends."
3816 (let* ((context-type (progn
3817 (back-to-indentation)
3818 (python-syntax-context-type)))
3819 (line-start (line-number-at-pos))
3820 (context-start (when context-type
3821 (python-syntax-context context-type))))
3822 (cond ((equal context-type 'paren)
3823 ;; Lines inside a paren are always a continuation line
3824 ;; (except the first one).
3825 (python-util-forward-comment -1)
3827 ((member context-type '(string comment))
3828 ;; move forward an roll again
3829 (goto-char context-start)
3830 (python-util-forward-comment)
3831 (python-info-continuation-line-p))
3833 ;; Not within a paren, string or comment, the only way
3834 ;; we are dealing with a continuation line is that
3835 ;; previous line contains a backslash, and this can
3836 ;; only be the previous line from current
3837 (back-to-indentation)
3838 (python-util-forward-comment -1)
3839 (when (and (equal (1- line-start) (line-number-at-pos))
3840 (python-info-line-ends-backslash-p))
3841 (point-marker))))))))
3843 (defun python-info-block-continuation-line-p ()
3844 "Return non-nil if current line is a continuation of a block."
3846 (when (python-info-continuation-line-p)
3848 (back-to-indentation)
3849 (when (looking-at (python-rx block-start))
3852 (defun python-info-assignment-continuation-line-p ()
3853 "Check if current line is a continuation of an assignment.
3854 When current line is continuation of another with an assignment
3855 return the point of the first non-blank character after the
3858 (when (python-info-continuation-line-p)
3860 (back-to-indentation)
3861 (when (and (not (looking-at (python-rx block-start)))
3862 (and (re-search-forward (python-rx not-simple-operator
3864 not-simple-operator)
3865 (line-end-position) t)
3866 (not (python-syntax-context-type))))
3867 (skip-syntax-forward "\s")
3870 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3871 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3872 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3874 (beginning-of-line 1)
3875 (looking-at python-nav-beginning-of-defun-regexp))))
3877 (defun python-info-current-line-comment-p ()
3878 "Return non-nil if current line is a comment line."
3880 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
3883 (defun python-info-current-line-empty-p ()
3884 "Return non-nil if current line is empty, ignoring whitespace."
3886 (beginning-of-line 1)
3888 (python-rx line-start (* whitespace)
3889 (group (* not-newline))
3890 (* whitespace) line-end))
3891 (string-equal "" (match-string-no-properties 1))))
3894 ;;; Utility functions
3896 (defun python-util-goto-line (line-number)
3897 "Move point to LINE-NUMBER."
3898 (goto-char (point-min))
3899 (forward-line (1- line-number)))
3901 ;; Stolen from org-mode
3902 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3903 "Clone local variables from FROM-BUFFER.
3904 Optional argument REGEXP selects variables to clone and defaults
3908 (and (symbolp (car pair))
3909 (string-match (or regexp "^python-")
3910 (symbol-name (car pair)))
3911 (set (make-local-variable (car pair))
3913 (buffer-local-variables from-buffer)))
3915 (defun python-util-forward-comment (&optional direction)
3916 "Python mode specific version of `forward-comment'.
3917 Optional argument DIRECTION defines the direction to move to."
3918 (let ((comment-start (python-syntax-context 'comment))
3919 (factor (if (< (or direction 0) 0)
3923 (goto-char comment-start))
3924 (forward-comment factor)))
3926 (defun python-util-popn (lst n)
3927 "Return LST first N elements.
3928 N should be an integer, when negative its opposite is used.
3929 When N is bigger than the length of LST, the list is
3931 (let* ((n (min (abs n)))
3937 (setq acc (cons (car lst) acc)
3942 (defun python-util-strip-string (string)
3943 "Strip STRING whitespace and newlines from end and beginning."
3944 (replace-regexp-in-string
3945 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
3946 (: (* (any whitespace ?\r ?\n)) string-end)))
3950 (defun python-util-valid-regexp-p (regexp)
3951 "Return non-nil if REGEXP is valid."
3952 (ignore-errors (string-match regexp "") t))
3955 (defun python-electric-pair-string-delimiter ()
3956 (when (and electric-pair-mode
3957 (memq last-command-event '(?\" ?\'))
3959 (while (eq (char-before (- (point) count)) last-command-event)
3962 (eq (char-after) last-command-event))
3963 (save-excursion (insert (make-string 2 last-command-event)))))
3965 (defvar electric-indent-inhibit)
3968 (define-derived-mode python-mode prog-mode "Python"
3969 "Major mode for editing Python files.
3971 \\{python-mode-map}"
3972 (set (make-local-variable 'tab-width) 8)
3973 (set (make-local-variable 'indent-tabs-mode) nil)
3975 (set (make-local-variable 'comment-start) "# ")
3976 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3978 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3979 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3981 (set (make-local-variable 'forward-sexp-function)
3982 'python-nav-forward-sexp)
3984 (set (make-local-variable 'font-lock-defaults)
3985 '(python-font-lock-keywords nil nil nil nil))
3987 (set (make-local-variable 'syntax-propertize-function)
3988 python-syntax-propertize-function)
3990 (set (make-local-variable 'indent-line-function)
3991 #'python-indent-line-function)
3992 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3993 ;; Because indentation is not redundant, we cannot safely reindent code.
3994 (setq-local electric-indent-inhibit t)
3995 (setq-local electric-indent-chars (cons ?: electric-indent-chars))
3997 ;; Add """ ... """ pairing to electric-pair-mode.
3998 (add-hook 'post-self-insert-hook
3999 #'python-electric-pair-string-delimiter 'append t)
4001 (set (make-local-variable 'paragraph-start) "\\s-*$")
4002 (set (make-local-variable 'fill-paragraph-function)
4003 #'python-fill-paragraph)
4005 (set (make-local-variable 'beginning-of-defun-function)
4006 #'python-nav-beginning-of-defun)
4007 (set (make-local-variable 'end-of-defun-function)
4008 #'python-nav-end-of-defun)
4010 (add-hook 'completion-at-point-functions
4011 #'python-completion-complete-at-point nil 'local)
4013 (add-hook 'post-self-insert-hook
4014 #'python-indent-post-self-insert-function 'append 'local)
4016 (set (make-local-variable 'imenu-create-index-function)
4017 #'python-imenu-create-index)
4019 (set (make-local-variable 'add-log-current-defun-function)
4020 #'python-info-current-defun)
4022 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4024 (set (make-local-variable 'skeleton-further-elements)
4026 (< '(backward-delete-char-untabify (min python-indent-offset
4028 (^ '(- (1+ (current-indentation))))))
4030 (set (make-local-variable 'eldoc-documentation-function)
4031 #'python-eldoc-function)
4033 (add-to-list 'hs-special-modes-alist
4034 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
4036 (python-nav-end-of-defun)) nil))
4038 (set (make-local-variable 'outline-regexp)
4039 (python-rx (* space) block-start))
4040 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4041 (set (make-local-variable 'outline-level)
4043 "`outline-level' function for Python mode."
4044 (1+ (/ (current-indentation) python-indent-offset))))
4046 (python-skeleton-add-menu-items)
4048 (make-local-variable 'python-shell-internal-buffer)
4050 (when python-indent-guess-indent-offset
4051 (python-indent-guess-indent-offset)))
4058 ;; indent-tabs-mode: nil
4061 ;;; python.el ends here