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