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 ;; If you are experiencing missing or delayed output in your shells,
98 ;; that's likely caused by your Operating System's pipe buffering
99 ;; (e.g. this is known to happen running CPython 3.3.4 in Windows 7.
100 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
101 ;; fix this, using CPython's "-u" commandline argument or setting the
102 ;; "PYTHONUNBUFFERED" environment variable should help: See URL
103 ;; `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
105 ;; The interaction relies upon having prompts for input (e.g. ">>> "
106 ;; and "... " in standard Python shell) and output (e.g. "Out[1]: " in
107 ;; IPython) detected properly. Failing that Emacs may hang but, in
108 ;; the case that happens, you can recover with \\[keyboard-quit]. To
109 ;; avoid this issue, a two-step prompt autodetection mechanism is
110 ;; provided: the first step is manual and consists of a collection of
111 ;; regular expressions matching common prompts for Python shells
112 ;; stored in `python-shell-prompt-input-regexps' and
113 ;; `python-shell-prompt-output-regexps', and dir-local friendly vars
114 ;; `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
115 ;; `python-shell-prompt-output-regexp' which are appended to the
116 ;; former automatically when a shell spawns; the second step is
117 ;; automatic and depends on the `python-shell-prompt-detect' helper
118 ;; function. See its docstring for details on global variables that
119 ;; modify its behavior.
121 ;; Shell completion: hitting tab will try to complete the current
122 ;; word. Shell completion is implemented in such way that if you
123 ;; change the `python-shell-interpreter' it should be possible to
124 ;; integrate custom logic to calculate completions. To achieve this
125 ;; you just need to set `python-shell-completion-setup-code' and
126 ;; `python-shell-completion-string-code'. The default provided code,
127 ;; enables autocompletion for both CPython and IPython (and ideally
128 ;; any readline based Python shell). This code depends on the
129 ;; readline module, so if you are using some Operating System that
130 ;; bundles Python without it (like Windows), installing pyreadline
131 ;; from URL `http://ipython.scipy.org/moin/PyReadline/Intro' should
132 ;; suffice. To troubleshoot why you are not getting any completions
133 ;; you can try the following in your Python shell:
135 ;; >>> import readline, rlcompleter
137 ;; If you see an error, then you need to either install pyreadline or
138 ;; setup custom code that avoids that dependency.
140 ;; Shell virtualenv support: The shell also contains support for
141 ;; virtualenvs and other special environment modifications thanks to
142 ;; `python-shell-process-environment' and `python-shell-exec-path'.
143 ;; These two variables allows you to modify execution paths and
144 ;; environment variables to make easy for you to setup virtualenv rules
145 ;; or behavior modifications when running shells. Here is an example
146 ;; of how to make shell processes to be run using the /path/to/env/
149 ;; (setq python-shell-process-environment
151 ;; (format "PATH=%s" (mapconcat
154 ;; (cons (getenv "PATH")
155 ;; '("/path/to/env/bin/")))
157 ;; "VIRTUAL_ENV=/path/to/env/"))
158 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
160 ;; Since the above is cumbersome and can be programmatically
161 ;; calculated, the variable `python-shell-virtualenv-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 probably will miss auto-indentation
221 ;; when inserting newlines. To achieve the same behavior you have
224 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
226 ;; 2) Add the following hook in your .emacs:
228 ;; (add-hook 'python-mode-hook
230 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
232 ;; I'd recommend the first one since you'll get the same behavior for
233 ;; all modes out-of-the-box.
237 ;; Add this to your .emacs:
239 ;; (add-to-list 'load-path "/folder/containing/file")
246 (require 'ansi-color
)
251 ;; Avoid compiler warnings
252 (defvar view-return-to-alist
)
253 (defvar compilation-error-regexp-alist
)
254 (defvar outline-heading-end-regexp
)
256 (autoload 'comint-mode
"comint")
259 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
261 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
264 "Python Language's flying circus support for Emacs."
267 :link
'(emacs-commentary-link "python"))
272 (defvar python-mode-map
273 (let ((map (make-sparse-keymap)))
275 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
276 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
277 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
278 (define-key map
"\C-c\C-j" 'imenu
)
280 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
281 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
282 (define-key map
"\C-c<" 'python-indent-shift-left
)
283 (define-key map
"\C-c>" 'python-indent-shift-right
)
285 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
286 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
287 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
288 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
289 (define-key map
"\C-c\C-tm" 'python-skeleton-import
)
290 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
291 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
293 (define-key map
"\C-c\C-p" 'run-python
)
294 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
295 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
296 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
297 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
298 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
299 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
300 ;; Some util commands
301 (define-key map
"\C-c\C-v" 'python-check
)
302 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
304 (substitute-key-definition 'complete-symbol
'completion-at-point
306 (easy-menu-define python-menu map
"Python Mode menu"
308 :help
"Python-specific Features"
309 ["Shift region left" python-indent-shift-left
:active mark-active
310 :help
"Shift region left by a single indentation step"]
311 ["Shift region right" python-indent-shift-right
:active mark-active
312 :help
"Shift region right by a single indentation step"]
314 ["Start of def/class" beginning-of-defun
315 :help
"Go to start of outermost definition around point"]
316 ["End of def/class" end-of-defun
317 :help
"Go to end of definition around point"]
318 ["Mark def/class" mark-defun
319 :help
"Mark outermost definition around point"]
320 ["Jump to def/class" imenu
321 :help
"Jump to a class or function definition"]
325 ["Start interpreter" run-python
326 :help
"Run inferior Python process in a separate buffer"]
327 ["Switch to shell" python-shell-switch-to-shell
328 :help
"Switch to running inferior Python process"]
329 ["Eval string" python-shell-send-string
330 :help
"Eval string in inferior Python session"]
331 ["Eval buffer" python-shell-send-buffer
332 :help
"Eval buffer in inferior Python session"]
333 ["Eval region" python-shell-send-region
334 :help
"Eval region in inferior Python session"]
335 ["Eval defun" python-shell-send-defun
336 :help
"Eval defun in inferior Python session"]
337 ["Eval file" python-shell-send-file
338 :help
"Eval file in inferior Python session"]
339 ["Debugger" pdb
:help
"Run pdb under GUD"]
341 ["Check file" python-check
342 :help
"Check file for errors"]
343 ["Help on symbol" python-eldoc-at-point
344 :help
"Get help on symbol at point"]
345 ["Complete symbol" completion-at-point
346 :help
"Complete symbol before point"]))
348 "Keymap for `python-mode'.")
351 ;;; Python specialized rx
354 (defconst python-rx-constituents
355 `((block-start .
,(rx symbol-start
356 (or "def" "class" "if" "elif" "else" "try"
357 "except" "finally" "for" "while" "with")
359 (dedenter .
,(rx symbol-start
360 (or "elif" "else" "except" "finally")
362 (block-ender .
,(rx symbol-start
364 "break" "continue" "pass" "raise" "return")
366 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
368 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
369 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
370 (+ space
) "==" (+ space
)
371 (any ?
' ?
\") "__main__" (any ?
' ?
\")
373 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
374 (open-paren .
,(rx (or "{" "[" "(")))
375 (close-paren .
,(rx (or "}" "]" ")")))
376 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
377 ;; FIXME: rx should support (not simple-operator).
378 (not-simple-operator .
,(rx
380 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
381 ;; FIXME: Use regexp-opt.
382 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
383 "=" "%" "**" "//" "<<" ">>" "<=" "!="
384 "==" ">=" "is" "not")))
385 ;; FIXME: Use regexp-opt.
386 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
387 ">>=" "<<=" "&=" "^=" "|=")))
388 (string-delimiter .
,(rx (and
389 ;; Match even number of backslashes.
390 (or (not (any ?
\\ ?
\' ?
\")) point
391 ;; Quotes might be preceded by a escaped quote.
392 (and (or (not (any ?
\\)) point
) ?
\\
393 (* ?
\\ ?
\\) (any ?
\' ?
\")))
395 ;; Match single or triple quotes of any kind.
396 (group (or "\"" "\"\"\"" "'" "'''"))))))
397 "Additional Python specific sexps for `python-rx'")
399 (defmacro python-rx
(&rest regexps
)
400 "Python mode specialized rx macro.
401 This variant of `rx' supports common Python named REGEXPS."
402 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
403 (cond ((null regexps
)
406 (rx-to-string `(and ,@regexps
) t
))
408 (rx-to-string (car regexps
) t
))))))
411 ;;; Font-lock and syntax
414 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
417 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
418 (and (nth 4 ppss
) (nth 8 ppss
))))
420 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
421 (and (nth 3 ppss
) (nth 8 ppss
))))
423 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
426 (defun python-syntax-context (type &optional syntax-ppss
)
427 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
428 TYPE can be `comment', `string' or `paren'. It returns the start
429 character address of the specified TYPE."
430 (declare (compiler-macro python-syntax--context-compiler-macro
))
431 (let ((ppss (or syntax-ppss
(syntax-ppss))))
433 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
434 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
435 (`paren
(nth 1 ppss
))
438 (defun python-syntax-context-type (&optional syntax-ppss
)
439 "Return the context type using SYNTAX-PPSS.
440 The type returned can be `comment', `string' or `paren'."
441 (let ((ppss (or syntax-ppss
(syntax-ppss))))
443 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
444 ((nth 1 ppss
) 'paren
))))
446 (defsubst python-syntax-comment-or-string-p
()
447 "Return non-nil if point is inside 'comment or 'string."
448 (nth 8 (syntax-ppss)))
450 (define-obsolete-function-alias
451 'python-info-ppss-context
#'python-syntax-context
"24.3")
453 (define-obsolete-function-alias
454 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
456 (define-obsolete-function-alias
457 'python-info-ppss-comment-or-string-p
458 #'python-syntax-comment-or-string-p
"24.3")
460 (defvar python-font-lock-keywords
464 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
465 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
466 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
471 ;; False, None, and True are listed as keywords on the Python 3
472 ;; documentation, but since they also qualify as constants they are
473 ;; fontified like that in order to keep font-lock consistent between
480 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
481 (1 font-lock-function-name-face
))
483 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
484 (1 font-lock-type-face
))
488 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
489 ;; copyright, license, credits, quit and exit are added by the site
490 ;; module and they are not intended to be used in programs
491 "copyright" "credits" "exit" "license" "quit")
492 symbol-end
) . font-lock-constant-face
)
494 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
495 (0+ "." (1+ (or word ?_
)))))
496 (1 font-lock-type-face
))
497 ;; Builtin Exceptions
500 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
501 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
502 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
503 "ImportError" "ImportWarning" "IndexError" "KeyError"
504 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
505 "NotImplementedError" "OSError" "OverflowError"
506 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
507 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
508 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
509 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
510 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
511 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
515 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
517 symbol-end
) . font-lock-type-face
)
521 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
522 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
523 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
524 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
525 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
526 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
527 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
528 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
531 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
532 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
535 "ascii" "bytearray" "bytes" "exec"
537 "__all__" "__doc__" "__name__" "__package__")
538 symbol-end
) . font-lock-builtin-face
)
540 ;; support for a = b = c = 5
542 (let ((re (python-rx (group (+ (any word ?. ?_
)))
543 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
544 assignment-operator
))
546 (while (and (setq res
(re-search-forward re limit t
))
547 (or (python-syntax-context 'paren
)
548 (equal (char-after (point)) ?
=))))
550 (1 font-lock-variable-name-face nil nil
))
551 ;; support for a, b, c = (1, 2, 3)
553 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
554 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
555 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
556 assignment-operator
))
558 (while (and (setq res
(re-search-forward re limit t
))
559 (goto-char (match-end 1))
560 (python-syntax-context 'paren
)))
562 (1 font-lock-variable-name-face nil nil
))))
564 (defconst python-syntax-propertize-function
565 (syntax-propertize-rules
566 ((python-rx string-delimiter
)
567 (0 (ignore (python-syntax-stringify))))))
569 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
570 "Count number of quotes around point (max is 3).
571 QUOTE-CHAR is the quote char to count. Optional argument POINT is
572 the point where scan starts (defaults to current point), and LIMIT
573 is used to limit the scan."
576 (or (not limit
) (< (+ point i
) limit
))
577 (eq (char-after (+ point i
)) quote-char
))
581 (defun python-syntax-stringify ()
582 "Put `syntax-table' property correctly on single/triple quotes."
583 (let* ((num-quotes (length (match-string-no-properties 1)))
585 (backward-char num-quotes
)
587 (forward-char num-quotes
)))
588 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
589 (quote-starting-pos (- (point) num-quotes
))
590 (quote-ending-pos (point))
593 (python-syntax-count-quotes
594 (char-before) string-start quote-starting-pos
))))
595 (cond ((and string-start
(= num-closing-quotes
0))
596 ;; This set of quotes doesn't match the string starting
600 ;; This set of quotes delimit the start of a string.
601 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
602 'syntax-table
(string-to-syntax "|")))
603 ((= num-quotes num-closing-quotes
)
604 ;; This set of quotes delimit the end of a string.
605 (put-text-property (1- quote-ending-pos
) quote-ending-pos
606 'syntax-table
(string-to-syntax "|")))
607 ((> num-quotes num-closing-quotes
)
608 ;; This may only happen whenever a triple quote is closing
609 ;; a single quoted string. Add string delimiter syntax to
611 (put-text-property quote-starting-pos quote-ending-pos
612 'syntax-table
(string-to-syntax "|"))))))
614 (defvar python-mode-syntax-table
615 (let ((table (make-syntax-table)))
616 ;; Give punctuation syntax to ASCII that normally has symbol
617 ;; syntax or has word syntax and isn't a letter.
618 (let ((symbol (string-to-syntax "_"))
619 (sst (standard-syntax-table)))
622 (if (equal symbol
(aref sst i
))
623 (modify-syntax-entry i
"." table
)))))
624 (modify-syntax-entry ?$
"." table
)
625 (modify-syntax-entry ?%
"." table
)
627 (modify-syntax-entry ?
# "<" table
)
628 (modify-syntax-entry ?
\n ">" table
)
629 (modify-syntax-entry ?
' "\"" table
)
630 (modify-syntax-entry ?
` "$" table
)
632 "Syntax table for Python files.")
634 (defvar python-dotty-syntax-table
635 (let ((table (make-syntax-table python-mode-syntax-table
)))
636 (modify-syntax-entry ?.
"w" table
)
637 (modify-syntax-entry ?_
"w" table
)
639 "Dotty syntax table for Python files.
640 It makes underscores and dots word constituent chars.")
645 (defcustom python-indent-offset
4
646 "Default indentation offset for Python."
651 (defcustom python-indent-guess-indent-offset t
652 "Non-nil tells Python mode to guess `python-indent-offset' value."
657 (defcustom python-indent-trigger-commands
658 '(indent-for-tab-command yas-expand yas
/expand
)
659 "Commands that might trigger a `python-indent-line' call."
660 :type
'(repeat symbol
)
663 (define-obsolete-variable-alias
664 'python-indent
'python-indent-offset
"24.3")
666 (define-obsolete-variable-alias
667 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
669 (defvar python-indent-current-level
0
670 "Current indentation level `python-indent-line-function' is using.")
672 (defvar python-indent-levels
'(0)
673 "Levels of indentation available for `python-indent-line-function'.")
675 (defun python-indent-guess-indent-offset ()
676 "Guess and set `python-indent-offset' for the current buffer."
681 (goto-char (point-min))
683 (while (and (not block-end
)
685 (python-rx line-start block-start
) nil t
))
687 (not (python-syntax-context-type))
689 (goto-char (line-end-position))
690 (python-util-forward-comment -
1)
691 (if (equal (char-before) ?
:)
694 (when (python-info-block-continuation-line-p)
695 (while (and (python-info-continuation-line-p)
698 (python-util-forward-comment -
1)
699 (when (equal (char-before) ?
:)
701 (setq block-end
(point-marker))))
704 (goto-char block-end
)
705 (python-util-forward-comment)
706 (current-indentation))))
707 (if (and indentation
(not (zerop indentation
)))
708 (set (make-local-variable 'python-indent-offset
) indentation
)
709 (message "Can't guess python-indent-offset, using defaults: %s"
710 python-indent-offset
)))))))
712 (defun python-indent-context ()
713 "Get information on indentation context.
714 Context information is returned with a cons with the form:
717 Where status can be any of the following symbols:
719 * after-comment: When current line might continue a comment block
720 * inside-paren: If point in between (), {} or []
721 * inside-string: If point is inside a string
722 * after-backslash: Previous line ends in a backslash
723 * after-beginning-of-block: Point is after beginning of block
724 * after-line: Point is after normal line
725 * dedenter-statement: Point is on a dedenter statement.
726 * no-indent: Point is at beginning of buffer or other special case
727 START is the buffer position where the sexp starts."
730 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
734 ;; Beginning of buffer
736 (goto-char (line-beginning-position))
739 ;; Comment continuation
743 (python-info-current-line-comment-p)
744 (python-info-current-line-empty-p))
747 (python-info-current-line-comment-p)))
751 ((setq start
(python-syntax-context 'string ppss
))
754 ((setq start
(python-syntax-context 'paren ppss
))
757 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
758 (python-syntax-context 'comment ppss
)))
759 (let ((line-beg-pos (line-number-at-pos)))
760 (python-info-line-ends-backslash-p
761 (1- line-beg-pos
)))))
763 ;; After beginning of block
764 ((setq start
(save-excursion
766 (back-to-indentation)
767 (python-util-forward-comment -
1)
768 (equal (char-before) ?
:))
769 ;; Move to the first block start that's not in within
770 ;; a string, comment or paren and that's not a
771 ;; continuation line.
772 (while (and (re-search-backward
773 (python-rx block-start
) nil t
)
775 (python-syntax-context-type)
776 (python-info-continuation-line-p))))
777 (when (looking-at (python-rx block-start
))
779 'after-beginning-of-block
)
780 ((when (setq start
(python-info-dedenter-statement-p))
781 'dedenter-statement
))
783 ((setq start
(save-excursion
784 (back-to-indentation)
785 (skip-chars-backward (rx (or whitespace ?
\n)))
786 (python-nav-beginning-of-statement)
793 (defun python-indent-calculate-indentation ()
794 "Calculate correct indentation offset for the current line."
795 (let* ((indentation-context (python-indent-context))
796 (context-status (car indentation-context
))
797 (context-start (cdr indentation-context
)))
801 (pcase context-status
804 (goto-char context-start
)
805 (current-indentation))
806 ;; When point is after beginning of block just add one level
807 ;; of indentation relative to the context-start
808 (`after-beginning-of-block
809 (goto-char context-start
)
810 (+ (current-indentation) python-indent-offset
))
811 ;; When after a simple line just use previous line
814 (let* ((pair (save-excursion
815 (goto-char context-start
)
817 (current-indentation)
818 (python-info-beginning-of-block-p))))
819 (context-indentation (car pair
))
820 ;; TODO: Separate block enders into its own case.
823 (python-util-forward-comment -
1)
824 (python-nav-beginning-of-statement)
825 (looking-at (python-rx block-ender
)))
828 (- context-indentation adjustment
)))
829 ;; When point is on a dedenter statement, search for the
830 ;; opening block that corresponds to it and use its
831 ;; indentation. If no opening block is found just remove
832 ;; indentation as this is an invalid python file.
834 (let ((block-start-point
835 (python-info-dedenter-opening-block-position)))
837 (if (not block-start-point
)
839 (goto-char block-start-point
)
840 (current-indentation)))))
841 ;; When inside of a string, do nothing. just use the current
842 ;; indentation. XXX: perhaps it would be a good idea to
843 ;; invoke standard text indentation here
845 (goto-char context-start
)
846 (current-indentation))
847 ;; After backslash we have several possibilities.
850 ;; Check if current line is a dot continuation. For this
851 ;; the current line must start with a dot and previous
852 ;; line must contain a dot too.
854 (back-to-indentation)
855 (when (looking-at "\\.")
856 ;; If after moving one line back point is inside a paren it
857 ;; needs to move back until it's not anymore
861 (python-syntax-context 'paren
))))
862 (goto-char (line-end-position))
863 (while (and (re-search-backward
864 "\\." (line-beginning-position) t
)
865 (python-syntax-context-type)))
866 (if (and (looking-at "\\.")
867 (not (python-syntax-context-type)))
868 ;; The indentation is the same column of the
869 ;; first matching dot that's not inside a
870 ;; comment, a string or a paren
872 ;; No dot found on previous line, just add another
873 ;; indentation level.
874 (+ (current-indentation) python-indent-offset
)))))
875 ;; Check if prev line is a block continuation
876 ((let ((block-continuation-start
877 (python-info-block-continuation-line-p)))
878 (when block-continuation-start
879 ;; If block-continuation-start is set jump to that
880 ;; marker and use first column after the block start
881 ;; as indentation value.
882 (goto-char block-continuation-start
)
884 (python-rx block-start
(* space
))
885 (line-end-position) t
)
887 ;; Check if current line is an assignment continuation
888 ((let ((assignment-continuation-start
889 (python-info-assignment-continuation-line-p)))
890 (when assignment-continuation-start
891 ;; If assignment-continuation is set jump to that
892 ;; marker and use first column after the assignment
893 ;; operator as indentation value.
894 (goto-char assignment-continuation-start
)
898 (goto-char (python-info-beginning-of-backslash))
903 (or (python-info-beginning-of-backslash) (point)))
904 (python-info-line-ends-backslash-p)))
905 ;; The two previous lines ended in a backslash so we must
906 ;; respect previous line indentation.
907 (current-indentation)
908 ;; What happens here is that we are dealing with the second
909 ;; line of a backslash continuation, in that case we just going
910 ;; to add one indentation level.
911 (+ (current-indentation) python-indent-offset
)))))
912 ;; When inside a paren there's a need to handle nesting
916 ;; If current line closes the outermost open paren use the
917 ;; current indentation of the context-start line.
919 (skip-syntax-forward "\s" (line-end-position))
920 (when (and (looking-at (regexp-opt '(")" "]" "}")))
923 (not (python-syntax-context 'paren
))))
924 (goto-char context-start
)
925 (current-indentation))))
926 ;; If open paren is contained on a line by itself add another
927 ;; indentation level, else look for the first word after the
928 ;; opening paren and use it's column position as indentation
930 ((let* ((content-starts-in-newline)
933 (if (setq content-starts-in-newline
935 (goto-char context-start
)
939 (line-beginning-position)
941 (python-util-forward-comment))
943 (+ (current-indentation) python-indent-offset
)
947 ;; If current line closes a nested open paren de-indent one
950 (back-to-indentation)
951 (looking-at (regexp-opt '(")" "]" "}"))))
952 (- indent python-indent-offset
))
953 ;; If the line of the opening paren that wraps the current
954 ;; line starts a block add another level of indentation to
955 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
957 (when (and content-starts-in-newline
959 (goto-char context-start
)
960 (back-to-indentation)
961 (looking-at (python-rx block-start
))))
962 (+ indent python-indent-offset
))))
965 (defun python-indent-calculate-levels ()
966 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
967 (if (or (python-info-continuation-line-p)
968 (not (python-info-dedenter-statement-p)))
969 ;; XXX: This asks for a refactor. Even if point is on a
970 ;; dedenter statement, it could be multiline and in that case
971 ;; the continuation lines should be indented with normal rules.
972 (let* ((indentation (python-indent-calculate-indentation))
973 (remainder (% indentation python-indent-offset
))
974 (steps (/ (- indentation remainder
) python-indent-offset
)))
975 (setq python-indent-levels
(list 0))
976 (dotimes (step steps
)
977 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
978 (when (not (eq 0 remainder
))
979 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
)))
980 (setq python-indent-levels
982 (mapcar (lambda (pos)
985 (current-indentation)))
986 (python-info-dedenter-opening-block-positions))
988 (setq python-indent-current-level
(1- (length python-indent-levels
))
989 python-indent-levels
(nreverse python-indent-levels
)))
991 (defun python-indent-toggle-levels ()
992 "Toggle `python-indent-current-level' over `python-indent-levels'."
993 (setq python-indent-current-level
(1- python-indent-current-level
))
994 (when (< python-indent-current-level
0)
995 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
997 (defun python-indent-line (&optional force-toggle
)
998 "Internal implementation of `python-indent-line-function'.
999 Uses the offset calculated in
1000 `python-indent-calculate-indentation' and available levels
1001 indicated by the variable `python-indent-levels' to set the
1002 current indentation.
1004 When the variable `last-command' is equal to one of the symbols
1005 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
1006 non-nil it cycles levels indicated in the variable
1007 `python-indent-levels' by setting the current level in the
1008 variable `python-indent-current-level'.
1010 When the variable `last-command' is not equal to one of the
1011 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
1012 is nil it calculates possible indentation levels and saves them
1013 in the variable `python-indent-levels'. Afterwards it sets the
1014 variable `python-indent-current-level' correctly so offset is
1016 (nth python-indent-current-level python-indent-levels)"
1018 (and (or (and (memq this-command python-indent-trigger-commands
)
1019 (eq last-command this-command
))
1021 (not (equal python-indent-levels
'(0)))
1022 (or (python-indent-toggle-levels) t
))
1023 (python-indent-calculate-levels))
1024 (let* ((starting-pos (point-marker))
1025 (indent-ending-position
1026 (+ (line-beginning-position) (current-indentation)))
1027 (follow-indentation-p
1029 (and (<= (line-beginning-position) starting-pos
)
1030 (>= indent-ending-position starting-pos
))))
1031 (next-indent (nth python-indent-current-level python-indent-levels
)))
1032 (unless (= next-indent
(current-indentation))
1034 (delete-horizontal-space)
1035 (indent-to next-indent
)
1036 (goto-char starting-pos
))
1037 (and follow-indentation-p
(back-to-indentation)))
1038 (python-info-dedenter-opening-block-message))
1040 (defun python-indent-line-function ()
1041 "`indent-line-function' for Python mode.
1042 See `python-indent-line' for details."
1043 (python-indent-line))
1045 (defun python-indent-dedent-line ()
1046 "De-indent current line."
1048 (when (and (not (python-syntax-comment-or-string-p))
1049 (<= (point) (save-excursion
1050 (back-to-indentation)
1052 (> (current-column) 0))
1053 (python-indent-line t
)
1056 (defun python-indent-dedent-line-backspace (arg)
1057 "De-indent current line.
1058 Argument ARG is passed to `backward-delete-char-untabify' when
1059 point is not in between the indentation."
1061 (when (not (python-indent-dedent-line))
1062 (backward-delete-char-untabify arg
)))
1063 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1065 (defun python-indent-region (start end
)
1066 "Indent a Python region automagically.
1068 Called from a program, START and END specify the region to indent."
1069 (let ((deactivate-mark nil
))
1072 (setq end
(point-marker))
1074 (or (bolp) (forward-line 1))
1075 (while (< (point) end
)
1076 (or (and (bolp) (eolp))
1078 ;; Skip if previous line is empty or a comment.
1080 (let ((line-is-comment-p
1081 (python-info-current-line-comment-p)))
1084 (or (and (python-info-current-line-comment-p)
1085 ;; Unless this line is a comment too.
1086 (not line-is-comment-p
))
1087 (python-info-current-line-empty-p)))))
1088 ;; Don't mess with strings, unless it's the
1089 ;; enclosing set of quotes.
1090 (or (not (python-syntax-context 'string
))
1094 (current-indentation)
1095 (python-syntax-count-quotes (char-after) (point))))
1096 (string-to-syntax "|")))
1097 ;; Skip if current line is a block start, a
1098 ;; dedenter or block ender.
1100 (back-to-indentation)
1103 (or block-start dedenter block-ender
))))))
1104 (python-indent-line)))
1106 (move-marker end nil
))))
1108 (defun python-indent-shift-left (start end
&optional count
)
1109 "Shift lines contained in region START END by COUNT columns to the left.
1110 COUNT defaults to `python-indent-offset'. If region isn't
1111 active, the current line is shifted. The shifted region includes
1112 the lines in which START and END lie. An error is signaled if
1113 any lines in the region are indented less than COUNT columns."
1116 (list (region-beginning) (region-end) current-prefix-arg
)
1117 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1119 (setq count
(prefix-numeric-value count
))
1120 (setq count python-indent-offset
))
1122 (let ((deactivate-mark nil
))
1125 (while (< (point) end
)
1126 (if (and (< (current-indentation) count
)
1127 (not (looking-at "[ \t]*$")))
1128 (user-error "Can't shift all lines enough"))
1130 (indent-rigidly start end
(- count
))))))
1132 (defun python-indent-shift-right (start end
&optional count
)
1133 "Shift lines contained in region START END by COUNT columns to the right.
1134 COUNT defaults to `python-indent-offset'. If region isn't
1135 active, the current line is shifted. The shifted region includes
1136 the lines in which START and END lie."
1139 (list (region-beginning) (region-end) current-prefix-arg
)
1140 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1141 (let ((deactivate-mark nil
))
1142 (setq count
(if count
(prefix-numeric-value count
)
1143 python-indent-offset
))
1144 (indent-rigidly start end count
)))
1146 (defun python-indent-post-self-insert-function ()
1147 "Adjust indentation after insertion of some characters.
1148 This function is intended to be added to `post-self-insert-hook.'
1149 If a line renders a paren alone, after adding a char before it,
1150 the line will be re-indented automatically if needed."
1151 (when (and electric-indent-mode
1152 (eq (char-before) last-command-event
))
1154 ;; Electric indent inside parens
1157 (let ((paren-start (python-syntax-context 'paren
)))
1158 ;; Check that point is inside parens.
1161 ;; Filter the case where input is happening in the same
1162 ;; line where the open paren is.
1163 (= (line-number-at-pos)
1164 (line-number-at-pos paren-start
)))))
1165 ;; When content has been added before the closing paren or a
1166 ;; comma has been inserted, it's ok to do the trick.
1168 (memq (char-after) '(?\
) ?\
] ?\
}))
1169 (eq (char-before) ?
,)))
1171 (goto-char (line-beginning-position))
1172 (let ((indentation (python-indent-calculate-indentation)))
1173 (when (< (current-indentation) indentation
)
1174 (indent-line-to indentation
)))))
1176 ((and (eq ?
: last-command-event
)
1177 (memq ?
: electric-indent-chars
)
1178 (not current-prefix-arg
)
1179 ;; Trigger electric colon only at end of line
1181 ;; Avoid re-indenting on extra colon
1182 (not (equal ?
: (char-before (1- (point)))))
1183 (not (python-syntax-comment-or-string-p))
1184 ;; Never re-indent at beginning of defun
1185 (not (save-excursion
1186 (python-nav-beginning-of-statement)
1187 (python-info-looking-at-beginning-of-defun))))
1188 (python-indent-line)))))
1193 (defvar python-nav-beginning-of-defun-regexp
1194 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1195 "Regexp matching class or function definition.
1196 The name of the defun should be grouped so it can be retrieved
1197 via `match-string'.")
1199 (defun python-nav--beginning-of-defun (&optional arg
)
1200 "Internal implementation of `python-nav-beginning-of-defun'.
1201 With positive ARG search backwards, else search forwards."
1202 (when (or (null arg
) (= arg
0)) (setq arg
1))
1203 (let* ((re-search-fn (if (> arg
0)
1204 #'re-search-backward
1205 #'re-search-forward
))
1206 (line-beg-pos (line-beginning-position))
1207 (line-content-start (+ line-beg-pos
(current-indentation)))
1208 (pos (point-marker))
1213 (not (python-info-looking-at-beginning-of-defun))
1214 (python-nav-backward-block)))
1215 (or (and (python-info-looking-at-beginning-of-defun)
1216 (+ (current-indentation) python-indent-offset
))
1220 (when (and (< arg
0)
1221 (python-info-looking-at-beginning-of-defun))
1223 (while (and (funcall re-search-fn
1224 python-nav-beginning-of-defun-regexp nil t
)
1225 (or (python-syntax-context-type)
1226 ;; Handle nested defuns when moving
1227 ;; backwards by checking indentation.
1229 (not (= (current-indentation) 0))
1230 (>= (current-indentation) beg-indentation
)))))
1231 (and (python-info-looking-at-beginning-of-defun)
1232 (or (not (= (line-number-at-pos pos
)
1233 (line-number-at-pos)))
1234 (and (>= (point) line-beg-pos
)
1235 (<= (point) line-content-start
)
1236 (> pos line-content-start
)))))))
1238 (or (beginning-of-line 1) t
)
1239 (and (goto-char pos
) nil
))))
1241 (defun python-nav-beginning-of-defun (&optional arg
)
1242 "Move point to `beginning-of-defun'.
1243 With positive ARG search backwards else search forward.
1244 ARG nil or 0 defaults to 1. When searching backwards,
1245 nested defuns are handled with care depending on current
1246 point position. Return non-nil if point is moved to
1247 `beginning-of-defun'."
1248 (when (or (null arg
) (= arg
0)) (setq arg
1))
1250 (while (and (not (= arg
0))
1251 (let ((keep-searching-p
1252 (python-nav--beginning-of-defun arg)))
1253 (when (and keep-searching-p
(null found
))
1256 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1259 (defun python-nav-end-of-defun ()
1260 "Move point to the end of def or class.
1261 Returns nil if point is not in a def or class."
1263 (let ((beg-defun-indent)
1265 (when (or (python-info-looking-at-beginning-of-defun)
1266 (python-nav-beginning-of-defun 1)
1267 (python-nav-beginning-of-defun -1))
1268 (setq beg-defun-indent
(current-indentation))
1270 (python-nav-end-of-statement)
1271 (python-util-forward-comment 1)
1272 (and (> (current-indentation) beg-defun-indent
)
1274 (python-util-forward-comment -
1)
1276 ;; Ensure point moves forward.
1277 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1279 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1280 "Move point using FN avoiding places with specific context.
1281 FN must take no arguments. POSCOMPFN is a two arguments function
1282 used to compare current and previous point after it is moved
1283 using FN, this is normally a less-than or greater-than
1284 comparison. Optional argument CONTEXTFN defaults to
1285 `python-syntax-context-type' and is used for checking current
1286 point context, it must return a non-nil value if this point must
1288 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1289 (start-pos (point-marker))
1294 (and (funcall fn
) (point-marker)))
1295 (context (funcall contextfn
)))
1296 (cond ((and (not context
) newpos
1297 (or (and (not prev-pos
) newpos
)
1298 (and prev-pos newpos
1299 (funcall poscompfn newpos prev-pos
))))
1300 (throw 'found
(point-marker)))
1301 ((and newpos context
)
1302 (setq prev-pos
(point)))
1303 (t (when (not newpos
) (goto-char start-pos
))
1304 (throw 'found nil
))))))))
1306 (defun python-nav--forward-defun (arg)
1307 "Internal implementation of python-nav-{backward,forward}-defun.
1308 Uses ARG to define which function to call, and how many times
1311 (while (and (> arg
0)
1313 (python-nav--syntactically
1316 python-nav-beginning-of-defun-regexp nil t
))
1318 (setq arg
(1- arg
)))
1319 (while (and (< arg
0)
1321 (python-nav--syntactically
1324 python-nav-beginning-of-defun-regexp nil t
))
1326 (setq arg
(1+ arg
)))
1329 (defun python-nav-backward-defun (&optional arg
)
1330 "Navigate to closer defun backward ARG times.
1331 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1332 nested definitions."
1334 (python-nav--forward-defun (- (or arg
1))))
1336 (defun python-nav-forward-defun (&optional arg
)
1337 "Navigate to closer defun forward ARG times.
1338 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1339 nested definitions."
1341 (python-nav--forward-defun (or arg
1)))
1343 (defun python-nav-beginning-of-statement ()
1344 "Move to start of current statement."
1346 (back-to-indentation)
1347 (let* ((ppss (syntax-ppss))
1350 (python-syntax-context 'paren ppss
)
1351 (python-syntax-context 'string ppss
))))
1354 (goto-char context-point
)
1355 (python-nav-beginning-of-statement))
1358 (python-info-line-ends-backslash-p))
1360 (python-nav-beginning-of-statement))))
1363 (defun python-nav-end-of-statement (&optional noend
)
1364 "Move to end of current statement.
1365 Optional argument NOEND is internal and makes the logic to not
1366 jump to the end of line when moving forward searching for the end
1369 (let (string-start bs-pos
)
1370 (while (and (or noend
(goto-char (line-end-position)))
1372 (cond ((setq string-start
(python-syntax-context 'string
))
1373 (goto-char string-start
)
1374 (if (python-syntax-context 'paren
)
1375 ;; Ended up inside a paren, roll again.
1376 (python-nav-end-of-statement t
)
1377 ;; This is not inside a paren, move to the
1378 ;; end of this string.
1379 (goto-char (+ (point)
1380 (python-syntax-count-quotes
1381 (char-after (point)) (point))))
1382 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1383 (goto-char (point-max)))))
1384 ((python-syntax-context 'paren
)
1385 ;; The statement won't end before we've escaped
1386 ;; at least one level of parenthesis.
1388 (goto-char (scan-lists (point) 1 -
1))
1389 (scan-error (goto-char (nth 3 err
)))))
1390 ((setq bs-pos
(python-info-line-ends-backslash-p))
1392 (forward-line 1))))))
1395 (defun python-nav-backward-statement (&optional arg
)
1396 "Move backward to previous statement.
1397 With ARG, repeat. See `python-nav-forward-statement'."
1399 (or arg
(setq arg
1))
1400 (python-nav-forward-statement (- arg
)))
1402 (defun python-nav-forward-statement (&optional arg
)
1403 "Move forward to next statement.
1404 With ARG, repeat. With negative argument, move ARG times
1405 backward to previous statement."
1407 (or arg
(setq arg
1))
1409 (python-nav-end-of-statement)
1410 (python-util-forward-comment)
1411 (python-nav-beginning-of-statement)
1412 (setq arg
(1- arg
)))
1414 (python-nav-beginning-of-statement)
1415 (python-util-forward-comment -
1)
1416 (python-nav-beginning-of-statement)
1417 (setq arg
(1+ arg
))))
1419 (defun python-nav-beginning-of-block ()
1420 "Move to start of current block."
1422 (let ((starting-pos (point)))
1424 (python-nav-beginning-of-statement)
1425 (looking-at (python-rx block-start
)))
1427 ;; Go to first line beginning a statement
1428 (while (and (not (bobp))
1429 (or (and (python-nav-beginning-of-statement) nil
)
1430 (python-info-current-line-comment-p)
1431 (python-info-current-line-empty-p)))
1433 (let ((block-matching-indent
1434 (- (current-indentation) python-indent-offset
)))
1436 (and (python-nav-backward-block)
1437 (> (current-indentation) block-matching-indent
)))
1438 (if (and (looking-at (python-rx block-start
))
1439 (= (current-indentation) block-matching-indent
))
1441 (and (goto-char starting-pos
) nil
))))))
1443 (defun python-nav-end-of-block ()
1444 "Move to end of current block."
1446 (when (python-nav-beginning-of-block)
1447 (let ((block-indentation (current-indentation)))
1448 (python-nav-end-of-statement)
1449 (while (and (forward-line 1)
1451 (or (and (> (current-indentation) block-indentation
)
1452 (or (python-nav-end-of-statement) t
))
1453 (python-info-current-line-comment-p)
1454 (python-info-current-line-empty-p))))
1455 (python-util-forward-comment -
1)
1458 (defun python-nav-backward-block (&optional arg
)
1459 "Move backward to previous block of code.
1460 With ARG, repeat. See `python-nav-forward-block'."
1462 (or arg
(setq arg
1))
1463 (python-nav-forward-block (- arg
)))
1465 (defun python-nav-forward-block (&optional arg
)
1466 "Move forward to next block of code.
1467 With ARG, repeat. With negative argument, move ARG times
1468 backward to previous block."
1470 (or arg
(setq arg
1))
1471 (let ((block-start-regexp
1472 (python-rx line-start
(* whitespace
) block-start
))
1473 (starting-pos (point)))
1475 (python-nav-end-of-statement)
1477 (re-search-forward block-start-regexp nil t
)
1478 (python-syntax-context-type)))
1479 (setq arg
(1- arg
)))
1481 (python-nav-beginning-of-statement)
1483 (re-search-backward block-start-regexp nil t
)
1484 (python-syntax-context-type)))
1485 (setq arg
(1+ arg
)))
1486 (python-nav-beginning-of-statement)
1487 (if (not (looking-at (python-rx block-start
)))
1488 (and (goto-char starting-pos
) nil
)
1489 (and (not (= (point) starting-pos
)) (point-marker)))))
1491 (defun python-nav--lisp-forward-sexp (&optional arg
)
1492 "Standard version `forward-sexp'.
1493 It ignores completely the value of `forward-sexp-function' by
1494 setting it to nil before calling `forward-sexp'. With positive
1495 ARG move forward only one sexp, else move backwards."
1496 (let ((forward-sexp-function)
1497 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1498 (forward-sexp arg
)))
1500 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1501 "Safe version of standard `forward-sexp'.
1502 When at end of sexp (i.e. looking at a opening/closing paren)
1503 skips it instead of throwing an error. With positive ARG move
1504 forward only one sexp, else move backwards."
1505 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1507 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1509 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1511 (python-nav--lisp-forward-sexp arg
)
1513 (while (and (funcall search-fn paren-regexp nil t
)
1514 (python-syntax-context 'paren
)))))))
1516 (defun python-nav--forward-sexp (&optional dir safe
)
1517 "Move to forward sexp.
1518 With positive optional argument DIR direction move forward, else
1519 backwards. When optional argument SAFE is non-nil do not throw
1520 errors when at end of sexp, skip it instead."
1521 (setq dir
(or dir
1))
1523 (let* ((forward-p (if (> dir
0)
1524 (and (setq dir
1) t
)
1525 (and (setq dir -
1) nil
)))
1526 (context-type (python-syntax-context-type)))
1528 ((memq context-type
'(string comment
))
1529 ;; Inside of a string, get out of it.
1530 (let ((forward-sexp-function))
1531 (forward-sexp dir
)))
1532 ((or (eq context-type
'paren
)
1533 (and forward-p
(looking-at (python-rx open-paren
)))
1534 (and (not forward-p
)
1535 (eq (syntax-class (syntax-after (1- (point))))
1536 (car (string-to-syntax ")")))))
1537 ;; Inside a paren or looking at it, lisp knows what to do.
1539 (python-nav--lisp-forward-sexp-safe dir
)
1540 (python-nav--lisp-forward-sexp dir
)))
1542 ;; This part handles the lispy feel of
1543 ;; `python-nav-forward-sexp'. Knowing everything about the
1544 ;; current context and the context of the next sexp tries to
1545 ;; follow the lisp sexp motion commands in a symmetric manner.
1548 ((python-info-beginning-of-block-p) 'block-start
)
1549 ((python-info-end-of-block-p) 'block-end
)
1550 ((python-info-beginning-of-statement-p) 'statement-start
)
1551 ((python-info-end-of-statement-p) 'statement-end
)))
1555 (python-nav--lisp-forward-sexp-safe dir
)
1556 (python-nav--lisp-forward-sexp dir
))
1560 (goto-char next-sexp-pos
)
1562 ((python-info-beginning-of-block-p) 'block-start
)
1563 ((python-info-end-of-block-p) 'block-end
)
1564 ((python-info-beginning-of-statement-p) 'statement-start
)
1565 ((python-info-end-of-statement-p) 'statement-end
)
1566 ((python-info-statement-starts-block-p) 'starts-block
)
1567 ((python-info-statement-ends-block-p) 'ends-block
)))))
1569 (cond ((and (not (eobp))
1570 (python-info-current-line-empty-p))
1571 (python-util-forward-comment dir
)
1572 (python-nav--forward-sexp dir
))
1573 ((eq context
'block-start
)
1574 (python-nav-end-of-block))
1575 ((eq context
'statement-start
)
1576 (python-nav-end-of-statement))
1577 ((and (memq context
'(statement-end block-end
))
1578 (eq next-sexp-context
'ends-block
))
1579 (goto-char next-sexp-pos
)
1580 (python-nav-end-of-block))
1581 ((and (memq context
'(statement-end block-end
))
1582 (eq next-sexp-context
'starts-block
))
1583 (goto-char next-sexp-pos
)
1584 (python-nav-end-of-block))
1585 ((memq context
'(statement-end block-end
))
1586 (goto-char next-sexp-pos
)
1587 (python-nav-end-of-statement))
1588 (t (goto-char next-sexp-pos
)))
1589 (cond ((and (not (bobp))
1590 (python-info-current-line-empty-p))
1591 (python-util-forward-comment dir
)
1592 (python-nav--forward-sexp dir
))
1593 ((eq context
'block-end
)
1594 (python-nav-beginning-of-block))
1595 ((eq context
'statement-end
)
1596 (python-nav-beginning-of-statement))
1597 ((and (memq context
'(statement-start block-start
))
1598 (eq next-sexp-context
'starts-block
))
1599 (goto-char next-sexp-pos
)
1600 (python-nav-beginning-of-block))
1601 ((and (memq context
'(statement-start block-start
))
1602 (eq next-sexp-context
'ends-block
))
1603 (goto-char next-sexp-pos
)
1604 (python-nav-beginning-of-block))
1605 ((memq context
'(statement-start block-start
))
1606 (goto-char next-sexp-pos
)
1607 (python-nav-beginning-of-statement))
1608 (t (goto-char next-sexp-pos
))))))))))
1610 (defun python-nav-forward-sexp (&optional arg
)
1611 "Move forward across expressions.
1612 With ARG, do it that many times. Negative arg -N means move
1615 (or arg
(setq arg
1))
1617 (python-nav--forward-sexp 1)
1618 (setq arg
(1- arg
)))
1620 (python-nav--forward-sexp -
1)
1621 (setq arg
(1+ arg
))))
1623 (defun python-nav-backward-sexp (&optional arg
)
1624 "Move backward across expressions.
1625 With ARG, do it that many times. Negative arg -N means move
1628 (or arg
(setq arg
1))
1629 (python-nav-forward-sexp (- arg
)))
1631 (defun python-nav-forward-sexp-safe (&optional arg
)
1632 "Move forward safely across expressions.
1633 With ARG, do it that many times. Negative arg -N means move
1636 (or arg
(setq arg
1))
1638 (python-nav--forward-sexp 1 t
)
1639 (setq arg
(1- arg
)))
1641 (python-nav--forward-sexp -
1 t
)
1642 (setq arg
(1+ arg
))))
1644 (defun python-nav-backward-sexp-safe (&optional arg
)
1645 "Move backward safely across expressions.
1646 With ARG, do it that many times. Negative arg -N means move
1649 (or arg
(setq arg
1))
1650 (python-nav-forward-sexp-safe (- arg
)))
1652 (defun python-nav--up-list (&optional dir
)
1653 "Internal implementation of `python-nav-up-list'.
1654 DIR is always 1 or -1 and comes sanitized from
1655 `python-nav-up-list' calls."
1656 (let ((context (python-syntax-context-type))
1657 (forward-p (> dir
0)))
1659 ((memq context
'(string comment
)))
1660 ((eq context
'paren
)
1661 (let ((forward-sexp-function))
1663 ((and forward-p
(python-info-end-of-block-p))
1664 (let ((parent-end-pos
1666 (let ((indentation (and
1667 (python-nav-beginning-of-block)
1668 (current-indentation))))
1669 (while (and indentation
1671 (>= (current-indentation) indentation
)
1672 (python-nav-backward-block)))
1673 (python-nav-end-of-block)))))
1674 (and (> (or parent-end-pos
(point)) (point))
1675 (goto-char parent-end-pos
))))
1676 (forward-p (python-nav-end-of-block))
1677 ((and (not forward-p
)
1678 (> (current-indentation) 0)
1679 (python-info-beginning-of-block-p))
1680 (let ((prev-block-pos
1682 (let ((indentation (current-indentation)))
1683 (while (and (python-nav-backward-block)
1684 (>= (current-indentation) indentation
))))
1686 (and (> (point) prev-block-pos
)
1687 (goto-char prev-block-pos
))))
1688 ((not forward-p
) (python-nav-beginning-of-block)))))
1690 (defun python-nav-up-list (&optional arg
)
1691 "Move forward out of one level of parentheses (or blocks).
1692 With ARG, do this that many times.
1693 A negative argument means move backward but still to a less deep spot.
1694 This command assumes point is not in a string or comment."
1696 (or arg
(setq arg
1))
1698 (python-nav--up-list 1)
1699 (setq arg
(1- arg
)))
1701 (python-nav--up-list -
1)
1702 (setq arg
(1+ arg
))))
1704 (defun python-nav-backward-up-list (&optional arg
)
1705 "Move backward out of one level of parentheses (or blocks).
1706 With ARG, do this that many times.
1707 A negative argument means move forward but still to a less deep spot.
1708 This command assumes point is not in a string or comment."
1710 (or arg
(setq arg
1))
1711 (python-nav-up-list (- arg
)))
1713 (defun python-nav-if-name-main ()
1714 "Move point at the beginning the __main__ block.
1715 When \"if __name__ == '__main__':\" is found returns its
1716 position, else returns nil."
1718 (let ((point (point))
1719 (found (catch 'found
1720 (goto-char (point-min))
1721 (while (re-search-forward
1722 (python-rx line-start
1724 "__name__" (+ space
)
1726 (group-n 1 (or ?
\" ?
\'))
1727 "__main__" (backref 1) (* space
) ":")
1729 (when (not (python-syntax-context-type))
1731 (throw 'found t
))))))
1734 (ignore (goto-char point
)))))
1737 ;;; Shell integration
1739 (defcustom python-shell-buffer-name
"Python"
1740 "Default buffer name for Python interpreter."
1745 (defcustom python-shell-interpreter
"python"
1746 "Default Python interpreter for shell."
1750 (defcustom python-shell-internal-buffer-name
"Python Internal"
1751 "Default buffer name for the Internal Python interpreter."
1756 (defcustom python-shell-interpreter-args
"-i"
1757 "Default arguments for the Python interpreter."
1761 (defcustom python-shell-interpreter-interactive-arg
"-i"
1762 "Interpreter argument to force it to run interactively."
1766 (defcustom python-shell-prompt-detect-enabled t
1767 "Non-nil enables autodetection of interpreter prompts."
1772 (defcustom python-shell-prompt-detect-failure-warning t
1773 "Non-nil enables warnings when detection of prompts fail."
1778 (defcustom python-shell-prompt-input-regexps
1779 '(">>> " "\\.\\.\\. " ; Python
1780 "In \\[[0-9]+\\]: " ; IPython
1781 " \\.\\.\\.: " ; IPython
1782 ;; Using ipdb outside IPython may fail to cleanup and leave static
1783 ;; IPython prompts activated, this adds some safeguard for that.
1784 "In : " "\\.\\.\\.: ")
1785 "List of regular expressions matching input prompts."
1786 :type
'(repeat string
)
1789 (defcustom python-shell-prompt-output-regexps
1791 "Out\\[[0-9]+\\]: " ; IPython
1792 "Out :") ; ipdb safeguard
1793 "List of regular expressions matching output prompts."
1794 :type
'(repeat string
)
1797 (defcustom python-shell-prompt-regexp
">>> "
1798 "Regular expression matching top level input prompt of Python shell.
1799 It should not contain a caret (^) at the beginning."
1802 (defcustom python-shell-prompt-block-regexp
"\\.\\.\\. "
1803 "Regular expression matching block input prompt of Python shell.
1804 It should not contain a caret (^) at the beginning."
1807 (defcustom python-shell-prompt-output-regexp
""
1808 "Regular expression matching output prompt of Python shell.
1809 It should not contain a caret (^) at the beginning."
1812 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1813 "Regular expression matching pdb input prompt of Python shell.
1814 It should not contain a caret (^) at the beginning."
1817 (define-obsolete-variable-alias
1818 'python-shell-enable-font-lock
'python-shell-font-lock-enable
"25.1")
1820 (defcustom python-shell-font-lock-enable t
1821 "Should syntax highlighting be enabled in the Python shell buffer?
1822 Restart the Python shell after changing this variable for it to take effect."
1827 (defcustom python-shell-process-environment nil
1828 "List of environment variables for Python shell.
1829 This variable follows the same rules as `process-environment'
1830 since it merges with it before the process creation routines are
1831 called. When this variable is nil, the Python shell is run with
1832 the default `process-environment'."
1833 :type
'(repeat string
)
1837 (defcustom python-shell-extra-pythonpaths nil
1838 "List of extra pythonpaths for Python shell.
1839 The values of this variable are added to the existing value of
1840 PYTHONPATH in the `process-environment' variable."
1841 :type
'(repeat string
)
1845 (defcustom python-shell-exec-path nil
1846 "List of path to search for binaries.
1847 This variable follows the same rules as `exec-path' since it
1848 merges with it before the process creation routines are called.
1849 When this variable is nil, the Python shell is run with the
1850 default `exec-path'."
1851 :type
'(repeat string
)
1855 (defcustom python-shell-virtualenv-root nil
1856 "Path to virtualenv root.
1857 This variable, when set to a string, makes the values stored in
1858 `python-shell-process-environment' and `python-shell-exec-path'
1859 to be modified properly so shells are started with the specified
1861 :type
'(choice (const nil
) string
)
1865 (define-obsolete-variable-alias
1866 'python-shell-virtualenv-path
'python-shell-virtualenv-root
"25.1")
1868 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1869 python-ffap-setup-code
1870 python-eldoc-setup-code
)
1871 "List of code run by `python-shell-send-setup-codes'."
1872 :type
'(repeat symbol
)
1876 (defcustom python-shell-compilation-regexp-alist
1877 `((,(rx line-start
(1+ (any " \t")) "File \""
1878 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1879 "\", line " (group (1+ digit
)))
1881 (,(rx " in file " (group (1+ not-newline
)) " on line "
1884 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1885 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1887 "`compilation-error-regexp-alist' for inferior Python."
1888 :type
'(alist string
)
1891 (defvar python-shell--prompt-calculated-input-regexp nil
1892 "Calculated input prompt regexp for inferior python shell.
1893 Do not set this variable directly, instead use
1894 `python-shell-prompt-set-calculated-regexps'.")
1896 (defvar python-shell--prompt-calculated-output-regexp nil
1897 "Calculated output prompt regexp for inferior python shell.
1898 Do not set this variable directly, instead use
1899 `python-shell-set-prompt-regexp'.")
1901 (defun python-shell-prompt-detect ()
1902 "Detect prompts for the current `python-shell-interpreter'.
1903 When prompts can be retrieved successfully from the
1904 `python-shell-interpreter' run with
1905 `python-shell-interpreter-interactive-arg', returns a list of
1906 three elements, where the first two are input prompts and the
1907 last one is an output prompt. When no prompts can be detected
1908 and `python-shell-prompt-detect-failure-warning' is non-nil,
1909 shows a warning with instructions to avoid hangs and returns nil.
1910 When `python-shell-prompt-detect-enabled' is nil avoids any
1911 detection and just returns nil."
1912 (when python-shell-prompt-detect-enabled
1913 (let* ((process-environment (python-shell-calculate-process-environment))
1914 (exec-path (python-shell-calculate-exec-path))
1917 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1918 ;; JSON is built manually for compatibility
1919 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1924 ;; TODO: improve error handling by using
1925 ;; `condition-case' and displaying the error message to
1926 ;; the user in the no-prompts warning.
1928 (let ((code-file (python-shell--save-temp-file code
)))
1929 ;; Use `process-file' as it is remote-host friendly.
1931 python-shell-interpreter
1935 python-shell-interpreter-interactive-arg
)
1937 (delete-file code-file
)))
1941 (dolist (line (split-string output
"\n" t
))
1943 ;; Check if current line is a valid JSON array
1944 (and (string= (substring line
0 2) "[\"")
1946 ;; Return prompts as a list, not vector
1947 (append (json-read-from-string line
) nil
)))))
1948 ;; The list must contain 3 strings, where the first
1949 ;; is the input prompt, the second is the block
1950 ;; prompt and the last one is the output prompt. The
1951 ;; input prompt is the only one that can't be empty.
1952 (when (and (= (length res
) 3)
1953 (cl-every #'stringp res
)
1954 (not (string= (car res
) "")))
1955 (throw 'prompts res
))))
1957 (when (and (not prompts
)
1958 python-shell-prompt-detect-failure-warning
)
1960 '(python python-shell-prompt-regexp
)
1963 "Python shell prompts cannot be detected.\n"
1964 "If your emacs session hangs when starting python shells\n"
1965 "recover with `keyboard-quit' and then try fixing the\n"
1966 "interactive flag for your interpreter by adjusting the\n"
1967 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1968 "matching shell prompts in the directory-local friendly vars:\n"
1969 " + `python-shell-prompt-regexp'\n"
1970 " + `python-shell-prompt-block-regexp'\n"
1971 " + `python-shell-prompt-output-regexp'\n"
1972 "Or alternatively in:\n"
1973 " + `python-shell-prompt-input-regexps'\n"
1974 " + `python-shell-prompt-output-regexps'")))
1977 (defun python-shell-prompt-validate-regexps ()
1978 "Validate all user provided regexps for prompts.
1979 Signals `user-error' if any of these vars contain invalid
1980 regexps: `python-shell-prompt-regexp',
1981 `python-shell-prompt-block-regexp',
1982 `python-shell-prompt-pdb-regexp',
1983 `python-shell-prompt-output-regexp',
1984 `python-shell-prompt-input-regexps',
1985 `python-shell-prompt-output-regexps'."
1986 (dolist (symbol (list 'python-shell-prompt-input-regexps
1987 'python-shell-prompt-output-regexps
1988 'python-shell-prompt-regexp
1989 'python-shell-prompt-block-regexp
1990 'python-shell-prompt-pdb-regexp
1991 'python-shell-prompt-output-regexp
))
1992 (dolist (regexp (let ((regexps (symbol-value symbol
)))
1996 (when (not (python-util-valid-regexp-p regexp
))
1997 (user-error "Invalid regexp %s in `%s'"
2000 (defun python-shell-prompt-set-calculated-regexps ()
2001 "Detect and set input and output prompt regexps.
2002 Build and set the values for `python-shell-input-prompt-regexp'
2003 and `python-shell-output-prompt-regexp' using the values from
2004 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2005 `python-shell-prompt-pdb-regexp',
2006 `python-shell-prompt-output-regexp',
2007 `python-shell-prompt-input-regexps',
2008 `python-shell-prompt-output-regexps' and detected prompts from
2009 `python-shell-prompt-detect'."
2010 (when (not (and python-shell--prompt-calculated-input-regexp
2011 python-shell--prompt-calculated-output-regexp
))
2012 (let* ((detected-prompts (python-shell-prompt-detect))
2014 (output-prompts nil
)
2018 (mapconcat #'identity
2021 (let ((length-a (length a
))
2022 (length-b (length b
)))
2023 (if (= length-a length-b
)
2025 (> (length a
) (length b
))))))
2028 ;; Validate ALL regexps
2029 (python-shell-prompt-validate-regexps)
2030 ;; Collect all user defined input prompts
2031 (dolist (prompt (append python-shell-prompt-input-regexps
2032 (list python-shell-prompt-regexp
2033 python-shell-prompt-block-regexp
2034 python-shell-prompt-pdb-regexp
)))
2035 (cl-pushnew prompt input-prompts
:test
#'string
=))
2036 ;; Collect all user defined output prompts
2037 (dolist (prompt (cons python-shell-prompt-output-regexp
2038 python-shell-prompt-output-regexps
))
2039 (cl-pushnew prompt output-prompts
:test
#'string
=))
2040 ;; Collect detected prompts if any
2041 (when detected-prompts
2042 (dolist (prompt (butlast detected-prompts
))
2043 (setq prompt
(regexp-quote prompt
))
2044 (cl-pushnew prompt input-prompts
:test
#'string
=))
2045 (cl-pushnew (regexp-quote
2046 (car (last detected-prompts
)))
2047 output-prompts
:test
#'string
=))
2048 ;; Set input and output prompt regexps from collected prompts
2049 (setq python-shell--prompt-calculated-input-regexp
2050 (funcall build-regexp input-prompts
)
2051 python-shell--prompt-calculated-output-regexp
2052 (funcall build-regexp output-prompts
)))))
2054 (defun python-shell-get-process-name (dedicated)
2055 "Calculate the appropriate process name for inferior Python process.
2056 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2057 returns a string with the form
2058 `python-shell-buffer-name'[variable `buffer-file-name'] else
2059 returns the value of `python-shell-buffer-name'."
2063 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
2064 (format "%s" python-shell-buffer-name
))))
2067 (defun python-shell-internal-get-process-name ()
2068 "Calculate the appropriate process name for Internal Python process.
2069 The name is calculated from `python-shell-global-buffer-name' and
2070 a hash of all relevant global shell settings in order to ensure
2071 uniqueness for different types of configurations."
2073 python-shell-internal-buffer-name
2076 python-shell-interpreter
2077 python-shell-interpreter-args
2078 python-shell--prompt-calculated-input-regexp
2079 python-shell--prompt-calculated-output-regexp
2080 (mapconcat #'symbol-value python-shell-setup-codes
"")
2081 (mapconcat #'identity python-shell-process-environment
"")
2082 (mapconcat #'identity python-shell-extra-pythonpaths
"")
2083 (mapconcat #'identity python-shell-exec-path
"")
2084 (or python-shell-virtualenv-root
"")
2085 (mapconcat #'identity python-shell-exec-path
"")))))
2087 (defun python-shell-calculate-command ()
2088 "Calculate the string used to execute the inferior Python process."
2089 (let ((exec-path (python-shell-calculate-exec-path)))
2090 ;; `exec-path' gets tweaked so that virtualenv's specific
2091 ;; `python-shell-interpreter' absolute path can be found by
2092 ;; `executable-find'.
2094 (executable-find python-shell-interpreter
)
2095 python-shell-interpreter-args
)))
2097 (define-obsolete-function-alias
2098 'python-shell-parse-command
2099 #'python-shell-calculate-command
"25.1")
2101 (defun python-shell-calculate-pythonpath ()
2102 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2103 (let ((pythonpath (getenv "PYTHONPATH"))
2104 (extra (mapconcat 'identity
2105 python-shell-extra-pythonpaths
2108 (concat extra path-separator pythonpath
)
2111 (defun python-shell-calculate-process-environment ()
2112 "Calculate process environment given `python-shell-virtualenv-root'."
2113 (let ((process-environment (append
2114 python-shell-process-environment
2115 process-environment nil
))
2116 (virtualenv (if python-shell-virtualenv-root
2117 (directory-file-name python-shell-virtualenv-root
)
2119 (when python-shell-extra-pythonpaths
2120 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2121 (if (not virtualenv
)
2123 (setenv "PYTHONHOME" nil
)
2124 (setenv "PATH" (format "%s/bin%s%s"
2125 virtualenv path-separator
2126 (or (getenv "PATH") "")))
2127 (setenv "VIRTUAL_ENV" virtualenv
))
2128 process-environment
))
2130 (defun python-shell-calculate-exec-path ()
2131 "Calculate exec path given `python-shell-virtualenv-root'."
2133 ;; Use nil as the tail so that the list is a full copy,
2134 ;; this is a paranoid safeguard for side-effects.
2135 python-shell-exec-path exec-path nil
)))
2136 (if (not python-shell-virtualenv-root
)
2138 (cons (expand-file-name "bin" python-shell-virtualenv-root
)
2141 (defvar python-shell--package-depth
10)
2143 (defun python-shell-package-enable (directory package
)
2144 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2146 (let* ((dir (expand-file-name
2147 (read-directory-name
2149 (file-name-directory
2150 (or (buffer-file-name) default-directory
)))))
2151 (name (completing-read
2153 (python-util-list-packages
2154 dir python-shell--package-depth
))))
2156 (python-shell-send-string
2159 "import os.path;import sys;"
2160 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2161 "__package__ = '''%s''';"
2163 directory package package
)
2164 (python-shell-get-process)))
2166 (defun python-shell-accept-process-output (process &optional timeout regexp
)
2167 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2168 Optional argument TIMEOUT is the timeout argument to
2169 `accept-process-output' calls. Optional argument REGEXP
2170 overrides the regexp to match the end of output, defaults to
2171 `comint-prompt-regexp.'. Returns non-nil when output was
2174 This utility is useful in situations where the output may be
2175 received in chunks, since `accept-process-output' gives no
2176 guarantees they will be grabbed in a single call. An example use
2177 case for this would be the CPython shell start-up, where the
2178 banner and the initial prompt are received separately."
2179 (let ((regexp (or regexp comint-prompt-regexp
)))
2182 (when (not (accept-process-output process timeout
))
2184 (when (looking-back regexp
)
2185 (throw 'found t
))))))
2187 (defun python-shell-comint-end-of-output-p (output)
2188 "Return non-nil if OUTPUT is ends with input prompt."
2190 ;; XXX: It seems on OSX an extra carriage return is attached
2191 ;; at the end of output, this handles that too.
2194 ;; Remove initial caret from calculated regexp
2195 (replace-regexp-in-string
2196 (rx string-start ?^
) ""
2197 python-shell--prompt-calculated-input-regexp
)
2201 (define-obsolete-function-alias
2202 'python-comint-output-filter-function
2203 'ansi-color-filter-apply
2206 (defun python-comint-postoutput-scroll-to-bottom (output)
2207 "Faster version of `comint-postoutput-scroll-to-bottom'.
2208 Avoids `recenter' calls until OUTPUT is completely sent."
2209 (when (and (not (string= "" output
))
2210 (python-shell-comint-end-of-output-p
2211 (ansi-color-filter-apply output
)))
2212 (comint-postoutput-scroll-to-bottom output
))
2215 (defvar python-shell--parent-buffer nil
)
2217 (defmacro python-shell-with-shell-buffer
(&rest body
)
2218 "Execute the forms in BODY with the shell buffer temporarily current.
2219 Signals an error if no shell buffer is available for current buffer."
2220 (declare (indent 0) (debug t
))
2221 (let ((shell-buffer (make-symbol "shell-buffer")))
2222 `(let ((,shell-buffer
(python-shell-get-buffer)))
2223 (when (not ,shell-buffer
)
2224 (error "No inferior Python buffer available."))
2225 (with-current-buffer ,shell-buffer
2228 (defvar python-shell--font-lock-buffer nil
)
2230 (defun python-shell-font-lock-get-or-create-buffer ()
2231 "Get or create a font-lock buffer for current inferior process."
2232 (python-shell-with-shell-buffer
2233 (if python-shell--font-lock-buffer
2234 python-shell--font-lock-buffer
2236 (process-name (get-buffer-process (current-buffer)))))
2237 (generate-new-buffer
2238 (format "*%s-font-lock*" process-name
))))))
2240 (defun python-shell-font-lock-kill-buffer ()
2241 "Kill the font-lock buffer safely."
2242 (python-shell-with-shell-buffer
2243 (when (and python-shell--font-lock-buffer
2244 (buffer-live-p python-shell--font-lock-buffer
))
2245 (kill-buffer python-shell--font-lock-buffer
)
2246 (when (derived-mode-p 'inferior-python-mode
)
2247 (setq python-shell--font-lock-buffer nil
)))))
2249 (defmacro python-shell-font-lock-with-font-lock-buffer
(&rest body
)
2250 "Execute the forms in BODY in the font-lock buffer.
2251 The value returned is the value of the last form in BODY. See
2252 also `with-current-buffer'."
2253 (declare (indent 0) (debug t
))
2254 `(python-shell-with-shell-buffer
2255 (save-current-buffer
2256 (when (not (and python-shell--font-lock-buffer
2257 (get-buffer python-shell--font-lock-buffer
)))
2258 (setq python-shell--font-lock-buffer
2259 (python-shell-font-lock-get-or-create-buffer)))
2260 (set-buffer python-shell--font-lock-buffer
)
2261 (set (make-local-variable 'delay-mode-hooks
) t
)
2262 (let ((python-indent-guess-indent-offset nil
))
2263 (when (not (derived-mode-p 'python-mode
))
2267 (defun python-shell-font-lock-cleanup-buffer ()
2268 "Cleanup the font-lock buffer.
2269 Provided as a command because this might be handy if something
2270 goes wrong and syntax highlighting in the shell gets messed up."
2272 (python-shell-with-shell-buffer
2273 (python-shell-font-lock-with-font-lock-buffer
2274 (delete-region (point-min) (point-max)))))
2276 (defun python-shell-font-lock-comint-output-filter-function (output)
2277 "Clean up the font-lock buffer after any OUTPUT."
2278 (when (and (not (string= "" output
))
2279 ;; Is end of output and is not just a prompt.
2281 (python-shell-comint-end-of-output-p
2282 (ansi-color-filter-apply output
))
2284 ;; If output is other than an input prompt then "real" output has
2285 ;; been received and the font-lock buffer must be cleaned up.
2286 (python-shell-font-lock-cleanup-buffer))
2289 (defun python-shell-font-lock-post-command-hook ()
2290 "Fontifies current line in shell buffer."
2291 (if (eq this-command
'comint-send-input
)
2292 ;; Add a newline when user sends input as this may be a block.
2293 (python-shell-font-lock-with-font-lock-buffer
2294 (goto-char (line-end-position))
2296 (when (and (python-util-comint-last-prompt)
2297 (> (point) (cdr (python-util-comint-last-prompt))))
2298 (let ((input (buffer-substring-no-properties
2299 (cdr (python-util-comint-last-prompt)) (point-max)))
2300 (old-input (python-shell-font-lock-with-font-lock-buffer
2301 (buffer-substring-no-properties
2302 (line-beginning-position) (point-max))))
2303 (current-point (point))
2304 (buffer-undo-list t
))
2305 ;; When input hasn't changed, do nothing.
2306 (when (not (string= input old-input
))
2307 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2309 (python-shell-font-lock-with-font-lock-buffer
2310 (delete-region (line-beginning-position)
2311 (line-end-position))
2313 ;; Ensure buffer is fontified, keeping it
2314 ;; compatible with Emacs < 24.4.
2315 (if (fboundp 'font-lock-ensure
)
2316 (funcall 'font-lock-ensure
)
2317 (font-lock-default-fontify-buffer))
2318 ;; Replace FACE text properties with FONT-LOCK-FACE so
2319 ;; they are not overwritten by comint buffer's font lock.
2320 (python-util-text-properties-replace-name
2321 'face
'font-lock-face
)
2322 (buffer-substring (line-beginning-position)
2323 (line-end-position))))
2324 (goto-char current-point
))))))
2326 (defun python-shell-font-lock-turn-on (&optional msg
)
2327 "Turn on shell font-lock.
2328 With argument MSG show activation message."
2330 (python-shell-with-shell-buffer
2331 (python-shell-font-lock-kill-buffer)
2332 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2333 (add-hook 'post-command-hook
2334 #'python-shell-font-lock-post-command-hook nil
'local
)
2335 (add-hook 'kill-buffer-hook
2336 #'python-shell-font-lock-kill-buffer nil
'local
)
2337 (add-hook 'comint-output-filter-functions
2338 #'python-shell-font-lock-comint-output-filter-function
2341 (message "Shell font-lock is enabled"))))
2343 (defun python-shell-font-lock-turn-off (&optional msg
)
2344 "Turn off shell font-lock.
2345 With argument MSG show deactivation message."
2347 (python-shell-with-shell-buffer
2348 (python-shell-font-lock-kill-buffer)
2349 (when (python-util-comint-last-prompt)
2350 ;; Cleanup current fontification
2351 (remove-text-properties
2352 (cdr (python-util-comint-last-prompt))
2354 '(face nil font-lock-face nil
)))
2355 (set (make-local-variable 'python-shell--font-lock-buffer
) nil
)
2356 (remove-hook 'post-command-hook
2357 #'python-shell-font-lock-post-command-hook
'local
)
2358 (remove-hook 'kill-buffer-hook
2359 #'python-shell-font-lock-kill-buffer
'local
)
2360 (remove-hook 'comint-output-filter-functions
2361 #'python-shell-font-lock-comint-output-filter-function
2364 (message "Shell font-lock is disabled"))))
2366 (defun python-shell-font-lock-toggle (&optional msg
)
2367 "Toggle font-lock for shell.
2368 With argument MSG show activation/deactivation message."
2370 (python-shell-with-shell-buffer
2371 (set (make-local-variable 'python-shell-font-lock-enable
)
2372 (not python-shell-font-lock-enable
))
2373 (if python-shell-font-lock-enable
2374 (python-shell-font-lock-turn-on msg
)
2375 (python-shell-font-lock-turn-off msg
))
2376 python-shell-font-lock-enable
))
2378 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
2379 "Major mode for Python inferior process.
2380 Runs a Python interpreter as a subprocess of Emacs, with Python
2381 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2382 and `python-shell-interpreter-args' control which Python
2383 interpreter is run. Variables
2384 `python-shell-prompt-regexp',
2385 `python-shell-prompt-output-regexp',
2386 `python-shell-prompt-block-regexp',
2387 `python-shell-font-lock-enable',
2388 `python-shell-completion-setup-code',
2389 `python-shell-completion-string-code',
2390 `python-eldoc-setup-code', `python-eldoc-string-code',
2391 `python-ffap-setup-code' and `python-ffap-string-code' can
2392 customize this mode for different Python interpreters.
2394 This mode resets `comint-output-filter-functions' locally, so you
2395 may want to re-add custom functions to it using the
2396 `inferior-python-mode-hook'.
2398 You can also add additional setup code to be run at
2399 initialization of the interpreter via `python-shell-setup-codes'
2402 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2403 (let ((interpreter python-shell-interpreter
)
2404 (args python-shell-interpreter-args
))
2405 (when python-shell--parent-buffer
2406 (python-util-clone-local-variables python-shell--parent-buffer
))
2407 ;; Users can override default values for these vars when calling
2408 ;; `run-python'. This ensures new values let-bound in
2409 ;; `python-shell-make-comint' are locally set.
2410 (set (make-local-variable 'python-shell-interpreter
) interpreter
)
2411 (set (make-local-variable 'python-shell-interpreter-args
) args
))
2412 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp
) nil
)
2413 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp
) nil
)
2414 (python-shell-prompt-set-calculated-regexps)
2415 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
2416 comint-prompt-read-only t
)
2417 (setq mode-line-process
'(":%s"))
2418 (set (make-local-variable 'comint-output-filter-functions
)
2419 '(ansi-color-process-output
2420 python-pdbtrack-comint-output-filter-function
2421 python-comint-postoutput-scroll-to-bottom
))
2422 (set (make-local-variable 'compilation-error-regexp-alist
)
2423 python-shell-compilation-regexp-alist
)
2424 (add-hook 'completion-at-point-functions
2425 #'python-shell-completion-at-point nil
'local
)
2426 (define-key inferior-python-mode-map
"\t"
2427 'python-shell-completion-complete-or-indent
)
2428 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
2429 (make-local-variable 'python-pdbtrack-tracked-buffer
)
2430 (make-local-variable 'python-shell-internal-last-output
)
2431 (when python-shell-font-lock-enable
2432 (python-shell-font-lock-turn-on))
2433 (compilation-shell-minor-mode 1)
2434 (python-shell-accept-process-output
2435 (get-buffer-process (current-buffer))))
2437 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
2438 "Create a Python shell comint buffer.
2439 CMD is the Python command to be executed and PROC-NAME is the
2440 process name the comint buffer will get. After the comint buffer
2441 is created the `inferior-python-mode' is activated. When
2442 optional argument POP is non-nil the buffer is shown. When
2443 optional argument INTERNAL is non-nil this process is run on a
2444 buffer with a name that starts with a space, following the Emacs
2445 convention for temporary/internal buffers, and also makes sure
2446 the user is not queried for confirmation when the process is
2449 (let* ((proc-buffer-name
2450 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
2451 (process-environment (python-shell-calculate-process-environment))
2452 (exec-path (python-shell-calculate-exec-path)))
2453 (when (not (comint-check-proc proc-buffer-name
))
2454 (let* ((cmdlist (split-string-and-unquote cmd
))
2455 (interpreter (car cmdlist
))
2456 (args (cdr cmdlist
))
2457 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2458 interpreter nil args
))
2459 (python-shell--parent-buffer (current-buffer))
2460 (process (get-buffer-process buffer
))
2461 ;; As the user may have overridden default values for
2462 ;; these vars on `run-python', let-binding them allows
2463 ;; to have the new right values in all setup code
2464 ;; that's is done in `inferior-python-mode', which is
2465 ;; important, especially for prompt detection.
2466 (python-shell-interpreter interpreter
)
2467 (python-shell-interpreter-args
2468 (mapconcat #'identity args
" ")))
2469 (with-current-buffer buffer
2470 (inferior-python-mode))
2471 (and pop
(pop-to-buffer buffer t
))
2472 (and internal
(set-process-query-on-exit-flag process nil
))))
2476 (defun run-python (&optional cmd dedicated show
)
2477 "Run an inferior Python process.
2478 Input and output via buffer named after
2479 `python-shell-buffer-name'. If there is a process already
2480 running in that buffer, just switch to it.
2482 Argument CMD defaults to `python-shell-calculate-command' return
2483 value. When called interactively with `prefix-arg', it allows
2484 the user to edit such value and choose whether the interpreter
2485 should be DEDICATED for the current buffer. When numeric prefix
2486 arg is other than 0 or 4 do not SHOW.
2488 Runs the hook `inferior-python-mode-hook' after
2489 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2490 process buffer for a list of commands.)"
2492 (if current-prefix-arg
2494 (read-shell-command "Run Python: " (python-shell-calculate-command))
2495 (y-or-n-p "Make dedicated process? ")
2496 (= (prefix-numeric-value current-prefix-arg
) 4))
2497 (list (python-shell-calculate-command) nil t
)))
2498 (python-shell-make-comint
2499 (or cmd
(python-shell-calculate-command))
2500 (python-shell-get-process-name dedicated
) show
)
2503 (defun run-python-internal ()
2504 "Run an inferior Internal Python process.
2505 Input and output via buffer named after
2506 `python-shell-internal-buffer-name' and what
2507 `python-shell-internal-get-process-name' returns.
2509 This new kind of shell is intended to be used for generic
2510 communication related to defined configurations; the main
2511 difference with global or dedicated shells is that these ones are
2512 attached to a configuration, not a buffer. This means that can
2513 be used for example to retrieve the sys.path and other stuff,
2514 without messing with user shells. Note that
2515 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2516 are set to nil for these shells, so setup codes are not sent at
2518 (let ((python-shell-font-lock-enable nil
)
2519 (inferior-python-mode-hook nil
))
2521 (python-shell-make-comint
2522 (python-shell-calculate-command)
2523 (python-shell-internal-get-process-name) nil t
))))
2525 (defun python-shell-get-buffer ()
2526 "Return inferior Python buffer for current buffer.
2527 If current buffer is in `inferior-python-mode', return it."
2528 (if (derived-mode-p 'inferior-python-mode
)
2530 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2531 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2532 (global-proc-name (python-shell-get-process-name nil
))
2533 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2534 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2535 (global-running (comint-check-proc global-proc-buffer-name
)))
2536 ;; Always prefer dedicated
2537 (or (and dedicated-running dedicated-proc-buffer-name
)
2538 (and global-running global-proc-buffer-name
)))))
2540 (defun python-shell-get-process ()
2541 "Return inferior Python process for current buffer."
2542 (get-buffer-process (python-shell-get-buffer)))
2544 (defun python-shell-get-or-create-process (&optional cmd dedicated show
)
2545 "Get or create an inferior Python process for current buffer and return it.
2546 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2547 are used to start the shell. If those arguments are not
2548 provided, `run-python' is called interactively and the user will
2549 be asked for their values."
2550 (let ((shell-process (python-shell-get-process)))
2551 (when (not shell-process
)
2553 ;; XXX: Refactor code such that calling `run-python'
2554 ;; interactively is not needed anymore.
2555 (call-interactively 'run-python
)
2556 (run-python cmd dedicated show
)))
2557 (or shell-process
(python-shell-get-process))))
2559 (defvar python-shell-internal-buffer nil
2560 "Current internal shell buffer for the current buffer.
2561 This is really not necessary at all for the code to work but it's
2562 there for compatibility with CEDET.")
2564 (defvar python-shell-internal-last-output nil
2565 "Last output captured by the internal shell.
2566 This is really not necessary at all for the code to work but it's
2567 there for compatibility with CEDET.")
2569 (defun python-shell-internal-get-or-create-process ()
2570 "Get or create an inferior Internal Python process."
2571 (let* ((proc-name (python-shell-internal-get-process-name))
2572 (proc-buffer-name (format " *%s*" proc-name
)))
2573 (when (not (process-live-p proc-name
))
2574 (run-python-internal)
2575 (setq python-shell-internal-buffer proc-buffer-name
))
2576 (get-buffer-process proc-buffer-name
)))
2578 (define-obsolete-function-alias
2579 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2581 (define-obsolete-variable-alias
2582 'python-buffer
'python-shell-internal-buffer
"24.3")
2584 (define-obsolete-variable-alias
2585 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2587 (defun python-shell--save-temp-file (string)
2588 (let* ((temporary-file-directory
2589 (if (file-remote-p default-directory
)
2590 (concat (file-remote-p default-directory
) "/tmp")
2591 temporary-file-directory
))
2592 (temp-file-name (make-temp-file "py"))
2593 (coding-system-for-write 'utf-8
))
2594 (with-temp-file temp-file-name
2595 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2597 (delete-trailing-whitespace))
2600 (defun python-shell-send-string (string &optional process
)
2601 "Send STRING to inferior Python PROCESS."
2602 (interactive "sPython command: ")
2603 (let ((process (or process
(python-shell-get-or-create-process))))
2604 (if (string-match ".\n+." string
) ;Multiline.
2605 (let* ((temp-file-name (python-shell--save-temp-file string
)))
2606 (python-shell-send-file temp-file-name process temp-file-name t
))
2607 (comint-send-string process string
)
2608 (when (or (not (string-match "\n\\'" string
))
2609 (string-match "\n[ \t].*\n?\\'" string
))
2610 (comint-send-string process
"\n")))))
2612 (defvar python-shell-output-filter-in-progress nil
)
2613 (defvar python-shell-output-filter-buffer nil
)
2615 (defun python-shell-output-filter (string)
2616 "Filter used in `python-shell-send-string-no-output' to grab output.
2617 STRING is the output received to this point from the process.
2618 This filter saves received output from the process in
2619 `python-shell-output-filter-buffer' and stops receiving it after
2620 detecting a prompt at the end of the buffer."
2622 string
(ansi-color-filter-apply string
)
2623 python-shell-output-filter-buffer
2624 (concat python-shell-output-filter-buffer string
))
2625 (when (python-shell-comint-end-of-output-p
2626 python-shell-output-filter-buffer
)
2627 ;; Output ends when `python-shell-output-filter-buffer' contains
2628 ;; the prompt attached at the end of it.
2629 (setq python-shell-output-filter-in-progress nil
2630 python-shell-output-filter-buffer
2631 (substring python-shell-output-filter-buffer
2632 0 (match-beginning 0)))
2634 python-shell--prompt-calculated-output-regexp
2635 python-shell-output-filter-buffer
)
2636 ;; Some shells, like IPython might append a prompt before the
2637 ;; output, clean that.
2638 (setq python-shell-output-filter-buffer
2639 (substring python-shell-output-filter-buffer
(match-end 0)))))
2642 (defun python-shell-send-string-no-output (string &optional process
)
2643 "Send STRING to PROCESS and inhibit output.
2645 (let ((process (or process
(python-shell-get-or-create-process)))
2646 (comint-preoutput-filter-functions
2647 '(python-shell-output-filter))
2648 (python-shell-output-filter-in-progress t
)
2652 (python-shell-send-string string process
)
2653 (while python-shell-output-filter-in-progress
2654 ;; `python-shell-output-filter' takes care of setting
2655 ;; `python-shell-output-filter-in-progress' to NIL after it
2656 ;; detects end of output.
2657 (accept-process-output process
))
2659 python-shell-output-filter-buffer
2660 (setq python-shell-output-filter-buffer nil
)))
2661 (with-current-buffer (process-buffer process
)
2662 (comint-interrupt-subjob)))))
2664 (defun python-shell-internal-send-string (string)
2665 "Send STRING to the Internal Python interpreter.
2666 Returns the output. See `python-shell-send-string-no-output'."
2667 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2668 ;; updated to support this new mode.
2669 (setq python-shell-internal-last-output
2670 (python-shell-send-string-no-output
2671 ;; Makes this function compatible with the old
2672 ;; python-send-receive. (At least for CEDET).
2673 (replace-regexp-in-string "_emacs_out +" "" string
)
2674 (python-shell-internal-get-or-create-process))))
2676 (define-obsolete-function-alias
2677 'python-send-receive
'python-shell-internal-send-string
"24.3")
2679 (define-obsolete-function-alias
2680 'python-send-string
'python-shell-internal-send-string
"24.3")
2682 (defvar python--use-fake-loc nil
2683 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2684 If nil, regions of text are prepended by the corresponding number of empty
2685 lines and Python is told to output error messages referring to the whole
2688 (defun python-shell-buffer-substring (start end
&optional nomain
)
2689 "Send buffer substring from START to END formatted for shell.
2690 This is a wrapper over `buffer-substring' that takes care of
2691 different transformations for the code sent to be evaluated in
2693 1. When optional argument NOMAIN is non-nil everything under an
2694 \"if __name__ == '__main__'\" block will be removed.
2695 2. When a subregion of the buffer is sent, it takes care of
2696 appending extra empty lines so tracebacks are correct.
2697 3. Wraps indented regions under an \"if True:\" block so the
2698 interpreter evaluates them correctly."
2699 (let ((substring (buffer-substring-no-properties start end
))
2700 (fillstr (unless python--use-fake-loc
2701 (make-string (1- (line-number-at-pos start
)) ?
\n)))
2702 (toplevel-block-p (save-excursion
2704 (or (zerop (line-number-at-pos start
))
2706 (python-util-forward-comment 1)
2707 (zerop (current-indentation)))))))
2710 (if fillstr
(insert fillstr
))
2712 (goto-char (point-min))
2713 (unless python--use-fake-loc
2714 ;; python-shell--save-temp-file adds an extra coding line, which would
2715 ;; throw off the line-counts, so let's try to compensate here.
2716 (if (looking-at "[ \t]*[#\n]")
2717 (delete-region (point) (line-beginning-position 2))))
2718 (when (not toplevel-block-p
)
2720 (delete-region (point) (line-end-position)))
2722 (let* ((if-name-main-start-end
2725 (when (python-nav-if-name-main)
2727 (progn (python-nav-forward-sexp-safe)
2729 ;; Oh destructuring bind, how I miss you.
2730 (if-name-main-start (car if-name-main-start-end
))
2731 (if-name-main-end (cdr if-name-main-start-end
)))
2732 (when if-name-main-start-end
2733 (goto-char if-name-main-start
)
2734 (delete-region if-name-main-start if-name-main-end
)
2737 (- (line-number-at-pos if-name-main-end
)
2738 (line-number-at-pos if-name-main-start
)) ?
\n)))))
2739 (buffer-substring-no-properties (point-min) (point-max)))))
2741 (declare-function compilation-fake-loc
"compile"
2742 (marker file
&optional line col
))
2744 (defun python-shell-send-region (start end
&optional nomain
)
2745 "Send the region delimited by START and END to inferior Python process."
2747 (let* ((python--use-fake-loc
2748 (or python--use-fake-loc
(not buffer-file-name
)))
2749 (string (python-shell-buffer-substring start end nomain
))
2750 (process (python-shell-get-or-create-process))
2751 (_ (string-match "\\`\n*\\(.*\\)" string
)))
2752 (message "Sent: %s..." (match-string 1 string
))
2753 (let* ((temp-file-name (python-shell--save-temp-file string
))
2754 (file-name (or (buffer-file-name) temp-file-name
)))
2755 (python-shell-send-file file-name process temp-file-name t
)
2756 (unless python--use-fake-loc
2757 (with-current-buffer (process-buffer process
)
2758 (compilation-fake-loc (copy-marker start
) temp-file-name
2759 2)) ;; Not 1, because of the added coding line.
2762 (defun python-shell-send-buffer (&optional arg
)
2763 "Send the entire buffer to inferior Python process.
2764 With prefix ARG allow execution of code inside blocks delimited
2765 by \"if __name__== '__main__':\"."
2769 (python-shell-send-region (point-min) (point-max) (not arg
))))
2771 (defun python-shell-send-defun (arg)
2772 "Send the current defun to inferior Python process.
2773 When argument ARG is non-nil do not include decorators."
2776 (python-shell-send-region
2779 (while (and (or (python-nav-beginning-of-defun)
2780 (beginning-of-line 1))
2781 (> (current-indentation) 0)))
2783 (while (and (forward-line -
1)
2784 (looking-at (python-rx decorator
))))
2788 (or (python-nav-end-of-defun)
2792 (defun python-shell-send-file (file-name &optional process temp-file-name
2794 "Send FILE-NAME to inferior Python PROCESS.
2795 If TEMP-FILE-NAME is passed then that file is used for processing
2796 instead, while internally the shell will continue to use FILE-NAME.
2797 If DELETE is non-nil, delete the file afterwards."
2798 (interactive "fFile to send: ")
2799 (let* ((process (or process
(python-shell-get-or-create-process)))
2800 (temp-file-name (when temp-file-name
2802 (or (file-remote-p temp-file-name
'localname
)
2804 (file-name (or (when file-name
2806 (or (file-remote-p file-name
'localname
)
2809 (when (not file-name
)
2810 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2811 (python-shell-send-string
2813 (concat "__pyfile = open('''%s''');"
2814 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2815 "__pyfile.close()%s")
2816 (or temp-file-name file-name
) file-name
2817 (if delete
(format "; import os; os.remove('''%s''')"
2818 (or temp-file-name file-name
))
2822 (defun python-shell-switch-to-shell ()
2823 "Switch to inferior Python process buffer."
2825 (process-buffer (python-shell-get-or-create-process)) t
)
2827 (defun python-shell-send-setup-code ()
2828 "Send all setup code for shell.
2829 This function takes the list of setup code to send from the
2830 `python-shell-setup-codes' list."
2831 (let ((process (python-shell-get-process))
2835 (cond ((stringp elt
) elt
)
2836 ((symbolp elt
) (symbol-value elt
))
2838 python-shell-setup-codes
2840 "\n\nprint ('python.el: sent setup code')")))
2841 (python-shell-send-string code process
)
2842 (python-shell-accept-process-output process
)))
2844 (add-hook 'inferior-python-mode-hook
2845 #'python-shell-send-setup-code
)
2848 ;;; Shell completion
2850 (defcustom python-shell-completion-setup-code
2852 import readline, rlcompleter
2854 def __PYTHON_EL_get_completions(text):
2857 def __PYTHON_EL_get_completions(text):
2860 splits = text.split()
2861 is_module = splits and splits[0] in ('from', 'import')
2862 is_ipython = getattr(
2863 __builtins__, '__IPYTHON__',
2864 getattr(__builtins__, '__IPYTHON__active', False))
2866 from IPython.core.completerlib import module_completion
2867 completions = module_completion(text.strip())
2868 elif is_ipython and getattr(__builtins__, '__IP', None):
2869 completions = __IP.complete(text)
2870 elif is_ipython and getattr(__builtins__, 'get_ipython', None):
2871 completions = get_ipython().Completer.all_completions(text)
2875 res = readline.get_completer()(text, i)
2879 completions.append(res)
2883 "Code used to setup completion in inferior Python processes."
2887 (defcustom python-shell-completion-string-code
2888 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2889 "Python code used to get a string of completions separated by semicolons.
2890 The string passed to the function is the current python name or
2891 the full statement in the case of imports."
2895 (define-obsolete-variable-alias
2896 'python-shell-completion-module-string-code
2897 'python-shell-completion-string-code
2899 "Completion string code must also autocomplete modules.")
2901 (define-obsolete-variable-alias
2902 'python-shell-completion-pdb-string-code
2903 'python-shell-completion-string-code
2905 "Completion string code must work for (i)pdb.")
2907 (defun python-shell-completion-get-completions (process import input
)
2908 "Do completion at point using PROCESS for IMPORT or INPUT.
2909 When IMPORT is non-nil takes precedence over INPUT for
2911 (with-current-buffer (process-buffer process
)
2913 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2914 (buffer-substring-no-properties
2915 (car prompt-boundaries
) (cdr prompt-boundaries
))))
2917 ;; Check whether a prompt matches a pdb string, an import
2918 ;; statement or just the standard prompt and use the
2919 ;; correct python-shell-completion-*-code string
2920 (cond ((and (string-match
2921 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2922 ;; Since there are no guarantees the user will remain
2923 ;; in the same context where completion code was sent
2924 ;; (e.g. user steps into a function), safeguard
2925 ;; resending completion setup continuously.
2926 (concat python-shell-completion-setup-code
2927 "\nprint (" python-shell-completion-string-code
")"))
2929 python-shell--prompt-calculated-input-regexp prompt
)
2930 python-shell-completion-string-code
)
2932 (subject (or import input
)))
2933 (and completion-code
2934 (> (length input
) 0)
2936 (python-util-strip-string
2937 (python-shell-send-string-no-output
2938 (format completion-code subject
) process
))))
2939 (and (> (length completions
) 2)
2940 (split-string completions
2941 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2943 (defun python-shell-completion-at-point (&optional process
)
2944 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2945 Optional argument PROCESS forces completions to be retrieved
2946 using that one instead of current buffer's process."
2947 (setq process
(or process
(get-buffer-process (current-buffer))))
2948 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2950 (when (string-match-p
2951 (rx (* space
) word-start
(or "from" "import") word-end space
)
2952 (buffer-substring-no-properties last-prompt-end
(point)))
2953 (buffer-substring-no-properties last-prompt-end
(point))))
2956 (if (not (re-search-backward
2958 (or whitespace open-paren close-paren string-delimiter
))
2962 (forward-char (length (match-string-no-properties 0)))
2966 (completion-table-dynamic
2968 #'python-shell-completion-get-completions
2969 process import-statement
)))))
2971 (define-obsolete-function-alias
2972 'python-shell-completion-complete-at-point
2973 'python-shell-completion-at-point
2976 (defun python-shell-completion-complete-or-indent ()
2977 "Complete or indent depending on the context.
2978 If content before pointer is all whitespace, indent.
2979 If not try to complete."
2981 (if (string-match "^[[:space:]]*$"
2982 (buffer-substring (comint-line-beginning-position)
2984 (indent-for-tab-command)
2985 (completion-at-point)))
2988 ;;; PDB Track integration
2990 (defcustom python-pdbtrack-activate t
2991 "Non-nil makes Python shell enable pdbtracking."
2996 (defcustom python-pdbtrack-stacktrace-info-regexp
2997 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2998 "Regular expression matching stacktrace information.
2999 Used to extract the current line and module being inspected."
3004 (defvar python-pdbtrack-tracked-buffer nil
3005 "Variable containing the value of the current tracked buffer.
3006 Never set this variable directly, use
3007 `python-pdbtrack-set-tracked-buffer' instead.")
3009 (defvar python-pdbtrack-buffers-to-kill nil
3010 "List of buffers to be deleted after tracking finishes.")
3012 (defun python-pdbtrack-set-tracked-buffer (file-name)
3013 "Set the buffer for FILE-NAME as the tracked buffer.
3014 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3015 Returns the tracked buffer."
3016 (let ((file-buffer (get-file-buffer
3017 (concat (file-remote-p default-directory
)
3020 (setq python-pdbtrack-tracked-buffer file-buffer
)
3021 (setq file-buffer
(find-file-noselect file-name
))
3022 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
3023 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
3026 (defun python-pdbtrack-comint-output-filter-function (output)
3027 "Move overlay arrow to current pdb line in tracked buffer.
3028 Argument OUTPUT is a string with the output from the comint process."
3029 (when (and python-pdbtrack-activate
(not (string= output
"")))
3030 (let* ((full-output (ansi-color-filter-apply
3031 (buffer-substring comint-last-input-end
(point-max))))
3035 (insert full-output
)
3036 ;; When the debugger encounters a pdb.set_trace()
3037 ;; command, it prints a single stack frame. Sometimes
3038 ;; it prints a bit of extra information about the
3039 ;; arguments of the present function. When ipdb
3040 ;; encounters an exception, it prints the _entire_ stack
3041 ;; trace. To handle all of these cases, we want to find
3042 ;; the _last_ stack frame printed in the most recent
3043 ;; batch of output, then jump to the corresponding
3044 ;; file/line number.
3045 (goto-char (point-max))
3046 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
3047 (setq line-number
(string-to-number
3048 (match-string-no-properties 2)))
3049 (match-string-no-properties 1)))))
3050 (if (and file-name line-number
)
3051 (let* ((tracked-buffer
3052 (python-pdbtrack-set-tracked-buffer file-name
))
3053 (shell-buffer (current-buffer))
3054 (tracked-buffer-window (get-buffer-window tracked-buffer
))
3055 (tracked-buffer-line-pos))
3056 (with-current-buffer tracked-buffer
3057 (set (make-local-variable 'overlay-arrow-string
) "=>")
3058 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
3059 (setq tracked-buffer-line-pos
(progn
3060 (goto-char (point-min))
3061 (forward-line (1- line-number
))
3063 (when tracked-buffer-window
3065 tracked-buffer-window tracked-buffer-line-pos
))
3066 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
3067 (pop-to-buffer tracked-buffer
)
3068 (switch-to-buffer-other-window shell-buffer
))
3069 (when python-pdbtrack-tracked-buffer
3070 (with-current-buffer python-pdbtrack-tracked-buffer
3071 (set-marker overlay-arrow-position nil
))
3072 (mapc #'(lambda (buffer)
3073 (ignore-errors (kill-buffer buffer
)))
3074 python-pdbtrack-buffers-to-kill
)
3075 (setq python-pdbtrack-tracked-buffer nil
3076 python-pdbtrack-buffers-to-kill nil
)))))
3080 ;;; Symbol completion
3082 (defun python-completion-at-point ()
3083 "Function for `completion-at-point-functions' in `python-mode'.
3084 For this to work as best as possible you should call
3085 `python-shell-send-buffer' from time to time so context in
3086 inferior Python process is updated properly."
3087 (let ((process (python-shell-get-process)))
3089 (python-shell-completion-at-point process
))))
3091 (define-obsolete-function-alias
3092 'python-completion-complete-at-point
3093 'python-completion-at-point
3099 (defcustom python-fill-comment-function
'python-fill-comment
3100 "Function to fill comments.
3101 This is the function used by `python-fill-paragraph' to
3106 (defcustom python-fill-string-function
'python-fill-string
3107 "Function to fill strings.
3108 This is the function used by `python-fill-paragraph' to
3113 (defcustom python-fill-decorator-function
'python-fill-decorator
3114 "Function to fill decorators.
3115 This is the function used by `python-fill-paragraph' to
3120 (defcustom python-fill-paren-function
'python-fill-paren
3121 "Function to fill parens.
3122 This is the function used by `python-fill-paragraph' to
3127 (defcustom python-fill-docstring-style
'pep-257
3128 "Style used to fill docstrings.
3129 This affects `python-fill-string' behavior with regards to
3130 triple quotes positioning.
3132 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3133 `symmetric', and nil. A value of nil won't care about quotes
3134 position and will treat docstrings a normal string, any other
3135 value may result in one of the following docstring styles:
3140 Process foo, return bar.
3144 Process foo, return bar.
3146 If processing fails throw ProcessingError.
3151 \"\"\"Process foo, return bar.\"\"\"
3154 Process foo, return bar.
3156 If processing fails throw ProcessingError.
3162 \"\"\"Process foo, return bar.\"\"\"
3164 \"\"\"Process foo, return bar.
3166 If processing fails throw ProcessingError.
3172 \"\"\"Process foo, return bar.\"\"\"
3174 \"\"\"Process foo, return bar.
3176 If processing fails throw ProcessingError.
3181 \"\"\"Process foo, return bar.\"\"\"
3184 Process foo, return bar.
3186 If processing fails throw ProcessingError.
3189 (const :tag
"Don't format docstrings" nil
)
3190 (const :tag
"Django's coding standards style." django
)
3191 (const :tag
"One newline and start and Two at end style." onetwo
)
3192 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
3193 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
3194 (const :tag
"Symmetric style." symmetric
))
3197 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
3199 (defun python-fill-paragraph (&optional justify
)
3200 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3201 If any of the current line is in or at the end of a multi-line string,
3202 fill the string or the paragraph of it that point is in, preserving
3203 the string's indentation.
3204 Optional argument JUSTIFY defines if the paragraph should be justified."
3209 ((python-syntax-context 'comment
)
3210 (funcall python-fill-comment-function justify
))
3211 ;; Strings/Docstrings
3212 ((save-excursion (or (python-syntax-context 'string
)
3213 (equal (string-to-syntax "|")
3214 (syntax-after (point)))))
3215 (funcall python-fill-string-function justify
))
3217 ((equal (char-after (save-excursion
3218 (python-nav-beginning-of-statement))) ?
@)
3219 (funcall python-fill-decorator-function justify
))
3221 ((or (python-syntax-context 'paren
)
3222 (looking-at (python-rx open-paren
))
3224 (skip-syntax-forward "^(" (line-end-position))
3225 (looking-at (python-rx open-paren
))))
3226 (funcall python-fill-paren-function justify
))
3229 (defun python-fill-comment (&optional justify
)
3230 "Comment fill function for `python-fill-paragraph'.
3231 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3232 (fill-comment-paragraph justify
))
3234 (defun python-fill-string (&optional justify
)
3235 "String fill function for `python-fill-paragraph'.
3236 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3237 (let* ((str-start-pos
3240 (or (python-syntax-context 'string
)
3241 (and (equal (string-to-syntax "|")
3242 (syntax-after (point)))
3244 (num-quotes (python-syntax-count-quotes
3245 (char-after str-start-pos
) str-start-pos
))
3248 (goto-char (+ str-start-pos num-quotes
))
3249 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
3250 (goto-char (point-max)))
3253 ;; Docstring styles may vary for oneliners and multi-liners.
3254 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
3256 (pcase python-fill-docstring-style
3257 ;; delimiters-style is a cons cell with the form
3258 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3259 ;; is NIL means to not add any newlines for start or end
3260 ;; of docstring. See `python-fill-docstring-style' for a
3261 ;; graphic idea of each style.
3262 (`django
(cons 1 1))
3263 (`onetwo
(and multi-line-p
(cons 1 2)))
3264 (`pep-257
(and multi-line-p
(cons nil
2)))
3265 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
3266 (`symmetric
(and multi-line-p
(cons 1 1)))))
3267 (docstring-p (save-excursion
3268 ;; Consider docstrings those strings which
3269 ;; start on a line by themselves.
3270 (python-nav-beginning-of-statement)
3271 (and (= (point) str-start-pos
))))
3272 (fill-paragraph-function))
3274 (narrow-to-region str-start-pos str-end-pos
)
3275 (fill-paragraph justify
))
3277 (when (and docstring-p python-fill-docstring-style
)
3278 ;; Add the number of newlines indicated by the selected style
3279 ;; at the start of the docstring.
3280 (goto-char (+ str-start-pos num-quotes
))
3281 (delete-region (point) (progn
3282 (skip-syntax-forward "> ")
3284 (and (car delimiters-style
)
3285 (or (newline (car delimiters-style
)) t
)
3286 ;; Indent only if a newline is added.
3287 (indent-according-to-mode))
3288 ;; Add the number of newlines indicated by the selected style
3289 ;; at the end of the docstring.
3290 (goto-char (if (not (= str-end-pos
(point-max)))
3291 (- str-end-pos num-quotes
)
3293 (delete-region (point) (progn
3294 (skip-syntax-backward "> ")
3296 (and (cdr delimiters-style
)
3297 ;; Add newlines only if string ends.
3298 (not (= str-end-pos
(point-max)))
3299 (or (newline (cdr delimiters-style
)) t
)
3300 ;; Again indent only if a newline is added.
3301 (indent-according-to-mode))))) t
)
3303 (defun python-fill-decorator (&optional _justify
)
3304 "Decorator fill function for `python-fill-paragraph'.
3305 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3308 (defun python-fill-paren (&optional justify
)
3309 "Paren fill function for `python-fill-paragraph'.
3310 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3312 (narrow-to-region (progn
3313 (while (python-syntax-context 'paren
)
3314 (goto-char (1- (point))))
3315 (line-beginning-position))
3317 (when (not (python-syntax-context 'paren
))
3319 (when (not (python-syntax-context 'paren
))
3320 (skip-syntax-backward "^)")))
3321 (while (and (python-syntax-context 'paren
)
3323 (goto-char (1+ (point))))
3325 (let ((paragraph-start "\f\\|[ \t]*$")
3326 (paragraph-separate ",")
3327 (fill-paragraph-function))
3328 (goto-char (point-min))
3329 (fill-paragraph justify
))
3332 (python-indent-line)
3333 (goto-char (line-end-position))))
3339 (defcustom python-skeleton-autoinsert nil
3340 "Non-nil means template skeletons will be automagically inserted.
3341 This happens when pressing \"if<SPACE>\", for example, to prompt for
3347 (define-obsolete-variable-alias
3348 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
3350 (defvar python-skeleton-available
'()
3351 "Internal list of available skeletons.")
3353 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
3354 "Abbrev table for Python mode skeletons."
3356 ;; Allow / inside abbrevs.
3357 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3358 ;; Only expand in code.
3359 :enable-function
(lambda ()
3361 (not (python-syntax-comment-or-string-p))
3362 python-skeleton-autoinsert
)))
3364 (defmacro python-skeleton-define
(name doc
&rest skel
)
3365 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3366 The skeleton will be bound to python-skeleton-NAME and will
3367 be added to `python-mode-skeleton-abbrev-table'."
3368 (declare (indent 2))
3369 (let* ((name (symbol-name name
))
3370 (function-name (intern (concat "python-skeleton-" name
))))
3372 (define-abbrev python-mode-skeleton-abbrev-table
3373 ,name
"" ',function-name
:system t
)
3374 (setq python-skeleton-available
3375 (cons ',function-name python-skeleton-available
))
3376 (define-skeleton ,function-name
3378 (format "Insert %s statement." name
))
3381 (define-abbrev-table 'python-mode-abbrev-table
()
3382 "Abbrev table for Python mode."
3383 :parents
(list python-mode-skeleton-abbrev-table
))
3385 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
3386 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3387 The skeleton will be bound to python-skeleton-NAME."
3388 (declare (indent 2))
3389 (let* ((name (symbol-name name
))
3390 (function-name (intern (concat "python-skeleton--" name
)))
3392 "Add '%s' clause? " name
)))
3395 `(< ,(format "%s:" name
) \n \n
3397 `(define-skeleton ,function-name
3399 (format "Auxiliary skeleton for %s statement." name
))
3401 (unless (y-or-n-p ,msg
)
3405 (python-define-auxiliary-skeleton else nil
)
3407 (python-define-auxiliary-skeleton except nil
)
3409 (python-define-auxiliary-skeleton finally nil
)
3411 (python-skeleton-define if nil
3415 ("other condition, %s: "
3419 '(python-skeleton--else) | ^
)
3421 (python-skeleton-define while nil
3425 '(python-skeleton--else) | ^
)
3427 (python-skeleton-define for nil
3431 '(python-skeleton--else) | ^
)
3433 (python-skeleton-define import nil
3434 "Import from module: "
3435 "from " str
& " " | -
5
3437 ("Identifier: " str
", ") -
2 \n _
)
3439 (python-skeleton-define try nil
3445 "except " str
":" \n
3448 '(python-skeleton--except)
3449 '(python-skeleton--else)
3450 '(python-skeleton--finally) | ^
)
3452 (python-skeleton-define def nil
3454 "def " str
"(" ("Parameter, %s: "
3455 (unless (equal ?\
( (char-before)) ", ")
3457 "\"\"\"" -
"\"\"\"" \n
3460 (python-skeleton-define class nil
3462 "class " str
"(" ("Inheritance, %s: "
3463 (unless (equal ?\
( (char-before)) ", ")
3467 "\"\"\"" -
"\"\"\"" \n
3470 (defun python-skeleton-add-menu-items ()
3471 "Add menu items to Python->Skeletons menu."
3472 (let ((skeletons (sort python-skeleton-available
'string
<)))
3473 (dolist (skeleton skeletons
)
3475 nil
'("Python" "Skeletons")
3477 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3482 (defcustom python-ffap-setup-code
3483 "def __FFAP_get_module_path(module):
3486 path = __import__(module).__file__
3487 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3492 "Python code to get a module path."
3496 (defcustom python-ffap-string-code
3497 "__FFAP_get_module_path('''%s''')\n"
3498 "Python code used to get a string with the path of a module."
3502 (defun python-ffap-module-path (module)
3503 "Function for `ffap-alist' to return path for MODULE."
3505 (and (derived-mode-p 'inferior-python-mode
)
3506 (get-buffer-process (current-buffer)))
3507 (python-shell-get-process))))
3511 (python-shell-send-string-no-output
3512 (format python-ffap-string-code module
) process
)))
3514 (substring-no-properties module-file
1 -
1))))))
3518 (eval-after-load "ffap"
3520 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3521 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3526 (defcustom python-check-command
3528 "Command used to check a Python file."
3532 (defcustom python-check-buffer-name
3533 "*Python check: %s*"
3534 "Buffer name used for check commands."
3538 (defvar python-check-custom-command nil
3541 (defun python-check (command)
3542 "Check a Python file (default current buffer's file).
3543 Runs COMMAND, a shell command, as if by `compile'.
3544 See `python-check-command' for the default."
3546 (list (read-string "Check command: "
3547 (or python-check-custom-command
3548 (concat python-check-command
" "
3549 (shell-quote-argument
3551 (let ((name (buffer-file-name)))
3553 (file-name-nondirectory name
)))
3555 (setq python-check-custom-command command
)
3556 (save-some-buffers (not compilation-ask-about-save
) nil
)
3557 (let ((process-environment (python-shell-calculate-process-environment))
3558 (exec-path (python-shell-calculate-exec-path)))
3559 (compilation-start command nil
3561 (format python-check-buffer-name command
)))))
3566 (defcustom python-eldoc-setup-code
3567 "def __PYDOC_get_help(obj):
3571 str_type = basestring
3574 if isinstance(obj, str_type):
3575 obj = eval(obj, globals())
3576 doc = inspect.getdoc(obj)
3577 if not doc and callable(obj):
3579 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3580 target = obj.__init__
3586 args = inspect.formatargspec(
3587 *inspect.getargspec(target)
3590 doc = '{objtype} {name}{args}'.format(
3591 objtype=objtype, name=name, args=args
3594 doc = doc.splitlines()[0]
3598 "Python code to setup documentation retrieval."
3602 (defcustom python-eldoc-string-code
3603 "__PYDOC_get_help('''%s''')\n"
3604 "Python code used to get a string with the documentation of an object."
3608 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
3609 "Internal implementation to get documentation at point.
3610 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3611 returns will be used. If not FORCE-PROCESS is passed what
3612 `python-shell-get-process' returns is used."
3613 (let ((process (or force-process
(python-shell-get-process))))
3615 (let ((input (or force-input
3616 (python-info-current-symbol t
))))
3618 ;; Prevent resizing the echo area when iPython is
3619 ;; enabled. Bug#18794.
3620 (python-util-strip-string
3621 (python-shell-send-string-no-output
3622 (format python-eldoc-string-code input
)
3625 (defun python-eldoc-function ()
3626 "`eldoc-documentation-function' for Python.
3627 For this to work as best as possible you should call
3628 `python-shell-send-buffer' from time to time so context in
3629 inferior Python process is updated properly."
3630 (python-eldoc--get-doc-at-point))
3632 (defun python-eldoc-at-point (symbol)
3633 "Get help on SYMBOL using `help'.
3634 Interactively, prompt for symbol."
3636 (let ((symbol (python-info-current-symbol t
))
3637 (enable-recursive-minibuffers t
))
3638 (list (read-string (if symbol
3639 (format "Describe symbol (default %s): " symbol
)
3640 "Describe symbol: ")
3642 (message (python-eldoc--get-doc-at-point symbol
)))
3647 (defvar python-imenu-format-item-label-function
3648 'python-imenu-format-item-label
3649 "Imenu function used to format an item label.
3650 It must be a function with two arguments: TYPE and NAME.")
3652 (defvar python-imenu-format-parent-item-label-function
3653 'python-imenu-format-parent-item-label
3654 "Imenu function used to format a parent item label.
3655 It must be a function with two arguments: TYPE and NAME.")
3657 (defvar python-imenu-format-parent-item-jump-label-function
3658 'python-imenu-format-parent-item-jump-label
3659 "Imenu function used to format a parent jump item label.
3660 It must be a function with two arguments: TYPE and NAME.")
3662 (defun python-imenu-format-item-label (type name
)
3663 "Return Imenu label for single node using TYPE and NAME."
3664 (format "%s (%s)" name type
))
3666 (defun python-imenu-format-parent-item-label (type name
)
3667 "Return Imenu label for parent node using TYPE and NAME."
3668 (format "%s..." (python-imenu-format-item-label type name
)))
3670 (defun python-imenu-format-parent-item-jump-label (type _name
)
3671 "Return Imenu label for parent node jump using TYPE and NAME."
3672 (if (string= type
"class")
3673 "*class definition*"
3674 "*function definition*"))
3676 (defun python-imenu--put-parent (type name pos tree
)
3677 "Add the parent with TYPE, NAME and POS to TREE."
3679 (funcall python-imenu-format-item-label-function type name
))
3681 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
3684 (cons label
(cons (cons jump-label pos
) tree
)))))
3686 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
3687 "Recursively build the tree of nested definitions of a node.
3688 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3689 not be passed explicitly unless you know what you are doing."
3690 (setq min-indent
(or min-indent
0)
3691 prev-indent
(or prev-indent python-indent-offset
))
3692 (let* ((pos (python-nav-backward-defun))
3694 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
3695 (let ((split (split-string (match-string-no-properties 0))))
3696 (setq type
(car split
))
3699 (funcall python-imenu-format-item-label-function type name
)))
3700 (indent (current-indentation))
3701 (children-indent-limit (+ python-indent-offset min-indent
)))
3703 ;; Nothing found, probably near to bobp.
3705 ((<= indent min-indent
)
3706 ;; The current indentation points that this is a parent
3707 ;; node, add it to the tree and stop recursing.
3708 (python-imenu--put-parent type name pos tree
))
3710 (python-imenu--build-tree
3713 (if (<= indent children-indent-limit
)
3714 ;; This lies within the children indent offset range,
3715 ;; so it's a normal child of its parent (i.e., not
3716 ;; a child of a child).
3717 (cons (cons label pos
) tree
)
3718 ;; Oh no, a child of a child?! Fear not, we
3719 ;; know how to roll. We recursively parse these by
3720 ;; swapping prev-indent and min-indent plus adding this
3721 ;; newly found item to a fresh subtree. This works, I
3724 (python-imenu--build-tree
3725 prev-indent indent
(list (cons label pos
)))
3728 (defun python-imenu-create-index ()
3729 "Return tree Imenu alist for the current Python buffer.
3730 Change `python-imenu-format-item-label-function',
3731 `python-imenu-format-parent-item-label-function',
3732 `python-imenu-format-parent-item-jump-label-function' to
3733 customize how labels are formatted."
3734 (goto-char (point-max))
3737 (while (setq tree
(python-imenu--build-tree))
3738 (setq index
(cons tree index
)))
3741 (defun python-imenu-create-flat-index (&optional alist prefix
)
3742 "Return flat outline of the current Python buffer for Imenu.
3743 Optional argument ALIST is the tree to be flattened; when nil
3744 `python-imenu-build-index' is used with
3745 `python-imenu-format-parent-item-jump-label-function'
3746 `python-imenu-format-parent-item-label-function'
3747 `python-imenu-format-item-label-function' set to
3748 (lambda (type name) name)
3749 Optional argument PREFIX is used in recursive calls and should
3750 not be passed explicitly.
3757 (\"decorator\" . 173)
3760 (\"wrapped_f\" . 393))))
3766 (\"decorator\" . 173)
3767 (\"decorator.wrap\" . 353)
3768 (\"decorator.wrapped_f\" . 393))"
3769 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3774 (let ((name (if prefix
3775 (concat prefix
"." (car item
))
3778 (cond ((or (numberp pos
) (markerp pos
))
3779 (list (cons name pos
)))
3782 (cons name
(cdar pos
))
3783 (python-imenu-create-flat-index (cddr item
) name
))))))
3785 (let* ((fn (lambda (_type name
) name
))
3786 (python-imenu-format-item-label-function fn
)
3787 (python-imenu-format-parent-item-label-function fn
)
3788 (python-imenu-format-parent-item-jump-label-function fn
))
3789 (python-imenu-create-index))))))
3794 (defun python-info-current-defun (&optional include-type
)
3795 "Return name of surrounding function with Python compatible dotty syntax.
3796 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3797 This function can be used as the value of `add-log-current-defun-function'
3798 since it returns nil if point is not inside a defun."
3804 (starting-indentation (current-indentation))
3805 (starting-pos (point))
3810 (while (python-nav-beginning-of-defun 1)
3811 (when (save-match-data
3813 (or (not last-indent
)
3814 (< (current-indentation) last-indent
))
3818 ;; If this is the first run, we may add
3819 ;; the current defun at point.
3820 (setq first-run nil
)
3821 (goto-char starting-pos
)
3822 (python-nav-beginning-of-statement)
3823 (beginning-of-line 1)
3825 python-nav-beginning-of-defun-regexp
)))
3829 (+ (current-indentation)
3830 python-indent-offset
)))
3831 (if (< starting-indentation min-indent
)
3832 ;; If the starting indentation is not
3833 ;; within the min defun indent make the
3836 ;; Else go to the end of defun and add
3837 ;; up the current indentation to the
3839 (python-nav-end-of-defun)
3841 (if (>= (current-indentation) min-indent
)
3842 (1+ (current-indentation))
3844 (save-match-data (setq last-indent
(current-indentation)))
3845 (if (or (not include-type
) type
)
3846 (setq names
(cons (match-string-no-properties 1) names
))
3847 (let ((match (split-string (match-string-no-properties 0))))
3848 (setq type
(car match
))
3849 (setq names
(cons (cadr match
) names
)))))
3850 ;; Stop searching ASAP.
3851 (and (= (current-indentation) 0) (throw 'exit t
))))
3853 (concat (and type
(format "%s " type
))
3854 (mapconcat 'identity names
".")))))))
3856 (defun python-info-current-symbol (&optional replace-self
)
3857 "Return current symbol using dotty syntax.
3858 With optional argument REPLACE-SELF convert \"self\" to current
3861 (and (not (python-syntax-comment-or-string-p))
3862 (with-syntax-table python-dotty-syntax-table
3863 (let ((sym (symbol-at-point)))
3865 (substring-no-properties (symbol-name sym
))))))))
3867 (if (not replace-self
)
3869 (let ((current-defun (python-info-current-defun)))
3870 (if (not current-defun
)
3872 (replace-regexp-in-string
3873 (python-rx line-start word-start
"self" word-end ?.
)
3875 (mapconcat 'identity
3876 (butlast (split-string current-defun
"\\."))
3880 (defun python-info-statement-starts-block-p ()
3881 "Return non-nil if current statement opens a block."
3883 (python-nav-beginning-of-statement)
3884 (looking-at (python-rx block-start
))))
3886 (defun python-info-statement-ends-block-p ()
3887 "Return non-nil if point is at end of block."
3888 (let ((end-of-block-pos (save-excursion
3889 (python-nav-end-of-block)))
3890 (end-of-statement-pos (save-excursion
3891 (python-nav-end-of-statement))))
3892 (and end-of-block-pos end-of-statement-pos
3893 (= end-of-block-pos end-of-statement-pos
))))
3895 (defun python-info-beginning-of-statement-p ()
3896 "Return non-nil if point is at beginning of statement."
3897 (= (point) (save-excursion
3898 (python-nav-beginning-of-statement)
3901 (defun python-info-end-of-statement-p ()
3902 "Return non-nil if point is at end of statement."
3903 (= (point) (save-excursion
3904 (python-nav-end-of-statement)
3907 (defun python-info-beginning-of-block-p ()
3908 "Return non-nil if point is at beginning of block."
3909 (and (python-info-beginning-of-statement-p)
3910 (python-info-statement-starts-block-p)))
3912 (defun python-info-end-of-block-p ()
3913 "Return non-nil if point is at end of block."
3914 (and (python-info-end-of-statement-p)
3915 (python-info-statement-ends-block-p)))
3917 (define-obsolete-function-alias
3918 'python-info-closing-block
3919 'python-info-dedenter-opening-block-position
"24.4")
3921 (defun python-info-dedenter-opening-block-position ()
3922 "Return the point of the closest block the current line closes.
3923 Returns nil if point is not on a dedenter statement or no opening
3924 block can be detected. The latter case meaning current file is
3925 likely an invalid python file."
3926 (let ((positions (python-info-dedenter-opening-block-positions))
3927 (indentation (current-indentation))
3929 (while (and (not position
)
3932 (goto-char (car positions
))
3933 (if (<= (current-indentation) indentation
)
3934 (setq position
(car positions
))
3935 (setq positions
(cdr positions
)))))
3938 (defun python-info-dedenter-opening-block-positions ()
3939 "Return points of blocks the current line may close sorted by closer.
3940 Returns nil if point is not on a dedenter statement or no opening
3941 block can be detected. The latter case meaning current file is
3942 likely an invalid python file."
3944 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3946 (goto-char dedenter-pos
)
3947 (let* ((pairs '(("elif" "elif" "if")
3948 ("else" "if" "elif" "except" "for" "while")
3949 ("except" "except" "try")
3950 ("finally" "else" "except" "try")))
3951 (dedenter (match-string-no-properties 0))
3952 (possible-opening-blocks (cdr (assoc-string dedenter pairs
)))
3953 (collected-indentations)
3956 (while (python-nav--syntactically
3958 (re-search-backward (python-rx block-start
) nil t
))
3960 (let ((indentation (current-indentation)))
3961 (when (and (not (memq indentation collected-indentations
))
3962 (or (not collected-indentations
)
3963 (< indentation
(apply #'min collected-indentations
))))
3964 (setq collected-indentations
3965 (cons indentation collected-indentations
))
3966 (when (member (match-string-no-properties 0)
3967 possible-opening-blocks
)
3968 (setq opening-blocks
(cons (point) opening-blocks
))))
3969 (when (zerop indentation
)
3970 (throw 'exit nil
)))))
3972 (nreverse opening-blocks
))))))
3974 (define-obsolete-function-alias
3975 'python-info-closing-block-message
3976 'python-info-dedenter-opening-block-message
"24.4")
3978 (defun python-info-dedenter-opening-block-message ()
3979 "Message the first line of the block the current statement closes."
3980 (let ((point (python-info-dedenter-opening-block-position)))
3984 (message "Closes %s" (save-excursion
3987 (point) (line-end-position))))))))
3989 (defun python-info-dedenter-statement-p ()
3990 "Return point if current statement is a dedenter.
3991 Sets `match-data' to the keyword that starts the dedenter
3994 (python-nav-beginning-of-statement)
3995 (when (and (not (python-syntax-context-type))
3996 (looking-at (python-rx dedenter
)))
3999 (defun python-info-line-ends-backslash-p (&optional line-number
)
4000 "Return non-nil if current line ends with backslash.
4001 With optional argument LINE-NUMBER, check that line instead."
4006 (python-util-goto-line line-number
))
4007 (while (and (not (eobp))
4008 (goto-char (line-end-position))
4009 (python-syntax-context 'paren
)
4010 (not (equal (char-before (point)) ?
\\)))
4012 (when (equal (char-before) ?
\\)
4015 (defun python-info-beginning-of-backslash (&optional line-number
)
4016 "Return the point where the backslashed line start.
4017 Optional argument LINE-NUMBER forces the line number to check against."
4022 (python-util-goto-line line-number
))
4023 (when (python-info-line-ends-backslash-p)
4024 (while (save-excursion
4025 (goto-char (line-beginning-position))
4026 (python-syntax-context 'paren
))
4028 (back-to-indentation)
4031 (defun python-info-continuation-line-p ()
4032 "Check if current line is continuation of another.
4033 When current line is continuation of another return the point
4034 where the continued line ends."
4038 (let* ((context-type (progn
4039 (back-to-indentation)
4040 (python-syntax-context-type)))
4041 (line-start (line-number-at-pos))
4042 (context-start (when context-type
4043 (python-syntax-context context-type
))))
4044 (cond ((equal context-type
'paren
)
4045 ;; Lines inside a paren are always a continuation line
4046 ;; (except the first one).
4047 (python-util-forward-comment -
1)
4049 ((member context-type
'(string comment
))
4050 ;; move forward an roll again
4051 (goto-char context-start
)
4052 (python-util-forward-comment)
4053 (python-info-continuation-line-p))
4055 ;; Not within a paren, string or comment, the only way
4056 ;; we are dealing with a continuation line is that
4057 ;; previous line contains a backslash, and this can
4058 ;; only be the previous line from current
4059 (back-to-indentation)
4060 (python-util-forward-comment -
1)
4061 (when (and (equal (1- line-start
) (line-number-at-pos))
4062 (python-info-line-ends-backslash-p))
4063 (point-marker))))))))
4065 (defun python-info-block-continuation-line-p ()
4066 "Return non-nil if current line is a continuation of a block."
4068 (when (python-info-continuation-line-p)
4070 (back-to-indentation)
4071 (when (looking-at (python-rx block-start
))
4074 (defun python-info-assignment-continuation-line-p ()
4075 "Check if current line is a continuation of an assignment.
4076 When current line is continuation of another with an assignment
4077 return the point of the first non-blank character after the
4080 (when (python-info-continuation-line-p)
4082 (back-to-indentation)
4083 (when (and (not (looking-at (python-rx block-start
)))
4084 (and (re-search-forward (python-rx not-simple-operator
4086 not-simple-operator
)
4087 (line-end-position) t
)
4088 (not (python-syntax-context-type))))
4089 (skip-syntax-forward "\s")
4092 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
4093 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4094 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
4096 (beginning-of-line 1)
4097 (looking-at python-nav-beginning-of-defun-regexp
))))
4099 (defun python-info-current-line-comment-p ()
4100 "Return non-nil if current line is a comment line."
4102 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
4105 (defun python-info-current-line-empty-p ()
4106 "Return non-nil if current line is empty, ignoring whitespace."
4108 (beginning-of-line 1)
4110 (python-rx line-start
(* whitespace
)
4111 (group (* not-newline
))
4112 (* whitespace
) line-end
))
4113 (string-equal "" (match-string-no-properties 1))))
4116 ;;; Utility functions
4118 (defun python-util-goto-line (line-number)
4119 "Move point to LINE-NUMBER."
4120 (goto-char (point-min))
4121 (forward-line (1- line-number
)))
4123 ;; Stolen from org-mode
4124 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
4125 "Clone local variables from FROM-BUFFER.
4126 Optional argument REGEXP selects variables to clone and defaults
4130 (and (symbolp (car pair
))
4131 (string-match (or regexp
"^python-")
4132 (symbol-name (car pair
)))
4133 (set (make-local-variable (car pair
))
4135 (buffer-local-variables from-buffer
)))
4137 (defvar comint-last-prompt-overlay
) ; Shut up, byte compiler.
4139 (defun python-util-comint-last-prompt ()
4140 "Return comint last prompt overlay start and end.
4141 This is for compatibility with Emacs < 24.4."
4142 (cond ((bound-and-true-p comint-last-prompt-overlay
)
4143 (cons (overlay-start comint-last-prompt-overlay
)
4144 (overlay-end comint-last-prompt-overlay
)))
4145 ((bound-and-true-p comint-last-prompt
)
4149 (defun python-util-forward-comment (&optional direction
)
4150 "Python mode specific version of `forward-comment'.
4151 Optional argument DIRECTION defines the direction to move to."
4152 (let ((comment-start (python-syntax-context 'comment
))
4153 (factor (if (< (or direction
0) 0)
4157 (goto-char comment-start
))
4158 (forward-comment factor
)))
4160 (defun python-util-list-directories (directory &optional predicate max-depth
)
4161 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4162 Argument PREDICATE defaults to `identity' and must be a function
4163 that takes one argument (a full path) and returns non-nil for
4164 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4165 searching when depth is reached, else don't limit."
4166 (let* ((dir (expand-file-name directory
))
4167 (dir-length (length dir
))
4168 (predicate (or predicate
#'identity
))
4169 (to-scan (list dir
))
4172 (let ((current-dir (car to-scan
)))
4173 (when (funcall predicate current-dir
)
4174 (setq tally
(cons current-dir tally
)))
4175 (setq to-scan
(append (cdr to-scan
)
4176 (python-util-list-files
4177 current-dir
#'file-directory-p
)
4179 (when (and max-depth
4181 (length (split-string
4182 (substring current-dir dir-length
)
4184 (setq to-scan nil
))))
4187 (defun python-util-list-files (dir &optional predicate
)
4188 "List files in DIR, filtering with PREDICATE.
4189 Argument PREDICATE defaults to `identity' and must be a function
4190 that takes one argument (a full path) and returns non-nil for
4192 (let ((dir-name (file-name-as-directory dir
)))
4194 (mapcar (lambda (file-name)
4195 (let ((full-file-name (expand-file-name file-name dir-name
)))
4197 (not (member file-name
'("." "..")))
4198 (funcall (or predicate
#'identity
) full-file-name
))
4199 (list full-file-name
))))
4200 (directory-files dir-name
)))))
4202 (defun python-util-list-packages (dir &optional max-depth
)
4203 "List packages in DIR, limited by MAX-DEPTH.
4204 When optional argument MAX-DEPTH is non-nil, stop searching when
4205 depth is reached, else don't limit."
4206 (let* ((dir (expand-file-name dir
))
4207 (parent-dir (file-name-directory
4208 (directory-file-name
4209 (file-name-directory
4210 (file-name-as-directory dir
)))))
4211 (subpath-length (length parent-dir
)))
4214 (replace-regexp-in-string
4215 (rx (or ?
\\ ?
/)) "." (substring file-name subpath-length
)))
4216 (python-util-list-directories
4217 (directory-file-name dir
)
4219 (file-exists-p (expand-file-name "__init__.py" dir
)))
4222 (defun python-util-popn (lst n
)
4223 "Return LST first N elements.
4224 N should be an integer, when negative its opposite is used.
4225 When N is bigger than the length of LST, the list is
4227 (let* ((n (min (abs n
)))
4233 (setq acc
(cons (car lst
) acc
)
4238 (defun python-util-text-properties-replace-name
4239 (from to
&optional start end
)
4240 "Replace properties named FROM to TO, keeping its value.
4241 Arguments START and END narrow the buffer region to work on."
4243 (goto-char (or start
(point-min)))
4245 (let ((plist (text-properties-at (point)))
4246 (next-change (or (next-property-change (point) (current-buffer))
4247 (or end
(point-max)))))
4248 (when (plist-get plist from
)
4249 (let* ((face (plist-get plist from
))
4250 (plist (plist-put plist from nil
))
4251 (plist (plist-put plist to face
)))
4252 (set-text-properties (point) next-change plist
(current-buffer))))
4253 (goto-char next-change
)))))
4255 (defun python-util-strip-string (string)
4256 "Strip STRING whitespace and newlines from end and beginning."
4257 (replace-regexp-in-string
4258 (rx (or (: string-start
(* (any whitespace ?
\r ?
\n)))
4259 (: (* (any whitespace ?
\r ?
\n)) string-end
)))
4263 (defun python-util-valid-regexp-p (regexp)
4264 "Return non-nil if REGEXP is valid."
4265 (ignore-errors (string-match regexp
"") t
))
4268 (defun python-electric-pair-string-delimiter ()
4269 (when (and electric-pair-mode
4270 (memq last-command-event
'(?
\" ?
\'))
4272 (while (eq (char-before (- (point) count
)) last-command-event
)
4275 (eq (char-after) last-command-event
))
4276 (save-excursion (insert (make-string 2 last-command-event
)))))
4278 (defvar electric-indent-inhibit
)
4281 (define-derived-mode python-mode prog-mode
"Python"
4282 "Major mode for editing Python files.
4284 \\{python-mode-map}"
4285 (set (make-local-variable 'tab-width
) 8)
4286 (set (make-local-variable 'indent-tabs-mode
) nil
)
4288 (set (make-local-variable 'comment-start
) "# ")
4289 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
4291 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
4292 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
4294 (set (make-local-variable 'forward-sexp-function
)
4295 'python-nav-forward-sexp
)
4297 (set (make-local-variable 'font-lock-defaults
)
4298 '(python-font-lock-keywords nil nil nil nil
))
4300 (set (make-local-variable 'syntax-propertize-function
)
4301 python-syntax-propertize-function
)
4303 (set (make-local-variable 'indent-line-function
)
4304 #'python-indent-line-function
)
4305 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
4306 ;; Because indentation is not redundant, we cannot safely reindent code.
4307 (set (make-local-variable 'electric-indent-inhibit
) t
)
4308 (set (make-local-variable 'electric-indent-chars
)
4309 (cons ?
: electric-indent-chars
))
4311 ;; Add """ ... """ pairing to electric-pair-mode.
4312 (add-hook 'post-self-insert-hook
4313 #'python-electric-pair-string-delimiter
'append t
)
4315 (set (make-local-variable 'paragraph-start
) "\\s-*$")
4316 (set (make-local-variable 'fill-paragraph-function
)
4317 #'python-fill-paragraph
)
4319 (set (make-local-variable 'beginning-of-defun-function
)
4320 #'python-nav-beginning-of-defun
)
4321 (set (make-local-variable 'end-of-defun-function
)
4322 #'python-nav-end-of-defun
)
4324 (add-hook 'completion-at-point-functions
4325 #'python-completion-at-point nil
'local
)
4327 (add-hook 'post-self-insert-hook
4328 #'python-indent-post-self-insert-function
'append
'local
)
4330 (set (make-local-variable 'imenu-create-index-function
)
4331 #'python-imenu-create-index
)
4333 (set (make-local-variable 'add-log-current-defun-function
)
4334 #'python-info-current-defun
)
4336 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
4338 (set (make-local-variable 'skeleton-further-elements
)
4340 (< '(backward-delete-char-untabify (min python-indent-offset
4342 (^
'(- (1+ (current-indentation))))))
4344 (set (make-local-variable 'eldoc-documentation-function
)
4345 #'python-eldoc-function
)
4347 (add-to-list 'hs-special-modes-alist
4348 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
4350 (python-nav-end-of-defun))
4353 (set (make-local-variable 'outline-regexp
)
4354 (python-rx (* space
) block-start
))
4355 (set (make-local-variable 'outline-heading-end-regexp
) ":[^\n]*\n")
4356 (set (make-local-variable 'outline-level
)
4358 "`outline-level' function for Python mode."
4359 (1+ (/ (current-indentation) python-indent-offset
))))
4361 (python-skeleton-add-menu-items)
4363 (make-local-variable 'python-shell-internal-buffer
)
4365 (when python-indent-guess-indent-offset
4366 (python-indent-guess-indent-offset)))
4373 ;; indent-tabs-mode: nil
4376 ;;; python.el ends here