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