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