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, Shell
35 ;; package support, Shell syntax highlighting, Pdb tracking, Symbol
36 ;; completion, Skeletons, FFAP, Code Check, Eldoc, Imenu.
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows opening Python shells
66 ;; inside Emacs and executing any block of code of your current buffer
67 ;; in that inferior Python process.
69 ;; Besides that only the standard CPython (2.x and 3.x) shell and
70 ;; IPython are officially supported out of the box, the interaction
71 ;; should support any other readline based Python shells as well
72 ;; (e.g. Jython and Pypy have been reported to work). You can change
73 ;; your default interpreter and commandline arguments by setting the
74 ;; `python-shell-interpreter' and `python-shell-interpreter-args'
75 ;; variables. This example enables IPython globally:
77 ;; (setq python-shell-interpreter "ipython"
78 ;; python-shell-interpreter-args "-i")
80 ;; Using the "console" subcommand to start IPython in server-client
81 ;; mode is known to fail intermittently due a bug on IPython itself
82 ;; (see URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=18052#27').
83 ;; There seems to be a race condition in the IPython server (A.K.A
84 ;; kernel) when code is sent while it is still initializing, sometimes
85 ;; causing the shell to get stalled. With that said, if an IPython
86 ;; kernel is already running, "console --existing" seems to work fine.
88 ;; Running IPython on Windows needs more tweaking. The way you should
89 ;; set `python-shell-interpreter' and `python-shell-interpreter-args'
90 ;; is as follows (of course you need to modify the paths according to
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-root' 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-root "/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 ;; Shell package support: you can enable a package in the current
174 ;; shell so that relative imports work properly using the
175 ;; `python-shell-package-enable' command.
177 ;; Shell syntax highlighting: when enabled current input in shell is
178 ;; highlighted. The variable `python-shell-font-lock-enable' controls
179 ;; activation of this feature globally when shells are started.
180 ;; Activation/deactivation can be also controlled on the fly via the
181 ;; `python-shell-font-lock-toggle' command.
183 ;; Pdb tracking: when you execute a block of code that contains some
184 ;; call to pdb (or ipdb) it will prompt the block of code and will
185 ;; follow the execution of pdb marking the current line with an arrow.
187 ;; Symbol completion: you can complete the symbol at point. It uses
188 ;; the shell completion in background so you should run
189 ;; `python-shell-send-buffer' from time to time to get better results.
191 ;; Skeletons: skeletons are provided for simple inserting of things like class,
192 ;; def, for, import, if, try, and while. These skeletons are
193 ;; integrated with abbrev. If you have `abbrev-mode' activated and
194 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
195 ;; the name of any of those defined and hit SPC, they will be
196 ;; automatically expanded. As an alternative you can use the defined
197 ;; skeleton commands: `python-skeleton-<foo>'.
199 ;; FFAP: You can find the filename for a given module when using ffap
200 ;; out of the box. This feature needs an inferior python shell
203 ;; Code check: Check the current file for errors with `python-check'
204 ;; using the program defined in `python-check-command'.
206 ;; Eldoc: returns documentation for object at point by using the
207 ;; inferior python subprocess to inspect its documentation. As you
208 ;; might guessed you should run `python-shell-send-buffer' from time
209 ;; to time to get better results too.
211 ;; Imenu: There are two index building functions to be used as
212 ;; `imenu-create-index-function': `python-imenu-create-index' (the
213 ;; default one, builds the alist in form of a tree) and
214 ;; `python-imenu-create-flat-index'. See also
215 ;; `python-imenu-format-item-label-function',
216 ;; `python-imenu-format-parent-item-label-function',
217 ;; `python-imenu-format-parent-item-jump-label-function' variables for
218 ;; changing the way labels are formatted in the tree version.
220 ;; If you used python-mode.el you may miss auto-indentation when
221 ;; inserting newlines. To achieve the same behavior you have two
224 ;; 1) Enable the minor-mode `electric-indent-mode' (enabled by
225 ;; default) and use RET. If this mode is disabled use
226 ;; `newline-and-indent', bound to C-j.
228 ;; 2) Add the following hook in your .emacs:
230 ;; (add-hook 'python-mode-hook
232 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
234 ;; I'd recommend the first one since you'll get the same behavior for
235 ;; all modes out-of-the-box.
239 ;; Add this to your .emacs:
241 ;; (add-to-list 'load-path "/folder/containing/file")
248 (require 'ansi-color
)
253 ;; Avoid compiler warnings
254 (defvar view-return-to-alist
)
255 (defvar compilation-error-regexp-alist
)
256 (defvar outline-heading-end-regexp
)
258 (autoload 'comint-mode
"comint")
261 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
263 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
266 "Python Language's flying circus support for Emacs."
269 :link
'(emacs-commentary-link "python"))
274 (defvar python-mode-map
275 (let ((map (make-sparse-keymap)))
277 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
278 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
279 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
280 (define-key map
"\C-c\C-j" 'imenu
)
282 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
283 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
284 (define-key map
"\C-c<" 'python-indent-shift-left
)
285 (define-key map
"\C-c>" 'python-indent-shift-right
)
287 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
288 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
289 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
290 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
291 (define-key map
"\C-c\C-tm" 'python-skeleton-import
)
292 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
293 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
295 (define-key map
"\C-c\C-p" 'run-python
)
296 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
297 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
298 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
299 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
300 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
301 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
302 ;; Some util commands
303 (define-key map
"\C-c\C-v" 'python-check
)
304 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
306 (substitute-key-definition 'complete-symbol
'completion-at-point
308 (easy-menu-define python-menu map
"Python Mode menu"
310 :help
"Python-specific Features"
311 ["Shift region left" python-indent-shift-left
:active mark-active
312 :help
"Shift region left by a single indentation step"]
313 ["Shift region right" python-indent-shift-right
:active mark-active
314 :help
"Shift region right by a single indentation step"]
316 ["Start of def/class" beginning-of-defun
317 :help
"Go to start of outermost definition around point"]
318 ["End of def/class" end-of-defun
319 :help
"Go to end of definition around point"]
320 ["Mark def/class" mark-defun
321 :help
"Mark outermost definition around point"]
322 ["Jump to def/class" imenu
323 :help
"Jump to a class or function definition"]
327 ["Start interpreter" run-python
328 :help
"Run inferior Python process in a separate buffer"]
329 ["Switch to shell" python-shell-switch-to-shell
330 :help
"Switch to running inferior Python process"]
331 ["Eval string" python-shell-send-string
332 :help
"Eval string in inferior Python session"]
333 ["Eval buffer" python-shell-send-buffer
334 :help
"Eval buffer in inferior Python session"]
335 ["Eval region" python-shell-send-region
336 :help
"Eval region in inferior Python session"]
337 ["Eval defun" python-shell-send-defun
338 :help
"Eval defun in inferior Python session"]
339 ["Eval file" python-shell-send-file
340 :help
"Eval file in inferior Python session"]
341 ["Debugger" pdb
:help
"Run pdb under GUD"]
343 ["Check file" python-check
344 :help
"Check file for errors"]
345 ["Help on symbol" python-eldoc-at-point
346 :help
"Get help on symbol at point"]
347 ["Complete symbol" completion-at-point
348 :help
"Complete symbol before point"]))
350 "Keymap for `python-mode'.")
353 ;;; Python specialized rx
356 (defconst python-rx-constituents
357 `((block-start .
,(rx symbol-start
358 (or "def" "class" "if" "elif" "else" "try"
359 "except" "finally" "for" "while" "with")
361 (dedenter .
,(rx symbol-start
362 (or "elif" "else" "except" "finally")
364 (block-ender .
,(rx symbol-start
366 "break" "continue" "pass" "raise" "return")
368 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
370 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
371 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
372 (+ space
) "==" (+ space
)
373 (any ?
' ?
\") "__main__" (any ?
' ?
\")
375 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
376 (open-paren .
,(rx (or "{" "[" "(")))
377 (close-paren .
,(rx (or "}" "]" ")")))
378 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
379 ;; FIXME: rx should support (not simple-operator).
380 (not-simple-operator .
,(rx
382 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
383 ;; FIXME: Use regexp-opt.
384 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
385 "=" "%" "**" "//" "<<" ">>" "<=" "!="
386 "==" ">=" "is" "not")))
387 ;; FIXME: Use regexp-opt.
388 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
389 ">>=" "<<=" "&=" "^=" "|=")))
390 (string-delimiter .
,(rx (and
391 ;; Match even number of backslashes.
392 (or (not (any ?
\\ ?
\' ?
\")) point
393 ;; Quotes might be preceded by a escaped quote.
394 (and (or (not (any ?
\\)) point
) ?
\\
395 (* ?
\\ ?
\\) (any ?
\' ?
\")))
397 ;; Match single or triple quotes of any kind.
398 (group (or "\"" "\"\"\"" "'" "'''")))))
399 (coding-cookie .
,(rx line-start ?
# (* space
)
401 ;; # coding=<encoding name>
402 (: "coding" (or ?
: ?
=) (* space
) (group-n 1 (+ (or word ?-
))))
403 ;; # -*- coding: <encoding name> -*-
404 (: "-*-" (* space
) "coding:" (* space
)
405 (group-n 1 (+ (or word ?-
))) (* space
) "-*-")
406 ;; # vim: set fileencoding=<encoding name> :
407 (: "vim:" (* space
) "set" (+ space
)
408 "fileencoding" (* space
) ?
= (* space
)
409 (group-n 1 (+ (or word ?-
))) (* space
) ":")))))
410 "Additional Python specific sexps for `python-rx'")
412 (defmacro python-rx
(&rest regexps
)
413 "Python mode specialized rx macro.
414 This variant of `rx' supports common Python named REGEXPS."
415 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
416 (cond ((null regexps
)
419 (rx-to-string `(and ,@regexps
) t
))
421 (rx-to-string (car regexps
) t
))))))
424 ;;; Font-lock and syntax
427 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
430 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
431 (and (nth 4 ppss
) (nth 8 ppss
))))
433 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
434 (and (nth 3 ppss
) (nth 8 ppss
))))
436 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
439 (defun python-syntax-context (type &optional syntax-ppss
)
440 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
441 TYPE can be `comment', `string' or `paren'. It returns the start
442 character address of the specified TYPE."
443 (declare (compiler-macro python-syntax--context-compiler-macro
))
444 (let ((ppss (or syntax-ppss
(syntax-ppss))))
446 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
447 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
448 (`paren
(nth 1 ppss
))
451 (defun python-syntax-context-type (&optional syntax-ppss
)
452 "Return the context type using SYNTAX-PPSS.
453 The type returned can be `comment', `string' or `paren'."
454 (let ((ppss (or syntax-ppss
(syntax-ppss))))
456 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
457 ((nth 1 ppss
) 'paren
))))
459 (defsubst python-syntax-comment-or-string-p
()
460 "Return non-nil if point is inside 'comment or 'string."
461 (nth 8 (syntax-ppss)))
463 (define-obsolete-function-alias
464 'python-info-ppss-context
#'python-syntax-context
"24.3")
466 (define-obsolete-function-alias
467 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
469 (define-obsolete-function-alias
470 'python-info-ppss-comment-or-string-p
471 #'python-syntax-comment-or-string-p
"24.3")
473 (defun python-docstring-at-p (pos)
474 "Check to see if there is a docstring at POS."
477 (if (looking-at-p "'''\\|\"\"\"")
479 (python-nav-backward-statement)
480 (looking-at "\\`\\|class \\|def "))
483 (defun python-font-lock-syntactic-face-function (state)
485 (if (python-docstring-at-p (nth 8 state
))
487 font-lock-string-face
)
488 font-lock-comment-face
))
490 (defvar python-font-lock-keywords
494 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
495 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
496 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
501 ;; False, None, and True are listed as keywords on the Python 3
502 ;; documentation, but since they also qualify as constants they are
503 ;; fontified like that in order to keep font-lock consistent between
510 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
511 (1 font-lock-function-name-face
))
513 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
514 (1 font-lock-type-face
))
518 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
519 ;; copyright, license, credits, quit and exit are added by the site
520 ;; module and they are not intended to be used in programs
521 "copyright" "credits" "exit" "license" "quit")
522 symbol-end
) . font-lock-constant-face
)
524 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
525 (0+ "." (1+ (or word ?_
)))))
526 (1 font-lock-type-face
))
527 ;; Builtin Exceptions
530 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
531 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
532 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
533 "ImportError" "ImportWarning" "IndexError" "KeyError"
534 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
535 "NotImplementedError" "OSError" "OverflowError"
536 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
537 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
538 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
539 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
540 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
541 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
545 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
547 symbol-end
) . font-lock-type-face
)
551 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
552 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
553 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
554 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
555 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
556 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
557 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
558 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
561 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
562 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
565 "ascii" "bytearray" "bytes" "exec"
567 "__all__" "__doc__" "__name__" "__package__")
568 symbol-end
) . font-lock-builtin-face
)
570 ;; support for a = b = c = 5
572 (let ((re (python-rx (group (+ (any word ?. ?_
)))
573 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
574 assignment-operator
))
576 (while (and (setq res
(re-search-forward re limit t
))
577 (or (python-syntax-context 'paren
)
578 (equal (char-after (point)) ?
=))))
580 (1 font-lock-variable-name-face nil nil
))
581 ;; support for a, b, c = (1, 2, 3)
583 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
584 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
585 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
586 assignment-operator
))
588 (while (and (setq res
(re-search-forward re limit t
))
589 (goto-char (match-end 1))
590 (python-syntax-context 'paren
)))
592 (1 font-lock-variable-name-face nil nil
))))
594 (defconst python-syntax-propertize-function
595 (syntax-propertize-rules
596 ((python-rx string-delimiter
)
597 (0 (ignore (python-syntax-stringify))))))
599 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
600 "Count number of quotes around point (max is 3).
601 QUOTE-CHAR is the quote char to count. Optional argument POINT is
602 the point where scan starts (defaults to current point), and LIMIT
603 is used to limit the scan."
606 (or (not limit
) (< (+ point i
) limit
))
607 (eq (char-after (+ point i
)) quote-char
))
611 (defun python-syntax-stringify ()
612 "Put `syntax-table' property correctly on single/triple quotes."
613 (let* ((num-quotes (length (match-string-no-properties 1)))
615 (backward-char num-quotes
)
617 (forward-char num-quotes
)))
618 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
619 (quote-starting-pos (- (point) num-quotes
))
620 (quote-ending-pos (point))
623 (python-syntax-count-quotes
624 (char-before) string-start quote-starting-pos
))))
625 (cond ((and string-start
(= num-closing-quotes
0))
626 ;; This set of quotes doesn't match the string starting
630 ;; This set of quotes delimit the start of a string.
631 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
632 'syntax-table
(string-to-syntax "|")))
633 ((= num-quotes num-closing-quotes
)
634 ;; This set of quotes delimit the end of a string.
635 (put-text-property (1- quote-ending-pos
) quote-ending-pos
636 'syntax-table
(string-to-syntax "|")))
637 ((> num-quotes num-closing-quotes
)
638 ;; This may only happen whenever a triple quote is closing
639 ;; a single quoted string. Add string delimiter syntax to
641 (put-text-property quote-starting-pos quote-ending-pos
642 'syntax-table
(string-to-syntax "|"))))))
644 (defvar python-mode-syntax-table
645 (let ((table (make-syntax-table)))
646 ;; Give punctuation syntax to ASCII that normally has symbol
647 ;; syntax or has word syntax and isn't a letter.
648 (let ((symbol (string-to-syntax "_"))
649 (sst (standard-syntax-table)))
652 (if (equal symbol
(aref sst i
))
653 (modify-syntax-entry i
"." table
)))))
654 (modify-syntax-entry ?$
"." table
)
655 (modify-syntax-entry ?%
"." table
)
657 (modify-syntax-entry ?
# "<" table
)
658 (modify-syntax-entry ?
\n ">" table
)
659 (modify-syntax-entry ?
' "\"" table
)
660 (modify-syntax-entry ?
` "$" table
)
662 "Syntax table for Python files.")
664 (defvar python-dotty-syntax-table
665 (let ((table (make-syntax-table python-mode-syntax-table
)))
666 (modify-syntax-entry ?.
"w" table
)
667 (modify-syntax-entry ?_
"w" table
)
669 "Dotty syntax table for Python files.
670 It makes underscores and dots word constituent chars.")
675 (defcustom python-indent-offset
4
676 "Default indentation offset for Python."
681 (defcustom python-indent-guess-indent-offset t
682 "Non-nil tells Python mode to guess `python-indent-offset' value."
687 (defcustom python-indent-trigger-commands
688 '(indent-for-tab-command yas-expand yas
/expand
)
689 "Commands that might trigger a `python-indent-line' call."
690 :type
'(repeat symbol
)
693 (define-obsolete-variable-alias
694 'python-indent
'python-indent-offset
"24.3")
696 (define-obsolete-variable-alias
697 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
699 (defvar python-indent-current-level
0
700 "Current indentation level `python-indent-line-function' is using.")
702 (defvar python-indent-levels
'(0)
703 "Levels of indentation available for `python-indent-line-function'.
704 Can also be `noindent' if automatic indentation can't be used.")
706 (defun python-indent-guess-indent-offset ()
707 "Guess and set `python-indent-offset' for the current buffer."
712 (goto-char (point-min))
714 (while (and (not block-end
)
716 (python-rx line-start block-start
) nil t
))
718 (not (python-syntax-context-type))
720 (goto-char (line-end-position))
721 (python-util-forward-comment -
1)
722 (if (equal (char-before) ?
:)
725 (when (python-info-block-continuation-line-p)
726 (while (and (python-info-continuation-line-p)
729 (python-util-forward-comment -
1)
730 (when (equal (char-before) ?
:)
732 (setq block-end
(point-marker))))
735 (goto-char block-end
)
736 (python-util-forward-comment)
737 (current-indentation))))
738 (if (and indentation
(not (zerop indentation
)))
739 (set (make-local-variable 'python-indent-offset
) indentation
)
740 (message "Can't guess python-indent-offset, using defaults: %s"
741 python-indent-offset
)))))))
743 (defun python-indent-context ()
744 "Get information on indentation context.
745 Context information is returned with a cons with the form:
748 Where status can be any of the following symbols:
750 * after-comment: When current line might continue a comment block
751 * inside-paren: If point in between (), {} or []
752 * inside-string: If point is inside a string
753 * after-backslash: Previous line ends in a backslash
754 * after-beginning-of-block: Point is after beginning of block
755 * after-line: Point is after normal line
756 * dedenter-statement: Point is on a dedenter statement.
757 * no-indent: Point is at beginning of buffer or other special case
758 START is the buffer position where the sexp starts."
761 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
765 ;; Beginning of buffer
767 (goto-char (line-beginning-position))
770 ;; Comment continuation
774 (python-info-current-line-comment-p)
775 (python-info-current-line-empty-p))
778 (python-info-current-line-comment-p)))
782 ((setq start
(python-syntax-context 'string ppss
))
785 ((setq start
(python-syntax-context 'paren ppss
))
788 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
789 (python-syntax-context 'comment ppss
)))
790 (let ((line-beg-pos (line-number-at-pos)))
791 (python-info-line-ends-backslash-p
792 (1- line-beg-pos
)))))
794 ;; After beginning of block
795 ((setq start
(save-excursion
797 (back-to-indentation)
798 (python-util-forward-comment -
1)
799 (equal (char-before) ?
:))
800 ;; Move to the first block start that's not in within
801 ;; a string, comment or paren and that's not a
802 ;; continuation line.
803 (while (and (re-search-backward
804 (python-rx block-start
) nil t
)
806 (python-syntax-context-type)
807 (python-info-continuation-line-p))))
808 (when (looking-at (python-rx block-start
))
810 'after-beginning-of-block
)
811 ((when (setq start
(python-info-dedenter-statement-p))
812 'dedenter-statement
))
814 ((setq start
(save-excursion
815 (back-to-indentation)
816 (skip-chars-backward (rx (or whitespace ?
\n)))
817 (python-nav-beginning-of-statement)
824 (defun python-indent-calculate-indentation ()
825 "Calculate correct indentation offset for the current line.
826 Returns `noindent' if the indentation does not depend on Python syntax,
828 (let* ((indentation-context (python-indent-context))
829 (context-status (car indentation-context
))
830 (context-start (cdr indentation-context
)))
834 (pcase context-status
837 (goto-char context-start
)
838 (current-indentation))
839 ;; When point is after beginning of block just add one level
840 ;; of indentation relative to the context-start
841 (`after-beginning-of-block
842 (goto-char context-start
)
843 (+ (current-indentation) python-indent-offset
))
844 ;; When after a simple line just use previous line
847 (let* ((pair (save-excursion
848 (goto-char context-start
)
850 (current-indentation)
851 (python-info-beginning-of-block-p))))
852 (context-indentation (car pair
))
853 ;; TODO: Separate block enders into its own case.
856 (python-util-forward-comment -
1)
857 (python-nav-beginning-of-statement)
858 (looking-at (python-rx block-ender
)))
861 (- context-indentation adjustment
)))
862 ;; When point is on a dedenter statement, search for the
863 ;; opening block that corresponds to it and use its
864 ;; indentation. If no opening block is found just remove
865 ;; indentation as this is an invalid python file.
867 (let ((block-start-point
868 (python-info-dedenter-opening-block-position)))
870 (if (not block-start-point
)
872 (goto-char block-start-point
)
873 (current-indentation)))))
874 ;; When inside of a string, do nothing. just use the current
875 ;; indentation. XXX: perhaps it would be a good idea to
876 ;; invoke standard text indentation here
877 (`inside-string
'noindent
)
878 ;; After backslash we have several possibilities.
881 ;; Check if current line is a dot continuation. For this
882 ;; the current line must start with a dot and previous
883 ;; line must contain a dot too.
885 (back-to-indentation)
886 (when (looking-at "\\.")
887 ;; If after moving one line back point is inside a paren it
888 ;; needs to move back until it's not anymore
892 (python-syntax-context 'paren
))))
893 (goto-char (line-end-position))
894 (while (and (re-search-backward
895 "\\." (line-beginning-position) t
)
896 (python-syntax-context-type)))
897 (if (and (looking-at "\\.")
898 (not (python-syntax-context-type)))
899 ;; The indentation is the same column of the
900 ;; first matching dot that's not inside a
901 ;; comment, a string or a paren
903 ;; No dot found on previous line, just add another
904 ;; indentation level.
905 (+ (current-indentation) python-indent-offset
)))))
906 ;; Check if prev line is a block continuation
907 ((let ((block-continuation-start
908 (python-info-block-continuation-line-p)))
909 (when block-continuation-start
910 ;; If block-continuation-start is set jump to that
911 ;; marker and use first column after the block start
912 ;; as indentation value.
913 (goto-char block-continuation-start
)
915 (python-rx block-start
(* space
))
916 (line-end-position) t
)
918 ;; Check if current line is an assignment continuation
919 ((let ((assignment-continuation-start
920 (python-info-assignment-continuation-line-p)))
921 (when assignment-continuation-start
922 ;; If assignment-continuation is set jump to that
923 ;; marker and use first column after the assignment
924 ;; operator as indentation value.
925 (goto-char assignment-continuation-start
)
929 (goto-char (python-info-beginning-of-backslash))
934 (or (python-info-beginning-of-backslash) (point)))
935 (python-info-line-ends-backslash-p)))
936 ;; The two previous lines ended in a backslash so we must
937 ;; respect previous line indentation.
938 (current-indentation)
939 ;; What happens here is that we are dealing with the second
940 ;; line of a backslash continuation, in that case we just going
941 ;; to add one indentation level.
942 (+ (current-indentation) python-indent-offset
)))))
943 ;; When inside a paren there's a need to handle nesting
947 ;; If current line closes the outermost open paren use the
948 ;; current indentation of the context-start line.
950 (skip-syntax-forward "\s" (line-end-position))
951 (when (and (looking-at (regexp-opt '(")" "]" "}")))
954 (not (python-syntax-context 'paren
))))
955 (goto-char context-start
)
956 (current-indentation))))
957 ;; If open paren is contained on a line by itself add another
958 ;; indentation level, else look for the first word after the
959 ;; opening paren and use it's column position as indentation
961 ((let* ((content-starts-in-newline)
964 (if (setq content-starts-in-newline
966 (goto-char context-start
)
970 (line-beginning-position)
972 (python-util-forward-comment))
974 (+ (current-indentation) python-indent-offset
)
978 ;; If current line closes a nested open paren de-indent one
981 (back-to-indentation)
982 (looking-at (regexp-opt '(")" "]" "}"))))
983 (- indent python-indent-offset
))
984 ;; If the line of the opening paren that wraps the current
985 ;; line starts a block add another level of indentation to
986 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
988 (when (and content-starts-in-newline
990 (goto-char context-start
)
991 (back-to-indentation)
992 (looking-at (python-rx block-start
))))
993 (+ indent python-indent-offset
))))
996 (defun python-indent-calculate-levels ()
997 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
998 (if (or (python-info-continuation-line-p)
999 (not (python-info-dedenter-statement-p)))
1000 ;; XXX: This asks for a refactor. Even if point is on a
1001 ;; dedenter statement, it could be multiline and in that case
1002 ;; the continuation lines should be indented with normal rules.
1003 (let* ((indentation (python-indent-calculate-indentation)))
1004 (if (not (numberp indentation
))
1005 (setq python-indent-levels indentation
)
1006 (let* ((remainder (% indentation python-indent-offset
))
1007 (steps (/ (- indentation remainder
) python-indent-offset
)))
1008 (setq python-indent-levels
(list 0))
1009 (dotimes (step steps
)
1010 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
1011 (when (not (eq 0 remainder
))
1012 (push (+ (* python-indent-offset steps
) remainder
)
1013 python-indent-levels
)))))
1014 (setq python-indent-levels
1016 (mapcar (lambda (pos)
1019 (current-indentation)))
1020 (python-info-dedenter-opening-block-positions))
1022 (when (listp python-indent-levels
)
1023 (setq python-indent-current-level
(1- (length python-indent-levels
))
1024 python-indent-levels
(nreverse python-indent-levels
))))
1026 (defun python-indent-toggle-levels ()
1027 "Toggle `python-indent-current-level' over `python-indent-levels'."
1028 (setq python-indent-current-level
(1- python-indent-current-level
))
1029 (when (< python-indent-current-level
0)
1030 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
1032 (defun python-indent-line (&optional force-toggle
)
1033 "Internal implementation of `python-indent-line-function'.
1034 Uses the offset calculated in
1035 `python-indent-calculate-indentation' and available levels
1036 indicated by the variable `python-indent-levels' to set the
1037 current indentation.
1039 When the variable `last-command' is equal to one of the symbols
1040 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
1041 non-nil it cycles levels indicated in the variable
1042 `python-indent-levels' by setting the current level in the
1043 variable `python-indent-current-level'.
1045 When the variable `last-command' is not equal to one of the
1046 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
1047 is nil it calculates possible indentation levels and saves them
1048 in the variable `python-indent-levels'. Afterwards it sets the
1049 variable `python-indent-current-level' correctly so offset is
1051 (nth python-indent-current-level python-indent-levels)"
1052 (if (and (or (and (memq this-command python-indent-trigger-commands
)
1053 (eq last-command this-command
))
1055 (not (equal python-indent-levels
'(0))))
1056 (if (listp python-indent-levels
)
1057 (python-indent-toggle-levels))
1058 (python-indent-calculate-levels))
1059 (if (eq python-indent-levels
'noindent
)
1060 python-indent-levels
1061 (let* ((starting-pos (point-marker))
1062 (indent-ending-position
1063 (+ (line-beginning-position) (current-indentation)))
1064 (follow-indentation-p
1066 (and (<= (line-beginning-position) starting-pos
)
1067 (>= indent-ending-position starting-pos
))))
1068 (next-indent (nth python-indent-current-level python-indent-levels
)))
1069 (unless (= next-indent
(current-indentation))
1071 (delete-horizontal-space)
1072 (indent-to next-indent
)
1073 (goto-char starting-pos
))
1074 (and follow-indentation-p
(back-to-indentation)))
1075 (python-info-dedenter-opening-block-message)))
1077 (defun python-indent-line-function ()
1078 "`indent-line-function' for Python mode.
1079 See `python-indent-line' for details."
1080 (python-indent-line))
1082 (defun python-indent-dedent-line ()
1083 "De-indent current line."
1085 (when (and (not (python-syntax-comment-or-string-p))
1086 (<= (point) (save-excursion
1087 (back-to-indentation)
1089 (> (current-column) 0))
1090 (python-indent-line t
)
1093 (defun python-indent-dedent-line-backspace (arg)
1094 "De-indent current line.
1095 Argument ARG is passed to `backward-delete-char-untabify' when
1096 point is not in between the indentation."
1098 (when (not (python-indent-dedent-line))
1099 (backward-delete-char-untabify arg
)))
1100 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1102 (defun python-indent-region (start end
)
1103 "Indent a Python region automagically.
1105 Called from a program, START and END specify the region to indent."
1106 (let ((deactivate-mark nil
))
1109 (setq end
(point-marker))
1111 (or (bolp) (forward-line 1))
1112 (while (< (point) end
)
1113 (or (and (bolp) (eolp))
1115 ;; Skip if previous line is empty or a comment.
1117 (let ((line-is-comment-p
1118 (python-info-current-line-comment-p)))
1121 (or (and (python-info-current-line-comment-p)
1122 ;; Unless this line is a comment too.
1123 (not line-is-comment-p
))
1124 (python-info-current-line-empty-p)))))
1125 ;; Don't mess with strings, unless it's the
1126 ;; enclosing set of quotes.
1127 (or (not (python-syntax-context 'string
))
1131 (current-indentation)
1132 (python-syntax-count-quotes (char-after) (point))))
1133 (string-to-syntax "|")))
1134 ;; Skip if current line is a block start, a
1135 ;; dedenter or block ender.
1137 (back-to-indentation)
1140 (or block-start dedenter block-ender
))))))
1141 (python-indent-line)))
1143 (move-marker end nil
))))
1145 (defun python-indent-shift-left (start end
&optional count
)
1146 "Shift lines contained in region START END by COUNT columns to the left.
1147 COUNT defaults to `python-indent-offset'. If region isn't
1148 active, the current line is shifted. The shifted region includes
1149 the lines in which START and END lie. An error is signaled if
1150 any lines in the region are indented less than COUNT columns."
1153 (list (region-beginning) (region-end) current-prefix-arg
)
1154 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1156 (setq count
(prefix-numeric-value count
))
1157 (setq count python-indent-offset
))
1159 (let ((deactivate-mark nil
))
1162 (while (< (point) end
)
1163 (if (and (< (current-indentation) count
)
1164 (not (looking-at "[ \t]*$")))
1165 (user-error "Can't shift all lines enough"))
1167 (indent-rigidly start end
(- count
))))))
1169 (defun python-indent-shift-right (start end
&optional count
)
1170 "Shift lines contained in region START END by COUNT columns to the right.
1171 COUNT defaults to `python-indent-offset'. If region isn't
1172 active, the current line is shifted. The shifted region includes
1173 the lines in which START and END lie."
1176 (list (region-beginning) (region-end) current-prefix-arg
)
1177 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1178 (let ((deactivate-mark nil
))
1179 (setq count
(if count
(prefix-numeric-value count
)
1180 python-indent-offset
))
1181 (indent-rigidly start end count
)))
1183 (defun python-indent-post-self-insert-function ()
1184 "Adjust indentation after insertion of some characters.
1185 This function is intended to be added to `post-self-insert-hook.'
1186 If a line renders a paren alone, after adding a char before it,
1187 the line will be re-indented automatically if needed."
1188 (when (and electric-indent-mode
1189 (eq (char-before) last-command-event
))
1191 ;; Electric indent inside parens
1194 (let ((paren-start (python-syntax-context 'paren
)))
1195 ;; Check that point is inside parens.
1198 ;; Filter the case where input is happening in the same
1199 ;; line where the open paren is.
1200 (= (line-number-at-pos)
1201 (line-number-at-pos paren-start
)))))
1202 ;; When content has been added before the closing paren or a
1203 ;; comma has been inserted, it's ok to do the trick.
1205 (memq (char-after) '(?\
) ?\
] ?\
}))
1206 (eq (char-before) ?
,)))
1208 (goto-char (line-beginning-position))
1209 (let ((indentation (python-indent-calculate-indentation)))
1210 (when (and (numberp indentation
) (< (current-indentation) indentation
))
1211 (indent-line-to indentation
)))))
1213 ((and (eq ?
: last-command-event
)
1214 (memq ?
: electric-indent-chars
)
1215 (not current-prefix-arg
)
1216 ;; Trigger electric colon only at end of line
1218 ;; Avoid re-indenting on extra colon
1219 (not (equal ?
: (char-before (1- (point)))))
1220 (not (python-syntax-comment-or-string-p)))
1221 ;; Just re-indent dedenters
1222 (let ((dedenter-pos (python-info-dedenter-statement-p))
1223 (current-pos (point)))
1226 (goto-char dedenter-pos
)
1227 (python-indent-line)
1228 (unless (= (line-number-at-pos dedenter-pos
)
1229 (line-number-at-pos current-pos
))
1230 ;; Reindent region if this is a multiline statement
1231 (python-indent-region dedenter-pos current-pos
)))))))))
1236 (defvar python-nav-beginning-of-defun-regexp
1237 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1238 "Regexp matching class or function definition.
1239 The name of the defun should be grouped so it can be retrieved
1240 via `match-string'.")
1242 (defun python-nav--beginning-of-defun (&optional arg
)
1243 "Internal implementation of `python-nav-beginning-of-defun'.
1244 With positive ARG search backwards, else search forwards."
1245 (when (or (null arg
) (= arg
0)) (setq arg
1))
1246 (let* ((re-search-fn (if (> arg
0)
1247 #'re-search-backward
1248 #'re-search-forward
))
1249 (line-beg-pos (line-beginning-position))
1250 (line-content-start (+ line-beg-pos
(current-indentation)))
1251 (pos (point-marker))
1256 (not (python-info-looking-at-beginning-of-defun))
1257 (python-nav-backward-block)))
1258 (or (and (python-info-looking-at-beginning-of-defun)
1259 (+ (current-indentation) python-indent-offset
))
1263 (when (and (< arg
0)
1264 (python-info-looking-at-beginning-of-defun))
1266 (while (and (funcall re-search-fn
1267 python-nav-beginning-of-defun-regexp nil t
)
1268 (or (python-syntax-context-type)
1269 ;; Handle nested defuns when moving
1270 ;; backwards by checking indentation.
1272 (not (= (current-indentation) 0))
1273 (>= (current-indentation) beg-indentation
)))))
1274 (and (python-info-looking-at-beginning-of-defun)
1275 (or (not (= (line-number-at-pos pos
)
1276 (line-number-at-pos)))
1277 (and (>= (point) line-beg-pos
)
1278 (<= (point) line-content-start
)
1279 (> pos line-content-start
)))))))
1281 (or (beginning-of-line 1) t
)
1282 (and (goto-char pos
) nil
))))
1284 (defun python-nav-beginning-of-defun (&optional arg
)
1285 "Move point to `beginning-of-defun'.
1286 With positive ARG search backwards else search forward.
1287 ARG nil or 0 defaults to 1. When searching backwards,
1288 nested defuns are handled with care depending on current
1289 point position. Return non-nil if point is moved to
1290 `beginning-of-defun'."
1291 (when (or (null arg
) (= arg
0)) (setq arg
1))
1293 (while (and (not (= arg
0))
1294 (let ((keep-searching-p
1295 (python-nav--beginning-of-defun arg)))
1296 (when (and keep-searching-p
(null found
))
1299 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1302 (defun python-nav-end-of-defun ()
1303 "Move point to the end of def or class.
1304 Returns nil if point is not in a def or class."
1306 (let ((beg-defun-indent)
1308 (when (or (python-info-looking-at-beginning-of-defun)
1309 (python-nav-beginning-of-defun 1)
1310 (python-nav-beginning-of-defun -1))
1311 (setq beg-defun-indent
(current-indentation))
1313 (python-nav-end-of-statement)
1314 (python-util-forward-comment 1)
1315 (and (> (current-indentation) beg-defun-indent
)
1317 (python-util-forward-comment -
1)
1319 ;; Ensure point moves forward.
1320 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1322 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1323 "Move point using FN avoiding places with specific context.
1324 FN must take no arguments. POSCOMPFN is a two arguments function
1325 used to compare current and previous point after it is moved
1326 using FN, this is normally a less-than or greater-than
1327 comparison. Optional argument CONTEXTFN defaults to
1328 `python-syntax-context-type' and is used for checking current
1329 point context, it must return a non-nil value if this point must
1331 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1332 (start-pos (point-marker))
1337 (and (funcall fn
) (point-marker)))
1338 (context (funcall contextfn
)))
1339 (cond ((and (not context
) newpos
1340 (or (and (not prev-pos
) newpos
)
1341 (and prev-pos newpos
1342 (funcall poscompfn newpos prev-pos
))))
1343 (throw 'found
(point-marker)))
1344 ((and newpos context
)
1345 (setq prev-pos
(point)))
1346 (t (when (not newpos
) (goto-char start-pos
))
1347 (throw 'found nil
))))))))
1349 (defun python-nav--forward-defun (arg)
1350 "Internal implementation of python-nav-{backward,forward}-defun.
1351 Uses ARG to define which function to call, and how many times
1354 (while (and (> arg
0)
1356 (python-nav--syntactically
1359 python-nav-beginning-of-defun-regexp nil t
))
1361 (setq arg
(1- arg
)))
1362 (while (and (< arg
0)
1364 (python-nav--syntactically
1367 python-nav-beginning-of-defun-regexp nil t
))
1369 (setq arg
(1+ arg
)))
1372 (defun python-nav-backward-defun (&optional arg
)
1373 "Navigate to closer defun backward ARG times.
1374 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1375 nested definitions."
1377 (python-nav--forward-defun (- (or arg
1))))
1379 (defun python-nav-forward-defun (&optional arg
)
1380 "Navigate to closer defun forward ARG times.
1381 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1382 nested definitions."
1384 (python-nav--forward-defun (or arg
1)))
1386 (defun python-nav-beginning-of-statement ()
1387 "Move to start of current statement."
1389 (back-to-indentation)
1390 (let* ((ppss (syntax-ppss))
1393 (python-syntax-context 'paren ppss
)
1394 (python-syntax-context 'string ppss
))))
1397 (goto-char context-point
)
1398 (python-nav-beginning-of-statement))
1401 (python-info-line-ends-backslash-p))
1403 (python-nav-beginning-of-statement))))
1406 (defun python-nav-end-of-statement (&optional noend
)
1407 "Move to end of current statement.
1408 Optional argument NOEND is internal and makes the logic to not
1409 jump to the end of line when moving forward searching for the end
1412 (let (string-start bs-pos
)
1413 (while (and (or noend
(goto-char (line-end-position)))
1415 (cond ((setq string-start
(python-syntax-context 'string
))
1416 (goto-char string-start
)
1417 (if (python-syntax-context 'paren
)
1418 ;; Ended up inside a paren, roll again.
1419 (python-nav-end-of-statement t
)
1420 ;; This is not inside a paren, move to the
1421 ;; end of this string.
1422 (goto-char (+ (point)
1423 (python-syntax-count-quotes
1424 (char-after (point)) (point))))
1425 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1426 (goto-char (point-max)))))
1427 ((python-syntax-context 'paren
)
1428 ;; The statement won't end before we've escaped
1429 ;; at least one level of parenthesis.
1431 (goto-char (scan-lists (point) 1 -
1))
1432 (scan-error (goto-char (nth 3 err
)))))
1433 ((setq bs-pos
(python-info-line-ends-backslash-p))
1435 (forward-line 1))))))
1438 (defun python-nav-backward-statement (&optional arg
)
1439 "Move backward to previous statement.
1440 With ARG, repeat. See `python-nav-forward-statement'."
1442 (or arg
(setq arg
1))
1443 (python-nav-forward-statement (- arg
)))
1445 (defun python-nav-forward-statement (&optional arg
)
1446 "Move forward to next statement.
1447 With ARG, repeat. With negative argument, move ARG times
1448 backward to previous statement."
1450 (or arg
(setq arg
1))
1452 (python-nav-end-of-statement)
1453 (python-util-forward-comment)
1454 (python-nav-beginning-of-statement)
1455 (setq arg
(1- arg
)))
1457 (python-nav-beginning-of-statement)
1458 (python-util-forward-comment -
1)
1459 (python-nav-beginning-of-statement)
1460 (setq arg
(1+ arg
))))
1462 (defun python-nav-beginning-of-block ()
1463 "Move to start of current block."
1465 (let ((starting-pos (point)))
1467 (python-nav-beginning-of-statement)
1468 (looking-at (python-rx block-start
)))
1470 ;; Go to first line beginning a statement
1471 (while (and (not (bobp))
1472 (or (and (python-nav-beginning-of-statement) nil
)
1473 (python-info-current-line-comment-p)
1474 (python-info-current-line-empty-p)))
1476 (let ((block-matching-indent
1477 (- (current-indentation) python-indent-offset
)))
1479 (and (python-nav-backward-block)
1480 (> (current-indentation) block-matching-indent
)))
1481 (if (and (looking-at (python-rx block-start
))
1482 (= (current-indentation) block-matching-indent
))
1484 (and (goto-char starting-pos
) nil
))))))
1486 (defun python-nav-end-of-block ()
1487 "Move to end of current block."
1489 (when (python-nav-beginning-of-block)
1490 (let ((block-indentation (current-indentation)))
1491 (python-nav-end-of-statement)
1492 (while (and (forward-line 1)
1494 (or (and (> (current-indentation) block-indentation
)
1495 (or (python-nav-end-of-statement) t
))
1496 (python-info-current-line-comment-p)
1497 (python-info-current-line-empty-p))))
1498 (python-util-forward-comment -
1)
1501 (defun python-nav-backward-block (&optional arg
)
1502 "Move backward to previous block of code.
1503 With ARG, repeat. See `python-nav-forward-block'."
1505 (or arg
(setq arg
1))
1506 (python-nav-forward-block (- arg
)))
1508 (defun python-nav-forward-block (&optional arg
)
1509 "Move forward to next block of code.
1510 With ARG, repeat. With negative argument, move ARG times
1511 backward to previous block."
1513 (or arg
(setq arg
1))
1514 (let ((block-start-regexp
1515 (python-rx line-start
(* whitespace
) block-start
))
1516 (starting-pos (point)))
1518 (python-nav-end-of-statement)
1520 (re-search-forward block-start-regexp nil t
)
1521 (python-syntax-context-type)))
1522 (setq arg
(1- arg
)))
1524 (python-nav-beginning-of-statement)
1526 (re-search-backward block-start-regexp nil t
)
1527 (python-syntax-context-type)))
1528 (setq arg
(1+ arg
)))
1529 (python-nav-beginning-of-statement)
1530 (if (not (looking-at (python-rx block-start
)))
1531 (and (goto-char starting-pos
) nil
)
1532 (and (not (= (point) starting-pos
)) (point-marker)))))
1534 (defun python-nav--lisp-forward-sexp (&optional arg
)
1535 "Standard version `forward-sexp'.
1536 It ignores completely the value of `forward-sexp-function' by
1537 setting it to nil before calling `forward-sexp'. With positive
1538 ARG move forward only one sexp, else move backwards."
1539 (let ((forward-sexp-function)
1540 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1541 (forward-sexp arg
)))
1543 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1544 "Safe version of standard `forward-sexp'.
1545 When at end of sexp (i.e. looking at a opening/closing paren)
1546 skips it instead of throwing an error. With positive ARG move
1547 forward only one sexp, else move backwards."
1548 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1550 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1552 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1554 (python-nav--lisp-forward-sexp arg
)
1556 (while (and (funcall search-fn paren-regexp nil t
)
1557 (python-syntax-context 'paren
)))))))
1559 (defun python-nav--forward-sexp (&optional dir safe
)
1560 "Move to forward sexp.
1561 With positive optional argument DIR direction move forward, else
1562 backwards. When optional argument SAFE is non-nil do not throw
1563 errors when at end of sexp, skip it instead."
1564 (setq dir
(or dir
1))
1566 (let* ((forward-p (if (> dir
0)
1567 (and (setq dir
1) t
)
1568 (and (setq dir -
1) nil
)))
1569 (context-type (python-syntax-context-type)))
1571 ((memq context-type
'(string comment
))
1572 ;; Inside of a string, get out of it.
1573 (let ((forward-sexp-function))
1574 (forward-sexp dir
)))
1575 ((or (eq context-type
'paren
)
1576 (and forward-p
(looking-at (python-rx open-paren
)))
1577 (and (not forward-p
)
1578 (eq (syntax-class (syntax-after (1- (point))))
1579 (car (string-to-syntax ")")))))
1580 ;; Inside a paren or looking at it, lisp knows what to do.
1582 (python-nav--lisp-forward-sexp-safe dir
)
1583 (python-nav--lisp-forward-sexp dir
)))
1585 ;; This part handles the lispy feel of
1586 ;; `python-nav-forward-sexp'. Knowing everything about the
1587 ;; current context and the context of the next sexp tries to
1588 ;; follow the lisp sexp motion commands in a symmetric manner.
1591 ((python-info-beginning-of-block-p) 'block-start
)
1592 ((python-info-end-of-block-p) 'block-end
)
1593 ((python-info-beginning-of-statement-p) 'statement-start
)
1594 ((python-info-end-of-statement-p) 'statement-end
)))
1598 (python-nav--lisp-forward-sexp-safe dir
)
1599 (python-nav--lisp-forward-sexp dir
))
1603 (goto-char next-sexp-pos
)
1605 ((python-info-beginning-of-block-p) 'block-start
)
1606 ((python-info-end-of-block-p) 'block-end
)
1607 ((python-info-beginning-of-statement-p) 'statement-start
)
1608 ((python-info-end-of-statement-p) 'statement-end
)
1609 ((python-info-statement-starts-block-p) 'starts-block
)
1610 ((python-info-statement-ends-block-p) 'ends-block
)))))
1612 (cond ((and (not (eobp))
1613 (python-info-current-line-empty-p))
1614 (python-util-forward-comment dir
)
1615 (python-nav--forward-sexp dir
))
1616 ((eq context
'block-start
)
1617 (python-nav-end-of-block))
1618 ((eq context
'statement-start
)
1619 (python-nav-end-of-statement))
1620 ((and (memq context
'(statement-end block-end
))
1621 (eq next-sexp-context
'ends-block
))
1622 (goto-char next-sexp-pos
)
1623 (python-nav-end-of-block))
1624 ((and (memq context
'(statement-end block-end
))
1625 (eq next-sexp-context
'starts-block
))
1626 (goto-char next-sexp-pos
)
1627 (python-nav-end-of-block))
1628 ((memq context
'(statement-end block-end
))
1629 (goto-char next-sexp-pos
)
1630 (python-nav-end-of-statement))
1631 (t (goto-char next-sexp-pos
)))
1632 (cond ((and (not (bobp))
1633 (python-info-current-line-empty-p))
1634 (python-util-forward-comment dir
)
1635 (python-nav--forward-sexp dir
))
1636 ((eq context
'block-end
)
1637 (python-nav-beginning-of-block))
1638 ((eq context
'statement-end
)
1639 (python-nav-beginning-of-statement))
1640 ((and (memq context
'(statement-start block-start
))
1641 (eq next-sexp-context
'starts-block
))
1642 (goto-char next-sexp-pos
)
1643 (python-nav-beginning-of-block))
1644 ((and (memq context
'(statement-start block-start
))
1645 (eq next-sexp-context
'ends-block
))
1646 (goto-char next-sexp-pos
)
1647 (python-nav-beginning-of-block))
1648 ((memq context
'(statement-start block-start
))
1649 (goto-char next-sexp-pos
)
1650 (python-nav-beginning-of-statement))
1651 (t (goto-char next-sexp-pos
))))))))))
1653 (defun python-nav-forward-sexp (&optional arg
)
1654 "Move forward across expressions.
1655 With ARG, do it that many times. Negative arg -N means move
1658 (or arg
(setq arg
1))
1660 (python-nav--forward-sexp 1)
1661 (setq arg
(1- arg
)))
1663 (python-nav--forward-sexp -
1)
1664 (setq arg
(1+ arg
))))
1666 (defun python-nav-backward-sexp (&optional arg
)
1667 "Move backward across expressions.
1668 With ARG, do it that many times. Negative arg -N means move
1671 (or arg
(setq arg
1))
1672 (python-nav-forward-sexp (- arg
)))
1674 (defun python-nav-forward-sexp-safe (&optional arg
)
1675 "Move forward safely across expressions.
1676 With ARG, do it that many times. Negative arg -N means move
1679 (or arg
(setq arg
1))
1681 (python-nav--forward-sexp 1 t
)
1682 (setq arg
(1- arg
)))
1684 (python-nav--forward-sexp -
1 t
)
1685 (setq arg
(1+ arg
))))
1687 (defun python-nav-backward-sexp-safe (&optional arg
)
1688 "Move backward safely across expressions.
1689 With ARG, do it that many times. Negative arg -N means move
1692 (or arg
(setq arg
1))
1693 (python-nav-forward-sexp-safe (- arg
)))
1695 (defun python-nav--up-list (&optional dir
)
1696 "Internal implementation of `python-nav-up-list'.
1697 DIR is always 1 or -1 and comes sanitized from
1698 `python-nav-up-list' calls."
1699 (let ((context (python-syntax-context-type))
1700 (forward-p (> dir
0)))
1702 ((memq context
'(string comment
)))
1703 ((eq context
'paren
)
1704 (let ((forward-sexp-function))
1706 ((and forward-p
(python-info-end-of-block-p))
1707 (let ((parent-end-pos
1709 (let ((indentation (and
1710 (python-nav-beginning-of-block)
1711 (current-indentation))))
1712 (while (and indentation
1714 (>= (current-indentation) indentation
)
1715 (python-nav-backward-block)))
1716 (python-nav-end-of-block)))))
1717 (and (> (or parent-end-pos
(point)) (point))
1718 (goto-char parent-end-pos
))))
1719 (forward-p (python-nav-end-of-block))
1720 ((and (not forward-p
)
1721 (> (current-indentation) 0)
1722 (python-info-beginning-of-block-p))
1723 (let ((prev-block-pos
1725 (let ((indentation (current-indentation)))
1726 (while (and (python-nav-backward-block)
1727 (>= (current-indentation) indentation
))))
1729 (and (> (point) prev-block-pos
)
1730 (goto-char prev-block-pos
))))
1731 ((not forward-p
) (python-nav-beginning-of-block)))))
1733 (defun python-nav-up-list (&optional arg
)
1734 "Move forward out of one level of parentheses (or blocks).
1735 With ARG, do this that many times.
1736 A negative argument means move backward but still to a less deep spot.
1737 This command assumes point is not in a string or comment."
1739 (or arg
(setq arg
1))
1741 (python-nav--up-list 1)
1742 (setq arg
(1- arg
)))
1744 (python-nav--up-list -
1)
1745 (setq arg
(1+ arg
))))
1747 (defun python-nav-backward-up-list (&optional arg
)
1748 "Move backward out of one level of parentheses (or blocks).
1749 With ARG, do this that many times.
1750 A negative argument means move forward but still to a less deep spot.
1751 This command assumes point is not in a string or comment."
1753 (or arg
(setq arg
1))
1754 (python-nav-up-list (- arg
)))
1756 (defun python-nav-if-name-main ()
1757 "Move point at the beginning the __main__ block.
1758 When \"if __name__ == '__main__':\" is found returns its
1759 position, else returns nil."
1761 (let ((point (point))
1762 (found (catch 'found
1763 (goto-char (point-min))
1764 (while (re-search-forward
1765 (python-rx line-start
1767 "__name__" (+ space
)
1769 (group-n 1 (or ?
\" ?
\'))
1770 "__main__" (backref 1) (* space
) ":")
1772 (when (not (python-syntax-context-type))
1774 (throw 'found t
))))))
1777 (ignore (goto-char point
)))))
1780 ;;; Shell integration
1782 (defcustom python-shell-buffer-name
"Python"
1783 "Default buffer name for Python interpreter."
1788 (defcustom python-shell-interpreter
"python"
1789 "Default Python interpreter for shell."
1793 (defcustom python-shell-internal-buffer-name
"Python Internal"
1794 "Default buffer name for the Internal Python interpreter."
1799 (defcustom python-shell-interpreter-args
"-i"
1800 "Default arguments for the Python interpreter."
1804 (defcustom python-shell-interpreter-interactive-arg
"-i"
1805 "Interpreter argument to force it to run interactively."
1809 (defcustom python-shell-prompt-detect-enabled t
1810 "Non-nil enables autodetection of interpreter prompts."
1815 (defcustom python-shell-prompt-detect-failure-warning t
1816 "Non-nil enables warnings when detection of prompts fail."
1821 (defcustom python-shell-prompt-input-regexps
1822 '(">>> " "\\.\\.\\. " ; Python
1823 "In \\[[0-9]+\\]: " ; IPython
1824 " \\.\\.\\.: " ; IPython
1825 ;; Using ipdb outside IPython may fail to cleanup and leave static
1826 ;; IPython prompts activated, this adds some safeguard for that.
1827 "In : " "\\.\\.\\.: ")
1828 "List of regular expressions matching input prompts."
1829 :type
'(repeat string
)
1832 (defcustom python-shell-prompt-output-regexps
1834 "Out\\[[0-9]+\\]: " ; IPython
1835 "Out :") ; ipdb safeguard
1836 "List of regular expressions matching output prompts."
1837 :type
'(repeat string
)
1840 (defcustom python-shell-prompt-regexp
">>> "
1841 "Regular expression matching top level input prompt of Python shell.
1842 It should not contain a caret (^) at the beginning."
1845 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1846 "Regular expression matching block input prompt of Python shell.
1847 It should not contain a caret (^) at the beginning."
1850 (defcustom python-shell-prompt-output-regexp
""
1851 "Regular expression matching output prompt of Python shell.
1852 It should not contain a caret (^) at the beginning."
1855 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1856 "Regular expression matching pdb input prompt of Python shell.
1857 It should not contain a caret (^) at the beginning."
1860 (define-obsolete-variable-alias
1861 'python-shell-enable-font-lock
'python-shell-font-lock-enable
"25.1")
1863 (defcustom python-shell-font-lock-enable t
1864 "Should syntax highlighting be enabled in the Python shell buffer?
1865 Restart the Python shell after changing this variable for it to take effect."
1870 (defcustom python-shell-unbuffered t
1871 "Should shell output be unbuffered?.
1872 When non-nil, this may prevent delayed and missing output in the
1873 Python shell. See commentary for details."
1878 (defcustom python-shell-process-environment nil
1879 "List of environment variables for Python shell.
1880 This variable follows the same rules as `process-environment'
1881 since it merges with it before the process creation routines are
1882 called. When this variable is nil, the Python shell is run with
1883 the default `process-environment'."
1884 :type
'(repeat string
)
1888 (defcustom python-shell-extra-pythonpaths nil
1889 "List of extra pythonpaths for Python shell.
1890 The values of this variable are added to the existing value of
1891 PYTHONPATH in the `process-environment' variable."
1892 :type
'(repeat string
)
1896 (defcustom python-shell-exec-path nil
1897 "List of path to search for binaries.
1898 This variable follows the same rules as `exec-path' since it
1899 merges with it before the process creation routines are called.
1900 When this variable is nil, the Python shell is run with the
1901 default `exec-path'."
1902 :type
'(repeat string
)
1906 (defcustom python-shell-virtualenv-root nil
1907 "Path to virtualenv root.
1908 This variable, when set to a string, makes the values stored in
1909 `python-shell-process-environment' and `python-shell-exec-path'
1910 to be modified properly so shells are started with the specified
1912 :type
'(choice (const nil
) string
)
1916 (define-obsolete-variable-alias
1917 'python-shell-virtualenv-path
'python-shell-virtualenv-root
"25.1")
1919 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1920 python-ffap-setup-code
1921 python-eldoc-setup-code
)
1922 "List of code run by `python-shell-send-setup-codes'."
1923 :type
'(repeat symbol
)
1927 (defcustom python-shell-compilation-regexp-alist
1928 `((,(rx line-start
(1+ (any " \t")) "File \""
1929 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1930 "\", line " (group (1+ digit
)))
1932 (,(rx " in file " (group (1+ not-newline
)) " on line "
1935 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1936 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1938 "`compilation-error-regexp-alist' for inferior Python."
1939 :type
'(alist string
)
1942 (defvar python-shell--prompt-calculated-input-regexp nil
1943 "Calculated input prompt regexp for inferior python shell.
1944 Do not set this variable directly, instead use
1945 `python-shell-prompt-set-calculated-regexps'.")
1947 (defvar python-shell--prompt-calculated-output-regexp nil
1948 "Calculated output prompt regexp for inferior python shell.
1949 Do not set this variable directly, instead use
1950 `python-shell-set-prompt-regexp'.")
1952 (defun python-shell-prompt-detect ()
1953 "Detect prompts for the current `python-shell-interpreter'.
1954 When prompts can be retrieved successfully from the
1955 `python-shell-interpreter' run with
1956 `python-shell-interpreter-interactive-arg', returns a list of
1957 three elements, where the first two are input prompts and the
1958 last one is an output prompt. When no prompts can be detected
1959 and `python-shell-prompt-detect-failure-warning' is non-nil,
1960 shows a warning with instructions to avoid hangs and returns nil.
1961 When `python-shell-prompt-detect-enabled' is nil avoids any
1962 detection and just returns nil."
1963 (when python-shell-prompt-detect-enabled
1964 (let* ((process-environment (python-shell-calculate-process-environment))
1965 (exec-path (python-shell-calculate-exec-path))
1968 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1969 ;; JSON is built manually for compatibility
1970 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1975 ;; TODO: improve error handling by using
1976 ;; `condition-case' and displaying the error message to
1977 ;; the user in the no-prompts warning.
1979 (let ((code-file (python-shell--save-temp-file code
)))
1980 ;; Use `process-file' as it is remote-host friendly.
1982 python-shell-interpreter
1986 python-shell-interpreter-interactive-arg
)
1988 (delete-file code-file
)))
1992 (dolist (line (split-string output
"\n" t
))
1994 ;; Check if current line is a valid JSON array
1995 (and (string= (substring line
0 2) "[\"")
1997 ;; Return prompts as a list, not vector
1998 (append (json-read-from-string line
) nil
)))))
1999 ;; The list must contain 3 strings, where the first
2000 ;; is the input prompt, the second is the block
2001 ;; prompt and the last one is the output prompt. The
2002 ;; input prompt is the only one that can't be empty.
2003 (when (and (= (length res
) 3)
2004 (cl-every #'stringp res
)
2005 (not (string= (car res
) "")))
2006 (throw 'prompts res
))))
2008 (when (and (not prompts
)
2009 python-shell-prompt-detect-failure-warning
)
2011 '(python python-shell-prompt-regexp
)
2014 "Python shell prompts cannot be detected.\n"
2015 "If your emacs session hangs when starting python shells\n"
2016 "recover with `keyboard-quit' and then try fixing the\n"
2017 "interactive flag for your interpreter by adjusting the\n"
2018 "`python-shell-interpreter-interactive-arg' or add regexps\n"
2019 "matching shell prompts in the directory-local friendly vars:\n"
2020 " + `python-shell-prompt-regexp'\n"
2021 " + `python-shell-prompt-block-regexp'\n"
2022 " + `python-shell-prompt-output-regexp'\n"
2023 "Or alternatively in:\n"
2024 " + `python-shell-prompt-input-regexps'\n"
2025 " + `python-shell-prompt-output-regexps'")))
2028 (defun python-shell-prompt-validate-regexps ()
2029 "Validate all user provided regexps for prompts.
2030 Signals `user-error' if any of these vars contain invalid
2031 regexps: `python-shell-prompt-regexp',
2032 `python-shell-prompt-block-regexp',
2033 `python-shell-prompt-pdb-regexp',
2034 `python-shell-prompt-output-regexp',
2035 `python-shell-prompt-input-regexps',
2036 `python-shell-prompt-output-regexps'."
2037 (dolist (symbol (list 'python-shell-prompt-input-regexps
2038 'python-shell-prompt-output-regexps
2039 'python-shell-prompt-regexp
2040 'python-shell-prompt-block-regexp
2041 'python-shell-prompt-pdb-regexp
2042 'python-shell-prompt-output-regexp
))
2043 (dolist (regexp (let ((regexps (symbol-value symbol
)))
2047 (when (not (python-util-valid-regexp-p regexp
))
2048 (user-error "Invalid regexp %s in `%s'"
2051 (defun python-shell-prompt-set-calculated-regexps ()
2052 "Detect and set input and output prompt regexps.
2053 Build and set the values for `python-shell-input-prompt-regexp'
2054 and `python-shell-output-prompt-regexp' using the values from
2055 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2056 `python-shell-prompt-pdb-regexp',
2057 `python-shell-prompt-output-regexp',
2058 `python-shell-prompt-input-regexps',
2059 `python-shell-prompt-output-regexps' and detected prompts from
2060 `python-shell-prompt-detect'."
2061 (when (not (and python-shell--prompt-calculated-input-regexp
2062 python-shell--prompt-calculated-output-regexp
))
2063 (let* ((detected-prompts (python-shell-prompt-detect))
2065 (output-prompts nil
)
2069 (mapconcat #'identity
2072 (let ((length-a (length a
))
2073 (length-b (length b
)))
2074 (if (= length-a length-b
)
2076 (> (length a
) (length b
))))))
2079 ;; Validate ALL regexps
2080 (python-shell-prompt-validate-regexps)
2081 ;; Collect all user defined input prompts
2082 (dolist (prompt (append python-shell-prompt-input-regexps
2083 (list python-shell-prompt-regexp
2084 python-shell-prompt-block-regexp
2085 python-shell-prompt-pdb-regexp
)))
2086 (cl-pushnew prompt input-prompts
:test
#'string
=))
2087 ;; Collect all user defined output prompts
2088 (dolist (prompt (cons python-shell-prompt-output-regexp
2089 python-shell-prompt-output-regexps
))
2090 (cl-pushnew prompt output-prompts
:test
#'string
=))
2091 ;; Collect detected prompts if any
2092 (when detected-prompts
2093 (dolist (prompt (butlast detected-prompts
))
2094 (setq prompt
(regexp-quote prompt
))
2095 (cl-pushnew prompt input-prompts
:test
#'string
=))
2096 (cl-pushnew (regexp-quote
2097 (car (last detected-prompts
)))
2098 output-prompts
:test
#'string
=))
2099 ;; Set input and output prompt regexps from collected prompts
2100 (setq python-shell--prompt-calculated-input-regexp
2101 (funcall build-regexp input-prompts
)
2102 python-shell--prompt-calculated-output-regexp
2103 (funcall build-regexp output-prompts
)))))
2105 (defun python-shell-get-process-name (dedicated)
2106 "Calculate the appropriate process name for inferior Python process.
2107 If DEDICATED is t returns a string with the form
2108 `python-shell-buffer-name'[`buffer-name'] else returns the value
2109 of `python-shell-buffer-name'."
2111 (format "%s[%s]" python-shell-buffer-name
(buffer-name))
2112 python-shell-buffer-name
))
2114 (defun python-shell-internal-get-process-name ()
2115 "Calculate the appropriate process name for Internal Python process.
2116 The name is calculated from `python-shell-global-buffer-name' and
2118 (format "%s[%s]" python-shell-internal-buffer-name
(buffer-name)))
2120 (defun python-shell-calculate-command ()
2121 "Calculate the string used to execute the inferior Python process."
2122 (let ((exec-path (python-shell-calculate-exec-path)))
2123 ;; `exec-path' gets tweaked so that virtualenv's specific
2124 ;; `python-shell-interpreter' absolute path can be found by
2125 ;; `executable-find'.
2127 ;; FIXME: Why executable-find?
2128 (shell-quote-argument
2129 (executable-find python-shell-interpreter
))
2130 python-shell-interpreter-args
)))
2132 (define-obsolete-function-alias
2133 'python-shell-parse-command
2134 #'python-shell-calculate-command
"25.1")
2136 (defun python-shell-calculate-pythonpath ()
2137 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2138 (let ((pythonpath (getenv "PYTHONPATH"))
2139 (extra (mapconcat 'identity
2140 python-shell-extra-pythonpaths
2143 (concat extra path-separator pythonpath
)
2146 (defun python-shell-calculate-process-environment ()
2147 "Calculate process environment given `python-shell-virtualenv-root'."
2148 (let ((process-environment (append
2149 python-shell-process-environment
2150 process-environment nil
))
2151 (virtualenv (if python-shell-virtualenv-root
2152 (directory-file-name python-shell-virtualenv-root
)
2154 (when python-shell-unbuffered
2155 (setenv "PYTHONUNBUFFERED" "1"))
2156 (when python-shell-extra-pythonpaths
2157 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2158 (if (not virtualenv
)
2160 (setenv "PYTHONHOME" nil
)
2161 (setenv "PATH" (format "%s/bin%s%s"
2162 virtualenv path-separator
2163 (or (getenv "PATH") "")))
2164 (setenv "VIRTUAL_ENV" virtualenv
))
2165 process-environment
))
2167 (defun python-shell-calculate-exec-path ()
2168 "Calculate exec path given `python-shell-virtualenv-root'."
2170 ;; Use nil as the tail so that the list is a full copy,
2171 ;; this is a paranoid safeguard for side-effects.
2172 python-shell-exec-path exec-path nil
)))
2173 (if (not python-shell-virtualenv-root
)
2175 (cons (expand-file-name "bin" python-shell-virtualenv-root
)
2178 (defvar python-shell--package-depth
10)
2180 (defun python-shell-package-enable (directory package
)
2181 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2183 (let* ((dir (expand-file-name
2184 (read-directory-name
2186 (file-name-directory
2187 (or (buffer-file-name) default-directory
)))))
2188 (name (completing-read
2190 (python-util-list-packages
2191 dir python-shell--package-depth
))))
2193 (python-shell-send-string
2196 "import os.path;import sys;"
2197 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2198 "__package__ = '''%s''';"
2200 directory package package
)
2201 (python-shell-get-process)))
2203 (defun python-shell-accept-process-output (process &optional timeout regexp
)
2204 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2205 Optional argument TIMEOUT is the timeout argument to
2206 `accept-process-output' calls. Optional argument REGEXP
2207 overrides the regexp to match the end of output, defaults to
2208 `comint-prompt-regexp.'. Returns non-nil when output was
2211 This utility is useful in situations where the output may be
2212 received in chunks, since `accept-process-output' gives no
2213 guarantees they will be grabbed in a single call. An example use
2214 case for this would be the CPython shell start-up, where the
2215 banner and the initial prompt are received separately."
2216 (let ((regexp (or regexp comint-prompt-regexp
)))
2219 (when (not (accept-process-output process timeout
))
2221 (when (looking-back regexp
)
2222 (throw 'found t
))))))
2224 (defun python-shell-comint-end-of-output-p (output)
2225 "Return non-nil if OUTPUT is ends with input prompt."
2227 ;; XXX: It seems on OSX an extra carriage return is attached
2228 ;; at the end of output, this handles that too.
2231 ;; Remove initial caret from calculated regexp
2232 (replace-regexp-in-string
2233 (rx string-start ?^
) ""
2234 python-shell--prompt-calculated-input-regexp
)
2238 (define-obsolete-function-alias
2239 'python-comint-output-filter-function
2240 'ansi-color-filter-apply
2243 (defun python-comint-postoutput-scroll-to-bottom (output)
2244 "Faster version of `comint-postoutput-scroll-to-bottom'.
2245 Avoids `recenter' calls until OUTPUT is completely sent."
2246 (when (and (not (string= "" output
))
2247 (python-shell-comint-end-of-output-p
2248 (ansi-color-filter-apply output
)))
2249 (comint-postoutput-scroll-to-bottom output
))
2252 (defvar python-shell--parent-buffer nil
)
2254 (defmacro python-shell-with-shell-buffer
(&rest body
)
2255 "Execute the forms in BODY with the shell buffer temporarily current.
2256 Signals an error if no shell buffer is available for current buffer."
2257 (declare (indent 0) (debug t
))
2258 (let ((shell-buffer (make-symbol "shell-buffer")))
2259 `(let ((,shell-buffer
(python-shell-get-buffer)))
2260 (when (not ,shell-buffer
)
2261 (error "No inferior Python buffer available."))
2262 (with-current-buffer ,shell-buffer
2265 (defvar python-shell--font-lock-buffer nil
)
2267 (defun python-shell-font-lock-get-or-create-buffer ()
2268 "Get or create a font-lock buffer for current inferior process."
2269 (python-shell-with-shell-buffer
2270 (if python-shell--font-lock-buffer
2271 python-shell--font-lock-buffer
2273 (process-name (get-buffer-process (current-buffer)))))
2274 (generate-new-buffer
2275 (format "*%s-font-lock*" process-name
))))))
2277 (defun python-shell-font-lock-kill-buffer ()
2278 "Kill the font-lock buffer safely."
2279 (python-shell-with-shell-buffer
2280 (when (and python-shell--font-lock-buffer
2281 (buffer-live-p python-shell--font-lock-buffer
))
2282 (kill-buffer python-shell--font-lock-buffer
)
2283 (when (derived-mode-p 'inferior-python-mode
)
2284 (setq python-shell--font-lock-buffer nil
)))))
2286 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2287 "Execute the forms in BODY in the font-lock buffer.
2288 The value returned is the value of the last form in BODY. See
2289 also `with-current-buffer'."
2290 (declare (indent 0) (debug t
))
2291 `(python-shell-with-shell-buffer
2292 (save-current-buffer
2293 (when (not (and python-shell--font-lock-buffer
2294 (get-buffer python-shell--font-lock-buffer
)))
2295 (setq python-shell--font-lock-buffer
2296 (python-shell-font-lock-get-or-create-buffer)))
2297 (set-buffer python-shell--font-lock-buffer
)
2298 (set (make-local-variable 'delay-mode-hooks
) t
)
2299 (let ((python-indent-guess-indent-offset nil
))
2300 (when (not (derived-mode-p 'python-mode
))
2304 (defun python-shell-font-lock-cleanup-buffer ()
2305 "Cleanup the font-lock buffer.
2306 Provided as a command because this might be handy if something
2307 goes wrong and syntax highlighting in the shell gets messed up."
2309 (python-shell-with-shell-buffer
2310 (python-shell-font-lock-with-font-lock-buffer
2311 (delete-region (point-min) (point-max)))))
2313 (defun python-shell-font-lock-comint-output-filter-function (output)
2314 "Clean up the font-lock buffer after any OUTPUT."
2315 (when (and (not (string= "" output
))
2316 ;; Is end of output and is not just a prompt.
2318 (python-shell-comint-end-of-output-p
2319 (ansi-color-filter-apply output
))
2321 ;; If output is other than an input prompt then "real" output has
2322 ;; been received and the font-lock buffer must be cleaned up.
2323 (python-shell-font-lock-cleanup-buffer))
2326 (defun python-shell-font-lock-post-command-hook ()
2327 "Fontifies current line in shell buffer."
2328 (if (eq this-command
'comint-send-input
)
2329 ;; Add a newline when user sends input as this may be a block.
2330 (python-shell-font-lock-with-font-lock-buffer
2331 (goto-char (line-end-position))
2333 (when (and (python-util-comint-last-prompt)
2334 (> (point) (cdr (python-util-comint-last-prompt))))
2335 (let ((input (buffer-substring-no-properties
2336 (cdr (python-util-comint-last-prompt)) (point-max)))
2337 (old-input (python-shell-font-lock-with-font-lock-buffer
2338 (buffer-substring-no-properties
2339 (line-beginning-position) (point-max))))
2340 (current-point (point))
2341 (buffer-undo-list t
))
2342 ;; When input hasn't changed, do nothing.
2343 (when (not (string= input old-input
))
2344 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2346 (python-shell-font-lock-with-font-lock-buffer
2347 (delete-region (line-beginning-position)
2348 (line-end-position))
2350 ;; Ensure buffer is fontified, keeping it
2351 ;; compatible with Emacs < 24.4.
2352 (if (fboundp 'font-lock-ensure
)
2353 (funcall 'font-lock-ensure
)
2354 (font-lock-default-fontify-buffer))
2355 ;; Replace FACE text properties with FONT-LOCK-FACE so
2356 ;; they are not overwritten by comint buffer's font lock.
2357 (python-util-text-properties-replace-name
2358 'face
'font-lock-face
)
2359 (buffer-substring (line-beginning-position)
2360 (line-end-position))))
2361 (goto-char current-point
))))))
2363 (defun python-shell-font-lock-turn-on (&optional msg
)
2364 "Turn on shell font-lock.
2365 With argument MSG show activation message."
2367 (python-shell-with-shell-buffer
2368 (python-shell-font-lock-kill-buffer)
2369 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2370 (add-hook 'post-command-hook
2371 #'python-shell-font-lock-post-command-hook nil
'local
)
2372 (add-hook 'kill-buffer-hook
2373 #'python-shell-font-lock-kill-buffer nil
'local
)
2374 (add-hook 'comint-output-filter-functions
2375 #'python-shell-font-lock-comint-output-filter-function
2378 (message "Shell font-lock is enabled"))))
2380 (defun python-shell-font-lock-turn-off (&optional msg
)
2381 "Turn off shell font-lock.
2382 With argument MSG show deactivation message."
2384 (python-shell-with-shell-buffer
2385 (python-shell-font-lock-kill-buffer)
2386 (when (python-util-comint-last-prompt)
2387 ;; Cleanup current fontification
2388 (remove-text-properties
2389 (cdr (python-util-comint-last-prompt))
2391 '(face nil font-lock-face nil
)))
2392 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2393 (remove-hook 'post-command-hook
2394 #'python-shell-font-lock-post-command-hook
'local
)
2395 (remove-hook 'kill-buffer-hook
2396 #'python-shell-font-lock-kill-buffer
'local
)
2397 (remove-hook 'comint-output-filter-functions
2398 #'python-shell-font-lock-comint-output-filter-function
2401 (message "Shell font-lock is disabled"))))
2403 (defun python-shell-font-lock-toggle (&optional msg
)
2404 "Toggle font-lock for shell.
2405 With argument MSG show activation/deactivation message."
2407 (python-shell-with-shell-buffer
2408 (set (make-local-variable 'python-shell-font-lock-enable
)
2409 (not python-shell-font-lock-enable
))
2410 (if python-shell-font-lock-enable
2411 (python-shell-font-lock-turn-on msg
)
2412 (python-shell-font-lock-turn-off msg
))
2413 python-shell-font-lock-enable
))
2415 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2416 "Major mode for Python inferior process.
2417 Runs a Python interpreter as a subprocess of Emacs, with Python
2418 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2419 and `python-shell-interpreter-args' control which Python
2420 interpreter is run. Variables
2421 `python-shell-prompt-regexp',
2422 `python-shell-prompt-output-regexp',
2423 `python-shell-prompt-block-regexp',
2424 `python-shell-font-lock-enable',
2425 `python-shell-completion-setup-code',
2426 `python-shell-completion-string-code',
2427 `python-eldoc-setup-code', `python-eldoc-string-code',
2428 `python-ffap-setup-code' and `python-ffap-string-code' can
2429 customize this mode for different Python interpreters.
2431 This mode resets `comint-output-filter-functions' locally, so you
2432 may want to re-add custom functions to it using the
2433 `inferior-python-mode-hook'.
2435 You can also add additional setup code to be run at
2436 initialization of the interpreter via `python-shell-setup-codes'
2439 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2440 (let ((interpreter python-shell-interpreter
)
2441 (args python-shell-interpreter-args
))
2442 (when python-shell--parent-buffer
2443 (python-util-clone-local-variables python-shell--parent-buffer
))
2444 ;; Users can override default values for these vars when calling
2445 ;; `run-python'. This ensures new values let-bound in
2446 ;; `python-shell-make-comint' are locally set.
2447 (set (make-local-variable 'python-shell-interpreter
) interpreter
)
2448 (set (make-local-variable 'python-shell-interpreter-args
) args
))
2449 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2450 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2451 (python-shell-prompt-set-calculated-regexps)
2452 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
)
2453 (set (make-local-variable 'comint-prompt-read-only
) t
)
2454 (setq mode-line-process
'(":%s"))
2455 (set (make-local-variable 'comint-output-filter-functions
)
2456 '(ansi-color-process-output
2457 python-pdbtrack-comint-output-filter-function
2458 python-comint-postoutput-scroll-to-bottom
))
2459 (set (make-local-variable 'compilation-error-regexp-alist
)
2460 python-shell-compilation-regexp-alist
)
2461 (add-hook 'completion-at-point-functions
2462 #'python-shell-completion-at-point nil
'local
)
2463 (define-key inferior-python-mode-map
"\t"
2464 'python-shell-completion-complete-or-indent
)
2465 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2466 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2467 (make-local-variable 'python-shell-internal-last-output
)
2468 (when python-shell-font-lock-enable
2469 (python-shell-font-lock-turn-on))
2470 (compilation-shell-minor-mode 1)
2471 (python-shell-accept-process-output
2472 (get-buffer-process (current-buffer))))
2474 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
2475 "Create a Python shell comint buffer.
2476 CMD is the Python command to be executed and PROC-NAME is the
2477 process name the comint buffer will get. After the comint buffer
2478 is created the `inferior-python-mode' is activated. When
2479 optional argument POP is non-nil the buffer is shown. When
2480 optional argument INTERNAL is non-nil this process is run on a
2481 buffer with a name that starts with a space, following the Emacs
2482 convention for temporary/internal buffers, and also makes sure
2483 the user is not queried for confirmation when the process is
2486 (let* ((proc-buffer-name
2487 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
2488 (process-environment (python-shell-calculate-process-environment))
2489 (exec-path (python-shell-calculate-exec-path)))
2490 (when (not (comint-check-proc proc-buffer-name
))
2491 (let* ((cmdlist (split-string-and-unquote cmd
))
2492 (interpreter (car cmdlist
))
2493 (args (cdr cmdlist
))
2494 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2495 interpreter nil args
))
2496 (python-shell--parent-buffer (current-buffer))
2497 (process (get-buffer-process buffer
))
2498 ;; As the user may have overridden default values for
2499 ;; these vars on `run-python', let-binding them allows
2500 ;; to have the new right values in all setup code
2501 ;; that's is done in `inferior-python-mode', which is
2502 ;; important, especially for prompt detection.
2503 (python-shell-interpreter interpreter
)
2504 (python-shell-interpreter-args
2505 (mapconcat #'identity args
" ")))
2506 (with-current-buffer buffer
2507 (inferior-python-mode))
2508 (and pop
(pop-to-buffer buffer t
))
2509 (and internal
(set-process-query-on-exit-flag process nil
))))
2513 (defun run-python (&optional cmd dedicated show
)
2514 "Run an inferior Python process.
2515 Input and output via buffer named after
2516 `python-shell-buffer-name'. If there is a process already
2517 running in that buffer, just switch to it.
2519 Argument CMD defaults to `python-shell-calculate-command' return
2520 value. When called interactively with `prefix-arg', it allows
2521 the user to edit such value and choose whether the interpreter
2522 should be DEDICATED for the current buffer. When numeric prefix
2523 arg is other than 0 or 4 do not SHOW.
2525 Runs the hook `inferior-python-mode-hook' after
2526 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2527 process buffer for a list of commands.)"
2529 (if current-prefix-arg
2531 (read-shell-command "Run Python: " (python-shell-calculate-command))
2532 (y-or-n-p "Make dedicated process? ")
2533 (= (prefix-numeric-value current-prefix-arg
) 4))
2534 (list (python-shell-calculate-command) nil t
)))
2535 (python-shell-make-comint
2536 (or cmd
(python-shell-calculate-command))
2537 (python-shell-get-process-name dedicated
) show
)
2540 (defun run-python-internal ()
2541 "Run an inferior Internal Python process.
2542 Input and output via buffer named after
2543 `python-shell-internal-buffer-name' and what
2544 `python-shell-internal-get-process-name' returns.
2546 This new kind of shell is intended to be used for generic
2547 communication related to defined configurations; the main
2548 difference with global or dedicated shells is that these ones are
2549 attached to a configuration, not a buffer. This means that can
2550 be used for example to retrieve the sys.path and other stuff,
2551 without messing with user shells. Note that
2552 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2553 are set to nil for these shells, so setup codes are not sent at
2555 (let ((python-shell-font-lock-enable nil
)
2556 (inferior-python-mode-hook nil
))
2558 (python-shell-make-comint
2559 (python-shell-calculate-command)
2560 (python-shell-internal-get-process-name) nil t
))))
2562 (defun python-shell-get-buffer ()
2563 "Return inferior Python buffer for current buffer.
2564 If current buffer is in `inferior-python-mode', return it."
2565 (if (derived-mode-p 'inferior-python-mode
)
2567 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2568 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2569 (global-proc-name (python-shell-get-process-name nil
))
2570 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2571 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2572 (global-running (comint-check-proc global-proc-buffer-name
)))
2573 ;; Always prefer dedicated
2574 (or (and dedicated-running dedicated-proc-buffer-name
)
2575 (and global-running global-proc-buffer-name
)))))
2577 (defun python-shell-get-process ()
2578 "Return inferior Python process for current buffer."
2579 (get-buffer-process (python-shell-get-buffer)))
2581 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2582 "Get or create an inferior Python process for current buffer and return it.
2583 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2584 are used to start the shell. If those arguments are not
2585 provided, `run-python' is called interactively and the user will
2586 be asked for their values."
2587 (let ((shell-process (python-shell-get-process)))
2588 (when (not shell-process
)
2590 ;; XXX: Refactor code such that calling `run-python'
2591 ;; interactively is not needed anymore.
2592 (call-interactively 'run-python
)
2593 (run-python cmd dedicated show
)))
2594 (or shell-process
(python-shell-get-process))))
2596 (defvar python-shell-internal-buffer nil
2597 "Current internal shell buffer for the current buffer.
2598 This is really not necessary at all for the code to work but it's
2599 there for compatibility with CEDET.")
2601 (defvar python-shell-internal-last-output nil
2602 "Last output captured by the internal shell.
2603 This is really not necessary at all for the code to work but it's
2604 there for compatibility with CEDET.")
2606 (defun python-shell-internal-get-or-create-process ()
2607 "Get or create an inferior Internal Python process."
2608 (let ((proc-name (python-shell-internal-get-process-name)))
2609 (if (process-live-p proc-name
)
2610 (get-process proc-name
)
2611 (run-python-internal))))
2613 (define-obsolete-function-alias
2614 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2616 (define-obsolete-variable-alias
2617 'python-buffer
'python-shell-internal-buffer
"24.3")
2619 (define-obsolete-variable-alias
2620 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2622 (defun python-shell--save-temp-file (string)
2623 (let* ((temporary-file-directory
2624 (if (file-remote-p default-directory
)
2625 (concat (file-remote-p default-directory
) "/tmp")
2626 temporary-file-directory
))
2627 (temp-file-name (make-temp-file "py"))
2628 (coding-system-for-write (python-info-encoding)))
2629 (with-temp-file temp-file-name
2631 (delete-trailing-whitespace))
2634 (defun python-shell-send-string (string &optional process
)
2635 "Send STRING to inferior Python PROCESS."
2636 (interactive "sPython command: ")
2637 (let ((process (or process
(python-shell-get-or-create-process))))
2638 (if (string-match ".\n+." string
) ;Multiline.
2639 (let* ((temp-file-name (python-shell--save-temp-file string
))
2640 (file-name (or (buffer-file-name) temp-file-name
)))
2641 (python-shell-send-file file-name process temp-file-name t
))
2642 (comint-send-string process string
)
2643 (when (or (not (string-match "\n\\'" string
))
2644 (string-match "\n[ \t].*\n?\\'" string
))
2645 (comint-send-string process
"\n")))))
2647 (defvar python-shell-output-filter-in-progress nil
)
2648 (defvar python-shell-output-filter-buffer nil
)
2650 (defun python-shell-output-filter (string)
2651 "Filter used in `python-shell-send-string-no-output' to grab output.
2652 STRING is the output received to this point from the process.
2653 This filter saves received output from the process in
2654 `python-shell-output-filter-buffer' and stops receiving it after
2655 detecting a prompt at the end of the buffer."
2657 string
(ansi-color-filter-apply string
)
2658 python-shell-output-filter-buffer
2659 (concat python-shell-output-filter-buffer string
))
2660 (when (python-shell-comint-end-of-output-p
2661 python-shell-output-filter-buffer
)
2662 ;; Output ends when `python-shell-output-filter-buffer' contains
2663 ;; the prompt attached at the end of it.
2664 (setq python-shell-output-filter-in-progress nil
2665 python-shell-output-filter-buffer
2666 (substring python-shell-output-filter-buffer
2667 0 (match-beginning 0)))
2669 python-shell--prompt-calculated-output-regexp
2670 python-shell-output-filter-buffer
)
2671 ;; Some shells, like IPython might append a prompt before the
2672 ;; output, clean that.
2673 (setq python-shell-output-filter-buffer
2674 (substring python-shell-output-filter-buffer
(match-end 0)))))
2677 (defun python-shell-send-string-no-output (string &optional process
)
2678 "Send STRING to PROCESS and inhibit output.
2680 (let ((process (or process
(python-shell-get-or-create-process)))
2681 (comint-preoutput-filter-functions
2682 '(python-shell-output-filter))
2683 (python-shell-output-filter-in-progress t
)
2687 (python-shell-send-string string process
)
2688 (while python-shell-output-filter-in-progress
2689 ;; `python-shell-output-filter' takes care of setting
2690 ;; `python-shell-output-filter-in-progress' to NIL after it
2691 ;; detects end of output.
2692 (accept-process-output process
))
2694 python-shell-output-filter-buffer
2695 (setq python-shell-output-filter-buffer nil
)))
2696 (with-current-buffer (process-buffer process
)
2697 (comint-interrupt-subjob)))))
2699 (defun python-shell-internal-send-string (string)
2700 "Send STRING to the Internal Python interpreter.
2701 Returns the output. See `python-shell-send-string-no-output'."
2702 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2703 ;; updated to support this new mode.
2704 (setq python-shell-internal-last-output
2705 (python-shell-send-string-no-output
2706 ;; Makes this function compatible with the old
2707 ;; python-send-receive. (At least for CEDET).
2708 (replace-regexp-in-string "_emacs_out +" "" string
)
2709 (python-shell-internal-get-or-create-process))))
2711 (define-obsolete-function-alias
2712 'python-send-receive
'python-shell-internal-send-string
"24.3")
2714 (define-obsolete-function-alias
2715 'python-send-string
'python-shell-internal-send-string
"24.3")
2717 (defun python-shell-buffer-substring (start end
&optional nomain
)
2718 "Send buffer substring from START to END formatted for shell.
2719 This is a wrapper over `buffer-substring' that takes care of
2720 different transformations for the code sent to be evaluated in
2722 1. When optional argument NOMAIN is non-nil everything under an
2723 \"if __name__ == '__main__'\" block will be removed.
2724 2. When a subregion of the buffer is sent, it takes care of
2725 appending extra empty lines so tracebacks are correct.
2726 3. When the region sent is a substring of the current buffer, a
2727 coding cookie is added.
2728 4. Wraps indented regions under an \"if True:\" block so the
2729 interpreter evaluates them correctly."
2730 (let* ((substring (buffer-substring-no-properties start end
))
2731 (buffer-substring-p (save-restriction
2733 (not (equal (list (point-min) (point-max))
2734 (list start end
)))))
2735 (encoding (python-info-encoding))
2737 (when buffer-substring-p
2738 (format "# -*- coding: %s -*-\n" encoding
))
2740 (- (line-number-at-pos start
)
2741 (if buffer-substring-p
2 1)) ?
\n)))
2742 (toplevel-block-p (save-excursion
2744 (or (zerop (line-number-at-pos start
))
2746 (python-util-forward-comment 1)
2747 (zerop (current-indentation)))))))
2750 (if fillstr
(insert fillstr
))
2752 (goto-char (point-min))
2753 (when (not toplevel-block-p
)
2755 (delete-region (point) (line-end-position)))
2757 (let* ((if-name-main-start-end
2760 (when (python-nav-if-name-main)
2762 (progn (python-nav-forward-sexp-safe)
2763 ;; Include ending newline
2766 ;; Oh destructuring bind, how I miss you.
2767 (if-name-main-start (car if-name-main-start-end
))
2768 (if-name-main-end (cdr if-name-main-start-end
))
2769 (fillstr (make-string
2770 (- (line-number-at-pos if-name-main-end
)
2771 (line-number-at-pos if-name-main-start
)) ?
\n)))
2772 (when if-name-main-start-end
2773 (goto-char if-name-main-start
)
2774 (delete-region if-name-main-start if-name-main-end
)
2776 ;; Ensure there's only one coding cookie in the generated string.
2777 (goto-char (point-min))
2778 (when (looking-at-p (python-rx coding-cookie
))
2780 (when (looking-at-p (python-rx coding-cookie
))
2782 (line-beginning-position) (line-end-position))))
2783 (buffer-substring-no-properties (point-min) (point-max)))))
2785 (defun python-shell-send-region (start end
&optional send-main
)
2786 "Send the region delimited by START and END to inferior Python process.
2787 When optional argument SEND-MAIN is non-nil, allow execution of
2788 code inside blocks delimited by \"if __name__== '__main__':\".
2789 When called interactively SEND-MAIN defaults to nil, unless it's
2790 called with prefix argument."
2791 (interactive "r\nP")
2792 (let* ((string (python-shell-buffer-substring start end
(not send-main
)))
2793 (process (python-shell-get-or-create-process))
2794 (original-string (buffer-substring-no-properties start end
))
2795 (_ (string-match "\\`\n*\\(.*\\)" original-string
)))
2796 (message "Sent: %s..." (match-string 1 original-string
))
2797 (python-shell-send-string string process
)))
2799 (defun python-shell-send-buffer (&optional send-main
)
2800 "Send the entire buffer to inferior Python process.
2801 When optional argument SEND-MAIN is non-nil, allow execution of
2802 code inside blocks delimited by \"if __name__== '__main__':\".
2803 When called interactively SEND-MAIN defaults to nil, unless it's
2804 called with prefix argument."
2808 (python-shell-send-region (point-min) (point-max) send-main
)))
2810 (defun python-shell-send-defun (arg)
2811 "Send the current defun to inferior Python process.
2812 When argument ARG is non-nil do not include decorators."
2815 (python-shell-send-region
2818 (while (and (or (python-nav-beginning-of-defun)
2819 (beginning-of-line 1))
2820 (> (current-indentation) 0)))
2822 (while (and (forward-line -
1)
2823 (looking-at (python-rx decorator
))))
2827 (or (python-nav-end-of-defun)
2831 (defun python-shell-send-file (file-name &optional process temp-file-name
2833 "Send FILE-NAME to inferior Python PROCESS.
2834 If TEMP-FILE-NAME is passed then that file is used for processing
2835 instead, while internally the shell will continue to use
2836 FILE-NAME. If TEMP-FILE-NAME and DELETE are non-nil, then
2837 TEMP-FILE-NAME is deleted after evaluation is performed."
2838 (interactive "fFile to send: ")
2839 (let* ((process (or process
(python-shell-get-or-create-process)))
2840 (encoding (with-temp-buffer
2841 (insert-file-contents
2842 (or temp-file-name file-name
))
2843 (python-info-encoding)))
2844 (file-name (expand-file-name
2845 (or (file-remote-p file-name
'localname
)
2847 (temp-file-name (when temp-file-name
2849 (or (file-remote-p temp-file-name
'localname
)
2851 (python-shell-send-string
2854 "import codecs, os;"
2855 "__pyfile = codecs.open('''%s''', encoding='''%s''');"
2856 "__code = __pyfile.read().encode('''%s''');"
2858 (when (and delete temp-file-name
)
2859 (format "os.remove('''%s''');" temp-file-name
))
2860 "exec(compile(__code, '''%s''', 'exec'));")
2861 (or temp-file-name file-name
) encoding encoding file-name
)
2864 (defun python-shell-switch-to-shell ()
2865 "Switch to inferior Python process buffer."
2867 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2869 (defun python-shell-send-setup-code ()
2870 "Send all setup code for shell.
2871 This function takes the list of setup code to send from the
2872 `python-shell-setup-codes' list."
2873 (let ((process (python-shell-get-process))
2877 (cond ((stringp elt
) elt
)
2878 ((symbolp elt
) (symbol-value elt
))
2880 python-shell-setup-codes
2882 "\n\nprint ('python.el: sent setup code')")))
2883 (python-shell-send-string code process
)
2884 (python-shell-accept-process-output process
)))
2886 (add-hook 'inferior-python-mode-hook
2887 #'python-shell-send-setup-code
)
2890 ;;; Shell completion
2892 (defcustom python-shell-completion-setup-code
2897 import builtins as __builtin__
2899 import readline, rlcompleter
2901 def __PYTHON_EL_get_completions(text):
2904 def __PYTHON_EL_get_completions(text):
2905 builtins = dir(__builtin__)
2908 splits = text.split()
2909 is_module = splits and splits[0] in ('from', 'import')
2910 is_ipython = ('__IPYTHON__' in builtins or
2911 '__IPYTHON__active' in builtins)
2913 from IPython.core.completerlib import module_completion
2914 completions = module_completion(text.strip())
2915 elif is_ipython and '__IP' in builtins:
2916 completions = __IP.complete(text)
2917 elif is_ipython and 'get_ipython' in builtins:
2918 completions = get_ipython().Completer.all_completions(text)
2922 res = readline.get_completer()(text, i)
2926 completions.append(res)
2930 "Code used to setup completion in inferior Python processes."
2934 (defcustom python-shell-completion-string-code
2935 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2936 "Python code used to get a string of completions separated by semicolons.
2937 The string passed to the function is the current python name or
2938 the full statement in the case of imports."
2942 (define-obsolete-variable-alias
2943 'python-shell-completion-module-string-code
2944 'python-shell-completion-string-code
2946 "Completion string code must also autocomplete modules.")
2948 (define-obsolete-variable-alias
2949 'python-shell-completion-pdb-string-code
2950 'python-shell-completion-string-code
2952 "Completion string code must work for (i)pdb.")
2954 (defun python-shell-completion-get-completions (process import input
)
2955 "Do completion at point using PROCESS for IMPORT or INPUT.
2956 When IMPORT is non-nil takes precedence over INPUT for
2958 (with-current-buffer (process-buffer process
)
2960 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2961 (buffer-substring-no-properties
2962 (car prompt-boundaries
) (cdr prompt-boundaries
))))
2964 ;; Check whether a prompt matches a pdb string, an import
2965 ;; statement or just the standard prompt and use the
2966 ;; correct python-shell-completion-*-code string
2967 (cond ((and (string-match
2968 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2969 ;; Since there are no guarantees the user will remain
2970 ;; in the same context where completion code was sent
2971 ;; (e.g. user steps into a function), safeguard
2972 ;; resending completion setup continuously.
2973 (concat python-shell-completion-setup-code
2974 "\nprint (" python-shell-completion-string-code
")"))
2976 python-shell--prompt-calculated-input-regexp prompt
)
2977 python-shell-completion-string-code
)
2979 (subject (or import input
)))
2980 (and completion-code
2981 (> (length input
) 0)
2983 (python-util-strip-string
2984 (python-shell-send-string-no-output
2985 (format completion-code subject
) process
))))
2986 (and (> (length completions
) 2)
2987 (split-string completions
2988 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2990 (defun python-shell-completion-at-point (&optional process
)
2991 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2992 Optional argument PROCESS forces completions to be retrieved
2993 using that one instead of current buffer's process."
2994 (setq process
(or process
(get-buffer-process (current-buffer))))
2995 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2997 (when (string-match-p
2998 (rx (* space
) word-start
(or "from" "import") word-end space
)
2999 (buffer-substring-no-properties last-prompt-end
(point)))
3000 (buffer-substring-no-properties last-prompt-end
(point))))
3003 (if (not (re-search-backward
3005 (or whitespace open-paren close-paren string-delimiter
))
3009 (forward-char (length (match-string-no-properties 0)))
3013 (completion-table-dynamic
3015 #'python-shell-completion-get-completions
3016 process import-statement
)))))
3018 (define-obsolete-function-alias
3019 'python-shell-completion-complete-at-point
3020 'python-shell-completion-at-point
3023 (defun python-shell-completion-complete-or-indent ()
3024 "Complete or indent depending on the context.
3025 If content before pointer is all whitespace, indent.
3026 If not try to complete."
3028 (if (string-match "^[[:space:]]*$"
3029 (buffer-substring (comint-line-beginning-position)
3031 (indent-for-tab-command)
3032 (completion-at-point)))
3035 ;;; PDB Track integration
3037 (defcustom python-pdbtrack-activate t
3038 "Non-nil makes Python shell enable pdbtracking."
3043 (defcustom python-pdbtrack-stacktrace-info-regexp
3044 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3045 "Regular expression matching stacktrace information.
3046 Used to extract the current line and module being inspected."
3051 (defvar python-pdbtrack-tracked-buffer nil
3052 "Variable containing the value of the current tracked buffer.
3053 Never set this variable directly, use
3054 `python-pdbtrack-set-tracked-buffer' instead.")
3056 (defvar python-pdbtrack-buffers-to-kill nil
3057 "List of buffers to be deleted after tracking finishes.")
3059 (defun python-pdbtrack-set-tracked-buffer (file-name)
3060 "Set the buffer for FILE-NAME as the tracked buffer.
3061 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3062 Returns the tracked buffer."
3063 (let ((file-buffer (get-file-buffer
3064 (concat (file-remote-p default-directory
)
3067 (setq python-pdbtrack-tracked-buffer file-buffer
)
3068 (setq file-buffer
(find-file-noselect file-name
))
3069 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3070 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3073 (defun python-pdbtrack-comint-output-filter-function (output)
3074 "Move overlay arrow to current pdb line in tracked buffer.
3075 Argument OUTPUT is a string with the output from the comint process."
3076 (when (and python-pdbtrack-activate
(not (string= output
"")))
3077 (let* ((full-output (ansi-color-filter-apply
3078 (buffer-substring comint-last-input-end
(point-max))))
3082 (insert full-output
)
3083 ;; When the debugger encounters a pdb.set_trace()
3084 ;; command, it prints a single stack frame. Sometimes
3085 ;; it prints a bit of extra information about the
3086 ;; arguments of the present function. When ipdb
3087 ;; encounters an exception, it prints the _entire_ stack
3088 ;; trace. To handle all of these cases, we want to find
3089 ;; the _last_ stack frame printed in the most recent
3090 ;; batch of output, then jump to the corresponding
3091 ;; file/line number.
3092 (goto-char (point-max))
3093 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3094 (setq line-number
(string-to-number
3095 (match-string-no-properties 2)))
3096 (match-string-no-properties 1)))))
3097 (if (and file-name line-number
)
3098 (let* ((tracked-buffer
3099 (python-pdbtrack-set-tracked-buffer file-name
))
3100 (shell-buffer (current-buffer))
3101 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3102 (tracked-buffer-line-pos))
3103 (with-current-buffer tracked-buffer
3104 (set (make-local-variable 'overlay-arrow-string
) "=>")
3105 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3106 (setq tracked-buffer-line-pos
(progn
3107 (goto-char (point-min))
3108 (forward-line (1- line-number
))
3110 (when tracked-buffer-window
3112 tracked-buffer-window tracked-buffer-line-pos
))
3113 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3114 (pop-to-buffer tracked-buffer
)
3115 (switch-to-buffer-other-window shell-buffer
))
3116 (when python-pdbtrack-tracked-buffer
3117 (with-current-buffer python-pdbtrack-tracked-buffer
3118 (set-marker overlay-arrow-position nil
))
3119 (mapc #'(lambda (buffer)
3120 (ignore-errors (kill-buffer buffer
)))
3121 python-pdbtrack-buffers-to-kill
)
3122 (setq python-pdbtrack-tracked-buffer nil
3123 python-pdbtrack-buffers-to-kill nil
)))))
3127 ;;; Symbol completion
3129 (defun python-completion-at-point ()
3130 "Function for `completion-at-point-functions' in `python-mode'.
3131 For this to work as best as possible you should call
3132 `python-shell-send-buffer' from time to time so context in
3133 inferior Python process is updated properly."
3134 (let ((process (python-shell-get-process)))
3136 (python-shell-completion-at-point process
))))
3138 (define-obsolete-function-alias
3139 'python-completion-complete-at-point
3140 'python-completion-at-point
3146 (defcustom python-fill-comment-function
'python-fill-comment
3147 "Function to fill comments.
3148 This is the function used by `python-fill-paragraph' to
3153 (defcustom python-fill-string-function
'python-fill-string
3154 "Function to fill strings.
3155 This is the function used by `python-fill-paragraph' to
3160 (defcustom python-fill-decorator-function
'python-fill-decorator
3161 "Function to fill decorators.
3162 This is the function used by `python-fill-paragraph' to
3167 (defcustom python-fill-paren-function
'python-fill-paren
3168 "Function to fill parens.
3169 This is the function used by `python-fill-paragraph' to
3174 (defcustom python-fill-docstring-style
'pep-257
3175 "Style used to fill docstrings.
3176 This affects `python-fill-string' behavior with regards to
3177 triple quotes positioning.
3179 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3180 `symmetric', and nil. A value of nil won't care about quotes
3181 position and will treat docstrings a normal string, any other
3182 value may result in one of the following docstring styles:
3187 Process foo, return bar.
3191 Process foo, return bar.
3193 If processing fails throw ProcessingError.
3198 \"\"\"Process foo, return bar.\"\"\"
3201 Process foo, return bar.
3203 If processing fails throw ProcessingError.
3209 \"\"\"Process foo, return bar.\"\"\"
3211 \"\"\"Process foo, return bar.
3213 If processing fails throw ProcessingError.
3219 \"\"\"Process foo, return bar.\"\"\"
3221 \"\"\"Process foo, return bar.
3223 If processing fails throw ProcessingError.
3228 \"\"\"Process foo, return bar.\"\"\"
3231 Process foo, return bar.
3233 If processing fails throw ProcessingError.
3236 (const :tag
"Don't format docstrings" nil
)
3237 (const :tag
"Django's coding standards style." django
)
3238 (const :tag
"One newline and start and Two at end style." onetwo
)
3239 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3240 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3241 (const :tag
"Symmetric style." symmetric
))
3244 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3246 (defun python-fill-paragraph (&optional justify
)
3247 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3248 If any of the current line is in or at the end of a multi-line string,
3249 fill the string or the paragraph of it that point is in, preserving
3250 the string's indentation.
3251 Optional argument JUSTIFY defines if the paragraph should be justified."
3256 ((python-syntax-context 'comment
)
3257 (funcall python-fill-comment-function justify
))
3258 ;; Strings/Docstrings
3259 ((save-excursion (or (python-syntax-context 'string
)
3260 (equal (string-to-syntax "|")
3261 (syntax-after (point)))))
3262 (funcall python-fill-string-function justify
))
3264 ((equal (char-after (save-excursion
3265 (python-nav-beginning-of-statement))) ?
@)
3266 (funcall python-fill-decorator-function justify
))
3268 ((or (python-syntax-context 'paren
)
3269 (looking-at (python-rx open-paren
))
3271 (skip-syntax-forward "^(" (line-end-position))
3272 (looking-at (python-rx open-paren
))))
3273 (funcall python-fill-paren-function justify
))
3276 (defun python-fill-comment (&optional justify
)
3277 "Comment fill function for `python-fill-paragraph'.
3278 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3279 (fill-comment-paragraph justify
))
3281 (defun python-fill-string (&optional justify
)
3282 "String fill function for `python-fill-paragraph'.
3283 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3284 (let* ((str-start-pos
3287 (or (python-syntax-context 'string
)
3288 (and (equal (string-to-syntax "|")
3289 (syntax-after (point)))
3291 (num-quotes (python-syntax-count-quotes
3292 (char-after str-start-pos
) str-start-pos
))
3295 (goto-char (+ str-start-pos num-quotes
))
3296 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3297 (goto-char (point-max)))
3300 ;; Docstring styles may vary for oneliners and multi-liners.
3301 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3303 (pcase python-fill-docstring-style
3304 ;; delimiters-style is a cons cell with the form
3305 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3306 ;; is NIL means to not add any newlines for start or end
3307 ;; of docstring. See `python-fill-docstring-style' for a
3308 ;; graphic idea of each style.
3309 (`django
(cons 1 1))
3310 (`onetwo
(and multi-line-p
(cons 1 2)))
3311 (`pep-257
(and multi-line-p
(cons nil
2)))
3312 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3313 (`symmetric
(and multi-line-p
(cons 1 1)))))
3314 (docstring-p (save-excursion
3315 ;; Consider docstrings those strings which
3316 ;; start on a line by themselves.
3317 (python-nav-beginning-of-statement)
3318 (and (= (point) str-start-pos
))))
3319 (fill-paragraph-function))
3321 (narrow-to-region str-start-pos str-end-pos
)
3322 (fill-paragraph justify
))
3324 (when (and docstring-p python-fill-docstring-style
)
3325 ;; Add the number of newlines indicated by the selected style
3326 ;; at the start of the docstring.
3327 (goto-char (+ str-start-pos num-quotes
))
3328 (delete-region (point) (progn
3329 (skip-syntax-forward "> ")
3331 (and (car delimiters-style
)
3332 (or (newline (car delimiters-style
)) t
)
3333 ;; Indent only if a newline is added.
3334 (indent-according-to-mode))
3335 ;; Add the number of newlines indicated by the selected style
3336 ;; at the end of the docstring.
3337 (goto-char (if (not (= str-end-pos
(point-max)))
3338 (- str-end-pos num-quotes
)
3340 (delete-region (point) (progn
3341 (skip-syntax-backward "> ")
3343 (and (cdr delimiters-style
)
3344 ;; Add newlines only if string ends.
3345 (not (= str-end-pos
(point-max)))
3346 (or (newline (cdr delimiters-style
)) t
)
3347 ;; Again indent only if a newline is added.
3348 (indent-according-to-mode))))) t
)
3350 (defun python-fill-decorator (&optional _justify
)
3351 "Decorator fill function for `python-fill-paragraph'.
3352 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3355 (defun python-fill-paren (&optional justify
)
3356 "Paren fill function for `python-fill-paragraph'.
3357 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3359 (narrow-to-region (progn
3360 (while (python-syntax-context 'paren
)
3361 (goto-char (1- (point))))
3362 (line-beginning-position))
3364 (when (not (python-syntax-context 'paren
))
3366 (when (not (python-syntax-context 'paren
))
3367 (skip-syntax-backward "^)")))
3368 (while (and (python-syntax-context 'paren
)
3370 (goto-char (1+ (point))))
3372 (let ((paragraph-start "\f\\|[ \t]*$")
3373 (paragraph-separate ",")
3374 (fill-paragraph-function))
3375 (goto-char (point-min))
3376 (fill-paragraph justify
))
3379 (python-indent-line)
3380 (goto-char (line-end-position))))
3386 (defcustom python-skeleton-autoinsert nil
3387 "Non-nil means template skeletons will be automagically inserted.
3388 This happens when pressing \"if<SPACE>\", for example, to prompt for
3394 (define-obsolete-variable-alias
3395 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3397 (defvar python-skeleton-available
'()
3398 "Internal list of available skeletons.")
3400 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3401 "Abbrev table for Python mode skeletons."
3403 ;; Allow / inside abbrevs.
3404 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3405 ;; Only expand in code.
3406 :enable-function
(lambda ()
3408 (not (python-syntax-comment-or-string-p))
3409 python-skeleton-autoinsert
)))
3411 (defmacro python-skeleton-define
(name doc
&rest skel
)
3412 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3413 The skeleton will be bound to python-skeleton-NAME and will
3414 be added to `python-mode-skeleton-abbrev-table'."
3415 (declare (indent 2))
3416 (let* ((name (symbol-name name
))
3417 (function-name (intern (concat "python-skeleton-" name
))))
3419 (define-abbrev python-mode-skeleton-abbrev-table
3420 ,name
"" ',function-name
:system t
)
3421 (setq python-skeleton-available
3422 (cons ',function-name python-skeleton-available
))
3423 (define-skeleton ,function-name
3425 (format "Insert %s statement." name
))
3428 (define-abbrev-table 'python-mode-abbrev-table
()
3429 "Abbrev table for Python mode."
3430 :parents
(list python-mode-skeleton-abbrev-table
))
3432 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3433 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3434 The skeleton will be bound to python-skeleton-NAME."
3435 (declare (indent 2))
3436 (let* ((name (symbol-name name
))
3437 (function-name (intern (concat "python-skeleton--" name
)))
3439 "Add '%s' clause? " name
)))
3442 `(< ,(format "%s:" name
) \n \n
3444 `(define-skeleton ,function-name
3446 (format "Auxiliary skeleton for %s statement." name
))
3448 (unless (y-or-n-p ,msg
)
3452 (python-define-auxiliary-skeleton else nil
)
3454 (python-define-auxiliary-skeleton except nil
)
3456 (python-define-auxiliary-skeleton finally nil
)
3458 (python-skeleton-define if nil
3462 ("other condition, %s: "
3466 '(python-skeleton--else) | ^
)
3468 (python-skeleton-define while nil
3472 '(python-skeleton--else) | ^
)
3474 (python-skeleton-define for nil
3478 '(python-skeleton--else) | ^
)
3480 (python-skeleton-define import nil
3481 "Import from module: "
3482 "from " str
& " " | -
5
3484 ("Identifier: " str
", ") -
2 \n _
)
3486 (python-skeleton-define try nil
3492 "except " str
":" \n
3495 '(python-skeleton--except)
3496 '(python-skeleton--else)
3497 '(python-skeleton--finally) | ^
)
3499 (python-skeleton-define def nil
3501 "def " str
"(" ("Parameter, %s: "
3502 (unless (equal ?\
( (char-before)) ", ")
3504 "\"\"\"" -
"\"\"\"" \n
3507 (python-skeleton-define class nil
3509 "class " str
"(" ("Inheritance, %s: "
3510 (unless (equal ?\
( (char-before)) ", ")
3514 "\"\"\"" -
"\"\"\"" \n
3517 (defun python-skeleton-add-menu-items ()
3518 "Add menu items to Python->Skeletons menu."
3519 (let ((skeletons (sort python-skeleton-available
'string
<)))
3520 (dolist (skeleton skeletons
)
3522 nil
'("Python" "Skeletons")
3524 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3529 (defcustom python-ffap-setup-code
3530 "def __FFAP_get_module_path(module):
3533 path = __import__(module).__file__
3534 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3539 "Python code to get a module path."
3543 (defcustom python-ffap-string-code
3544 "__FFAP_get_module_path('''%s''')\n"
3545 "Python code used to get a string with the path of a module."
3549 (defun python-ffap-module-path (module)
3550 "Function for `ffap-alist' to return path for MODULE."
3552 (and (derived-mode-p 'inferior-python-mode
)
3553 (get-buffer-process (current-buffer)))
3554 (python-shell-get-process))))
3558 (python-shell-send-string-no-output
3559 (format python-ffap-string-code module
) process
)))
3561 (substring-no-properties module-file
1 -
1))))))
3565 (eval-after-load "ffap"
3567 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3568 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3573 (defcustom python-check-command
3575 "Command used to check a Python file."
3579 (defcustom python-check-buffer-name
3580 "*Python check: %s*"
3581 "Buffer name used for check commands."
3585 (defvar python-check-custom-command nil
3588 (defun python-check (command)
3589 "Check a Python file (default current buffer's file).
3590 Runs COMMAND, a shell command, as if by `compile'.
3591 See `python-check-command' for the default."
3593 (list (read-string "Check command: "
3594 (or python-check-custom-command
3595 (concat python-check-command
" "
3596 (shell-quote-argument
3598 (let ((name (buffer-file-name)))
3600 (file-name-nondirectory name
)))
3602 (setq python-check-custom-command command
)
3603 (save-some-buffers (not compilation-ask-about-save
) nil
)
3604 (let ((process-environment (python-shell-calculate-process-environment))
3605 (exec-path (python-shell-calculate-exec-path)))
3606 (compilation-start command nil
3608 (format python-check-buffer-name command
)))))
3613 (defcustom python-eldoc-setup-code
3614 "def __PYDOC_get_help(obj):
3618 str_type = basestring
3621 if isinstance(obj, str_type):
3622 obj = eval(obj, globals())
3623 doc = inspect.getdoc(obj)
3624 if not doc and callable(obj):
3626 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3627 target = obj.__init__
3633 args = inspect.formatargspec(
3634 *inspect.getargspec(target)
3637 doc = '{objtype} {name}{args}'.format(
3638 objtype=objtype, name=name, args=args
3641 doc = doc.splitlines()[0]
3645 "Python code to setup documentation retrieval."
3649 (defcustom python-eldoc-string-code
3650 "__PYDOC_get_help('''%s''')\n"
3651 "Python code used to get a string with the documentation of an object."
3655 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
3656 "Internal implementation to get documentation at point.
3657 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3658 returns will be used. If not FORCE-PROCESS is passed what
3659 `python-shell-get-process' returns is used."
3660 (let ((process (or force-process
(python-shell-get-process))))
3662 (let ((input (or force-input
3663 (python-info-current-symbol t
))))
3665 ;; Prevent resizing the echo area when iPython is
3666 ;; enabled. Bug#18794.
3667 (python-util-strip-string
3668 (python-shell-send-string-no-output
3669 (format python-eldoc-string-code input
)
3672 (defun python-eldoc-function ()
3673 "`eldoc-documentation-function' for Python.
3674 For this to work as best as possible you should call
3675 `python-shell-send-buffer' from time to time so context in
3676 inferior Python process is updated properly."
3677 (python-eldoc--get-doc-at-point))
3679 (defun python-eldoc-at-point (symbol)
3680 "Get help on SYMBOL using `help'.
3681 Interactively, prompt for symbol."
3683 (let ((symbol (python-info-current-symbol t
))
3684 (enable-recursive-minibuffers t
))
3685 (list (read-string (if symbol
3686 (format "Describe symbol (default %s): " symbol
)
3687 "Describe symbol: ")
3689 (message (python-eldoc--get-doc-at-point symbol
)))
3694 (defvar python-imenu-format-item-label-function
3695 'python-imenu-format-item-label
3696 "Imenu function used to format an item label.
3697 It must be a function with two arguments: TYPE and NAME.")
3699 (defvar python-imenu-format-parent-item-label-function
3700 'python-imenu-format-parent-item-label
3701 "Imenu function used to format a parent item label.
3702 It must be a function with two arguments: TYPE and NAME.")
3704 (defvar python-imenu-format-parent-item-jump-label-function
3705 'python-imenu-format-parent-item-jump-label
3706 "Imenu function used to format a parent jump item label.
3707 It must be a function with two arguments: TYPE and NAME.")
3709 (defun python-imenu-format-item-label (type name
)
3710 "Return Imenu label for single node using TYPE and NAME."
3711 (format "%s (%s)" name type
))
3713 (defun python-imenu-format-parent-item-label (type name
)
3714 "Return Imenu label for parent node using TYPE and NAME."
3715 (format "%s..." (python-imenu-format-item-label type name
)))
3717 (defun python-imenu-format-parent-item-jump-label (type _name
)
3718 "Return Imenu label for parent node jump using TYPE and NAME."
3719 (if (string= type
"class")
3720 "*class definition*"
3721 "*function definition*"))
3723 (defun python-imenu--put-parent (type name pos tree
)
3724 "Add the parent with TYPE, NAME and POS to TREE."
3726 (funcall python-imenu-format-item-label-function type name
))
3728 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
3731 (cons label
(cons (cons jump-label pos
) tree
)))))
3733 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
3734 "Recursively build the tree of nested definitions of a node.
3735 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3736 not be passed explicitly unless you know what you are doing."
3737 (setq min-indent
(or min-indent
0)
3738 prev-indent
(or prev-indent python-indent-offset
))
3739 (let* ((pos (python-nav-backward-defun))
3741 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
3742 (let ((split (split-string (match-string-no-properties 0))))
3743 (setq type
(car split
))
3746 (funcall python-imenu-format-item-label-function type name
)))
3747 (indent (current-indentation))
3748 (children-indent-limit (+ python-indent-offset min-indent
)))
3750 ;; Nothing found, probably near to bobp.
3752 ((<= indent min-indent
)
3753 ;; The current indentation points that this is a parent
3754 ;; node, add it to the tree and stop recursing.
3755 (python-imenu--put-parent type name pos tree
))
3757 (python-imenu--build-tree
3760 (if (<= indent children-indent-limit
)
3761 ;; This lies within the children indent offset range,
3762 ;; so it's a normal child of its parent (i.e., not
3763 ;; a child of a child).
3764 (cons (cons label pos
) tree
)
3765 ;; Oh no, a child of a child?! Fear not, we
3766 ;; know how to roll. We recursively parse these by
3767 ;; swapping prev-indent and min-indent plus adding this
3768 ;; newly found item to a fresh subtree. This works, I
3771 (python-imenu--build-tree
3772 prev-indent indent
(list (cons label pos
)))
3775 (defun python-imenu-create-index ()
3776 "Return tree Imenu alist for the current Python buffer.
3777 Change `python-imenu-format-item-label-function',
3778 `python-imenu-format-parent-item-label-function',
3779 `python-imenu-format-parent-item-jump-label-function' to
3780 customize how labels are formatted."
3781 (goto-char (point-max))
3784 (while (setq tree
(python-imenu--build-tree))
3785 (setq index
(cons tree index
)))
3788 (defun python-imenu-create-flat-index (&optional alist prefix
)
3789 "Return flat outline of the current Python buffer for Imenu.
3790 Optional argument ALIST is the tree to be flattened; when nil
3791 `python-imenu-build-index' is used with
3792 `python-imenu-format-parent-item-jump-label-function'
3793 `python-imenu-format-parent-item-label-function'
3794 `python-imenu-format-item-label-function' set to
3795 (lambda (type name) name)
3796 Optional argument PREFIX is used in recursive calls and should
3797 not be passed explicitly.
3804 (\"decorator\" . 173)
3807 (\"wrapped_f\" . 393))))
3813 (\"decorator\" . 173)
3814 (\"decorator.wrap\" . 353)
3815 (\"decorator.wrapped_f\" . 393))"
3816 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3821 (let ((name (if prefix
3822 (concat prefix
"." (car item
))
3825 (cond ((or (numberp pos
) (markerp pos
))
3826 (list (cons name pos
)))
3829 (cons name
(cdar pos
))
3830 (python-imenu-create-flat-index (cddr item
) name
))))))
3832 (let* ((fn (lambda (_type name
) name
))
3833 (python-imenu-format-item-label-function fn
)
3834 (python-imenu-format-parent-item-label-function fn
)
3835 (python-imenu-format-parent-item-jump-label-function fn
))
3836 (python-imenu-create-index))))))
3841 (defun python-info-current-defun (&optional include-type
)
3842 "Return name of surrounding function with Python compatible dotty syntax.
3843 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3844 This function can be used as the value of `add-log-current-defun-function'
3845 since it returns nil if point is not inside a defun."
3851 (starting-indentation (current-indentation))
3852 (starting-pos (point))
3857 (while (python-nav-beginning-of-defun 1)
3858 (when (save-match-data
3860 (or (not last-indent
)
3861 (< (current-indentation) last-indent
))
3865 ;; If this is the first run, we may add
3866 ;; the current defun at point.
3867 (setq first-run nil
)
3868 (goto-char starting-pos
)
3869 (python-nav-beginning-of-statement)
3870 (beginning-of-line 1)
3872 python-nav-beginning-of-defun-regexp
)))
3876 (+ (current-indentation)
3877 python-indent-offset
)))
3878 (if (< starting-indentation min-indent
)
3879 ;; If the starting indentation is not
3880 ;; within the min defun indent make the
3883 ;; Else go to the end of defun and add
3884 ;; up the current indentation to the
3886 (python-nav-end-of-defun)
3888 (if (>= (current-indentation) min-indent
)
3889 (1+ (current-indentation))
3891 (save-match-data (setq last-indent
(current-indentation)))
3892 (if (or (not include-type
) type
)
3893 (setq names
(cons (match-string-no-properties 1) names
))
3894 (let ((match (split-string (match-string-no-properties 0))))
3895 (setq type
(car match
))
3896 (setq names
(cons (cadr match
) names
)))))
3897 ;; Stop searching ASAP.
3898 (and (= (current-indentation) 0) (throw 'exit t
))))
3900 (concat (and type
(format "%s " type
))
3901 (mapconcat 'identity names
".")))))))
3903 (defun python-info-current-symbol (&optional replace-self
)
3904 "Return current symbol using dotty syntax.
3905 With optional argument REPLACE-SELF convert \"self\" to current
3908 (and (not (python-syntax-comment-or-string-p))
3909 (with-syntax-table python-dotty-syntax-table
3910 (let ((sym (symbol-at-point)))
3912 (substring-no-properties (symbol-name sym
))))))))
3914 (if (not replace-self
)
3916 (let ((current-defun (python-info-current-defun)))
3917 (if (not current-defun
)
3919 (replace-regexp-in-string
3920 (python-rx line-start word-start
"self" word-end ?.
)
3922 (mapconcat 'identity
3923 (butlast (split-string current-defun
"\\."))
3927 (defun python-info-statement-starts-block-p ()
3928 "Return non-nil if current statement opens a block."
3930 (python-nav-beginning-of-statement)
3931 (looking-at (python-rx block-start
))))
3933 (defun python-info-statement-ends-block-p ()
3934 "Return non-nil if point is at end of block."
3935 (let ((end-of-block-pos (save-excursion
3936 (python-nav-end-of-block)))
3937 (end-of-statement-pos (save-excursion
3938 (python-nav-end-of-statement))))
3939 (and end-of-block-pos end-of-statement-pos
3940 (= end-of-block-pos end-of-statement-pos
))))
3942 (defun python-info-beginning-of-statement-p ()
3943 "Return non-nil if point is at beginning of statement."
3944 (= (point) (save-excursion
3945 (python-nav-beginning-of-statement)
3948 (defun python-info-end-of-statement-p ()
3949 "Return non-nil if point is at end of statement."
3950 (= (point) (save-excursion
3951 (python-nav-end-of-statement)
3954 (defun python-info-beginning-of-block-p ()
3955 "Return non-nil if point is at beginning of block."
3956 (and (python-info-beginning-of-statement-p)
3957 (python-info-statement-starts-block-p)))
3959 (defun python-info-end-of-block-p ()
3960 "Return non-nil if point is at end of block."
3961 (and (python-info-end-of-statement-p)
3962 (python-info-statement-ends-block-p)))
3964 (define-obsolete-function-alias
3965 'python-info-closing-block
3966 'python-info-dedenter-opening-block-position
"24.4")
3968 (defun python-info-dedenter-opening-block-position ()
3969 "Return the point of the closest block the current line closes.
3970 Returns nil if point is not on a dedenter statement or no opening
3971 block can be detected. The latter case meaning current file is
3972 likely an invalid python file."
3973 (let ((positions (python-info-dedenter-opening-block-positions))
3974 (indentation (current-indentation))
3976 (while (and (not position
)
3979 (goto-char (car positions
))
3980 (if (<= (current-indentation) indentation
)
3981 (setq position
(car positions
))
3982 (setq positions
(cdr positions
)))))
3985 (defun python-info-dedenter-opening-block-positions ()
3986 "Return points of blocks the current line may close sorted by closer.
3987 Returns nil if point is not on a dedenter statement or no opening
3988 block can be detected. The latter case meaning current file is
3989 likely an invalid python file."
3991 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3993 (goto-char dedenter-pos
)
3994 (let* ((pairs '(("elif" "elif" "if")
3995 ("else" "if" "elif" "except" "for" "while")
3996 ("except" "except" "try")
3997 ("finally" "else" "except" "try")))
3998 (dedenter (match-string-no-properties 0))
3999 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
4000 (collected-indentations)
4003 (while (python-nav--syntactically
4005 (re-search-backward (python-rx block-start
) nil t
))
4007 (let ((indentation (current-indentation)))
4008 (when (and (not (memq indentation collected-indentations
))
4009 (or (not collected-indentations
)
4010 (< indentation
(apply #'min collected-indentations
))))
4011 (setq collected-indentations
4012 (cons indentation collected-indentations
))
4013 (when (member (match-string-no-properties 0)
4014 possible-opening-blocks
)
4015 (setq opening-blocks
(cons (point) opening-blocks
))))
4016 (when (zerop indentation
)
4017 (throw 'exit nil
)))))
4019 (nreverse opening-blocks
))))))
4021 (define-obsolete-function-alias
4022 'python-info-closing-block-message
4023 'python-info-dedenter-opening-block-message
"24.4")
4025 (defun python-info-dedenter-opening-block-message ()
4026 "Message the first line of the block the current statement closes."
4027 (let ((point (python-info-dedenter-opening-block-position)))
4031 (message "Closes %s" (save-excursion
4034 (point) (line-end-position))))))))
4036 (defun python-info-dedenter-statement-p ()
4037 "Return point if current statement is a dedenter.
4038 Sets `match-data' to the keyword that starts the dedenter
4041 (python-nav-beginning-of-statement)
4042 (when (and (not (python-syntax-context-type))
4043 (looking-at (python-rx dedenter
)))
4046 (defun python-info-line-ends-backslash-p (&optional line-number
)
4047 "Return non-nil if current line ends with backslash.
4048 With optional argument LINE-NUMBER, check that line instead."
4053 (python-util-goto-line line-number
))
4054 (while (and (not (eobp))
4055 (goto-char (line-end-position))
4056 (python-syntax-context 'paren
)
4057 (not (equal (char-before (point)) ?
\\)))
4059 (when (equal (char-before) ?
\\)
4062 (defun python-info-beginning-of-backslash (&optional line-number
)
4063 "Return the point where the backslashed line start.
4064 Optional argument LINE-NUMBER forces the line number to check against."
4069 (python-util-goto-line line-number
))
4070 (when (python-info-line-ends-backslash-p)
4071 (while (save-excursion
4072 (goto-char (line-beginning-position))
4073 (python-syntax-context 'paren
))
4075 (back-to-indentation)
4078 (defun python-info-continuation-line-p ()
4079 "Check if current line is continuation of another.
4080 When current line is continuation of another return the point
4081 where the continued line ends."
4085 (let* ((context-type (progn
4086 (back-to-indentation)
4087 (python-syntax-context-type)))
4088 (line-start (line-number-at-pos))
4089 (context-start (when context-type
4090 (python-syntax-context context-type
))))
4091 (cond ((equal context-type
'paren
)
4092 ;; Lines inside a paren are always a continuation line
4093 ;; (except the first one).
4094 (python-util-forward-comment -
1)
4096 ((member context-type
'(string comment
))
4097 ;; move forward an roll again
4098 (goto-char context-start
)
4099 (python-util-forward-comment)
4100 (python-info-continuation-line-p))
4102 ;; Not within a paren, string or comment, the only way
4103 ;; we are dealing with a continuation line is that
4104 ;; previous line contains a backslash, and this can
4105 ;; only be the previous line from current
4106 (back-to-indentation)
4107 (python-util-forward-comment -
1)
4108 (when (and (equal (1- line-start
) (line-number-at-pos))
4109 (python-info-line-ends-backslash-p))
4110 (point-marker))))))))
4112 (defun python-info-block-continuation-line-p ()
4113 "Return non-nil if current line is a continuation of a block."
4115 (when (python-info-continuation-line-p)
4117 (back-to-indentation)
4118 (when (looking-at (python-rx block-start
))
4121 (defun python-info-assignment-continuation-line-p ()
4122 "Check if current line is a continuation of an assignment.
4123 When current line is continuation of another with an assignment
4124 return the point of the first non-blank character after the
4127 (when (python-info-continuation-line-p)
4129 (back-to-indentation)
4130 (when (and (not (looking-at (python-rx block-start
)))
4131 (and (re-search-forward (python-rx not-simple-operator
4133 not-simple-operator
)
4134 (line-end-position) t
)
4135 (not (python-syntax-context-type))))
4136 (skip-syntax-forward "\s")
4139 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4140 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4141 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4143 (beginning-of-line 1)
4144 (looking-at python-nav-beginning-of-defun-regexp
))))
4146 (defun python-info-current-line-comment-p ()
4147 "Return non-nil if current line is a comment line."
4149 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4152 (defun python-info-current-line-empty-p ()
4153 "Return non-nil if current line is empty, ignoring whitespace."
4155 (beginning-of-line 1)
4157 (python-rx line-start
(* whitespace
)
4158 (group (* not-newline
))
4159 (* whitespace
) line-end
))
4160 (string-equal "" (match-string-no-properties 1))))
4162 (defun python-info-encoding-from-cookie ()
4163 "Detect current buffer's encoding from its coding cookie.
4164 Returns the enconding as a symbol."
4165 (let ((first-two-lines
4169 (goto-char (point-min))
4171 (buffer-substring-no-properties
4174 (when (string-match (python-rx coding-cookie
) first-two-lines
)
4175 (intern (match-string-no-properties 1 first-two-lines
)))))
4177 (defun python-info-encoding ()
4178 "Return encoding for file.
4179 Try `python-info-encoding-from-cookie', if none is found then
4181 ;; If no enconding is defined, then it's safe to use UTF-8: Python 2
4182 ;; uses ASCII as default while Python 3 uses UTF-8. This means that
4183 ;; in the worst case escenario python.el will make things work for
4184 ;; Python 2 files with unicode data and no encoding defined.
4185 (or (python-info-encoding-from-cookie)
4189 ;;; Utility functions
4191 (defun python-util-goto-line (line-number)
4192 "Move point to LINE-NUMBER."
4193 (goto-char (point-min))
4194 (forward-line (1- line-number
)))
4196 ;; Stolen from org-mode
4197 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
4198 "Clone local variables from FROM-BUFFER.
4199 Optional argument REGEXP selects variables to clone and defaults
4203 (and (symbolp (car pair
))
4204 (string-match (or regexp
"^python-")
4205 (symbol-name (car pair
)))
4206 (set (make-local-variable (car pair
))
4208 (buffer-local-variables from-buffer
)))
4210 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
4212 (defun python-util-comint-last-prompt ()
4213 "Return comint last prompt overlay start and end.
4214 This is for compatibility with Emacs < 24.4."
4215 (cond ((bound-and-true-p comint-last-prompt-overlay
)
4216 (cons (overlay-start comint-last-prompt-overlay
)
4217 (overlay-end comint-last-prompt-overlay
)))
4218 ((bound-and-true-p comint-last-prompt
)
4222 (defun python-util-forward-comment (&optional direction
)
4223 "Python mode specific version of `forward-comment'.
4224 Optional argument DIRECTION defines the direction to move to."
4225 (let ((comment-start (python-syntax-context 'comment
))
4226 (factor (if (< (or direction
0) 0)
4230 (goto-char comment-start
))
4231 (forward-comment factor
)))
4233 (defun python-util-list-directories (directory &optional predicate max-depth
)
4234 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4235 Argument PREDICATE defaults to `identity' and must be a function
4236 that takes one argument (a full path) and returns non-nil for
4237 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4238 searching when depth is reached, else don't limit."
4239 (let* ((dir (expand-file-name directory
))
4240 (dir-length (length dir
))
4241 (predicate (or predicate
#'identity
))
4242 (to-scan (list dir
))
4245 (let ((current-dir (car to-scan
)))
4246 (when (funcall predicate current-dir
)
4247 (setq tally
(cons current-dir tally
)))
4248 (setq to-scan
(append (cdr to-scan
)
4249 (python-util-list-files
4250 current-dir
#'file-directory-p
)
4252 (when (and max-depth
4254 (length (split-string
4255 (substring current-dir dir-length
)
4257 (setq to-scan nil
))))
4260 (defun python-util-list-files (dir &optional predicate
)
4261 "List files in DIR, filtering with PREDICATE.
4262 Argument PREDICATE defaults to `identity' and must be a function
4263 that takes one argument (a full path) and returns non-nil for
4265 (let ((dir-name (file-name-as-directory dir
)))
4267 (mapcar (lambda (file-name)
4268 (let ((full-file-name (expand-file-name file-name dir-name
)))
4270 (not (member file-name
'("." "..")))
4271 (funcall (or predicate
#'identity
) full-file-name
))
4272 (list full-file-name
))))
4273 (directory-files dir-name
)))))
4275 (defun python-util-list-packages (dir &optional max-depth
)
4276 "List packages in DIR, limited by MAX-DEPTH.
4277 When optional argument MAX-DEPTH is non-nil, stop searching when
4278 depth is reached, else don't limit."
4279 (let* ((dir (expand-file-name dir
))
4280 (parent-dir (file-name-directory
4281 (directory-file-name
4282 (file-name-directory
4283 (file-name-as-directory dir
)))))
4284 (subpath-length (length parent-dir
)))
4287 (replace-regexp-in-string
4288 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
4289 (python-util-list-directories
4290 (directory-file-name dir
)
4292 (file-exists-p (expand-file-name "__init__.py" dir
)))
4295 (defun python-util-popn (lst n
)
4296 "Return LST first N elements.
4297 N should be an integer, when negative its opposite is used.
4298 When N is bigger than the length of LST, the list is
4300 (let* ((n (min (abs n
)))
4306 (setq acc
(cons (car lst
) acc
)
4311 (defun python-util-text-properties-replace-name
4312 (from to
&optional start end
)
4313 "Replace properties named FROM to TO, keeping its value.
4314 Arguments START and END narrow the buffer region to work on."
4316 (goto-char (or start
(point-min)))
4318 (let ((plist (text-properties-at (point)))
4319 (next-change (or (next-property-change (point) (current-buffer))
4320 (or end
(point-max)))))
4321 (when (plist-get plist from
)
4322 (let* ((face (plist-get plist from
))
4323 (plist (plist-put plist from nil
))
4324 (plist (plist-put plist to face
)))
4325 (set-text-properties (point) next-change plist
(current-buffer))))
4326 (goto-char next-change
)))))
4328 (defun python-util-strip-string (string)
4329 "Strip STRING whitespace and newlines from end and beginning."
4330 (replace-regexp-in-string
4331 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
4332 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
4336 (defun python-util-valid-regexp-p (regexp)
4337 "Return non-nil if REGEXP is valid."
4338 (ignore-errors (string-match regexp
"") t
))
4341 (defun python-electric-pair-string-delimiter ()
4342 (when (and electric-pair-mode
4343 (memq last-command-event
'(?
\" ?
\'))
4345 (while (eq (char-before (- (point) count
)) last-command-event
)
4348 (eq (char-after) last-command-event
))
4349 (save-excursion (insert (make-string 2 last-command-event
)))))
4351 (defvar electric-indent-inhibit
)
4354 (define-derived-mode python-mode prog-mode
"Python"
4355 "Major mode for editing Python files.
4357 \\{python-mode-map}"
4358 (set (make-local-variable 'tab-width
) 8)
4359 (set (make-local-variable 'indent-tabs-mode
) nil
)
4361 (set (make-local-variable 'comment-start
) "# ")
4362 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4364 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4365 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4367 (set (make-local-variable 'forward-sexp-function
)
4368 'python-nav-forward-sexp
)
4370 (set (make-local-variable 'font-lock-defaults
)
4371 '(python-font-lock-keywords
4373 (font-lock-syntactic-face-function
4374 . python-font-lock-syntactic-face-function
)))
4376 (set (make-local-variable 'syntax-propertize-function
)
4377 python-syntax-propertize-function
)
4379 (set (make-local-variable 'indent-line-function
)
4380 #'python-indent-line-function
)
4381 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4382 ;; Because indentation is not redundant, we cannot safely reindent code.
4383 (set (make-local-variable 'electric-indent-inhibit
) t
)
4384 (set (make-local-variable 'electric-indent-chars
)
4385 (cons ?
: electric-indent-chars
))
4387 ;; Add """ ... """ pairing to electric-pair-mode.
4388 (add-hook 'post-self-insert-hook
4389 #'python-electric-pair-string-delimiter
'append t
)
4391 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4392 (set (make-local-variable 'fill-paragraph-function
)
4393 #'python-fill-paragraph
)
4395 (set (make-local-variable 'beginning-of-defun-function
)
4396 #'python-nav-beginning-of-defun
)
4397 (set (make-local-variable 'end-of-defun-function
)
4398 #'python-nav-end-of-defun
)
4400 (add-hook 'completion-at-point-functions
4401 #'python-completion-at-point nil
'local
)
4403 (add-hook 'post-self-insert-hook
4404 #'python-indent-post-self-insert-function
'append
'local
)
4406 (set (make-local-variable 'imenu-create-index-function
)
4407 #'python-imenu-create-index
)
4409 (set (make-local-variable 'add-log-current-defun-function
)
4410 #'python-info-current-defun
)
4412 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4414 (set (make-local-variable 'skeleton-further-elements
)
4416 (< '(backward-delete-char-untabify (min python-indent-offset
4418 (^
'(- (1+ (current-indentation))))))
4420 (set (make-local-variable 'eldoc-documentation-function
)
4421 #'python-eldoc-function
)
4423 (add-to-list 'hs-special-modes-alist
4424 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
4426 (python-nav-end-of-defun))
4429 (set (make-local-variable 'outline-regexp
)
4430 (python-rx (* space
) block-start
))
4431 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
4432 (set (make-local-variable 'outline-level
)
4434 "`outline-level' function for Python mode."
4435 (1+ (/ (current-indentation) python-indent-offset
))))
4437 (python-skeleton-add-menu-items)
4439 (make-local-variable 'python-shell-internal-buffer
)
4441 (when python-indent-guess-indent-offset
4442 (python-indent-guess-indent-offset)))
4449 ;; indent-tabs-mode: nil
4452 ;;; python.el ends here