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