]> code.delx.au - gnu-emacs/blob - lisp/progmodes/python.el
Merge branch 'emacs-24'.
[gnu-emacs] / lisp / progmodes / python.el
1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2003-2014 Free Software Foundation, Inc.
4
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
7 ;; Version: 0.24.4
8 ;; Maintainer: emacs-devel@gnu.org
9 ;; Created: Jul 2010
10 ;; Keywords: languages
11
12 ;; This file is part of GNU Emacs.
13
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.
18
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.
23
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/>.
26
27 ;;; Commentary:
28
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.
32
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.
37
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
40
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.
46
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':
61
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
64
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.
68
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:
76
77 ;; (setq python-shell-interpreter "ipython"
78 ;; python-shell-interpreter-args "-i")
79
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.
87
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
91 ;; your system):
92
93 ;; (setq python-shell-interpreter "C:\\Python27\\python.exe"
94 ;; python-shell-interpreter-args
95 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
96
97 ;; Missing or delayed output used to happen due to differences between
98 ;; Operating Systems' pipe buffering (e.g. CPython 3.3.4 in Windows 7.
99 ;; See URL `http://debbugs.gnu.org/cgi/bugreport.cgi?bug=17304'). To
100 ;; avoid this, the `python-shell-unbuffered' defaults to non-nil and
101 ;; controls whether `python-shell-calculate-process-environment'
102 ;; should set the "PYTHONUNBUFFERED" environment variable on startup:
103 ;; See URL `https://docs.python.org/3/using/cmdline.html#cmdoption-u'.
104
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.
120
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:
134
135 ;; >>> import readline, rlcompleter
136
137 ;; If you see an error, then you need to either install pyreadline or
138 ;; setup custom code that avoids that dependency.
139
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/
147 ;; virtualenv:
148
149 ;; (setq python-shell-process-environment
150 ;; (list
151 ;; (format "PATH=%s" (mapconcat
152 ;; 'identity
153 ;; (reverse
154 ;; (cons (getenv "PATH")
155 ;; '("/path/to/env/bin/")))
156 ;; ":"))
157 ;; "VIRTUAL_ENV=/path/to/env/"))
158 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
159
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:
166
167 ;; (setq python-shell-virtualenv-root "/path/to/env/")
168
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.
172
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.
176
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.
182
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.
186
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.
190
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>'.
198
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
201 ;; running.
202
203 ;; Code check: Check the current file for errors with `python-check'
204 ;; using the program defined in `python-check-command'.
205
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.
210
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.
219
220 ;; If you used python-mode.el you probably will miss auto-indentation
221 ;; when inserting newlines. To achieve the same behavior you have
222 ;; two options:
223
224 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
225
226 ;; 2) Add the following hook in your .emacs:
227
228 ;; (add-hook 'python-mode-hook
229 ;; #'(lambda ()
230 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
231
232 ;; I'd recommend the first one since you'll get the same behavior for
233 ;; all modes out-of-the-box.
234
235 ;;; Installation:
236
237 ;; Add this to your .emacs:
238
239 ;; (add-to-list 'load-path "/folder/containing/file")
240 ;; (require 'python)
241
242 ;;; TODO:
243
244 ;;; Code:
245
246 (require 'ansi-color)
247 (require 'cl-lib)
248 (require 'comint)
249 (require 'json)
250
251 ;; Avoid compiler warnings
252 (defvar view-return-to-alist)
253 (defvar compilation-error-regexp-alist)
254 (defvar outline-heading-end-regexp)
255
256 (autoload 'comint-mode "comint")
257
258 ;;;###autoload
259 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
260 ;;;###autoload
261 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
262
263 (defgroup python nil
264 "Python Language's flying circus support for Emacs."
265 :group 'languages
266 :version "24.3"
267 :link '(emacs-commentary-link "python"))
268
269 \f
270 ;;; Bindings
271
272 (defvar python-mode-map
273 (let ((map (make-sparse-keymap)))
274 ;; Movement
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)
279 ;; Indent specific
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)
284 ;; Skeletons
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)
292 ;; Shell interaction
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)
303 ;; Utilities
304 (substitute-key-definition 'complete-symbol 'completion-at-point
305 map global-map)
306 (easy-menu-define python-menu map "Python Mode menu"
307 `("Python"
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"]
313 "-"
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"]
322 "--"
323 ("Skeletons")
324 "---"
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"]
340 "----"
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"]))
347 map)
348 "Keymap for `python-mode'.")
349
350 \f
351 ;;; Python specialized rx
352
353 (eval-when-compile
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")
358 symbol-end))
359 (dedenter . ,(rx symbol-start
360 (or "elif" "else" "except" "finally")
361 symbol-end))
362 (block-ender . ,(rx symbol-start
363 (or
364 "break" "continue" "pass" "raise" "return")
365 symbol-end))
366 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
367 (* (any word ?_))))
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 ?' ?\")
372 (* space) ?:))
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
379 (not
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 ?\' ?\")))
394 (* ?\\ ?\\)
395 ;; Match single or triple quotes of any kind.
396 (group (or "\"" "\"\"\"" "'" "'''"))))))
397 "Additional Python specific sexps for `python-rx'")
398
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)
404 (error "No regexp"))
405 ((cdr regexps)
406 (rx-to-string `(and ,@regexps) t))
407 (t
408 (rx-to-string (car regexps) t))))))
409
410 \f
411 ;;; Font-lock and syntax
412
413 (eval-when-compile
414 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
415 (pcase type
416 (`'comment
417 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
418 (and (nth 4 ppss) (nth 8 ppss))))
419 (`'string
420 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
421 (and (nth 3 ppss) (nth 8 ppss))))
422 (`'paren
423 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
424 (_ form))))
425
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))))
432 (pcase type
433 (`comment (and (nth 4 ppss) (nth 8 ppss)))
434 (`string (and (nth 3 ppss) (nth 8 ppss)))
435 (`paren (nth 1 ppss))
436 (_ nil))))
437
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))))
442 (cond
443 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
444 ((nth 1 ppss) 'paren))))
445
446 (defsubst python-syntax-comment-or-string-p ()
447 "Return non-nil if point is inside 'comment or 'string."
448 (nth 8 (syntax-ppss)))
449
450 (define-obsolete-function-alias
451 'python-info-ppss-context #'python-syntax-context "24.3")
452
453 (define-obsolete-function-alias
454 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
455
456 (define-obsolete-function-alias
457 'python-info-ppss-comment-or-string-p
458 #'python-syntax-comment-or-string-p "24.3")
459
460 (defvar python-font-lock-keywords
461 ;; Keywords
462 `(,(rx symbol-start
463 (or
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"
467 "try"
468 ;; Python 2:
469 "print" "exec"
470 ;; Python 3:
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
474 ;; Python versions.
475 "nonlocal"
476 ;; Extra:
477 "self")
478 symbol-end)
479 ;; functions
480 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
481 (1 font-lock-function-name-face))
482 ;; classes
483 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
484 (1 font-lock-type-face))
485 ;; Constants
486 (,(rx symbol-start
487 (or
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)
493 ;; Decorators.
494 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
495 (0+ "." (1+ (or word ?_)))))
496 (1 font-lock-type-face))
497 ;; Builtin Exceptions
498 (,(rx symbol-start
499 (or
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"
512 ;; Python 2:
513 "StandardError"
514 ;; Python 3:
515 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
516 "TabError")
517 symbol-end) . font-lock-type-face)
518 ;; Builtins
519 (,(rx symbol-start
520 (or
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"
529 "__import__"
530 ;; Python 2:
531 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
532 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
533 "intern"
534 ;; Python 3:
535 "ascii" "bytearray" "bytes" "exec"
536 ;; Extra:
537 "__all__" "__doc__" "__name__" "__package__")
538 symbol-end) . font-lock-builtin-face)
539 ;; assignments
540 ;; support for a = b = c = 5
541 (,(lambda (limit)
542 (let ((re (python-rx (group (+ (any word ?. ?_)))
543 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
544 assignment-operator))
545 (res nil))
546 (while (and (setq res (re-search-forward re limit t))
547 (or (python-syntax-context 'paren)
548 (equal (char-after (point)) ?=))))
549 res))
550 (1 font-lock-variable-name-face nil nil))
551 ;; support for a, b, c = (1, 2, 3)
552 (,(lambda (limit)
553 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
554 (* ?, (* space) (+ (any word ?. ?_)) (* space))
555 ?, (* space) (+ (any word ?. ?_)) (* space)
556 assignment-operator))
557 (res nil))
558 (while (and (setq res (re-search-forward re limit t))
559 (goto-char (match-end 1))
560 (python-syntax-context 'paren)))
561 res))
562 (1 font-lock-variable-name-face nil nil))))
563
564 (defconst python-syntax-propertize-function
565 (syntax-propertize-rules
566 ((python-rx string-delimiter)
567 (0 (ignore (python-syntax-stringify))))))
568
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."
574 (let ((i 0))
575 (while (and (< i 3)
576 (or (not limit) (< (+ point i) limit))
577 (eq (char-after (+ point i)) quote-char))
578 (setq i (1+ i)))
579 i))
580
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)))
584 (ppss (prog2
585 (backward-char num-quotes)
586 (syntax-ppss)
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))
591 (num-closing-quotes
592 (and string-start
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
597 ;; kind. Do nothing.
598 nil)
599 ((not string-start)
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
610 ;; all three quotes.
611 (put-text-property quote-starting-pos quote-ending-pos
612 'syntax-table (string-to-syntax "|"))))))
613
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)))
620 (dotimes (i 128)
621 (unless (= i ?_)
622 (if (equal symbol (aref sst i))
623 (modify-syntax-entry i "." table)))))
624 (modify-syntax-entry ?$ "." table)
625 (modify-syntax-entry ?% "." table)
626 ;; exceptions
627 (modify-syntax-entry ?# "<" table)
628 (modify-syntax-entry ?\n ">" table)
629 (modify-syntax-entry ?' "\"" table)
630 (modify-syntax-entry ?` "$" table)
631 table)
632 "Syntax table for Python files.")
633
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)
638 table)
639 "Dotty syntax table for Python files.
640 It makes underscores and dots word constituent chars.")
641
642 \f
643 ;;; Indentation
644
645 (defcustom python-indent-offset 4
646 "Default indentation offset for Python."
647 :group 'python
648 :type 'integer
649 :safe 'integerp)
650
651 (defcustom python-indent-guess-indent-offset t
652 "Non-nil tells Python mode to guess `python-indent-offset' value."
653 :type 'boolean
654 :group 'python
655 :safe 'booleanp)
656
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)
661 :group 'python)
662
663 (define-obsolete-variable-alias
664 'python-indent 'python-indent-offset "24.3")
665
666 (define-obsolete-variable-alias
667 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
668
669 (defvar python-indent-current-level 0
670 "Current indentation level `python-indent-line-function' is using.")
671
672 (defvar python-indent-levels '(0)
673 "Levels of indentation available for `python-indent-line-function'.")
674
675 (defun python-indent-guess-indent-offset ()
676 "Guess and set `python-indent-offset' for the current buffer."
677 (interactive)
678 (save-excursion
679 (save-restriction
680 (widen)
681 (goto-char (point-min))
682 (let ((block-end))
683 (while (and (not block-end)
684 (re-search-forward
685 (python-rx line-start block-start) nil t))
686 (when (and
687 (not (python-syntax-context-type))
688 (progn
689 (goto-char (line-end-position))
690 (python-util-forward-comment -1)
691 (if (equal (char-before) ?:)
692 t
693 (forward-line 1)
694 (when (python-info-block-continuation-line-p)
695 (while (and (python-info-continuation-line-p)
696 (not (eobp)))
697 (forward-line 1))
698 (python-util-forward-comment -1)
699 (when (equal (char-before) ?:)
700 t)))))
701 (setq block-end (point-marker))))
702 (let ((indentation
703 (when block-end
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)))))))
711
712 (defun python-indent-context ()
713 "Get information on indentation context.
714 Context information is returned with a cons with the form:
715 (STATUS . START)
716
717 Where status can be any of the following symbols:
718
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."
728 (save-restriction
729 (widen)
730 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
731 (start))
732 (cons
733 (cond
734 ;; Beginning of buffer
735 ((save-excursion
736 (goto-char (line-beginning-position))
737 (bobp))
738 'no-indent)
739 ;; Comment continuation
740 ((save-excursion
741 (when (and
742 (or
743 (python-info-current-line-comment-p)
744 (python-info-current-line-empty-p))
745 (progn
746 (forward-comment -1)
747 (python-info-current-line-comment-p)))
748 (setq start (point))
749 'after-comment)))
750 ;; Inside string
751 ((setq start (python-syntax-context 'string ppss))
752 'inside-string)
753 ;; Inside a paren
754 ((setq start (python-syntax-context 'paren ppss))
755 'inside-paren)
756 ;; After backslash
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)))))
762 'after-backslash)
763 ;; After beginning of block
764 ((setq start (save-excursion
765 (when (progn
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)
774 (or
775 (python-syntax-context-type)
776 (python-info-continuation-line-p))))
777 (when (looking-at (python-rx block-start))
778 (point-marker)))))
779 'after-beginning-of-block)
780 ((when (setq start (python-info-dedenter-statement-p))
781 'dedenter-statement))
782 ;; After normal line
783 ((setq start (save-excursion
784 (back-to-indentation)
785 (skip-chars-backward (rx (or whitespace ?\n)))
786 (python-nav-beginning-of-statement)
787 (point-marker)))
788 'after-line)
789 ;; Do not indent
790 (t 'no-indent))
791 start))))
792
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)))
798 (save-restriction
799 (widen)
800 (save-excursion
801 (pcase context-status
802 (`no-indent 0)
803 (`after-comment
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
812 ;; indentation.
813 (`after-line
814 (let* ((pair (save-excursion
815 (goto-char context-start)
816 (cons
817 (current-indentation)
818 (python-info-beginning-of-block-p))))
819 (context-indentation (car pair))
820 ;; TODO: Separate block enders into its own case.
821 (adjustment
822 (if (save-excursion
823 (python-util-forward-comment -1)
824 (python-nav-beginning-of-statement)
825 (looking-at (python-rx block-ender)))
826 python-indent-offset
827 0)))
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.
833 (`dedenter-statement
834 (let ((block-start-point
835 (python-info-dedenter-opening-block-position)))
836 (save-excursion
837 (if (not block-start-point)
838 0
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
844 (`inside-string
845 (goto-char context-start)
846 (current-indentation))
847 ;; After backslash we have several possibilities.
848 (`after-backslash
849 (cond
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.
853 ((save-excursion
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
858 (while (prog2
859 (forward-line -1)
860 (and (not (bobp))
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
871 (current-column)
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)
883 (re-search-forward
884 (python-rx block-start (* space))
885 (line-end-position) t)
886 (current-column))))
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)
895 (current-column))))
896 (t
897 (forward-line -1)
898 (goto-char (python-info-beginning-of-backslash))
899 (if (save-excursion
900 (and
901 (forward-line -1)
902 (goto-char
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
913 ;; correctly
914 (`inside-paren
915 (cond
916 ;; If current line closes the outermost open paren use the
917 ;; current indentation of the context-start line.
918 ((save-excursion
919 (skip-syntax-forward "\s" (line-end-position))
920 (when (and (looking-at (regexp-opt '(")" "]" "}")))
921 (progn
922 (forward-char 1)
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
929 ;; level.
930 ((let* ((content-starts-in-newline)
931 (indent
932 (save-excursion
933 (if (setq content-starts-in-newline
934 (progn
935 (goto-char context-start)
936 (forward-char)
937 (save-restriction
938 (narrow-to-region
939 (line-beginning-position)
940 (line-end-position))
941 (python-util-forward-comment))
942 (looking-at "$")))
943 (+ (current-indentation) python-indent-offset)
944 (current-column)))))
945 ;; Adjustments
946 (cond
947 ;; If current line closes a nested open paren de-indent one
948 ;; level.
949 ((progn
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
956 ((save-excursion
957 (when (and content-starts-in-newline
958 (progn
959 (goto-char context-start)
960 (back-to-indentation)
961 (looking-at (python-rx block-start))))
962 (+ indent python-indent-offset))))
963 (t indent)))))))))))
964
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
981 (or
982 (mapcar (lambda (pos)
983 (save-excursion
984 (goto-char pos)
985 (current-indentation)))
986 (python-info-dedenter-opening-block-positions))
987 (list 0))))
988 (setq python-indent-current-level (1- (length python-indent-levels))
989 python-indent-levels (nreverse python-indent-levels)))
990
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)))))
996
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.
1003
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'.
1009
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
1015 equal to
1016 (nth python-indent-current-level python-indent-levels)"
1017 (or
1018 (and (or (and (memq this-command python-indent-trigger-commands)
1019 (eq last-command this-command))
1020 force-toggle)
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
1028 (or (bolp)
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))
1033 (beginning-of-line)
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))
1039
1040 (defun python-indent-line-function ()
1041 "`indent-line-function' for Python mode.
1042 See `python-indent-line' for details."
1043 (python-indent-line))
1044
1045 (defun python-indent-dedent-line ()
1046 "De-indent current line."
1047 (interactive "*")
1048 (when (and (not (python-syntax-comment-or-string-p))
1049 (<= (point) (save-excursion
1050 (back-to-indentation)
1051 (point)))
1052 (> (current-column) 0))
1053 (python-indent-line t)
1054 t))
1055
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."
1060 (interactive "*p")
1061 (when (not (python-indent-dedent-line))
1062 (backward-delete-char-untabify arg)))
1063 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1064
1065 (defun python-indent-region (start end)
1066 "Indent a Python region automagically.
1067
1068 Called from a program, START and END specify the region to indent."
1069 (let ((deactivate-mark nil))
1070 (save-excursion
1071 (goto-char end)
1072 (setq end (point-marker))
1073 (goto-char start)
1074 (or (bolp) (forward-line 1))
1075 (while (< (point) end)
1076 (or (and (bolp) (eolp))
1077 (when (and
1078 ;; Skip if previous line is empty or a comment.
1079 (save-excursion
1080 (let ((line-is-comment-p
1081 (python-info-current-line-comment-p)))
1082 (forward-line -1)
1083 (not
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))
1091 (eq
1092 (syntax-after
1093 (+ (1- (point))
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.
1099 (save-excursion
1100 (back-to-indentation)
1101 (not (looking-at
1102 (python-rx
1103 (or block-start dedenter block-ender))))))
1104 (python-indent-line)))
1105 (forward-line 1))
1106 (move-marker end nil))))
1107
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."
1114 (interactive
1115 (if mark-active
1116 (list (region-beginning) (region-end) current-prefix-arg)
1117 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1118 (if count
1119 (setq count (prefix-numeric-value count))
1120 (setq count python-indent-offset))
1121 (when (> count 0)
1122 (let ((deactivate-mark nil))
1123 (save-excursion
1124 (goto-char start)
1125 (while (< (point) end)
1126 (if (and (< (current-indentation) count)
1127 (not (looking-at "[ \t]*$")))
1128 (user-error "Can't shift all lines enough"))
1129 (forward-line))
1130 (indent-rigidly start end (- count))))))
1131
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."
1137 (interactive
1138 (if mark-active
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)))
1145
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))
1153 (cond
1154 ;; Electric indent inside parens
1155 ((and
1156 (not (bolp))
1157 (let ((paren-start (python-syntax-context 'paren)))
1158 ;; Check that point is inside parens.
1159 (when paren-start
1160 (not
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.
1167 (or
1168 (memq (char-after) '(?\) ?\] ?\}))
1169 (eq (char-before) ?,)))
1170 (save-excursion
1171 (goto-char (line-beginning-position))
1172 (let ((indentation (python-indent-calculate-indentation)))
1173 (when (< (current-indentation) indentation)
1174 (indent-line-to indentation)))))
1175 ;; Electric colon
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
1180 (eolp)
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)))))
1189
1190 \f
1191 ;;; Navigation
1192
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'.")
1198
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))
1209 (beg-indentation
1210 (and (> arg 0)
1211 (save-excursion
1212 (while (and
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))
1217 0))))
1218 (found
1219 (progn
1220 (when (and (< arg 0)
1221 (python-info-looking-at-beginning-of-defun))
1222 (end-of-line 1))
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.
1228 (and (> arg 0)
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)))))))
1237 (if found
1238 (or (beginning-of-line 1) t)
1239 (and (goto-char pos) nil))))
1240
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))
1249 (let ((found))
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))
1254 (setq found t))
1255 keep-searching-p))
1256 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1257 found))
1258
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."
1262 (interactive)
1263 (let ((beg-defun-indent)
1264 (beg-pos (point)))
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))
1269 (while (progn
1270 (python-nav-end-of-statement)
1271 (python-util-forward-comment 1)
1272 (and (> (current-indentation) beg-defun-indent)
1273 (not (eobp)))))
1274 (python-util-forward-comment -1)
1275 (forward-line 1)
1276 ;; Ensure point moves forward.
1277 (and (> beg-pos (point)) (goto-char beg-pos)))))
1278
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
1287 be skipped."
1288 (let ((contextfn (or contextfn 'python-syntax-context-type))
1289 (start-pos (point-marker))
1290 (prev-pos))
1291 (catch 'found
1292 (while t
1293 (let* ((newpos
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))))))))
1305
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
1309 repeat it."
1310 (let ((found))
1311 (while (and (> arg 0)
1312 (setq found
1313 (python-nav--syntactically
1314 (lambda ()
1315 (re-search-forward
1316 python-nav-beginning-of-defun-regexp nil t))
1317 '>)))
1318 (setq arg (1- arg)))
1319 (while (and (< arg 0)
1320 (setq found
1321 (python-nav--syntactically
1322 (lambda ()
1323 (re-search-backward
1324 python-nav-beginning-of-defun-regexp nil t))
1325 '<)))
1326 (setq arg (1+ arg)))
1327 found))
1328
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."
1333 (interactive "^p")
1334 (python-nav--forward-defun (- (or arg 1))))
1335
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."
1340 (interactive "^p")
1341 (python-nav--forward-defun (or arg 1)))
1342
1343 (defun python-nav-beginning-of-statement ()
1344 "Move to start of current statement."
1345 (interactive "^")
1346 (back-to-indentation)
1347 (let* ((ppss (syntax-ppss))
1348 (context-point
1349 (or
1350 (python-syntax-context 'paren ppss)
1351 (python-syntax-context 'string ppss))))
1352 (cond ((bobp))
1353 (context-point
1354 (goto-char context-point)
1355 (python-nav-beginning-of-statement))
1356 ((save-excursion
1357 (forward-line -1)
1358 (python-info-line-ends-backslash-p))
1359 (forward-line -1)
1360 (python-nav-beginning-of-statement))))
1361 (point-marker))
1362
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
1367 of the statement."
1368 (interactive "^")
1369 (let (string-start bs-pos)
1370 (while (and (or noend (goto-char (line-end-position)))
1371 (not (eobp))
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.
1387 (condition-case err
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))
1391 (goto-char bs-pos)
1392 (forward-line 1))))))
1393 (point-marker))
1394
1395 (defun python-nav-backward-statement (&optional arg)
1396 "Move backward to previous statement.
1397 With ARG, repeat. See `python-nav-forward-statement'."
1398 (interactive "^p")
1399 (or arg (setq arg 1))
1400 (python-nav-forward-statement (- arg)))
1401
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."
1406 (interactive "^p")
1407 (or arg (setq arg 1))
1408 (while (> arg 0)
1409 (python-nav-end-of-statement)
1410 (python-util-forward-comment)
1411 (python-nav-beginning-of-statement)
1412 (setq arg (1- arg)))
1413 (while (< arg 0)
1414 (python-nav-beginning-of-statement)
1415 (python-util-forward-comment -1)
1416 (python-nav-beginning-of-statement)
1417 (setq arg (1+ arg))))
1418
1419 (defun python-nav-beginning-of-block ()
1420 "Move to start of current block."
1421 (interactive "^")
1422 (let ((starting-pos (point)))
1423 (if (progn
1424 (python-nav-beginning-of-statement)
1425 (looking-at (python-rx block-start)))
1426 (point-marker)
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)))
1432 (forward-line -1))
1433 (let ((block-matching-indent
1434 (- (current-indentation) python-indent-offset)))
1435 (while
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))
1440 (point-marker)
1441 (and (goto-char starting-pos) nil))))))
1442
1443 (defun python-nav-end-of-block ()
1444 "Move to end of current block."
1445 (interactive "^")
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)
1450 (not (eobp))
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)
1456 (point-marker))))
1457
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'."
1461 (interactive "^p")
1462 (or arg (setq arg 1))
1463 (python-nav-forward-block (- arg)))
1464
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."
1469 (interactive "^p")
1470 (or arg (setq arg 1))
1471 (let ((block-start-regexp
1472 (python-rx line-start (* whitespace) block-start))
1473 (starting-pos (point)))
1474 (while (> arg 0)
1475 (python-nav-end-of-statement)
1476 (while (and
1477 (re-search-forward block-start-regexp nil t)
1478 (python-syntax-context-type)))
1479 (setq arg (1- arg)))
1480 (while (< arg 0)
1481 (python-nav-beginning-of-statement)
1482 (while (and
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)))))
1490
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)))
1499
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))
1506 (paren-regexp
1507 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1508 (search-fn
1509 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1510 (condition-case nil
1511 (python-nav--lisp-forward-sexp arg)
1512 (error
1513 (while (and (funcall search-fn paren-regexp nil t)
1514 (python-syntax-context 'paren)))))))
1515
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))
1522 (unless (= dir 0)
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)))
1527 (cond
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.
1538 (if safe
1539 (python-nav--lisp-forward-sexp-safe dir)
1540 (python-nav--lisp-forward-sexp dir)))
1541 (t
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.
1546 (let* ((context
1547 (cond
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)))
1552 (next-sexp-pos
1553 (save-excursion
1554 (if safe
1555 (python-nav--lisp-forward-sexp-safe dir)
1556 (python-nav--lisp-forward-sexp dir))
1557 (point)))
1558 (next-sexp-context
1559 (save-excursion
1560 (goto-char next-sexp-pos)
1561 (cond
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)))))
1568 (if forward-p
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))))))))))
1609
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
1613 backward N times."
1614 (interactive "^p")
1615 (or arg (setq arg 1))
1616 (while (> arg 0)
1617 (python-nav--forward-sexp 1)
1618 (setq arg (1- arg)))
1619 (while (< arg 0)
1620 (python-nav--forward-sexp -1)
1621 (setq arg (1+ arg))))
1622
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
1626 forward N times."
1627 (interactive "^p")
1628 (or arg (setq arg 1))
1629 (python-nav-forward-sexp (- arg)))
1630
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
1634 backward N times."
1635 (interactive "^p")
1636 (or arg (setq arg 1))
1637 (while (> arg 0)
1638 (python-nav--forward-sexp 1 t)
1639 (setq arg (1- arg)))
1640 (while (< arg 0)
1641 (python-nav--forward-sexp -1 t)
1642 (setq arg (1+ arg))))
1643
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
1647 forward N times."
1648 (interactive "^p")
1649 (or arg (setq arg 1))
1650 (python-nav-forward-sexp-safe (- arg)))
1651
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)))
1658 (cond
1659 ((memq context '(string comment)))
1660 ((eq context 'paren)
1661 (let ((forward-sexp-function))
1662 (up-list dir)))
1663 ((and forward-p (python-info-end-of-block-p))
1664 (let ((parent-end-pos
1665 (save-excursion
1666 (let ((indentation (and
1667 (python-nav-beginning-of-block)
1668 (current-indentation))))
1669 (while (and indentation
1670 (> indentation 0)
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
1681 (save-excursion
1682 (let ((indentation (current-indentation)))
1683 (while (and (python-nav-backward-block)
1684 (>= (current-indentation) indentation))))
1685 (point))))
1686 (and (> (point) prev-block-pos)
1687 (goto-char prev-block-pos))))
1688 ((not forward-p) (python-nav-beginning-of-block)))))
1689
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."
1695 (interactive "^p")
1696 (or arg (setq arg 1))
1697 (while (> arg 0)
1698 (python-nav--up-list 1)
1699 (setq arg (1- arg)))
1700 (while (< arg 0)
1701 (python-nav--up-list -1)
1702 (setq arg (1+ arg))))
1703
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."
1709 (interactive "^p")
1710 (or arg (setq arg 1))
1711 (python-nav-up-list (- arg)))
1712
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."
1717 (interactive)
1718 (let ((point (point))
1719 (found (catch 'found
1720 (goto-char (point-min))
1721 (while (re-search-forward
1722 (python-rx line-start
1723 "if" (+ space)
1724 "__name__" (+ space)
1725 "==" (+ space)
1726 (group-n 1 (or ?\" ?\'))
1727 "__main__" (backref 1) (* space) ":")
1728 nil t)
1729 (when (not (python-syntax-context-type))
1730 (beginning-of-line)
1731 (throw 'found t))))))
1732 (if found
1733 (point)
1734 (ignore (goto-char point)))))
1735
1736 \f
1737 ;;; Shell integration
1738
1739 (defcustom python-shell-buffer-name "Python"
1740 "Default buffer name for Python interpreter."
1741 :type 'string
1742 :group 'python
1743 :safe 'stringp)
1744
1745 (defcustom python-shell-interpreter "python"
1746 "Default Python interpreter for shell."
1747 :type 'string
1748 :group 'python)
1749
1750 (defcustom python-shell-internal-buffer-name "Python Internal"
1751 "Default buffer name for the Internal Python interpreter."
1752 :type 'string
1753 :group 'python
1754 :safe 'stringp)
1755
1756 (defcustom python-shell-interpreter-args "-i"
1757 "Default arguments for the Python interpreter."
1758 :type 'string
1759 :group 'python)
1760
1761 (defcustom python-shell-interpreter-interactive-arg "-i"
1762 "Interpreter argument to force it to run interactively."
1763 :type 'string
1764 :version "24.4")
1765
1766 (defcustom python-shell-prompt-detect-enabled t
1767 "Non-nil enables autodetection of interpreter prompts."
1768 :type 'boolean
1769 :safe 'booleanp
1770 :version "24.4")
1771
1772 (defcustom python-shell-prompt-detect-failure-warning t
1773 "Non-nil enables warnings when detection of prompts fail."
1774 :type 'boolean
1775 :safe 'booleanp
1776 :version "24.4")
1777
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)
1787 :version "24.4")
1788
1789 (defcustom python-shell-prompt-output-regexps
1790 '("" ; Python
1791 "Out\\[[0-9]+\\]: " ; IPython
1792 "Out :") ; ipdb safeguard
1793 "List of regular expressions matching output prompts."
1794 :type '(repeat string)
1795 :version "24.4")
1796
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."
1800 :type 'string)
1801
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."
1805 :type 'string)
1806
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."
1810 :type 'string)
1811
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."
1815 :type 'string)
1816
1817 (define-obsolete-variable-alias
1818 'python-shell-enable-font-lock 'python-shell-font-lock-enable "25.1")
1819
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."
1823 :type 'boolean
1824 :group 'python
1825 :safe 'booleanp)
1826
1827 (defcustom python-shell-unbuffered t
1828 "Should shell output be unbuffered?.
1829 When non-nil, this may prevent delayed and missing output in the
1830 Python shell. See commentary for details."
1831 :type 'boolean
1832 :group 'python
1833 :safe 'booleanp)
1834
1835 (defcustom python-shell-process-environment nil
1836 "List of environment variables for Python shell.
1837 This variable follows the same rules as `process-environment'
1838 since it merges with it before the process creation routines are
1839 called. When this variable is nil, the Python shell is run with
1840 the default `process-environment'."
1841 :type '(repeat string)
1842 :group 'python
1843 :safe 'listp)
1844
1845 (defcustom python-shell-extra-pythonpaths nil
1846 "List of extra pythonpaths for Python shell.
1847 The values of this variable are added to the existing value of
1848 PYTHONPATH in the `process-environment' variable."
1849 :type '(repeat string)
1850 :group 'python
1851 :safe 'listp)
1852
1853 (defcustom python-shell-exec-path nil
1854 "List of path to search for binaries.
1855 This variable follows the same rules as `exec-path' since it
1856 merges with it before the process creation routines are called.
1857 When this variable is nil, the Python shell is run with the
1858 default `exec-path'."
1859 :type '(repeat string)
1860 :group 'python
1861 :safe 'listp)
1862
1863 (defcustom python-shell-virtualenv-root nil
1864 "Path to virtualenv root.
1865 This variable, when set to a string, makes the values stored in
1866 `python-shell-process-environment' and `python-shell-exec-path'
1867 to be modified properly so shells are started with the specified
1868 virtualenv."
1869 :type '(choice (const nil) string)
1870 :group 'python
1871 :safe 'stringp)
1872
1873 (define-obsolete-variable-alias
1874 'python-shell-virtualenv-path 'python-shell-virtualenv-root "25.1")
1875
1876 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1877 python-ffap-setup-code
1878 python-eldoc-setup-code)
1879 "List of code run by `python-shell-send-setup-codes'."
1880 :type '(repeat symbol)
1881 :group 'python
1882 :safe 'listp)
1883
1884 (defcustom python-shell-compilation-regexp-alist
1885 `((,(rx line-start (1+ (any " \t")) "File \""
1886 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1887 "\", line " (group (1+ digit)))
1888 1 2)
1889 (,(rx " in file " (group (1+ not-newline)) " on line "
1890 (group (1+ digit)))
1891 1 2)
1892 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1893 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1894 1 2))
1895 "`compilation-error-regexp-alist' for inferior Python."
1896 :type '(alist string)
1897 :group 'python)
1898
1899 (defvar python-shell--prompt-calculated-input-regexp nil
1900 "Calculated input prompt regexp for inferior python shell.
1901 Do not set this variable directly, instead use
1902 `python-shell-prompt-set-calculated-regexps'.")
1903
1904 (defvar python-shell--prompt-calculated-output-regexp nil
1905 "Calculated output prompt regexp for inferior python shell.
1906 Do not set this variable directly, instead use
1907 `python-shell-set-prompt-regexp'.")
1908
1909 (defun python-shell-prompt-detect ()
1910 "Detect prompts for the current `python-shell-interpreter'.
1911 When prompts can be retrieved successfully from the
1912 `python-shell-interpreter' run with
1913 `python-shell-interpreter-interactive-arg', returns a list of
1914 three elements, where the first two are input prompts and the
1915 last one is an output prompt. When no prompts can be detected
1916 and `python-shell-prompt-detect-failure-warning' is non-nil,
1917 shows a warning with instructions to avoid hangs and returns nil.
1918 When `python-shell-prompt-detect-enabled' is nil avoids any
1919 detection and just returns nil."
1920 (when python-shell-prompt-detect-enabled
1921 (let* ((process-environment (python-shell-calculate-process-environment))
1922 (exec-path (python-shell-calculate-exec-path))
1923 (code (concat
1924 "import sys\n"
1925 "ps = [getattr(sys, 'ps%s' % i, '') for i in range(1,4)]\n"
1926 ;; JSON is built manually for compatibility
1927 "ps_json = '\\n[\"%s\", \"%s\", \"%s\"]\\n' % tuple(ps)\n"
1928 "print (ps_json)\n"
1929 "sys.exit(0)\n"))
1930 (output
1931 (with-temp-buffer
1932 ;; TODO: improve error handling by using
1933 ;; `condition-case' and displaying the error message to
1934 ;; the user in the no-prompts warning.
1935 (ignore-errors
1936 (let ((code-file (python-shell--save-temp-file code)))
1937 ;; Use `process-file' as it is remote-host friendly.
1938 (process-file
1939 python-shell-interpreter
1940 code-file
1941 '(t nil)
1942 nil
1943 python-shell-interpreter-interactive-arg)
1944 ;; Try to cleanup
1945 (delete-file code-file)))
1946 (buffer-string)))
1947 (prompts
1948 (catch 'prompts
1949 (dolist (line (split-string output "\n" t))
1950 (let ((res
1951 ;; Check if current line is a valid JSON array
1952 (and (string= (substring line 0 2) "[\"")
1953 (ignore-errors
1954 ;; Return prompts as a list, not vector
1955 (append (json-read-from-string line) nil)))))
1956 ;; The list must contain 3 strings, where the first
1957 ;; is the input prompt, the second is the block
1958 ;; prompt and the last one is the output prompt. The
1959 ;; input prompt is the only one that can't be empty.
1960 (when (and (= (length res) 3)
1961 (cl-every #'stringp res)
1962 (not (string= (car res) "")))
1963 (throw 'prompts res))))
1964 nil)))
1965 (when (and (not prompts)
1966 python-shell-prompt-detect-failure-warning)
1967 (lwarn
1968 '(python python-shell-prompt-regexp)
1969 :warning
1970 (concat
1971 "Python shell prompts cannot be detected.\n"
1972 "If your emacs session hangs when starting python shells\n"
1973 "recover with `keyboard-quit' and then try fixing the\n"
1974 "interactive flag for your interpreter by adjusting the\n"
1975 "`python-shell-interpreter-interactive-arg' or add regexps\n"
1976 "matching shell prompts in the directory-local friendly vars:\n"
1977 " + `python-shell-prompt-regexp'\n"
1978 " + `python-shell-prompt-block-regexp'\n"
1979 " + `python-shell-prompt-output-regexp'\n"
1980 "Or alternatively in:\n"
1981 " + `python-shell-prompt-input-regexps'\n"
1982 " + `python-shell-prompt-output-regexps'")))
1983 prompts)))
1984
1985 (defun python-shell-prompt-validate-regexps ()
1986 "Validate all user provided regexps for prompts.
1987 Signals `user-error' if any of these vars contain invalid
1988 regexps: `python-shell-prompt-regexp',
1989 `python-shell-prompt-block-regexp',
1990 `python-shell-prompt-pdb-regexp',
1991 `python-shell-prompt-output-regexp',
1992 `python-shell-prompt-input-regexps',
1993 `python-shell-prompt-output-regexps'."
1994 (dolist (symbol (list 'python-shell-prompt-input-regexps
1995 'python-shell-prompt-output-regexps
1996 'python-shell-prompt-regexp
1997 'python-shell-prompt-block-regexp
1998 'python-shell-prompt-pdb-regexp
1999 'python-shell-prompt-output-regexp))
2000 (dolist (regexp (let ((regexps (symbol-value symbol)))
2001 (if (listp regexps)
2002 regexps
2003 (list regexps))))
2004 (when (not (python-util-valid-regexp-p regexp))
2005 (user-error "Invalid regexp %s in `%s'"
2006 regexp symbol)))))
2007
2008 (defun python-shell-prompt-set-calculated-regexps ()
2009 "Detect and set input and output prompt regexps.
2010 Build and set the values for `python-shell-input-prompt-regexp'
2011 and `python-shell-output-prompt-regexp' using the values from
2012 `python-shell-prompt-regexp', `python-shell-prompt-block-regexp',
2013 `python-shell-prompt-pdb-regexp',
2014 `python-shell-prompt-output-regexp',
2015 `python-shell-prompt-input-regexps',
2016 `python-shell-prompt-output-regexps' and detected prompts from
2017 `python-shell-prompt-detect'."
2018 (when (not (and python-shell--prompt-calculated-input-regexp
2019 python-shell--prompt-calculated-output-regexp))
2020 (let* ((detected-prompts (python-shell-prompt-detect))
2021 (input-prompts nil)
2022 (output-prompts nil)
2023 (build-regexp
2024 (lambda (prompts)
2025 (concat "^\\("
2026 (mapconcat #'identity
2027 (sort prompts
2028 (lambda (a b)
2029 (let ((length-a (length a))
2030 (length-b (length b)))
2031 (if (= length-a length-b)
2032 (string< a b)
2033 (> (length a) (length b))))))
2034 "\\|")
2035 "\\)"))))
2036 ;; Validate ALL regexps
2037 (python-shell-prompt-validate-regexps)
2038 ;; Collect all user defined input prompts
2039 (dolist (prompt (append python-shell-prompt-input-regexps
2040 (list python-shell-prompt-regexp
2041 python-shell-prompt-block-regexp
2042 python-shell-prompt-pdb-regexp)))
2043 (cl-pushnew prompt input-prompts :test #'string=))
2044 ;; Collect all user defined output prompts
2045 (dolist (prompt (cons python-shell-prompt-output-regexp
2046 python-shell-prompt-output-regexps))
2047 (cl-pushnew prompt output-prompts :test #'string=))
2048 ;; Collect detected prompts if any
2049 (when detected-prompts
2050 (dolist (prompt (butlast detected-prompts))
2051 (setq prompt (regexp-quote prompt))
2052 (cl-pushnew prompt input-prompts :test #'string=))
2053 (cl-pushnew (regexp-quote
2054 (car (last detected-prompts)))
2055 output-prompts :test #'string=))
2056 ;; Set input and output prompt regexps from collected prompts
2057 (setq python-shell--prompt-calculated-input-regexp
2058 (funcall build-regexp input-prompts)
2059 python-shell--prompt-calculated-output-regexp
2060 (funcall build-regexp output-prompts)))))
2061
2062 (defun python-shell-get-process-name (dedicated)
2063 "Calculate the appropriate process name for inferior Python process.
2064 If DEDICATED is t and the variable `buffer-file-name' is non-nil
2065 returns a string with the form
2066 `python-shell-buffer-name'[variable `buffer-file-name'] else
2067 returns the value of `python-shell-buffer-name'."
2068 (let ((process-name
2069 (if (and dedicated
2070 buffer-file-name)
2071 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
2072 (format "%s" python-shell-buffer-name))))
2073 process-name))
2074
2075 (defun python-shell-internal-get-process-name ()
2076 "Calculate the appropriate process name for Internal Python process.
2077 The name is calculated from `python-shell-global-buffer-name' and
2078 a hash of all relevant global shell settings in order to ensure
2079 uniqueness for different types of configurations."
2080 (format "%s [%s]"
2081 python-shell-internal-buffer-name
2082 (md5
2083 (concat
2084 python-shell-interpreter
2085 python-shell-interpreter-args
2086 python-shell--prompt-calculated-input-regexp
2087 python-shell--prompt-calculated-output-regexp
2088 (mapconcat #'symbol-value python-shell-setup-codes "")
2089 (mapconcat #'identity python-shell-process-environment "")
2090 (mapconcat #'identity python-shell-extra-pythonpaths "")
2091 (mapconcat #'identity python-shell-exec-path "")
2092 (or python-shell-virtualenv-root "")
2093 (mapconcat #'identity python-shell-exec-path "")))))
2094
2095 (defun python-shell-calculate-command ()
2096 "Calculate the string used to execute the inferior Python process."
2097 (let ((exec-path (python-shell-calculate-exec-path)))
2098 ;; `exec-path' gets tweaked so that virtualenv's specific
2099 ;; `python-shell-interpreter' absolute path can be found by
2100 ;; `executable-find'.
2101 (format "%s %s"
2102 (executable-find python-shell-interpreter)
2103 python-shell-interpreter-args)))
2104
2105 (define-obsolete-function-alias
2106 'python-shell-parse-command
2107 #'python-shell-calculate-command "25.1")
2108
2109 (defun python-shell-calculate-pythonpath ()
2110 "Calculate the PYTHONPATH using `python-shell-extra-pythonpaths'."
2111 (let ((pythonpath (getenv "PYTHONPATH"))
2112 (extra (mapconcat 'identity
2113 python-shell-extra-pythonpaths
2114 path-separator)))
2115 (if pythonpath
2116 (concat extra path-separator pythonpath)
2117 extra)))
2118
2119 (defun python-shell-calculate-process-environment ()
2120 "Calculate process environment given `python-shell-virtualenv-root'."
2121 (let ((process-environment (append
2122 python-shell-process-environment
2123 process-environment nil))
2124 (virtualenv (if python-shell-virtualenv-root
2125 (directory-file-name python-shell-virtualenv-root)
2126 nil)))
2127 (when python-shell-unbuffered
2128 (setenv "PYTHONUNBUFFERED" "1"))
2129 (when python-shell-extra-pythonpaths
2130 (setenv "PYTHONPATH" (python-shell-calculate-pythonpath)))
2131 (if (not virtualenv)
2132 process-environment
2133 (setenv "PYTHONHOME" nil)
2134 (setenv "PATH" (format "%s/bin%s%s"
2135 virtualenv path-separator
2136 (or (getenv "PATH") "")))
2137 (setenv "VIRTUAL_ENV" virtualenv))
2138 process-environment))
2139
2140 (defun python-shell-calculate-exec-path ()
2141 "Calculate exec path given `python-shell-virtualenv-root'."
2142 (let ((path (append
2143 ;; Use nil as the tail so that the list is a full copy,
2144 ;; this is a paranoid safeguard for side-effects.
2145 python-shell-exec-path exec-path nil)))
2146 (if (not python-shell-virtualenv-root)
2147 path
2148 (cons (expand-file-name "bin" python-shell-virtualenv-root)
2149 path))))
2150
2151 (defvar python-shell--package-depth 10)
2152
2153 (defun python-shell-package-enable (directory package)
2154 "Add DIRECTORY parent to $PYTHONPATH and enable PACKAGE."
2155 (interactive
2156 (let* ((dir (expand-file-name
2157 (read-directory-name
2158 "Package root: "
2159 (file-name-directory
2160 (or (buffer-file-name) default-directory)))))
2161 (name (completing-read
2162 "Package: "
2163 (python-util-list-packages
2164 dir python-shell--package-depth))))
2165 (list dir name)))
2166 (python-shell-send-string
2167 (format
2168 (concat
2169 "import os.path;import sys;"
2170 "sys.path.append(os.path.dirname(os.path.dirname('''%s''')));"
2171 "__package__ = '''%s''';"
2172 "import %s")
2173 directory package package)
2174 (python-shell-get-process)))
2175
2176 (defun python-shell-accept-process-output (process &optional timeout regexp)
2177 "Accept PROCESS output with TIMEOUT until REGEXP is found.
2178 Optional argument TIMEOUT is the timeout argument to
2179 `accept-process-output' calls. Optional argument REGEXP
2180 overrides the regexp to match the end of output, defaults to
2181 `comint-prompt-regexp.'. Returns non-nil when output was
2182 properly captured.
2183
2184 This utility is useful in situations where the output may be
2185 received in chunks, since `accept-process-output' gives no
2186 guarantees they will be grabbed in a single call. An example use
2187 case for this would be the CPython shell start-up, where the
2188 banner and the initial prompt are received separately."
2189 (let ((regexp (or regexp comint-prompt-regexp)))
2190 (catch 'found
2191 (while t
2192 (when (not (accept-process-output process timeout))
2193 (throw 'found nil))
2194 (when (looking-back regexp)
2195 (throw 'found t))))))
2196
2197 (defun python-shell-comint-end-of-output-p (output)
2198 "Return non-nil if OUTPUT is ends with input prompt."
2199 (string-match
2200 ;; XXX: It seems on OSX an extra carriage return is attached
2201 ;; at the end of output, this handles that too.
2202 (concat
2203 "\r?\n?"
2204 ;; Remove initial caret from calculated regexp
2205 (replace-regexp-in-string
2206 (rx string-start ?^) ""
2207 python-shell--prompt-calculated-input-regexp)
2208 (rx eos))
2209 output))
2210
2211 (define-obsolete-function-alias
2212 'python-comint-output-filter-function
2213 'ansi-color-filter-apply
2214 "25.1")
2215
2216 (defun python-comint-postoutput-scroll-to-bottom (output)
2217 "Faster version of `comint-postoutput-scroll-to-bottom'.
2218 Avoids `recenter' calls until OUTPUT is completely sent."
2219 (when (and (not (string= "" output))
2220 (python-shell-comint-end-of-output-p
2221 (ansi-color-filter-apply output)))
2222 (comint-postoutput-scroll-to-bottom output))
2223 output)
2224
2225 (defvar python-shell--parent-buffer nil)
2226
2227 (defmacro python-shell-with-shell-buffer (&rest body)
2228 "Execute the forms in BODY with the shell buffer temporarily current.
2229 Signals an error if no shell buffer is available for current buffer."
2230 (declare (indent 0) (debug t))
2231 (let ((shell-buffer (make-symbol "shell-buffer")))
2232 `(let ((,shell-buffer (python-shell-get-buffer)))
2233 (when (not ,shell-buffer)
2234 (error "No inferior Python buffer available."))
2235 (with-current-buffer ,shell-buffer
2236 ,@body))))
2237
2238 (defvar python-shell--font-lock-buffer nil)
2239
2240 (defun python-shell-font-lock-get-or-create-buffer ()
2241 "Get or create a font-lock buffer for current inferior process."
2242 (python-shell-with-shell-buffer
2243 (if python-shell--font-lock-buffer
2244 python-shell--font-lock-buffer
2245 (let ((process-name
2246 (process-name (get-buffer-process (current-buffer)))))
2247 (generate-new-buffer
2248 (format "*%s-font-lock*" process-name))))))
2249
2250 (defun python-shell-font-lock-kill-buffer ()
2251 "Kill the font-lock buffer safely."
2252 (python-shell-with-shell-buffer
2253 (when (and python-shell--font-lock-buffer
2254 (buffer-live-p python-shell--font-lock-buffer))
2255 (kill-buffer python-shell--font-lock-buffer)
2256 (when (derived-mode-p 'inferior-python-mode)
2257 (setq python-shell--font-lock-buffer nil)))))
2258
2259 (defmacro python-shell-font-lock-with-font-lock-buffer (&rest body)
2260 "Execute the forms in BODY in the font-lock buffer.
2261 The value returned is the value of the last form in BODY. See
2262 also `with-current-buffer'."
2263 (declare (indent 0) (debug t))
2264 `(python-shell-with-shell-buffer
2265 (save-current-buffer
2266 (when (not (and python-shell--font-lock-buffer
2267 (get-buffer python-shell--font-lock-buffer)))
2268 (setq python-shell--font-lock-buffer
2269 (python-shell-font-lock-get-or-create-buffer)))
2270 (set-buffer python-shell--font-lock-buffer)
2271 (set (make-local-variable 'delay-mode-hooks) t)
2272 (let ((python-indent-guess-indent-offset nil))
2273 (when (not (derived-mode-p 'python-mode))
2274 (python-mode))
2275 ,@body))))
2276
2277 (defun python-shell-font-lock-cleanup-buffer ()
2278 "Cleanup the font-lock buffer.
2279 Provided as a command because this might be handy if something
2280 goes wrong and syntax highlighting in the shell gets messed up."
2281 (interactive)
2282 (python-shell-with-shell-buffer
2283 (python-shell-font-lock-with-font-lock-buffer
2284 (delete-region (point-min) (point-max)))))
2285
2286 (defun python-shell-font-lock-comint-output-filter-function (output)
2287 "Clean up the font-lock buffer after any OUTPUT."
2288 (when (and (not (string= "" output))
2289 ;; Is end of output and is not just a prompt.
2290 (not (member
2291 (python-shell-comint-end-of-output-p
2292 (ansi-color-filter-apply output))
2293 '(nil 0))))
2294 ;; If output is other than an input prompt then "real" output has
2295 ;; been received and the font-lock buffer must be cleaned up.
2296 (python-shell-font-lock-cleanup-buffer))
2297 output)
2298
2299 (defun python-shell-font-lock-post-command-hook ()
2300 "Fontifies current line in shell buffer."
2301 (if (eq this-command 'comint-send-input)
2302 ;; Add a newline when user sends input as this may be a block.
2303 (python-shell-font-lock-with-font-lock-buffer
2304 (goto-char (line-end-position))
2305 (newline))
2306 (when (and (python-util-comint-last-prompt)
2307 (> (point) (cdr (python-util-comint-last-prompt))))
2308 (let ((input (buffer-substring-no-properties
2309 (cdr (python-util-comint-last-prompt)) (point-max)))
2310 (old-input (python-shell-font-lock-with-font-lock-buffer
2311 (buffer-substring-no-properties
2312 (line-beginning-position) (point-max))))
2313 (current-point (point))
2314 (buffer-undo-list t))
2315 ;; When input hasn't changed, do nothing.
2316 (when (not (string= input old-input))
2317 (delete-region (cdr (python-util-comint-last-prompt)) (point-max))
2318 (insert
2319 (python-shell-font-lock-with-font-lock-buffer
2320 (delete-region (line-beginning-position)
2321 (line-end-position))
2322 (insert input)
2323 ;; Ensure buffer is fontified, keeping it
2324 ;; compatible with Emacs < 24.4.
2325 (if (fboundp 'font-lock-ensure)
2326 (funcall 'font-lock-ensure)
2327 (font-lock-default-fontify-buffer))
2328 ;; Replace FACE text properties with FONT-LOCK-FACE so
2329 ;; they are not overwritten by comint buffer's font lock.
2330 (python-util-text-properties-replace-name
2331 'face 'font-lock-face)
2332 (buffer-substring (line-beginning-position)
2333 (line-end-position))))
2334 (goto-char current-point))))))
2335
2336 (defun python-shell-font-lock-turn-on (&optional msg)
2337 "Turn on shell font-lock.
2338 With argument MSG show activation message."
2339 (interactive "p")
2340 (python-shell-with-shell-buffer
2341 (python-shell-font-lock-kill-buffer)
2342 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2343 (add-hook 'post-command-hook
2344 #'python-shell-font-lock-post-command-hook nil 'local)
2345 (add-hook 'kill-buffer-hook
2346 #'python-shell-font-lock-kill-buffer nil 'local)
2347 (add-hook 'comint-output-filter-functions
2348 #'python-shell-font-lock-comint-output-filter-function
2349 'append 'local)
2350 (when msg
2351 (message "Shell font-lock is enabled"))))
2352
2353 (defun python-shell-font-lock-turn-off (&optional msg)
2354 "Turn off shell font-lock.
2355 With argument MSG show deactivation message."
2356 (interactive "p")
2357 (python-shell-with-shell-buffer
2358 (python-shell-font-lock-kill-buffer)
2359 (when (python-util-comint-last-prompt)
2360 ;; Cleanup current fontification
2361 (remove-text-properties
2362 (cdr (python-util-comint-last-prompt))
2363 (line-end-position)
2364 '(face nil font-lock-face nil)))
2365 (set (make-local-variable 'python-shell--font-lock-buffer) nil)
2366 (remove-hook 'post-command-hook
2367 #'python-shell-font-lock-post-command-hook'local)
2368 (remove-hook 'kill-buffer-hook
2369 #'python-shell-font-lock-kill-buffer 'local)
2370 (remove-hook 'comint-output-filter-functions
2371 #'python-shell-font-lock-comint-output-filter-function
2372 'local)
2373 (when msg
2374 (message "Shell font-lock is disabled"))))
2375
2376 (defun python-shell-font-lock-toggle (&optional msg)
2377 "Toggle font-lock for shell.
2378 With argument MSG show activation/deactivation message."
2379 (interactive "p")
2380 (python-shell-with-shell-buffer
2381 (set (make-local-variable 'python-shell-font-lock-enable)
2382 (not python-shell-font-lock-enable))
2383 (if python-shell-font-lock-enable
2384 (python-shell-font-lock-turn-on msg)
2385 (python-shell-font-lock-turn-off msg))
2386 python-shell-font-lock-enable))
2387
2388 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
2389 "Major mode for Python inferior process.
2390 Runs a Python interpreter as a subprocess of Emacs, with Python
2391 I/O through an Emacs buffer. Variables `python-shell-interpreter'
2392 and `python-shell-interpreter-args' control which Python
2393 interpreter is run. Variables
2394 `python-shell-prompt-regexp',
2395 `python-shell-prompt-output-regexp',
2396 `python-shell-prompt-block-regexp',
2397 `python-shell-font-lock-enable',
2398 `python-shell-completion-setup-code',
2399 `python-shell-completion-string-code',
2400 `python-eldoc-setup-code', `python-eldoc-string-code',
2401 `python-ffap-setup-code' and `python-ffap-string-code' can
2402 customize this mode for different Python interpreters.
2403
2404 This mode resets `comint-output-filter-functions' locally, so you
2405 may want to re-add custom functions to it using the
2406 `inferior-python-mode-hook'.
2407
2408 You can also add additional setup code to be run at
2409 initialization of the interpreter via `python-shell-setup-codes'
2410 variable.
2411
2412 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
2413 (let ((interpreter python-shell-interpreter)
2414 (args python-shell-interpreter-args))
2415 (when python-shell--parent-buffer
2416 (python-util-clone-local-variables python-shell--parent-buffer))
2417 ;; Users can override default values for these vars when calling
2418 ;; `run-python'. This ensures new values let-bound in
2419 ;; `python-shell-make-comint' are locally set.
2420 (set (make-local-variable 'python-shell-interpreter) interpreter)
2421 (set (make-local-variable 'python-shell-interpreter-args) args))
2422 (set (make-local-variable 'python-shell--prompt-calculated-input-regexp) nil)
2423 (set (make-local-variable 'python-shell--prompt-calculated-output-regexp) nil)
2424 (python-shell-prompt-set-calculated-regexps)
2425 (setq comint-prompt-regexp python-shell--prompt-calculated-input-regexp
2426 comint-prompt-read-only t)
2427 (setq mode-line-process '(":%s"))
2428 (set (make-local-variable 'comint-output-filter-functions)
2429 '(ansi-color-process-output
2430 python-pdbtrack-comint-output-filter-function
2431 python-comint-postoutput-scroll-to-bottom))
2432 (set (make-local-variable 'compilation-error-regexp-alist)
2433 python-shell-compilation-regexp-alist)
2434 (add-hook 'completion-at-point-functions
2435 #'python-shell-completion-at-point nil 'local)
2436 (define-key inferior-python-mode-map "\t"
2437 'python-shell-completion-complete-or-indent)
2438 (make-local-variable 'python-pdbtrack-buffers-to-kill)
2439 (make-local-variable 'python-pdbtrack-tracked-buffer)
2440 (make-local-variable 'python-shell-internal-last-output)
2441 (when python-shell-font-lock-enable
2442 (python-shell-font-lock-turn-on))
2443 (compilation-shell-minor-mode 1)
2444 (python-shell-accept-process-output
2445 (get-buffer-process (current-buffer))))
2446
2447 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
2448 "Create a Python shell comint buffer.
2449 CMD is the Python command to be executed and PROC-NAME is the
2450 process name the comint buffer will get. After the comint buffer
2451 is created the `inferior-python-mode' is activated. When
2452 optional argument POP is non-nil the buffer is shown. When
2453 optional argument INTERNAL is non-nil this process is run on a
2454 buffer with a name that starts with a space, following the Emacs
2455 convention for temporary/internal buffers, and also makes sure
2456 the user is not queried for confirmation when the process is
2457 killed."
2458 (save-excursion
2459 (let* ((proc-buffer-name
2460 (format (if (not internal) "*%s*" " *%s*") proc-name))
2461 (process-environment (python-shell-calculate-process-environment))
2462 (exec-path (python-shell-calculate-exec-path)))
2463 (when (not (comint-check-proc proc-buffer-name))
2464 (let* ((cmdlist (split-string-and-unquote cmd))
2465 (interpreter (car cmdlist))
2466 (args (cdr cmdlist))
2467 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
2468 interpreter nil args))
2469 (python-shell--parent-buffer (current-buffer))
2470 (process (get-buffer-process buffer))
2471 ;; As the user may have overridden default values for
2472 ;; these vars on `run-python', let-binding them allows
2473 ;; to have the new right values in all setup code
2474 ;; that's is done in `inferior-python-mode', which is
2475 ;; important, especially for prompt detection.
2476 (python-shell-interpreter interpreter)
2477 (python-shell-interpreter-args
2478 (mapconcat #'identity args " ")))
2479 (with-current-buffer buffer
2480 (inferior-python-mode))
2481 (and pop (pop-to-buffer buffer t))
2482 (and internal (set-process-query-on-exit-flag process nil))))
2483 proc-buffer-name)))
2484
2485 ;;;###autoload
2486 (defun run-python (&optional cmd dedicated show)
2487 "Run an inferior Python process.
2488 Input and output via buffer named after
2489 `python-shell-buffer-name'. If there is a process already
2490 running in that buffer, just switch to it.
2491
2492 Argument CMD defaults to `python-shell-calculate-command' return
2493 value. When called interactively with `prefix-arg', it allows
2494 the user to edit such value and choose whether the interpreter
2495 should be DEDICATED for the current buffer. When numeric prefix
2496 arg is other than 0 or 4 do not SHOW.
2497
2498 Runs the hook `inferior-python-mode-hook' after
2499 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2500 process buffer for a list of commands.)"
2501 (interactive
2502 (if current-prefix-arg
2503 (list
2504 (read-shell-command "Run Python: " (python-shell-calculate-command))
2505 (y-or-n-p "Make dedicated process? ")
2506 (= (prefix-numeric-value current-prefix-arg) 4))
2507 (list (python-shell-calculate-command) nil t)))
2508 (python-shell-make-comint
2509 (or cmd (python-shell-calculate-command))
2510 (python-shell-get-process-name dedicated) show)
2511 dedicated)
2512
2513 (defun run-python-internal ()
2514 "Run an inferior Internal Python process.
2515 Input and output via buffer named after
2516 `python-shell-internal-buffer-name' and what
2517 `python-shell-internal-get-process-name' returns.
2518
2519 This new kind of shell is intended to be used for generic
2520 communication related to defined configurations; the main
2521 difference with global or dedicated shells is that these ones are
2522 attached to a configuration, not a buffer. This means that can
2523 be used for example to retrieve the sys.path and other stuff,
2524 without messing with user shells. Note that
2525 `python-shell-font-lock-enable' and `inferior-python-mode-hook'
2526 are set to nil for these shells, so setup codes are not sent at
2527 startup."
2528 (let ((python-shell-font-lock-enable nil)
2529 (inferior-python-mode-hook nil))
2530 (get-buffer-process
2531 (python-shell-make-comint
2532 (python-shell-calculate-command)
2533 (python-shell-internal-get-process-name) nil t))))
2534
2535 (defun python-shell-get-buffer ()
2536 "Return inferior Python buffer for current buffer.
2537 If current buffer is in `inferior-python-mode', return it."
2538 (if (derived-mode-p 'inferior-python-mode)
2539 (current-buffer)
2540 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2541 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2542 (global-proc-name (python-shell-get-process-name nil))
2543 (global-proc-buffer-name (format "*%s*" global-proc-name))
2544 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2545 (global-running (comint-check-proc global-proc-buffer-name)))
2546 ;; Always prefer dedicated
2547 (or (and dedicated-running dedicated-proc-buffer-name)
2548 (and global-running global-proc-buffer-name)))))
2549
2550 (defun python-shell-get-process ()
2551 "Return inferior Python process for current buffer."
2552 (get-buffer-process (python-shell-get-buffer)))
2553
2554 (defun python-shell-get-or-create-process (&optional cmd dedicated show)
2555 "Get or create an inferior Python process for current buffer and return it.
2556 Arguments CMD, DEDICATED and SHOW are those of `run-python' and
2557 are used to start the shell. If those arguments are not
2558 provided, `run-python' is called interactively and the user will
2559 be asked for their values."
2560 (let ((shell-process (python-shell-get-process)))
2561 (when (not shell-process)
2562 (if (not cmd)
2563 ;; XXX: Refactor code such that calling `run-python'
2564 ;; interactively is not needed anymore.
2565 (call-interactively 'run-python)
2566 (run-python cmd dedicated show)))
2567 (or shell-process (python-shell-get-process))))
2568
2569 (defvar python-shell-internal-buffer nil
2570 "Current internal shell buffer for the current buffer.
2571 This is really not necessary at all for the code to work but it's
2572 there for compatibility with CEDET.")
2573
2574 (defvar python-shell-internal-last-output nil
2575 "Last output captured by the internal shell.
2576 This is really not necessary at all for the code to work but it's
2577 there for compatibility with CEDET.")
2578
2579 (defun python-shell-internal-get-or-create-process ()
2580 "Get or create an inferior Internal Python process."
2581 (let* ((proc-name (python-shell-internal-get-process-name))
2582 (proc-buffer-name (format " *%s*" proc-name)))
2583 (when (not (process-live-p proc-name))
2584 (run-python-internal)
2585 (setq python-shell-internal-buffer proc-buffer-name))
2586 (get-buffer-process proc-buffer-name)))
2587
2588 (define-obsolete-function-alias
2589 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2590
2591 (define-obsolete-variable-alias
2592 'python-buffer 'python-shell-internal-buffer "24.3")
2593
2594 (define-obsolete-variable-alias
2595 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2596
2597 (defun python-shell--save-temp-file (string)
2598 (let* ((temporary-file-directory
2599 (if (file-remote-p default-directory)
2600 (concat (file-remote-p default-directory) "/tmp")
2601 temporary-file-directory))
2602 (temp-file-name (make-temp-file "py"))
2603 (coding-system-for-write 'utf-8))
2604 (with-temp-file temp-file-name
2605 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2606 (insert string)
2607 (delete-trailing-whitespace))
2608 temp-file-name))
2609
2610 (defun python-shell-send-string (string &optional process)
2611 "Send STRING to inferior Python PROCESS."
2612 (interactive "sPython command: ")
2613 (let ((process (or process (python-shell-get-or-create-process))))
2614 (if (string-match ".\n+." string) ;Multiline.
2615 (let* ((temp-file-name (python-shell--save-temp-file string)))
2616 (python-shell-send-file temp-file-name process temp-file-name t))
2617 (comint-send-string process string)
2618 (when (or (not (string-match "\n\\'" string))
2619 (string-match "\n[ \t].*\n?\\'" string))
2620 (comint-send-string process "\n")))))
2621
2622 (defvar python-shell-output-filter-in-progress nil)
2623 (defvar python-shell-output-filter-buffer nil)
2624
2625 (defun python-shell-output-filter (string)
2626 "Filter used in `python-shell-send-string-no-output' to grab output.
2627 STRING is the output received to this point from the process.
2628 This filter saves received output from the process in
2629 `python-shell-output-filter-buffer' and stops receiving it after
2630 detecting a prompt at the end of the buffer."
2631 (setq
2632 string (ansi-color-filter-apply string)
2633 python-shell-output-filter-buffer
2634 (concat python-shell-output-filter-buffer string))
2635 (when (python-shell-comint-end-of-output-p
2636 python-shell-output-filter-buffer)
2637 ;; Output ends when `python-shell-output-filter-buffer' contains
2638 ;; the prompt attached at the end of it.
2639 (setq python-shell-output-filter-in-progress nil
2640 python-shell-output-filter-buffer
2641 (substring python-shell-output-filter-buffer
2642 0 (match-beginning 0)))
2643 (when (string-match
2644 python-shell--prompt-calculated-output-regexp
2645 python-shell-output-filter-buffer)
2646 ;; Some shells, like IPython might append a prompt before the
2647 ;; output, clean that.
2648 (setq python-shell-output-filter-buffer
2649 (substring python-shell-output-filter-buffer (match-end 0)))))
2650 "")
2651
2652 (defun python-shell-send-string-no-output (string &optional process)
2653 "Send STRING to PROCESS and inhibit output.
2654 Return the output."
2655 (let ((process (or process (python-shell-get-or-create-process)))
2656 (comint-preoutput-filter-functions
2657 '(python-shell-output-filter))
2658 (python-shell-output-filter-in-progress t)
2659 (inhibit-quit t))
2660 (or
2661 (with-local-quit
2662 (python-shell-send-string string process)
2663 (while python-shell-output-filter-in-progress
2664 ;; `python-shell-output-filter' takes care of setting
2665 ;; `python-shell-output-filter-in-progress' to NIL after it
2666 ;; detects end of output.
2667 (accept-process-output process))
2668 (prog1
2669 python-shell-output-filter-buffer
2670 (setq python-shell-output-filter-buffer nil)))
2671 (with-current-buffer (process-buffer process)
2672 (comint-interrupt-subjob)))))
2673
2674 (defun python-shell-internal-send-string (string)
2675 "Send STRING to the Internal Python interpreter.
2676 Returns the output. See `python-shell-send-string-no-output'."
2677 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2678 ;; updated to support this new mode.
2679 (setq python-shell-internal-last-output
2680 (python-shell-send-string-no-output
2681 ;; Makes this function compatible with the old
2682 ;; python-send-receive. (At least for CEDET).
2683 (replace-regexp-in-string "_emacs_out +" "" string)
2684 (python-shell-internal-get-or-create-process))))
2685
2686 (define-obsolete-function-alias
2687 'python-send-receive 'python-shell-internal-send-string "24.3")
2688
2689 (define-obsolete-function-alias
2690 'python-send-string 'python-shell-internal-send-string "24.3")
2691
2692 (defvar python--use-fake-loc nil
2693 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2694 If nil, regions of text are prepended by the corresponding number of empty
2695 lines and Python is told to output error messages referring to the whole
2696 source file.")
2697
2698 (defun python-shell-buffer-substring (start end &optional nomain)
2699 "Send buffer substring from START to END formatted for shell.
2700 This is a wrapper over `buffer-substring' that takes care of
2701 different transformations for the code sent to be evaluated in
2702 the python shell:
2703 1. When optional argument NOMAIN is non-nil everything under an
2704 \"if __name__ == '__main__'\" block will be removed.
2705 2. When a subregion of the buffer is sent, it takes care of
2706 appending extra empty lines so tracebacks are correct.
2707 3. Wraps indented regions under an \"if True:\" block so the
2708 interpreter evaluates them correctly."
2709 (let ((substring (buffer-substring-no-properties start end))
2710 (fillstr (unless python--use-fake-loc
2711 (make-string (1- (line-number-at-pos start)) ?\n)))
2712 (toplevel-block-p (save-excursion
2713 (goto-char start)
2714 (or (zerop (line-number-at-pos start))
2715 (progn
2716 (python-util-forward-comment 1)
2717 (zerop (current-indentation)))))))
2718 (with-temp-buffer
2719 (python-mode)
2720 (if fillstr (insert fillstr))
2721 (insert substring)
2722 (goto-char (point-min))
2723 (unless python--use-fake-loc
2724 ;; python-shell--save-temp-file adds an extra coding line, which would
2725 ;; throw off the line-counts, so let's try to compensate here.
2726 (if (looking-at "[ \t]*[#\n]")
2727 (delete-region (point) (line-beginning-position 2))))
2728 (when (not toplevel-block-p)
2729 (insert "if True:")
2730 (delete-region (point) (line-end-position)))
2731 (when nomain
2732 (let* ((if-name-main-start-end
2733 (and nomain
2734 (save-excursion
2735 (when (python-nav-if-name-main)
2736 (cons (point)
2737 (progn (python-nav-forward-sexp-safe)
2738 (point)))))))
2739 ;; Oh destructuring bind, how I miss you.
2740 (if-name-main-start (car if-name-main-start-end))
2741 (if-name-main-end (cdr if-name-main-start-end)))
2742 (when if-name-main-start-end
2743 (goto-char if-name-main-start)
2744 (delete-region if-name-main-start if-name-main-end)
2745 (insert
2746 (make-string
2747 (- (line-number-at-pos if-name-main-end)
2748 (line-number-at-pos if-name-main-start)) ?\n)))))
2749 (buffer-substring-no-properties (point-min) (point-max)))))
2750
2751 (declare-function compilation-fake-loc "compile"
2752 (marker file &optional line col))
2753
2754 (defun python-shell-send-region (start end &optional nomain)
2755 "Send the region delimited by START and END to inferior Python process."
2756 (interactive "r")
2757 (let* ((python--use-fake-loc
2758 (or python--use-fake-loc (not buffer-file-name)))
2759 (string (python-shell-buffer-substring start end nomain))
2760 (process (python-shell-get-or-create-process))
2761 (_ (string-match "\\`\n*\\(.*\\)" string)))
2762 (message "Sent: %s..." (match-string 1 string))
2763 (let* ((temp-file-name (python-shell--save-temp-file string))
2764 (file-name (or (buffer-file-name) temp-file-name)))
2765 (python-shell-send-file file-name process temp-file-name t)
2766 (unless python--use-fake-loc
2767 (with-current-buffer (process-buffer process)
2768 (compilation-fake-loc (copy-marker start) temp-file-name
2769 2)) ;; Not 1, because of the added coding line.
2770 ))))
2771
2772 (defun python-shell-send-buffer (&optional arg)
2773 "Send the entire buffer to inferior Python process.
2774 With prefix ARG allow execution of code inside blocks delimited
2775 by \"if __name__== '__main__':\"."
2776 (interactive "P")
2777 (save-restriction
2778 (widen)
2779 (python-shell-send-region (point-min) (point-max) (not arg))))
2780
2781 (defun python-shell-send-defun (arg)
2782 "Send the current defun to inferior Python process.
2783 When argument ARG is non-nil do not include decorators."
2784 (interactive "P")
2785 (save-excursion
2786 (python-shell-send-region
2787 (progn
2788 (end-of-line 1)
2789 (while (and (or (python-nav-beginning-of-defun)
2790 (beginning-of-line 1))
2791 (> (current-indentation) 0)))
2792 (when (not arg)
2793 (while (and (forward-line -1)
2794 (looking-at (python-rx decorator))))
2795 (forward-line 1))
2796 (point-marker))
2797 (progn
2798 (or (python-nav-end-of-defun)
2799 (end-of-line 1))
2800 (point-marker)))))
2801
2802 (defun python-shell-send-file (file-name &optional process temp-file-name
2803 delete)
2804 "Send FILE-NAME to inferior Python PROCESS.
2805 If TEMP-FILE-NAME is passed then that file is used for processing
2806 instead, while internally the shell will continue to use FILE-NAME.
2807 If DELETE is non-nil, delete the file afterwards."
2808 (interactive "fFile to send: ")
2809 (let* ((process (or process (python-shell-get-or-create-process)))
2810 (temp-file-name (when temp-file-name
2811 (expand-file-name
2812 (or (file-remote-p temp-file-name 'localname)
2813 temp-file-name))))
2814 (file-name (or (when file-name
2815 (expand-file-name
2816 (or (file-remote-p file-name 'localname)
2817 file-name)))
2818 temp-file-name)))
2819 (when (not file-name)
2820 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2821 (python-shell-send-string
2822 (format
2823 (concat "__pyfile = open('''%s''');"
2824 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2825 "__pyfile.close()%s")
2826 (or temp-file-name file-name) file-name
2827 (if delete (format "; import os; os.remove('''%s''')"
2828 (or temp-file-name file-name))
2829 ""))
2830 process)))
2831
2832 (defun python-shell-switch-to-shell ()
2833 "Switch to inferior Python process buffer."
2834 (interactive)
2835 (process-buffer (python-shell-get-or-create-process)) t)
2836
2837 (defun python-shell-send-setup-code ()
2838 "Send all setup code for shell.
2839 This function takes the list of setup code to send from the
2840 `python-shell-setup-codes' list."
2841 (let ((process (python-shell-get-process))
2842 (code (concat
2843 (mapconcat
2844 (lambda (elt)
2845 (cond ((stringp elt) elt)
2846 ((symbolp elt) (symbol-value elt))
2847 (t "")))
2848 python-shell-setup-codes
2849 "\n\n")
2850 "\n\nprint ('python.el: sent setup code')")))
2851 (python-shell-send-string code process)
2852 (python-shell-accept-process-output process)))
2853
2854 (add-hook 'inferior-python-mode-hook
2855 #'python-shell-send-setup-code)
2856
2857 \f
2858 ;;; Shell completion
2859
2860 (defcustom python-shell-completion-setup-code
2861 "try:
2862 import __builtin__
2863 except ImportError:
2864 # Python 3
2865 import builtins as __builtin__
2866 try:
2867 import readline, rlcompleter
2868 except:
2869 def __PYTHON_EL_get_completions(text):
2870 return []
2871 else:
2872 def __PYTHON_EL_get_completions(text):
2873 builtins = dir(__builtin__)
2874 completions = []
2875 try:
2876 splits = text.split()
2877 is_module = splits and splits[0] in ('from', 'import')
2878 is_ipython = ('__IPYTHON__' in builtins or
2879 '__IPYTHON__active' in builtins)
2880 if is_module:
2881 from IPython.core.completerlib import module_completion
2882 completions = module_completion(text.strip())
2883 elif is_ipython and '__IP' in builtins:
2884 completions = __IP.complete(text)
2885 elif is_ipython and 'get_ipython' in builtins:
2886 completions = get_ipython().Completer.all_completions(text)
2887 else:
2888 i = 0
2889 while True:
2890 res = readline.get_completer()(text, i)
2891 if not res:
2892 break
2893 i += 1
2894 completions.append(res)
2895 except:
2896 pass
2897 return completions"
2898 "Code used to setup completion in inferior Python processes."
2899 :type 'string
2900 :group 'python)
2901
2902 (defcustom python-shell-completion-string-code
2903 "';'.join(__PYTHON_EL_get_completions('''%s'''))\n"
2904 "Python code used to get a string of completions separated by semicolons.
2905 The string passed to the function is the current python name or
2906 the full statement in the case of imports."
2907 :type 'string
2908 :group 'python)
2909
2910 (define-obsolete-variable-alias
2911 'python-shell-completion-module-string-code
2912 'python-shell-completion-string-code
2913 "24.4"
2914 "Completion string code must also autocomplete modules.")
2915
2916 (define-obsolete-variable-alias
2917 'python-shell-completion-pdb-string-code
2918 'python-shell-completion-string-code
2919 "25.1"
2920 "Completion string code must work for (i)pdb.")
2921
2922 (defun python-shell-completion-get-completions (process import input)
2923 "Do completion at point using PROCESS for IMPORT or INPUT.
2924 When IMPORT is non-nil takes precedence over INPUT for
2925 completion."
2926 (with-current-buffer (process-buffer process)
2927 (let* ((prompt
2928 (let ((prompt-boundaries (python-util-comint-last-prompt)))
2929 (buffer-substring-no-properties
2930 (car prompt-boundaries) (cdr prompt-boundaries))))
2931 (completion-code
2932 ;; Check whether a prompt matches a pdb string, an import
2933 ;; statement or just the standard prompt and use the
2934 ;; correct python-shell-completion-*-code string
2935 (cond ((and (string-match
2936 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2937 ;; Since there are no guarantees the user will remain
2938 ;; in the same context where completion code was sent
2939 ;; (e.g. user steps into a function), safeguard
2940 ;; resending completion setup continuously.
2941 (concat python-shell-completion-setup-code
2942 "\nprint (" python-shell-completion-string-code ")"))
2943 ((string-match
2944 python-shell--prompt-calculated-input-regexp prompt)
2945 python-shell-completion-string-code)
2946 (t nil)))
2947 (subject (or import input)))
2948 (and completion-code
2949 (> (length input) 0)
2950 (let ((completions
2951 (python-util-strip-string
2952 (python-shell-send-string-no-output
2953 (format completion-code subject) process))))
2954 (and (> (length completions) 2)
2955 (split-string completions
2956 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2957
2958 (defun python-shell-completion-at-point (&optional process)
2959 "Function for `completion-at-point-functions' in `inferior-python-mode'.
2960 Optional argument PROCESS forces completions to be retrieved
2961 using that one instead of current buffer's process."
2962 (setq process (or process (get-buffer-process (current-buffer))))
2963 (let* ((last-prompt-end (cdr (python-util-comint-last-prompt)))
2964 (import-statement
2965 (when (string-match-p
2966 (rx (* space) word-start (or "from" "import") word-end space)
2967 (buffer-substring-no-properties last-prompt-end (point)))
2968 (buffer-substring-no-properties last-prompt-end (point))))
2969 (start
2970 (save-excursion
2971 (if (not (re-search-backward
2972 (python-rx
2973 (or whitespace open-paren close-paren string-delimiter))
2974 last-prompt-end
2975 t 1))
2976 last-prompt-end
2977 (forward-char (length (match-string-no-properties 0)))
2978 (point))))
2979 (end (point)))
2980 (list start end
2981 (completion-table-dynamic
2982 (apply-partially
2983 #'python-shell-completion-get-completions
2984 process import-statement)))))
2985
2986 (define-obsolete-function-alias
2987 'python-shell-completion-complete-at-point
2988 'python-shell-completion-at-point
2989 "25.1")
2990
2991 (defun python-shell-completion-complete-or-indent ()
2992 "Complete or indent depending on the context.
2993 If content before pointer is all whitespace, indent.
2994 If not try to complete."
2995 (interactive)
2996 (if (string-match "^[[:space:]]*$"
2997 (buffer-substring (comint-line-beginning-position)
2998 (point)))
2999 (indent-for-tab-command)
3000 (completion-at-point)))
3001
3002 \f
3003 ;;; PDB Track integration
3004
3005 (defcustom python-pdbtrack-activate t
3006 "Non-nil makes Python shell enable pdbtracking."
3007 :type 'boolean
3008 :group 'python
3009 :safe 'booleanp)
3010
3011 (defcustom python-pdbtrack-stacktrace-info-regexp
3012 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
3013 "Regular expression matching stacktrace information.
3014 Used to extract the current line and module being inspected."
3015 :type 'string
3016 :group 'python
3017 :safe 'stringp)
3018
3019 (defvar python-pdbtrack-tracked-buffer nil
3020 "Variable containing the value of the current tracked buffer.
3021 Never set this variable directly, use
3022 `python-pdbtrack-set-tracked-buffer' instead.")
3023
3024 (defvar python-pdbtrack-buffers-to-kill nil
3025 "List of buffers to be deleted after tracking finishes.")
3026
3027 (defun python-pdbtrack-set-tracked-buffer (file-name)
3028 "Set the buffer for FILE-NAME as the tracked buffer.
3029 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
3030 Returns the tracked buffer."
3031 (let ((file-buffer (get-file-buffer
3032 (concat (file-remote-p default-directory)
3033 file-name))))
3034 (if file-buffer
3035 (setq python-pdbtrack-tracked-buffer file-buffer)
3036 (setq file-buffer (find-file-noselect file-name))
3037 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
3038 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
3039 file-buffer))
3040
3041 (defun python-pdbtrack-comint-output-filter-function (output)
3042 "Move overlay arrow to current pdb line in tracked buffer.
3043 Argument OUTPUT is a string with the output from the comint process."
3044 (when (and python-pdbtrack-activate (not (string= output "")))
3045 (let* ((full-output (ansi-color-filter-apply
3046 (buffer-substring comint-last-input-end (point-max))))
3047 (line-number)
3048 (file-name
3049 (with-temp-buffer
3050 (insert full-output)
3051 ;; When the debugger encounters a pdb.set_trace()
3052 ;; command, it prints a single stack frame. Sometimes
3053 ;; it prints a bit of extra information about the
3054 ;; arguments of the present function. When ipdb
3055 ;; encounters an exception, it prints the _entire_ stack
3056 ;; trace. To handle all of these cases, we want to find
3057 ;; the _last_ stack frame printed in the most recent
3058 ;; batch of output, then jump to the corresponding
3059 ;; file/line number.
3060 (goto-char (point-max))
3061 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
3062 (setq line-number (string-to-number
3063 (match-string-no-properties 2)))
3064 (match-string-no-properties 1)))))
3065 (if (and file-name line-number)
3066 (let* ((tracked-buffer
3067 (python-pdbtrack-set-tracked-buffer file-name))
3068 (shell-buffer (current-buffer))
3069 (tracked-buffer-window (get-buffer-window tracked-buffer))
3070 (tracked-buffer-line-pos))
3071 (with-current-buffer tracked-buffer
3072 (set (make-local-variable 'overlay-arrow-string) "=>")
3073 (set (make-local-variable 'overlay-arrow-position) (make-marker))
3074 (setq tracked-buffer-line-pos (progn
3075 (goto-char (point-min))
3076 (forward-line (1- line-number))
3077 (point-marker)))
3078 (when tracked-buffer-window
3079 (set-window-point
3080 tracked-buffer-window tracked-buffer-line-pos))
3081 (set-marker overlay-arrow-position tracked-buffer-line-pos))
3082 (pop-to-buffer tracked-buffer)
3083 (switch-to-buffer-other-window shell-buffer))
3084 (when python-pdbtrack-tracked-buffer
3085 (with-current-buffer python-pdbtrack-tracked-buffer
3086 (set-marker overlay-arrow-position nil))
3087 (mapc #'(lambda (buffer)
3088 (ignore-errors (kill-buffer buffer)))
3089 python-pdbtrack-buffers-to-kill)
3090 (setq python-pdbtrack-tracked-buffer nil
3091 python-pdbtrack-buffers-to-kill nil)))))
3092 output)
3093
3094 \f
3095 ;;; Symbol completion
3096
3097 (defun python-completion-at-point ()
3098 "Function for `completion-at-point-functions' in `python-mode'.
3099 For this to work as best as possible you should call
3100 `python-shell-send-buffer' from time to time so context in
3101 inferior Python process is updated properly."
3102 (let ((process (python-shell-get-process)))
3103 (when process
3104 (python-shell-completion-at-point process))))
3105
3106 (define-obsolete-function-alias
3107 'python-completion-complete-at-point
3108 'python-completion-at-point
3109 "25.1")
3110
3111 \f
3112 ;;; Fill paragraph
3113
3114 (defcustom python-fill-comment-function 'python-fill-comment
3115 "Function to fill comments.
3116 This is the function used by `python-fill-paragraph' to
3117 fill comments."
3118 :type 'symbol
3119 :group 'python)
3120
3121 (defcustom python-fill-string-function 'python-fill-string
3122 "Function to fill strings.
3123 This is the function used by `python-fill-paragraph' to
3124 fill strings."
3125 :type 'symbol
3126 :group 'python)
3127
3128 (defcustom python-fill-decorator-function 'python-fill-decorator
3129 "Function to fill decorators.
3130 This is the function used by `python-fill-paragraph' to
3131 fill decorators."
3132 :type 'symbol
3133 :group 'python)
3134
3135 (defcustom python-fill-paren-function 'python-fill-paren
3136 "Function to fill parens.
3137 This is the function used by `python-fill-paragraph' to
3138 fill parens."
3139 :type 'symbol
3140 :group 'python)
3141
3142 (defcustom python-fill-docstring-style 'pep-257
3143 "Style used to fill docstrings.
3144 This affects `python-fill-string' behavior with regards to
3145 triple quotes positioning.
3146
3147 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
3148 `symmetric', and nil. A value of nil won't care about quotes
3149 position and will treat docstrings a normal string, any other
3150 value may result in one of the following docstring styles:
3151
3152 `django':
3153
3154 \"\"\"
3155 Process foo, return bar.
3156 \"\"\"
3157
3158 \"\"\"
3159 Process foo, return bar.
3160
3161 If processing fails throw ProcessingError.
3162 \"\"\"
3163
3164 `onetwo':
3165
3166 \"\"\"Process foo, return bar.\"\"\"
3167
3168 \"\"\"
3169 Process foo, return bar.
3170
3171 If processing fails throw ProcessingError.
3172
3173 \"\"\"
3174
3175 `pep-257':
3176
3177 \"\"\"Process foo, return bar.\"\"\"
3178
3179 \"\"\"Process foo, return bar.
3180
3181 If processing fails throw ProcessingError.
3182
3183 \"\"\"
3184
3185 `pep-257-nn':
3186
3187 \"\"\"Process foo, return bar.\"\"\"
3188
3189 \"\"\"Process foo, return bar.
3190
3191 If processing fails throw ProcessingError.
3192 \"\"\"
3193
3194 `symmetric':
3195
3196 \"\"\"Process foo, return bar.\"\"\"
3197
3198 \"\"\"
3199 Process foo, return bar.
3200
3201 If processing fails throw ProcessingError.
3202 \"\"\""
3203 :type '(choice
3204 (const :tag "Don't format docstrings" nil)
3205 (const :tag "Django's coding standards style." django)
3206 (const :tag "One newline and start and Two at end style." onetwo)
3207 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
3208 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
3209 (const :tag "Symmetric style." symmetric))
3210 :group 'python
3211 :safe (lambda (val)
3212 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
3213
3214 (defun python-fill-paragraph (&optional justify)
3215 "`fill-paragraph-function' handling multi-line strings and possibly comments.
3216 If any of the current line is in or at the end of a multi-line string,
3217 fill the string or the paragraph of it that point is in, preserving
3218 the string's indentation.
3219 Optional argument JUSTIFY defines if the paragraph should be justified."
3220 (interactive "P")
3221 (save-excursion
3222 (cond
3223 ;; Comments
3224 ((python-syntax-context 'comment)
3225 (funcall python-fill-comment-function justify))
3226 ;; Strings/Docstrings
3227 ((save-excursion (or (python-syntax-context 'string)
3228 (equal (string-to-syntax "|")
3229 (syntax-after (point)))))
3230 (funcall python-fill-string-function justify))
3231 ;; Decorators
3232 ((equal (char-after (save-excursion
3233 (python-nav-beginning-of-statement))) ?@)
3234 (funcall python-fill-decorator-function justify))
3235 ;; Parens
3236 ((or (python-syntax-context 'paren)
3237 (looking-at (python-rx open-paren))
3238 (save-excursion
3239 (skip-syntax-forward "^(" (line-end-position))
3240 (looking-at (python-rx open-paren))))
3241 (funcall python-fill-paren-function justify))
3242 (t t))))
3243
3244 (defun python-fill-comment (&optional justify)
3245 "Comment fill function for `python-fill-paragraph'.
3246 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3247 (fill-comment-paragraph justify))
3248
3249 (defun python-fill-string (&optional justify)
3250 "String fill function for `python-fill-paragraph'.
3251 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3252 (let* ((str-start-pos
3253 (set-marker
3254 (make-marker)
3255 (or (python-syntax-context 'string)
3256 (and (equal (string-to-syntax "|")
3257 (syntax-after (point)))
3258 (point)))))
3259 (num-quotes (python-syntax-count-quotes
3260 (char-after str-start-pos) str-start-pos))
3261 (str-end-pos
3262 (save-excursion
3263 (goto-char (+ str-start-pos num-quotes))
3264 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
3265 (goto-char (point-max)))
3266 (point-marker)))
3267 (multi-line-p
3268 ;; Docstring styles may vary for oneliners and multi-liners.
3269 (> (count-matches "\n" str-start-pos str-end-pos) 0))
3270 (delimiters-style
3271 (pcase python-fill-docstring-style
3272 ;; delimiters-style is a cons cell with the form
3273 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
3274 ;; is NIL means to not add any newlines for start or end
3275 ;; of docstring. See `python-fill-docstring-style' for a
3276 ;; graphic idea of each style.
3277 (`django (cons 1 1))
3278 (`onetwo (and multi-line-p (cons 1 2)))
3279 (`pep-257 (and multi-line-p (cons nil 2)))
3280 (`pep-257-nn (and multi-line-p (cons nil 1)))
3281 (`symmetric (and multi-line-p (cons 1 1)))))
3282 (docstring-p (save-excursion
3283 ;; Consider docstrings those strings which
3284 ;; start on a line by themselves.
3285 (python-nav-beginning-of-statement)
3286 (and (= (point) str-start-pos))))
3287 (fill-paragraph-function))
3288 (save-restriction
3289 (narrow-to-region str-start-pos str-end-pos)
3290 (fill-paragraph justify))
3291 (save-excursion
3292 (when (and docstring-p python-fill-docstring-style)
3293 ;; Add the number of newlines indicated by the selected style
3294 ;; at the start of the docstring.
3295 (goto-char (+ str-start-pos num-quotes))
3296 (delete-region (point) (progn
3297 (skip-syntax-forward "> ")
3298 (point)))
3299 (and (car delimiters-style)
3300 (or (newline (car delimiters-style)) t)
3301 ;; Indent only if a newline is added.
3302 (indent-according-to-mode))
3303 ;; Add the number of newlines indicated by the selected style
3304 ;; at the end of the docstring.
3305 (goto-char (if (not (= str-end-pos (point-max)))
3306 (- str-end-pos num-quotes)
3307 str-end-pos))
3308 (delete-region (point) (progn
3309 (skip-syntax-backward "> ")
3310 (point)))
3311 (and (cdr delimiters-style)
3312 ;; Add newlines only if string ends.
3313 (not (= str-end-pos (point-max)))
3314 (or (newline (cdr delimiters-style)) t)
3315 ;; Again indent only if a newline is added.
3316 (indent-according-to-mode))))) t)
3317
3318 (defun python-fill-decorator (&optional _justify)
3319 "Decorator fill function for `python-fill-paragraph'.
3320 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3321 t)
3322
3323 (defun python-fill-paren (&optional justify)
3324 "Paren fill function for `python-fill-paragraph'.
3325 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
3326 (save-restriction
3327 (narrow-to-region (progn
3328 (while (python-syntax-context 'paren)
3329 (goto-char (1- (point))))
3330 (line-beginning-position))
3331 (progn
3332 (when (not (python-syntax-context 'paren))
3333 (end-of-line)
3334 (when (not (python-syntax-context 'paren))
3335 (skip-syntax-backward "^)")))
3336 (while (and (python-syntax-context 'paren)
3337 (not (eobp)))
3338 (goto-char (1+ (point))))
3339 (point)))
3340 (let ((paragraph-start "\f\\|[ \t]*$")
3341 (paragraph-separate ",")
3342 (fill-paragraph-function))
3343 (goto-char (point-min))
3344 (fill-paragraph justify))
3345 (while (not (eobp))
3346 (forward-line 1)
3347 (python-indent-line)
3348 (goto-char (line-end-position))))
3349 t)
3350
3351 \f
3352 ;;; Skeletons
3353
3354 (defcustom python-skeleton-autoinsert nil
3355 "Non-nil means template skeletons will be automagically inserted.
3356 This happens when pressing \"if<SPACE>\", for example, to prompt for
3357 the if condition."
3358 :type 'boolean
3359 :group 'python
3360 :safe 'booleanp)
3361
3362 (define-obsolete-variable-alias
3363 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
3364
3365 (defvar python-skeleton-available '()
3366 "Internal list of available skeletons.")
3367
3368 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
3369 "Abbrev table for Python mode skeletons."
3370 :case-fixed t
3371 ;; Allow / inside abbrevs.
3372 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
3373 ;; Only expand in code.
3374 :enable-function (lambda ()
3375 (and
3376 (not (python-syntax-comment-or-string-p))
3377 python-skeleton-autoinsert)))
3378
3379 (defmacro python-skeleton-define (name doc &rest skel)
3380 "Define a `python-mode' skeleton using NAME DOC and SKEL.
3381 The skeleton will be bound to python-skeleton-NAME and will
3382 be added to `python-mode-skeleton-abbrev-table'."
3383 (declare (indent 2))
3384 (let* ((name (symbol-name name))
3385 (function-name (intern (concat "python-skeleton-" name))))
3386 `(progn
3387 (define-abbrev python-mode-skeleton-abbrev-table
3388 ,name "" ',function-name :system t)
3389 (setq python-skeleton-available
3390 (cons ',function-name python-skeleton-available))
3391 (define-skeleton ,function-name
3392 ,(or doc
3393 (format "Insert %s statement." name))
3394 ,@skel))))
3395
3396 (define-abbrev-table 'python-mode-abbrev-table ()
3397 "Abbrev table for Python mode."
3398 :parents (list python-mode-skeleton-abbrev-table))
3399
3400 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
3401 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
3402 The skeleton will be bound to python-skeleton-NAME."
3403 (declare (indent 2))
3404 (let* ((name (symbol-name name))
3405 (function-name (intern (concat "python-skeleton--" name)))
3406 (msg (format
3407 "Add '%s' clause? " name)))
3408 (when (not skel)
3409 (setq skel
3410 `(< ,(format "%s:" name) \n \n
3411 > _ \n)))
3412 `(define-skeleton ,function-name
3413 ,(or doc
3414 (format "Auxiliary skeleton for %s statement." name))
3415 nil
3416 (unless (y-or-n-p ,msg)
3417 (signal 'quit t))
3418 ,@skel)))
3419
3420 (python-define-auxiliary-skeleton else nil)
3421
3422 (python-define-auxiliary-skeleton except nil)
3423
3424 (python-define-auxiliary-skeleton finally nil)
3425
3426 (python-skeleton-define if nil
3427 "Condition: "
3428 "if " str ":" \n
3429 _ \n
3430 ("other condition, %s: "
3431 <
3432 "elif " str ":" \n
3433 > _ \n nil)
3434 '(python-skeleton--else) | ^)
3435
3436 (python-skeleton-define while nil
3437 "Condition: "
3438 "while " str ":" \n
3439 > _ \n
3440 '(python-skeleton--else) | ^)
3441
3442 (python-skeleton-define for nil
3443 "Iteration spec: "
3444 "for " str ":" \n
3445 > _ \n
3446 '(python-skeleton--else) | ^)
3447
3448 (python-skeleton-define import nil
3449 "Import from module: "
3450 "from " str & " " | -5
3451 "import "
3452 ("Identifier: " str ", ") -2 \n _)
3453
3454 (python-skeleton-define try nil
3455 nil
3456 "try:" \n
3457 > _ \n
3458 ("Exception, %s: "
3459 <
3460 "except " str ":" \n
3461 > _ \n nil)
3462 resume:
3463 '(python-skeleton--except)
3464 '(python-skeleton--else)
3465 '(python-skeleton--finally) | ^)
3466
3467 (python-skeleton-define def nil
3468 "Function name: "
3469 "def " str "(" ("Parameter, %s: "
3470 (unless (equal ?\( (char-before)) ", ")
3471 str) "):" \n
3472 "\"\"\"" - "\"\"\"" \n
3473 > _ \n)
3474
3475 (python-skeleton-define class nil
3476 "Class name: "
3477 "class " str "(" ("Inheritance, %s: "
3478 (unless (equal ?\( (char-before)) ", ")
3479 str)
3480 & ")" | -1
3481 ":" \n
3482 "\"\"\"" - "\"\"\"" \n
3483 > _ \n)
3484
3485 (defun python-skeleton-add-menu-items ()
3486 "Add menu items to Python->Skeletons menu."
3487 (let ((skeletons (sort python-skeleton-available 'string<)))
3488 (dolist (skeleton skeletons)
3489 (easy-menu-add-item
3490 nil '("Python" "Skeletons")
3491 `[,(format
3492 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3493 ,skeleton t]))))
3494 \f
3495 ;;; FFAP
3496
3497 (defcustom python-ffap-setup-code
3498 "def __FFAP_get_module_path(module):
3499 try:
3500 import os
3501 path = __import__(module).__file__
3502 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3503 path = path[:-1]
3504 return path
3505 except:
3506 return ''"
3507 "Python code to get a module path."
3508 :type 'string
3509 :group 'python)
3510
3511 (defcustom python-ffap-string-code
3512 "__FFAP_get_module_path('''%s''')\n"
3513 "Python code used to get a string with the path of a module."
3514 :type 'string
3515 :group 'python)
3516
3517 (defun python-ffap-module-path (module)
3518 "Function for `ffap-alist' to return path for MODULE."
3519 (let ((process (or
3520 (and (derived-mode-p 'inferior-python-mode)
3521 (get-buffer-process (current-buffer)))
3522 (python-shell-get-process))))
3523 (if (not process)
3524 nil
3525 (let ((module-file
3526 (python-shell-send-string-no-output
3527 (format python-ffap-string-code module) process)))
3528 (when module-file
3529 (substring-no-properties module-file 1 -1))))))
3530
3531 (defvar ffap-alist)
3532
3533 (eval-after-load "ffap"
3534 '(progn
3535 (push '(python-mode . python-ffap-module-path) ffap-alist)
3536 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3537
3538 \f
3539 ;;; Code check
3540
3541 (defcustom python-check-command
3542 "pyflakes"
3543 "Command used to check a Python file."
3544 :type 'string
3545 :group 'python)
3546
3547 (defcustom python-check-buffer-name
3548 "*Python check: %s*"
3549 "Buffer name used for check commands."
3550 :type 'string
3551 :group 'python)
3552
3553 (defvar python-check-custom-command nil
3554 "Internal use.")
3555
3556 (defun python-check (command)
3557 "Check a Python file (default current buffer's file).
3558 Runs COMMAND, a shell command, as if by `compile'.
3559 See `python-check-command' for the default."
3560 (interactive
3561 (list (read-string "Check command: "
3562 (or python-check-custom-command
3563 (concat python-check-command " "
3564 (shell-quote-argument
3565 (or
3566 (let ((name (buffer-file-name)))
3567 (and name
3568 (file-name-nondirectory name)))
3569 "")))))))
3570 (setq python-check-custom-command command)
3571 (save-some-buffers (not compilation-ask-about-save) nil)
3572 (let ((process-environment (python-shell-calculate-process-environment))
3573 (exec-path (python-shell-calculate-exec-path)))
3574 (compilation-start command nil
3575 (lambda (_modename)
3576 (format python-check-buffer-name command)))))
3577
3578 \f
3579 ;;; Eldoc
3580
3581 (defcustom python-eldoc-setup-code
3582 "def __PYDOC_get_help(obj):
3583 try:
3584 import inspect
3585 try:
3586 str_type = basestring
3587 except NameError:
3588 str_type = str
3589 if isinstance(obj, str_type):
3590 obj = eval(obj, globals())
3591 doc = inspect.getdoc(obj)
3592 if not doc and callable(obj):
3593 target = None
3594 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3595 target = obj.__init__
3596 objtype = 'class'
3597 else:
3598 target = obj
3599 objtype = 'def'
3600 if target:
3601 args = inspect.formatargspec(
3602 *inspect.getargspec(target)
3603 )
3604 name = obj.__name__
3605 doc = '{objtype} {name}{args}'.format(
3606 objtype=objtype, name=name, args=args
3607 )
3608 else:
3609 doc = doc.splitlines()[0]
3610 except:
3611 doc = ''
3612 print (doc)"
3613 "Python code to setup documentation retrieval."
3614 :type 'string
3615 :group 'python)
3616
3617 (defcustom python-eldoc-string-code
3618 "__PYDOC_get_help('''%s''')\n"
3619 "Python code used to get a string with the documentation of an object."
3620 :type 'string
3621 :group 'python)
3622
3623 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3624 "Internal implementation to get documentation at point.
3625 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3626 returns will be used. If not FORCE-PROCESS is passed what
3627 `python-shell-get-process' returns is used."
3628 (let ((process (or force-process (python-shell-get-process))))
3629 (when process
3630 (let ((input (or force-input
3631 (python-info-current-symbol t))))
3632 (and input
3633 ;; Prevent resizing the echo area when iPython is
3634 ;; enabled. Bug#18794.
3635 (python-util-strip-string
3636 (python-shell-send-string-no-output
3637 (format python-eldoc-string-code input)
3638 process)))))))
3639
3640 (defun python-eldoc-function ()
3641 "`eldoc-documentation-function' for Python.
3642 For this to work as best as possible you should call
3643 `python-shell-send-buffer' from time to time so context in
3644 inferior Python process is updated properly."
3645 (python-eldoc--get-doc-at-point))
3646
3647 (defun python-eldoc-at-point (symbol)
3648 "Get help on SYMBOL using `help'.
3649 Interactively, prompt for symbol."
3650 (interactive
3651 (let ((symbol (python-info-current-symbol t))
3652 (enable-recursive-minibuffers t))
3653 (list (read-string (if symbol
3654 (format "Describe symbol (default %s): " symbol)
3655 "Describe symbol: ")
3656 nil nil symbol))))
3657 (message (python-eldoc--get-doc-at-point symbol)))
3658
3659 \f
3660 ;;; Imenu
3661
3662 (defvar python-imenu-format-item-label-function
3663 'python-imenu-format-item-label
3664 "Imenu function used to format an item label.
3665 It must be a function with two arguments: TYPE and NAME.")
3666
3667 (defvar python-imenu-format-parent-item-label-function
3668 'python-imenu-format-parent-item-label
3669 "Imenu function used to format a parent item label.
3670 It must be a function with two arguments: TYPE and NAME.")
3671
3672 (defvar python-imenu-format-parent-item-jump-label-function
3673 'python-imenu-format-parent-item-jump-label
3674 "Imenu function used to format a parent jump item label.
3675 It must be a function with two arguments: TYPE and NAME.")
3676
3677 (defun python-imenu-format-item-label (type name)
3678 "Return Imenu label for single node using TYPE and NAME."
3679 (format "%s (%s)" name type))
3680
3681 (defun python-imenu-format-parent-item-label (type name)
3682 "Return Imenu label for parent node using TYPE and NAME."
3683 (format "%s..." (python-imenu-format-item-label type name)))
3684
3685 (defun python-imenu-format-parent-item-jump-label (type _name)
3686 "Return Imenu label for parent node jump using TYPE and NAME."
3687 (if (string= type "class")
3688 "*class definition*"
3689 "*function definition*"))
3690
3691 (defun python-imenu--put-parent (type name pos tree)
3692 "Add the parent with TYPE, NAME and POS to TREE."
3693 (let ((label
3694 (funcall python-imenu-format-item-label-function type name))
3695 (jump-label
3696 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3697 (if (not tree)
3698 (cons label pos)
3699 (cons label (cons (cons jump-label pos) tree)))))
3700
3701 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3702 "Recursively build the tree of nested definitions of a node.
3703 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3704 not be passed explicitly unless you know what you are doing."
3705 (setq min-indent (or min-indent 0)
3706 prev-indent (or prev-indent python-indent-offset))
3707 (let* ((pos (python-nav-backward-defun))
3708 (type)
3709 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3710 (let ((split (split-string (match-string-no-properties 0))))
3711 (setq type (car split))
3712 (cadr split))))
3713 (label (when name
3714 (funcall python-imenu-format-item-label-function type name)))
3715 (indent (current-indentation))
3716 (children-indent-limit (+ python-indent-offset min-indent)))
3717 (cond ((not pos)
3718 ;; Nothing found, probably near to bobp.
3719 nil)
3720 ((<= indent min-indent)
3721 ;; The current indentation points that this is a parent
3722 ;; node, add it to the tree and stop recursing.
3723 (python-imenu--put-parent type name pos tree))
3724 (t
3725 (python-imenu--build-tree
3726 min-indent
3727 indent
3728 (if (<= indent children-indent-limit)
3729 ;; This lies within the children indent offset range,
3730 ;; so it's a normal child of its parent (i.e., not
3731 ;; a child of a child).
3732 (cons (cons label pos) tree)
3733 ;; Oh no, a child of a child?! Fear not, we
3734 ;; know how to roll. We recursively parse these by
3735 ;; swapping prev-indent and min-indent plus adding this
3736 ;; newly found item to a fresh subtree. This works, I
3737 ;; promise.
3738 (cons
3739 (python-imenu--build-tree
3740 prev-indent indent (list (cons label pos)))
3741 tree)))))))
3742
3743 (defun python-imenu-create-index ()
3744 "Return tree Imenu alist for the current Python buffer.
3745 Change `python-imenu-format-item-label-function',
3746 `python-imenu-format-parent-item-label-function',
3747 `python-imenu-format-parent-item-jump-label-function' to
3748 customize how labels are formatted."
3749 (goto-char (point-max))
3750 (let ((index)
3751 (tree))
3752 (while (setq tree (python-imenu--build-tree))
3753 (setq index (cons tree index)))
3754 index))
3755
3756 (defun python-imenu-create-flat-index (&optional alist prefix)
3757 "Return flat outline of the current Python buffer for Imenu.
3758 Optional argument ALIST is the tree to be flattened; when nil
3759 `python-imenu-build-index' is used with
3760 `python-imenu-format-parent-item-jump-label-function'
3761 `python-imenu-format-parent-item-label-function'
3762 `python-imenu-format-item-label-function' set to
3763 (lambda (type name) name)
3764 Optional argument PREFIX is used in recursive calls and should
3765 not be passed explicitly.
3766
3767 Converts this:
3768
3769 ((\"Foo\" . 103)
3770 (\"Bar\" . 138)
3771 (\"decorator\"
3772 (\"decorator\" . 173)
3773 (\"wrap\"
3774 (\"wrap\" . 353)
3775 (\"wrapped_f\" . 393))))
3776
3777 To this:
3778
3779 ((\"Foo\" . 103)
3780 (\"Bar\" . 138)
3781 (\"decorator\" . 173)
3782 (\"decorator.wrap\" . 353)
3783 (\"decorator.wrapped_f\" . 393))"
3784 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3785 (apply
3786 'nconc
3787 (mapcar
3788 (lambda (item)
3789 (let ((name (if prefix
3790 (concat prefix "." (car item))
3791 (car item)))
3792 (pos (cdr item)))
3793 (cond ((or (numberp pos) (markerp pos))
3794 (list (cons name pos)))
3795 ((listp pos)
3796 (cons
3797 (cons name (cdar pos))
3798 (python-imenu-create-flat-index (cddr item) name))))))
3799 (or alist
3800 (let* ((fn (lambda (_type name) name))
3801 (python-imenu-format-item-label-function fn)
3802 (python-imenu-format-parent-item-label-function fn)
3803 (python-imenu-format-parent-item-jump-label-function fn))
3804 (python-imenu-create-index))))))
3805
3806 \f
3807 ;;; Misc helpers
3808
3809 (defun python-info-current-defun (&optional include-type)
3810 "Return name of surrounding function with Python compatible dotty syntax.
3811 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3812 This function can be used as the value of `add-log-current-defun-function'
3813 since it returns nil if point is not inside a defun."
3814 (save-restriction
3815 (widen)
3816 (save-excursion
3817 (end-of-line 1)
3818 (let ((names)
3819 (starting-indentation (current-indentation))
3820 (starting-pos (point))
3821 (first-run t)
3822 (last-indent)
3823 (type))
3824 (catch 'exit
3825 (while (python-nav-beginning-of-defun 1)
3826 (when (save-match-data
3827 (and
3828 (or (not last-indent)
3829 (< (current-indentation) last-indent))
3830 (or
3831 (and first-run
3832 (save-excursion
3833 ;; If this is the first run, we may add
3834 ;; the current defun at point.
3835 (setq first-run nil)
3836 (goto-char starting-pos)
3837 (python-nav-beginning-of-statement)
3838 (beginning-of-line 1)
3839 (looking-at-p
3840 python-nav-beginning-of-defun-regexp)))
3841 (< starting-pos
3842 (save-excursion
3843 (let ((min-indent
3844 (+ (current-indentation)
3845 python-indent-offset)))
3846 (if (< starting-indentation min-indent)
3847 ;; If the starting indentation is not
3848 ;; within the min defun indent make the
3849 ;; check fail.
3850 starting-pos
3851 ;; Else go to the end of defun and add
3852 ;; up the current indentation to the
3853 ;; ending position.
3854 (python-nav-end-of-defun)
3855 (+ (point)
3856 (if (>= (current-indentation) min-indent)
3857 (1+ (current-indentation))
3858 0)))))))))
3859 (save-match-data (setq last-indent (current-indentation)))
3860 (if (or (not include-type) type)
3861 (setq names (cons (match-string-no-properties 1) names))
3862 (let ((match (split-string (match-string-no-properties 0))))
3863 (setq type (car match))
3864 (setq names (cons (cadr match) names)))))
3865 ;; Stop searching ASAP.
3866 (and (= (current-indentation) 0) (throw 'exit t))))
3867 (and names
3868 (concat (and type (format "%s " type))
3869 (mapconcat 'identity names ".")))))))
3870
3871 (defun python-info-current-symbol (&optional replace-self)
3872 "Return current symbol using dotty syntax.
3873 With optional argument REPLACE-SELF convert \"self\" to current
3874 parent defun name."
3875 (let ((name
3876 (and (not (python-syntax-comment-or-string-p))
3877 (with-syntax-table python-dotty-syntax-table
3878 (let ((sym (symbol-at-point)))
3879 (and sym
3880 (substring-no-properties (symbol-name sym))))))))
3881 (when name
3882 (if (not replace-self)
3883 name
3884 (let ((current-defun (python-info-current-defun)))
3885 (if (not current-defun)
3886 name
3887 (replace-regexp-in-string
3888 (python-rx line-start word-start "self" word-end ?.)
3889 (concat
3890 (mapconcat 'identity
3891 (butlast (split-string current-defun "\\."))
3892 ".") ".")
3893 name)))))))
3894
3895 (defun python-info-statement-starts-block-p ()
3896 "Return non-nil if current statement opens a block."
3897 (save-excursion
3898 (python-nav-beginning-of-statement)
3899 (looking-at (python-rx block-start))))
3900
3901 (defun python-info-statement-ends-block-p ()
3902 "Return non-nil if point is at end of block."
3903 (let ((end-of-block-pos (save-excursion
3904 (python-nav-end-of-block)))
3905 (end-of-statement-pos (save-excursion
3906 (python-nav-end-of-statement))))
3907 (and end-of-block-pos end-of-statement-pos
3908 (= end-of-block-pos end-of-statement-pos))))
3909
3910 (defun python-info-beginning-of-statement-p ()
3911 "Return non-nil if point is at beginning of statement."
3912 (= (point) (save-excursion
3913 (python-nav-beginning-of-statement)
3914 (point))))
3915
3916 (defun python-info-end-of-statement-p ()
3917 "Return non-nil if point is at end of statement."
3918 (= (point) (save-excursion
3919 (python-nav-end-of-statement)
3920 (point))))
3921
3922 (defun python-info-beginning-of-block-p ()
3923 "Return non-nil if point is at beginning of block."
3924 (and (python-info-beginning-of-statement-p)
3925 (python-info-statement-starts-block-p)))
3926
3927 (defun python-info-end-of-block-p ()
3928 "Return non-nil if point is at end of block."
3929 (and (python-info-end-of-statement-p)
3930 (python-info-statement-ends-block-p)))
3931
3932 (define-obsolete-function-alias
3933 'python-info-closing-block
3934 'python-info-dedenter-opening-block-position "24.4")
3935
3936 (defun python-info-dedenter-opening-block-position ()
3937 "Return the point of the closest block the current line closes.
3938 Returns nil if point is not on a dedenter statement or no opening
3939 block can be detected. The latter case meaning current file is
3940 likely an invalid python file."
3941 (let ((positions (python-info-dedenter-opening-block-positions))
3942 (indentation (current-indentation))
3943 (position))
3944 (while (and (not position)
3945 positions)
3946 (save-excursion
3947 (goto-char (car positions))
3948 (if (<= (current-indentation) indentation)
3949 (setq position (car positions))
3950 (setq positions (cdr positions)))))
3951 position))
3952
3953 (defun python-info-dedenter-opening-block-positions ()
3954 "Return points of blocks the current line may close sorted by closer.
3955 Returns nil if point is not on a dedenter statement or no opening
3956 block can be detected. The latter case meaning current file is
3957 likely an invalid python file."
3958 (save-excursion
3959 (let ((dedenter-pos (python-info-dedenter-statement-p)))
3960 (when dedenter-pos
3961 (goto-char dedenter-pos)
3962 (let* ((pairs '(("elif" "elif" "if")
3963 ("else" "if" "elif" "except" "for" "while")
3964 ("except" "except" "try")
3965 ("finally" "else" "except" "try")))
3966 (dedenter (match-string-no-properties 0))
3967 (possible-opening-blocks (cdr (assoc-string dedenter pairs)))
3968 (collected-indentations)
3969 (opening-blocks))
3970 (catch 'exit
3971 (while (python-nav--syntactically
3972 (lambda ()
3973 (re-search-backward (python-rx block-start) nil t))
3974 #'<)
3975 (let ((indentation (current-indentation)))
3976 (when (and (not (memq indentation collected-indentations))
3977 (or (not collected-indentations)
3978 (< indentation (apply #'min collected-indentations))))
3979 (setq collected-indentations
3980 (cons indentation collected-indentations))
3981 (when (member (match-string-no-properties 0)
3982 possible-opening-blocks)
3983 (setq opening-blocks (cons (point) opening-blocks))))
3984 (when (zerop indentation)
3985 (throw 'exit nil)))))
3986 ;; sort by closer
3987 (nreverse opening-blocks))))))
3988
3989 (define-obsolete-function-alias
3990 'python-info-closing-block-message
3991 'python-info-dedenter-opening-block-message "24.4")
3992
3993 (defun python-info-dedenter-opening-block-message ()
3994 "Message the first line of the block the current statement closes."
3995 (let ((point (python-info-dedenter-opening-block-position)))
3996 (when point
3997 (save-restriction
3998 (widen)
3999 (message "Closes %s" (save-excursion
4000 (goto-char point)
4001 (buffer-substring
4002 (point) (line-end-position))))))))
4003
4004 (defun python-info-dedenter-statement-p ()
4005 "Return point if current statement is a dedenter.
4006 Sets `match-data' to the keyword that starts the dedenter
4007 statement."
4008 (save-excursion
4009 (python-nav-beginning-of-statement)
4010 (when (and (not (python-syntax-context-type))
4011 (looking-at (python-rx dedenter)))
4012 (point))))
4013
4014 (defun python-info-line-ends-backslash-p (&optional line-number)
4015 "Return non-nil if current line ends with backslash.
4016 With optional argument LINE-NUMBER, check that line instead."
4017 (save-excursion
4018 (save-restriction
4019 (widen)
4020 (when line-number
4021 (python-util-goto-line line-number))
4022 (while (and (not (eobp))
4023 (goto-char (line-end-position))
4024 (python-syntax-context 'paren)
4025 (not (equal (char-before (point)) ?\\)))
4026 (forward-line 1))
4027 (when (equal (char-before) ?\\)
4028 (point-marker)))))
4029
4030 (defun python-info-beginning-of-backslash (&optional line-number)
4031 "Return the point where the backslashed line start.
4032 Optional argument LINE-NUMBER forces the line number to check against."
4033 (save-excursion
4034 (save-restriction
4035 (widen)
4036 (when line-number
4037 (python-util-goto-line line-number))
4038 (when (python-info-line-ends-backslash-p)
4039 (while (save-excursion
4040 (goto-char (line-beginning-position))
4041 (python-syntax-context 'paren))
4042 (forward-line -1))
4043 (back-to-indentation)
4044 (point-marker)))))
4045
4046 (defun python-info-continuation-line-p ()
4047 "Check if current line is continuation of another.
4048 When current line is continuation of another return the point
4049 where the continued line ends."
4050 (save-excursion
4051 (save-restriction
4052 (widen)
4053 (let* ((context-type (progn
4054 (back-to-indentation)
4055 (python-syntax-context-type)))
4056 (line-start (line-number-at-pos))
4057 (context-start (when context-type
4058 (python-syntax-context context-type))))
4059 (cond ((equal context-type 'paren)
4060 ;; Lines inside a paren are always a continuation line
4061 ;; (except the first one).
4062 (python-util-forward-comment -1)
4063 (point-marker))
4064 ((member context-type '(string comment))
4065 ;; move forward an roll again
4066 (goto-char context-start)
4067 (python-util-forward-comment)
4068 (python-info-continuation-line-p))
4069 (t
4070 ;; Not within a paren, string or comment, the only way
4071 ;; we are dealing with a continuation line is that
4072 ;; previous line contains a backslash, and this can
4073 ;; only be the previous line from current
4074 (back-to-indentation)
4075 (python-util-forward-comment -1)
4076 (when (and (equal (1- line-start) (line-number-at-pos))
4077 (python-info-line-ends-backslash-p))
4078 (point-marker))))))))
4079
4080 (defun python-info-block-continuation-line-p ()
4081 "Return non-nil if current line is a continuation of a block."
4082 (save-excursion
4083 (when (python-info-continuation-line-p)
4084 (forward-line -1)
4085 (back-to-indentation)
4086 (when (looking-at (python-rx block-start))
4087 (point-marker)))))
4088
4089 (defun python-info-assignment-continuation-line-p ()
4090 "Check if current line is a continuation of an assignment.
4091 When current line is continuation of another with an assignment
4092 return the point of the first non-blank character after the
4093 operator."
4094 (save-excursion
4095 (when (python-info-continuation-line-p)
4096 (forward-line -1)
4097 (back-to-indentation)
4098 (when (and (not (looking-at (python-rx block-start)))
4099 (and (re-search-forward (python-rx not-simple-operator
4100 assignment-operator
4101 not-simple-operator)
4102 (line-end-position) t)
4103 (not (python-syntax-context-type))))
4104 (skip-syntax-forward "\s")
4105 (point-marker)))))
4106
4107 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4108 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
4109 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
4110 (save-excursion
4111 (beginning-of-line 1)
4112 (looking-at python-nav-beginning-of-defun-regexp))))
4113
4114 (defun python-info-current-line-comment-p ()
4115 "Return non-nil if current line is a comment line."
4116 (char-equal
4117 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
4118 ?#))
4119
4120 (defun python-info-current-line-empty-p ()
4121 "Return non-nil if current line is empty, ignoring whitespace."
4122 (save-excursion
4123 (beginning-of-line 1)
4124 (looking-at
4125 (python-rx line-start (* whitespace)
4126 (group (* not-newline))
4127 (* whitespace) line-end))
4128 (string-equal "" (match-string-no-properties 1))))
4129
4130 \f
4131 ;;; Utility functions
4132
4133 (defun python-util-goto-line (line-number)
4134 "Move point to LINE-NUMBER."
4135 (goto-char (point-min))
4136 (forward-line (1- line-number)))
4137
4138 ;; Stolen from org-mode
4139 (defun python-util-clone-local-variables (from-buffer &optional regexp)
4140 "Clone local variables from FROM-BUFFER.
4141 Optional argument REGEXP selects variables to clone and defaults
4142 to \"^python-\"."
4143 (mapc
4144 (lambda (pair)
4145 (and (symbolp (car pair))
4146 (string-match (or regexp "^python-")
4147 (symbol-name (car pair)))
4148 (set (make-local-variable (car pair))
4149 (cdr pair))))
4150 (buffer-local-variables from-buffer)))
4151
4152 (defvar comint-last-prompt-overlay) ; Shut up, byte compiler.
4153
4154 (defun python-util-comint-last-prompt ()
4155 "Return comint last prompt overlay start and end.
4156 This is for compatibility with Emacs < 24.4."
4157 (cond ((bound-and-true-p comint-last-prompt-overlay)
4158 (cons (overlay-start comint-last-prompt-overlay)
4159 (overlay-end comint-last-prompt-overlay)))
4160 ((bound-and-true-p comint-last-prompt)
4161 comint-last-prompt)
4162 (t nil)))
4163
4164 (defun python-util-forward-comment (&optional direction)
4165 "Python mode specific version of `forward-comment'.
4166 Optional argument DIRECTION defines the direction to move to."
4167 (let ((comment-start (python-syntax-context 'comment))
4168 (factor (if (< (or direction 0) 0)
4169 -99999
4170 99999)))
4171 (when comment-start
4172 (goto-char comment-start))
4173 (forward-comment factor)))
4174
4175 (defun python-util-list-directories (directory &optional predicate max-depth)
4176 "List DIRECTORY subdirs, filtered by PREDICATE and limited by MAX-DEPTH.
4177 Argument PREDICATE defaults to `identity' and must be a function
4178 that takes one argument (a full path) and returns non-nil for
4179 allowed files. When optional argument MAX-DEPTH is non-nil, stop
4180 searching when depth is reached, else don't limit."
4181 (let* ((dir (expand-file-name directory))
4182 (dir-length (length dir))
4183 (predicate (or predicate #'identity))
4184 (to-scan (list dir))
4185 (tally nil))
4186 (while to-scan
4187 (let ((current-dir (car to-scan)))
4188 (when (funcall predicate current-dir)
4189 (setq tally (cons current-dir tally)))
4190 (setq to-scan (append (cdr to-scan)
4191 (python-util-list-files
4192 current-dir #'file-directory-p)
4193 nil))
4194 (when (and max-depth
4195 (<= max-depth
4196 (length (split-string
4197 (substring current-dir dir-length)
4198 "/\\|\\\\" t))))
4199 (setq to-scan nil))))
4200 (nreverse tally)))
4201
4202 (defun python-util-list-files (dir &optional predicate)
4203 "List files in DIR, filtering with PREDICATE.
4204 Argument PREDICATE defaults to `identity' and must be a function
4205 that takes one argument (a full path) and returns non-nil for
4206 allowed files."
4207 (let ((dir-name (file-name-as-directory dir)))
4208 (apply #'nconc
4209 (mapcar (lambda (file-name)
4210 (let ((full-file-name (expand-file-name file-name dir-name)))
4211 (when (and
4212 (not (member file-name '("." "..")))
4213 (funcall (or predicate #'identity) full-file-name))
4214 (list full-file-name))))
4215 (directory-files dir-name)))))
4216
4217 (defun python-util-list-packages (dir &optional max-depth)
4218 "List packages in DIR, limited by MAX-DEPTH.
4219 When optional argument MAX-DEPTH is non-nil, stop searching when
4220 depth is reached, else don't limit."
4221 (let* ((dir (expand-file-name dir))
4222 (parent-dir (file-name-directory
4223 (directory-file-name
4224 (file-name-directory
4225 (file-name-as-directory dir)))))
4226 (subpath-length (length parent-dir)))
4227 (mapcar
4228 (lambda (file-name)
4229 (replace-regexp-in-string
4230 (rx (or ?\\ ?/)) "." (substring file-name subpath-length)))
4231 (python-util-list-directories
4232 (directory-file-name dir)
4233 (lambda (dir)
4234 (file-exists-p (expand-file-name "__init__.py" dir)))
4235 max-depth))))
4236
4237 (defun python-util-popn (lst n)
4238 "Return LST first N elements.
4239 N should be an integer, when negative its opposite is used.
4240 When N is bigger than the length of LST, the list is
4241 returned as is."
4242 (let* ((n (min (abs n)))
4243 (len (length lst))
4244 (acc))
4245 (if (> n len)
4246 lst
4247 (while (< 0 n)
4248 (setq acc (cons (car lst) acc)
4249 lst (cdr lst)
4250 n (1- n)))
4251 (reverse acc))))
4252
4253 (defun python-util-text-properties-replace-name
4254 (from to &optional start end)
4255 "Replace properties named FROM to TO, keeping its value.
4256 Arguments START and END narrow the buffer region to work on."
4257 (save-excursion
4258 (goto-char (or start (point-min)))
4259 (while (not (eobp))
4260 (let ((plist (text-properties-at (point)))
4261 (next-change (or (next-property-change (point) (current-buffer))
4262 (or end (point-max)))))
4263 (when (plist-get plist from)
4264 (let* ((face (plist-get plist from))
4265 (plist (plist-put plist from nil))
4266 (plist (plist-put plist to face)))
4267 (set-text-properties (point) next-change plist (current-buffer))))
4268 (goto-char next-change)))))
4269
4270 (defun python-util-strip-string (string)
4271 "Strip STRING whitespace and newlines from end and beginning."
4272 (replace-regexp-in-string
4273 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
4274 (: (* (any whitespace ?\r ?\n)) string-end)))
4275 ""
4276 string))
4277
4278 (defun python-util-valid-regexp-p (regexp)
4279 "Return non-nil if REGEXP is valid."
4280 (ignore-errors (string-match regexp "") t))
4281
4282 \f
4283 (defun python-electric-pair-string-delimiter ()
4284 (when (and electric-pair-mode
4285 (memq last-command-event '(?\" ?\'))
4286 (let ((count 0))
4287 (while (eq (char-before (- (point) count)) last-command-event)
4288 (cl-incf count))
4289 (= count 3))
4290 (eq (char-after) last-command-event))
4291 (save-excursion (insert (make-string 2 last-command-event)))))
4292
4293 (defvar electric-indent-inhibit)
4294
4295 ;;;###autoload
4296 (define-derived-mode python-mode prog-mode "Python"
4297 "Major mode for editing Python files.
4298
4299 \\{python-mode-map}"
4300 (set (make-local-variable 'tab-width) 8)
4301 (set (make-local-variable 'indent-tabs-mode) nil)
4302
4303 (set (make-local-variable 'comment-start) "# ")
4304 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
4305
4306 (set (make-local-variable 'parse-sexp-lookup-properties) t)
4307 (set (make-local-variable 'parse-sexp-ignore-comments) t)
4308
4309 (set (make-local-variable 'forward-sexp-function)
4310 'python-nav-forward-sexp)
4311
4312 (set (make-local-variable 'font-lock-defaults)
4313 '(python-font-lock-keywords nil nil nil nil))
4314
4315 (set (make-local-variable 'syntax-propertize-function)
4316 python-syntax-propertize-function)
4317
4318 (set (make-local-variable 'indent-line-function)
4319 #'python-indent-line-function)
4320 (set (make-local-variable 'indent-region-function) #'python-indent-region)
4321 ;; Because indentation is not redundant, we cannot safely reindent code.
4322 (set (make-local-variable 'electric-indent-inhibit) t)
4323 (set (make-local-variable 'electric-indent-chars)
4324 (cons ?: electric-indent-chars))
4325
4326 ;; Add """ ... """ pairing to electric-pair-mode.
4327 (add-hook 'post-self-insert-hook
4328 #'python-electric-pair-string-delimiter 'append t)
4329
4330 (set (make-local-variable 'paragraph-start) "\\s-*$")
4331 (set (make-local-variable 'fill-paragraph-function)
4332 #'python-fill-paragraph)
4333
4334 (set (make-local-variable 'beginning-of-defun-function)
4335 #'python-nav-beginning-of-defun)
4336 (set (make-local-variable 'end-of-defun-function)
4337 #'python-nav-end-of-defun)
4338
4339 (add-hook 'completion-at-point-functions
4340 #'python-completion-at-point nil 'local)
4341
4342 (add-hook 'post-self-insert-hook
4343 #'python-indent-post-self-insert-function 'append 'local)
4344
4345 (set (make-local-variable 'imenu-create-index-function)
4346 #'python-imenu-create-index)
4347
4348 (set (make-local-variable 'add-log-current-defun-function)
4349 #'python-info-current-defun)
4350
4351 (add-hook 'which-func-functions #'python-info-current-defun nil t)
4352
4353 (set (make-local-variable 'skeleton-further-elements)
4354 '((abbrev-mode nil)
4355 (< '(backward-delete-char-untabify (min python-indent-offset
4356 (current-column))))
4357 (^ '(- (1+ (current-indentation))))))
4358
4359 (set (make-local-variable 'eldoc-documentation-function)
4360 #'python-eldoc-function)
4361
4362 (add-to-list 'hs-special-modes-alist
4363 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
4364 ,(lambda (_arg)
4365 (python-nav-end-of-defun))
4366 nil))
4367
4368 (set (make-local-variable 'outline-regexp)
4369 (python-rx (* space) block-start))
4370 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
4371 (set (make-local-variable 'outline-level)
4372 #'(lambda ()
4373 "`outline-level' function for Python mode."
4374 (1+ (/ (current-indentation) python-indent-offset))))
4375
4376 (python-skeleton-add-menu-items)
4377
4378 (make-local-variable 'python-shell-internal-buffer)
4379
4380 (when python-indent-guess-indent-offset
4381 (python-indent-guess-indent-offset)))
4382
4383
4384 (provide 'python)
4385
4386 ;; Local Variables:
4387 ;; coding: utf-8
4388 ;; indent-tabs-mode: nil
4389 ;; End:
4390
4391 ;;; python.el ends here