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