* lisp/progmodes/python.el (python-imenu--build-tree): Fix corner case
[emacs.git] / lisp / progmodes / python.el
blob62870f9085b40eb25d80dfabcdceaf94b4e40a57
1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2013 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: FSF
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 when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be 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' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp' allows easy navigation
58 ;; between code blocks. If you prefer `cc-mode'-like `forward-sexp'
59 ;; movement, setting `forward-sexp-function' to nil is enough, You can
60 ;; 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") '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 (define-key map ":" 'python-indent-electric-colon)
252 ;; Skeletons
253 (define-key map "\C-c\C-tc" 'python-skeleton-class)
254 (define-key map "\C-c\C-td" 'python-skeleton-def)
255 (define-key map "\C-c\C-tf" 'python-skeleton-for)
256 (define-key map "\C-c\C-ti" 'python-skeleton-if)
257 (define-key map "\C-c\C-tt" 'python-skeleton-try)
258 (define-key map "\C-c\C-tw" 'python-skeleton-while)
259 ;; Shell interaction
260 (define-key map "\C-c\C-p" 'run-python)
261 (define-key map "\C-c\C-s" 'python-shell-send-string)
262 (define-key map "\C-c\C-r" 'python-shell-send-region)
263 (define-key map "\C-\M-x" 'python-shell-send-defun)
264 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
265 (define-key map "\C-c\C-l" 'python-shell-send-file)
266 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
267 ;; Some util commands
268 (define-key map "\C-c\C-v" 'python-check)
269 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
270 ;; Utilities
271 (substitute-key-definition 'complete-symbol 'completion-at-point
272 map global-map)
273 (easy-menu-define python-menu map "Python Mode menu"
274 `("Python"
275 :help "Python-specific Features"
276 ["Shift region left" python-indent-shift-left :active mark-active
277 :help "Shift region left by a single indentation step"]
278 ["Shift region right" python-indent-shift-right :active mark-active
279 :help "Shift region right by a single indentation step"]
281 ["Start of def/class" beginning-of-defun
282 :help "Go to start of outermost definition around point"]
283 ["End of def/class" end-of-defun
284 :help "Go to end of definition around point"]
285 ["Mark def/class" mark-defun
286 :help "Mark outermost definition around point"]
287 ["Jump to def/class" imenu
288 :help "Jump to a class or function definition"]
289 "--"
290 ("Skeletons")
291 "---"
292 ["Start interpreter" run-python
293 :help "Run inferior Python process in a separate buffer"]
294 ["Switch to shell" python-shell-switch-to-shell
295 :help "Switch to running inferior Python process"]
296 ["Eval string" python-shell-send-string
297 :help "Eval string in inferior Python session"]
298 ["Eval buffer" python-shell-send-buffer
299 :help "Eval buffer in inferior Python session"]
300 ["Eval region" python-shell-send-region
301 :help "Eval region in inferior Python session"]
302 ["Eval defun" python-shell-send-defun
303 :help "Eval defun in inferior Python session"]
304 ["Eval file" python-shell-send-file
305 :help "Eval file in inferior Python session"]
306 ["Debugger" pdb :help "Run pdb under GUD"]
307 "----"
308 ["Check file" python-check
309 :help "Check file for errors"]
310 ["Help on symbol" python-eldoc-at-point
311 :help "Get help on symbol at point"]
312 ["Complete symbol" completion-at-point
313 :help "Complete symbol before point"]))
314 map)
315 "Keymap for `python-mode'.")
318 ;;; Python specialized rx
320 (eval-when-compile
321 (defconst python-rx-constituents
322 `((block-start . ,(rx symbol-start
323 (or "def" "class" "if" "elif" "else" "try"
324 "except" "finally" "for" "while" "with")
325 symbol-end))
326 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
327 (* (any word ?_))))
328 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
329 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
330 (+ space) "==" (+ space)
331 (any ?' ?\") "__main__" (any ?' ?\")
332 (* space) ?:))
333 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
334 (open-paren . ,(rx (or "{" "[" "(")))
335 (close-paren . ,(rx (or "}" "]" ")")))
336 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
337 ;; FIXME: rx should support (not simple-operator).
338 (not-simple-operator . ,(rx
339 (not
340 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
341 ;; FIXME: Use regexp-opt.
342 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
343 "=" "%" "**" "//" "<<" ">>" "<=" "!="
344 "==" ">=" "is" "not")))
345 ;; FIXME: Use regexp-opt.
346 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
347 ">>=" "<<=" "&=" "^=" "|=")))
348 (string-delimiter . ,(rx (and
349 ;; Match even number of backslashes.
350 (or (not (any ?\\ ?\' ?\")) point
351 ;; Quotes might be preceded by a escaped quote.
352 (and (or (not (any ?\\)) point) ?\\
353 (* ?\\ ?\\) (any ?\' ?\")))
354 (* ?\\ ?\\)
355 ;; Match single or triple quotes of any kind.
356 (group (or "\"" "\"\"\"" "'" "'''"))))))
357 "Additional Python specific sexps for `python-rx'")
359 (defmacro python-rx (&rest regexps)
360 "Python mode specialized rx macro.
361 This variant of `rx' supports common python named REGEXPS."
362 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
363 (cond ((null regexps)
364 (error "No regexp"))
365 ((cdr regexps)
366 (rx-to-string `(and ,@regexps) t))
368 (rx-to-string (car regexps) t))))))
371 ;;; Font-lock and syntax
373 (eval-when-compile
374 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
375 (pcase type
376 (`'comment
377 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
378 (and (nth 4 ppss) (nth 8 ppss))))
379 (`'string
380 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
381 (and (nth 3 ppss) (nth 8 ppss))))
382 (`'paren
383 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
384 (_ form))))
386 (defun python-syntax-context (type &optional syntax-ppss)
387 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
388 TYPE can be `comment', `string' or `paren'. It returns the start
389 character address of the specified TYPE."
390 (declare (compiler-macro python-syntax--context-compiler-macro))
391 (let ((ppss (or syntax-ppss (syntax-ppss))))
392 (pcase type
393 (`comment (and (nth 4 ppss) (nth 8 ppss)))
394 (`string (and (nth 3 ppss) (nth 8 ppss)))
395 (`paren (nth 1 ppss))
396 (_ nil))))
398 (defun python-syntax-context-type (&optional syntax-ppss)
399 "Return the context type using SYNTAX-PPSS.
400 The type returned can be `comment', `string' or `paren'."
401 (let ((ppss (or syntax-ppss (syntax-ppss))))
402 (cond
403 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
404 ((nth 1 ppss) 'paren))))
406 (defsubst python-syntax-comment-or-string-p ()
407 "Return non-nil if point is inside 'comment or 'string."
408 (nth 8 (syntax-ppss)))
410 (define-obsolete-function-alias
411 'python-info-ppss-context #'python-syntax-context "24.3")
413 (define-obsolete-function-alias
414 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
416 (define-obsolete-function-alias
417 'python-info-ppss-comment-or-string-p
418 #'python-syntax-comment-or-string-p "24.3")
420 (defvar python-font-lock-keywords
421 ;; Keywords
422 `(,(rx symbol-start
424 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
425 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
426 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
427 "try"
428 ;; Python 2:
429 "print" "exec"
430 ;; Python 3:
431 ;; False, None, and True are listed as keywords on the Python 3
432 ;; documentation, but since they also qualify as constants they are
433 ;; fontified like that in order to keep font-lock consistent between
434 ;; Python versions.
435 "nonlocal"
436 ;; Extra:
437 "self")
438 symbol-end)
439 ;; functions
440 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
441 (1 font-lock-function-name-face))
442 ;; classes
443 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
444 (1 font-lock-type-face))
445 ;; Constants
446 (,(rx symbol-start
448 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
449 ;; copyright, license, credits, quit and exit are added by the site
450 ;; module and they are not intended to be used in programs
451 "copyright" "credits" "exit" "license" "quit")
452 symbol-end) . font-lock-constant-face)
453 ;; Decorators.
454 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
455 (0+ "." (1+ (or word ?_)))))
456 (1 font-lock-type-face))
457 ;; Builtin Exceptions
458 (,(rx symbol-start
460 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
461 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
462 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
463 "ImportError" "ImportWarning" "IndexError" "KeyError"
464 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
465 "NotImplementedError" "OSError" "OverflowError"
466 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
467 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
468 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
469 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
470 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
471 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
472 ;; Python 2:
473 "StandardError"
474 ;; Python 3:
475 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
476 "TabError")
477 symbol-end) . font-lock-type-face)
478 ;; Builtins
479 (,(rx symbol-start
481 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
482 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
483 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
484 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
485 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
486 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
487 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
488 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
489 "__import__"
490 ;; Python 2:
491 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
492 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
493 "intern"
494 ;; Python 3:
495 "ascii" "bytearray" "bytes" "exec"
496 ;; Extra:
497 "__all__" "__doc__" "__name__" "__package__")
498 symbol-end) . font-lock-builtin-face)
499 ;; assignments
500 ;; support for a = b = c = 5
501 (,(lambda (limit)
502 (let ((re (python-rx (group (+ (any word ?. ?_)))
503 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
504 assignment-operator)))
505 (when (re-search-forward re limit t)
506 (while (and (python-syntax-context 'paren)
507 (re-search-forward re limit t)))
508 (if (not (or (python-syntax-context 'paren)
509 (equal (char-after (point-marker)) ?=)))
511 (set-match-data nil)))))
512 (1 font-lock-variable-name-face nil nil))
513 ;; support for a, b, c = (1, 2, 3)
514 (,(lambda (limit)
515 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
516 (* ?, (* space) (+ (any word ?. ?_)) (* space))
517 ?, (* space) (+ (any word ?. ?_)) (* space)
518 assignment-operator)))
519 (when (and (re-search-forward re limit t)
520 (goto-char (nth 3 (match-data))))
521 (while (and (python-syntax-context 'paren)
522 (re-search-forward re limit t))
523 (goto-char (nth 3 (match-data))))
524 (if (not (python-syntax-context 'paren))
526 (set-match-data nil)))))
527 (1 font-lock-variable-name-face nil nil))))
529 (defconst python-syntax-propertize-function
530 (syntax-propertize-rules
531 ((python-rx string-delimiter)
532 (0 (ignore (python-syntax-stringify))))))
534 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
535 "Count number of quotes around point (max is 3).
536 QUOTE-CHAR is the quote char to count. Optional argument POINT is
537 the point where scan starts (defaults to current point) and LIMIT
538 is used to limit the scan."
539 (let ((i 0))
540 (while (and (< i 3)
541 (or (not limit) (< (+ point i) limit))
542 (eq (char-after (+ point i)) quote-char))
543 (setq i (1+ i)))
546 (defun python-syntax-stringify ()
547 "Put `syntax-table' property correctly on single/triple quotes."
548 (let* ((num-quotes (length (match-string-no-properties 1)))
549 (ppss (prog2
550 (backward-char num-quotes)
551 (syntax-ppss)
552 (forward-char num-quotes)))
553 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
554 (quote-starting-pos (- (point) num-quotes))
555 (quote-ending-pos (point))
556 (num-closing-quotes
557 (and string-start
558 (python-syntax-count-quotes
559 (char-before) string-start quote-starting-pos))))
560 (cond ((and string-start (= num-closing-quotes 0))
561 ;; This set of quotes doesn't match the string starting
562 ;; kind. Do nothing.
563 nil)
564 ((not string-start)
565 ;; This set of quotes delimit the start of a string.
566 (put-text-property quote-starting-pos (1+ quote-starting-pos)
567 'syntax-table (string-to-syntax "|")))
568 ((= num-quotes num-closing-quotes)
569 ;; This set of quotes delimit the end of a string.
570 (put-text-property (1- quote-ending-pos) quote-ending-pos
571 'syntax-table (string-to-syntax "|")))
572 ((> num-quotes num-closing-quotes)
573 ;; This may only happen whenever a triple quote is closing
574 ;; a single quoted string. Add string delimiter syntax to
575 ;; all three quotes.
576 (put-text-property quote-starting-pos quote-ending-pos
577 'syntax-table (string-to-syntax "|"))))))
579 (defvar python-mode-syntax-table
580 (let ((table (make-syntax-table)))
581 ;; Give punctuation syntax to ASCII that normally has symbol
582 ;; syntax or has word syntax and isn't a letter.
583 (let ((symbol (string-to-syntax "_"))
584 (sst (standard-syntax-table)))
585 (dotimes (i 128)
586 (unless (= i ?_)
587 (if (equal symbol (aref sst i))
588 (modify-syntax-entry i "." table)))))
589 (modify-syntax-entry ?$ "." table)
590 (modify-syntax-entry ?% "." table)
591 ;; exceptions
592 (modify-syntax-entry ?# "<" table)
593 (modify-syntax-entry ?\n ">" table)
594 (modify-syntax-entry ?' "\"" table)
595 (modify-syntax-entry ?` "$" table)
596 table)
597 "Syntax table for Python files.")
599 (defvar python-dotty-syntax-table
600 (let ((table (make-syntax-table python-mode-syntax-table)))
601 (modify-syntax-entry ?. "w" table)
602 (modify-syntax-entry ?_ "w" table)
603 table)
604 "Dotty syntax table for Python files.
605 It makes underscores and dots word constituent chars.")
608 ;;; Indentation
610 (defcustom python-indent-offset 4
611 "Default indentation offset for Python."
612 :group 'python
613 :type 'integer
614 :safe 'integerp)
616 (defcustom python-indent-guess-indent-offset t
617 "Non-nil tells Python mode to guess `python-indent-offset' value."
618 :type 'boolean
619 :group 'python
620 :safe 'booleanp)
622 (defcustom python-indent-trigger-commands
623 '(indent-for-tab-command yas-expand yas/expand)
624 "Commands that might trigger a `python-indent-line' call."
625 :type '(repeat symbol)
626 :group 'python)
628 (define-obsolete-variable-alias
629 'python-indent 'python-indent-offset "24.3")
631 (define-obsolete-variable-alias
632 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
634 (defvar python-indent-current-level 0
635 "Current indentation level `python-indent-line-function' is using.")
637 (defvar python-indent-levels '(0)
638 "Levels of indentation available for `python-indent-line-function'.")
640 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
641 "List of words that should be dedented.
642 These make `python-indent-calculate-indentation' subtract the value of
643 `python-indent-offset'.")
645 (defvar python-indent-block-enders
646 '("break" "continue" "pass" "raise" "return")
647 "List of words that mark the end of a block.
648 These make `python-indent-calculate-indentation' subtract the
649 value of `python-indent-offset' when `python-indent-context' is
650 AFTER-LINE.")
652 (defun python-indent-guess-indent-offset ()
653 "Guess and set `python-indent-offset' for the current buffer."
654 (interactive)
655 (save-excursion
656 (save-restriction
657 (widen)
658 (goto-char (point-min))
659 (let ((block-end))
660 (while (and (not block-end)
661 (re-search-forward
662 (python-rx line-start block-start) nil t))
663 (when (and
664 (not (python-syntax-context-type))
665 (progn
666 (goto-char (line-end-position))
667 (python-util-forward-comment -1)
668 (if (equal (char-before) ?:)
670 (forward-line 1)
671 (when (python-info-block-continuation-line-p)
672 (while (and (python-info-continuation-line-p)
673 (not (eobp)))
674 (forward-line 1))
675 (python-util-forward-comment -1)
676 (when (equal (char-before) ?:)
677 t)))))
678 (setq block-end (point-marker))))
679 (let ((indentation
680 (when block-end
681 (goto-char block-end)
682 (python-util-forward-comment)
683 (current-indentation))))
684 (if indentation
685 (set (make-local-variable 'python-indent-offset) indentation)
686 (message "Can't guess python-indent-offset, using defaults: %s"
687 python-indent-offset)))))))
689 (defun python-indent-context ()
690 "Get information on indentation context.
691 Context information is returned with a cons with the form:
692 \(STATUS . START)
694 Where status can be any of the following symbols:
695 * inside-paren: If point in between (), {} or []
696 * inside-string: If point is inside a string
697 * after-backslash: Previous line ends in a backslash
698 * after-beginning-of-block: Point is after beginning of block
699 * after-line: Point is after normal line
700 * no-indent: Point is at beginning of buffer or other special case
701 START is the buffer position where the sexp starts."
702 (save-restriction
703 (widen)
704 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
705 (start))
706 (cons
707 (cond
708 ;; Beginning of buffer
709 ((save-excursion
710 (goto-char (line-beginning-position))
711 (bobp))
712 'no-indent)
713 ;; Inside string
714 ((setq start (python-syntax-context 'string ppss))
715 'inside-string)
716 ;; Inside a paren
717 ((setq start (python-syntax-context 'paren ppss))
718 'inside-paren)
719 ;; After backslash
720 ((setq start (when (not (or (python-syntax-context 'string ppss)
721 (python-syntax-context 'comment ppss)))
722 (let ((line-beg-pos (line-number-at-pos)))
723 (python-info-line-ends-backslash-p
724 (1- line-beg-pos)))))
725 'after-backslash)
726 ;; After beginning of block
727 ((setq start (save-excursion
728 (when (progn
729 (back-to-indentation)
730 (python-util-forward-comment -1)
731 (equal (char-before) ?:))
732 ;; Move to the first block start that's not in within
733 ;; a string, comment or paren and that's not a
734 ;; continuation line.
735 (while (and (re-search-backward
736 (python-rx block-start) nil t)
738 (python-syntax-context-type)
739 (python-info-continuation-line-p))))
740 (when (looking-at (python-rx block-start))
741 (point-marker)))))
742 'after-beginning-of-block)
743 ;; After normal line
744 ((setq start (save-excursion
745 (back-to-indentation)
746 (skip-chars-backward (rx (or whitespace ?\n)))
747 (python-nav-beginning-of-statement)
748 (point-marker)))
749 'after-line)
750 ;; Do not indent
751 (t 'no-indent))
752 start))))
754 (defun python-indent-calculate-indentation ()
755 "Calculate correct indentation offset for the current line."
756 (let* ((indentation-context (python-indent-context))
757 (context-status (car indentation-context))
758 (context-start (cdr indentation-context)))
759 (save-restriction
760 (widen)
761 (save-excursion
762 (pcase context-status
763 (`no-indent 0)
764 ;; When point is after beginning of block just add one level
765 ;; of indentation relative to the context-start
766 (`after-beginning-of-block
767 (goto-char context-start)
768 (+ (current-indentation) python-indent-offset))
769 ;; When after a simple line just use previous line
770 ;; indentation, in the case current line starts with a
771 ;; `python-indent-dedenters' de-indent one level.
772 (`after-line
774 (save-excursion
775 (goto-char context-start)
776 (current-indentation))
777 (if (or (save-excursion
778 (back-to-indentation)
779 (looking-at (regexp-opt python-indent-dedenters)))
780 (save-excursion
781 (python-util-forward-comment -1)
782 (python-nav-beginning-of-statement)
783 (member (current-word) python-indent-block-enders)))
784 python-indent-offset
785 0)))
786 ;; When inside of a string, do nothing. just use the current
787 ;; indentation. XXX: perhaps it would be a good idea to
788 ;; invoke standard text indentation here
789 (`inside-string
790 (goto-char context-start)
791 (current-indentation))
792 ;; After backslash we have several possibilities.
793 (`after-backslash
794 (cond
795 ;; Check if current line is a dot continuation. For this
796 ;; the current line must start with a dot and previous
797 ;; line must contain a dot too.
798 ((save-excursion
799 (back-to-indentation)
800 (when (looking-at "\\.")
801 ;; If after moving one line back point is inside a paren it
802 ;; needs to move back until it's not anymore
803 (while (prog2
804 (forward-line -1)
805 (and (not (bobp))
806 (python-syntax-context 'paren))))
807 (goto-char (line-end-position))
808 (while (and (re-search-backward
809 "\\." (line-beginning-position) t)
810 (python-syntax-context-type)))
811 (if (and (looking-at "\\.")
812 (not (python-syntax-context-type)))
813 ;; The indentation is the same column of the
814 ;; first matching dot that's not inside a
815 ;; comment, a string or a paren
816 (current-column)
817 ;; No dot found on previous line, just add another
818 ;; indentation level.
819 (+ (current-indentation) python-indent-offset)))))
820 ;; Check if prev line is a block continuation
821 ((let ((block-continuation-start
822 (python-info-block-continuation-line-p)))
823 (when block-continuation-start
824 ;; If block-continuation-start is set jump to that
825 ;; marker and use first column after the block start
826 ;; as indentation value.
827 (goto-char block-continuation-start)
828 (re-search-forward
829 (python-rx block-start (* space))
830 (line-end-position) t)
831 (current-column))))
832 ;; Check if current line is an assignment continuation
833 ((let ((assignment-continuation-start
834 (python-info-assignment-continuation-line-p)))
835 (when assignment-continuation-start
836 ;; If assignment-continuation is set jump to that
837 ;; marker and use first column after the assignment
838 ;; operator as indentation value.
839 (goto-char assignment-continuation-start)
840 (current-column))))
842 (forward-line -1)
843 (goto-char (python-info-beginning-of-backslash))
844 (if (save-excursion
845 (and
846 (forward-line -1)
847 (goto-char
848 (or (python-info-beginning-of-backslash) (point)))
849 (python-info-line-ends-backslash-p)))
850 ;; The two previous lines ended in a backslash so we must
851 ;; respect previous line indentation.
852 (current-indentation)
853 ;; What happens here is that we are dealing with the second
854 ;; line of a backslash continuation, in that case we just going
855 ;; to add one indentation level.
856 (+ (current-indentation) python-indent-offset)))))
857 ;; When inside a paren there's a need to handle nesting
858 ;; correctly
859 (`inside-paren
860 (cond
861 ;; If current line closes the outermost open paren use the
862 ;; current indentation of the context-start line.
863 ((save-excursion
864 (skip-syntax-forward "\s" (line-end-position))
865 (when (and (looking-at (regexp-opt '(")" "]" "}")))
866 (progn
867 (forward-char 1)
868 (not (python-syntax-context 'paren))))
869 (goto-char context-start)
870 (current-indentation))))
871 ;; If open paren is contained on a line by itself add another
872 ;; indentation level, else look for the first word after the
873 ;; opening paren and use it's column position as indentation
874 ;; level.
875 ((let* ((content-starts-in-newline)
876 (indent
877 (save-excursion
878 (if (setq content-starts-in-newline
879 (progn
880 (goto-char context-start)
881 (forward-char)
882 (save-restriction
883 (narrow-to-region
884 (line-beginning-position)
885 (line-end-position))
886 (python-util-forward-comment))
887 (looking-at "$")))
888 (+ (current-indentation) python-indent-offset)
889 (current-column)))))
890 ;; Adjustments
891 (cond
892 ;; If current line closes a nested open paren de-indent one
893 ;; level.
894 ((progn
895 (back-to-indentation)
896 (looking-at (regexp-opt '(")" "]" "}"))))
897 (- indent python-indent-offset))
898 ;; If the line of the opening paren that wraps the current
899 ;; line starts a block add another level of indentation to
900 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
901 ((save-excursion
902 (when (and content-starts-in-newline
903 (progn
904 (goto-char context-start)
905 (back-to-indentation)
906 (looking-at (python-rx block-start))))
907 (+ indent python-indent-offset))))
908 (t indent)))))))))))
910 (defun python-indent-calculate-levels ()
911 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
912 (let* ((indentation (python-indent-calculate-indentation))
913 (remainder (% indentation python-indent-offset))
914 (steps (/ (- indentation remainder) python-indent-offset)))
915 (setq python-indent-levels (list 0))
916 (dotimes (step steps)
917 (push (* python-indent-offset (1+ step)) python-indent-levels))
918 (when (not (eq 0 remainder))
919 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
920 (setq python-indent-levels (nreverse python-indent-levels))
921 (setq python-indent-current-level (1- (length python-indent-levels)))))
923 (defun python-indent-toggle-levels ()
924 "Toggle `python-indent-current-level' over `python-indent-levels'."
925 (setq python-indent-current-level (1- python-indent-current-level))
926 (when (< python-indent-current-level 0)
927 (setq python-indent-current-level (1- (length python-indent-levels)))))
929 (defun python-indent-line (&optional force-toggle)
930 "Internal implementation of `python-indent-line-function'.
931 Uses the offset calculated in
932 `python-indent-calculate-indentation' and available levels
933 indicated by the variable `python-indent-levels' to set the
934 current indentation.
936 When the variable `last-command' is equal to one of the symbols
937 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
938 non-nil it cycles levels indicated in the variable
939 `python-indent-levels' by setting the current level in the
940 variable `python-indent-current-level'.
942 When the variable `last-command' is not equal to one of the
943 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
944 is nil it calculates possible indentation levels and saves it in
945 the variable `python-indent-levels'. Afterwards it sets the
946 variable `python-indent-current-level' correctly so offset is
947 equal to (`nth' `python-indent-current-level'
948 `python-indent-levels')"
950 (and (or (and (memq this-command python-indent-trigger-commands)
951 (eq last-command this-command))
952 force-toggle)
953 (not (equal python-indent-levels '(0)))
954 (or (python-indent-toggle-levels) t))
955 (python-indent-calculate-levels))
956 (let* ((starting-pos (point-marker))
957 (indent-ending-position
958 (+ (line-beginning-position) (current-indentation)))
959 (follow-indentation-p
960 (or (bolp)
961 (and (<= (line-beginning-position) starting-pos)
962 (>= indent-ending-position starting-pos))))
963 (next-indent (nth python-indent-current-level python-indent-levels)))
964 (unless (= next-indent (current-indentation))
965 (beginning-of-line)
966 (delete-horizontal-space)
967 (indent-to next-indent)
968 (goto-char starting-pos))
969 (and follow-indentation-p (back-to-indentation)))
970 (python-info-closing-block-message))
972 (defun python-indent-line-function ()
973 "`indent-line-function' for Python mode.
974 See `python-indent-line' for details."
975 (python-indent-line))
977 (defun python-indent-dedent-line ()
978 "De-indent current line."
979 (interactive "*")
980 (when (and (not (python-syntax-comment-or-string-p))
981 (<= (point-marker) (save-excursion
982 (back-to-indentation)
983 (point-marker)))
984 (> (current-column) 0))
985 (python-indent-line t)
988 (defun python-indent-dedent-line-backspace (arg)
989 "De-indent current line.
990 Argument ARG is passed to `backward-delete-char-untabify' when
991 point is not in between the indentation."
992 (interactive "*p")
993 (when (not (python-indent-dedent-line))
994 (backward-delete-char-untabify arg)))
995 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
997 (defun python-indent-region (start end)
998 "Indent a python region automagically.
1000 Called from a program, START and END specify the region to indent."
1001 (let ((deactivate-mark nil))
1002 (save-excursion
1003 (goto-char end)
1004 (setq end (point-marker))
1005 (goto-char start)
1006 (or (bolp) (forward-line 1))
1007 (while (< (point) end)
1008 (or (and (bolp) (eolp))
1009 (let (word)
1010 (forward-line -1)
1011 (back-to-indentation)
1012 (setq word (current-word))
1013 (forward-line 1)
1014 (when (and word
1015 ;; Don't mess with strings, unless it's the
1016 ;; enclosing set of quotes.
1017 (or (not (python-syntax-context 'string))
1019 (syntax-after
1020 (+ (1- (point))
1021 (current-indentation)
1022 (python-syntax-count-quotes (char-after) (point))))
1023 (string-to-syntax "|"))))
1024 (beginning-of-line)
1025 (delete-horizontal-space)
1026 (indent-to (python-indent-calculate-indentation)))))
1027 (forward-line 1))
1028 (move-marker end nil))))
1030 (defun python-indent-shift-left (start end &optional count)
1031 "Shift lines contained in region START END by COUNT columns to the left.
1032 COUNT defaults to `python-indent-offset'. If region isn't
1033 active, the current line is shifted. The shifted region includes
1034 the lines in which START and END lie. An error is signaled if
1035 any lines in the region are indented less than COUNT columns."
1036 (interactive
1037 (if mark-active
1038 (list (region-beginning) (region-end) current-prefix-arg)
1039 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1040 (if count
1041 (setq count (prefix-numeric-value count))
1042 (setq count python-indent-offset))
1043 (when (> count 0)
1044 (let ((deactivate-mark nil))
1045 (save-excursion
1046 (goto-char start)
1047 (while (< (point) end)
1048 (if (and (< (current-indentation) count)
1049 (not (looking-at "[ \t]*$")))
1050 (error "Can't shift all lines enough"))
1051 (forward-line))
1052 (indent-rigidly start end (- count))))))
1054 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1056 (defun python-indent-shift-right (start end &optional count)
1057 "Shift lines contained in region START END by COUNT columns to the left.
1058 COUNT defaults to `python-indent-offset'. If region isn't
1059 active, the current line is shifted. The shifted region includes
1060 the lines in which START and END lie."
1061 (interactive
1062 (if mark-active
1063 (list (region-beginning) (region-end) current-prefix-arg)
1064 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1065 (let ((deactivate-mark nil))
1066 (if count
1067 (setq count (prefix-numeric-value count))
1068 (setq count python-indent-offset))
1069 (indent-rigidly start end count)))
1071 (defun python-indent-electric-colon (arg)
1072 "Insert a colon and maybe de-indent the current line.
1073 With numeric ARG, just insert that many colons. With
1074 \\[universal-argument], just insert a single colon."
1075 (interactive "*P")
1076 (self-insert-command (if (not (integerp arg)) 1 arg))
1077 (when (and (not arg)
1078 (eolp)
1079 (not (equal ?: (char-after (- (point-marker) 2))))
1080 (not (python-syntax-comment-or-string-p)))
1081 (let ((indentation (current-indentation))
1082 (calculated-indentation (python-indent-calculate-indentation)))
1083 (python-info-closing-block-message)
1084 (when (> indentation calculated-indentation)
1085 (save-excursion
1086 (indent-line-to calculated-indentation)
1087 (when (not (python-info-closing-block-message))
1088 (indent-line-to indentation)))))))
1089 (put 'python-indent-electric-colon 'delete-selection t)
1091 (defun python-indent-post-self-insert-function ()
1092 "Adjust closing paren line indentation after a char is added.
1093 This function is intended to be added to the
1094 `post-self-insert-hook.' If a line renders a paren alone, after
1095 adding a char before it, the line will be re-indented
1096 automatically if needed."
1097 (when (and (eq (char-before) last-command-event)
1098 (not (bolp))
1099 (memq (char-after) '(?\) ?\] ?\})))
1100 (save-excursion
1101 (goto-char (line-beginning-position))
1102 ;; If after going to the beginning of line the point
1103 ;; is still inside a paren it's ok to do the trick
1104 (when (python-syntax-context 'paren)
1105 (let ((indentation (python-indent-calculate-indentation)))
1106 (when (< (current-indentation) indentation)
1107 (indent-line-to indentation)))))))
1110 ;;; Navigation
1112 (defvar python-nav-beginning-of-defun-regexp
1113 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1114 "Regexp matching class or function definition.
1115 The name of the defun should be grouped so it can be retrieved
1116 via `match-string'.")
1118 (defun python-nav--beginning-of-defun (&optional arg)
1119 "Internal implementation of `python-nav-beginning-of-defun'.
1120 With positive ARG search backwards, else search forwards."
1121 (when (or (null arg) (= arg 0)) (setq arg 1))
1122 (let* ((re-search-fn (if (> arg 0)
1123 #'re-search-backward
1124 #'re-search-forward))
1125 (line-beg-pos (line-beginning-position))
1126 (line-content-start (+ line-beg-pos (current-indentation)))
1127 (pos (point-marker))
1128 (beg-indentation
1129 (and (> arg 0)
1130 (save-excursion
1131 (while (and
1132 (not (python-info-looking-at-beginning-of-defun))
1133 (python-nav-backward-block)))
1134 (or (and (python-info-looking-at-beginning-of-defun)
1135 (+ (current-indentation) python-indent-offset))
1136 0))))
1137 (found
1138 (progn
1139 (when (and (< arg 0)
1140 (python-info-looking-at-beginning-of-defun))
1141 (end-of-line 1))
1142 (while (and (funcall re-search-fn
1143 python-nav-beginning-of-defun-regexp nil t)
1144 (or (python-syntax-context-type)
1145 ;; Handle nested defuns when moving
1146 ;; backwards by checking indentation.
1147 (and (> arg 0)
1148 (not (= (current-indentation) 0))
1149 (>= (current-indentation) beg-indentation)))))
1150 (and (python-info-looking-at-beginning-of-defun)
1151 (or (not (= (line-number-at-pos pos)
1152 (line-number-at-pos)))
1153 (and (>= (point) line-beg-pos)
1154 (<= (point) line-content-start)
1155 (> pos line-content-start)))))))
1156 (if found
1157 (or (beginning-of-line 1) t)
1158 (and (goto-char pos) nil))))
1160 (defun python-nav-beginning-of-defun (&optional arg)
1161 "Move point to `beginning-of-defun'.
1162 With positive ARG search backwards else search forward. When ARG
1163 is nil or 0 defaults to 1. When searching backwards nested
1164 defuns are handled with care depending on current point
1165 position. Return non-nil if point is moved to
1166 `beginning-of-defun'."
1167 (when (or (null arg) (= arg 0)) (setq arg 1))
1168 (let ((found))
1169 (cond ((and (eq this-command 'mark-defun)
1170 (python-info-looking-at-beginning-of-defun)))
1172 (dotimes (i (if (> arg 0) arg (- arg)))
1173 (when (and (python-nav--beginning-of-defun arg)
1174 (not found))
1175 (setq found t)))))
1176 found))
1178 (defun python-nav-end-of-defun ()
1179 "Move point to the end of def or class.
1180 Returns nil if point is not in a def or class."
1181 (interactive)
1182 (let ((beg-defun-indent)
1183 (beg-pos (point)))
1184 (when (or (python-info-looking-at-beginning-of-defun)
1185 (python-nav-beginning-of-defun 1)
1186 (python-nav-beginning-of-defun -1))
1187 (setq beg-defun-indent (current-indentation))
1188 (while (progn
1189 (python-nav-end-of-statement)
1190 (python-util-forward-comment 1)
1191 (and (> (current-indentation) beg-defun-indent)
1192 (not (eobp)))))
1193 (python-util-forward-comment -1)
1194 (forward-line 1)
1195 ;; Ensure point moves forward.
1196 (and (> beg-pos (point)) (goto-char beg-pos)))))
1198 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1199 "Move point using FN avoiding places with specific context.
1200 FN must take no arguments. POSCOMPFN is a two arguments function
1201 used to compare current and previous point after it is moved
1202 using FN, this is normally a less-than or greater-than
1203 comparison. Optional argument CONTEXTFN defaults to
1204 `python-syntax-context-type' and is used for checking current
1205 point context, it must return a non-nil value if this point must
1206 be skipped."
1207 (let ((contextfn (or contextfn 'python-syntax-context-type))
1208 (start-pos (point-marker))
1209 (prev-pos))
1210 (catch 'found
1211 (while t
1212 (let* ((newpos
1213 (and (funcall fn) (point-marker)))
1214 (context (funcall contextfn)))
1215 (cond ((and (not context) newpos
1216 (or (and (not prev-pos) newpos)
1217 (and prev-pos newpos
1218 (funcall poscompfn newpos prev-pos))))
1219 (throw 'found (point-marker)))
1220 ((and newpos context)
1221 (setq prev-pos (point)))
1222 (t (when (not newpos) (goto-char start-pos))
1223 (throw 'found nil))))))))
1225 (defun python-nav--forward-defun (arg)
1226 "Internal implementation of python-nav-{backward,forward}-defun.
1227 Uses ARG to define which function to call, and how many times
1228 repeat it."
1229 (let ((found))
1230 (while (and (> arg 0)
1231 (setq found
1232 (python-nav--syntactically
1233 (lambda ()
1234 (re-search-forward
1235 python-nav-beginning-of-defun-regexp nil t))
1236 '>)))
1237 (setq arg (1- arg)))
1238 (while (and (< arg 0)
1239 (setq found
1240 (python-nav--syntactically
1241 (lambda ()
1242 (re-search-backward
1243 python-nav-beginning-of-defun-regexp nil t))
1244 '<)))
1245 (setq arg (1+ arg)))
1246 found))
1248 (defun python-nav-backward-defun (&optional arg)
1249 "Navigate to closer defun backward ARG times.
1250 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1251 nested definitions."
1252 (interactive "^p")
1253 (python-nav--forward-defun (- (or arg 1))))
1255 (defun python-nav-forward-defun (&optional arg)
1256 "Navigate to closer defun forward ARG times.
1257 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1258 nested definitions."
1259 (interactive "^p")
1260 (python-nav--forward-defun (or arg 1)))
1262 (defun python-nav-beginning-of-statement ()
1263 "Move to start of current statement."
1264 (interactive "^")
1265 (while (and (or (back-to-indentation) t)
1266 (not (bobp))
1267 (when (or
1268 (save-excursion
1269 (forward-line -1)
1270 (python-info-line-ends-backslash-p))
1271 (python-syntax-context 'string)
1272 (python-syntax-context 'paren))
1273 (forward-line -1))))
1274 (point-marker))
1276 (defun python-nav-end-of-statement (&optional noend)
1277 "Move to end of current statement.
1278 Optional argument NOEND is internal and makes the logic to not
1279 jump to the end of line when moving forward searching for the end
1280 of the statement."
1281 (interactive "^")
1282 (let (string-start bs-pos)
1283 (while (and (or noend (goto-char (line-end-position)))
1284 (not (eobp))
1285 (cond ((setq string-start (python-syntax-context 'string))
1286 (goto-char string-start)
1287 (if (python-syntax-context 'paren)
1288 ;; Ended up inside a paren, roll again.
1289 (python-nav-end-of-statement t)
1290 ;; This is not inside a paren, move to the
1291 ;; end of this string.
1292 (goto-char (+ (point)
1293 (python-syntax-count-quotes
1294 (char-after (point)) (point))))
1295 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1296 (goto-char (point-max)))))
1297 ((python-syntax-context 'paren)
1298 ;; The statement won't end before we've escaped
1299 ;; at least one level of parenthesis.
1300 (condition-case err
1301 (goto-char (scan-lists (point) 1 -1))
1302 (scan-error (goto-char (nth 3 err)))))
1303 ((setq bs-pos (python-info-line-ends-backslash-p))
1304 (goto-char bs-pos)
1305 (forward-line 1))))))
1306 (point-marker))
1308 (defun python-nav-backward-statement (&optional arg)
1309 "Move backward to previous statement.
1310 With ARG, repeat. See `python-nav-forward-statement'."
1311 (interactive "^p")
1312 (or arg (setq arg 1))
1313 (python-nav-forward-statement (- arg)))
1315 (defun python-nav-forward-statement (&optional arg)
1316 "Move forward to next statement.
1317 With ARG, repeat. With negative argument, move ARG times
1318 backward to previous statement."
1319 (interactive "^p")
1320 (or arg (setq arg 1))
1321 (while (> arg 0)
1322 (python-nav-end-of-statement)
1323 (python-util-forward-comment)
1324 (python-nav-beginning-of-statement)
1325 (setq arg (1- arg)))
1326 (while (< arg 0)
1327 (python-nav-beginning-of-statement)
1328 (python-util-forward-comment -1)
1329 (python-nav-beginning-of-statement)
1330 (setq arg (1+ arg))))
1332 (defun python-nav-beginning-of-block ()
1333 "Move to start of current block."
1334 (interactive "^")
1335 (let ((starting-pos (point))
1336 (block-regexp (python-rx
1337 line-start (* whitespace) block-start)))
1338 (if (progn
1339 (python-nav-beginning-of-statement)
1340 (looking-at (python-rx block-start)))
1341 (point-marker)
1342 ;; Go to first line beginning a statement
1343 (while (and (not (bobp))
1344 (or (and (python-nav-beginning-of-statement) nil)
1345 (python-info-current-line-comment-p)
1346 (python-info-current-line-empty-p)))
1347 (forward-line -1))
1348 (let ((block-matching-indent
1349 (- (current-indentation) python-indent-offset)))
1350 (while
1351 (and (python-nav-backward-block)
1352 (> (current-indentation) block-matching-indent)))
1353 (if (and (looking-at (python-rx block-start))
1354 (= (current-indentation) block-matching-indent))
1355 (point-marker)
1356 (and (goto-char starting-pos) nil))))))
1358 (defun python-nav-end-of-block ()
1359 "Move to end of current block."
1360 (interactive "^")
1361 (when (python-nav-beginning-of-block)
1362 (let ((block-indentation (current-indentation)))
1363 (python-nav-end-of-statement)
1364 (while (and (forward-line 1)
1365 (not (eobp))
1366 (or (and (> (current-indentation) block-indentation)
1367 (or (python-nav-end-of-statement) t))
1368 (python-info-current-line-comment-p)
1369 (python-info-current-line-empty-p))))
1370 (python-util-forward-comment -1)
1371 (point-marker))))
1373 (defun python-nav-backward-block (&optional arg)
1374 "Move backward to previous block of code.
1375 With ARG, repeat. See `python-nav-forward-block'."
1376 (interactive "^p")
1377 (or arg (setq arg 1))
1378 (python-nav-forward-block (- arg)))
1380 (defun python-nav-forward-block (&optional arg)
1381 "Move forward to next block of code.
1382 With ARG, repeat. With negative argument, move ARG times
1383 backward to previous block."
1384 (interactive "^p")
1385 (or arg (setq arg 1))
1386 (let ((block-start-regexp
1387 (python-rx line-start (* whitespace) block-start))
1388 (starting-pos (point)))
1389 (while (> arg 0)
1390 (python-nav-end-of-statement)
1391 (while (and
1392 (re-search-forward block-start-regexp nil t)
1393 (python-syntax-context-type)))
1394 (setq arg (1- arg)))
1395 (while (< arg 0)
1396 (python-nav-beginning-of-statement)
1397 (while (and
1398 (re-search-backward block-start-regexp nil t)
1399 (python-syntax-context-type)))
1400 (setq arg (1+ arg)))
1401 (python-nav-beginning-of-statement)
1402 (if (not (looking-at (python-rx block-start)))
1403 (and (goto-char starting-pos) nil)
1404 (and (not (= (point) starting-pos)) (point-marker)))))
1406 (defun python-nav-lisp-forward-sexp-safe (&optional arg)
1407 "Safe version of standard `forward-sexp'.
1408 When ARG > 0 move forward, else if ARG is < 0."
1409 (or arg (setq arg 1))
1410 (let ((forward-sexp-function)
1411 (paren-regexp
1412 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1413 (search-fn
1414 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1415 (condition-case nil
1416 (forward-sexp arg)
1417 (error
1418 (while (and (funcall search-fn paren-regexp nil t)
1419 (python-syntax-context 'paren)))))))
1421 (defun python-nav--forward-sexp (&optional dir)
1422 "Move to forward sexp.
1423 With positive Optional argument DIR direction move forward, else
1424 backwards."
1425 (setq dir (or dir 1))
1426 (unless (= dir 0)
1427 (let* ((forward-p (if (> dir 0)
1428 (and (setq dir 1) t)
1429 (and (setq dir -1) nil)))
1430 (re-search-fn (if forward-p
1431 're-search-forward
1432 're-search-backward))
1433 (context-type (python-syntax-context-type)))
1434 (cond
1435 ((memq context-type '(string comment))
1436 ;; Inside of a string, get out of it.
1437 (let ((forward-sexp-function))
1438 (forward-sexp dir)))
1439 ((or (eq context-type 'paren)
1440 (and forward-p (looking-at (python-rx open-paren)))
1441 (and (not forward-p)
1442 (eq (syntax-class (syntax-after (1- (point))))
1443 (car (string-to-syntax ")")))))
1444 ;; Inside a paren or looking at it, lisp knows what to do.
1445 (python-nav-lisp-forward-sexp-safe dir))
1447 ;; This part handles the lispy feel of
1448 ;; `python-nav-forward-sexp'. Knowing everything about the
1449 ;; current context and the context of the next sexp tries to
1450 ;; follow the lisp sexp motion commands in a symmetric manner.
1451 (let* ((context
1452 (cond
1453 ((python-info-beginning-of-block-p) 'block-start)
1454 ((python-info-end-of-block-p) 'block-end)
1455 ((python-info-beginning-of-statement-p) 'statement-start)
1456 ((python-info-end-of-statement-p) 'statement-end)))
1457 (next-sexp-pos
1458 (save-excursion
1459 (python-nav-lisp-forward-sexp-safe dir)
1460 (point)))
1461 (next-sexp-context
1462 (save-excursion
1463 (goto-char next-sexp-pos)
1464 (cond
1465 ((python-info-beginning-of-block-p) 'block-start)
1466 ((python-info-end-of-block-p) 'block-end)
1467 ((python-info-beginning-of-statement-p) 'statement-start)
1468 ((python-info-end-of-statement-p) 'statement-end)
1469 ((python-info-statement-starts-block-p) 'starts-block)
1470 ((python-info-statement-ends-block-p) 'ends-block)))))
1471 (if forward-p
1472 (cond ((and (not (eobp))
1473 (python-info-current-line-empty-p))
1474 (python-util-forward-comment dir)
1475 (python-nav--forward-sexp dir))
1476 ((eq context 'block-start)
1477 (python-nav-end-of-block))
1478 ((eq context 'statement-start)
1479 (python-nav-end-of-statement))
1480 ((and (memq context '(statement-end block-end))
1481 (eq next-sexp-context 'ends-block))
1482 (goto-char next-sexp-pos)
1483 (python-nav-end-of-block))
1484 ((and (memq context '(statement-end block-end))
1485 (eq next-sexp-context 'starts-block))
1486 (goto-char next-sexp-pos)
1487 (python-nav-end-of-block))
1488 ((memq context '(statement-end block-end))
1489 (goto-char next-sexp-pos)
1490 (python-nav-end-of-statement))
1491 (t (goto-char next-sexp-pos)))
1492 (cond ((and (not (bobp))
1493 (python-info-current-line-empty-p))
1494 (python-util-forward-comment dir)
1495 (python-nav--forward-sexp dir))
1496 ((eq context 'block-end)
1497 (python-nav-beginning-of-block))
1498 ((eq context 'statement-end)
1499 (python-nav-beginning-of-statement))
1500 ((and (memq context '(statement-start block-start))
1501 (eq next-sexp-context 'starts-block))
1502 (goto-char next-sexp-pos)
1503 (python-nav-beginning-of-block))
1504 ((and (memq context '(statement-start block-start))
1505 (eq next-sexp-context 'ends-block))
1506 (goto-char next-sexp-pos)
1507 (python-nav-beginning-of-block))
1508 ((memq context '(statement-start block-start))
1509 (goto-char next-sexp-pos)
1510 (python-nav-beginning-of-statement))
1511 (t (goto-char next-sexp-pos))))))))))
1513 (defun python-nav--backward-sexp ()
1514 "Move to backward sexp."
1515 (python-nav--forward-sexp -1))
1517 (defun python-nav-forward-sexp (&optional arg)
1518 "Move forward across one block of code.
1519 With ARG, do it that many times. Negative arg -N means
1520 move backward N times."
1521 (interactive "^p")
1522 (or arg (setq arg 1))
1523 (while (> arg 0)
1524 (python-nav--forward-sexp)
1525 (setq arg (1- arg)))
1526 (while (< arg 0)
1527 (python-nav--backward-sexp)
1528 (setq arg (1+ arg))))
1530 (defun python-nav--up-list (&optional dir)
1531 "Internal implementation of `python-nav-up-list'.
1532 DIR is always 1 or -1 and comes sanitized from
1533 `python-nav-up-list' calls."
1534 (let ((context (python-syntax-context-type))
1535 (forward-p (> dir 0)))
1536 (cond
1537 ((memq context '(string comment)))
1538 ((eq context 'paren)
1539 (let ((forward-sexp-function))
1540 (up-list dir)))
1541 ((and forward-p (python-info-end-of-block-p))
1542 (let ((parent-end-pos
1543 (save-excursion
1544 (let ((indentation (and
1545 (python-nav-beginning-of-block)
1546 (current-indentation))))
1547 (while (and indentation
1548 (> indentation 0)
1549 (>= (current-indentation) indentation)
1550 (python-nav-backward-block)))
1551 (python-nav-end-of-block)))))
1552 (and (> (or parent-end-pos (point)) (point))
1553 (goto-char parent-end-pos))))
1554 (forward-p (python-nav-end-of-block))
1555 ((and (not forward-p)
1556 (> (current-indentation) 0)
1557 (python-info-beginning-of-block-p))
1558 (let ((prev-block-pos
1559 (save-excursion
1560 (let ((indentation (current-indentation)))
1561 (while (and (python-nav-backward-block)
1562 (>= (current-indentation) indentation))))
1563 (point))))
1564 (and (> (point) prev-block-pos)
1565 (goto-char prev-block-pos))))
1566 ((not forward-p) (python-nav-beginning-of-block)))))
1568 (defun python-nav-up-list (&optional arg)
1569 "Move forward out of one level of parentheses (or blocks).
1570 With ARG, do this that many times.
1571 A negative argument means move backward but still to a less deep spot.
1572 This command assumes point is not in a string or comment."
1573 (interactive "^p")
1574 (or arg (setq arg 1))
1575 (while (> arg 0)
1576 (python-nav--up-list 1)
1577 (setq arg (1- arg)))
1578 (while (< arg 0)
1579 (python-nav--up-list -1)
1580 (setq arg (1+ arg))))
1582 (defun python-nav-backward-up-list (&optional arg)
1583 "Move backward out of one level of parentheses (or blocks).
1584 With ARG, do this that many times.
1585 A negative argument means move backward but still to a less deep spot.
1586 This command assumes point is not in a string or comment."
1587 (interactive "^p")
1588 (or arg (setq arg 1))
1589 (python-nav-up-list (- arg)))
1592 ;;; Shell integration
1594 (defcustom python-shell-buffer-name "Python"
1595 "Default buffer name for Python interpreter."
1596 :type 'string
1597 :group 'python
1598 :safe 'stringp)
1600 (defcustom python-shell-interpreter "python"
1601 "Default Python interpreter for shell."
1602 :type 'string
1603 :group 'python)
1605 (defcustom python-shell-internal-buffer-name "Python Internal"
1606 "Default buffer name for the Internal Python interpreter."
1607 :type 'string
1608 :group 'python
1609 :safe 'stringp)
1611 (defcustom python-shell-interpreter-args "-i"
1612 "Default arguments for the Python interpreter."
1613 :type 'string
1614 :group 'python)
1616 (defcustom python-shell-prompt-regexp ">>> "
1617 "Regular Expression matching top\-level input prompt of python shell.
1618 It should not contain a caret (^) at the beginning."
1619 :type 'string
1620 :group 'python
1621 :safe 'stringp)
1623 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1624 "Regular Expression matching block input prompt of python shell.
1625 It should not contain a caret (^) at the beginning."
1626 :type 'string
1627 :group 'python
1628 :safe 'stringp)
1630 (defcustom python-shell-prompt-output-regexp ""
1631 "Regular Expression matching output prompt of python shell.
1632 It should not contain a caret (^) at the beginning."
1633 :type 'string
1634 :group 'python
1635 :safe 'stringp)
1637 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1638 "Regular Expression matching pdb input prompt of python shell.
1639 It should not contain a caret (^) at the beginning."
1640 :type 'string
1641 :group 'python
1642 :safe 'stringp)
1644 (defcustom python-shell-enable-font-lock t
1645 "Should syntax highlighting be enabled in the python shell buffer?
1646 Restart the python shell after changing this variable for it to take effect."
1647 :type 'boolean
1648 :group 'python
1649 :safe 'booleanp)
1651 (defcustom python-shell-process-environment nil
1652 "List of environment variables for Python shell.
1653 This variable follows the same rules as `process-environment'
1654 since it merges with it before the process creation routines are
1655 called. When this variable is nil, the Python shell is run with
1656 the default `process-environment'."
1657 :type '(repeat string)
1658 :group 'python
1659 :safe 'listp)
1661 (defcustom python-shell-extra-pythonpaths nil
1662 "List of extra pythonpaths for Python shell.
1663 The values of this variable are added to the existing value of
1664 PYTHONPATH in the `process-environment' variable."
1665 :type '(repeat string)
1666 :group 'python
1667 :safe 'listp)
1669 (defcustom python-shell-exec-path nil
1670 "List of path to search for binaries.
1671 This variable follows the same rules as `exec-path' since it
1672 merges with it before the process creation routines are called.
1673 When this variable is nil, the Python shell is run with the
1674 default `exec-path'."
1675 :type '(repeat string)
1676 :group 'python
1677 :safe 'listp)
1679 (defcustom python-shell-virtualenv-path nil
1680 "Path to virtualenv root.
1681 This variable, when set to a string, makes the values stored in
1682 `python-shell-process-environment' and `python-shell-exec-path'
1683 to be modified properly so shells are started with the specified
1684 virtualenv."
1685 :type '(choice (const nil) string)
1686 :group 'python
1687 :safe 'stringp)
1689 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1690 python-ffap-setup-code
1691 python-eldoc-setup-code)
1692 "List of code run by `python-shell-send-setup-codes'."
1693 :type '(repeat symbol)
1694 :group 'python
1695 :safe 'listp)
1697 (defcustom python-shell-compilation-regexp-alist
1698 `((,(rx line-start (1+ (any " \t")) "File \""
1699 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1700 "\", line " (group (1+ digit)))
1701 1 2)
1702 (,(rx " in file " (group (1+ not-newline)) " on line "
1703 (group (1+ digit)))
1704 1 2)
1705 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1706 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1707 1 2))
1708 "`compilation-error-regexp-alist' for inferior Python."
1709 :type '(alist string)
1710 :group 'python)
1712 (defun python-shell-get-process-name (dedicated)
1713 "Calculate the appropriate process name for inferior Python process.
1714 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1715 returns a string with the form
1716 `python-shell-buffer-name'[variable `buffer-file-name'] else
1717 returns the value of `python-shell-buffer-name'."
1718 (let ((process-name
1719 (if (and dedicated
1720 buffer-file-name)
1721 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1722 (format "%s" python-shell-buffer-name))))
1723 process-name))
1725 (defun python-shell-internal-get-process-name ()
1726 "Calculate the appropriate process name for Internal Python process.
1727 The name is calculated from `python-shell-global-buffer-name' and
1728 a hash of all relevant global shell settings in order to ensure
1729 uniqueness for different types of configurations."
1730 (format "%s [%s]"
1731 python-shell-internal-buffer-name
1732 (md5
1733 (concat
1734 (python-shell-parse-command)
1735 python-shell-prompt-regexp
1736 python-shell-prompt-block-regexp
1737 python-shell-prompt-output-regexp
1738 (mapconcat #'symbol-value python-shell-setup-codes "")
1739 (mapconcat #'identity python-shell-process-environment "")
1740 (mapconcat #'identity python-shell-extra-pythonpaths "")
1741 (mapconcat #'identity python-shell-exec-path "")
1742 (or python-shell-virtualenv-path "")
1743 (mapconcat #'identity python-shell-exec-path "")))))
1745 (defun python-shell-parse-command ()
1746 "Calculate the string used to execute the inferior Python process."
1747 (let ((process-environment (python-shell-calculate-process-environment))
1748 (exec-path (python-shell-calculate-exec-path)))
1749 (format "%s %s"
1750 (executable-find python-shell-interpreter)
1751 python-shell-interpreter-args)))
1753 (defun python-shell-calculate-process-environment ()
1754 "Calculate process environment given `python-shell-virtualenv-path'."
1755 (let ((process-environment (append
1756 python-shell-process-environment
1757 process-environment nil))
1758 (virtualenv (if python-shell-virtualenv-path
1759 (directory-file-name python-shell-virtualenv-path)
1760 nil)))
1761 (when python-shell-extra-pythonpaths
1762 (setenv "PYTHONPATH"
1763 (format "%s%s%s"
1764 (mapconcat 'identity
1765 python-shell-extra-pythonpaths
1766 path-separator)
1767 path-separator
1768 (or (getenv "PYTHONPATH") ""))))
1769 (if (not virtualenv)
1770 process-environment
1771 (setenv "PYTHONHOME" nil)
1772 (setenv "PATH" (format "%s/bin%s%s"
1773 virtualenv path-separator
1774 (or (getenv "PATH") "")))
1775 (setenv "VIRTUAL_ENV" virtualenv))
1776 process-environment))
1778 (defun python-shell-calculate-exec-path ()
1779 "Calculate exec path given `python-shell-virtualenv-path'."
1780 (let ((path (append python-shell-exec-path
1781 exec-path nil)))
1782 (if (not python-shell-virtualenv-path)
1783 path
1784 (cons (format "%s/bin"
1785 (directory-file-name python-shell-virtualenv-path))
1786 path))))
1788 (defun python-comint-output-filter-function (output)
1789 "Hook run after content is put into comint buffer.
1790 OUTPUT is a string with the contents of the buffer."
1791 (ansi-color-filter-apply output))
1793 (defvar python-shell--parent-buffer nil)
1795 (defvar python-shell-output-syntax-table
1796 (let ((table (make-syntax-table python-dotty-syntax-table)))
1797 (modify-syntax-entry ?\' "." table)
1798 (modify-syntax-entry ?\" "." table)
1799 (modify-syntax-entry ?\( "." table)
1800 (modify-syntax-entry ?\[ "." table)
1801 (modify-syntax-entry ?\{ "." table)
1802 (modify-syntax-entry ?\) "." table)
1803 (modify-syntax-entry ?\] "." table)
1804 (modify-syntax-entry ?\} "." table)
1805 table)
1806 "Syntax table for shell output.
1807 It makes parens and quotes be treated as punctuation chars.")
1809 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1810 "Major mode for Python inferior process.
1811 Runs a Python interpreter as a subprocess of Emacs, with Python
1812 I/O through an Emacs buffer. Variables
1813 `python-shell-interpreter' and `python-shell-interpreter-args'
1814 controls which Python interpreter is run. Variables
1815 `python-shell-prompt-regexp',
1816 `python-shell-prompt-output-regexp',
1817 `python-shell-prompt-block-regexp',
1818 `python-shell-enable-font-lock',
1819 `python-shell-completion-setup-code',
1820 `python-shell-completion-string-code',
1821 `python-shell-completion-module-string-code',
1822 `python-eldoc-setup-code', `python-eldoc-string-code',
1823 `python-ffap-setup-code' and `python-ffap-string-code' can
1824 customize this mode for different Python interpreters.
1826 You can also add additional setup code to be run at
1827 initialization of the interpreter via `python-shell-setup-codes'
1828 variable.
1830 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1831 (and python-shell--parent-buffer
1832 (python-util-clone-local-variables python-shell--parent-buffer))
1833 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1834 python-shell-prompt-regexp
1835 python-shell-prompt-block-regexp
1836 python-shell-prompt-pdb-regexp))
1837 (setq mode-line-process '(":%s"))
1838 (make-local-variable 'comint-output-filter-functions)
1839 (add-hook 'comint-output-filter-functions
1840 'python-comint-output-filter-function)
1841 (add-hook 'comint-output-filter-functions
1842 'python-pdbtrack-comint-output-filter-function)
1843 (set (make-local-variable 'compilation-error-regexp-alist)
1844 python-shell-compilation-regexp-alist)
1845 (define-key inferior-python-mode-map [remap complete-symbol]
1846 'completion-at-point)
1847 (add-hook 'completion-at-point-functions
1848 'python-shell-completion-complete-at-point nil 'local)
1849 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1850 'python-shell-completion-complete-at-point)
1851 (define-key inferior-python-mode-map "\t"
1852 'python-shell-completion-complete-or-indent)
1853 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1854 (make-local-variable 'python-pdbtrack-tracked-buffer)
1855 (make-local-variable 'python-shell-internal-last-output)
1856 (when python-shell-enable-font-lock
1857 (set-syntax-table python-mode-syntax-table)
1858 (set (make-local-variable 'font-lock-defaults)
1859 '(python-font-lock-keywords nil nil nil nil))
1860 (set (make-local-variable 'syntax-propertize-function)
1861 (eval
1862 ;; XXX: Unfortunately eval is needed here to make use of the
1863 ;; dynamic value of `comint-prompt-regexp'.
1864 `(syntax-propertize-rules
1865 (,comint-prompt-regexp
1866 (0 (ignore
1867 (put-text-property
1868 comint-last-input-start end 'syntax-table
1869 python-shell-output-syntax-table)
1870 ;; XXX: This might look weird, but it is the easiest
1871 ;; way to ensure font lock gets cleaned up before the
1872 ;; current prompt, which is needed for unclosed
1873 ;; strings to not mess up with current input.
1874 (font-lock-unfontify-region comint-last-input-start end))))
1875 (,(python-rx string-delimiter)
1876 (0 (ignore
1877 (and (not (eq (get-text-property start 'field) 'output))
1878 (python-syntax-stringify)))))))))
1879 (compilation-shell-minor-mode 1))
1881 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
1882 "Create a python shell comint buffer.
1883 CMD is the python command to be executed and PROC-NAME is the
1884 process name the comint buffer will get. After the comint buffer
1885 is created the `inferior-python-mode' is activated. When
1886 optional argument POP is non-nil the buffer is shown. When
1887 optional argument INTERNAL is non-nil this process is run on a
1888 buffer with a name that starts with a space, following the Emacs
1889 convention for temporary/internal buffers, and also makes sure
1890 the user is not queried for confirmation when the process is
1891 killed."
1892 (save-excursion
1893 (let* ((proc-buffer-name
1894 (format (if (not internal) "*%s*" " *%s*") proc-name))
1895 (process-environment (python-shell-calculate-process-environment))
1896 (exec-path (python-shell-calculate-exec-path)))
1897 (when (not (comint-check-proc proc-buffer-name))
1898 (let* ((cmdlist (split-string-and-unquote cmd))
1899 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1900 (car cmdlist) nil (cdr cmdlist)))
1901 (python-shell--parent-buffer (current-buffer))
1902 (process (get-buffer-process buffer)))
1903 (with-current-buffer buffer
1904 (inferior-python-mode))
1905 (accept-process-output process)
1906 (and pop (pop-to-buffer buffer t))
1907 (and internal (set-process-query-on-exit-flag process nil))))
1908 proc-buffer-name)))
1910 ;;;###autoload
1911 (defun run-python (cmd &optional dedicated show)
1912 "Run an inferior Python process.
1913 Input and output via buffer named after
1914 `python-shell-buffer-name'. If there is a process already
1915 running in that buffer, just switch to it.
1917 With argument, allows you to define CMD so you can edit the
1918 command used to call the interpreter and define DEDICATED, so a
1919 dedicated process for the current buffer is open. When numeric
1920 prefix arg is other than 0 or 4 do not SHOW.
1922 Runs the hook `inferior-python-mode-hook' (after the
1923 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1924 process buffer for a list of commands.)"
1925 (interactive
1926 (if current-prefix-arg
1927 (list
1928 (read-string "Run Python: " (python-shell-parse-command))
1929 (y-or-n-p "Make dedicated process? ")
1930 (= (prefix-numeric-value current-prefix-arg) 4))
1931 (list (python-shell-parse-command) nil t)))
1932 (python-shell-make-comint
1933 cmd (python-shell-get-process-name dedicated) show)
1934 dedicated)
1936 (defun run-python-internal ()
1937 "Run an inferior Internal Python process.
1938 Input and output via buffer named after
1939 `python-shell-internal-buffer-name' and what
1940 `python-shell-internal-get-process-name' returns.
1942 This new kind of shell is intended to be used for generic
1943 communication related to defined configurations, the main
1944 difference with global or dedicated shells is that these ones are
1945 attached to a configuration, not a buffer. This means that can
1946 be used for example to retrieve the sys.path and other stuff,
1947 without messing with user shells. Note that
1948 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1949 are set to nil for these shells, so setup codes are not sent at
1950 startup."
1951 (let ((python-shell-enable-font-lock nil)
1952 (inferior-python-mode-hook nil))
1953 (get-buffer-process
1954 (python-shell-make-comint
1955 (python-shell-parse-command)
1956 (python-shell-internal-get-process-name) nil t))))
1958 (defun python-shell-get-process ()
1959 "Get inferior Python process for current buffer and return it."
1960 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1961 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1962 (global-proc-name (python-shell-get-process-name nil))
1963 (global-proc-buffer-name (format "*%s*" global-proc-name))
1964 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1965 (global-running (comint-check-proc global-proc-buffer-name)))
1966 ;; Always prefer dedicated
1967 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1968 (and global-running global-proc-buffer-name)))))
1970 (defun python-shell-get-or-create-process ()
1971 "Get or create an inferior Python process for current buffer and return it."
1972 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1973 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1974 (global-proc-name (python-shell-get-process-name nil))
1975 (global-proc-buffer-name (format "*%s*" global-proc-name))
1976 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1977 (global-running (comint-check-proc global-proc-buffer-name))
1978 (current-prefix-arg 16))
1979 (when (and (not dedicated-running) (not global-running))
1980 (if (call-interactively 'run-python)
1981 (setq dedicated-running t)
1982 (setq global-running t)))
1983 ;; Always prefer dedicated
1984 (get-buffer-process (if dedicated-running
1985 dedicated-proc-buffer-name
1986 global-proc-buffer-name))))
1988 (defvar python-shell-internal-buffer nil
1989 "Current internal shell buffer for the current buffer.
1990 This is really not necessary at all for the code to work but it's
1991 there for compatibility with CEDET.")
1993 (defvar python-shell-internal-last-output nil
1994 "Last output captured by the internal shell.
1995 This is really not necessary at all for the code to work but it's
1996 there for compatibility with CEDET.")
1998 (defun python-shell-internal-get-or-create-process ()
1999 "Get or create an inferior Internal Python process."
2000 (let* ((proc-name (python-shell-internal-get-process-name))
2001 (proc-buffer-name (format " *%s*" proc-name)))
2002 (when (not (process-live-p proc-name))
2003 (run-python-internal)
2004 (setq python-shell-internal-buffer proc-buffer-name)
2005 ;; XXX: Why is this `sit-for' needed?
2006 ;; `python-shell-make-comint' calls `accept-process-output'
2007 ;; already but it is not helping to get proper output on
2008 ;; 'gnu/linux when the internal shell process is not running and
2009 ;; a call to `python-shell-internal-send-string' is issued.
2010 (sit-for 0.1 t))
2011 (get-buffer-process proc-buffer-name)))
2013 (define-obsolete-function-alias
2014 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2016 (define-obsolete-variable-alias
2017 'python-buffer 'python-shell-internal-buffer "24.3")
2019 (define-obsolete-variable-alias
2020 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2022 (defun python-shell-send-string (string &optional process msg)
2023 "Send STRING to inferior Python PROCESS.
2024 When MSG is non-nil messages the first line of STRING."
2025 (interactive "sPython command: ")
2026 (let ((process (or process (python-shell-get-or-create-process)))
2027 (lines (split-string string "\n" t)))
2028 (and msg (message "Sent: %s..." (nth 0 lines)))
2029 (if (> (length lines) 1)
2030 (let* ((temporary-file-directory
2031 (if (file-remote-p default-directory)
2032 (concat (file-remote-p default-directory) "/tmp")
2033 temporary-file-directory))
2034 (temp-file-name (make-temp-file "py"))
2035 (file-name (or (buffer-file-name) temp-file-name)))
2036 (with-temp-file temp-file-name
2037 (insert string)
2038 (delete-trailing-whitespace))
2039 (python-shell-send-file file-name process temp-file-name))
2040 (comint-send-string process string)
2041 (when (or (not (string-match "\n$" string))
2042 (string-match "\n[ \t].*\n?$" string))
2043 (comint-send-string process "\n")))))
2045 (defvar python-shell-output-filter-in-progress nil)
2046 (defvar python-shell-output-filter-buffer nil)
2048 (defun python-shell-output-filter (string)
2049 "Filter used in `python-shell-send-string-no-output' to grab output.
2050 STRING is the output received to this point from the process.
2051 This filter saves received output from the process in
2052 `python-shell-output-filter-buffer' and stops receiving it after
2053 detecting a prompt at the end of the buffer."
2054 (setq
2055 string (ansi-color-filter-apply string)
2056 python-shell-output-filter-buffer
2057 (concat python-shell-output-filter-buffer string))
2058 (when (string-match
2059 ;; XXX: It seems on OSX an extra carriage return is attached
2060 ;; at the end of output, this handles that too.
2061 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
2062 python-shell-prompt-regexp
2063 python-shell-prompt-block-regexp
2064 python-shell-prompt-pdb-regexp)
2065 python-shell-output-filter-buffer)
2066 ;; Output ends when `python-shell-output-filter-buffer' contains
2067 ;; the prompt attached at the end of it.
2068 (setq python-shell-output-filter-in-progress nil
2069 python-shell-output-filter-buffer
2070 (substring python-shell-output-filter-buffer
2071 0 (match-beginning 0)))
2072 (when (and (> (length python-shell-prompt-output-regexp) 0)
2073 (string-match (concat "^" python-shell-prompt-output-regexp)
2074 python-shell-output-filter-buffer))
2075 ;; Some shells, like iPython might append a prompt before the
2076 ;; output, clean that.
2077 (setq python-shell-output-filter-buffer
2078 (substring python-shell-output-filter-buffer (match-end 0)))))
2081 (defun python-shell-send-string-no-output (string &optional process msg)
2082 "Send STRING to PROCESS and inhibit output.
2083 When MSG is non-nil messages the first line of STRING. Return
2084 the output."
2085 (let ((process (or process (python-shell-get-or-create-process)))
2086 (comint-preoutput-filter-functions
2087 '(python-shell-output-filter))
2088 (python-shell-output-filter-in-progress t)
2089 (inhibit-quit t))
2091 (with-local-quit
2092 (python-shell-send-string string process msg)
2093 (while python-shell-output-filter-in-progress
2094 ;; `python-shell-output-filter' takes care of setting
2095 ;; `python-shell-output-filter-in-progress' to NIL after it
2096 ;; detects end of output.
2097 (accept-process-output process))
2098 (prog1
2099 python-shell-output-filter-buffer
2100 (setq python-shell-output-filter-buffer nil)))
2101 (with-current-buffer (process-buffer process)
2102 (comint-interrupt-subjob)))))
2104 (defun python-shell-internal-send-string (string)
2105 "Send STRING to the Internal Python interpreter.
2106 Returns the output. See `python-shell-send-string-no-output'."
2107 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2108 ;; updated to support this new mode.
2109 (setq python-shell-internal-last-output
2110 (python-shell-send-string-no-output
2111 ;; Makes this function compatible with the old
2112 ;; python-send-receive. (At least for CEDET).
2113 (replace-regexp-in-string "_emacs_out +" "" string)
2114 (python-shell-internal-get-or-create-process) nil)))
2116 (define-obsolete-function-alias
2117 'python-send-receive 'python-shell-internal-send-string "24.3")
2119 (define-obsolete-function-alias
2120 'python-send-string 'python-shell-internal-send-string "24.3")
2122 (defun python-shell-send-region (start end)
2123 "Send the region delimited by START and END to inferior Python process."
2124 (interactive "r")
2125 (python-shell-send-string
2126 (concat
2127 (let ((line-num (line-number-at-pos start)))
2128 ;; When sending a region, add blank lines for non sent code so
2129 ;; backtraces remain correct.
2130 (make-string (1- line-num) ?\n))
2131 (buffer-substring start end))
2132 nil t))
2134 (defun python-shell-send-buffer (&optional arg)
2135 "Send the entire buffer to inferior Python process.
2136 With prefix ARG allow execution of code inside blocks delimited
2137 by \"if __name__== '__main__':\""
2138 (interactive "P")
2139 (save-restriction
2140 (widen)
2141 (let ((str (buffer-substring (point-min) (point-max))))
2142 (and
2143 (not arg)
2144 (setq str (replace-regexp-in-string
2145 (python-rx if-name-main)
2146 "if __name__ == '__main__ ':" str)))
2147 (python-shell-send-string str))))
2149 (defun python-shell-send-defun (arg)
2150 "Send the current defun to inferior Python process.
2151 When argument ARG is non-nil do not include decorators."
2152 (interactive "P")
2153 (save-excursion
2154 (python-shell-send-region
2155 (progn
2156 (end-of-line 1)
2157 (while (and (or (python-nav-beginning-of-defun)
2158 (beginning-of-line 1))
2159 (> (current-indentation) 0)))
2160 (when (not arg)
2161 (while (and (forward-line -1)
2162 (looking-at (python-rx decorator))))
2163 (forward-line 1))
2164 (point-marker))
2165 (progn
2166 (or (python-nav-end-of-defun)
2167 (end-of-line 1))
2168 (point-marker)))))
2170 (defun python-shell-send-file (file-name &optional process temp-file-name)
2171 "Send FILE-NAME to inferior Python PROCESS.
2172 If TEMP-FILE-NAME is passed then that file is used for processing
2173 instead, while internally the shell will continue to use
2174 FILE-NAME."
2175 (interactive "fFile to send: ")
2176 (let* ((process (or process (python-shell-get-or-create-process)))
2177 (temp-file-name (when temp-file-name
2178 (expand-file-name
2179 (or (file-remote-p temp-file-name 'localname)
2180 temp-file-name))))
2181 (file-name (or (when file-name
2182 (expand-file-name
2183 (or (file-remote-p file-name 'localname)
2184 file-name)))
2185 temp-file-name)))
2186 (when (not file-name)
2187 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2188 (python-shell-send-string
2189 (format
2190 (concat "__pyfile = open('''%s''');"
2191 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2192 "__pyfile.close()")
2193 (or temp-file-name file-name) file-name)
2194 process)))
2196 (defun python-shell-switch-to-shell ()
2197 "Switch to inferior Python process buffer."
2198 (interactive)
2199 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2201 (defun python-shell-send-setup-code ()
2202 "Send all setup code for shell.
2203 This function takes the list of setup code to send from the
2204 `python-shell-setup-codes' list."
2205 (let ((process (get-buffer-process (current-buffer))))
2206 (dolist (code python-shell-setup-codes)
2207 (when code
2208 (message "Sent %s" code)
2209 (python-shell-send-string
2210 (symbol-value code) process)))))
2212 (add-hook 'inferior-python-mode-hook
2213 #'python-shell-send-setup-code)
2216 ;;; Shell completion
2218 (defcustom python-shell-completion-setup-code
2219 "try:
2220 import readline
2221 except ImportError:
2222 def __COMPLETER_all_completions(text): []
2223 else:
2224 import rlcompleter
2225 readline.set_completer(rlcompleter.Completer().complete)
2226 def __COMPLETER_all_completions(text):
2227 import sys
2228 completions = []
2229 try:
2230 i = 0
2231 while True:
2232 res = readline.get_completer()(text, i)
2233 if not res: break
2234 i += 1
2235 completions.append(res)
2236 except NameError:
2237 pass
2238 return completions"
2239 "Code used to setup completion in inferior Python processes."
2240 :type 'string
2241 :group 'python)
2243 (defcustom python-shell-completion-string-code
2244 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2245 "Python code used to get a string of completions separated by semicolons."
2246 :type 'string
2247 :group 'python)
2249 (defcustom python-shell-completion-module-string-code ""
2250 "Python code used to get completions separated by semicolons for imports.
2252 For IPython v0.11, add the following line to
2253 `python-shell-completion-setup-code':
2255 from IPython.core.completerlib import module_completion
2257 and use the following as the value of this variable:
2259 ';'.join(module_completion('''%s'''))\n"
2260 :type 'string
2261 :group 'python)
2263 (defcustom python-shell-completion-pdb-string-code
2264 "';'.join(globals().keys() + locals().keys())"
2265 "Python code used to get completions separated by semicolons for [i]pdb."
2266 :type 'string
2267 :group 'python)
2269 (defun python-shell-completion-get-completions (process line input)
2270 "Do completion at point for PROCESS.
2271 LINE is used to detect the context on how to complete given
2272 INPUT."
2273 (let* ((prompt
2274 ;; Get the last prompt for the inferior process
2275 ;; buffer. This is used for the completion code selection
2276 ;; heuristic.
2277 (with-current-buffer (process-buffer process)
2278 (buffer-substring-no-properties
2279 (overlay-start comint-last-prompt-overlay)
2280 (overlay-end comint-last-prompt-overlay))))
2281 (completion-context
2282 ;; Check whether a prompt matches a pdb string, an import
2283 ;; statement or just the standard prompt and use the
2284 ;; correct python-shell-completion-*-code string
2285 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2286 (string-match
2287 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2288 'pdb)
2289 ((and (>
2290 (length python-shell-completion-module-string-code) 0)
2291 (string-match
2292 (concat "^" python-shell-prompt-regexp) prompt)
2293 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2294 'import)
2295 ((string-match
2296 (concat "^" python-shell-prompt-regexp) prompt)
2297 'default)
2298 (t nil)))
2299 (completion-code
2300 (pcase completion-context
2301 (`pdb python-shell-completion-pdb-string-code)
2302 (`import python-shell-completion-module-string-code)
2303 (`default python-shell-completion-string-code)
2304 (_ nil)))
2305 (input
2306 (if (eq completion-context 'import)
2307 (replace-regexp-in-string "^[ \t]+" "" line)
2308 input)))
2309 (and completion-code
2310 (> (length input) 0)
2311 (with-current-buffer (process-buffer process)
2312 (let ((completions (python-shell-send-string-no-output
2313 (format completion-code input) process)))
2314 (and (> (length completions) 2)
2315 (split-string completions
2316 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2318 (defun python-shell-completion-complete-at-point (&optional process)
2319 "Perform completion at point in inferior Python.
2320 Optional argument PROCESS forces completions to be retrieved
2321 using that one instead of current buffer's process."
2322 (setq process (or process (get-buffer-process (current-buffer))))
2323 (let* ((start
2324 (save-excursion
2325 (with-syntax-table python-dotty-syntax-table
2326 (let* ((paren-depth (car (syntax-ppss)))
2327 (syntax-string "w_")
2328 (syntax-list (string-to-syntax syntax-string)))
2329 ;; Stop scanning for the beginning of the completion
2330 ;; subject after the char before point matches a
2331 ;; delimiter
2332 (while (member
2333 (car (syntax-after (1- (point)))) syntax-list)
2334 (skip-syntax-backward syntax-string)
2335 (when (or (equal (char-before) ?\))
2336 (equal (char-before) ?\"))
2337 (forward-char -1))
2338 (while (or
2339 ;; honor initial paren depth
2340 (> (car (syntax-ppss)) paren-depth)
2341 (python-syntax-context 'string))
2342 (forward-char -1)))
2343 (point)))))
2344 (end (point)))
2345 (list start end
2346 (completion-table-dynamic
2347 (apply-partially
2348 #'python-shell-completion-get-completions
2349 process (buffer-substring-no-properties
2350 (line-beginning-position) end))))))
2352 (defun python-shell-completion-complete-or-indent ()
2353 "Complete or indent depending on the context.
2354 If content before pointer is all whitespace indent. If not try
2355 to complete."
2356 (interactive)
2357 (if (string-match "^[[:space:]]*$"
2358 (buffer-substring (comint-line-beginning-position)
2359 (point-marker)))
2360 (indent-for-tab-command)
2361 (completion-at-point)))
2364 ;;; PDB Track integration
2366 (defcustom python-pdbtrack-activate t
2367 "Non-nil makes python shell enable pdbtracking."
2368 :type 'boolean
2369 :group 'python
2370 :safe 'booleanp)
2372 (defcustom python-pdbtrack-stacktrace-info-regexp
2373 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2374 "Regular Expression matching stacktrace information.
2375 Used to extract the current line and module being inspected."
2376 :type 'string
2377 :group 'python
2378 :safe 'stringp)
2380 (defvar python-pdbtrack-tracked-buffer nil
2381 "Variable containing the value of the current tracked buffer.
2382 Never set this variable directly, use
2383 `python-pdbtrack-set-tracked-buffer' instead.")
2385 (defvar python-pdbtrack-buffers-to-kill nil
2386 "List of buffers to be deleted after tracking finishes.")
2388 (defun python-pdbtrack-set-tracked-buffer (file-name)
2389 "Set the buffer for FILE-NAME as the tracked buffer.
2390 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2391 Returns the tracked buffer."
2392 (let ((file-buffer (get-file-buffer file-name)))
2393 (if file-buffer
2394 (setq python-pdbtrack-tracked-buffer file-buffer)
2395 (setq file-buffer (find-file-noselect file-name))
2396 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2397 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2398 file-buffer))
2400 (defun python-pdbtrack-comint-output-filter-function (output)
2401 "Move overlay arrow to current pdb line in tracked buffer.
2402 Argument OUTPUT is a string with the output from the comint process."
2403 (when (and python-pdbtrack-activate (not (string= output "")))
2404 (let* ((full-output (ansi-color-filter-apply
2405 (buffer-substring comint-last-input-end (point-max))))
2406 (line-number)
2407 (file-name
2408 (with-temp-buffer
2409 (insert full-output)
2410 ;; When the debugger encounters a pdb.set_trace()
2411 ;; command, it prints a single stack frame. Sometimes
2412 ;; it prints a bit of extra information about the
2413 ;; arguments of the present function. When ipdb
2414 ;; encounters an exception, it prints the _entire_ stack
2415 ;; trace. To handle all of these cases, we want to find
2416 ;; the _last_ stack frame printed in the most recent
2417 ;; batch of output, then jump to the corresponding
2418 ;; file/line number.
2419 (goto-char (point-max))
2420 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
2421 (setq line-number (string-to-number
2422 (match-string-no-properties 2)))
2423 (match-string-no-properties 1)))))
2424 (if (and file-name line-number)
2425 (let* ((tracked-buffer
2426 (python-pdbtrack-set-tracked-buffer file-name))
2427 (shell-buffer (current-buffer))
2428 (tracked-buffer-window (get-buffer-window tracked-buffer))
2429 (tracked-buffer-line-pos))
2430 (with-current-buffer tracked-buffer
2431 (set (make-local-variable 'overlay-arrow-string) "=>")
2432 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2433 (setq tracked-buffer-line-pos (progn
2434 (goto-char (point-min))
2435 (forward-line (1- line-number))
2436 (point-marker)))
2437 (when tracked-buffer-window
2438 (set-window-point
2439 tracked-buffer-window tracked-buffer-line-pos))
2440 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2441 (pop-to-buffer tracked-buffer)
2442 (switch-to-buffer-other-window shell-buffer))
2443 (when python-pdbtrack-tracked-buffer
2444 (with-current-buffer python-pdbtrack-tracked-buffer
2445 (set-marker overlay-arrow-position nil))
2446 (mapc #'(lambda (buffer)
2447 (ignore-errors (kill-buffer buffer)))
2448 python-pdbtrack-buffers-to-kill)
2449 (setq python-pdbtrack-tracked-buffer nil
2450 python-pdbtrack-buffers-to-kill nil)))))
2451 output)
2454 ;;; Symbol completion
2456 (defun python-completion-complete-at-point ()
2457 "Complete current symbol at point.
2458 For this to work the best as possible you should call
2459 `python-shell-send-buffer' from time to time so context in
2460 inferior python process is updated properly."
2461 (let ((process (python-shell-get-process)))
2462 (if (not process)
2463 (error "Completion needs an inferior Python process running")
2464 (python-shell-completion-complete-at-point process))))
2466 (add-to-list 'debug-ignored-errors
2467 "^Completion needs an inferior Python process running.")
2470 ;;; Fill paragraph
2472 (defcustom python-fill-comment-function 'python-fill-comment
2473 "Function to fill comments.
2474 This is the function used by `python-fill-paragraph' to
2475 fill comments."
2476 :type 'symbol
2477 :group 'python)
2479 (defcustom python-fill-string-function 'python-fill-string
2480 "Function to fill strings.
2481 This is the function used by `python-fill-paragraph' to
2482 fill strings."
2483 :type 'symbol
2484 :group 'python)
2486 (defcustom python-fill-decorator-function 'python-fill-decorator
2487 "Function to fill decorators.
2488 This is the function used by `python-fill-paragraph' to
2489 fill decorators."
2490 :type 'symbol
2491 :group 'python)
2493 (defcustom python-fill-paren-function 'python-fill-paren
2494 "Function to fill parens.
2495 This is the function used by `python-fill-paragraph' to
2496 fill parens."
2497 :type 'symbol
2498 :group 'python)
2500 (defcustom python-fill-docstring-style 'pep-257
2501 "Style used to fill docstrings.
2502 This affects `python-fill-string' behavior with regards to
2503 triple quotes positioning.
2505 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2506 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2507 position and will treat docstrings a normal string, any other
2508 value may result in one of the following docstring styles:
2510 DJANGO:
2512 \"\"\"
2513 Process foo, return bar.
2514 \"\"\"
2516 \"\"\"
2517 Process foo, return bar.
2519 If processing fails throw ProcessingError.
2520 \"\"\"
2522 ONETWO:
2524 \"\"\"Process foo, return bar.\"\"\"
2526 \"\"\"
2527 Process foo, return bar.
2529 If processing fails throw ProcessingError.
2531 \"\"\"
2533 PEP-257:
2535 \"\"\"Process foo, return bar.\"\"\"
2537 \"\"\"Process foo, return bar.
2539 If processing fails throw ProcessingError.
2541 \"\"\"
2543 PEP-257-NN:
2545 \"\"\"Process foo, return bar.\"\"\"
2547 \"\"\"Process foo, return bar.
2549 If processing fails throw ProcessingError.
2550 \"\"\"
2552 SYMMETRIC:
2554 \"\"\"Process foo, return bar.\"\"\"
2556 \"\"\"
2557 Process foo, return bar.
2559 If processing fails throw ProcessingError.
2560 \"\"\""
2561 :type '(choice
2562 (const :tag "Don't format docstrings" nil)
2563 (const :tag "Django's coding standards style." django)
2564 (const :tag "One newline and start and Two at end style." onetwo)
2565 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2566 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2567 (const :tag "Symmetric style." symmetric))
2568 :group 'python
2569 :safe (lambda (val)
2570 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2572 (defun python-fill-paragraph (&optional justify)
2573 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2574 If any of the current line is in or at the end of a multi-line string,
2575 fill the string or the paragraph of it that point is in, preserving
2576 the string's indentation.
2577 Optional argument JUSTIFY defines if the paragraph should be justified."
2578 (interactive "P")
2579 (save-excursion
2580 (cond
2581 ;; Comments
2582 ((python-syntax-context 'comment)
2583 (funcall python-fill-comment-function justify))
2584 ;; Strings/Docstrings
2585 ((save-excursion (or (python-syntax-context 'string)
2586 (equal (string-to-syntax "|")
2587 (syntax-after (point)))))
2588 (funcall python-fill-string-function justify))
2589 ;; Decorators
2590 ((equal (char-after (save-excursion
2591 (python-nav-beginning-of-statement))) ?@)
2592 (funcall python-fill-decorator-function justify))
2593 ;; Parens
2594 ((or (python-syntax-context 'paren)
2595 (looking-at (python-rx open-paren))
2596 (save-excursion
2597 (skip-syntax-forward "^(" (line-end-position))
2598 (looking-at (python-rx open-paren))))
2599 (funcall python-fill-paren-function justify))
2600 (t t))))
2602 (defun python-fill-comment (&optional justify)
2603 "Comment fill function for `python-fill-paragraph'.
2604 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2605 (fill-comment-paragraph justify))
2607 (defun python-fill-string (&optional justify)
2608 "String fill function for `python-fill-paragraph'.
2609 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2610 (let* ((marker (point-marker))
2611 (str-start-pos
2612 (set-marker
2613 (make-marker)
2614 (or (python-syntax-context 'string)
2615 (and (equal (string-to-syntax "|")
2616 (syntax-after (point)))
2617 (point)))))
2618 (num-quotes (python-syntax-count-quotes
2619 (char-after str-start-pos) str-start-pos))
2620 (str-end-pos
2621 (save-excursion
2622 (goto-char (+ str-start-pos num-quotes))
2623 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2624 (goto-char (point-max)))
2625 (point-marker)))
2626 (multi-line-p
2627 ;; Docstring styles may vary for oneliners and multi-liners.
2628 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2629 (delimiters-style
2630 (pcase python-fill-docstring-style
2631 ;; delimiters-style is a cons cell with the form
2632 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2633 ;; is NIL means to not add any newlines for start or end
2634 ;; of docstring. See `python-fill-docstring-style' for a
2635 ;; graphic idea of each style.
2636 (`django (cons 1 1))
2637 (`onetwo (and multi-line-p (cons 1 2)))
2638 (`pep-257 (and multi-line-p (cons nil 2)))
2639 (`pep-257-nn (and multi-line-p (cons nil 1)))
2640 (`symmetric (and multi-line-p (cons 1 1)))))
2641 (docstring-p (save-excursion
2642 ;; Consider docstrings those strings which
2643 ;; start on a line by themselves.
2644 (python-nav-beginning-of-statement)
2645 (and (= (point) str-start-pos))))
2646 (fill-paragraph-function))
2647 (save-restriction
2648 (narrow-to-region str-start-pos str-end-pos)
2649 (fill-paragraph justify))
2650 (save-excursion
2651 (when (and docstring-p python-fill-docstring-style)
2652 ;; Add the number of newlines indicated by the selected style
2653 ;; at the start of the docstring.
2654 (goto-char (+ str-start-pos num-quotes))
2655 (delete-region (point) (progn
2656 (skip-syntax-forward "> ")
2657 (point)))
2658 (and (car delimiters-style)
2659 (or (newline (car delimiters-style)) t)
2660 ;; Indent only if a newline is added.
2661 (indent-according-to-mode))
2662 ;; Add the number of newlines indicated by the selected style
2663 ;; at the end of the docstring.
2664 (goto-char (if (not (= str-end-pos (point-max)))
2665 (- str-end-pos num-quotes)
2666 str-end-pos))
2667 (delete-region (point) (progn
2668 (skip-syntax-backward "> ")
2669 (point)))
2670 (and (cdr delimiters-style)
2671 ;; Add newlines only if string ends.
2672 (not (= str-end-pos (point-max)))
2673 (or (newline (cdr delimiters-style)) t)
2674 ;; Again indent only if a newline is added.
2675 (indent-according-to-mode))))) t)
2677 (defun python-fill-decorator (&optional justify)
2678 "Decorator fill function for `python-fill-paragraph'.
2679 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2682 (defun python-fill-paren (&optional justify)
2683 "Paren fill function for `python-fill-paragraph'.
2684 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2685 (save-restriction
2686 (narrow-to-region (progn
2687 (while (python-syntax-context 'paren)
2688 (goto-char (1- (point-marker))))
2689 (point-marker)
2690 (line-beginning-position))
2691 (progn
2692 (when (not (python-syntax-context 'paren))
2693 (end-of-line)
2694 (when (not (python-syntax-context 'paren))
2695 (skip-syntax-backward "^)")))
2696 (while (python-syntax-context 'paren)
2697 (goto-char (1+ (point-marker))))
2698 (point-marker)))
2699 (let ((paragraph-start "\f\\|[ \t]*$")
2700 (paragraph-separate ",")
2701 (fill-paragraph-function))
2702 (goto-char (point-min))
2703 (fill-paragraph justify))
2704 (while (not (eobp))
2705 (forward-line 1)
2706 (python-indent-line)
2707 (goto-char (line-end-position)))) t)
2710 ;;; Skeletons
2712 (defcustom python-skeleton-autoinsert nil
2713 "Non-nil means template skeletons will be automagically inserted.
2714 This happens when pressing \"if<SPACE>\", for example, to prompt for
2715 the if condition."
2716 :type 'boolean
2717 :group 'python
2718 :safe 'booleanp)
2720 (define-obsolete-variable-alias
2721 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2723 (defvar python-skeleton-available '()
2724 "Internal list of available skeletons.")
2726 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
2727 "Abbrev table for Python mode skeletons."
2728 :case-fixed t
2729 ;; Allow / inside abbrevs.
2730 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2731 ;; Only expand in code.
2732 :enable-function (lambda ()
2733 (and
2734 (not (python-syntax-comment-or-string-p))
2735 python-skeleton-autoinsert)))
2737 (defmacro python-skeleton-define (name doc &rest skel)
2738 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2739 The skeleton will be bound to python-skeleton-NAME and will
2740 be added to `python-mode-skeleton-abbrev-table'."
2741 (declare (indent 2))
2742 (let* ((name (symbol-name name))
2743 (function-name (intern (concat "python-skeleton-" name))))
2744 `(progn
2745 (define-abbrev python-mode-skeleton-abbrev-table
2746 ,name "" ',function-name :system t)
2747 (setq python-skeleton-available
2748 (cons ',function-name python-skeleton-available))
2749 (define-skeleton ,function-name
2750 ,(or doc
2751 (format "Insert %s statement." name))
2752 ,@skel))))
2754 (define-abbrev-table 'python-mode-abbrev-table ()
2755 "Abbrev table for Python mode."
2756 :parents (list python-mode-skeleton-abbrev-table))
2758 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2759 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2760 The skeleton will be bound to python-skeleton-NAME."
2761 (declare (indent 2))
2762 (let* ((name (symbol-name name))
2763 (function-name (intern (concat "python-skeleton--" name)))
2764 (msg (format
2765 "Add '%s' clause? " name)))
2766 (when (not skel)
2767 (setq skel
2768 `(< ,(format "%s:" name) \n \n
2769 > _ \n)))
2770 `(define-skeleton ,function-name
2771 ,(or doc
2772 (format "Auxiliary skeleton for %s statement." name))
2774 (unless (y-or-n-p ,msg)
2775 (signal 'quit t))
2776 ,@skel)))
2778 (python-define-auxiliary-skeleton else nil)
2780 (python-define-auxiliary-skeleton except nil)
2782 (python-define-auxiliary-skeleton finally nil)
2784 (python-skeleton-define if nil
2785 "Condition: "
2786 "if " str ":" \n
2787 _ \n
2788 ("other condition, %s: "
2790 "elif " str ":" \n
2791 > _ \n nil)
2792 '(python-skeleton--else) | ^)
2794 (python-skeleton-define while nil
2795 "Condition: "
2796 "while " str ":" \n
2797 > _ \n
2798 '(python-skeleton--else) | ^)
2800 (python-skeleton-define for nil
2801 "Iteration spec: "
2802 "for " str ":" \n
2803 > _ \n
2804 '(python-skeleton--else) | ^)
2806 (python-skeleton-define try nil
2808 "try:" \n
2809 > _ \n
2810 ("Exception, %s: "
2812 "except " str ":" \n
2813 > _ \n nil)
2814 resume:
2815 '(python-skeleton--except)
2816 '(python-skeleton--else)
2817 '(python-skeleton--finally) | ^)
2819 (python-skeleton-define def nil
2820 "Function name: "
2821 "def " str "(" ("Parameter, %s: "
2822 (unless (equal ?\( (char-before)) ", ")
2823 str) "):" \n
2824 "\"\"\"" - "\"\"\"" \n
2825 > _ \n)
2827 (python-skeleton-define class nil
2828 "Class name: "
2829 "class " str "(" ("Inheritance, %s: "
2830 (unless (equal ?\( (char-before)) ", ")
2831 str)
2832 & ")" | -2
2833 ":" \n
2834 "\"\"\"" - "\"\"\"" \n
2835 > _ \n)
2837 (defun python-skeleton-add-menu-items ()
2838 "Add menu items to Python->Skeletons menu."
2839 (let ((skeletons (sort python-skeleton-available 'string<))
2840 (items))
2841 (dolist (skeleton skeletons)
2842 (easy-menu-add-item
2843 nil '("Python" "Skeletons")
2844 `[,(format
2845 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
2846 ,skeleton t]))))
2848 ;;; FFAP
2850 (defcustom python-ffap-setup-code
2851 "def __FFAP_get_module_path(module):
2852 try:
2853 import os
2854 path = __import__(module).__file__
2855 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2856 path = path[:-1]
2857 return path
2858 except:
2859 return ''"
2860 "Python code to get a module path."
2861 :type 'string
2862 :group 'python)
2864 (defcustom python-ffap-string-code
2865 "__FFAP_get_module_path('''%s''')\n"
2866 "Python code used to get a string with the path of a module."
2867 :type 'string
2868 :group 'python)
2870 (defun python-ffap-module-path (module)
2871 "Function for `ffap-alist' to return path for MODULE."
2872 (let ((process (or
2873 (and (eq major-mode 'inferior-python-mode)
2874 (get-buffer-process (current-buffer)))
2875 (python-shell-get-process))))
2876 (if (not process)
2878 (let ((module-file
2879 (python-shell-send-string-no-output
2880 (format python-ffap-string-code module) process)))
2881 (when module-file
2882 (substring-no-properties module-file 1 -1))))))
2884 (defvar ffap-alist)
2886 (eval-after-load "ffap"
2887 '(progn
2888 (push '(python-mode . python-ffap-module-path) ffap-alist)
2889 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2892 ;;; Code check
2894 (defcustom python-check-command
2895 "pyflakes"
2896 "Command used to check a Python file."
2897 :type 'string
2898 :group 'python)
2900 (defcustom python-check-buffer-name
2901 "*Python check: %s*"
2902 "Buffer name used for check commands."
2903 :type 'string
2904 :group 'python)
2906 (defvar python-check-custom-command nil
2907 "Internal use.")
2909 (defun python-check (command)
2910 "Check a Python file (default current buffer's file).
2911 Runs COMMAND, a shell command, as if by `compile'. See
2912 `python-check-command' for the default."
2913 (interactive
2914 (list (read-string "Check command: "
2915 (or python-check-custom-command
2916 (concat python-check-command " "
2917 (shell-quote-argument
2919 (let ((name (buffer-file-name)))
2920 (and name
2921 (file-name-nondirectory name)))
2922 "")))))))
2923 (setq python-check-custom-command command)
2924 (save-some-buffers (not compilation-ask-about-save) nil)
2925 (let ((process-environment (python-shell-calculate-process-environment))
2926 (exec-path (python-shell-calculate-exec-path)))
2927 (compilation-start command nil
2928 (lambda (mode-name)
2929 (format python-check-buffer-name command)))))
2932 ;;; Eldoc
2934 (defcustom python-eldoc-setup-code
2935 "def __PYDOC_get_help(obj):
2936 try:
2937 import inspect
2938 if hasattr(obj, 'startswith'):
2939 obj = eval(obj, globals())
2940 doc = inspect.getdoc(obj)
2941 if not doc and callable(obj):
2942 target = None
2943 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2944 target = obj.__init__
2945 objtype = 'class'
2946 else:
2947 target = obj
2948 objtype = 'def'
2949 if target:
2950 args = inspect.formatargspec(
2951 *inspect.getargspec(target)
2953 name = obj.__name__
2954 doc = '{objtype} {name}{args}'.format(
2955 objtype=objtype, name=name, args=args
2957 else:
2958 doc = doc.splitlines()[0]
2959 except:
2960 doc = ''
2961 try:
2962 exec('print doc')
2963 except SyntaxError:
2964 print(doc)"
2965 "Python code to setup documentation retrieval."
2966 :type 'string
2967 :group 'python)
2969 (defcustom python-eldoc-string-code
2970 "__PYDOC_get_help('''%s''')\n"
2971 "Python code used to get a string with the documentation of an object."
2972 :type 'string
2973 :group 'python)
2975 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2976 "Internal implementation to get documentation at point.
2977 If not FORCE-INPUT is passed then what
2978 `python-info-current-symbol' returns will be used. If not
2979 FORCE-PROCESS is passed what `python-shell-get-process' returns
2980 is used."
2981 (let ((process (or force-process (python-shell-get-process))))
2982 (if (not process)
2983 (error "Eldoc needs an inferior Python process running")
2984 (let ((input (or force-input
2985 (python-info-current-symbol t))))
2986 (and input
2987 (python-shell-send-string-no-output
2988 (format python-eldoc-string-code input)
2989 process))))))
2991 (defun python-eldoc-function ()
2992 "`eldoc-documentation-function' for Python.
2993 For this to work the best as possible you should call
2994 `python-shell-send-buffer' from time to time so context in
2995 inferior python process is updated properly."
2996 (python-eldoc--get-doc-at-point))
2998 (defun python-eldoc-at-point (symbol)
2999 "Get help on SYMBOL using `help'.
3000 Interactively, prompt for symbol."
3001 (interactive
3002 (let ((symbol (python-info-current-symbol t))
3003 (enable-recursive-minibuffers t))
3004 (list (read-string (if symbol
3005 (format "Describe symbol (default %s): " symbol)
3006 "Describe symbol: ")
3007 nil nil symbol))))
3008 (message (python-eldoc--get-doc-at-point symbol)))
3010 (add-to-list 'debug-ignored-errors
3011 "^Eldoc needs an inferior Python process running.")
3014 ;;; Imenu
3016 (defvar python-imenu-format-item-label-function
3017 'python-imenu-format-item-label
3018 "Imenu function used to format an item label.
3019 It must be a function with two arguments: TYPE and NAME.")
3021 (defvar python-imenu-format-parent-item-label-function
3022 'python-imenu-format-parent-item-label
3023 "Imenu function used to format a parent item label.
3024 It must be a function with two arguments: TYPE and NAME.")
3026 (defvar python-imenu-format-parent-item-jump-label-function
3027 'python-imenu-format-parent-item-jump-label
3028 "Imenu function used to format a parent jump item label.
3029 It must be a function with two arguments: TYPE and NAME.")
3031 (defun python-imenu-format-item-label (type name)
3032 "Return imenu label for single node using TYPE and NAME."
3033 (format "%s (%s)" name type))
3035 (defun python-imenu-format-parent-item-label (type name)
3036 "Return imenu label for parent node using TYPE and NAME."
3037 (format "%s..." (python-imenu-format-item-label type name)))
3039 (defun python-imenu-format-parent-item-jump-label (type name)
3040 "Return imenu label for parent node jump using TYPE and NAME."
3041 (if (string= type "class")
3042 "*class definition*"
3043 "*function definition*"))
3045 (defun python-imenu--put-parent (type name pos num-children tree &optional root)
3046 "Add the parent with TYPE, NAME, POS and NUM-CHILDREN to TREE.
3047 Optional Argument ROOT must be non-nil when the node being
3048 processed is the root of the TREE."
3049 (let ((label
3050 (funcall python-imenu-format-item-label-function type name))
3051 (jump-label
3052 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3053 (if root
3054 ;; This is the root, everything is a children.
3055 (cons label (cons (cons jump-label pos) tree))
3056 ;; This is node a which may contain some children.
3057 (cons
3058 (cons label (cons (cons jump-label pos)
3059 ;; Append all the children
3060 (python-util-popn tree num-children)))
3061 ;; All previous non-children nodes.
3062 (nthcdr num-children tree)))))
3064 (defun python-imenu--build-tree (&optional min-indent prev-indent num-children tree)
3065 "Recursively build the tree of nested definitions of a node.
3066 Arguments MIN-INDENT PREV-INDENT NUM-CHILDREN and TREE are
3067 internal and should not be passed explicitly unless you know what
3068 you are doing."
3069 (setq num-children (or num-children 0)
3070 min-indent (or min-indent 0))
3071 (let* ((pos (python-nav-backward-defun))
3072 (type)
3073 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3074 (let ((split (split-string (match-string-no-properties 0))))
3075 (setq type (car split))
3076 (cadr split))))
3077 (label (when name
3078 (funcall python-imenu-format-item-label-function type name)))
3079 (indent (current-indentation)))
3080 (cond ((not pos)
3081 ;; No defun found, nothing to add.
3082 tree)
3083 ((equal indent 0)
3084 (if (> num-children 0)
3085 ;; Append it as the parent of everything collected to
3086 ;; this point.
3087 (python-imenu--put-parent type name pos num-children tree t)
3088 ;; There are no children, this is a lonely defun.
3089 (cons label pos)))
3090 ((equal min-indent indent)
3091 ;; Stop collecting nodes after moving to a position with
3092 ;; indentation equaling min-indent. This is specially
3093 ;; useful for navigating nested definitions recursively.
3094 (if (> num-children 0)
3095 tree
3096 ;; When there are no children, the collected tree is a
3097 ;; single node intended to be added in the list of defuns
3098 ;; of its parent.
3099 (car tree)))
3101 (python-imenu--build-tree
3102 min-indent
3103 indent
3104 ;; Add another children, either when this is the
3105 ;; first call or when indentation is
3106 ;; less-or-equal than previous. And do not
3107 ;; discard the number of children, because the
3108 ;; way code is scanned, all children are
3109 ;; collected until a root node yet to be found
3110 ;; appears.
3111 (if (or (not prev-indent)
3112 (and
3113 (> indent min-indent)
3114 (<= indent prev-indent)))
3115 (1+ num-children)
3116 num-children)
3117 (cond ((not prev-indent)
3118 ;; First call to the function: append this
3119 ;; defun to the index.
3120 (list (cons label pos)))
3121 ((= indent prev-indent)
3122 ;; Add another defun with the same depth
3123 ;; as the previous.
3124 (cons (cons label pos) tree))
3125 ((and (< indent prev-indent)
3126 (< 0 num-children))
3127 ;; There are children to be appended and
3128 ;; the previous defun had more
3129 ;; indentation, the current one must be a
3130 ;; parent.
3131 (python-imenu--put-parent type name pos num-children tree))
3132 ((> indent prev-indent)
3133 ;; There are children defuns deeper than
3134 ;; current depth. Fear not, we already
3135 ;; know how to treat them.
3136 (cons
3137 (prog1
3138 (python-imenu--build-tree
3139 prev-indent indent 0 (list (cons label pos)))
3140 ;; Adjustment: after scanning backwards
3141 ;; for all deeper children, we need to
3142 ;; continue our scan for a parent from
3143 ;; the current defun we are looking at.
3144 (python-nav-forward-defun))
3145 tree))))))))
3147 (defun python-imenu-create-index ()
3148 "Return tree Imenu alist for the current python buffer.
3149 Change `python-imenu-format-item-label-function',
3150 `python-imenu-format-parent-item-label-function',
3151 `python-imenu-format-parent-item-jump-label-function' to
3152 customize how labels are formatted."
3153 (goto-char (point-max))
3154 (let ((index)
3155 (tree))
3156 (while (setq tree (python-imenu--build-tree))
3157 (setq index (cons tree index)))
3158 index))
3160 (defun python-imenu-create-flat-index (&optional alist prefix)
3161 "Return flat outline of the current python buffer for Imenu.
3162 Optional Argument ALIST is the tree to be flattened, when nil
3163 `python-imenu-build-index' is used with
3164 `python-imenu-format-parent-item-jump-label-function'
3165 `python-imenu-format-parent-item-label-function'
3166 `python-imenu-format-item-label-function' set to (lambda (type
3167 name) name). Optional Argument PREFIX is used in recursive calls
3168 and should not be passed explicitly.
3170 Converts this:
3172 \((\"Foo\" . 103)
3173 (\"Bar\" . 138)
3174 (\"decorator\"
3175 (\"decorator\" . 173)
3176 (\"wrap\"
3177 (\"wrap\" . 353)
3178 (\"wrapped_f\" . 393))))
3180 To this:
3182 \((\"Foo\" . 103)
3183 (\"Bar\" . 138)
3184 (\"decorator\" . 173)
3185 (\"decorator.wrap\" . 353)
3186 (\"decorator.wrapped_f\" . 393))"
3187 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3188 (apply
3189 'nconc
3190 (mapcar
3191 (lambda (item)
3192 (let ((name (if prefix
3193 (concat prefix "." (car item))
3194 (car item)))
3195 (pos (cdr item)))
3196 (cond ((or (numberp pos) (markerp pos))
3197 (list (cons name pos)))
3198 ((listp pos)
3199 (cons
3200 (cons name (cdar pos))
3201 (python-imenu-create-flat-index (cddr item) name))))))
3202 (or alist
3203 (let* ((fn (lambda (type name) name))
3204 (python-imenu-format-item-label-function fn)
3205 (python-imenu-format-parent-item-label-function fn)
3206 (python-imenu-format-parent-item-jump-label-function fn))
3207 (python-imenu-create-index))))))
3210 ;;; Misc helpers
3212 (defun python-info-current-defun (&optional include-type)
3213 "Return name of surrounding function with Python compatible dotty syntax.
3214 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3215 This function is compatible to be used as
3216 `add-log-current-defun-function' since it returns nil if point is
3217 not inside a defun."
3218 (save-restriction
3219 (widen)
3220 (save-excursion
3221 (end-of-line 1)
3222 (let ((names)
3223 (starting-indentation (current-indentation))
3224 (starting-pos (point))
3225 (first-run t)
3226 (last-indent)
3227 (type))
3228 (catch 'exit
3229 (while (python-nav-beginning-of-defun 1)
3230 (when (save-match-data
3231 (and
3232 (or (not last-indent)
3233 (< (current-indentation) last-indent))
3235 (and first-run
3236 (save-excursion
3237 ;; If this is the first run, we may add
3238 ;; the current defun at point.
3239 (setq first-run nil)
3240 (goto-char starting-pos)
3241 (python-nav-beginning-of-statement)
3242 (beginning-of-line 1)
3243 (looking-at-p
3244 python-nav-beginning-of-defun-regexp)))
3245 (< starting-pos
3246 (save-excursion
3247 (let ((min-indent
3248 (+ (current-indentation)
3249 python-indent-offset)))
3250 (if (< starting-indentation min-indent)
3251 ;; If the starting indentation is not
3252 ;; within the min defun indent make the
3253 ;; check fail.
3254 starting-pos
3255 ;; Else go to the end of defun and add
3256 ;; up the current indentation to the
3257 ;; ending position.
3258 (python-nav-end-of-defun)
3259 (+ (point)
3260 (if (>= (current-indentation) min-indent)
3261 (1+ (current-indentation))
3262 0)))))))))
3263 (save-match-data (setq last-indent (current-indentation)))
3264 (if (or (not include-type) type)
3265 (setq names (cons (match-string-no-properties 1) names))
3266 (let ((match (split-string (match-string-no-properties 0))))
3267 (setq type (car match))
3268 (setq names (cons (cadr match) names)))))
3269 ;; Stop searching ASAP.
3270 (and (= (current-indentation) 0) (throw 'exit t))))
3271 (and names
3272 (concat (and type (format "%s " type))
3273 (mapconcat 'identity names ".")))))))
3275 (defun python-info-current-symbol (&optional replace-self)
3276 "Return current symbol using dotty syntax.
3277 With optional argument REPLACE-SELF convert \"self\" to current
3278 parent defun name."
3279 (let ((name
3280 (and (not (python-syntax-comment-or-string-p))
3281 (with-syntax-table python-dotty-syntax-table
3282 (let ((sym (symbol-at-point)))
3283 (and sym
3284 (substring-no-properties (symbol-name sym))))))))
3285 (when name
3286 (if (not replace-self)
3287 name
3288 (let ((current-defun (python-info-current-defun)))
3289 (if (not current-defun)
3290 name
3291 (replace-regexp-in-string
3292 (python-rx line-start word-start "self" word-end ?.)
3293 (concat
3294 (mapconcat 'identity
3295 (butlast (split-string current-defun "\\."))
3296 ".") ".")
3297 name)))))))
3299 (defun python-info-statement-starts-block-p ()
3300 "Return non-nil if current statement opens a block."
3301 (save-excursion
3302 (python-nav-beginning-of-statement)
3303 (looking-at (python-rx block-start))))
3305 (defun python-info-statement-ends-block-p ()
3306 "Return non-nil if point is at end of block."
3307 (let ((end-of-block-pos (save-excursion
3308 (python-nav-end-of-block)))
3309 (end-of-statement-pos (save-excursion
3310 (python-nav-end-of-statement))))
3311 (and end-of-block-pos end-of-statement-pos
3312 (= end-of-block-pos end-of-statement-pos))))
3314 (defun python-info-beginning-of-statement-p ()
3315 "Return non-nil if point is at beginning of statement."
3316 (= (point) (save-excursion
3317 (python-nav-beginning-of-statement)
3318 (point))))
3320 (defun python-info-end-of-statement-p ()
3321 "Return non-nil if point is at end of statement."
3322 (= (point) (save-excursion
3323 (python-nav-end-of-statement)
3324 (point))))
3326 (defun python-info-beginning-of-block-p ()
3327 "Return non-nil if point is at beginning of block."
3328 (and (python-info-beginning-of-statement-p)
3329 (python-info-statement-starts-block-p)))
3331 (defun python-info-end-of-block-p ()
3332 "Return non-nil if point is at end of block."
3333 (and (python-info-end-of-statement-p)
3334 (python-info-statement-ends-block-p)))
3336 (defun python-info-closing-block ()
3337 "Return the point of the block the current line closes."
3338 (let ((closing-word (save-excursion
3339 (back-to-indentation)
3340 (current-word)))
3341 (indentation (current-indentation)))
3342 (when (member closing-word python-indent-dedenters)
3343 (save-excursion
3344 (forward-line -1)
3345 (while (and (> (current-indentation) indentation)
3346 (not (bobp))
3347 (not (back-to-indentation))
3348 (forward-line -1)))
3349 (back-to-indentation)
3350 (cond
3351 ((not (equal indentation (current-indentation))) nil)
3352 ((string= closing-word "elif")
3353 (when (member (current-word) '("if" "elif"))
3354 (point-marker)))
3355 ((string= closing-word "else")
3356 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3357 (point-marker)))
3358 ((string= closing-word "except")
3359 (when (member (current-word) '("try"))
3360 (point-marker)))
3361 ((string= closing-word "finally")
3362 (when (member (current-word) '("except" "else"))
3363 (point-marker))))))))
3365 (defun python-info-closing-block-message (&optional closing-block-point)
3366 "Message the contents of the block the current line closes.
3367 With optional argument CLOSING-BLOCK-POINT use that instead of
3368 recalculating it calling `python-info-closing-block'."
3369 (let ((point (or closing-block-point (python-info-closing-block))))
3370 (when point
3371 (save-restriction
3372 (widen)
3373 (message "Closes %s" (save-excursion
3374 (goto-char point)
3375 (back-to-indentation)
3376 (buffer-substring
3377 (point) (line-end-position))))))))
3379 (defun python-info-line-ends-backslash-p (&optional line-number)
3380 "Return non-nil if current line ends with backslash.
3381 With optional argument LINE-NUMBER, check that line instead."
3382 (save-excursion
3383 (save-restriction
3384 (widen)
3385 (when line-number
3386 (python-util-goto-line line-number))
3387 (while (and (not (eobp))
3388 (goto-char (line-end-position))
3389 (python-syntax-context 'paren)
3390 (not (equal (char-before (point)) ?\\)))
3391 (forward-line 1))
3392 (when (equal (char-before) ?\\)
3393 (point-marker)))))
3395 (defun python-info-beginning-of-backslash (&optional line-number)
3396 "Return the point where the backslashed line start.
3397 Optional argument LINE-NUMBER forces the line number to check against."
3398 (save-excursion
3399 (save-restriction
3400 (widen)
3401 (when line-number
3402 (python-util-goto-line line-number))
3403 (when (python-info-line-ends-backslash-p)
3404 (while (save-excursion
3405 (goto-char (line-beginning-position))
3406 (python-syntax-context 'paren))
3407 (forward-line -1))
3408 (back-to-indentation)
3409 (point-marker)))))
3411 (defun python-info-continuation-line-p ()
3412 "Check if current line is continuation of another.
3413 When current line is continuation of another return the point
3414 where the continued line ends."
3415 (save-excursion
3416 (save-restriction
3417 (widen)
3418 (let* ((context-type (progn
3419 (back-to-indentation)
3420 (python-syntax-context-type)))
3421 (line-start (line-number-at-pos))
3422 (context-start (when context-type
3423 (python-syntax-context context-type))))
3424 (cond ((equal context-type 'paren)
3425 ;; Lines inside a paren are always a continuation line
3426 ;; (except the first one).
3427 (python-util-forward-comment -1)
3428 (point-marker))
3429 ((member context-type '(string comment))
3430 ;; move forward an roll again
3431 (goto-char context-start)
3432 (python-util-forward-comment)
3433 (python-info-continuation-line-p))
3435 ;; Not within a paren, string or comment, the only way
3436 ;; we are dealing with a continuation line is that
3437 ;; previous line contains a backslash, and this can
3438 ;; only be the previous line from current
3439 (back-to-indentation)
3440 (python-util-forward-comment -1)
3441 (when (and (equal (1- line-start) (line-number-at-pos))
3442 (python-info-line-ends-backslash-p))
3443 (point-marker))))))))
3445 (defun python-info-block-continuation-line-p ()
3446 "Return non-nil if current line is a continuation of a block."
3447 (save-excursion
3448 (when (python-info-continuation-line-p)
3449 (forward-line -1)
3450 (back-to-indentation)
3451 (when (looking-at (python-rx block-start))
3452 (point-marker)))))
3454 (defun python-info-assignment-continuation-line-p ()
3455 "Check if current line is a continuation of an assignment.
3456 When current line is continuation of another with an assignment
3457 return the point of the first non-blank character after the
3458 operator."
3459 (save-excursion
3460 (when (python-info-continuation-line-p)
3461 (forward-line -1)
3462 (back-to-indentation)
3463 (when (and (not (looking-at (python-rx block-start)))
3464 (and (re-search-forward (python-rx not-simple-operator
3465 assignment-operator
3466 not-simple-operator)
3467 (line-end-position) t)
3468 (not (python-syntax-context-type))))
3469 (skip-syntax-forward "\s")
3470 (point-marker)))))
3472 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3473 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3474 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3475 (save-excursion
3476 (beginning-of-line 1)
3477 (looking-at python-nav-beginning-of-defun-regexp))))
3479 (defun python-info-current-line-comment-p ()
3480 "Check if current line is a comment line."
3481 (char-equal
3482 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
3483 ?#))
3485 (defun python-info-current-line-empty-p ()
3486 "Check if current line is empty, ignoring whitespace."
3487 (save-excursion
3488 (beginning-of-line 1)
3489 (looking-at
3490 (python-rx line-start (* whitespace)
3491 (group (* not-newline))
3492 (* whitespace) line-end))
3493 (string-equal "" (match-string-no-properties 1))))
3496 ;;; Utility functions
3498 (defun python-util-goto-line (line-number)
3499 "Move point to LINE-NUMBER."
3500 (goto-char (point-min))
3501 (forward-line (1- line-number)))
3503 ;; Stolen from org-mode
3504 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3505 "Clone local variables from FROM-BUFFER.
3506 Optional argument REGEXP selects variables to clone and defaults
3507 to \"^python-\"."
3508 (mapc
3509 (lambda (pair)
3510 (and (symbolp (car pair))
3511 (string-match (or regexp "^python-")
3512 (symbol-name (car pair)))
3513 (set (make-local-variable (car pair))
3514 (cdr pair))))
3515 (buffer-local-variables from-buffer)))
3517 (defun python-util-forward-comment (&optional direction)
3518 "Python mode specific version of `forward-comment'.
3519 Optional argument DIRECTION defines the direction to move to."
3520 (let ((comment-start (python-syntax-context 'comment))
3521 (factor (if (< (or direction 0) 0)
3522 -99999
3523 99999)))
3524 (when comment-start
3525 (goto-char comment-start))
3526 (forward-comment factor)))
3528 (defun python-util-popn (lst n)
3529 "Return LST first N elements.
3530 N should be an integer, when it's a natural negative number its
3531 opposite is used. When N is bigger than the length of LST, the
3532 list is returned as is."
3533 (let* ((n (min (abs n)))
3534 (len (length lst))
3535 (acc))
3536 (if (> n len)
3538 (while (< 0 n)
3539 (setq acc (cons (car lst) acc)
3540 lst (cdr lst)
3541 n (1- n)))
3542 (reverse acc))))
3545 ;;;###autoload
3546 (define-derived-mode python-mode prog-mode "Python"
3547 "Major mode for editing Python files.
3549 \\{python-mode-map}
3550 Entry to this mode calls the value of `python-mode-hook'
3551 if that value is non-nil."
3552 (set (make-local-variable 'tab-width) 8)
3553 (set (make-local-variable 'indent-tabs-mode) nil)
3555 (set (make-local-variable 'comment-start) "# ")
3556 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3558 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3559 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3561 (set (make-local-variable 'forward-sexp-function)
3562 'python-nav-forward-sexp)
3564 (set (make-local-variable 'font-lock-defaults)
3565 '(python-font-lock-keywords nil nil nil nil))
3567 (set (make-local-variable 'syntax-propertize-function)
3568 python-syntax-propertize-function)
3570 (set (make-local-variable 'indent-line-function)
3571 #'python-indent-line-function)
3572 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3574 (set (make-local-variable 'paragraph-start) "\\s-*$")
3575 (set (make-local-variable 'fill-paragraph-function)
3576 'python-fill-paragraph)
3578 (set (make-local-variable 'beginning-of-defun-function)
3579 #'python-nav-beginning-of-defun)
3580 (set (make-local-variable 'end-of-defun-function)
3581 #'python-nav-end-of-defun)
3583 (add-hook 'completion-at-point-functions
3584 'python-completion-complete-at-point nil 'local)
3586 (add-hook 'post-self-insert-hook
3587 'python-indent-post-self-insert-function nil 'local)
3589 (set (make-local-variable 'imenu-create-index-function)
3590 #'python-imenu-create-index)
3592 (set (make-local-variable 'add-log-current-defun-function)
3593 #'python-info-current-defun)
3595 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3597 (set (make-local-variable 'skeleton-further-elements)
3598 '((abbrev-mode nil)
3599 (< '(backward-delete-char-untabify (min python-indent-offset
3600 (current-column))))
3601 (^ '(- (1+ (current-indentation))))))
3603 (set (make-local-variable 'eldoc-documentation-function)
3604 #'python-eldoc-function)
3606 (add-to-list 'hs-special-modes-alist
3607 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3608 ,(lambda (arg)
3609 (python-nav-end-of-defun)) nil))
3611 (set (make-local-variable 'mode-require-final-newline) t)
3613 (set (make-local-variable 'outline-regexp)
3614 (python-rx (* space) block-start))
3615 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3616 (set (make-local-variable 'outline-level)
3617 #'(lambda ()
3618 "`outline-level' function for Python mode."
3619 (1+ (/ (current-indentation) python-indent-offset))))
3621 (python-skeleton-add-menu-items)
3623 (make-local-variable 'python-shell-internal-buffer)
3625 (when python-indent-guess-indent-offset
3626 (python-indent-guess-indent-offset)))
3629 (provide 'python)
3631 ;; Local Variables:
3632 ;; coding: utf-8
3633 ;; indent-tabs-mode: nil
3634 ;; End:
3636 ;;; python.el ends here