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 ;; Missing or delayed output used to happen due to differences between
98 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
99 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
100 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
101 ;; controls whether `python-shell-calculate-process-environment'
102 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
103 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
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: 6 skeletons are provided for simple inserting of class,
182 ;; def, for, if, try and while. These skeletons are integrated with
183 ;; 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-class', `python-skeleton-def'
188 ;; `python-skeleton-for', `python-skeleton-if', `python-skeleton-try'
189 ;; and `python-skeleton-while'.
191 ;; FFAP: You can find the filename for a given module when using ffap
192 ;; out of the box. This feature needs an inferior python shell
195 ;; Code check: Check the current file for errors with `python-check'
196 ;; using the program defined in `python-check-command'.
198 ;; Eldoc: returns documentation for object at point by using the
199 ;; inferior python subprocess to inspect its documentation. As you
200 ;; might guessed you should run `python-shell-send-buffer' from time
201 ;; to time to get better results too.
203 ;; Imenu: There are two index building functions to be used as
204 ;; `imenu-create-index-function': `python-imenu-create-index' (the
205 ;; default one, builds the alist in form of a tree) and
206 ;; `python-imenu-create-flat-index'. See also
207 ;; `python-imenu-format-item-label-function',
208 ;; `python-imenu-format-parent-item-label-function',
209 ;; `python-imenu-format-parent-item-jump-label-function' variables for
210 ;; changing the way labels are formatted in the tree version.
212 ;; If you used python-mode.el you may miss auto-indentation when
213 ;; inserting newlines. To achieve the same behavior you have two
216 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
217 ;; default) and use RET. If this mode is disabled use
218 ;; `newline-and-indent', bound to C-j.
220 ;; 2) Add the following hook in your .emacs:
222 ;; (add-hook 'python-mode-hook
224 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
226 ;; I'd recommend the first one since you'll get the same behavior for
227 ;; all modes out-of-the-box.
231 ;; Add this to your .emacs:
233 ;; (add-to-list 'load-path "/folder/containing/file")
240 (require 'ansi-color
)
245 ;; Avoid compiler warnings
246 (defvar view-return-to-alist
)
247 (defvar compilation-error-regexp-alist
)
248 (defvar outline-heading-end-regexp
)
250 (autoload 'comint-mode
"comint")
253 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
255 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
258 "Python Language's flying circus support for Emacs."
261 :link
'(emacs-commentary-link "python"))
266 (defvar python-mode-map
267 (let ((map (make-sparse-keymap)))
269 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
270 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
271 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
272 (define-key map
"\C-c\C-j" 'imenu
)
274 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
275 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
276 (define-key map
"\C-c<" 'python-indent-shift-left
)
277 (define-key map
"\C-c>" 'python-indent-shift-right
)
279 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
280 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
281 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
282 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
283 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
284 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
286 (define-key map
"\C-c\C-p" 'run-python
)
287 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
288 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
289 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
290 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
291 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
292 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
293 ;; Some util commands
294 (define-key map
"\C-c\C-v" 'python-check
)
295 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
297 (substitute-key-definition 'complete-symbol
'completion-at-point
299 (easy-menu-define python-menu map
"Python Mode menu"
301 :help
"Python-specific Features"
302 ["Shift region left" python-indent-shift-left
:active mark-active
303 :help
"Shift region left by a single indentation step"]
304 ["Shift region right" python-indent-shift-right
:active mark-active
305 :help
"Shift region right by a single indentation step"]
307 ["Start of def/class" beginning-of-defun
308 :help
"Go to start of outermost definition around point"]
309 ["End of def/class" end-of-defun
310 :help
"Go to end of definition around point"]
311 ["Mark def/class" mark-defun
312 :help
"Mark outermost definition around point"]
313 ["Jump to def/class" imenu
314 :help
"Jump to a class or function definition"]
318 ["Start interpreter" run-python
319 :help
"Run inferior Python process in a separate buffer"]
320 ["Switch to shell" python-shell-switch-to-shell
321 :help
"Switch to running inferior Python process"]
322 ["Eval string" python-shell-send-string
323 :help
"Eval string in inferior Python session"]
324 ["Eval buffer" python-shell-send-buffer
325 :help
"Eval buffer in inferior Python session"]
326 ["Eval region" python-shell-send-region
327 :help
"Eval region in inferior Python session"]
328 ["Eval defun" python-shell-send-defun
329 :help
"Eval defun in inferior Python session"]
330 ["Eval file" python-shell-send-file
331 :help
"Eval file in inferior Python session"]
332 ["Debugger" pdb
:help
"Run pdb under GUD"]
334 ["Check file" python-check
335 :help
"Check file for errors"]
336 ["Help on symbol" python-eldoc-at-point
337 :help
"Get help on symbol at point"]
338 ["Complete symbol" completion-at-point
339 :help
"Complete symbol before point"]))
341 "Keymap for `python-mode'.")
344 ;;; Python specialized rx
347 (defconst python-rx-constituents
348 `((block-start .
,(rx symbol-start
349 (or "def" "class" "if" "elif" "else" "try"
350 "except" "finally" "for" "while" "with")
352 (dedenter .
,(rx symbol-start
353 (or "elif" "else" "except" "finally")
355 (block-ender .
,(rx symbol-start
357 "break" "continue" "pass" "raise" "return")
359 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
361 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
362 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
363 (+ space
) "==" (+ space
)
364 (any ?
' ?
\") "__main__" (any ?
' ?
\")
366 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
367 (open-paren .
,(rx (or "{" "[" "(")))
368 (close-paren .
,(rx (or "}" "]" ")")))
369 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
370 ;; FIXME: rx should support (not simple-operator).
371 (not-simple-operator .
,(rx
373 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
374 ;; FIXME: Use regexp-opt.
375 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
376 "=" "%" "**" "//" "<<" ">>" "<=" "!="
377 "==" ">=" "is" "not")))
378 ;; FIXME: Use regexp-opt.
379 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
380 ">>=" "<<=" "&=" "^=" "|=")))
381 (string-delimiter .
,(rx (and
382 ;; Match even number of backslashes.
383 (or (not (any ?
\\ ?
\' ?
\")) point
384 ;; Quotes might be preceded by a escaped quote.
385 (and (or (not (any ?
\\)) point
) ?
\\
386 (* ?
\\ ?
\\) (any ?
\' ?
\")))
388 ;; Match single or triple quotes of any kind.
389 (group (or "\"" "\"\"\"" "'" "'''"))))))
390 "Additional Python specific sexps for `python-rx'")
392 (defmacro python-rx
(&rest regexps
)
393 "Python mode specialized rx macro.
394 This variant of `rx' supports common Python named REGEXPS."
395 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
396 (cond ((null regexps
)
399 (rx-to-string `(and ,@regexps
) t
))
401 (rx-to-string (car regexps
) t
))))))
404 ;;; Font-lock and syntax
407 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
410 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
411 (and (nth 4 ppss
) (nth 8 ppss
))))
413 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
414 (and (nth 3 ppss
) (nth 8 ppss
))))
416 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
419 (defun python-syntax-context (type &optional syntax-ppss
)
420 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
421 TYPE can be `comment', `string' or `paren'. It returns the start
422 character address of the specified TYPE."
423 (declare (compiler-macro python-syntax--context-compiler-macro
))
424 (let ((ppss (or syntax-ppss
(syntax-ppss))))
426 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
427 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
428 (`paren
(nth 1 ppss
))
431 (defun python-syntax-context-type (&optional syntax-ppss
)
432 "Return the context type using SYNTAX-PPSS.
433 The type returned can be `comment', `string' or `paren'."
434 (let ((ppss (or syntax-ppss
(syntax-ppss))))
436 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
437 ((nth 1 ppss
) 'paren
))))
439 (defsubst python-syntax-comment-or-string-p
()
440 "Return non-nil if point is inside 'comment or 'string."
441 (nth 8 (syntax-ppss)))
443 (define-obsolete-function-alias
444 'python-info-ppss-context
#'python-syntax-context
"24.3")
446 (define-obsolete-function-alias
447 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
449 (define-obsolete-function-alias
450 'python-info-ppss-comment-or-string-p
451 #'python-syntax-comment-or-string-p
"24.3")
453 (defvar python-font-lock-keywords
457 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
458 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
459 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
464 ;; False, None, and True are listed as keywords on the Python 3
465 ;; documentation, but since they also qualify as constants they are
466 ;; fontified like that in order to keep font-lock consistent between
473 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
474 (1 font-lock-function-name-face
))
476 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
477 (1 font-lock-type-face
))
481 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
482 ;; copyright, license, credits, quit and exit are added by the site
483 ;; module and they are not intended to be used in programs
484 "copyright" "credits" "exit" "license" "quit")
485 symbol-end
) . font-lock-constant-face
)
487 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
488 (0+ "." (1+ (or word ?_
)))))
489 (1 font-lock-type-face
))
490 ;; Builtin Exceptions
493 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
494 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
495 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
496 "ImportError" "ImportWarning" "IndexError" "KeyError"
497 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
498 "NotImplementedError" "OSError" "OverflowError"
499 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
500 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
501 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
502 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
503 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
504 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
508 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
510 symbol-end
) . font-lock-type-face
)
514 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
515 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
516 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
517 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
518 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
519 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
520 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
521 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
524 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
525 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
528 "ascii" "bytearray" "bytes" "exec"
530 "__all__" "__doc__" "__name__" "__package__")
531 symbol-end
) . font-lock-builtin-face
)
533 ;; support for a = b = c = 5
535 (let ((re (python-rx (group (+ (any word ?. ?_
)))
536 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
537 assignment-operator
))
539 (while (and (setq res
(re-search-forward re limit t
))
540 (or (python-syntax-context 'paren
)
541 (equal (char-after (point-marker)) ?
=))))
543 (1 font-lock-variable-name-face nil nil
))
544 ;; support for a, b, c = (1, 2, 3)
546 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
547 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
548 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
549 assignment-operator
))
551 (while (and (setq res
(re-search-forward re limit t
))
552 (goto-char (match-end 1))
553 (python-syntax-context 'paren
)))
555 (1 font-lock-variable-name-face nil nil
))))
557 (defconst python-syntax-propertize-function
558 (syntax-propertize-rules
559 ((python-rx string-delimiter
)
560 (0 (ignore (python-syntax-stringify))))))
562 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
563 "Count number of quotes around point (max is 3).
564 QUOTE-CHAR is the quote char to count. Optional argument POINT is
565 the point where scan starts (defaults to current point), and LIMIT
566 is used to limit the scan."
569 (or (not limit
) (< (+ point i
) limit
))
570 (eq (char-after (+ point i
)) quote-char
))
574 (defun python-syntax-stringify ()
575 "Put `syntax-table' property correctly on single/triple quotes."
576 (let* ((num-quotes (length (match-string-no-properties 1)))
578 (backward-char num-quotes
)
580 (forward-char num-quotes
)))
581 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
582 (quote-starting-pos (- (point) num-quotes
))
583 (quote-ending-pos (point))
586 (python-syntax-count-quotes
587 (char-before) string-start quote-starting-pos
))))
588 (cond ((and string-start
(= num-closing-quotes
0))
589 ;; This set of quotes doesn't match the string starting
593 ;; This set of quotes delimit the start of a string.
594 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
595 'syntax-table
(string-to-syntax "|")))
596 ((= num-quotes num-closing-quotes
)
597 ;; This set of quotes delimit the end of a string.
598 (put-text-property (1- quote-ending-pos
) quote-ending-pos
599 'syntax-table
(string-to-syntax "|")))
600 ((> num-quotes num-closing-quotes
)
601 ;; This may only happen whenever a triple quote is closing
602 ;; a single quoted string. Add string delimiter syntax to
604 (put-text-property quote-starting-pos quote-ending-pos
605 'syntax-table
(string-to-syntax "|"))))))
607 (defvar python-mode-syntax-table
608 (let ((table (make-syntax-table)))
609 ;; Give punctuation syntax to ASCII that normally has symbol
610 ;; syntax or has word syntax and isn't a letter.
611 (let ((symbol (string-to-syntax "_"))
612 (sst (standard-syntax-table)))
615 (if (equal symbol
(aref sst i
))
616 (modify-syntax-entry i
"." table
)))))
617 (modify-syntax-entry ?$
"." table
)
618 (modify-syntax-entry ?%
"." table
)
620 (modify-syntax-entry ?
# "<" table
)
621 (modify-syntax-entry ?
\n ">" table
)
622 (modify-syntax-entry ?
' "\"" table
)
623 (modify-syntax-entry ?
` "$" table
)
625 "Syntax table for Python files.")
627 (defvar python-dotty-syntax-table
628 (let ((table (make-syntax-table python-mode-syntax-table
)))
629 (modify-syntax-entry ?.
"w" table
)
630 (modify-syntax-entry ?_
"w" table
)
632 "Dotty syntax table for Python files.
633 It makes underscores and dots word constituent chars.")
638 (defcustom python-indent-offset
4
639 "Default indentation offset for Python."
644 (defcustom python-indent-guess-indent-offset t
645 "Non-nil tells Python mode to guess `python-indent-offset' value."
650 (defcustom python-indent-trigger-commands
651 '(indent-for-tab-command yas-expand yas
/expand
)
652 "Commands that might trigger a `python-indent-line' call."
653 :type
'(repeat symbol
)
656 (define-obsolete-variable-alias
657 'python-indent
'python-indent-offset
"24.3")
659 (define-obsolete-variable-alias
660 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
662 (defvar python-indent-current-level
0
663 "Current indentation level `python-indent-line-function' is using.")
665 (defvar python-indent-levels
'(0)
666 "Levels of indentation available for `python-indent-line-function'.")
668 (defun python-indent-guess-indent-offset ()
669 "Guess and set `python-indent-offset' for the current buffer."
674 (goto-char (point-min))
676 (while (and (not block-end
)
678 (python-rx line-start block-start
) nil t
))
680 (not (python-syntax-context-type))
682 (goto-char (line-end-position))
683 (python-util-forward-comment -
1)
684 (if (equal (char-before) ?
:)
687 (when (python-info-block-continuation-line-p)
688 (while (and (python-info-continuation-line-p)
691 (python-util-forward-comment -
1)
692 (when (equal (char-before) ?
:)
694 (setq block-end
(point-marker))))
697 (goto-char block-end
)
698 (python-util-forward-comment)
699 (current-indentation))))
700 (if (and indentation
(not (zerop indentation
)))
701 (set (make-local-variable 'python-indent-offset
) indentation
)
702 (message "Can't guess python-indent-offset, using defaults: %s"
703 python-indent-offset
)))))))
705 (defun python-indent-context ()
706 "Get information on indentation context.
707 Context information is returned with a cons with the form:
710 Where status can be any of the following symbols:
712 * after-comment: When current line might continue a comment block
713 * inside-paren: If point in between (), {} or []
714 * inside-string: If point is inside a string
715 * after-backslash: Previous line ends in a backslash
716 * after-beginning-of-block: Point is after beginning of block
717 * after-line: Point is after normal line
718 * dedenter-statement: Point is on a dedenter statement.
719 * no-indent: Point is at beginning of buffer or other special case
720 START is the buffer position where the sexp starts."
723 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
727 ;; Beginning of buffer
729 (goto-char (line-beginning-position))
732 ;; Comment continuation
736 (python-info-current-line-comment-p)
737 (python-info-current-line-empty-p))
740 (python-info-current-line-comment-p)))
744 ((setq start
(python-syntax-context 'string ppss
))
747 ((setq start
(python-syntax-context 'paren ppss
))
750 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
751 (python-syntax-context 'comment ppss
)))
752 (let ((line-beg-pos (line-number-at-pos)))
753 (python-info-line-ends-backslash-p
754 (1- line-beg-pos
)))))
756 ;; After beginning of block
757 ((setq start
(save-excursion
759 (back-to-indentation)
760 (python-util-forward-comment -
1)
761 (equal (char-before) ?
:))
762 ;; Move to the first block start that's not in within
763 ;; a string, comment or paren and that's not a
764 ;; continuation line.
765 (while (and (re-search-backward
766 (python-rx block-start
) nil t
)
768 (python-syntax-context-type)
769 (python-info-continuation-line-p))))
770 (when (looking-at (python-rx block-start
))
772 'after-beginning-of-block
)
773 ((when (setq start
(python-info-dedenter-statement-p))
774 'dedenter-statement
))
776 ((setq start
(save-excursion
777 (back-to-indentation)
778 (skip-chars-backward (rx (or whitespace ?
\n)))
779 (python-nav-beginning-of-statement)
786 (defun python-indent-calculate-indentation ()
787 "Calculate correct indentation offset for the current line."
788 (let* ((indentation-context (python-indent-context))
789 (context-status (car indentation-context
))
790 (context-start (cdr indentation-context
)))
794 (pcase context-status
797 (goto-char context-start
)
798 (current-indentation))
799 ;; When point is after beginning of block just add one level
800 ;; of indentation relative to the context-start
801 (`after-beginning-of-block
802 (goto-char context-start
)
803 (+ (current-indentation) python-indent-offset
))
804 ;; When after a simple line just use previous line
807 (let* ((pair (save-excursion
808 (goto-char context-start
)
810 (current-indentation)
811 (python-info-beginning-of-block-p))))
812 (context-indentation (car pair
))
813 ;; TODO: Separate block enders into its own case.
816 (python-util-forward-comment -
1)
817 (python-nav-beginning-of-statement)
818 (looking-at (python-rx block-ender
)))
821 (- context-indentation adjustment
)))
822 ;; When point is on a dedenter statement, search for the
823 ;; opening block that corresponds to it and use its
824 ;; indentation. If no opening block is found just remove
825 ;; indentation as this is an invalid python file.
827 (let ((block-start-point
828 (python-info-dedenter-opening-block-position)))
830 (if (not block-start-point
)
832 (goto-char block-start-point
)
833 (current-indentation)))))
834 ;; When inside of a string, do nothing. just use the current
835 ;; indentation. XXX: perhaps it would be a good idea to
836 ;; invoke standard text indentation here
838 (goto-char context-start
)
839 (current-indentation))
840 ;; After backslash we have several possibilities.
843 ;; Check if current line is a dot continuation. For this
844 ;; the current line must start with a dot and previous
845 ;; line must contain a dot too.
847 (back-to-indentation)
848 (when (looking-at "\\.")
849 ;; If after moving one line back point is inside a paren it
850 ;; needs to move back until it's not anymore
854 (python-syntax-context 'paren
))))
855 (goto-char (line-end-position))
856 (while (and (re-search-backward
857 "\\." (line-beginning-position) t
)
858 (python-syntax-context-type)))
859 (if (and (looking-at "\\.")
860 (not (python-syntax-context-type)))
861 ;; The indentation is the same column of the
862 ;; first matching dot that's not inside a
863 ;; comment, a string or a paren
865 ;; No dot found on previous line, just add another
866 ;; indentation level.
867 (+ (current-indentation) python-indent-offset
)))))
868 ;; Check if prev line is a block continuation
869 ((let ((block-continuation-start
870 (python-info-block-continuation-line-p)))
871 (when block-continuation-start
872 ;; If block-continuation-start is set jump to that
873 ;; marker and use first column after the block start
874 ;; as indentation value.
875 (goto-char block-continuation-start
)
877 (python-rx block-start
(* space
))
878 (line-end-position) t
)
880 ;; Check if current line is an assignment continuation
881 ((let ((assignment-continuation-start
882 (python-info-assignment-continuation-line-p)))
883 (when assignment-continuation-start
884 ;; If assignment-continuation is set jump to that
885 ;; marker and use first column after the assignment
886 ;; operator as indentation value.
887 (goto-char assignment-continuation-start
)
891 (goto-char (python-info-beginning-of-backslash))
896 (or (python-info-beginning-of-backslash) (point)))
897 (python-info-line-ends-backslash-p)))
898 ;; The two previous lines ended in a backslash so we must
899 ;; respect previous line indentation.
900 (current-indentation)
901 ;; What happens here is that we are dealing with the second
902 ;; line of a backslash continuation, in that case we just going
903 ;; to add one indentation level.
904 (+ (current-indentation) python-indent-offset
)))))
905 ;; When inside a paren there's a need to handle nesting
909 ;; If current line closes the outermost open paren use the
910 ;; current indentation of the context-start line.
912 (skip-syntax-forward "\s" (line-end-position))
913 (when (and (looking-at (regexp-opt '(")" "]" "}")))
916 (not (python-syntax-context 'paren
))))
917 (goto-char context-start
)
918 (current-indentation))))
919 ;; If open paren is contained on a line by itself add another
920 ;; indentation level, else look for the first word after the
921 ;; opening paren and use it's column position as indentation
923 ((let* ((content-starts-in-newline)
926 (if (setq content-starts-in-newline
928 (goto-char context-start
)
932 (line-beginning-position)
934 (python-util-forward-comment))
936 (+ (current-indentation) python-indent-offset
)
940 ;; If current line closes a nested open paren de-indent one
943 (back-to-indentation)
944 (looking-at (regexp-opt '(")" "]" "}"))))
945 (- indent python-indent-offset
))
946 ;; If the line of the opening paren that wraps the current
947 ;; line starts a block add another level of indentation to
948 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
950 (when (and content-starts-in-newline
952 (goto-char context-start
)
953 (back-to-indentation)
954 (looking-at (python-rx block-start
))))
955 (+ indent python-indent-offset
))))
958 (defun python-indent-calculate-levels ()
959 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
960 (if (or (python-info-continuation-line-p)
961 (not (python-info-dedenter-statement-p)))
962 ;; XXX: This asks for a refactor. Even if point is on a
963 ;; dedenter statement, it could be multiline and in that case
964 ;; the continuation lines should be indented with normal rules.
965 (let* ((indentation (python-indent-calculate-indentation))
966 (remainder (% indentation python-indent-offset
))
967 (steps (/ (- indentation remainder
) python-indent-offset
)))
968 (setq python-indent-levels
(list 0))
969 (dotimes (step steps
)
970 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
971 (when (not (eq 0 remainder
))
972 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
)))
973 (setq python-indent-levels
975 (mapcar (lambda (pos)
978 (current-indentation)))
979 (python-info-dedenter-opening-block-positions))
981 (setq python-indent-current-level
(1- (length python-indent-levels
))
982 python-indent-levels
(nreverse python-indent-levels
)))
984 (defun python-indent-toggle-levels ()
985 "Toggle `python-indent-current-level' over `python-indent-levels'."
986 (setq python-indent-current-level
(1- python-indent-current-level
))
987 (when (< python-indent-current-level
0)
988 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
990 (defun python-indent-line (&optional force-toggle
)
991 "Internal implementation of `python-indent-line-function'.
992 Uses the offset calculated in
993 `python-indent-calculate-indentation' and available levels
994 indicated by the variable `python-indent-levels' to set the
997 When the variable `last-command' is equal to one of the symbols
998 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
999 non-nil it cycles levels indicated in the variable
1000 `python-indent-levels' by setting the current level in the
1001 variable `python-indent-current-level'.
1003 When the variable `last-command' is not equal to one of the
1004 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
1005 is nil it calculates possible indentation levels and saves them
1006 in the variable `python-indent-levels'. Afterwards it sets the
1007 variable `python-indent-current-level' correctly so offset is
1009 (nth python-indent-current-level python-indent-levels)"
1011 (and (or (and (memq this-command python-indent-trigger-commands
)
1012 (eq last-command this-command
))
1014 (not (equal python-indent-levels
'(0)))
1015 (or (python-indent-toggle-levels) t
))
1016 (python-indent-calculate-levels))
1017 (let* ((starting-pos (point-marker))
1018 (indent-ending-position
1019 (+ (line-beginning-position) (current-indentation)))
1020 (follow-indentation-p
1022 (and (<= (line-beginning-position) starting-pos
)
1023 (>= indent-ending-position starting-pos
))))
1024 (next-indent (nth python-indent-current-level python-indent-levels
)))
1025 (unless (= next-indent
(current-indentation))
1027 (delete-horizontal-space)
1028 (indent-to next-indent
)
1029 (goto-char starting-pos
))
1030 (and follow-indentation-p
(back-to-indentation)))
1031 (python-info-dedenter-opening-block-message))
1033 (defun python-indent-line-function ()
1034 "`indent-line-function' for Python mode.
1035 See `python-indent-line' for details."
1036 (python-indent-line))
1038 (defun python-indent-dedent-line ()
1039 "De-indent current line."
1041 (when (and (not (python-syntax-comment-or-string-p))
1042 (<= (point-marker) (save-excursion
1043 (back-to-indentation)
1045 (> (current-column) 0))
1046 (python-indent-line t
)
1049 (defun python-indent-dedent-line-backspace (arg)
1050 "De-indent current line.
1051 Argument ARG is passed to `backward-delete-char-untabify' when
1052 point is not in between the indentation."
1054 (when (not (python-indent-dedent-line))
1055 (backward-delete-char-untabify arg
)))
1056 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1058 (defun python-indent-region (start end
)
1059 "Indent a Python region automagically.
1061 Called from a program, START and END specify the region to indent."
1062 (let ((deactivate-mark nil
))
1065 (setq end
(point-marker))
1067 (or (bolp) (forward-line 1))
1068 (while (< (point) end
)
1069 (or (and (bolp) (eolp))
1071 ;; Skip if previous line is empty or a comment.
1073 (let ((line-is-comment-p
1074 (python-info-current-line-comment-p)))
1077 (or (and (python-info-current-line-comment-p)
1078 ;; Unless this line is a comment too.
1079 (not line-is-comment-p
))
1080 (python-info-current-line-empty-p)))))
1081 ;; Don't mess with strings, unless it's the
1082 ;; enclosing set of quotes.
1083 (or (not (python-syntax-context 'string
))
1087 (current-indentation)
1088 (python-syntax-count-quotes (char-after) (point))))
1089 (string-to-syntax "|")))
1090 ;; Skip if current line is a block start, a
1091 ;; dedenter or block ender.
1093 (back-to-indentation)
1096 (or block-start dedenter block-ender
))))))
1097 (python-indent-line)))
1099 (move-marker end nil
))))
1101 (defun python-indent-shift-left (start end
&optional count
)
1102 "Shift lines contained in region START END by COUNT columns to the left.
1103 COUNT defaults to `python-indent-offset'. If region isn't
1104 active, the current line is shifted. The shifted region includes
1105 the lines in which START and END lie. An error is signaled if
1106 any lines in the region are indented less than COUNT columns."
1109 (list (region-beginning) (region-end) current-prefix-arg
)
1110 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1112 (setq count
(prefix-numeric-value count
))
1113 (setq count python-indent-offset
))
1115 (let ((deactivate-mark nil
))
1118 (while (< (point) end
)
1119 (if (and (< (current-indentation) count
)
1120 (not (looking-at "[ \t]*$")))
1121 (error "Can't shift all lines enough"))
1123 (indent-rigidly start end
(- count
))))))
1125 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1127 (defun python-indent-shift-right (start end
&optional count
)
1128 "Shift lines contained in region START END by COUNT columns to the right.
1129 COUNT defaults to `python-indent-offset'. If region isn't
1130 active, the current line is shifted. The shifted region includes
1131 the lines in which START and END lie."
1134 (list (region-beginning) (region-end) current-prefix-arg
)
1135 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1136 (let ((deactivate-mark nil
))
1137 (setq count
(if count
(prefix-numeric-value count
)
1138 python-indent-offset
))
1139 (indent-rigidly start end count
)))
1141 (defun python-indent-post-self-insert-function ()
1142 "Adjust indentation after insertion of some characters.
1143 This function is intended to be added to `post-self-insert-hook.'
1144 If a line renders a paren alone, after adding a char before it,
1145 the line will be re-indented automatically if needed."
1146 (when (and electric-indent-mode
1147 (eq (char-before) last-command-event
))
1149 ;; Electric indent inside parens
1152 (let ((paren-start (python-syntax-context 'paren
)))
1153 ;; Check that point is inside parens.
1156 ;; Filter the case where input is happening in the same
1157 ;; line where the open paren is.
1158 (= (line-number-at-pos)
1159 (line-number-at-pos paren-start
)))))
1160 ;; When content has been added before the closing paren or a
1161 ;; comma has been inserted, it's ok to do the trick.
1163 (memq (char-after) '(?\
) ?\
] ?\
}))
1164 (eq (char-before) ?
,)))
1166 (goto-char (line-beginning-position))
1167 (let ((indentation (python-indent-calculate-indentation)))
1168 (when (< (current-indentation) indentation
)
1169 (indent-line-to indentation
)))))
1171 ((and (eq ?
: last-command-event
)
1172 (memq ?
: electric-indent-chars
)
1173 (not current-prefix-arg
)
1174 ;; Trigger electric colon only at end of line
1176 ;; Avoid re-indenting on extra colon
1177 (not (equal ?
: (char-before (1- (point)))))
1178 (not (python-syntax-comment-or-string-p))
1179 ;; Never re-indent at beginning of defun
1180 (not (save-excursion
1181 (python-nav-beginning-of-statement)
1182 (python-info-looking-at-beginning-of-defun))))
1183 (python-indent-line)))))
1188 (defvar python-nav-beginning-of-defun-regexp
1189 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1190 "Regexp matching class or function definition.
1191 The name of the defun should be grouped so it can be retrieved
1192 via `match-string'.")
1194 (defun python-nav--beginning-of-defun (&optional arg
)
1195 "Internal implementation of `python-nav-beginning-of-defun'.
1196 With positive ARG search backwards, else search forwards."
1197 (when (or (null arg
) (= arg
0)) (setq arg
1))
1198 (let* ((re-search-fn (if (> arg
0)
1199 #'re-search-backward
1200 #'re-search-forward
))
1201 (line-beg-pos (line-beginning-position))
1202 (line-content-start (+ line-beg-pos
(current-indentation)))
1203 (pos (point-marker))
1208 (not (python-info-looking-at-beginning-of-defun))
1209 (python-nav-backward-block)))
1210 (or (and (python-info-looking-at-beginning-of-defun)
1211 (+ (current-indentation) python-indent-offset
))
1215 (when (and (< arg
0)
1216 (python-info-looking-at-beginning-of-defun))
1218 (while (and (funcall re-search-fn
1219 python-nav-beginning-of-defun-regexp nil t
)
1220 (or (python-syntax-context-type)
1221 ;; Handle nested defuns when moving
1222 ;; backwards by checking indentation.
1224 (not (= (current-indentation) 0))
1225 (>= (current-indentation) beg-indentation
)))))
1226 (and (python-info-looking-at-beginning-of-defun)
1227 (or (not (= (line-number-at-pos pos
)
1228 (line-number-at-pos)))
1229 (and (>= (point) line-beg-pos
)
1230 (<= (point) line-content-start
)
1231 (> pos line-content-start
)))))))
1233 (or (beginning-of-line 1) t
)
1234 (and (goto-char pos
) nil
))))
1236 (defun python-nav-beginning-of-defun (&optional arg
)
1237 "Move point to `beginning-of-defun'.
1238 With positive ARG search backwards else search forward.
1239 ARG nil or 0 defaults to 1. When searching backwards,
1240 nested defuns are handled with care depending on current
1241 point position. Return non-nil if point is moved to
1242 `beginning-of-defun'."
1243 (when (or (null arg
) (= arg
0)) (setq arg
1))
1245 (while (and (not (= arg
0))
1246 (let ((keep-searching-p
1247 (python-nav--beginning-of-defun arg)))
1248 (when (and keep-searching-p
(null found
))
1251 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1254 (defun python-nav-end-of-defun ()
1255 "Move point to the end of def or class.
1256 Returns nil if point is not in a def or class."
1258 (let ((beg-defun-indent)
1260 (when (or (python-info-looking-at-beginning-of-defun)
1261 (python-nav-beginning-of-defun 1)
1262 (python-nav-beginning-of-defun -1))
1263 (setq beg-defun-indent
(current-indentation))
1265 (python-nav-end-of-statement)
1266 (python-util-forward-comment 1)
1267 (and (> (current-indentation) beg-defun-indent
)
1269 (python-util-forward-comment -
1)
1271 ;; Ensure point moves forward.
1272 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1274 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1275 "Move point using FN avoiding places with specific context.
1276 FN must take no arguments. POSCOMPFN is a two arguments function
1277 used to compare current and previous point after it is moved
1278 using FN, this is normally a less-than or greater-than
1279 comparison. Optional argument CONTEXTFN defaults to
1280 `python-syntax-context-type' and is used for checking current
1281 point context, it must return a non-nil value if this point must
1283 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1284 (start-pos (point-marker))
1289 (and (funcall fn
) (point-marker)))
1290 (context (funcall contextfn
)))
1291 (cond ((and (not context
) newpos
1292 (or (and (not prev-pos
) newpos
)
1293 (and prev-pos newpos
1294 (funcall poscompfn newpos prev-pos
))))
1295 (throw 'found
(point-marker)))
1296 ((and newpos context
)
1297 (setq prev-pos
(point)))
1298 (t (when (not newpos
) (goto-char start-pos
))
1299 (throw 'found nil
))))))))
1301 (defun python-nav--forward-defun (arg)
1302 "Internal implementation of python-nav-{backward,forward}-defun.
1303 Uses ARG to define which function to call, and how many times
1306 (while (and (> arg
0)
1308 (python-nav--syntactically
1311 python-nav-beginning-of-defun-regexp nil t
))
1313 (setq arg
(1- arg
)))
1314 (while (and (< arg
0)
1316 (python-nav--syntactically
1319 python-nav-beginning-of-defun-regexp nil t
))
1321 (setq arg
(1+ arg
)))
1324 (defun python-nav-backward-defun (&optional arg
)
1325 "Navigate to closer defun backward ARG times.
1326 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1327 nested definitions."
1329 (python-nav--forward-defun (- (or arg
1))))
1331 (defun python-nav-forward-defun (&optional arg
)
1332 "Navigate to closer defun forward ARG times.
1333 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1334 nested definitions."
1336 (python-nav--forward-defun (or arg
1)))
1338 (defun python-nav-beginning-of-statement ()
1339 "Move to start of current statement."
1341 (back-to-indentation)
1342 (let* ((ppss (syntax-ppss))
1345 (python-syntax-context 'paren ppss
)
1346 (python-syntax-context 'string ppss
))))
1349 (goto-char context-point
)
1350 (python-nav-beginning-of-statement))
1353 (python-info-line-ends-backslash-p))
1355 (python-nav-beginning-of-statement))))
1358 (defun python-nav-end-of-statement (&optional noend
)
1359 "Move to end of current statement.
1360 Optional argument NOEND is internal and makes the logic to not
1361 jump to the end of line when moving forward searching for the end
1364 (let (string-start bs-pos
)
1365 (while (and (or noend
(goto-char (line-end-position)))
1367 (cond ((setq string-start
(python-syntax-context 'string
))
1368 (goto-char string-start
)
1369 (if (python-syntax-context 'paren
)
1370 ;; Ended up inside a paren, roll again.
1371 (python-nav-end-of-statement t
)
1372 ;; This is not inside a paren, move to the
1373 ;; end of this string.
1374 (goto-char (+ (point)
1375 (python-syntax-count-quotes
1376 (char-after (point)) (point))))
1377 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1378 (goto-char (point-max)))))
1379 ((python-syntax-context 'paren
)
1380 ;; The statement won't end before we've escaped
1381 ;; at least one level of parenthesis.
1383 (goto-char (scan-lists (point) 1 -
1))
1384 (scan-error (goto-char (nth 3 err
)))))
1385 ((setq bs-pos
(python-info-line-ends-backslash-p))
1387 (forward-line 1))))))
1390 (defun python-nav-backward-statement (&optional arg
)
1391 "Move backward to previous statement.
1392 With ARG, repeat. See `python-nav-forward-statement'."
1394 (or arg
(setq arg
1))
1395 (python-nav-forward-statement (- arg
)))
1397 (defun python-nav-forward-statement (&optional arg
)
1398 "Move forward to next statement.
1399 With ARG, repeat. With negative argument, move ARG times
1400 backward to previous statement."
1402 (or arg
(setq arg
1))
1404 (python-nav-end-of-statement)
1405 (python-util-forward-comment)
1406 (python-nav-beginning-of-statement)
1407 (setq arg
(1- arg
)))
1409 (python-nav-beginning-of-statement)
1410 (python-util-forward-comment -
1)
1411 (python-nav-beginning-of-statement)
1412 (setq arg
(1+ arg
))))
1414 (defun python-nav-beginning-of-block ()
1415 "Move to start of current block."
1417 (let ((starting-pos (point)))
1419 (python-nav-beginning-of-statement)
1420 (looking-at (python-rx block-start
)))
1422 ;; Go to first line beginning a statement
1423 (while (and (not (bobp))
1424 (or (and (python-nav-beginning-of-statement) nil
)
1425 (python-info-current-line-comment-p)
1426 (python-info-current-line-empty-p)))
1428 (let ((block-matching-indent
1429 (- (current-indentation) python-indent-offset
)))
1431 (and (python-nav-backward-block)
1432 (> (current-indentation) block-matching-indent
)))
1433 (if (and (looking-at (python-rx block-start
))
1434 (= (current-indentation) block-matching-indent
))
1436 (and (goto-char starting-pos
) nil
))))))
1438 (defun python-nav-end-of-block ()
1439 "Move to end of current block."
1441 (when (python-nav-beginning-of-block)
1442 (let ((block-indentation (current-indentation)))
1443 (python-nav-end-of-statement)
1444 (while (and (forward-line 1)
1446 (or (and (> (current-indentation) block-indentation
)
1447 (or (python-nav-end-of-statement) t
))
1448 (python-info-current-line-comment-p)
1449 (python-info-current-line-empty-p))))
1450 (python-util-forward-comment -
1)
1453 (defun python-nav-backward-block (&optional arg
)
1454 "Move backward to previous block of code.
1455 With ARG, repeat. See `python-nav-forward-block'."
1457 (or arg
(setq arg
1))
1458 (python-nav-forward-block (- arg
)))
1460 (defun python-nav-forward-block (&optional arg
)
1461 "Move forward to next block of code.
1462 With ARG, repeat. With negative argument, move ARG times
1463 backward to previous block."
1465 (or arg
(setq arg
1))
1466 (let ((block-start-regexp
1467 (python-rx line-start
(* whitespace
) block-start
))
1468 (starting-pos (point)))
1470 (python-nav-end-of-statement)
1472 (re-search-forward block-start-regexp nil t
)
1473 (python-syntax-context-type)))
1474 (setq arg
(1- arg
)))
1476 (python-nav-beginning-of-statement)
1478 (re-search-backward block-start-regexp nil t
)
1479 (python-syntax-context-type)))
1480 (setq arg
(1+ arg
)))
1481 (python-nav-beginning-of-statement)
1482 (if (not (looking-at (python-rx block-start
)))
1483 (and (goto-char starting-pos
) nil
)
1484 (and (not (= (point) starting-pos
)) (point-marker)))))
1486 (defun python-nav--lisp-forward-sexp (&optional arg
)
1487 "Standard version `forward-sexp'.
1488 It ignores completely the value of `forward-sexp-function' by
1489 setting it to nil before calling `forward-sexp'. With positive
1490 ARG move forward only one sexp, else move backwards."
1491 (let ((forward-sexp-function)
1492 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1493 (forward-sexp arg
)))
1495 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1496 "Safe version of standard `forward-sexp'.
1497 When at end of sexp (i.e. looking at a opening/closing paren)
1498 skips it instead of throwing an error. With positive ARG move
1499 forward only one sexp, else move backwards."
1500 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1502 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1504 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1506 (python-nav--lisp-forward-sexp arg
)
1508 (while (and (funcall search-fn paren-regexp nil t
)
1509 (python-syntax-context 'paren
)))))))
1511 (defun python-nav--forward-sexp (&optional dir safe
)
1512 "Move to forward sexp.
1513 With positive optional argument DIR direction move forward, else
1514 backwards. When optional argument SAFE is non-nil do not throw
1515 errors when at end of sexp, skip it instead."
1516 (setq dir
(or dir
1))
1518 (let* ((forward-p (if (> dir
0)
1519 (and (setq dir
1) t
)
1520 (and (setq dir -
1) nil
)))
1521 (context-type (python-syntax-context-type)))
1523 ((memq context-type
'(string comment
))
1524 ;; Inside of a string, get out of it.
1525 (let ((forward-sexp-function))
1526 (forward-sexp dir
)))
1527 ((or (eq context-type
'paren
)
1528 (and forward-p
(looking-at (python-rx open-paren
)))
1529 (and (not forward-p
)
1530 (eq (syntax-class (syntax-after (1- (point))))
1531 (car (string-to-syntax ")")))))
1532 ;; Inside a paren or looking at it, lisp knows what to do.
1534 (python-nav--lisp-forward-sexp-safe dir
)
1535 (python-nav--lisp-forward-sexp dir
)))
1537 ;; This part handles the lispy feel of
1538 ;; `python-nav-forward-sexp'. Knowing everything about the
1539 ;; current context and the context of the next sexp tries to
1540 ;; follow the lisp sexp motion commands in a symmetric manner.
1543 ((python-info-beginning-of-block-p) 'block-start
)
1544 ((python-info-end-of-block-p) 'block-end
)
1545 ((python-info-beginning-of-statement-p) 'statement-start
)
1546 ((python-info-end-of-statement-p) 'statement-end
)))
1550 (python-nav--lisp-forward-sexp-safe dir
)
1551 (python-nav--lisp-forward-sexp dir
))
1555 (goto-char next-sexp-pos
)
1557 ((python-info-beginning-of-block-p) 'block-start
)
1558 ((python-info-end-of-block-p) 'block-end
)
1559 ((python-info-beginning-of-statement-p) 'statement-start
)
1560 ((python-info-end-of-statement-p) 'statement-end
)
1561 ((python-info-statement-starts-block-p) 'starts-block
)
1562 ((python-info-statement-ends-block-p) 'ends-block
)))))
1564 (cond ((and (not (eobp))
1565 (python-info-current-line-empty-p))
1566 (python-util-forward-comment dir
)
1567 (python-nav--forward-sexp dir
))
1568 ((eq context
'block-start
)
1569 (python-nav-end-of-block))
1570 ((eq context
'statement-start
)
1571 (python-nav-end-of-statement))
1572 ((and (memq context
'(statement-end block-end
))
1573 (eq next-sexp-context
'ends-block
))
1574 (goto-char next-sexp-pos
)
1575 (python-nav-end-of-block))
1576 ((and (memq context
'(statement-end block-end
))
1577 (eq next-sexp-context
'starts-block
))
1578 (goto-char next-sexp-pos
)
1579 (python-nav-end-of-block))
1580 ((memq context
'(statement-end block-end
))
1581 (goto-char next-sexp-pos
)
1582 (python-nav-end-of-statement))
1583 (t (goto-char next-sexp-pos
)))
1584 (cond ((and (not (bobp))
1585 (python-info-current-line-empty-p))
1586 (python-util-forward-comment dir
)
1587 (python-nav--forward-sexp dir
))
1588 ((eq context
'block-end
)
1589 (python-nav-beginning-of-block))
1590 ((eq context
'statement-end
)
1591 (python-nav-beginning-of-statement))
1592 ((and (memq context
'(statement-start block-start
))
1593 (eq next-sexp-context
'starts-block
))
1594 (goto-char next-sexp-pos
)
1595 (python-nav-beginning-of-block))
1596 ((and (memq context
'(statement-start block-start
))
1597 (eq next-sexp-context
'ends-block
))
1598 (goto-char next-sexp-pos
)
1599 (python-nav-beginning-of-block))
1600 ((memq context
'(statement-start block-start
))
1601 (goto-char next-sexp-pos
)
1602 (python-nav-beginning-of-statement))
1603 (t (goto-char next-sexp-pos
))))))))))
1605 (defun python-nav-forward-sexp (&optional arg
)
1606 "Move forward across expressions.
1607 With ARG, do it that many times. Negative arg -N means move
1610 (or arg
(setq arg
1))
1612 (python-nav--forward-sexp 1)
1613 (setq arg
(1- arg
)))
1615 (python-nav--forward-sexp -
1)
1616 (setq arg
(1+ arg
))))
1618 (defun python-nav-backward-sexp (&optional arg
)
1619 "Move backward across expressions.
1620 With ARG, do it that many times. Negative arg -N means move
1623 (or arg
(setq arg
1))
1624 (python-nav-forward-sexp (- arg
)))
1626 (defun python-nav-forward-sexp-safe (&optional arg
)
1627 "Move forward safely across expressions.
1628 With ARG, do it that many times. Negative arg -N means move
1631 (or arg
(setq arg
1))
1633 (python-nav--forward-sexp 1 t
)
1634 (setq arg
(1- arg
)))
1636 (python-nav--forward-sexp -
1 t
)
1637 (setq arg
(1+ arg
))))
1639 (defun python-nav-backward-sexp-safe (&optional arg
)
1640 "Move backward safely across expressions.
1641 With ARG, do it that many times. Negative arg -N means move
1644 (or arg
(setq arg
1))
1645 (python-nav-forward-sexp-safe (- arg
)))
1647 (defun python-nav--up-list (&optional dir
)
1648 "Internal implementation of `python-nav-up-list'.
1649 DIR is always 1 or -1 and comes sanitized from
1650 `python-nav-up-list' calls."
1651 (let ((context (python-syntax-context-type))
1652 (forward-p (> dir
0)))
1654 ((memq context
'(string comment
)))
1655 ((eq context
'paren
)
1656 (let ((forward-sexp-function))
1658 ((and forward-p
(python-info-end-of-block-p))
1659 (let ((parent-end-pos
1661 (let ((indentation (and
1662 (python-nav-beginning-of-block)
1663 (current-indentation))))
1664 (while (and indentation
1666 (>= (current-indentation) indentation
)
1667 (python-nav-backward-block)))
1668 (python-nav-end-of-block)))))
1669 (and (> (or parent-end-pos
(point)) (point))
1670 (goto-char parent-end-pos
))))
1671 (forward-p (python-nav-end-of-block))
1672 ((and (not forward-p
)
1673 (> (current-indentation) 0)
1674 (python-info-beginning-of-block-p))
1675 (let ((prev-block-pos
1677 (let ((indentation (current-indentation)))
1678 (while (and (python-nav-backward-block)
1679 (>= (current-indentation) indentation
))))
1681 (and (> (point) prev-block-pos
)
1682 (goto-char prev-block-pos
))))
1683 ((not forward-p
) (python-nav-beginning-of-block)))))
1685 (defun python-nav-up-list (&optional arg
)
1686 "Move forward out of one level of parentheses (or blocks).
1687 With ARG, do this that many times.
1688 A negative argument means move backward but still to a less deep spot.
1689 This command assumes point is not in a string or comment."
1691 (or arg
(setq arg
1))
1693 (python-nav--up-list 1)
1694 (setq arg
(1- arg
)))
1696 (python-nav--up-list -
1)
1697 (setq arg
(1+ arg
))))
1699 (defun python-nav-backward-up-list (&optional arg
)
1700 "Move backward out of one level of parentheses (or blocks).
1701 With ARG, do this that many times.
1702 A negative argument means move forward but still to a less deep spot.
1703 This command assumes point is not in a string or comment."
1705 (or arg
(setq arg
1))
1706 (python-nav-up-list (- arg
)))
1708 (defun python-nav-if-name-main ()
1709 "Move point at the beginning the __main__ block.
1710 When \"if __name__ == '__main__':\" is found returns its
1711 position, else returns nil."
1713 (let ((point (point))
1714 (found (catch 'found
1715 (goto-char (point-min))
1716 (while (re-search-forward
1717 (python-rx line-start
1719 "__name__" (+ space
)
1721 (group-n 1 (or ?
\" ?
\'))
1722 "__main__" (backref 1) (* space
) ":")
1724 (when (not (python-syntax-context-type))
1726 (throw 'found t
))))))
1729 (ignore (goto-char point
)))))
1732 ;;; Shell integration
1734 (defcustom python-shell-buffer-name
"Python"
1735 "Default buffer name for Python interpreter."
1740 (defcustom python-shell-interpreter
"python"
1741 "Default Python interpreter for shell."
1745 (defcustom python-shell-internal-buffer-name
"Python Internal"
1746 "Default buffer name for the Internal Python interpreter."
1751 (defcustom python-shell-interpreter-args
"-i"
1752 "Default arguments for the Python interpreter."
1756 (defcustom python-shell-interpreter-interactive-arg
"-i"
1757 "Interpreter argument to force it to run interactively."
1761 (defcustom python-shell-prompt-detect-enabled t
1762 "Non-nil enables autodetection of interpreter prompts."
1767 (defcustom python-shell-prompt-detect-failure-warning t
1768 "Non-nil enables warnings when detection of prompts fail."
1773 (defcustom python-shell-prompt-input-regexps
1774 '(">>> " "\\.\\.\\. " ; Python
1775 "In \\[[0-9]+\\]: " ; IPython
1776 ;; Using ipdb outside IPython may fail to cleanup and leave static
1777 ;; IPython prompts activated, this adds some safeguard for that.
1778 "In : " "\\.\\.\\.: ")
1779 "List of regular expressions matching input prompts."
1780 :type
'(repeat string
)
1783 (defcustom python-shell-prompt-output-regexps
1785 "Out\\[[0-9]+\\]: " ; IPython
1786 "Out :") ; ipdb safeguard
1787 "List of regular expressions matching output prompts."
1788 :type
'(repeat string
)
1791 (defcustom python-shell-prompt-regexp
">>> "
1792 "Regular expression matching top level input prompt of Python shell.
1793 It should not contain a caret (^) at the beginning."
1796 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1797 "Regular expression matching block input prompt of Python shell.
1798 It should not contain a caret (^) at the beginning."
1801 (defcustom python-shell-prompt-output-regexp
""
1802 "Regular expression matching output prompt of Python shell.
1803 It should not contain a caret (^) at the beginning."
1806 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1807 "Regular expression matching pdb input prompt of Python shell.
1808 It should not contain a caret (^) at the beginning."
1811 (defcustom python-shell-enable-font-lock t
1812 "Should syntax highlighting be enabled in the Python shell buffer?
1813 Restart the Python shell after changing this variable for it to take effect."
1818 (defcustom python-shell-unbuffered t
1819 "Should shell output be unbuffered?.
1820 When non-nil, this may prevent delayed and missing output in the
1821 Python shell. See commentary for details."
1826 (defcustom python-shell-process-environment nil
1827 "List of environment variables for Python shell.
1828 This variable follows the same rules as `process-environment'
1829 since it merges with it before the process creation routines are
1830 called. When this variable is nil, the Python shell is run with
1831 the default `process-environment'."
1832 :type
'(repeat string
)
1836 (defcustom python-shell-extra-pythonpaths nil
1837 "List of extra pythonpaths for Python shell.
1838 The values of this variable are added to the existing value of
1839 PYTHONPATH in the `process-environment' variable."
1840 :type
'(repeat string
)
1844 (defcustom python-shell-exec-path nil
1845 "List of path to search for binaries.
1846 This variable follows the same rules as `exec-path' since it
1847 merges with it before the process creation routines are called.
1848 When this variable is nil, the Python shell is run with the
1849 default `exec-path'."
1850 :type
'(repeat string
)
1854 (defcustom python-shell-virtualenv-path nil
1855 "Path to virtualenv root.
1856 This variable, when set to a string, makes the values stored in
1857 `python-shell-process-environment' and `python-shell-exec-path'
1858 to be modified properly so shells are started with the specified
1860 :type
'(choice (const nil
) string
)
1864 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1865 python-ffap-setup-code
1866 python-eldoc-setup-code
)
1867 "List of code run by `python-shell-send-setup-codes'."
1868 :type
'(repeat symbol
)
1872 (defcustom python-shell-compilation-regexp-alist
1873 `((,(rx line-start
(1+ (any " \t")) "File \""
1874 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1875 "\", line " (group (1+ digit
)))
1877 (,(rx " in file " (group (1+ not-newline
)) " on line "
1880 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1881 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1883 "`compilation-error-regexp-alist' for inferior Python."
1884 :type
'(alist string
)
1887 (defvar python-shell--prompt-calculated-input-regexp nil
1888 "Calculated input prompt regexp for inferior python shell.
1889 Do not set this variable directly, instead use
1890 `python-shell-prompt-set-calculated-regexps'.")
1892 (defvar python-shell--prompt-calculated-output-regexp nil
1893 "Calculated output prompt regexp for inferior python shell.
1894 Do not set this variable directly, instead use
1895 `python-shell-set-prompt-regexp'.")
1897 (defun python-shell-prompt-detect ()
1898 "Detect prompts for the current `python-shell-interpreter'.
1899 When prompts can be retrieved successfully from the
1900 `python-shell-interpreter' run with
1901 `python-shell-interpreter-interactive-arg', returns a list of
1902 three elements, where the first two are input prompts and the
1903 last one is an output prompt. When no prompts can be detected
1904 and `python-shell-prompt-detect-failure-warning' is non-nil,
1905 shows a warning with instructions to avoid hangs and returns nil.
1906 When `python-shell-prompt-detect-enabled' is nil avoids any
1907 detection and just returns nil."
1908 (when python-shell-prompt-detect-enabled
1909 (let* ((process-environment (python-shell-calculate-process-environment))
1910 (exec-path (python-shell-calculate-exec-path))
1913 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1914 ;; JSON is built manually for compatibility
1915 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1920 ;; TODO: improve error handling by using
1921 ;; `condition-case' and displaying the error message to
1922 ;; the user in the no-prompts warning.
1924 (let ((code-file (python-shell--save-temp-file code
)))
1925 ;; Use `process-file' as it is remote-host friendly.
1927 python-shell-interpreter
1931 python-shell-interpreter-interactive-arg
)
1933 (delete-file code-file
)))
1937 (dolist (line (split-string output
"\n" t
))
1939 ;; Check if current line is a valid JSON array
1940 (and (string= (substring line
0 2) "[\"")
1942 ;; Return prompts as a list, not vector
1943 (append (json-read-from-string line
) nil
)))))
1944 ;; The list must contain 3 strings, where the first
1945 ;; is the input prompt, the second is the block
1946 ;; prompt and the last one is the output prompt. The
1947 ;; input prompt is the only one that can't be empty.
1948 (when (and (= (length res
) 3)
1949 (cl-every #'stringp res
)
1950 (not (string= (car res
) "")))
1951 (throw 'prompts res
))))
1953 (when (and (not prompts
)
1954 python-shell-prompt-detect-failure-warning
)
1957 "Python shell prompts cannot be detected.\n"
1958 "If your emacs session hangs when starting python shells\n"
1959 "recover with `keyboard-quit' and then try fixing the\n"
1960 "interactive flag for your interpreter by adjusting the\n"
1961 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1962 "matching shell prompts in the directory-local friendly vars:\n"
1963 " + `python-shell-prompt-regexp'\n"
1964 " + `python-shell-prompt-block-regexp'\n"
1965 " + `python-shell-prompt-output-regexp'\n"
1966 "Or alternatively in:\n"
1967 " + `python-shell-prompt-input-regexps'\n"
1968 " + `python-shell-prompt-output-regexps'")))
1971 (defun python-shell-prompt-validate-regexps ()
1972 "Validate all user provided regexps for prompts.
1973 Signals `user-error' if any of these vars contain invalid
1974 regexps: `python-shell-prompt-regexp',
1975 `python-shell-prompt-block-regexp',
1976 `python-shell-prompt-pdb-regexp',
1977 `python-shell-prompt-output-regexp',
1978 `python-shell-prompt-input-regexps',
1979 `python-shell-prompt-output-regexps'."
1980 (dolist (symbol (list 'python-shell-prompt-input-regexps
1981 'python-shell-prompt-output-regexps
1982 'python-shell-prompt-regexp
1983 'python-shell-prompt-block-regexp
1984 'python-shell-prompt-pdb-regexp
1985 'python-shell-prompt-output-regexp
))
1986 (dolist (regexp (let ((regexps (symbol-value symbol
)))
1990 (when (not (python-util-valid-regexp-p regexp
))
1991 (user-error "Invalid regexp %s in `%s'"
1994 (defun python-shell-prompt-set-calculated-regexps ()
1995 "Detect and set input and output prompt regexps.
1996 Build and set the values for `python-shell-input-prompt-regexp'
1997 and `python-shell-output-prompt-regexp' using the values from
1998 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
1999 `python-shell-prompt-pdb-regexp',
2000 `python-shell-prompt-output-regexp',
2001 `python-shell-prompt-input-regexps',
2002 `python-shell-prompt-output-regexps' and detected prompts from
2003 `python-shell-prompt-detect'."
2004 (when (not (and python-shell--prompt-calculated-input-regexp
2005 python-shell--prompt-calculated-output-regexp
))
2006 (let* ((detected-prompts (python-shell-prompt-detect))
2008 (output-prompts nil
)
2012 (mapconcat #'identity
2015 (let ((length-a (length a
))
2016 (length-b (length b
)))
2017 (if (= length-a length-b
)
2019 (> (length a
) (length b
))))))
2022 ;; Validate ALL regexps
2023 (python-shell-prompt-validate-regexps)
2024 ;; Collect all user defined input prompts
2025 (dolist (prompt (append python-shell-prompt-input-regexps
2026 (list python-shell-prompt-regexp
2027 python-shell-prompt-block-regexp
2028 python-shell-prompt-pdb-regexp
)))
2029 (cl-pushnew prompt input-prompts
:test
#'string
=))
2030 ;; Collect all user defined output prompts
2031 (dolist (prompt (cons python-shell-prompt-output-regexp
2032 python-shell-prompt-output-regexps
))
2033 (cl-pushnew prompt output-prompts
:test
#'string
=))
2034 ;; Collect detected prompts if any
2035 (when detected-prompts
2036 (dolist (prompt (butlast detected-prompts
))
2037 (setq prompt
(regexp-quote prompt
))
2038 (cl-pushnew prompt input-prompts
:test
#'string
=))
2039 (cl-pushnew (regexp-quote
2040 (car (last detected-prompts
)))
2041 output-prompts
:test
#'string
=))
2042 ;; Set input and output prompt regexps from collected prompts
2043 (setq python-shell--prompt-calculated-input-regexp
2044 (funcall build-regexp input-prompts
)
2045 python-shell--prompt-calculated-output-regexp
2046 (funcall build-regexp output-prompts
)))))
2048 (defun python-shell-get-process-name (dedicated)
2049 "Calculate the appropriate process name for inferior Python process.
2050 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2051 returns a string with the form
2052 `python-shell-buffer-name'[variable `buffer-file-name'] else
2053 returns the value of `python-shell-buffer-name'."
2057 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
2058 (format "%s" python-shell-buffer-name
))))
2061 (defun python-shell-internal-get-process-name ()
2062 "Calculate the appropriate process name for Internal Python process.
2063 The name is calculated from `python-shell-global-buffer-name' and
2064 a hash of all relevant global shell settings in order to ensure
2065 uniqueness for different types of configurations."
2067 python-shell-internal-buffer-name
2070 python-shell-interpreter
2071 python-shell-interpreter-args
2072 python-shell--prompt-calculated-input-regexp
2073 python-shell--prompt-calculated-output-regexp
2074 (mapconcat #'symbol-value python-shell-setup-codes
"")
2075 (mapconcat #'identity python-shell-process-environment
"")
2076 (mapconcat #'identity python-shell-extra-pythonpaths
"")
2077 (mapconcat #'identity python-shell-exec-path
"")
2078 (or python-shell-virtualenv-path
"")
2079 (mapconcat #'identity python-shell-exec-path
"")))))
2081 (defun python-shell-parse-command () ;FIXME: why name it "parse"?
2082 "Calculate the string used to execute the inferior Python process."
2083 ;; FIXME: process-environment doesn't seem to be used anywhere within
2085 (let ((process-environment (python-shell-calculate-process-environment))
2086 (exec-path (python-shell-calculate-exec-path)))
2088 ;; FIXME: Why executable-find?
2089 (executable-find python-shell-interpreter
)
2090 python-shell-interpreter-args
)))
2092 (defun python-shell-calculate-process-environment ()
2093 "Calculate process environment given `python-shell-virtualenv-path'."
2094 (let ((process-environment (append
2095 python-shell-process-environment
2096 process-environment nil
))
2097 (virtualenv (if python-shell-virtualenv-path
2098 (directory-file-name python-shell-virtualenv-path
)
2100 (when python-shell-unbuffered
2101 (setenv "PYTHONUNBUFFERED" "1"))
2102 (when python-shell-extra-pythonpaths
2103 (setenv "PYTHONPATH"
2105 (mapconcat 'identity
2106 python-shell-extra-pythonpaths
2109 (or (getenv "PYTHONPATH") ""))))
2110 (if (not virtualenv
)
2112 (setenv "PYTHONHOME" nil
)
2113 (setenv "PATH" (format "%s/bin%s%s"
2114 virtualenv path-separator
2115 (or (getenv "PATH") "")))
2116 (setenv "VIRTUAL_ENV" virtualenv
))
2117 process-environment
))
2119 (defun python-shell-calculate-exec-path ()
2120 "Calculate exec path given `python-shell-virtualenv-path'."
2121 (let ((path (append python-shell-exec-path
2122 exec-path nil
))) ;FIXME: Why nil?
2123 (if (not python-shell-virtualenv-path
)
2125 (cons (expand-file-name "bin" python-shell-virtualenv-path
)
2128 (defun python-comint-output-filter-function (output)
2129 "Hook run after content is put into comint buffer.
2130 OUTPUT is a string with the contents of the buffer."
2131 (ansi-color-filter-apply output
))
2133 (defvar python-shell--parent-buffer nil
)
2135 (defvar python-shell-output-syntax-table
2136 (let ((table (make-syntax-table python-dotty-syntax-table
)))
2137 (modify-syntax-entry ?
\' "." table
)
2138 (modify-syntax-entry ?
\" "." table
)
2139 (modify-syntax-entry ?\
( "." table
)
2140 (modify-syntax-entry ?\
[ "." table
)
2141 (modify-syntax-entry ?\
{ "." table
)
2142 (modify-syntax-entry ?\
) "." table
)
2143 (modify-syntax-entry ?\
] "." table
)
2144 (modify-syntax-entry ?\
} "." table
)
2146 "Syntax table for shell output.
2147 It makes parens and quotes be treated as punctuation chars.")
2149 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2150 "Major mode for Python inferior process.
2151 Runs a Python interpreter as a subprocess of Emacs, with Python
2152 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2153 and `python-shell-interpreter-args' control which Python
2154 interpreter is run. Variables
2155 `python-shell-prompt-regexp',
2156 `python-shell-prompt-output-regexp',
2157 `python-shell-prompt-block-regexp',
2158 `python-shell-enable-font-lock',
2159 `python-shell-completion-setup-code',
2160 `python-shell-completion-string-code',
2161 `python-eldoc-setup-code', `python-eldoc-string-code',
2162 `python-ffap-setup-code' and `python-ffap-string-code' can
2163 customize this mode for different Python interpreters.
2165 You can also add additional setup code to be run at
2166 initialization of the interpreter via `python-shell-setup-codes'
2169 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2170 (let ((interpreter python-shell-interpreter
)
2171 (args python-shell-interpreter-args
))
2172 (when python-shell--parent-buffer
2173 (python-util-clone-local-variables python-shell--parent-buffer
))
2174 ;; Users can override default values for these vars when calling
2175 ;; `run-python'. This ensures new values let-bound in
2176 ;; `python-shell-make-comint' are locally set.
2177 (set (make-local-variable 'python-shell-interpreter
) interpreter
)
2178 (set (make-local-variable 'python-shell-interpreter-args
) args
))
2179 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2180 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2181 (python-shell-prompt-set-calculated-regexps)
2182 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2183 (setq mode-line-process
'(":%s"))
2184 (make-local-variable 'comint-output-filter-functions
)
2185 (add-hook 'comint-output-filter-functions
2186 'python-comint-output-filter-function
)
2187 (add-hook 'comint-output-filter-functions
2188 'python-pdbtrack-comint-output-filter-function
)
2189 (set (make-local-variable 'compilation-error-regexp-alist
)
2190 python-shell-compilation-regexp-alist
)
2191 (define-key inferior-python-mode-map
[remap complete-symbol
]
2192 'completion-at-point
)
2193 (add-hook 'completion-at-point-functions
2194 #'python-shell-completion-complete-at-point nil
'local
)
2195 (add-hook 'comint-dynamic-complete-functions
;FIXME: really?
2196 #'python-shell-completion-complete-at-point nil
'local
)
2197 (define-key inferior-python-mode-map
"\t"
2198 'python-shell-completion-complete-or-indent
)
2199 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2200 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2201 (make-local-variable 'python-shell-internal-last-output
)
2202 (when python-shell-enable-font-lock
2203 (set-syntax-table python-mode-syntax-table
)
2204 (set (make-local-variable 'font-lock-defaults
)
2205 '(python-font-lock-keywords nil nil nil nil
))
2206 (set (make-local-variable 'syntax-propertize-function
)
2208 ;; XXX: Unfortunately eval is needed here to make use of the
2209 ;; dynamic value of `comint-prompt-regexp'.
2210 `(syntax-propertize-rules
2211 (,comint-prompt-regexp
2214 comint-last-input-start end
'syntax-table
2215 python-shell-output-syntax-table
)
2216 ;; XXX: This might look weird, but it is the easiest
2217 ;; way to ensure font lock gets cleaned up before the
2218 ;; current prompt, which is needed for unclosed
2219 ;; strings to not mess up with current input.
2220 (font-lock-unfontify-region comint-last-input-start end
))))
2221 (,(python-rx string-delimiter
)
2223 (and (not (eq (get-text-property start
'field
) 'output
))
2224 (python-syntax-stringify)))))))))
2225 (compilation-shell-minor-mode 1))
2227 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
2228 "Create a Python shell comint buffer.
2229 CMD is the Python command to be executed and PROC-NAME is the
2230 process name the comint buffer will get. After the comint buffer
2231 is created the `inferior-python-mode' is activated. When
2232 optional argument POP is non-nil the buffer is shown. When
2233 optional argument INTERNAL is non-nil this process is run on a
2234 buffer with a name that starts with a space, following the Emacs
2235 convention for temporary/internal buffers, and also makes sure
2236 the user is not queried for confirmation when the process is
2239 (let* ((proc-buffer-name
2240 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
2241 (process-environment (python-shell-calculate-process-environment))
2242 (exec-path (python-shell-calculate-exec-path)))
2243 (when (not (comint-check-proc proc-buffer-name
))
2244 (let* ((cmdlist (split-string-and-unquote cmd
))
2245 (interpreter (car cmdlist
))
2246 (args (cdr cmdlist
))
2247 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2248 interpreter nil args
))
2249 (python-shell--parent-buffer (current-buffer))
2250 (process (get-buffer-process buffer
))
2251 ;; As the user may have overridden default values for
2252 ;; these vars on `run-python', let-binding them allows
2253 ;; to have the new right values in all setup code
2254 ;; that's is done in `inferior-python-mode', which is
2255 ;; important, especially for prompt detection.
2256 (python-shell-interpreter interpreter
)
2257 (python-shell-interpreter-args
2258 (mapconcat #'identity args
" ")))
2259 (with-current-buffer buffer
2260 (inferior-python-mode))
2261 (accept-process-output process
)
2262 (and pop
(pop-to-buffer buffer t
))
2263 (and internal
(set-process-query-on-exit-flag process nil
))))
2267 (defun run-python (cmd &optional dedicated show
)
2268 "Run an inferior Python process.
2269 Input and output via buffer named after
2270 `python-shell-buffer-name'. If there is a process already
2271 running in that buffer, just switch to it.
2273 With argument, allows you to define CMD so you can edit the
2274 command used to call the interpreter and define DEDICATED, so a
2275 dedicated process for the current buffer is open. When numeric
2276 prefix arg is other than 0 or 4 do not SHOW.
2278 Runs the hook `inferior-python-mode-hook' after
2279 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2280 process buffer for a list of commands.)"
2282 (if current-prefix-arg
2284 (read-string "Run Python: " (python-shell-parse-command))
2285 (y-or-n-p "Make dedicated process? ")
2286 (= (prefix-numeric-value current-prefix-arg
) 4))
2287 (list (python-shell-parse-command) nil t
)))
2288 (python-shell-make-comint
2289 cmd
(python-shell-get-process-name dedicated
) show
)
2292 (defun run-python-internal ()
2293 "Run an inferior Internal Python process.
2294 Input and output via buffer named after
2295 `python-shell-internal-buffer-name' and what
2296 `python-shell-internal-get-process-name' returns.
2298 This new kind of shell is intended to be used for generic
2299 communication related to defined configurations; the main
2300 difference with global or dedicated shells is that these ones are
2301 attached to a configuration, not a buffer. This means that can
2302 be used for example to retrieve the sys.path and other stuff,
2303 without messing with user shells. Note that
2304 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
2305 are set to nil for these shells, so setup codes are not sent at
2307 (let ((python-shell-enable-font-lock nil
)
2308 (inferior-python-mode-hook nil
))
2310 (python-shell-make-comint
2311 (python-shell-parse-command)
2312 (python-shell-internal-get-process-name) nil t
))))
2314 (defun python-shell-get-buffer ()
2315 "Return inferior Python buffer for current buffer."
2316 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2317 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2318 (global-proc-name (python-shell-get-process-name nil
))
2319 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2320 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2321 (global-running (comint-check-proc global-proc-buffer-name
)))
2322 ;; Always prefer dedicated
2323 (or (and dedicated-running dedicated-proc-buffer-name
)
2324 (and global-running global-proc-buffer-name
))))
2326 (defun python-shell-get-process ()
2327 "Return inferior Python process for current buffer."
2328 (get-buffer-process (python-shell-get-buffer)))
2330 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2331 "Get or create an inferior Python process for current buffer and return it.
2332 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2333 are used to start the shell. If those arguments are not
2334 provided, `run-python' is called interactively and the user will
2335 be asked for their values."
2336 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2337 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2338 (global-proc-name (python-shell-get-process-name nil
))
2339 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2340 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2341 (global-running (comint-check-proc global-proc-buffer-name
))
2342 (current-prefix-arg 16))
2343 (when (and (not dedicated-running
) (not global-running
))
2345 ;; XXX: Refactor code such that calling `run-python'
2346 ;; interactively is not needed anymore.
2347 (call-interactively 'run-python
)
2348 (run-python cmd dedicated show
))
2349 (setq dedicated-running t
)
2350 (setq global-running t
)))
2351 ;; Always prefer dedicated
2352 (get-buffer-process (if dedicated-running
2353 dedicated-proc-buffer-name
2354 global-proc-buffer-name
))))
2356 (defvar python-shell-internal-buffer nil
2357 "Current internal shell buffer for the current buffer.
2358 This is really not necessary at all for the code to work but it's
2359 there for compatibility with CEDET.")
2361 (defvar python-shell-internal-last-output nil
2362 "Last output captured by the internal shell.
2363 This is really not necessary at all for the code to work but it's
2364 there for compatibility with CEDET.")
2366 (defun python-shell-internal-get-or-create-process ()
2367 "Get or create an inferior Internal Python process."
2368 (let* ((proc-name (python-shell-internal-get-process-name))
2369 (proc-buffer-name (format " *%s*" proc-name
)))
2370 (when (not (process-live-p proc-name
))
2371 (run-python-internal)
2372 (setq python-shell-internal-buffer proc-buffer-name
)
2373 ;; XXX: Why is this `sit-for' needed?
2374 ;; `python-shell-make-comint' calls `accept-process-output'
2375 ;; already but it is not helping to get proper output on
2376 ;; 'gnu/linux when the internal shell process is not running and
2377 ;; a call to `python-shell-internal-send-string' is issued.
2379 (get-buffer-process proc-buffer-name
)))
2381 (define-obsolete-function-alias
2382 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2384 (define-obsolete-variable-alias
2385 'python-buffer
'python-shell-internal-buffer
"24.3")
2387 (define-obsolete-variable-alias
2388 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2390 (defun python-shell--save-temp-file (string)
2391 (let* ((temporary-file-directory
2392 (if (file-remote-p default-directory
)
2393 (concat (file-remote-p default-directory
) "/tmp")
2394 temporary-file-directory
))
2395 (temp-file-name (make-temp-file "py"))
2396 (coding-system-for-write 'utf-8
))
2397 (with-temp-file temp-file-name
2398 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2400 (delete-trailing-whitespace))
2403 (defun python-shell-send-string (string &optional process
)
2404 "Send STRING to inferior Python PROCESS."
2405 (interactive "sPython command: ")
2406 (let ((process (or process
(python-shell-get-or-create-process))))
2407 (if (string-match ".\n+." string
) ;Multiline.
2408 (let* ((temp-file-name (python-shell--save-temp-file string
)))
2409 (python-shell-send-file temp-file-name process temp-file-name t
))
2410 (comint-send-string process string
)
2411 (when (or (not (string-match "\n\\'" string
))
2412 (string-match "\n[ \t].*\n?\\'" string
))
2413 (comint-send-string process
"\n")))))
2415 (defvar python-shell-output-filter-in-progress nil
)
2416 (defvar python-shell-output-filter-buffer nil
)
2418 (defun python-shell-output-filter (string)
2419 "Filter used in `python-shell-send-string-no-output' to grab output.
2420 STRING is the output received to this point from the process.
2421 This filter saves received output from the process in
2422 `python-shell-output-filter-buffer' and stops receiving it after
2423 detecting a prompt at the end of the buffer."
2425 string
(ansi-color-filter-apply string
)
2426 python-shell-output-filter-buffer
2427 (concat python-shell-output-filter-buffer string
))
2429 ;; XXX: It seems on OSX an extra carriage return is attached
2430 ;; at the end of output, this handles that too.
2433 ;; Remove initial caret from calculated regexp
2434 (replace-regexp-in-string
2435 (rx string-start ?^
) ""
2436 python-shell--prompt-calculated-input-regexp
)
2438 python-shell-output-filter-buffer
)
2439 ;; Output ends when `python-shell-output-filter-buffer' contains
2440 ;; the prompt attached at the end of it.
2441 (setq python-shell-output-filter-in-progress nil
2442 python-shell-output-filter-buffer
2443 (substring python-shell-output-filter-buffer
2444 0 (match-beginning 0)))
2446 python-shell--prompt-calculated-output-regexp
2447 python-shell-output-filter-buffer
)
2448 ;; Some shells, like IPython might append a prompt before the
2449 ;; output, clean that.
2450 (setq python-shell-output-filter-buffer
2451 (substring python-shell-output-filter-buffer
(match-end 0)))))
2454 (defun python-shell-send-string-no-output (string &optional process
)
2455 "Send STRING to PROCESS and inhibit output.
2457 (let ((process (or process
(python-shell-get-or-create-process)))
2458 (comint-preoutput-filter-functions
2459 '(python-shell-output-filter))
2460 (python-shell-output-filter-in-progress t
)
2464 (python-shell-send-string string process
)
2465 (while python-shell-output-filter-in-progress
2466 ;; `python-shell-output-filter' takes care of setting
2467 ;; `python-shell-output-filter-in-progress' to NIL after it
2468 ;; detects end of output.
2469 (accept-process-output process
))
2471 python-shell-output-filter-buffer
2472 (setq python-shell-output-filter-buffer nil
)))
2473 (with-current-buffer (process-buffer process
)
2474 (comint-interrupt-subjob)))))
2476 (defun python-shell-internal-send-string (string)
2477 "Send STRING to the Internal Python interpreter.
2478 Returns the output. See `python-shell-send-string-no-output'."
2479 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2480 ;; updated to support this new mode.
2481 (setq python-shell-internal-last-output
2482 (python-shell-send-string-no-output
2483 ;; Makes this function compatible with the old
2484 ;; python-send-receive. (At least for CEDET).
2485 (replace-regexp-in-string "_emacs_out +" "" string
)
2486 (python-shell-internal-get-or-create-process))))
2488 (define-obsolete-function-alias
2489 'python-send-receive
'python-shell-internal-send-string
"24.3")
2491 (define-obsolete-function-alias
2492 'python-send-string
'python-shell-internal-send-string
"24.3")
2494 (defvar python--use-fake-loc nil
2495 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2496 If nil, regions of text are prepended by the corresponding number of empty
2497 lines and Python is told to output error messages referring to the whole
2500 (defun python-shell-buffer-substring (start end
&optional nomain
)
2501 "Send buffer substring from START to END formatted for shell.
2502 This is a wrapper over `buffer-substring' that takes care of
2503 different transformations for the code sent to be evaluated in
2505 1. When optional argument NOMAIN is non-nil everything under an
2506 \"if __name__ == '__main__'\" block will be removed.
2507 2. When a subregion of the buffer is sent, it takes care of
2508 appending extra empty lines so tracebacks are correct.
2509 3. Wraps indented regions under an \"if True:\" block so the
2510 interpreter evaluates them correctly."
2511 (let ((substring (buffer-substring-no-properties start end
))
2512 (fillstr (unless python--use-fake-loc
2513 (make-string (1- (line-number-at-pos start
)) ?
\n)))
2514 (toplevel-block-p (save-excursion
2516 (or (zerop (line-number-at-pos start
))
2518 (python-util-forward-comment 1)
2519 (zerop (current-indentation)))))))
2522 (if fillstr
(insert fillstr
))
2524 (goto-char (point-min))
2525 (unless python--use-fake-loc
2526 ;; python-shell--save-temp-file adds an extra coding line, which would
2527 ;; throw off the line-counts, so let's try to compensate here.
2528 (if (looking-at "[ \t]*[#\n]")
2529 (delete-region (point) (line-beginning-position 2))))
2530 (when (not toplevel-block-p
)
2532 (delete-region (point) (line-end-position)))
2534 (let* ((if-name-main-start-end
2537 (when (python-nav-if-name-main)
2539 (progn (python-nav-forward-sexp-safe)
2541 ;; Oh destructuring bind, how I miss you.
2542 (if-name-main-start (car if-name-main-start-end
))
2543 (if-name-main-end (cdr if-name-main-start-end
)))
2544 (when if-name-main-start-end
2545 (goto-char if-name-main-start
)
2546 (delete-region if-name-main-start if-name-main-end
)
2549 (- (line-number-at-pos if-name-main-end
)
2550 (line-number-at-pos if-name-main-start
)) ?
\n)))))
2551 (buffer-substring-no-properties (point-min) (point-max)))))
2553 (declare-function compilation-fake-loc
"compile"
2554 (marker file
&optional line col
))
2556 (defun python-shell-send-region (start end
&optional nomain
)
2557 "Send the region delimited by START and END to inferior Python process."
2559 (let* ((python--use-fake-loc
2560 (or python--use-fake-loc
(not buffer-file-name
)))
2561 (string (python-shell-buffer-substring start end nomain
))
2562 (process (python-shell-get-or-create-process))
2563 (_ (string-match "\\`\n*\\(.*\\)" string
)))
2564 (message "Sent: %s..." (match-string 1 string
))
2565 (let* ((temp-file-name (python-shell--save-temp-file string
))
2566 (file-name (or (buffer-file-name) temp-file-name
)))
2567 (python-shell-send-file file-name process temp-file-name t
)
2568 (unless python--use-fake-loc
2569 (with-current-buffer (process-buffer process
)
2570 (compilation-fake-loc (copy-marker start
) temp-file-name
2571 2)) ;; Not 1, because of the added coding line.
2574 (defun python-shell-send-buffer (&optional arg
)
2575 "Send the entire buffer to inferior Python process.
2576 With prefix ARG allow execution of code inside blocks delimited
2577 by \"if __name__== '__main__':\"."
2581 (python-shell-send-region (point-min) (point-max) (not arg
))))
2583 (defun python-shell-send-defun (arg)
2584 "Send the current defun to inferior Python process.
2585 When argument ARG is non-nil do not include decorators."
2588 (python-shell-send-region
2591 (while (and (or (python-nav-beginning-of-defun)
2592 (beginning-of-line 1))
2593 (> (current-indentation) 0)))
2595 (while (and (forward-line -
1)
2596 (looking-at (python-rx decorator
))))
2600 (or (python-nav-end-of-defun)
2604 (defun python-shell-send-file (file-name &optional process temp-file-name
2606 "Send FILE-NAME to inferior Python PROCESS.
2607 If TEMP-FILE-NAME is passed then that file is used for processing
2608 instead, while internally the shell will continue to use FILE-NAME.
2609 If DELETE is non-nil, delete the file afterwards."
2610 (interactive "fFile to send: ")
2611 (let* ((process (or process
(python-shell-get-or-create-process)))
2612 (temp-file-name (when temp-file-name
2614 (or (file-remote-p temp-file-name
'localname
)
2616 (file-name (or (when file-name
2618 (or (file-remote-p file-name
'localname
)
2621 (when (not file-name
)
2622 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2623 (python-shell-send-string
2625 (concat "__pyfile = open('''%s''');"
2626 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2627 "__pyfile.close()%s")
2628 (or temp-file-name file-name
) file-name
2629 (if delete
(format "; import os; os.remove('''%s''')"
2630 (or temp-file-name file-name
))
2634 (defun python-shell-switch-to-shell ()
2635 "Switch to inferior Python process buffer."
2637 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2639 (defun python-shell-send-setup-code ()
2640 "Send all setup code for shell.
2641 This function takes the list of setup code to send from the
2642 `python-shell-setup-codes' list."
2643 (let ((process (get-buffer-process (current-buffer))))
2644 (dolist (code python-shell-setup-codes
)
2646 (message "Sent %s" code
)
2647 (python-shell-send-string
2648 (symbol-value code
) process
)))))
2650 (add-hook 'inferior-python-mode-hook
2651 #'python-shell-send-setup-code
)
2654 ;;; Shell completion
2656 (defcustom python-shell-completion-setup-code
2661 import builtins as __builtin__
2663 import readline, rlcompleter
2665 def __PYTHON_EL_get_completions(text):
2668 def __PYTHON_EL_get_completions(text):
2669 builtins = dir(__builtin__)
2672 splits = text.split()
2673 is_module = splits and splits[0] in ('from', 'import')
2674 is_ipython = ('__IPYTHON__' in builtins or
2675 '__IPYTHON__active' in builtins)
2677 from IPython.core.completerlib import module_completion
2678 completions = module_completion(text.strip())
2679 elif is_ipython and '__IP' in builtins:
2680 completions = __IP.complete(text)
2681 elif is_ipython and 'get_ipython' in builtins:
2682 completions = get_ipython().Completer.all_completions(text)
2686 res = readline.get_completer()(text, i)
2690 completions.append(res)
2694 "Code used to setup completion in inferior Python processes."
2698 (defcustom python-shell-completion-string-code
2699 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2700 "Python code used to get a string of completions separated by semicolons.
2701 The string passed to the function is the current python name or
2702 the full statement in the case of imports."
2706 (define-obsolete-variable-alias
2707 'python-shell-completion-module-string-code
2708 'python-shell-completion-string-code
2710 "Completion string code must also autocomplete modules.")
2712 (defcustom python-shell-completion-pdb-string-code
2713 "';'.join(globals().keys() + locals().keys())"
2714 "Python code used to get completions separated by semicolons for [i]pdb."
2718 (defun python-shell-completion-get-completions (process line input
)
2719 "Do completion at point for PROCESS.
2720 LINE is used to detect the context on how to complete given INPUT."
2721 (with-current-buffer (process-buffer process
)
2723 ;; Get last prompt of the inferior process buffer (this
2724 ;; intentionally avoids using `comint-last-prompt' because
2725 ;; of incompatibilities with Emacs 24.x).
2727 (buffer-substring-no-properties
2728 (line-beginning-position) ;End of prompt.
2729 (re-search-backward "^"))))
2731 ;; Check whether a prompt matches a pdb string, an import
2732 ;; statement or just the standard prompt and use the
2733 ;; correct python-shell-completion-*-code string
2734 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2736 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2737 python-shell-completion-pdb-string-code
)
2739 python-shell--prompt-calculated-input-regexp prompt
)
2740 python-shell-completion-string-code
)
2744 (python-rx line-start
(* space
) (or "from" "import") space
)
2748 (and completion-code
2749 (> (length input
) 0)
2751 (python-util-strip-string
2752 (python-shell-send-string-no-output
2753 (format completion-code input
) process
))))
2754 (and (> (length completions
) 2)
2755 (split-string completions
2756 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2758 (defun python-shell-completion-complete-at-point (&optional process
)
2759 "Perform completion at point in inferior Python.
2760 Optional argument PROCESS forces completions to be retrieved
2761 using that one instead of current buffer's process."
2762 (setq process
(or process
(get-buffer-process (current-buffer))))
2765 (with-syntax-table python-dotty-syntax-table
2766 (let* ((paren-depth (car (syntax-ppss)))
2767 (syntax-string "w_")
2768 (syntax-list (string-to-syntax syntax-string
)))
2769 ;; Stop scanning for the beginning of the completion
2770 ;; subject after the char before point matches a
2773 (car (syntax-after (1- (point)))) syntax-list
)
2774 (skip-syntax-backward syntax-string
)
2775 (when (or (equal (char-before) ?\
))
2776 (equal (char-before) ?
\"))
2779 ;; honor initial paren depth
2780 (> (car (syntax-ppss)) paren-depth
)
2781 (python-syntax-context 'string
))
2786 (completion-table-dynamic
2788 #'python-shell-completion-get-completions
2789 process
(buffer-substring-no-properties
2790 (line-beginning-position) end
))))))
2792 (defun python-shell-completion-complete-or-indent ()
2793 "Complete or indent depending on the context.
2794 If content before pointer is all whitespace, indent.
2795 If not try to complete."
2797 (if (string-match "^[[:space:]]*$"
2798 (buffer-substring (comint-line-beginning-position)
2800 (indent-for-tab-command)
2801 (completion-at-point)))
2804 ;;; PDB Track integration
2806 (defcustom python-pdbtrack-activate t
2807 "Non-nil makes Python shell enable pdbtracking."
2812 (defcustom python-pdbtrack-stacktrace-info-regexp
2813 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2814 "Regular expression matching stacktrace information.
2815 Used to extract the current line and module being inspected."
2820 (defvar python-pdbtrack-tracked-buffer nil
2821 "Variable containing the value of the current tracked buffer.
2822 Never set this variable directly, use
2823 `python-pdbtrack-set-tracked-buffer' instead.")
2825 (defvar python-pdbtrack-buffers-to-kill nil
2826 "List of buffers to be deleted after tracking finishes.")
2828 (defun python-pdbtrack-set-tracked-buffer (file-name)
2829 "Set the buffer for FILE-NAME as the tracked buffer.
2830 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2831 Returns the tracked buffer."
2832 (let ((file-buffer (get-file-buffer
2833 (concat (file-remote-p default-directory
)
2836 (setq python-pdbtrack-tracked-buffer file-buffer
)
2837 (setq file-buffer
(find-file-noselect file-name
))
2838 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2839 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2842 (defun python-pdbtrack-comint-output-filter-function (output)
2843 "Move overlay arrow to current pdb line in tracked buffer.
2844 Argument OUTPUT is a string with the output from the comint process."
2845 (when (and python-pdbtrack-activate
(not (string= output
"")))
2846 (let* ((full-output (ansi-color-filter-apply
2847 (buffer-substring comint-last-input-end
(point-max))))
2851 (insert full-output
)
2852 ;; When the debugger encounters a pdb.set_trace()
2853 ;; command, it prints a single stack frame. Sometimes
2854 ;; it prints a bit of extra information about the
2855 ;; arguments of the present function. When ipdb
2856 ;; encounters an exception, it prints the _entire_ stack
2857 ;; trace. To handle all of these cases, we want to find
2858 ;; the _last_ stack frame printed in the most recent
2859 ;; batch of output, then jump to the corresponding
2860 ;; file/line number.
2861 (goto-char (point-max))
2862 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
2863 (setq line-number
(string-to-number
2864 (match-string-no-properties 2)))
2865 (match-string-no-properties 1)))))
2866 (if (and file-name line-number
)
2867 (let* ((tracked-buffer
2868 (python-pdbtrack-set-tracked-buffer file-name
))
2869 (shell-buffer (current-buffer))
2870 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2871 (tracked-buffer-line-pos))
2872 (with-current-buffer tracked-buffer
2873 (set (make-local-variable 'overlay-arrow-string
) "=>")
2874 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2875 (setq tracked-buffer-line-pos
(progn
2876 (goto-char (point-min))
2877 (forward-line (1- line-number
))
2879 (when tracked-buffer-window
2881 tracked-buffer-window tracked-buffer-line-pos
))
2882 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2883 (pop-to-buffer tracked-buffer
)
2884 (switch-to-buffer-other-window shell-buffer
))
2885 (when python-pdbtrack-tracked-buffer
2886 (with-current-buffer python-pdbtrack-tracked-buffer
2887 (set-marker overlay-arrow-position nil
))
2888 (mapc #'(lambda (buffer)
2889 (ignore-errors (kill-buffer buffer
)))
2890 python-pdbtrack-buffers-to-kill
)
2891 (setq python-pdbtrack-tracked-buffer nil
2892 python-pdbtrack-buffers-to-kill nil
)))))
2896 ;;; Symbol completion
2898 (defun python-completion-complete-at-point ()
2899 "Complete current symbol at point.
2900 For this to work as best as possible you should call
2901 `python-shell-send-buffer' from time to time so context in
2902 inferior Python process is updated properly."
2903 (let ((process (python-shell-get-process)))
2905 (error "Completion needs an inferior Python process running")
2906 (python-shell-completion-complete-at-point process
))))
2908 (add-to-list 'debug-ignored-errors
2909 "^Completion needs an inferior Python process running.")
2914 (defcustom python-fill-comment-function
'python-fill-comment
2915 "Function to fill comments.
2916 This is the function used by `python-fill-paragraph' to
2921 (defcustom python-fill-string-function
'python-fill-string
2922 "Function to fill strings.
2923 This is the function used by `python-fill-paragraph' to
2928 (defcustom python-fill-decorator-function
'python-fill-decorator
2929 "Function to fill decorators.
2930 This is the function used by `python-fill-paragraph' to
2935 (defcustom python-fill-paren-function
'python-fill-paren
2936 "Function to fill parens.
2937 This is the function used by `python-fill-paragraph' to
2942 (defcustom python-fill-docstring-style
'pep-257
2943 "Style used to fill docstrings.
2944 This affects `python-fill-string' behavior with regards to
2945 triple quotes positioning.
2947 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
2948 `symmetric', and nil. A value of nil won't care about quotes
2949 position and will treat docstrings a normal string, any other
2950 value may result in one of the following docstring styles:
2955 Process foo, return bar.
2959 Process foo, return bar.
2961 If processing fails throw ProcessingError.
2966 \"\"\"Process foo, return bar.\"\"\"
2969 Process foo, return bar.
2971 If processing fails throw ProcessingError.
2977 \"\"\"Process foo, return bar.\"\"\"
2979 \"\"\"Process foo, return bar.
2981 If processing fails throw ProcessingError.
2987 \"\"\"Process foo, return bar.\"\"\"
2989 \"\"\"Process foo, return bar.
2991 If processing fails throw ProcessingError.
2996 \"\"\"Process foo, return bar.\"\"\"
2999 Process foo, return bar.
3001 If processing fails throw ProcessingError.
3004 (const :tag
"Don't format docstrings" nil
)
3005 (const :tag
"Django's coding standards style." django
)
3006 (const :tag
"One newline and start and Two at end style." onetwo
)
3007 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3008 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3009 (const :tag
"Symmetric style." symmetric
))
3012 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3014 (defun python-fill-paragraph (&optional justify
)
3015 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3016 If any of the current line is in or at the end of a multi-line string,
3017 fill the string or the paragraph of it that point is in, preserving
3018 the string's indentation.
3019 Optional argument JUSTIFY defines if the paragraph should be justified."
3024 ((python-syntax-context 'comment
)
3025 (funcall python-fill-comment-function justify
))
3026 ;; Strings/Docstrings
3027 ((save-excursion (or (python-syntax-context 'string
)
3028 (equal (string-to-syntax "|")
3029 (syntax-after (point)))))
3030 (funcall python-fill-string-function justify
))
3032 ((equal (char-after (save-excursion
3033 (python-nav-beginning-of-statement))) ?
@)
3034 (funcall python-fill-decorator-function justify
))
3036 ((or (python-syntax-context 'paren
)
3037 (looking-at (python-rx open-paren
))
3039 (skip-syntax-forward "^(" (line-end-position))
3040 (looking-at (python-rx open-paren
))))
3041 (funcall python-fill-paren-function justify
))
3044 (defun python-fill-comment (&optional justify
)
3045 "Comment fill function for `python-fill-paragraph'.
3046 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3047 (fill-comment-paragraph justify
))
3049 (defun python-fill-string (&optional justify
)
3050 "String fill function for `python-fill-paragraph'.
3051 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3052 (let* ((str-start-pos
3055 (or (python-syntax-context 'string
)
3056 (and (equal (string-to-syntax "|")
3057 (syntax-after (point)))
3059 (num-quotes (python-syntax-count-quotes
3060 (char-after str-start-pos
) str-start-pos
))
3063 (goto-char (+ str-start-pos num-quotes
))
3064 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3065 (goto-char (point-max)))
3068 ;; Docstring styles may vary for oneliners and multi-liners.
3069 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3071 (pcase python-fill-docstring-style
3072 ;; delimiters-style is a cons cell with the form
3073 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3074 ;; is NIL means to not add any newlines for start or end
3075 ;; of docstring. See `python-fill-docstring-style' for a
3076 ;; graphic idea of each style.
3077 (`django
(cons 1 1))
3078 (`onetwo
(and multi-line-p
(cons 1 2)))
3079 (`pep-257
(and multi-line-p
(cons nil
2)))
3080 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3081 (`symmetric
(and multi-line-p
(cons 1 1)))))
3082 (docstring-p (save-excursion
3083 ;; Consider docstrings those strings which
3084 ;; start on a line by themselves.
3085 (python-nav-beginning-of-statement)
3086 (and (= (point) str-start-pos
))))
3087 (fill-paragraph-function))
3089 (narrow-to-region str-start-pos str-end-pos
)
3090 (fill-paragraph justify
))
3092 (when (and docstring-p python-fill-docstring-style
)
3093 ;; Add the number of newlines indicated by the selected style
3094 ;; at the start of the docstring.
3095 (goto-char (+ str-start-pos num-quotes
))
3096 (delete-region (point) (progn
3097 (skip-syntax-forward "> ")
3099 (and (car delimiters-style
)
3100 (or (newline (car delimiters-style
)) t
)
3101 ;; Indent only if a newline is added.
3102 (indent-according-to-mode))
3103 ;; Add the number of newlines indicated by the selected style
3104 ;; at the end of the docstring.
3105 (goto-char (if (not (= str-end-pos
(point-max)))
3106 (- str-end-pos num-quotes
)
3108 (delete-region (point) (progn
3109 (skip-syntax-backward "> ")
3111 (and (cdr delimiters-style
)
3112 ;; Add newlines only if string ends.
3113 (not (= str-end-pos
(point-max)))
3114 (or (newline (cdr delimiters-style
)) t
)
3115 ;; Again indent only if a newline is added.
3116 (indent-according-to-mode))))) t
)
3118 (defun python-fill-decorator (&optional _justify
)
3119 "Decorator fill function for `python-fill-paragraph'.
3120 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3123 (defun python-fill-paren (&optional justify
)
3124 "Paren fill function for `python-fill-paragraph'.
3125 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3127 (narrow-to-region (progn
3128 (while (python-syntax-context 'paren
)
3129 (goto-char (1- (point-marker))))
3131 (line-beginning-position))
3133 (when (not (python-syntax-context 'paren
))
3135 (when (not (python-syntax-context 'paren
))
3136 (skip-syntax-backward "^)")))
3137 (while (and (python-syntax-context 'paren
)
3139 (goto-char (1+ (point-marker))))
3141 (let ((paragraph-start "\f\\|[ \t]*$")
3142 (paragraph-separate ",")
3143 (fill-paragraph-function))
3144 (goto-char (point-min))
3145 (fill-paragraph justify
))
3148 (python-indent-line)
3149 (goto-char (line-end-position))))
3155 (defcustom python-skeleton-autoinsert nil
3156 "Non-nil means template skeletons will be automagically inserted.
3157 This happens when pressing \"if<SPACE>\", for example, to prompt for
3163 (define-obsolete-variable-alias
3164 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3166 (defvar python-skeleton-available
'()
3167 "Internal list of available skeletons.")
3169 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3170 "Abbrev table for Python mode skeletons."
3172 ;; Allow / inside abbrevs.
3173 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3174 ;; Only expand in code.
3175 :enable-function
(lambda ()
3177 (not (python-syntax-comment-or-string-p))
3178 python-skeleton-autoinsert
)))
3180 (defmacro python-skeleton-define
(name doc
&rest skel
)
3181 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3182 The skeleton will be bound to python-skeleton-NAME and will
3183 be added to `python-mode-skeleton-abbrev-table'."
3184 (declare (indent 2))
3185 (let* ((name (symbol-name name
))
3186 (function-name (intern (concat "python-skeleton-" name
))))
3188 (define-abbrev python-mode-skeleton-abbrev-table
3189 ,name
"" ',function-name
:system t
)
3190 (setq python-skeleton-available
3191 (cons ',function-name python-skeleton-available
))
3192 (define-skeleton ,function-name
3194 (format "Insert %s statement." name
))
3197 (define-abbrev-table 'python-mode-abbrev-table
()
3198 "Abbrev table for Python mode."
3199 :parents
(list python-mode-skeleton-abbrev-table
))
3201 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3202 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3203 The skeleton will be bound to python-skeleton-NAME."
3204 (declare (indent 2))
3205 (let* ((name (symbol-name name
))
3206 (function-name (intern (concat "python-skeleton--" name
)))
3208 "Add '%s' clause? " name
)))
3211 `(< ,(format "%s:" name
) \n \n
3213 `(define-skeleton ,function-name
3215 (format "Auxiliary skeleton for %s statement." name
))
3217 (unless (y-or-n-p ,msg
)
3221 (python-define-auxiliary-skeleton else nil
)
3223 (python-define-auxiliary-skeleton except nil
)
3225 (python-define-auxiliary-skeleton finally nil
)
3227 (python-skeleton-define if nil
3231 ("other condition, %s: "
3235 '(python-skeleton--else) | ^
)
3237 (python-skeleton-define while nil
3241 '(python-skeleton--else) | ^
)
3243 (python-skeleton-define for nil
3247 '(python-skeleton--else) | ^
)
3249 (python-skeleton-define try nil
3255 "except " str
":" \n
3258 '(python-skeleton--except)
3259 '(python-skeleton--else)
3260 '(python-skeleton--finally) | ^
)
3262 (python-skeleton-define def nil
3264 "def " str
"(" ("Parameter, %s: "
3265 (unless (equal ?\
( (char-before)) ", ")
3267 "\"\"\"" -
"\"\"\"" \n
3270 (python-skeleton-define class nil
3272 "class " str
"(" ("Inheritance, %s: "
3273 (unless (equal ?\
( (char-before)) ", ")
3277 "\"\"\"" -
"\"\"\"" \n
3280 (defun python-skeleton-add-menu-items ()
3281 "Add menu items to Python->Skeletons menu."
3282 (let ((skeletons (sort python-skeleton-available
'string
<)))
3283 (dolist (skeleton skeletons
)
3285 nil
'("Python" "Skeletons")
3287 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3292 (defcustom python-ffap-setup-code
3293 "def __FFAP_get_module_path(module):
3296 path = __import__(module).__file__
3297 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3302 "Python code to get a module path."
3306 (defcustom python-ffap-string-code
3307 "__FFAP_get_module_path('''%s''')\n"
3308 "Python code used to get a string with the path of a module."
3312 (defun python-ffap-module-path (module)
3313 "Function for `ffap-alist' to return path for MODULE."
3315 (and (derived-mode-p 'inferior-python-mode
)
3316 (get-buffer-process (current-buffer)))
3317 (python-shell-get-process))))
3321 (python-shell-send-string-no-output
3322 (format python-ffap-string-code module
) process
)))
3324 (substring-no-properties module-file
1 -
1))))))
3328 (eval-after-load "ffap"
3330 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3331 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3336 (defcustom python-check-command
3338 "Command used to check a Python file."
3342 (defcustom python-check-buffer-name
3343 "*Python check: %s*"
3344 "Buffer name used for check commands."
3348 (defvar python-check-custom-command nil
3351 (defun python-check (command)
3352 "Check a Python file (default current buffer's file).
3353 Runs COMMAND, a shell command, as if by `compile'.
3354 See `python-check-command' for the default."
3356 (list (read-string "Check command: "
3357 (or python-check-custom-command
3358 (concat python-check-command
" "
3359 (shell-quote-argument
3361 (let ((name (buffer-file-name)))
3363 (file-name-nondirectory name
)))
3365 (setq python-check-custom-command command
)
3366 (save-some-buffers (not compilation-ask-about-save
) nil
)
3367 (let ((process-environment (python-shell-calculate-process-environment))
3368 (exec-path (python-shell-calculate-exec-path)))
3369 (compilation-start command nil
3371 (format python-check-buffer-name command
)))))
3376 (defcustom python-eldoc-setup-code
3377 "def __PYDOC_get_help(obj):
3380 if hasattr(obj, 'startswith'):
3381 obj = eval(obj, globals())
3382 doc = inspect.getdoc(obj)
3383 if not doc and callable(obj):
3385 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3386 target = obj.__init__
3392 args = inspect.formatargspec(
3393 *inspect.getargspec(target)
3396 doc = '{objtype} {name}{args}'.format(
3397 objtype=objtype, name=name, args=args
3400 doc = doc.splitlines()[0]
3407 "Python code to setup documentation retrieval."
3411 (defcustom python-eldoc-string-code
3412 "__PYDOC_get_help('''%s''')\n"
3413 "Python code used to get a string with the documentation of an object."
3417 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
3418 "Internal implementation to get documentation at point.
3419 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3420 returns will be used. If not FORCE-PROCESS is passed what
3421 `python-shell-get-process' returns is used."
3422 (let ((process (or force-process
(python-shell-get-process))))
3424 (error "Eldoc needs an inferior Python process running")
3425 (let ((input (or force-input
3426 (python-info-current-symbol t
))))
3428 ;; Prevent resizing the echo area when iPython is
3429 ;; enabled. Bug#18794.
3430 (python-util-strip-string
3431 (python-shell-send-string-no-output
3432 (format python-eldoc-string-code input
)
3435 (defun python-eldoc-function ()
3436 "`eldoc-documentation-function' for Python.
3437 For this to work as best as possible you should call
3438 `python-shell-send-buffer' from time to time so context in
3439 inferior Python process is updated properly."
3440 (python-eldoc--get-doc-at-point))
3442 (defun python-eldoc-at-point (symbol)
3443 "Get help on SYMBOL using `help'.
3444 Interactively, prompt for symbol."
3446 (let ((symbol (python-info-current-symbol t
))
3447 (enable-recursive-minibuffers t
))
3448 (list (read-string (if symbol
3449 (format "Describe symbol (default %s): " symbol
)
3450 "Describe symbol: ")
3452 (message (python-eldoc--get-doc-at-point symbol
)))
3454 (add-to-list 'debug-ignored-errors
3455 "^Eldoc needs an inferior Python process running.")
3460 (defvar python-imenu-format-item-label-function
3461 'python-imenu-format-item-label
3462 "Imenu function used to format an item label.
3463 It must be a function with two arguments: TYPE and NAME.")
3465 (defvar python-imenu-format-parent-item-label-function
3466 'python-imenu-format-parent-item-label
3467 "Imenu function used to format a parent item label.
3468 It must be a function with two arguments: TYPE and NAME.")
3470 (defvar python-imenu-format-parent-item-jump-label-function
3471 'python-imenu-format-parent-item-jump-label
3472 "Imenu function used to format a parent jump item label.
3473 It must be a function with two arguments: TYPE and NAME.")
3475 (defun python-imenu-format-item-label (type name
)
3476 "Return Imenu label for single node using TYPE and NAME."
3477 (format "%s (%s)" name type
))
3479 (defun python-imenu-format-parent-item-label (type name
)
3480 "Return Imenu label for parent node using TYPE and NAME."
3481 (format "%s..." (python-imenu-format-item-label type name
)))
3483 (defun python-imenu-format-parent-item-jump-label (type _name
)
3484 "Return Imenu label for parent node jump using TYPE and NAME."
3485 (if (string= type
"class")
3486 "*class definition*"
3487 "*function definition*"))
3489 (defun python-imenu--put-parent (type name pos tree
)
3490 "Add the parent with TYPE, NAME and POS to TREE."
3492 (funcall python-imenu-format-item-label-function type name
))
3494 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
3497 (cons label
(cons (cons jump-label pos
) tree
)))))
3499 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
3500 "Recursively build the tree of nested definitions of a node.
3501 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3502 not be passed explicitly unless you know what you are doing."
3503 (setq min-indent
(or min-indent
0)
3504 prev-indent
(or prev-indent python-indent-offset
))
3505 (let* ((pos (python-nav-backward-defun))
3507 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
3508 (let ((split (split-string (match-string-no-properties 0))))
3509 (setq type
(car split
))
3512 (funcall python-imenu-format-item-label-function type name
)))
3513 (indent (current-indentation))
3514 (children-indent-limit (+ python-indent-offset min-indent
)))
3516 ;; Nothing found, probably near to bobp.
3518 ((<= indent min-indent
)
3519 ;; The current indentation points that this is a parent
3520 ;; node, add it to the tree and stop recursing.
3521 (python-imenu--put-parent type name pos tree
))
3523 (python-imenu--build-tree
3526 (if (<= indent children-indent-limit
)
3527 ;; This lies within the children indent offset range,
3528 ;; so it's a normal child of its parent (i.e., not
3529 ;; a child of a child).
3530 (cons (cons label pos
) tree
)
3531 ;; Oh no, a child of a child?! Fear not, we
3532 ;; know how to roll. We recursively parse these by
3533 ;; swapping prev-indent and min-indent plus adding this
3534 ;; newly found item to a fresh subtree. This works, I
3537 (python-imenu--build-tree
3538 prev-indent indent
(list (cons label pos
)))
3541 (defun python-imenu-create-index ()
3542 "Return tree Imenu alist for the current Python buffer.
3543 Change `python-imenu-format-item-label-function',
3544 `python-imenu-format-parent-item-label-function',
3545 `python-imenu-format-parent-item-jump-label-function' to
3546 customize how labels are formatted."
3547 (goto-char (point-max))
3550 (while (setq tree
(python-imenu--build-tree))
3551 (setq index
(cons tree index
)))
3554 (defun python-imenu-create-flat-index (&optional alist prefix
)
3555 "Return flat outline of the current Python buffer for Imenu.
3556 Optional argument ALIST is the tree to be flattened; when nil
3557 `python-imenu-build-index' is used with
3558 `python-imenu-format-parent-item-jump-label-function'
3559 `python-imenu-format-parent-item-label-function'
3560 `python-imenu-format-item-label-function' set to
3561 (lambda (type name) name)
3562 Optional argument PREFIX is used in recursive calls and should
3563 not be passed explicitly.
3570 (\"decorator\" . 173)
3573 (\"wrapped_f\" . 393))))
3579 (\"decorator\" . 173)
3580 (\"decorator.wrap\" . 353)
3581 (\"decorator.wrapped_f\" . 393))"
3582 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3587 (let ((name (if prefix
3588 (concat prefix
"." (car item
))
3591 (cond ((or (numberp pos
) (markerp pos
))
3592 (list (cons name pos
)))
3595 (cons name
(cdar pos
))
3596 (python-imenu-create-flat-index (cddr item
) name
))))))
3598 (let* ((fn (lambda (_type name
) name
))
3599 (python-imenu-format-item-label-function fn
)
3600 (python-imenu-format-parent-item-label-function fn
)
3601 (python-imenu-format-parent-item-jump-label-function fn
))
3602 (python-imenu-create-index))))))
3607 (defun python-info-current-defun (&optional include-type
)
3608 "Return name of surrounding function with Python compatible dotty syntax.
3609 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3610 This function can be used as the value of `add-log-current-defun-function'
3611 since it returns nil if point is not inside a defun."
3617 (starting-indentation (current-indentation))
3618 (starting-pos (point))
3623 (while (python-nav-beginning-of-defun 1)
3624 (when (save-match-data
3626 (or (not last-indent
)
3627 (< (current-indentation) last-indent
))
3631 ;; If this is the first run, we may add
3632 ;; the current defun at point.
3633 (setq first-run nil
)
3634 (goto-char starting-pos
)
3635 (python-nav-beginning-of-statement)
3636 (beginning-of-line 1)
3638 python-nav-beginning-of-defun-regexp
)))
3642 (+ (current-indentation)
3643 python-indent-offset
)))
3644 (if (< starting-indentation min-indent
)
3645 ;; If the starting indentation is not
3646 ;; within the min defun indent make the
3649 ;; Else go to the end of defun and add
3650 ;; up the current indentation to the
3652 (python-nav-end-of-defun)
3654 (if (>= (current-indentation) min-indent
)
3655 (1+ (current-indentation))
3657 (save-match-data (setq last-indent
(current-indentation)))
3658 (if (or (not include-type
) type
)
3659 (setq names
(cons (match-string-no-properties 1) names
))
3660 (let ((match (split-string (match-string-no-properties 0))))
3661 (setq type
(car match
))
3662 (setq names
(cons (cadr match
) names
)))))
3663 ;; Stop searching ASAP.
3664 (and (= (current-indentation) 0) (throw 'exit t
))))
3666 (concat (and type
(format "%s " type
))
3667 (mapconcat 'identity names
".")))))))
3669 (defun python-info-current-symbol (&optional replace-self
)
3670 "Return current symbol using dotty syntax.
3671 With optional argument REPLACE-SELF convert \"self\" to current
3674 (and (not (python-syntax-comment-or-string-p))
3675 (with-syntax-table python-dotty-syntax-table
3676 (let ((sym (symbol-at-point)))
3678 (substring-no-properties (symbol-name sym
))))))))
3680 (if (not replace-self
)
3682 (let ((current-defun (python-info-current-defun)))
3683 (if (not current-defun
)
3685 (replace-regexp-in-string
3686 (python-rx line-start word-start
"self" word-end ?.
)
3688 (mapconcat 'identity
3689 (butlast (split-string current-defun
"\\."))
3693 (defun python-info-statement-starts-block-p ()
3694 "Return non-nil if current statement opens a block."
3696 (python-nav-beginning-of-statement)
3697 (looking-at (python-rx block-start
))))
3699 (defun python-info-statement-ends-block-p ()
3700 "Return non-nil if point is at end of block."
3701 (let ((end-of-block-pos (save-excursion
3702 (python-nav-end-of-block)))
3703 (end-of-statement-pos (save-excursion
3704 (python-nav-end-of-statement))))
3705 (and end-of-block-pos end-of-statement-pos
3706 (= end-of-block-pos end-of-statement-pos
))))
3708 (defun python-info-beginning-of-statement-p ()
3709 "Return non-nil if point is at beginning of statement."
3710 (= (point) (save-excursion
3711 (python-nav-beginning-of-statement)
3714 (defun python-info-end-of-statement-p ()
3715 "Return non-nil if point is at end of statement."
3716 (= (point) (save-excursion
3717 (python-nav-end-of-statement)
3720 (defun python-info-beginning-of-block-p ()
3721 "Return non-nil if point is at beginning of block."
3722 (and (python-info-beginning-of-statement-p)
3723 (python-info-statement-starts-block-p)))
3725 (defun python-info-end-of-block-p ()
3726 "Return non-nil if point is at end of block."
3727 (and (python-info-end-of-statement-p)
3728 (python-info-statement-ends-block-p)))
3730 (define-obsolete-function-alias
3731 'python-info-closing-block
3732 'python-info-dedenter-opening-block-position
"24.4")
3734 (defun python-info-dedenter-opening-block-position ()
3735 "Return the point of the closest block the current line closes.
3736 Returns nil if point is not on a dedenter statement or no opening
3737 block can be detected. The latter case meaning current file is
3738 likely an invalid python file."
3739 (let ((positions (python-info-dedenter-opening-block-positions))
3740 (indentation (current-indentation))
3742 (while (and (not position
)
3745 (goto-char (car positions
))
3746 (if (<= (current-indentation) indentation
)
3747 (setq position
(car positions
))
3748 (setq positions
(cdr positions
)))))
3751 (defun python-info-dedenter-opening-block-positions ()
3752 "Return points of blocks the current line may close sorted by closer.
3753 Returns nil if point is not on a dedenter statement or no opening
3754 block can be detected. The latter case meaning current file is
3755 likely an invalid python file."
3757 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3759 (goto-char dedenter-pos
)
3760 (let* ((pairs '(("elif" "elif" "if")
3761 ("else" "if" "elif" "except" "for" "while")
3762 ("except" "except" "try")
3763 ("finally" "else" "except" "try")))
3764 (dedenter (match-string-no-properties 0))
3765 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
3766 (collected-indentations)
3769 (while (python-nav--syntactically
3771 (re-search-backward (python-rx block-start
) nil t
))
3773 (let ((indentation (current-indentation)))
3774 (when (and (not (memq indentation collected-indentations
))
3775 (or (not collected-indentations
)
3776 (< indentation
(apply #'min collected-indentations
))))
3777 (setq collected-indentations
3778 (cons indentation collected-indentations
))
3779 (when (member (match-string-no-properties 0)
3780 possible-opening-blocks
)
3781 (setq opening-blocks
(cons (point) opening-blocks
))))
3782 (when (zerop indentation
)
3783 (throw 'exit nil
)))))
3785 (nreverse opening-blocks
))))))
3787 (define-obsolete-function-alias
3788 'python-info-closing-block-message
3789 'python-info-dedenter-opening-block-message
"24.4")
3791 (defun python-info-dedenter-opening-block-message ()
3792 "Message the first line of the block the current statement closes."
3793 (let ((point (python-info-dedenter-opening-block-position)))
3797 (message "Closes %s" (save-excursion
3800 (point) (line-end-position))))))))
3802 (defun python-info-dedenter-statement-p ()
3803 "Return point if current statement is a dedenter.
3804 Sets `match-data' to the keyword that starts the dedenter
3807 (python-nav-beginning-of-statement)
3808 (when (and (not (python-syntax-context-type))
3809 (looking-at (python-rx dedenter
)))
3812 (defun python-info-line-ends-backslash-p (&optional line-number
)
3813 "Return non-nil if current line ends with backslash.
3814 With optional argument LINE-NUMBER, check that line instead."
3819 (python-util-goto-line line-number
))
3820 (while (and (not (eobp))
3821 (goto-char (line-end-position))
3822 (python-syntax-context 'paren
)
3823 (not (equal (char-before (point)) ?
\\)))
3825 (when (equal (char-before) ?
\\)
3828 (defun python-info-beginning-of-backslash (&optional line-number
)
3829 "Return the point where the backslashed line start.
3830 Optional argument LINE-NUMBER forces the line number to check against."
3835 (python-util-goto-line line-number
))
3836 (when (python-info-line-ends-backslash-p)
3837 (while (save-excursion
3838 (goto-char (line-beginning-position))
3839 (python-syntax-context 'paren
))
3841 (back-to-indentation)
3844 (defun python-info-continuation-line-p ()
3845 "Check if current line is continuation of another.
3846 When current line is continuation of another return the point
3847 where the continued line ends."
3851 (let* ((context-type (progn
3852 (back-to-indentation)
3853 (python-syntax-context-type)))
3854 (line-start (line-number-at-pos))
3855 (context-start (when context-type
3856 (python-syntax-context context-type
))))
3857 (cond ((equal context-type
'paren
)
3858 ;; Lines inside a paren are always a continuation line
3859 ;; (except the first one).
3860 (python-util-forward-comment -
1)
3862 ((member context-type
'(string comment
))
3863 ;; move forward an roll again
3864 (goto-char context-start
)
3865 (python-util-forward-comment)
3866 (python-info-continuation-line-p))
3868 ;; Not within a paren, string or comment, the only way
3869 ;; we are dealing with a continuation line is that
3870 ;; previous line contains a backslash, and this can
3871 ;; only be the previous line from current
3872 (back-to-indentation)
3873 (python-util-forward-comment -
1)
3874 (when (and (equal (1- line-start
) (line-number-at-pos))
3875 (python-info-line-ends-backslash-p))
3876 (point-marker))))))))
3878 (defun python-info-block-continuation-line-p ()
3879 "Return non-nil if current line is a continuation of a block."
3881 (when (python-info-continuation-line-p)
3883 (back-to-indentation)
3884 (when (looking-at (python-rx block-start
))
3887 (defun python-info-assignment-continuation-line-p ()
3888 "Check if current line is a continuation of an assignment.
3889 When current line is continuation of another with an assignment
3890 return the point of the first non-blank character after the
3893 (when (python-info-continuation-line-p)
3895 (back-to-indentation)
3896 (when (and (not (looking-at (python-rx block-start
)))
3897 (and (re-search-forward (python-rx not-simple-operator
3899 not-simple-operator
)
3900 (line-end-position) t
)
3901 (not (python-syntax-context-type))))
3902 (skip-syntax-forward "\s")
3905 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3906 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3907 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3909 (beginning-of-line 1)
3910 (looking-at python-nav-beginning-of-defun-regexp
))))
3912 (defun python-info-current-line-comment-p ()
3913 "Return non-nil if current line is a comment line."
3915 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
3918 (defun python-info-current-line-empty-p ()
3919 "Return non-nil if current line is empty, ignoring whitespace."
3921 (beginning-of-line 1)
3923 (python-rx line-start
(* whitespace
)
3924 (group (* not-newline
))
3925 (* whitespace
) line-end
))
3926 (string-equal "" (match-string-no-properties 1))))
3929 ;;; Utility functions
3931 (defun python-util-goto-line (line-number)
3932 "Move point to LINE-NUMBER."
3933 (goto-char (point-min))
3934 (forward-line (1- line-number
)))
3936 ;; Stolen from org-mode
3937 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3938 "Clone local variables from FROM-BUFFER.
3939 Optional argument REGEXP selects variables to clone and defaults
3943 (and (symbolp (car pair
))
3944 (string-match (or regexp
"^python-")
3945 (symbol-name (car pair
)))
3946 (set (make-local-variable (car pair
))
3948 (buffer-local-variables from-buffer
)))
3950 (defun python-util-forward-comment (&optional direction
)
3951 "Python mode specific version of `forward-comment'.
3952 Optional argument DIRECTION defines the direction to move to."
3953 (let ((comment-start (python-syntax-context 'comment
))
3954 (factor (if (< (or direction
0) 0)
3958 (goto-char comment-start
))
3959 (forward-comment factor
)))
3961 (defun python-util-popn (lst n
)
3962 "Return LST first N elements.
3963 N should be an integer, when negative its opposite is used.
3964 When N is bigger than the length of LST, the list is
3966 (let* ((n (min (abs n
)))
3972 (setq acc
(cons (car lst
) acc
)
3977 (defun python-util-strip-string (string)
3978 "Strip STRING whitespace and newlines from end and beginning."
3979 (replace-regexp-in-string
3980 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
3981 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
3985 (defun python-util-valid-regexp-p (regexp)
3986 "Return non-nil if REGEXP is valid."
3987 (ignore-errors (string-match regexp
"") t
))
3990 (defun python-electric-pair-string-delimiter ()
3991 (when (and electric-pair-mode
3992 (memq last-command-event
'(?
\" ?
\'))
3994 (while (eq (char-before (- (point) count
)) last-command-event
)
3997 (eq (char-after) last-command-event
))
3998 (save-excursion (insert (make-string 2 last-command-event
)))))
4000 (defvar electric-indent-inhibit
)
4003 (define-derived-mode python-mode prog-mode
"Python"
4004 "Major mode for editing Python files.
4006 \\{python-mode-map}"
4007 (set (make-local-variable 'tab-width
) 8)
4008 (set (make-local-variable 'indent-tabs-mode
) nil
)
4010 (set (make-local-variable 'comment-start
) "# ")
4011 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4013 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4014 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4016 (set (make-local-variable 'forward-sexp-function
)
4017 'python-nav-forward-sexp
)
4019 (set (make-local-variable 'font-lock-defaults
)
4020 '(python-font-lock-keywords nil nil nil nil
))
4022 (set (make-local-variable 'syntax-propertize-function
)
4023 python-syntax-propertize-function
)
4025 (set (make-local-variable 'indent-line-function
)
4026 #'python-indent-line-function
)
4027 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4028 ;; Because indentation is not redundant, we cannot safely reindent code.
4029 (setq-local electric-indent-inhibit t
)
4030 (setq-local electric-indent-chars
(cons ?
: electric-indent-chars
))
4032 ;; Add """ ... """ pairing to electric-pair-mode.
4033 (add-hook 'post-self-insert-hook
4034 #'python-electric-pair-string-delimiter
'append t
)
4036 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4037 (set (make-local-variable 'fill-paragraph-function
)
4038 #'python-fill-paragraph
)
4040 (set (make-local-variable 'beginning-of-defun-function
)
4041 #'python-nav-beginning-of-defun
)
4042 (set (make-local-variable 'end-of-defun-function
)
4043 #'python-nav-end-of-defun
)
4045 (add-hook 'completion-at-point-functions
4046 #'python-completion-complete-at-point nil
'local
)
4048 (add-hook 'post-self-insert-hook
4049 #'python-indent-post-self-insert-function
'append
'local
)
4051 (set (make-local-variable 'imenu-create-index-function
)
4052 #'python-imenu-create-index
)
4054 (set (make-local-variable 'add-log-current-defun-function
)
4055 #'python-info-current-defun
)
4057 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4059 (set (make-local-variable 'skeleton-further-elements
)
4061 (< '(backward-delete-char-untabify (min python-indent-offset
4063 (^
'(- (1+ (current-indentation))))))
4065 (set (make-local-variable 'eldoc-documentation-function
)
4066 #'python-eldoc-function
)
4068 (add-to-list 'hs-special-modes-alist
4069 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
4071 (python-nav-end-of-defun)) nil
))
4073 (set (make-local-variable 'outline-regexp
)
4074 (python-rx (* space
) block-start
))
4075 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
4076 (set (make-local-variable 'outline-level
)
4078 "`outline-level' function for Python mode."
4079 (1+ (/ (current-indentation) python-indent-offset
))))
4081 (python-skeleton-add-menu-items)
4083 (make-local-variable 'python-shell-internal-buffer
)
4085 (when python-indent-guess-indent-offset
4086 (python-indent-guess-indent-offset)))
4093 ;; indent-tabs-mode: nil
4096 ;;; python.el ends here