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