1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2014 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Maintainer: emacs-devel@gnu.org
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/>.
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,
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows you to execute easily any
66 ;; block of code of your current buffer in an inferior Python process.
68 ;; Shell completion: hitting tab will try to complete the current
69 ;; word. Shell completion is implemented in a manner that if you
70 ;; change the `python-shell-interpreter' to any other (for example
71 ;; IPython) it should be easy to integrate another way to calculate
72 ;; completions. You just need to specify your custom
73 ;; `python-shell-completion-setup-code' and
74 ;; `python-shell-completion-string-code'.
76 ;; Here is a complete example of the settings you would use for
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:
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/
126 ;; (setq python-shell-process-environment
128 ;; (format "PATH=%s" (mapconcat
131 ;; (cons (getenv "PATH")
132 ;; '("/path/to/env/bin/")))
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: skeletons are provided for simple inserting of things like class,
159 ;; def, for, import, if, try, and while. These skeletons are
160 ;; integrated with 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-<foo>'.
166 ;; FFAP: You can find the filename for a given module when using ffap
167 ;; out of the box. This feature needs an inferior python shell
170 ;; Code check: Check the current file for errors with `python-check'
171 ;; using the program defined in `python-check-command'.
173 ;; Eldoc: returns documentation for object at point by using the
174 ;; inferior python subprocess to inspect its documentation. As you
175 ;; might guessed you should run `python-shell-send-buffer' from time
176 ;; to time to get better results too.
178 ;; Imenu: There are two index building functions to be used as
179 ;; `imenu-create-index-function': `python-imenu-create-index' (the
180 ;; default one, builds the alist in form of a tree) and
181 ;; `python-imenu-create-flat-index'. See also
182 ;; `python-imenu-format-item-label-function',
183 ;; `python-imenu-format-parent-item-label-function',
184 ;; `python-imenu-format-parent-item-jump-label-function' variables for
185 ;; changing the way labels are formatted in the tree version.
187 ;; If you used python-mode.el you probably will miss auto-indentation
188 ;; when inserting newlines. To achieve the same behavior you have
191 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
193 ;; 2) Add the following hook in your .emacs:
195 ;; (add-hook 'python-mode-hook
197 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
199 ;; I'd recommend the first one since you'll get the same behavior for
200 ;; all modes out-of-the-box.
204 ;; Add this to your .emacs:
206 ;; (add-to-list 'load-path "/folder/containing/file")
213 (require 'ansi-color)
216 ;; Avoid compiler warnings
217 (defvar view-return-to-alist)
218 (defvar compilation-error-regexp-alist)
219 (defvar outline-heading-end-regexp)
221 (autoload 'comint-mode "comint")
224 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
226 (add-to-list 'interpreter-mode-alist (cons (purecopy "python[0-9.]*") 'python-mode))
229 "Python Language's flying circus support for Emacs."
232 :link '(emacs-commentary-link "python"))
237 (defvar python-mode-map
238 (let ((map (make-sparse-keymap)))
240 (define-key map [remap backward-sentence] 'python-nav-backward-block)
241 (define-key map [remap forward-sentence] 'python-nav-forward-block)
242 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
243 (define-key map "\C-c\C-j" 'imenu)
245 (define-key map "\177" 'python-indent-dedent-line-backspace)
246 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
247 (define-key map "\C-c<" 'python-indent-shift-left)
248 (define-key map "\C-c>" 'python-indent-shift-right)
250 (define-key map "\C-c\C-tc" 'python-skeleton-class)
251 (define-key map "\C-c\C-td" 'python-skeleton-def)
252 (define-key map "\C-c\C-tf" 'python-skeleton-for)
253 (define-key map "\C-c\C-ti" 'python-skeleton-if)
254 (define-key map "\C-c\C-tm" 'python-skeleton-import)
255 (define-key map "\C-c\C-tt" 'python-skeleton-try)
256 (define-key map "\C-c\C-tw" 'python-skeleton-while)
258 (define-key map "\C-c\C-p" 'run-python)
259 (define-key map "\C-c\C-s" 'python-shell-send-string)
260 (define-key map "\C-c\C-r" 'python-shell-send-region)
261 (define-key map "\C-\M-x" 'python-shell-send-defun)
262 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
263 (define-key map "\C-c\C-l" 'python-shell-send-file)
264 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
265 ;; Some util commands
266 (define-key map "\C-c\C-v" 'python-check)
267 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
269 (substitute-key-definition 'complete-symbol 'completion-at-point
271 (easy-menu-define python-menu map "Python Mode menu"
273 :help "Python-specific Features"
274 ["Shift region left" python-indent-shift-left :active mark-active
275 :help "Shift region left by a single indentation step"]
276 ["Shift region right" python-indent-shift-right :active mark-active
277 :help "Shift region right by a single indentation step"]
279 ["Start of def/class" beginning-of-defun
280 :help "Go to start of outermost definition around point"]
281 ["End of def/class" end-of-defun
282 :help "Go to end of definition around point"]
283 ["Mark def/class" mark-defun
284 :help "Mark outermost definition around point"]
285 ["Jump to def/class" imenu
286 :help "Jump to a class or function definition"]
290 ["Start interpreter" run-python
291 :help "Run inferior Python process in a separate buffer"]
292 ["Switch to shell" python-shell-switch-to-shell
293 :help "Switch to running inferior Python process"]
294 ["Eval string" python-shell-send-string
295 :help "Eval string in inferior Python session"]
296 ["Eval buffer" python-shell-send-buffer
297 :help "Eval buffer in inferior Python session"]
298 ["Eval region" python-shell-send-region
299 :help "Eval region in inferior Python session"]
300 ["Eval defun" python-shell-send-defun
301 :help "Eval defun in inferior Python session"]
302 ["Eval file" python-shell-send-file
303 :help "Eval file in inferior Python session"]
304 ["Debugger" pdb :help "Run pdb under GUD"]
306 ["Check file" python-check
307 :help "Check file for errors"]
308 ["Help on symbol" python-eldoc-at-point
309 :help "Get help on symbol at point"]
310 ["Complete symbol" completion-at-point
311 :help "Complete symbol before point"]))
313 "Keymap for `python-mode'.")
316 ;;; Python specialized rx
319 (defconst python-rx-constituents
320 `((block-start . ,(rx symbol-start
321 (or "def" "class" "if" "elif" "else" "try"
322 "except" "finally" "for" "while" "with")
324 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
326 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
327 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
328 (+ space) "==" (+ space)
329 (any ?' ?\") "__main__" (any ?' ?\")
331 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
332 (open-paren . ,(rx (or "{" "[" "(")))
333 (close-paren . ,(rx (or "}" "]" ")")))
334 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
335 ;; FIXME: rx should support (not simple-operator).
336 (not-simple-operator . ,(rx
338 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
339 ;; FIXME: Use regexp-opt.
340 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
341 "=" "%" "**" "//" "<<" ">>" "<=" "!="
342 "==" ">=" "is" "not")))
343 ;; FIXME: Use regexp-opt.
344 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
345 ">>=" "<<=" "&=" "^=" "|=")))
346 (string-delimiter . ,(rx (and
347 ;; Match even number of backslashes.
348 (or (not (any ?\\ ?\' ?\")) point
349 ;; Quotes might be preceded by a escaped quote.
350 (and (or (not (any ?\\)) point) ?\\
351 (* ?\\ ?\\) (any ?\' ?\")))
353 ;; Match single or triple quotes of any kind.
354 (group (or "\"" "\"\"\"" "'" "'''"))))))
355 "Additional Python specific sexps for `python-rx'")
357 (defmacro python-rx (&rest regexps)
358 "Python mode specialized rx macro.
359 This variant of `rx' supports common Python named REGEXPS."
360 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
361 (cond ((null regexps)
364 (rx-to-string `(and ,@regexps) t))
366 (rx-to-string (car regexps) t))))))
369 ;;; Font-lock and syntax
372 (defun python-syntax--context-compiler-macro (form type &optional syntax-ppss)
375 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
376 (and (nth 4 ppss) (nth 8 ppss))))
378 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
379 (and (nth 3 ppss) (nth 8 ppss))))
381 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
384 (defun python-syntax-context (type &optional syntax-ppss)
385 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
386 TYPE can be `comment', `string' or `paren'. It returns the start
387 character address of the specified TYPE."
388 (declare (compiler-macro python-syntax--context-compiler-macro))
389 (let ((ppss (or syntax-ppss (syntax-ppss))))
391 (`comment (and (nth 4 ppss) (nth 8 ppss)))
392 (`string (and (nth 3 ppss) (nth 8 ppss)))
393 (`paren (nth 1 ppss))
396 (defun python-syntax-context-type (&optional syntax-ppss)
397 "Return the context type using SYNTAX-PPSS.
398 The type returned can be `comment', `string' or `paren'."
399 (let ((ppss (or syntax-ppss (syntax-ppss))))
401 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
402 ((nth 1 ppss) 'paren))))
404 (defsubst python-syntax-comment-or-string-p ()
405 "Return non-nil if point is inside 'comment or 'string."
406 (nth 8 (syntax-ppss)))
408 (define-obsolete-function-alias
409 'python-info-ppss-context #'python-syntax-context "24.3")
411 (define-obsolete-function-alias
412 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
414 (define-obsolete-function-alias
415 'python-info-ppss-comment-or-string-p
416 #'python-syntax-comment-or-string-p "24.3")
418 (defvar python-font-lock-keywords
422 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
423 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
424 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
429 ;; False, None, and True are listed as keywords on the Python 3
430 ;; documentation, but since they also qualify as constants they are
431 ;; fontified like that in order to keep font-lock consistent between
438 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
439 (1 font-lock-function-name-face))
441 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
442 (1 font-lock-type-face))
446 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
447 ;; copyright, license, credits, quit and exit are added by the site
448 ;; module and they are not intended to be used in programs
449 "copyright" "credits" "exit" "license" "quit")
450 symbol-end) . font-lock-constant-face)
452 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
453 (0+ "." (1+ (or word ?_)))))
454 (1 font-lock-type-face))
455 ;; Builtin Exceptions
458 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
459 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
460 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
461 "ImportError" "ImportWarning" "IndexError" "KeyError"
462 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
463 "NotImplementedError" "OSError" "OverflowError"
464 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
465 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
466 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
467 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
468 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
469 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
473 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
475 symbol-end) . font-lock-type-face)
479 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
480 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
481 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
482 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
483 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
484 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
485 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
486 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
489 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
490 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
493 "ascii" "bytearray" "bytes" "exec"
495 "__all__" "__doc__" "__name__" "__package__")
496 symbol-end) . font-lock-builtin-face)
498 ;; support for a = b = c = 5
500 (let ((re (python-rx (group (+ (any word ?. ?_)))
501 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
502 assignment-operator))
504 (while (and (setq res (re-search-forward re limit t))
505 (or (python-syntax-context 'paren)
506 (equal (char-after (point-marker)) ?=))))
508 (1 font-lock-variable-name-face nil nil))
509 ;; support for a, b, c = (1, 2, 3)
511 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
512 (* ?, (* space) (+ (any word ?. ?_)) (* space))
513 ?, (* space) (+ (any word ?. ?_)) (* space)
514 assignment-operator))
516 (while (and (setq res (re-search-forward re limit t))
517 (goto-char (match-end 1))
518 (python-syntax-context 'paren)))
520 (1 font-lock-variable-name-face nil nil))))
522 (defconst python-syntax-propertize-function
523 (syntax-propertize-rules
524 ((python-rx string-delimiter)
525 (0 (ignore (python-syntax-stringify))))))
527 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
528 "Count number of quotes around point (max is 3).
529 QUOTE-CHAR is the quote char to count. Optional argument POINT is
530 the point where scan starts (defaults to current point), and LIMIT
531 is used to limit the scan."
534 (or (not limit) (< (+ point i) limit))
535 (eq (char-after (+ point i)) quote-char))
539 (defun python-syntax-stringify ()
540 "Put `syntax-table' property correctly on single/triple quotes."
541 (let* ((num-quotes (length (match-string-no-properties 1)))
543 (backward-char num-quotes)
545 (forward-char num-quotes)))
546 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
547 (quote-starting-pos (- (point) num-quotes))
548 (quote-ending-pos (point))
551 (python-syntax-count-quotes
552 (char-before) string-start quote-starting-pos))))
553 (cond ((and string-start (= num-closing-quotes 0))
554 ;; This set of quotes doesn't match the string starting
558 ;; This set of quotes delimit the start of a string.
559 (put-text-property quote-starting-pos (1+ quote-starting-pos)
560 'syntax-table (string-to-syntax "|")))
561 ((= num-quotes num-closing-quotes)
562 ;; This set of quotes delimit the end of a string.
563 (put-text-property (1- quote-ending-pos) quote-ending-pos
564 'syntax-table (string-to-syntax "|")))
565 ((> num-quotes num-closing-quotes)
566 ;; This may only happen whenever a triple quote is closing
567 ;; a single quoted string. Add string delimiter syntax to
569 (put-text-property quote-starting-pos quote-ending-pos
570 'syntax-table (string-to-syntax "|"))))))
572 (defvar python-mode-syntax-table
573 (let ((table (make-syntax-table)))
574 ;; Give punctuation syntax to ASCII that normally has symbol
575 ;; syntax or has word syntax and isn't a letter.
576 (let ((symbol (string-to-syntax "_"))
577 (sst (standard-syntax-table)))
580 (if (equal symbol (aref sst i))
581 (modify-syntax-entry i "." table)))))
582 (modify-syntax-entry ?$ "." table)
583 (modify-syntax-entry ?% "." table)
585 (modify-syntax-entry ?# "<" table)
586 (modify-syntax-entry ?\n ">" table)
587 (modify-syntax-entry ?' "\"" table)
588 (modify-syntax-entry ?` "$" table)
590 "Syntax table for Python files.")
592 (defvar python-dotty-syntax-table
593 (let ((table (make-syntax-table python-mode-syntax-table)))
594 (modify-syntax-entry ?. "w" table)
595 (modify-syntax-entry ?_ "w" table)
597 "Dotty syntax table for Python files.
598 It makes underscores and dots word constituent chars.")
603 (defcustom python-indent-offset 4
604 "Default indentation offset for Python."
609 (defcustom python-indent-guess-indent-offset t
610 "Non-nil tells Python mode to guess `python-indent-offset' value."
615 (defcustom python-indent-trigger-commands
616 '(indent-for-tab-command yas-expand yas/expand)
617 "Commands that might trigger a `python-indent-line' call."
618 :type '(repeat symbol)
621 (define-obsolete-variable-alias
622 'python-indent 'python-indent-offset "24.3")
624 (define-obsolete-variable-alias
625 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
627 (defvar python-indent-current-level 0
628 "Current indentation level `python-indent-line-function' is using.")
630 (defvar python-indent-levels '(0)
631 "Levels of indentation available for `python-indent-line-function'.")
633 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
634 "List of words that should be dedented.
635 These make `python-indent-calculate-indentation' subtract the value of
636 `python-indent-offset'.")
638 (defvar python-indent-block-enders
639 '("break" "continue" "pass" "raise" "return")
640 "List of words that mark the end of a block.
641 These make `python-indent-calculate-indentation' subtract the
642 value of `python-indent-offset' when `python-indent-context' is
645 (defun python-indent-guess-indent-offset ()
646 "Guess and set `python-indent-offset' for the current buffer."
651 (goto-char (point-min))
653 (while (and (not block-end)
655 (python-rx line-start block-start) nil t))
657 (not (python-syntax-context-type))
659 (goto-char (line-end-position))
660 (python-util-forward-comment -1)
661 (if (equal (char-before) ?:)
664 (when (python-info-block-continuation-line-p)
665 (while (and (python-info-continuation-line-p)
668 (python-util-forward-comment -1)
669 (when (equal (char-before) ?:)
671 (setq block-end (point-marker))))
674 (goto-char block-end)
675 (python-util-forward-comment)
676 (current-indentation))))
677 (if (and indentation (not (zerop indentation)))
678 (set (make-local-variable 'python-indent-offset) indentation)
679 (message "Can't guess python-indent-offset, using defaults: %s"
680 python-indent-offset)))))))
682 (defun python-indent-context ()
683 "Get information on indentation context.
684 Context information is returned with a cons with the form:
687 Where status can be any of the following symbols:
689 * after-comment: When current line might continue a comment block
690 * inside-paren: If point in between (), {} or []
691 * inside-string: If point is inside a string
692 * after-backslash: Previous line ends in a backslash
693 * after-beginning-of-block: Point is after beginning of block
694 * after-line: Point is after normal line
695 * no-indent: Point is at beginning of buffer or other special case
696 START is the buffer position where the sexp starts."
699 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
703 ;; Beginning of buffer
705 (goto-char (line-beginning-position))
708 ;; Comment continuation
712 (python-info-current-line-comment-p)
713 (python-info-current-line-empty-p))
716 (python-info-current-line-comment-p)))
720 ((setq start (python-syntax-context 'string ppss))
723 ((setq start (python-syntax-context 'paren ppss))
726 ((setq start (when (not (or (python-syntax-context 'string ppss)
727 (python-syntax-context 'comment ppss)))
728 (let ((line-beg-pos (line-number-at-pos)))
729 (python-info-line-ends-backslash-p
730 (1- line-beg-pos)))))
732 ;; After beginning of block
733 ((setq start (save-excursion
735 (back-to-indentation)
736 (python-util-forward-comment -1)
737 (equal (char-before) ?:))
738 ;; Move to the first block start that's not in within
739 ;; a string, comment or paren and that's not a
740 ;; continuation line.
741 (while (and (re-search-backward
742 (python-rx block-start) nil t)
744 (python-syntax-context-type)
745 (python-info-continuation-line-p))))
746 (when (looking-at (python-rx block-start))
748 'after-beginning-of-block)
750 ((setq start (save-excursion
751 (back-to-indentation)
752 (skip-chars-backward (rx (or whitespace ?\n)))
753 (python-nav-beginning-of-statement)
760 (defun python-indent-calculate-indentation ()
761 "Calculate correct indentation offset for the current line."
762 (let* ((indentation-context (python-indent-context))
763 (context-status (car indentation-context))
764 (context-start (cdr indentation-context)))
768 (pcase context-status
771 (goto-char context-start)
772 (current-indentation))
773 ;; When point is after beginning of block just add one level
774 ;; of indentation relative to the context-start
775 (`after-beginning-of-block
776 (goto-char context-start)
777 (+ (current-indentation) python-indent-offset))
778 ;; When after a simple line just use previous line
779 ;; indentation, in the case current line starts with a
780 ;; `python-indent-dedenters' de-indent one level.
782 (let* ((pair (save-excursion
783 (goto-char context-start)
785 (current-indentation)
786 (python-info-beginning-of-block-p))))
787 (context-indentation (car pair))
788 (after-block-start-p (cdr pair))
790 (if (or (save-excursion
791 (back-to-indentation)
793 ;; De-indent only when dedenters are not
794 ;; next to a block start. This allows
795 ;; one-liner constructs such as:
796 ;; if condition: print "yay"
798 (not after-block-start-p)
799 (looking-at (regexp-opt python-indent-dedenters))))
801 (python-util-forward-comment -1)
802 (python-nav-beginning-of-statement)
803 (looking-at (regexp-opt python-indent-block-enders))))
806 (- context-indentation adjustment)))
807 ;; When inside of a string, do nothing. just use the current
808 ;; indentation. XXX: perhaps it would be a good idea to
809 ;; invoke standard text indentation here
811 (goto-char context-start)
812 (current-indentation))
813 ;; After backslash we have several possibilities.
816 ;; Check if current line is a dot continuation. For this
817 ;; the current line must start with a dot and previous
818 ;; line must contain a dot too.
820 (back-to-indentation)
821 (when (looking-at "\\.")
822 ;; If after moving one line back point is inside a paren it
823 ;; needs to move back until it's not anymore
827 (python-syntax-context 'paren))))
828 (goto-char (line-end-position))
829 (while (and (re-search-backward
830 "\\." (line-beginning-position) t)
831 (python-syntax-context-type)))
832 (if (and (looking-at "\\.")
833 (not (python-syntax-context-type)))
834 ;; The indentation is the same column of the
835 ;; first matching dot that's not inside a
836 ;; comment, a string or a paren
838 ;; No dot found on previous line, just add another
839 ;; indentation level.
840 (+ (current-indentation) python-indent-offset)))))
841 ;; Check if prev line is a block continuation
842 ((let ((block-continuation-start
843 (python-info-block-continuation-line-p)))
844 (when block-continuation-start
845 ;; If block-continuation-start is set jump to that
846 ;; marker and use first column after the block start
847 ;; as indentation value.
848 (goto-char block-continuation-start)
850 (python-rx block-start (* space))
851 (line-end-position) t)
853 ;; Check if current line is an assignment continuation
854 ((let ((assignment-continuation-start
855 (python-info-assignment-continuation-line-p)))
856 (when assignment-continuation-start
857 ;; If assignment-continuation is set jump to that
858 ;; marker and use first column after the assignment
859 ;; operator as indentation value.
860 (goto-char assignment-continuation-start)
864 (goto-char (python-info-beginning-of-backslash))
869 (or (python-info-beginning-of-backslash) (point)))
870 (python-info-line-ends-backslash-p)))
871 ;; The two previous lines ended in a backslash so we must
872 ;; respect previous line indentation.
873 (current-indentation)
874 ;; What happens here is that we are dealing with the second
875 ;; line of a backslash continuation, in that case we just going
876 ;; to add one indentation level.
877 (+ (current-indentation) python-indent-offset)))))
878 ;; When inside a paren there's a need to handle nesting
882 ;; If current line closes the outermost open paren use the
883 ;; current indentation of the context-start line.
885 (skip-syntax-forward "\s" (line-end-position))
886 (when (and (looking-at (regexp-opt '(")" "]" "}")))
889 (not (python-syntax-context 'paren))))
890 (goto-char context-start)
891 (current-indentation))))
892 ;; If open paren is contained on a line by itself add another
893 ;; indentation level, else look for the first word after the
894 ;; opening paren and use it's column position as indentation
896 ((let* ((content-starts-in-newline)
899 (if (setq content-starts-in-newline
901 (goto-char context-start)
905 (line-beginning-position)
907 (python-util-forward-comment))
909 (+ (current-indentation) python-indent-offset)
913 ;; If current line closes a nested open paren de-indent one
916 (back-to-indentation)
917 (looking-at (regexp-opt '(")" "]" "}"))))
918 (- indent python-indent-offset))
919 ;; If the line of the opening paren that wraps the current
920 ;; line starts a block add another level of indentation to
921 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
923 (when (and content-starts-in-newline
925 (goto-char context-start)
926 (back-to-indentation)
927 (looking-at (python-rx block-start))))
928 (+ indent python-indent-offset))))
931 (defun python-indent-calculate-levels ()
932 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
933 (let* ((indentation (python-indent-calculate-indentation))
934 (remainder (% indentation python-indent-offset))
935 (steps (/ (- indentation remainder) python-indent-offset)))
936 (setq python-indent-levels (list 0))
937 (dotimes (step steps)
938 (push (* python-indent-offset (1+ step)) python-indent-levels))
939 (when (not (eq 0 remainder))
940 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
941 (setq python-indent-levels (nreverse python-indent-levels))
942 (setq python-indent-current-level (1- (length python-indent-levels)))))
944 (defun python-indent-toggle-levels ()
945 "Toggle `python-indent-current-level' over `python-indent-levels'."
946 (setq python-indent-current-level (1- python-indent-current-level))
947 (when (< python-indent-current-level 0)
948 (setq python-indent-current-level (1- (length python-indent-levels)))))
950 (defun python-indent-line (&optional force-toggle)
951 "Internal implementation of `python-indent-line-function'.
952 Uses the offset calculated in
953 `python-indent-calculate-indentation' and available levels
954 indicated by the variable `python-indent-levels' to set the
957 When the variable `last-command' is equal to one of the symbols
958 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
959 non-nil it cycles levels indicated in the variable
960 `python-indent-levels' by setting the current level in the
961 variable `python-indent-current-level'.
963 When the variable `last-command' is not equal to one of the
964 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
965 is nil it calculates possible indentation levels and saves them
966 in the variable `python-indent-levels'. Afterwards it sets the
967 variable `python-indent-current-level' correctly so offset is
969 (nth python-indent-current-level python-indent-levels)"
971 (and (or (and (memq this-command python-indent-trigger-commands)
972 (eq last-command this-command))
974 (not (equal python-indent-levels '(0)))
975 (or (python-indent-toggle-levels) t))
976 (python-indent-calculate-levels))
977 (let* ((starting-pos (point-marker))
978 (indent-ending-position
979 (+ (line-beginning-position) (current-indentation)))
980 (follow-indentation-p
982 (and (<= (line-beginning-position) starting-pos)
983 (>= indent-ending-position starting-pos))))
984 (next-indent (nth python-indent-current-level python-indent-levels)))
985 (unless (= next-indent (current-indentation))
987 (delete-horizontal-space)
988 (indent-to next-indent)
989 (goto-char starting-pos))
990 (and follow-indentation-p (back-to-indentation)))
991 (python-info-closing-block-message))
993 (defun python-indent-line-function ()
994 "`indent-line-function' for Python mode.
995 See `python-indent-line' for details."
996 (python-indent-line))
998 (defun python-indent-dedent-line ()
999 "De-indent current line."
1001 (when (and (not (python-syntax-comment-or-string-p))
1002 (<= (point-marker) (save-excursion
1003 (back-to-indentation)
1005 (> (current-column) 0))
1006 (python-indent-line t)
1009 (defun python-indent-dedent-line-backspace (arg)
1010 "De-indent current line.
1011 Argument ARG is passed to `backward-delete-char-untabify' when
1012 point is not in between the indentation."
1014 (when (not (python-indent-dedent-line))
1015 (backward-delete-char-untabify arg)))
1016 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
1018 (defun python-indent-region (start end)
1019 "Indent a Python region automagically.
1021 Called from a program, START and END specify the region to indent."
1022 (let ((deactivate-mark nil))
1025 (setq end (point-marker))
1027 (or (bolp) (forward-line 1))
1028 (while (< (point) end)
1029 (or (and (bolp) (eolp))
1032 (back-to-indentation)
1033 (setq word (current-word))
1036 ;; Don't mess with strings, unless it's the
1037 ;; enclosing set of quotes.
1038 (or (not (python-syntax-context 'string))
1042 (current-indentation)
1043 (python-syntax-count-quotes (char-after) (point))))
1044 (string-to-syntax "|"))))
1046 (delete-horizontal-space)
1047 (indent-to (python-indent-calculate-indentation)))))
1049 (move-marker end nil))))
1051 (defun python-indent-shift-left (start end &optional count)
1052 "Shift lines contained in region START END by COUNT columns to the left.
1053 COUNT defaults to `python-indent-offset'. If region isn't
1054 active, the current line is shifted. The shifted region includes
1055 the lines in which START and END lie. An error is signaled if
1056 any lines in the region are indented less than COUNT columns."
1059 (list (region-beginning) (region-end) current-prefix-arg)
1060 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1062 (setq count (prefix-numeric-value count))
1063 (setq count python-indent-offset))
1065 (let ((deactivate-mark nil))
1068 (while (< (point) end)
1069 (if (and (< (current-indentation) count)
1070 (not (looking-at "[ \t]*$")))
1071 (error "Can't shift all lines enough"))
1073 (indent-rigidly start end (- count))))))
1075 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1077 (defun python-indent-shift-right (start end &optional count)
1078 "Shift lines contained in region START END by COUNT columns to the right.
1079 COUNT defaults to `python-indent-offset'. If region isn't
1080 active, the current line is shifted. The shifted region includes
1081 the lines in which START and END lie."
1084 (list (region-beginning) (region-end) current-prefix-arg)
1085 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1086 (let ((deactivate-mark nil))
1087 (setq count (if count (prefix-numeric-value count)
1088 python-indent-offset))
1089 (indent-rigidly start end count)))
1091 (defun python-indent-post-self-insert-function ()
1092 "Adjust indentation after insertion of some characters.
1093 This function is intended to be added to `post-self-insert-hook.'
1094 If a line renders a paren alone, after adding a char before it,
1095 the line will be re-indented automatically if needed."
1096 (when (and electric-indent-mode
1097 (eq (char-before) last-command-event))
1100 (memq (char-after) '(?\) ?\] ?\})))
1102 (goto-char (line-beginning-position))
1103 ;; If after going to the beginning of line the point
1104 ;; is still inside a paren it's ok to do the trick
1105 (when (python-syntax-context 'paren)
1106 (let ((indentation (python-indent-calculate-indentation)))
1107 (when (< (current-indentation) indentation)
1108 (indent-line-to indentation))))))
1109 ((and (eq ?: last-command-event)
1110 (memq ?: electric-indent-chars)
1111 (not current-prefix-arg)
1113 (not (equal ?: (char-before (1- (point)))))
1114 (not (python-syntax-comment-or-string-p)))
1115 (let ((indentation (current-indentation))
1116 (calculated-indentation (python-indent-calculate-indentation)))
1117 (python-info-closing-block-message)
1118 (when (> indentation calculated-indentation)
1120 (indent-line-to calculated-indentation)
1121 (when (not (python-info-closing-block-message))
1122 (indent-line-to indentation)))))))))
1127 (defvar python-nav-beginning-of-defun-regexp
1128 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1129 "Regexp matching class or function definition.
1130 The name of the defun should be grouped so it can be retrieved
1131 via `match-string'.")
1133 (defun python-nav--beginning-of-defun (&optional arg)
1134 "Internal implementation of `python-nav-beginning-of-defun'.
1135 With positive ARG search backwards, else search forwards."
1136 (when (or (null arg) (= arg 0)) (setq arg 1))
1137 (let* ((re-search-fn (if (> arg 0)
1138 #'re-search-backward
1139 #'re-search-forward))
1140 (line-beg-pos (line-beginning-position))
1141 (line-content-start (+ line-beg-pos (current-indentation)))
1142 (pos (point-marker))
1147 (not (python-info-looking-at-beginning-of-defun))
1148 (python-nav-backward-block)))
1149 (or (and (python-info-looking-at-beginning-of-defun)
1150 (+ (current-indentation) python-indent-offset))
1154 (when (and (< arg 0)
1155 (python-info-looking-at-beginning-of-defun))
1157 (while (and (funcall re-search-fn
1158 python-nav-beginning-of-defun-regexp nil t)
1159 (or (python-syntax-context-type)
1160 ;; Handle nested defuns when moving
1161 ;; backwards by checking indentation.
1163 (not (= (current-indentation) 0))
1164 (>= (current-indentation) beg-indentation)))))
1165 (and (python-info-looking-at-beginning-of-defun)
1166 (or (not (= (line-number-at-pos pos)
1167 (line-number-at-pos)))
1168 (and (>= (point) line-beg-pos)
1169 (<= (point) line-content-start)
1170 (> pos line-content-start)))))))
1172 (or (beginning-of-line 1) t)
1173 (and (goto-char pos) nil))))
1175 (defun python-nav-beginning-of-defun (&optional arg)
1176 "Move point to `beginning-of-defun'.
1177 With positive ARG search backwards else search forward.
1178 ARG nil or 0 defaults to 1. When searching backwards,
1179 nested defuns are handled with care depending on current
1180 point position. Return non-nil if point is moved to
1181 `beginning-of-defun'."
1182 (when (or (null arg) (= arg 0)) (setq arg 1))
1184 (while (and (not (= arg 0))
1185 (let ((keep-searching-p
1186 (python-nav--beginning-of-defun arg)))
1187 (when (and keep-searching-p (null found))
1190 (setq arg (if (> arg 0) (1- arg) (1+ arg))))
1193 (defun python-nav-end-of-defun ()
1194 "Move point to the end of def or class.
1195 Returns nil if point is not in a def or class."
1197 (let ((beg-defun-indent)
1199 (when (or (python-info-looking-at-beginning-of-defun)
1200 (python-nav-beginning-of-defun 1)
1201 (python-nav-beginning-of-defun -1))
1202 (setq beg-defun-indent (current-indentation))
1204 (python-nav-end-of-statement)
1205 (python-util-forward-comment 1)
1206 (and (> (current-indentation) beg-defun-indent)
1208 (python-util-forward-comment -1)
1210 ;; Ensure point moves forward.
1211 (and (> beg-pos (point)) (goto-char beg-pos)))))
1213 (defun python-nav--syntactically (fn poscompfn &optional contextfn)
1214 "Move point using FN avoiding places with specific context.
1215 FN must take no arguments. POSCOMPFN is a two arguments function
1216 used to compare current and previous point after it is moved
1217 using FN, this is normally a less-than or greater-than
1218 comparison. Optional argument CONTEXTFN defaults to
1219 `python-syntax-context-type' and is used for checking current
1220 point context, it must return a non-nil value if this point must
1222 (let ((contextfn (or contextfn 'python-syntax-context-type))
1223 (start-pos (point-marker))
1228 (and (funcall fn) (point-marker)))
1229 (context (funcall contextfn)))
1230 (cond ((and (not context) newpos
1231 (or (and (not prev-pos) newpos)
1232 (and prev-pos newpos
1233 (funcall poscompfn newpos prev-pos))))
1234 (throw 'found (point-marker)))
1235 ((and newpos context)
1236 (setq prev-pos (point)))
1237 (t (when (not newpos) (goto-char start-pos))
1238 (throw 'found nil))))))))
1240 (defun python-nav--forward-defun (arg)
1241 "Internal implementation of python-nav-{backward,forward}-defun.
1242 Uses ARG to define which function to call, and how many times
1245 (while (and (> arg 0)
1247 (python-nav--syntactically
1250 python-nav-beginning-of-defun-regexp nil t))
1252 (setq arg (1- arg)))
1253 (while (and (< arg 0)
1255 (python-nav--syntactically
1258 python-nav-beginning-of-defun-regexp nil t))
1260 (setq arg (1+ arg)))
1263 (defun python-nav-backward-defun (&optional arg)
1264 "Navigate to closer defun backward ARG times.
1265 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1266 nested definitions."
1268 (python-nav--forward-defun (- (or arg 1))))
1270 (defun python-nav-forward-defun (&optional arg)
1271 "Navigate to closer defun forward ARG times.
1272 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1273 nested definitions."
1275 (python-nav--forward-defun (or arg 1)))
1277 (defun python-nav-beginning-of-statement ()
1278 "Move to start of current statement."
1280 (back-to-indentation)
1281 (let* ((ppss (syntax-ppss))
1284 (python-syntax-context 'paren ppss)
1285 (python-syntax-context 'string ppss))))
1288 (goto-char context-point)
1289 (python-nav-beginning-of-statement))
1292 (python-info-line-ends-backslash-p))
1294 (python-nav-beginning-of-statement))))
1297 (defun python-nav-end-of-statement (&optional noend)
1298 "Move to end of current statement.
1299 Optional argument NOEND is internal and makes the logic to not
1300 jump to the end of line when moving forward searching for the end
1303 (let (string-start bs-pos)
1304 (while (and (or noend (goto-char (line-end-position)))
1306 (cond ((setq string-start (python-syntax-context 'string))
1307 (goto-char string-start)
1308 (if (python-syntax-context 'paren)
1309 ;; Ended up inside a paren, roll again.
1310 (python-nav-end-of-statement t)
1311 ;; This is not inside a paren, move to the
1312 ;; end of this string.
1313 (goto-char (+ (point)
1314 (python-syntax-count-quotes
1315 (char-after (point)) (point))))
1316 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1317 (goto-char (point-max)))))
1318 ((python-syntax-context 'paren)
1319 ;; The statement won't end before we've escaped
1320 ;; at least one level of parenthesis.
1322 (goto-char (scan-lists (point) 1 -1))
1323 (scan-error (goto-char (nth 3 err)))))
1324 ((setq bs-pos (python-info-line-ends-backslash-p))
1326 (forward-line 1))))))
1329 (defun python-nav-backward-statement (&optional arg)
1330 "Move backward to previous statement.
1331 With ARG, repeat. See `python-nav-forward-statement'."
1333 (or arg (setq arg 1))
1334 (python-nav-forward-statement (- arg)))
1336 (defun python-nav-forward-statement (&optional arg)
1337 "Move forward to next statement.
1338 With ARG, repeat. With negative argument, move ARG times
1339 backward to previous statement."
1341 (or arg (setq arg 1))
1343 (python-nav-end-of-statement)
1344 (python-util-forward-comment)
1345 (python-nav-beginning-of-statement)
1346 (setq arg (1- arg)))
1348 (python-nav-beginning-of-statement)
1349 (python-util-forward-comment -1)
1350 (python-nav-beginning-of-statement)
1351 (setq arg (1+ arg))))
1353 (defun python-nav-beginning-of-block ()
1354 "Move to start of current block."
1356 (let ((starting-pos (point)))
1358 (python-nav-beginning-of-statement)
1359 (looking-at (python-rx block-start)))
1361 ;; Go to first line beginning a statement
1362 (while (and (not (bobp))
1363 (or (and (python-nav-beginning-of-statement) nil)
1364 (python-info-current-line-comment-p)
1365 (python-info-current-line-empty-p)))
1367 (let ((block-matching-indent
1368 (- (current-indentation) python-indent-offset)))
1370 (and (python-nav-backward-block)
1371 (> (current-indentation) block-matching-indent)))
1372 (if (and (looking-at (python-rx block-start))
1373 (= (current-indentation) block-matching-indent))
1375 (and (goto-char starting-pos) nil))))))
1377 (defun python-nav-end-of-block ()
1378 "Move to end of current block."
1380 (when (python-nav-beginning-of-block)
1381 (let ((block-indentation (current-indentation)))
1382 (python-nav-end-of-statement)
1383 (while (and (forward-line 1)
1385 (or (and (> (current-indentation) block-indentation)
1386 (or (python-nav-end-of-statement) t))
1387 (python-info-current-line-comment-p)
1388 (python-info-current-line-empty-p))))
1389 (python-util-forward-comment -1)
1392 (defun python-nav-backward-block (&optional arg)
1393 "Move backward to previous block of code.
1394 With ARG, repeat. See `python-nav-forward-block'."
1396 (or arg (setq arg 1))
1397 (python-nav-forward-block (- arg)))
1399 (defun python-nav-forward-block (&optional arg)
1400 "Move forward to next block of code.
1401 With ARG, repeat. With negative argument, move ARG times
1402 backward to previous block."
1404 (or arg (setq arg 1))
1405 (let ((block-start-regexp
1406 (python-rx line-start (* whitespace) block-start))
1407 (starting-pos (point)))
1409 (python-nav-end-of-statement)
1411 (re-search-forward block-start-regexp nil t)
1412 (python-syntax-context-type)))
1413 (setq arg (1- arg)))
1415 (python-nav-beginning-of-statement)
1417 (re-search-backward block-start-regexp nil t)
1418 (python-syntax-context-type)))
1419 (setq arg (1+ arg)))
1420 (python-nav-beginning-of-statement)
1421 (if (not (looking-at (python-rx block-start)))
1422 (and (goto-char starting-pos) nil)
1423 (and (not (= (point) starting-pos)) (point-marker)))))
1425 (defun python-nav--lisp-forward-sexp (&optional arg)
1426 "Standard version `forward-sexp'.
1427 It ignores completely the value of `forward-sexp-function' by
1428 setting it to nil before calling `forward-sexp'. With positive
1429 ARG move forward only one sexp, else move backwards."
1430 (let ((forward-sexp-function)
1431 (arg (if (or (not arg) (> arg 0)) 1 -1)))
1432 (forward-sexp arg)))
1434 (defun python-nav--lisp-forward-sexp-safe (&optional arg)
1435 "Safe version of standard `forward-sexp'.
1436 When at end of sexp (i.e. looking at a opening/closing paren)
1437 skips it instead of throwing an error. With positive ARG move
1438 forward only one sexp, else move backwards."
1439 (let* ((arg (if (or (not arg) (> arg 0)) 1 -1))
1441 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1443 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1445 (python-nav--lisp-forward-sexp arg)
1447 (while (and (funcall search-fn paren-regexp nil t)
1448 (python-syntax-context 'paren)))))))
1450 (defun python-nav--forward-sexp (&optional dir safe)
1451 "Move to forward sexp.
1452 With positive optional argument DIR direction move forward, else
1453 backwards. When optional argument SAFE is non-nil do not throw
1454 errors when at end of sexp, skip it instead."
1455 (setq dir (or dir 1))
1457 (let* ((forward-p (if (> dir 0)
1458 (and (setq dir 1) t)
1459 (and (setq dir -1) nil)))
1460 (context-type (python-syntax-context-type)))
1462 ((memq context-type '(string comment))
1463 ;; Inside of a string, get out of it.
1464 (let ((forward-sexp-function))
1465 (forward-sexp dir)))
1466 ((or (eq context-type 'paren)
1467 (and forward-p (looking-at (python-rx open-paren)))
1468 (and (not forward-p)
1469 (eq (syntax-class (syntax-after (1- (point))))
1470 (car (string-to-syntax ")")))))
1471 ;; Inside a paren or looking at it, lisp knows what to do.
1473 (python-nav--lisp-forward-sexp-safe dir)
1474 (python-nav--lisp-forward-sexp dir)))
1476 ;; This part handles the lispy feel of
1477 ;; `python-nav-forward-sexp'. Knowing everything about the
1478 ;; current context and the context of the next sexp tries to
1479 ;; follow the lisp sexp motion commands in a symmetric manner.
1482 ((python-info-beginning-of-block-p) 'block-start)
1483 ((python-info-end-of-block-p) 'block-end)
1484 ((python-info-beginning-of-statement-p) 'statement-start)
1485 ((python-info-end-of-statement-p) 'statement-end)))
1489 (python-nav--lisp-forward-sexp-safe dir)
1490 (python-nav--lisp-forward-sexp dir))
1494 (goto-char next-sexp-pos)
1496 ((python-info-beginning-of-block-p) 'block-start)
1497 ((python-info-end-of-block-p) 'block-end)
1498 ((python-info-beginning-of-statement-p) 'statement-start)
1499 ((python-info-end-of-statement-p) 'statement-end)
1500 ((python-info-statement-starts-block-p) 'starts-block)
1501 ((python-info-statement-ends-block-p) 'ends-block)))))
1503 (cond ((and (not (eobp))
1504 (python-info-current-line-empty-p))
1505 (python-util-forward-comment dir)
1506 (python-nav--forward-sexp dir))
1507 ((eq context 'block-start)
1508 (python-nav-end-of-block))
1509 ((eq context 'statement-start)
1510 (python-nav-end-of-statement))
1511 ((and (memq context '(statement-end block-end))
1512 (eq next-sexp-context 'ends-block))
1513 (goto-char next-sexp-pos)
1514 (python-nav-end-of-block))
1515 ((and (memq context '(statement-end block-end))
1516 (eq next-sexp-context 'starts-block))
1517 (goto-char next-sexp-pos)
1518 (python-nav-end-of-block))
1519 ((memq context '(statement-end block-end))
1520 (goto-char next-sexp-pos)
1521 (python-nav-end-of-statement))
1522 (t (goto-char next-sexp-pos)))
1523 (cond ((and (not (bobp))
1524 (python-info-current-line-empty-p))
1525 (python-util-forward-comment dir)
1526 (python-nav--forward-sexp dir))
1527 ((eq context 'block-end)
1528 (python-nav-beginning-of-block))
1529 ((eq context 'statement-end)
1530 (python-nav-beginning-of-statement))
1531 ((and (memq context '(statement-start block-start))
1532 (eq next-sexp-context 'starts-block))
1533 (goto-char next-sexp-pos)
1534 (python-nav-beginning-of-block))
1535 ((and (memq context '(statement-start block-start))
1536 (eq next-sexp-context 'ends-block))
1537 (goto-char next-sexp-pos)
1538 (python-nav-beginning-of-block))
1539 ((memq context '(statement-start block-start))
1540 (goto-char next-sexp-pos)
1541 (python-nav-beginning-of-statement))
1542 (t (goto-char next-sexp-pos))))))))))
1544 (defun python-nav-forward-sexp (&optional arg)
1545 "Move forward across expressions.
1546 With ARG, do it that many times. Negative arg -N means move
1549 (or arg (setq arg 1))
1551 (python-nav--forward-sexp 1)
1552 (setq arg (1- arg)))
1554 (python-nav--forward-sexp -1)
1555 (setq arg (1+ arg))))
1557 (defun python-nav-backward-sexp (&optional arg)
1558 "Move backward across expressions.
1559 With ARG, do it that many times. Negative arg -N means move
1562 (or arg (setq arg 1))
1563 (python-nav-forward-sexp (- arg)))
1565 (defun python-nav-forward-sexp-safe (&optional arg)
1566 "Move forward safely across expressions.
1567 With ARG, do it that many times. Negative arg -N means move
1570 (or arg (setq arg 1))
1572 (python-nav--forward-sexp 1 t)
1573 (setq arg (1- arg)))
1575 (python-nav--forward-sexp -1 t)
1576 (setq arg (1+ arg))))
1578 (defun python-nav-backward-sexp-safe (&optional arg)
1579 "Move backward safely across expressions.
1580 With ARG, do it that many times. Negative arg -N means move
1583 (or arg (setq arg 1))
1584 (python-nav-forward-sexp-safe (- arg)))
1586 (defun python-nav--up-list (&optional dir)
1587 "Internal implementation of `python-nav-up-list'.
1588 DIR is always 1 or -1 and comes sanitized from
1589 `python-nav-up-list' calls."
1590 (let ((context (python-syntax-context-type))
1591 (forward-p (> dir 0)))
1593 ((memq context '(string comment)))
1594 ((eq context 'paren)
1595 (let ((forward-sexp-function))
1597 ((and forward-p (python-info-end-of-block-p))
1598 (let ((parent-end-pos
1600 (let ((indentation (and
1601 (python-nav-beginning-of-block)
1602 (current-indentation))))
1603 (while (and indentation
1605 (>= (current-indentation) indentation)
1606 (python-nav-backward-block)))
1607 (python-nav-end-of-block)))))
1608 (and (> (or parent-end-pos (point)) (point))
1609 (goto-char parent-end-pos))))
1610 (forward-p (python-nav-end-of-block))
1611 ((and (not forward-p)
1612 (> (current-indentation) 0)
1613 (python-info-beginning-of-block-p))
1614 (let ((prev-block-pos
1616 (let ((indentation (current-indentation)))
1617 (while (and (python-nav-backward-block)
1618 (>= (current-indentation) indentation))))
1620 (and (> (point) prev-block-pos)
1621 (goto-char prev-block-pos))))
1622 ((not forward-p) (python-nav-beginning-of-block)))))
1624 (defun python-nav-up-list (&optional arg)
1625 "Move forward out of one level of parentheses (or blocks).
1626 With ARG, do this that many times.
1627 A negative argument means move backward but still to a less deep spot.
1628 This command assumes point is not in a string or comment."
1630 (or arg (setq arg 1))
1632 (python-nav--up-list 1)
1633 (setq arg (1- arg)))
1635 (python-nav--up-list -1)
1636 (setq arg (1+ arg))))
1638 (defun python-nav-backward-up-list (&optional arg)
1639 "Move backward out of one level of parentheses (or blocks).
1640 With ARG, do this that many times.
1641 A negative argument means move forward but still to a less deep spot.
1642 This command assumes point is not in a string or comment."
1644 (or arg (setq arg 1))
1645 (python-nav-up-list (- arg)))
1647 (defun python-nav-if-name-main ()
1648 "Move point at the beginning the __main__ block.
1649 When \"if __name__ == '__main__':\" is found returns its
1650 position, else returns nil."
1652 (let ((point (point))
1653 (found (catch 'found
1654 (goto-char (point-min))
1655 (while (re-search-forward
1656 (python-rx line-start
1658 "__name__" (+ space)
1660 (group-n 1 (or ?\" ?\'))
1661 "__main__" (backref 1) (* space) ":")
1663 (when (not (python-syntax-context-type))
1665 (throw 'found t))))))
1668 (ignore (goto-char point)))))
1671 ;;; Shell integration
1673 (defcustom python-shell-buffer-name "Python"
1674 "Default buffer name for Python interpreter."
1679 (defcustom python-shell-interpreter "python"
1680 "Default Python interpreter for shell."
1684 (defcustom python-shell-internal-buffer-name "Python Internal"
1685 "Default buffer name for the Internal Python interpreter."
1690 (defcustom python-shell-interpreter-args "-i"
1691 "Default arguments for the Python interpreter."
1695 (defcustom python-shell-prompt-regexp ">>> "
1696 "Regular expression matching top-level input prompt of Python shell.
1697 It should not contain a caret (^) at the beginning."
1702 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1703 "Regular expression matching block input prompt of Python shell.
1704 It should not contain a caret (^) at the beginning."
1709 (defcustom python-shell-prompt-output-regexp ""
1710 "Regular expression matching output prompt of Python shell.
1711 It should not contain a caret (^) at the beginning."
1716 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1717 "Regular expression matching pdb input prompt of Python shell.
1718 It should not contain a caret (^) at the beginning."
1723 (defcustom python-shell-enable-font-lock t
1724 "Should syntax highlighting be enabled in the Python shell buffer?
1725 Restart the Python shell after changing this variable for it to take effect."
1730 (defcustom python-shell-process-environment nil
1731 "List of environment variables for Python shell.
1732 This variable follows the same rules as `process-environment'
1733 since it merges with it before the process creation routines are
1734 called. When this variable is nil, the Python shell is run with
1735 the default `process-environment'."
1736 :type '(repeat string)
1740 (defcustom python-shell-extra-pythonpaths nil
1741 "List of extra pythonpaths for Python shell.
1742 The values of this variable are added to the existing value of
1743 PYTHONPATH in the `process-environment' variable."
1744 :type '(repeat string)
1748 (defcustom python-shell-exec-path nil
1749 "List of path to search for binaries.
1750 This variable follows the same rules as `exec-path' since it
1751 merges with it before the process creation routines are called.
1752 When this variable is nil, the Python shell is run with the
1753 default `exec-path'."
1754 :type '(repeat string)
1758 (defcustom python-shell-virtualenv-path nil
1759 "Path to virtualenv root.
1760 This variable, when set to a string, makes the values stored in
1761 `python-shell-process-environment' and `python-shell-exec-path'
1762 to be modified properly so shells are started with the specified
1764 :type '(choice (const nil) string)
1768 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1769 python-ffap-setup-code
1770 python-eldoc-setup-code)
1771 "List of code run by `python-shell-send-setup-codes'."
1772 :type '(repeat symbol)
1776 (defcustom python-shell-compilation-regexp-alist
1777 `((,(rx line-start (1+ (any " \t")) "File \""
1778 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1779 "\", line " (group (1+ digit)))
1781 (,(rx " in file " (group (1+ not-newline)) " on line "
1784 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1785 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1787 "`compilation-error-regexp-alist' for inferior Python."
1788 :type '(alist string)
1791 (defun python-shell-get-process-name (dedicated)
1792 "Calculate the appropriate process name for inferior Python process.
1793 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1794 returns a string with the form
1795 `python-shell-buffer-name'[variable `buffer-file-name'] else
1796 returns the value of `python-shell-buffer-name'."
1800 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1801 (format "%s" python-shell-buffer-name))))
1804 (defun python-shell-internal-get-process-name ()
1805 "Calculate the appropriate process name for Internal Python process.
1806 The name is calculated from `python-shell-global-buffer-name' and
1807 a hash of all relevant global shell settings in order to ensure
1808 uniqueness for different types of configurations."
1810 python-shell-internal-buffer-name
1813 (python-shell-parse-command)
1814 python-shell-prompt-regexp
1815 python-shell-prompt-block-regexp
1816 python-shell-prompt-output-regexp
1817 (mapconcat #'symbol-value python-shell-setup-codes "")
1818 (mapconcat #'identity python-shell-process-environment "")
1819 (mapconcat #'identity python-shell-extra-pythonpaths "")
1820 (mapconcat #'identity python-shell-exec-path "")
1821 (or python-shell-virtualenv-path "")
1822 (mapconcat #'identity python-shell-exec-path "")))))
1824 (defun python-shell-parse-command ()
1825 "Calculate the string used to execute the inferior Python process."
1826 (let ((process-environment (python-shell-calculate-process-environment))
1827 (exec-path (python-shell-calculate-exec-path)))
1829 (executable-find python-shell-interpreter)
1830 python-shell-interpreter-args)))
1832 (defun python-shell-calculate-process-environment ()
1833 "Calculate process environment given `python-shell-virtualenv-path'."
1834 (let ((process-environment (append
1835 python-shell-process-environment
1836 process-environment nil))
1837 (virtualenv (if python-shell-virtualenv-path
1838 (directory-file-name python-shell-virtualenv-path)
1840 (when python-shell-extra-pythonpaths
1841 (setenv "PYTHONPATH"
1843 (mapconcat 'identity
1844 python-shell-extra-pythonpaths
1847 (or (getenv "PYTHONPATH") ""))))
1848 (if (not virtualenv)
1850 (setenv "PYTHONHOME" nil)
1851 (setenv "PATH" (format "%s/bin%s%s"
1852 virtualenv path-separator
1853 (or (getenv "PATH") "")))
1854 (setenv "VIRTUAL_ENV" virtualenv))
1855 process-environment))
1857 (defun python-shell-calculate-exec-path ()
1858 "Calculate exec path given `python-shell-virtualenv-path'."
1859 (let ((path (append python-shell-exec-path
1861 (if (not python-shell-virtualenv-path)
1863 (cons (format "%s/bin"
1864 (directory-file-name python-shell-virtualenv-path))
1867 (defun python-comint-output-filter-function (output)
1868 "Hook run after content is put into comint buffer.
1869 OUTPUT is a string with the contents of the buffer."
1870 (ansi-color-filter-apply output))
1872 (defvar python-shell--parent-buffer nil)
1874 (defvar python-shell-output-syntax-table
1875 (let ((table (make-syntax-table python-dotty-syntax-table)))
1876 (modify-syntax-entry ?\' "." table)
1877 (modify-syntax-entry ?\" "." table)
1878 (modify-syntax-entry ?\( "." table)
1879 (modify-syntax-entry ?\[ "." table)
1880 (modify-syntax-entry ?\{ "." table)
1881 (modify-syntax-entry ?\) "." table)
1882 (modify-syntax-entry ?\] "." table)
1883 (modify-syntax-entry ?\} "." table)
1885 "Syntax table for shell output.
1886 It makes parens and quotes be treated as punctuation chars.")
1888 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1889 "Major mode for Python inferior process.
1890 Runs a Python interpreter as a subprocess of Emacs, with Python
1891 I/O through an Emacs buffer. Variables `python-shell-interpreter'
1892 and `python-shell-interpreter-args' control which Python
1893 interpreter is run. Variables
1894 `python-shell-prompt-regexp',
1895 `python-shell-prompt-output-regexp',
1896 `python-shell-prompt-block-regexp',
1897 `python-shell-enable-font-lock',
1898 `python-shell-completion-setup-code',
1899 `python-shell-completion-string-code',
1900 `python-shell-completion-module-string-code',
1901 `python-eldoc-setup-code', `python-eldoc-string-code',
1902 `python-ffap-setup-code' and `python-ffap-string-code' can
1903 customize this mode for different Python interpreters.
1905 You can also add additional setup code to be run at
1906 initialization of the interpreter via `python-shell-setup-codes'
1909 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1910 (and python-shell--parent-buffer
1911 (python-util-clone-local-variables python-shell--parent-buffer))
1912 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1913 python-shell-prompt-regexp
1914 python-shell-prompt-block-regexp
1915 python-shell-prompt-pdb-regexp))
1916 (setq mode-line-process '(":%s"))
1917 (make-local-variable 'comint-output-filter-functions)
1918 (add-hook 'comint-output-filter-functions
1919 'python-comint-output-filter-function)
1920 (add-hook 'comint-output-filter-functions
1921 'python-pdbtrack-comint-output-filter-function)
1922 (set (make-local-variable 'compilation-error-regexp-alist)
1923 python-shell-compilation-regexp-alist)
1924 (define-key inferior-python-mode-map [remap complete-symbol]
1925 'completion-at-point)
1926 (add-hook 'completion-at-point-functions
1927 'python-shell-completion-complete-at-point nil 'local)
1928 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1929 'python-shell-completion-complete-at-point)
1930 (define-key inferior-python-mode-map "\t"
1931 'python-shell-completion-complete-or-indent)
1932 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1933 (make-local-variable 'python-pdbtrack-tracked-buffer)
1934 (make-local-variable 'python-shell-internal-last-output)
1935 (when python-shell-enable-font-lock
1936 (set-syntax-table python-mode-syntax-table)
1937 (set (make-local-variable 'font-lock-defaults)
1938 '(python-font-lock-keywords nil nil nil nil))
1939 (set (make-local-variable 'syntax-propertize-function)
1941 ;; XXX: Unfortunately eval is needed here to make use of the
1942 ;; dynamic value of `comint-prompt-regexp'.
1943 `(syntax-propertize-rules
1944 (,comint-prompt-regexp
1947 comint-last-input-start end 'syntax-table
1948 python-shell-output-syntax-table)
1949 ;; XXX: This might look weird, but it is the easiest
1950 ;; way to ensure font lock gets cleaned up before the
1951 ;; current prompt, which is needed for unclosed
1952 ;; strings to not mess up with current input.
1953 (font-lock-unfontify-region comint-last-input-start end))))
1954 (,(python-rx string-delimiter)
1956 (and (not (eq (get-text-property start 'field) 'output))
1957 (python-syntax-stringify)))))))))
1958 (compilation-shell-minor-mode 1))
1960 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
1961 "Create a Python shell comint buffer.
1962 CMD is the Python command to be executed and PROC-NAME is the
1963 process name the comint buffer will get. After the comint buffer
1964 is created the `inferior-python-mode' is activated. When
1965 optional argument POP is non-nil the buffer is shown. When
1966 optional argument INTERNAL is non-nil this process is run on a
1967 buffer with a name that starts with a space, following the Emacs
1968 convention for temporary/internal buffers, and also makes sure
1969 the user is not queried for confirmation when the process is
1972 (let* ((proc-buffer-name
1973 (format (if (not internal) "*%s*" " *%s*") proc-name))
1974 (process-environment (python-shell-calculate-process-environment))
1975 (exec-path (python-shell-calculate-exec-path)))
1976 (when (not (comint-check-proc proc-buffer-name))
1977 (let* ((cmdlist (split-string-and-unquote cmd))
1978 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1979 (car cmdlist) nil (cdr cmdlist)))
1980 (python-shell--parent-buffer (current-buffer))
1981 (process (get-buffer-process buffer)))
1982 (with-current-buffer buffer
1983 (inferior-python-mode))
1984 (accept-process-output process)
1985 (and pop (pop-to-buffer buffer t))
1986 (and internal (set-process-query-on-exit-flag process nil))))
1990 (defun run-python (cmd &optional dedicated show)
1991 "Run an inferior Python process.
1992 Input and output via buffer named after
1993 `python-shell-buffer-name'. If there is a process already
1994 running in that buffer, just switch to it.
1996 With argument, allows you to define CMD so you can edit the
1997 command used to call the interpreter and define DEDICATED, so a
1998 dedicated process for the current buffer is open. When numeric
1999 prefix arg is other than 0 or 4 do not SHOW.
2001 Runs the hook `inferior-python-mode-hook' after
2002 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2003 process buffer for a list of commands.)"
2005 (if current-prefix-arg
2007 (read-shell-command "Run Python: " (python-shell-parse-command))
2008 (y-or-n-p "Make dedicated process? ")
2009 (= (prefix-numeric-value current-prefix-arg) 4))
2010 (list (python-shell-parse-command) nil t)))
2011 (python-shell-make-comint
2012 cmd (python-shell-get-process-name dedicated) show)
2015 (defun run-python-internal ()
2016 "Run an inferior Internal Python process.
2017 Input and output via buffer named after
2018 `python-shell-internal-buffer-name' and what
2019 `python-shell-internal-get-process-name' returns.
2021 This new kind of shell is intended to be used for generic
2022 communication related to defined configurations; the main
2023 difference with global or dedicated shells is that these ones are
2024 attached to a configuration, not a buffer. This means that can
2025 be used for example to retrieve the sys.path and other stuff,
2026 without messing with user shells. Note that
2027 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
2028 are set to nil for these shells, so setup codes are not sent at
2030 (let ((python-shell-enable-font-lock nil)
2031 (inferior-python-mode-hook nil))
2033 (python-shell-make-comint
2034 (python-shell-parse-command)
2035 (python-shell-internal-get-process-name) nil t))))
2037 (defun python-shell-get-buffer ()
2038 "Return inferior Python buffer for current buffer."
2039 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2040 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2041 (global-proc-name (python-shell-get-process-name nil))
2042 (global-proc-buffer-name (format "*%s*" global-proc-name))
2043 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2044 (global-running (comint-check-proc global-proc-buffer-name)))
2045 ;; Always prefer dedicated
2046 (or (and dedicated-running dedicated-proc-buffer-name)
2047 (and global-running global-proc-buffer-name))))
2049 (defun python-shell-get-process ()
2050 "Return inferior Python process for current buffer."
2051 (get-buffer-process (python-shell-get-buffer)))
2053 (defun python-shell-get-or-create-process ()
2054 "Get or create an inferior Python process for current buffer and return it."
2055 (let* ((dedicated-proc-name (python-shell-get-process-name t))
2056 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
2057 (global-proc-name (python-shell-get-process-name nil))
2058 (global-proc-buffer-name (format "*%s*" global-proc-name))
2059 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
2060 (global-running (comint-check-proc global-proc-buffer-name)))
2061 (when (and (not dedicated-running) (not global-running))
2062 (if (call-interactively 'run-python)
2063 (setq dedicated-running t)
2064 (setq global-running t)))
2065 ;; Always prefer dedicated
2066 (get-buffer-process (if dedicated-running
2067 dedicated-proc-buffer-name
2068 global-proc-buffer-name))))
2070 (defvar python-shell-internal-buffer nil
2071 "Current internal shell buffer for the current buffer.
2072 This is really not necessary at all for the code to work but it's
2073 there for compatibility with CEDET.")
2075 (defvar python-shell-internal-last-output nil
2076 "Last output captured by the internal shell.
2077 This is really not necessary at all for the code to work but it's
2078 there for compatibility with CEDET.")
2080 (defun python-shell-internal-get-or-create-process ()
2081 "Get or create an inferior Internal Python process."
2082 (let* ((proc-name (python-shell-internal-get-process-name))
2083 (proc-buffer-name (format " *%s*" proc-name)))
2084 (when (not (process-live-p proc-name))
2085 (run-python-internal)
2086 (setq python-shell-internal-buffer proc-buffer-name)
2087 ;; XXX: Why is this `sit-for' needed?
2088 ;; `python-shell-make-comint' calls `accept-process-output'
2089 ;; already but it is not helping to get proper output on
2090 ;; 'gnu/linux when the internal shell process is not running and
2091 ;; a call to `python-shell-internal-send-string' is issued.
2093 (get-buffer-process proc-buffer-name)))
2095 (define-obsolete-function-alias
2096 'python-proc 'python-shell-internal-get-or-create-process "24.3")
2098 (define-obsolete-variable-alias
2099 'python-buffer 'python-shell-internal-buffer "24.3")
2101 (define-obsolete-variable-alias
2102 'python-preoutput-result 'python-shell-internal-last-output "24.3")
2104 (defun python-shell--save-temp-file (string)
2105 (let* ((temporary-file-directory
2106 (if (file-remote-p default-directory)
2107 (concat (file-remote-p default-directory) "/tmp")
2108 temporary-file-directory))
2109 (temp-file-name (make-temp-file "py"))
2110 (coding-system-for-write 'utf-8))
2111 (with-temp-file temp-file-name
2112 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2114 (delete-trailing-whitespace))
2117 (defun python-shell-send-string (string &optional process)
2118 "Send STRING to inferior Python PROCESS."
2119 (interactive "sPython command: ")
2120 (let ((process (or process (python-shell-get-or-create-process))))
2121 (if (string-match ".\n+." string) ;Multiline.
2122 (let* ((temp-file-name (python-shell--save-temp-file string)))
2123 (python-shell-send-file temp-file-name process temp-file-name t))
2124 (comint-send-string process string)
2125 (when (or (not (string-match "\n\\'" string))
2126 (string-match "\n[ \t].*\n?\\'" string))
2127 (comint-send-string process "\n")))))
2129 (defvar python-shell-output-filter-in-progress nil)
2130 (defvar python-shell-output-filter-buffer nil)
2132 (defun python-shell-output-filter (string)
2133 "Filter used in `python-shell-send-string-no-output' to grab output.
2134 STRING is the output received to this point from the process.
2135 This filter saves received output from the process in
2136 `python-shell-output-filter-buffer' and stops receiving it after
2137 detecting a prompt at the end of the buffer."
2139 string (ansi-color-filter-apply string)
2140 python-shell-output-filter-buffer
2141 (concat python-shell-output-filter-buffer string))
2143 ;; XXX: It seems on OSX an extra carriage return is attached
2144 ;; at the end of output, this handles that too.
2145 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
2146 python-shell-prompt-regexp
2147 python-shell-prompt-block-regexp
2148 python-shell-prompt-pdb-regexp)
2149 python-shell-output-filter-buffer)
2150 ;; Output ends when `python-shell-output-filter-buffer' contains
2151 ;; the prompt attached at the end of it.
2152 (setq python-shell-output-filter-in-progress nil
2153 python-shell-output-filter-buffer
2154 (substring python-shell-output-filter-buffer
2155 0 (match-beginning 0)))
2156 (when (and (> (length python-shell-prompt-output-regexp) 0)
2157 (string-match (concat "^" python-shell-prompt-output-regexp)
2158 python-shell-output-filter-buffer))
2159 ;; Some shells, like iPython might append a prompt before the
2160 ;; output, clean that.
2161 (setq python-shell-output-filter-buffer
2162 (substring python-shell-output-filter-buffer (match-end 0)))))
2165 (defun python-shell-send-string-no-output (string &optional process)
2166 "Send STRING to PROCESS and inhibit output.
2168 (let ((process (or process (python-shell-get-or-create-process)))
2169 (comint-preoutput-filter-functions
2170 '(python-shell-output-filter))
2171 (python-shell-output-filter-in-progress t)
2175 (python-shell-send-string string process)
2176 (while python-shell-output-filter-in-progress
2177 ;; `python-shell-output-filter' takes care of setting
2178 ;; `python-shell-output-filter-in-progress' to NIL after it
2179 ;; detects end of output.
2180 (accept-process-output process))
2182 python-shell-output-filter-buffer
2183 (setq python-shell-output-filter-buffer nil)))
2184 (with-current-buffer (process-buffer process)
2185 (comint-interrupt-subjob)))))
2187 (defun python-shell-internal-send-string (string)
2188 "Send STRING to the Internal Python interpreter.
2189 Returns the output. See `python-shell-send-string-no-output'."
2190 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2191 ;; updated to support this new mode.
2192 (setq python-shell-internal-last-output
2193 (python-shell-send-string-no-output
2194 ;; Makes this function compatible with the old
2195 ;; python-send-receive. (At least for CEDET).
2196 (replace-regexp-in-string "_emacs_out +" "" string)
2197 (python-shell-internal-get-or-create-process))))
2199 (define-obsolete-function-alias
2200 'python-send-receive 'python-shell-internal-send-string "24.3")
2202 (define-obsolete-function-alias
2203 'python-send-string 'python-shell-internal-send-string "24.3")
2205 (defvar python--use-fake-loc nil
2206 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2207 If nil, regions of text are prepended by the corresponding number of empty
2208 lines and Python is told to output error messages referring to the whole
2211 (defun python-shell-buffer-substring (start end &optional nomain)
2212 "Send buffer substring from START to END formatted for shell.
2213 This is a wrapper over `buffer-substring' that takes care of
2214 different transformations for the code sent to be evaluated in
2216 1. When optional argument NOMAIN is non-nil everything under an
2217 \"if __name__ == '__main__'\" block will be removed.
2218 2. When a subregion of the buffer is sent, it takes care of
2219 appending extra empty lines so tracebacks are correct.
2220 3. Wraps indented regions under an \"if True:\" block so the
2221 interpreter evaluates them correctly."
2222 (let ((substring (buffer-substring-no-properties start end))
2223 (fillstr (unless python--use-fake-loc
2224 (make-string (1- (line-number-at-pos start)) ?\n)))
2225 (toplevel-block-p (save-excursion
2227 (or (zerop (line-number-at-pos start))
2229 (python-util-forward-comment 1)
2230 (zerop (current-indentation)))))))
2233 (if fillstr (insert fillstr))
2235 (goto-char (point-min))
2236 (unless python--use-fake-loc
2237 ;; python-shell--save-temp-file adds an extra coding line, which would
2238 ;; throw off the line-counts, so let's try to compensate here.
2239 (if (looking-at "[ \t]*[#\n]")
2240 (delete-region (point) (line-beginning-position 2))))
2241 (when (not toplevel-block-p)
2243 (delete-region (point) (line-end-position)))
2245 (let* ((if-name-main-start-end
2248 (when (python-nav-if-name-main)
2250 (progn (python-nav-forward-sexp-safe)
2252 ;; Oh destructuring bind, how I miss you.
2253 (if-name-main-start (car if-name-main-start-end))
2254 (if-name-main-end (cdr if-name-main-start-end)))
2255 (when if-name-main-start-end
2256 (goto-char if-name-main-start)
2257 (delete-region if-name-main-start if-name-main-end)
2260 (- (line-number-at-pos if-name-main-end)
2261 (line-number-at-pos if-name-main-start)) ?\n)))))
2262 (buffer-substring-no-properties (point-min) (point-max)))))
2264 (declare-function compilation-fake-loc "compile"
2265 (marker file &optional line col))
2267 (defun python-shell-send-region (start end &optional nomain)
2268 "Send the region delimited by START and END to inferior Python process."
2270 (let* ((python--use-fake-loc
2271 (or python--use-fake-loc (not buffer-file-name)))
2272 (string (python-shell-buffer-substring start end nomain))
2273 (process (python-shell-get-or-create-process))
2274 (_ (string-match "\\`\n*\\(.*\\)" string)))
2275 (message "Sent: %s..." (match-string 1 string))
2276 (let* ((temp-file-name (python-shell--save-temp-file string))
2277 (file-name (or (buffer-file-name) temp-file-name)))
2278 (python-shell-send-file file-name process temp-file-name t)
2279 (unless python--use-fake-loc
2280 (with-current-buffer (process-buffer process)
2281 (compilation-fake-loc (copy-marker start) temp-file-name
2282 2)) ;; Not 1, because of the added coding line.
2285 (defun python-shell-send-buffer (&optional arg)
2286 "Send the entire buffer to inferior Python process.
2287 With prefix ARG allow execution of code inside blocks delimited
2288 by \"if __name__== '__main__':\"."
2292 (python-shell-send-region (point-min) (point-max) (not arg))))
2294 (defun python-shell-send-defun (arg)
2295 "Send the current defun to inferior Python process.
2296 When argument ARG is non-nil do not include decorators."
2299 (python-shell-send-region
2302 (while (and (or (python-nav-beginning-of-defun)
2303 (beginning-of-line 1))
2304 (> (current-indentation) 0)))
2306 (while (and (forward-line -1)
2307 (looking-at (python-rx decorator))))
2311 (or (python-nav-end-of-defun)
2315 (defun python-shell-send-file (file-name &optional process temp-file-name
2317 "Send FILE-NAME to inferior Python PROCESS.
2318 If TEMP-FILE-NAME is passed then that file is used for processing
2319 instead, while internally the shell will continue to use FILE-NAME.
2320 If DELETE is non-nil, delete the file afterwards."
2321 (interactive "fFile to send: ")
2322 (let* ((process (or process (python-shell-get-or-create-process)))
2323 (temp-file-name (when temp-file-name
2325 (or (file-remote-p temp-file-name 'localname)
2327 (file-name (or (when file-name
2329 (or (file-remote-p file-name 'localname)
2332 (when (not file-name)
2333 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2334 (python-shell-send-string
2336 (concat "__pyfile = open('''%s''');"
2337 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2338 "__pyfile.close()%s")
2339 (or temp-file-name file-name) file-name
2340 (if delete (format "; import os; os.remove('''%s''')"
2341 (or temp-file-name file-name))
2345 (defun python-shell-switch-to-shell ()
2346 "Switch to inferior Python process buffer."
2348 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2350 (defun python-shell-send-setup-code ()
2351 "Send all setup code for shell.
2352 This function takes the list of setup code to send from the
2353 `python-shell-setup-codes' list."
2354 (let ((process (get-buffer-process (current-buffer))))
2355 (dolist (code python-shell-setup-codes)
2357 (message "Sent %s" code)
2358 (python-shell-send-string
2359 (symbol-value code) process)))))
2361 (add-hook 'inferior-python-mode-hook
2362 #'python-shell-send-setup-code)
2365 ;;; Shell completion
2367 (defcustom python-shell-completion-setup-code
2371 def __COMPLETER_all_completions(text): []
2374 readline.set_completer(rlcompleter.Completer().complete)
2375 def __COMPLETER_all_completions(text):
2381 res = readline.get_completer()(text, i)
2384 completions.append(res)
2388 "Code used to setup completion in inferior Python processes."
2392 (defcustom python-shell-completion-string-code
2393 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2394 "Python code used to get a string of completions separated by semicolons."
2398 (defcustom python-shell-completion-module-string-code ""
2399 "Python code used to get completions separated by semicolons for imports.
2401 For IPython v0.11, add the following line to
2402 `python-shell-completion-setup-code':
2404 from IPython.core.completerlib import module_completion
2406 and use the following as the value of this variable:
2408 ';'.join(module_completion('''%s'''))\n"
2412 (defcustom python-shell-completion-pdb-string-code
2413 "';'.join(globals().keys() + locals().keys())"
2414 "Python code used to get completions separated by semicolons for [i]pdb."
2418 (defun python-shell-completion-get-completions (process line input)
2419 "Do completion at point for PROCESS.
2420 LINE is used to detect the context on how to complete given INPUT."
2422 ;; Get last prompt of the inferior process buffer (this
2423 ;; intentionally avoids using `comint-last-prompt' because
2424 ;; of incompatibilities with Emacs 24.x).
2425 (with-current-buffer (process-buffer process)
2427 (buffer-substring-no-properties
2428 (- (point) (length line))
2430 (re-search-backward "^")
2431 (python-util-forward-comment)
2434 ;; Check whether a prompt matches a pdb string, an import
2435 ;; statement or just the standard prompt and use the
2436 ;; correct python-shell-completion-*-code string
2437 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2439 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2442 (length python-shell-completion-module-string-code) 0)
2444 (concat "^" python-shell-prompt-regexp) prompt)
2445 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2448 (concat "^" python-shell-prompt-regexp) prompt)
2452 (pcase completion-context
2453 (`pdb python-shell-completion-pdb-string-code)
2454 (`import python-shell-completion-module-string-code)
2455 (`default python-shell-completion-string-code)
2458 (if (eq completion-context 'import)
2459 (replace-regexp-in-string "^[ \t]+" "" line)
2461 (and completion-code
2462 (> (length input) 0)
2463 (with-current-buffer (process-buffer process)
2465 (python-util-strip-string
2466 (python-shell-send-string-no-output
2467 (format completion-code input) process))))
2468 (and (> (length completions) 2)
2469 (split-string completions
2470 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2472 (defun python-shell-completion-complete-at-point (&optional process)
2473 "Perform completion at point in inferior Python.
2474 Optional argument PROCESS forces completions to be retrieved
2475 using that one instead of current buffer's process."
2476 (setq process (or process (get-buffer-process (current-buffer))))
2479 (with-syntax-table python-dotty-syntax-table
2480 (let* ((paren-depth (car (syntax-ppss)))
2481 (syntax-string "w_")
2482 (syntax-list (string-to-syntax syntax-string)))
2483 ;; Stop scanning for the beginning of the completion
2484 ;; subject after the char before point matches a
2487 (car (syntax-after (1- (point)))) syntax-list)
2488 (skip-syntax-backward syntax-string)
2489 (when (or (equal (char-before) ?\))
2490 (equal (char-before) ?\"))
2493 ;; honor initial paren depth
2494 (> (car (syntax-ppss)) paren-depth)
2495 (python-syntax-context 'string))
2500 (completion-table-dynamic
2502 #'python-shell-completion-get-completions
2503 process (buffer-substring-no-properties
2504 (line-beginning-position) end))))))
2506 (defun python-shell-completion-complete-or-indent ()
2507 "Complete or indent depending on the context.
2508 If content before pointer is all whitespace, indent.
2509 If not try to complete."
2511 (if (string-match "^[[:space:]]*$"
2512 (buffer-substring (comint-line-beginning-position)
2514 (indent-for-tab-command)
2515 (completion-at-point)))
2518 ;;; PDB Track integration
2520 (defcustom python-pdbtrack-activate t
2521 "Non-nil makes Python shell enable pdbtracking."
2526 (defcustom python-pdbtrack-stacktrace-info-regexp
2527 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2528 "Regular expression matching stacktrace information.
2529 Used to extract the current line and module being inspected."
2534 (defvar python-pdbtrack-tracked-buffer nil
2535 "Variable containing the value of the current tracked buffer.
2536 Never set this variable directly, use
2537 `python-pdbtrack-set-tracked-buffer' instead.")
2539 (defvar python-pdbtrack-buffers-to-kill nil
2540 "List of buffers to be deleted after tracking finishes.")
2542 (defun python-pdbtrack-set-tracked-buffer (file-name)
2543 "Set the buffer for FILE-NAME as the tracked buffer.
2544 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2545 Returns the tracked buffer."
2546 (let ((file-buffer (get-file-buffer
2547 (concat (file-remote-p default-directory)
2550 (setq python-pdbtrack-tracked-buffer file-buffer)
2551 (setq file-buffer (find-file-noselect file-name))
2552 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2553 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2556 (defun python-pdbtrack-comint-output-filter-function (output)
2557 "Move overlay arrow to current pdb line in tracked buffer.
2558 Argument OUTPUT is a string with the output from the comint process."
2559 (when (and python-pdbtrack-activate (not (string= output "")))
2560 (let* ((full-output (ansi-color-filter-apply
2561 (buffer-substring comint-last-input-end (point-max))))
2565 (insert full-output)
2566 ;; When the debugger encounters a pdb.set_trace()
2567 ;; command, it prints a single stack frame. Sometimes
2568 ;; it prints a bit of extra information about the
2569 ;; arguments of the present function. When ipdb
2570 ;; encounters an exception, it prints the _entire_ stack
2571 ;; trace. To handle all of these cases, we want to find
2572 ;; the _last_ stack frame printed in the most recent
2573 ;; batch of output, then jump to the corresponding
2574 ;; file/line number.
2575 (goto-char (point-max))
2576 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
2577 (setq line-number (string-to-number
2578 (match-string-no-properties 2)))
2579 (match-string-no-properties 1)))))
2580 (if (and file-name line-number)
2581 (let* ((tracked-buffer
2582 (python-pdbtrack-set-tracked-buffer file-name))
2583 (shell-buffer (current-buffer))
2584 (tracked-buffer-window (get-buffer-window tracked-buffer))
2585 (tracked-buffer-line-pos))
2586 (with-current-buffer tracked-buffer
2587 (set (make-local-variable 'overlay-arrow-string) "=>")
2588 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2589 (setq tracked-buffer-line-pos (progn
2590 (goto-char (point-min))
2591 (forward-line (1- line-number))
2593 (when tracked-buffer-window
2595 tracked-buffer-window tracked-buffer-line-pos))
2596 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2597 (pop-to-buffer tracked-buffer)
2598 (switch-to-buffer-other-window shell-buffer))
2599 (when python-pdbtrack-tracked-buffer
2600 (with-current-buffer python-pdbtrack-tracked-buffer
2601 (set-marker overlay-arrow-position nil))
2602 (mapc #'(lambda (buffer)
2603 (ignore-errors (kill-buffer buffer)))
2604 python-pdbtrack-buffers-to-kill)
2605 (setq python-pdbtrack-tracked-buffer nil
2606 python-pdbtrack-buffers-to-kill nil)))))
2610 ;;; Symbol completion
2612 (defun python-completion-complete-at-point ()
2613 "Complete current symbol at point.
2614 For this to work as best as possible you should call
2615 `python-shell-send-buffer' from time to time so context in
2616 inferior Python process is updated properly."
2617 (let ((process (python-shell-get-process)))
2619 (error "Completion needs an inferior Python process running")
2620 (python-shell-completion-complete-at-point process))))
2622 (add-to-list 'debug-ignored-errors
2623 "^Completion needs an inferior Python process running.")
2628 (defcustom python-fill-comment-function 'python-fill-comment
2629 "Function to fill comments.
2630 This is the function used by `python-fill-paragraph' to
2635 (defcustom python-fill-string-function 'python-fill-string
2636 "Function to fill strings.
2637 This is the function used by `python-fill-paragraph' to
2642 (defcustom python-fill-decorator-function 'python-fill-decorator
2643 "Function to fill decorators.
2644 This is the function used by `python-fill-paragraph' to
2649 (defcustom python-fill-paren-function 'python-fill-paren
2650 "Function to fill parens.
2651 This is the function used by `python-fill-paragraph' to
2656 (defcustom python-fill-docstring-style 'pep-257
2657 "Style used to fill docstrings.
2658 This affects `python-fill-string' behavior with regards to
2659 triple quotes positioning.
2661 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
2662 `symmetric', and nil. A value of nil won't care about quotes
2663 position and will treat docstrings a normal string, any other
2664 value may result in one of the following docstring styles:
2669 Process foo, return bar.
2673 Process foo, return bar.
2675 If processing fails throw ProcessingError.
2680 \"\"\"Process foo, return bar.\"\"\"
2683 Process foo, return bar.
2685 If processing fails throw ProcessingError.
2691 \"\"\"Process foo, return bar.\"\"\"
2693 \"\"\"Process foo, return bar.
2695 If processing fails throw ProcessingError.
2701 \"\"\"Process foo, return bar.\"\"\"
2703 \"\"\"Process foo, return bar.
2705 If processing fails throw ProcessingError.
2710 \"\"\"Process foo, return bar.\"\"\"
2713 Process foo, return bar.
2715 If processing fails throw ProcessingError.
2718 (const :tag "Don't format docstrings" nil)
2719 (const :tag "Django's coding standards style." django)
2720 (const :tag "One newline and start and Two at end style." onetwo)
2721 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2722 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2723 (const :tag "Symmetric style." symmetric))
2726 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2728 (defun python-fill-paragraph (&optional justify)
2729 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2730 If any of the current line is in or at the end of a multi-line string,
2731 fill the string or the paragraph of it that point is in, preserving
2732 the string's indentation.
2733 Optional argument JUSTIFY defines if the paragraph should be justified."
2738 ((python-syntax-context 'comment)
2739 (funcall python-fill-comment-function justify))
2740 ;; Strings/Docstrings
2741 ((save-excursion (or (python-syntax-context 'string)
2742 (equal (string-to-syntax "|")
2743 (syntax-after (point)))))
2744 (funcall python-fill-string-function justify))
2746 ((equal (char-after (save-excursion
2747 (python-nav-beginning-of-statement))) ?@)
2748 (funcall python-fill-decorator-function justify))
2750 ((or (python-syntax-context 'paren)
2751 (looking-at (python-rx open-paren))
2753 (skip-syntax-forward "^(" (line-end-position))
2754 (looking-at (python-rx open-paren))))
2755 (funcall python-fill-paren-function justify))
2758 (defun python-fill-comment (&optional justify)
2759 "Comment fill function for `python-fill-paragraph'.
2760 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2761 (fill-comment-paragraph justify))
2763 (defun python-fill-string (&optional justify)
2764 "String fill function for `python-fill-paragraph'.
2765 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2766 (let* ((str-start-pos
2769 (or (python-syntax-context 'string)
2770 (and (equal (string-to-syntax "|")
2771 (syntax-after (point)))
2773 (num-quotes (python-syntax-count-quotes
2774 (char-after str-start-pos) str-start-pos))
2777 (goto-char (+ str-start-pos num-quotes))
2778 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2779 (goto-char (point-max)))
2782 ;; Docstring styles may vary for oneliners and multi-liners.
2783 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2785 (pcase python-fill-docstring-style
2786 ;; delimiters-style is a cons cell with the form
2787 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2788 ;; is NIL means to not add any newlines for start or end
2789 ;; of docstring. See `python-fill-docstring-style' for a
2790 ;; graphic idea of each style.
2791 (`django (cons 1 1))
2792 (`onetwo (and multi-line-p (cons 1 2)))
2793 (`pep-257 (and multi-line-p (cons nil 2)))
2794 (`pep-257-nn (and multi-line-p (cons nil 1)))
2795 (`symmetric (and multi-line-p (cons 1 1)))))
2796 (docstring-p (save-excursion
2797 ;; Consider docstrings those strings which
2798 ;; start on a line by themselves.
2799 (python-nav-beginning-of-statement)
2800 (and (= (point) str-start-pos))))
2801 (fill-paragraph-function))
2803 (narrow-to-region str-start-pos str-end-pos)
2804 (fill-paragraph justify))
2806 (when (and docstring-p python-fill-docstring-style)
2807 ;; Add the number of newlines indicated by the selected style
2808 ;; at the start of the docstring.
2809 (goto-char (+ str-start-pos num-quotes))
2810 (delete-region (point) (progn
2811 (skip-syntax-forward "> ")
2813 (and (car delimiters-style)
2814 (or (newline (car delimiters-style)) t)
2815 ;; Indent only if a newline is added.
2816 (indent-according-to-mode))
2817 ;; Add the number of newlines indicated by the selected style
2818 ;; at the end of the docstring.
2819 (goto-char (if (not (= str-end-pos (point-max)))
2820 (- str-end-pos num-quotes)
2822 (delete-region (point) (progn
2823 (skip-syntax-backward "> ")
2825 (and (cdr delimiters-style)
2826 ;; Add newlines only if string ends.
2827 (not (= str-end-pos (point-max)))
2828 (or (newline (cdr delimiters-style)) t)
2829 ;; Again indent only if a newline is added.
2830 (indent-according-to-mode))))) t)
2832 (defun python-fill-decorator (&optional _justify)
2833 "Decorator fill function for `python-fill-paragraph'.
2834 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2837 (defun python-fill-paren (&optional justify)
2838 "Paren fill function for `python-fill-paragraph'.
2839 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2841 (narrow-to-region (progn
2842 (while (python-syntax-context 'paren)
2843 (goto-char (1- (point-marker))))
2845 (line-beginning-position))
2847 (when (not (python-syntax-context 'paren))
2849 (when (not (python-syntax-context 'paren))
2850 (skip-syntax-backward "^)")))
2851 (while (python-syntax-context 'paren)
2852 (goto-char (1+ (point-marker))))
2854 (let ((paragraph-start "\f\\|[ \t]*$")
2855 (paragraph-separate ",")
2856 (fill-paragraph-function))
2857 (goto-char (point-min))
2858 (fill-paragraph justify))
2861 (python-indent-line)
2862 (goto-char (line-end-position)))) t)
2867 (defcustom python-skeleton-autoinsert nil
2868 "Non-nil means template skeletons will be automagically inserted.
2869 This happens when pressing \"if<SPACE>\", for example, to prompt for
2875 (define-obsolete-variable-alias
2876 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2878 (defvar python-skeleton-available '()
2879 "Internal list of available skeletons.")
2881 (define-abbrev-table 'python-mode-skeleton-abbrev-table ()
2882 "Abbrev table for Python mode skeletons."
2884 ;; Allow / inside abbrevs.
2885 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2886 ;; Only expand in code.
2887 :enable-function (lambda ()
2889 (not (python-syntax-comment-or-string-p))
2890 python-skeleton-autoinsert)))
2892 (defmacro python-skeleton-define (name doc &rest skel)
2893 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2894 The skeleton will be bound to python-skeleton-NAME and will
2895 be added to `python-mode-skeleton-abbrev-table'."
2896 (declare (indent 2))
2897 (let* ((name (symbol-name name))
2898 (function-name (intern (concat "python-skeleton-" name))))
2900 (define-abbrev python-mode-skeleton-abbrev-table
2901 ,name "" ',function-name :system t)
2902 (setq python-skeleton-available
2903 (cons ',function-name python-skeleton-available))
2904 (define-skeleton ,function-name
2906 (format "Insert %s statement." name))
2909 (define-abbrev-table 'python-mode-abbrev-table ()
2910 "Abbrev table for Python mode."
2911 :parents (list python-mode-skeleton-abbrev-table))
2913 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2914 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2915 The skeleton will be bound to python-skeleton-NAME."
2916 (declare (indent 2))
2917 (let* ((name (symbol-name name))
2918 (function-name (intern (concat "python-skeleton--" name)))
2920 "Add '%s' clause? " name)))
2923 `(< ,(format "%s:" name) \n \n
2925 `(define-skeleton ,function-name
2927 (format "Auxiliary skeleton for %s statement." name))
2929 (unless (y-or-n-p ,msg)
2933 (python-define-auxiliary-skeleton else nil)
2935 (python-define-auxiliary-skeleton except nil)
2937 (python-define-auxiliary-skeleton finally nil)
2939 (python-skeleton-define if nil
2943 ("other condition, %s: "
2947 '(python-skeleton--else) | ^)
2949 (python-skeleton-define while nil
2953 '(python-skeleton--else) | ^)
2955 (python-skeleton-define for nil
2959 '(python-skeleton--else) | ^)
2961 (python-skeleton-define import nil
2962 "Import from module: "
2963 "from " str & " " | -5
2965 ("Identifier: " str ", ") -2 \n _)
2967 (python-skeleton-define try nil
2973 "except " str ":" \n
2976 '(python-skeleton--except)
2977 '(python-skeleton--else)
2978 '(python-skeleton--finally) | ^)
2980 (python-skeleton-define def nil
2982 "def " str "(" ("Parameter, %s: "
2983 (unless (equal ?\( (char-before)) ", ")
2985 "\"\"\"" - "\"\"\"" \n
2988 (python-skeleton-define class nil
2990 "class " str "(" ("Inheritance, %s: "
2991 (unless (equal ?\( (char-before)) ", ")
2995 "\"\"\"" - "\"\"\"" \n
2998 (defun python-skeleton-add-menu-items ()
2999 "Add menu items to Python->Skeletons menu."
3000 (let ((skeletons (sort python-skeleton-available 'string<)))
3001 (dolist (skeleton skeletons)
3003 nil '("Python" "Skeletons")
3005 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
3010 (defcustom python-ffap-setup-code
3011 "def __FFAP_get_module_path(module):
3014 path = __import__(module).__file__
3015 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3020 "Python code to get a module path."
3024 (defcustom python-ffap-string-code
3025 "__FFAP_get_module_path('''%s''')\n"
3026 "Python code used to get a string with the path of a module."
3030 (defun python-ffap-module-path (module)
3031 "Function for `ffap-alist' to return path for MODULE."
3033 (and (eq major-mode 'inferior-python-mode)
3034 (get-buffer-process (current-buffer)))
3035 (python-shell-get-process))))
3039 (python-shell-send-string-no-output
3040 (format python-ffap-string-code module) process)))
3042 (substring-no-properties module-file 1 -1))))))
3046 (eval-after-load "ffap"
3048 (push '(python-mode . python-ffap-module-path) ffap-alist)
3049 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
3054 (defcustom python-check-command
3056 "Command used to check a Python file."
3060 (defcustom python-check-buffer-name
3061 "*Python check: %s*"
3062 "Buffer name used for check commands."
3066 (defvar python-check-custom-command nil
3069 (defun python-check (command)
3070 "Check a Python file (default current buffer's file).
3071 Runs COMMAND, a shell command, as if by `compile'.
3072 See `python-check-command' for the default."
3074 (list (read-string "Check command: "
3075 (or python-check-custom-command
3076 (concat python-check-command " "
3077 (shell-quote-argument
3079 (let ((name (buffer-file-name)))
3081 (file-name-nondirectory name)))
3083 (setq python-check-custom-command command)
3084 (save-some-buffers (not compilation-ask-about-save) nil)
3085 (let ((process-environment (python-shell-calculate-process-environment))
3086 (exec-path (python-shell-calculate-exec-path)))
3087 (compilation-start command nil
3089 (format python-check-buffer-name command)))))
3094 (defcustom python-eldoc-setup-code
3095 "def __PYDOC_get_help(obj):
3098 if hasattr(obj, 'startswith'):
3099 obj = eval(obj, globals())
3100 doc = inspect.getdoc(obj)
3101 if not doc and callable(obj):
3103 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3104 target = obj.__init__
3110 args = inspect.formatargspec(
3111 *inspect.getargspec(target)
3114 doc = '{objtype} {name}{args}'.format(
3115 objtype=objtype, name=name, args=args
3118 doc = doc.splitlines()[0]
3125 "Python code to setup documentation retrieval."
3129 (defcustom python-eldoc-string-code
3130 "__PYDOC_get_help('''%s''')\n"
3131 "Python code used to get a string with the documentation of an object."
3135 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
3136 "Internal implementation to get documentation at point.
3137 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3138 returns will be used. If not FORCE-PROCESS is passed what
3139 `python-shell-get-process' returns is used."
3140 (let ((process (or force-process (python-shell-get-process))))
3142 (error "Eldoc needs an inferior Python process running")
3143 (let ((input (or force-input
3144 (python-info-current-symbol t))))
3146 (python-shell-send-string-no-output
3147 (format python-eldoc-string-code input)
3150 (defun python-eldoc-function ()
3151 "`eldoc-documentation-function' for Python.
3152 For this to work as best as possible you should call
3153 `python-shell-send-buffer' from time to time so context in
3154 inferior Python process is updated properly."
3155 (python-eldoc--get-doc-at-point))
3157 (defun python-eldoc-at-point (symbol)
3158 "Get help on SYMBOL using `help'.
3159 Interactively, prompt for symbol."
3161 (let ((symbol (python-info-current-symbol t))
3162 (enable-recursive-minibuffers t))
3163 (list (read-string (if symbol
3164 (format "Describe symbol (default %s): " symbol)
3165 "Describe symbol: ")
3167 (message (python-eldoc--get-doc-at-point symbol)))
3169 (add-to-list 'debug-ignored-errors
3170 "^Eldoc needs an inferior Python process running.")
3175 (defvar python-imenu-format-item-label-function
3176 'python-imenu-format-item-label
3177 "Imenu function used to format an item label.
3178 It must be a function with two arguments: TYPE and NAME.")
3180 (defvar python-imenu-format-parent-item-label-function
3181 'python-imenu-format-parent-item-label
3182 "Imenu function used to format a parent item label.
3183 It must be a function with two arguments: TYPE and NAME.")
3185 (defvar python-imenu-format-parent-item-jump-label-function
3186 'python-imenu-format-parent-item-jump-label
3187 "Imenu function used to format a parent jump item label.
3188 It must be a function with two arguments: TYPE and NAME.")
3190 (defun python-imenu-format-item-label (type name)
3191 "Return Imenu label for single node using TYPE and NAME."
3192 (format "%s (%s)" name type))
3194 (defun python-imenu-format-parent-item-label (type name)
3195 "Return Imenu label for parent node using TYPE and NAME."
3196 (format "%s..." (python-imenu-format-item-label type name)))
3198 (defun python-imenu-format-parent-item-jump-label (type _name)
3199 "Return Imenu label for parent node jump using TYPE and NAME."
3200 (if (string= type "class")
3201 "*class definition*"
3202 "*function definition*"))
3204 (defun python-imenu--put-parent (type name pos tree)
3205 "Add the parent with TYPE, NAME and POS to TREE."
3207 (funcall python-imenu-format-item-label-function type name))
3209 (funcall python-imenu-format-parent-item-jump-label-function type name)))
3212 (cons label (cons (cons jump-label pos) tree)))))
3214 (defun python-imenu--build-tree (&optional min-indent prev-indent tree)
3215 "Recursively build the tree of nested definitions of a node.
3216 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3217 not be passed explicitly unless you know what you are doing."
3218 (setq min-indent (or min-indent 0)
3219 prev-indent (or prev-indent python-indent-offset))
3220 (let* ((pos (python-nav-backward-defun))
3222 (name (when (and pos (looking-at python-nav-beginning-of-defun-regexp))
3223 (let ((split (split-string (match-string-no-properties 0))))
3224 (setq type (car split))
3227 (funcall python-imenu-format-item-label-function type name)))
3228 (indent (current-indentation))
3229 (children-indent-limit (+ python-indent-offset min-indent)))
3231 ;; Nothing found, probably near to bobp.
3233 ((<= indent min-indent)
3234 ;; The current indentation points that this is a parent
3235 ;; node, add it to the tree and stop recursing.
3236 (python-imenu--put-parent type name pos tree))
3238 (python-imenu--build-tree
3241 (if (<= indent children-indent-limit)
3242 ;; This lies within the children indent offset range,
3243 ;; so it's a normal child of its parent (i.e., not
3244 ;; a child of a child).
3245 (cons (cons label pos) tree)
3246 ;; Oh no, a child of a child?! Fear not, we
3247 ;; know how to roll. We recursively parse these by
3248 ;; swapping prev-indent and min-indent plus adding this
3249 ;; newly found item to a fresh subtree. This works, I
3252 (python-imenu--build-tree
3253 prev-indent indent (list (cons label pos)))
3256 (defun python-imenu-create-index ()
3257 "Return tree Imenu alist for the current Python buffer.
3258 Change `python-imenu-format-item-label-function',
3259 `python-imenu-format-parent-item-label-function',
3260 `python-imenu-format-parent-item-jump-label-function' to
3261 customize how labels are formatted."
3262 (goto-char (point-max))
3265 (while (setq tree (python-imenu--build-tree))
3266 (setq index (cons tree index)))
3269 (defun python-imenu-create-flat-index (&optional alist prefix)
3270 "Return flat outline of the current Python buffer for Imenu.
3271 Optional argument ALIST is the tree to be flattened; when nil
3272 `python-imenu-build-index' is used with
3273 `python-imenu-format-parent-item-jump-label-function'
3274 `python-imenu-format-parent-item-label-function'
3275 `python-imenu-format-item-label-function' set to
3276 (lambda (type name) name)
3277 Optional argument PREFIX is used in recursive calls and should
3278 not be passed explicitly.
3285 (\"decorator\" . 173)
3288 (\"wrapped_f\" . 393))))
3294 (\"decorator\" . 173)
3295 (\"decorator.wrap\" . 353)
3296 (\"decorator.wrapped_f\" . 393))"
3297 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3302 (let ((name (if prefix
3303 (concat prefix "." (car item))
3306 (cond ((or (numberp pos) (markerp pos))
3307 (list (cons name pos)))
3310 (cons name (cdar pos))
3311 (python-imenu-create-flat-index (cddr item) name))))))
3313 (let* ((fn (lambda (_type name) name))
3314 (python-imenu-format-item-label-function fn)
3315 (python-imenu-format-parent-item-label-function fn)
3316 (python-imenu-format-parent-item-jump-label-function fn))
3317 (python-imenu-create-index))))))
3322 (defun python-info-current-defun (&optional include-type)
3323 "Return name of surrounding function with Python compatible dotty syntax.
3324 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3325 This function can be used as the value of `add-log-current-defun-function'
3326 since it returns nil if point is not inside a defun."
3332 (starting-indentation (current-indentation))
3333 (starting-pos (point))
3338 (while (python-nav-beginning-of-defun 1)
3339 (when (save-match-data
3341 (or (not last-indent)
3342 (< (current-indentation) last-indent))
3346 ;; If this is the first run, we may add
3347 ;; the current defun at point.
3348 (setq first-run nil)
3349 (goto-char starting-pos)
3350 (python-nav-beginning-of-statement)
3351 (beginning-of-line 1)
3353 python-nav-beginning-of-defun-regexp)))
3357 (+ (current-indentation)
3358 python-indent-offset)))
3359 (if (< starting-indentation min-indent)
3360 ;; If the starting indentation is not
3361 ;; within the min defun indent make the
3364 ;; Else go to the end of defun and add
3365 ;; up the current indentation to the
3367 (python-nav-end-of-defun)
3369 (if (>= (current-indentation) min-indent)
3370 (1+ (current-indentation))
3372 (save-match-data (setq last-indent (current-indentation)))
3373 (if (or (not include-type) type)
3374 (setq names (cons (match-string-no-properties 1) names))
3375 (let ((match (split-string (match-string-no-properties 0))))
3376 (setq type (car match))
3377 (setq names (cons (cadr match) names)))))
3378 ;; Stop searching ASAP.
3379 (and (= (current-indentation) 0) (throw 'exit t))))
3381 (concat (and type (format "%s " type))
3382 (mapconcat 'identity names ".")))))))
3384 (defun python-info-current-symbol (&optional replace-self)
3385 "Return current symbol using dotty syntax.
3386 With optional argument REPLACE-SELF convert \"self\" to current
3389 (and (not (python-syntax-comment-or-string-p))
3390 (with-syntax-table python-dotty-syntax-table
3391 (let ((sym (symbol-at-point)))
3393 (substring-no-properties (symbol-name sym))))))))
3395 (if (not replace-self)
3397 (let ((current-defun (python-info-current-defun)))
3398 (if (not current-defun)
3400 (replace-regexp-in-string
3401 (python-rx line-start word-start "self" word-end ?.)
3403 (mapconcat 'identity
3404 (butlast (split-string current-defun "\\."))
3408 (defun python-info-statement-starts-block-p ()
3409 "Return non-nil if current statement opens a block."
3411 (python-nav-beginning-of-statement)
3412 (looking-at (python-rx block-start))))
3414 (defun python-info-statement-ends-block-p ()
3415 "Return non-nil if point is at end of block."
3416 (let ((end-of-block-pos (save-excursion
3417 (python-nav-end-of-block)))
3418 (end-of-statement-pos (save-excursion
3419 (python-nav-end-of-statement))))
3420 (and end-of-block-pos end-of-statement-pos
3421 (= end-of-block-pos end-of-statement-pos))))
3423 (defun python-info-beginning-of-statement-p ()
3424 "Return non-nil if point is at beginning of statement."
3425 (= (point) (save-excursion
3426 (python-nav-beginning-of-statement)
3429 (defun python-info-end-of-statement-p ()
3430 "Return non-nil if point is at end of statement."
3431 (= (point) (save-excursion
3432 (python-nav-end-of-statement)
3435 (defun python-info-beginning-of-block-p ()
3436 "Return non-nil if point is at beginning of block."
3437 (and (python-info-beginning-of-statement-p)
3438 (python-info-statement-starts-block-p)))
3440 (defun python-info-end-of-block-p ()
3441 "Return non-nil if point is at end of block."
3442 (and (python-info-end-of-statement-p)
3443 (python-info-statement-ends-block-p)))
3445 (defun python-info-closing-block ()
3446 "Return the point of the block the current line closes."
3447 (let ((closing-word (save-excursion
3448 (back-to-indentation)
3450 (indentation (current-indentation)))
3451 (when (member closing-word python-indent-dedenters)
3454 (while (and (> (current-indentation) indentation)
3456 (not (back-to-indentation))
3458 (back-to-indentation)
3460 ((not (equal indentation (current-indentation))) nil)
3461 ((string= closing-word "elif")
3462 (when (member (current-word) '("if" "elif"))
3464 ((string= closing-word "else")
3465 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3467 ((string= closing-word "except")
3468 (when (member (current-word) '("try"))
3470 ((string= closing-word "finally")
3471 (when (member (current-word) '("except" "else"))
3472 (point-marker))))))))
3474 (defun python-info-closing-block-message (&optional closing-block-point)
3475 "Message the contents of the block the current line closes.
3476 With optional argument CLOSING-BLOCK-POINT use that instead of
3477 recalculating it calling `python-info-closing-block'."
3478 (let ((point (or closing-block-point (python-info-closing-block))))
3482 (message "Closes %s" (save-excursion
3484 (back-to-indentation)
3486 (point) (line-end-position))))))))
3488 (defun python-info-line-ends-backslash-p (&optional line-number)
3489 "Return non-nil if current line ends with backslash.
3490 With optional argument LINE-NUMBER, check that line instead."
3495 (python-util-goto-line line-number))
3496 (while (and (not (eobp))
3497 (goto-char (line-end-position))
3498 (python-syntax-context 'paren)
3499 (not (equal (char-before (point)) ?\\)))
3501 (when (equal (char-before) ?\\)
3504 (defun python-info-beginning-of-backslash (&optional line-number)
3505 "Return the point where the backslashed line start.
3506 Optional argument LINE-NUMBER forces the line number to check against."
3511 (python-util-goto-line line-number))
3512 (when (python-info-line-ends-backslash-p)
3513 (while (save-excursion
3514 (goto-char (line-beginning-position))
3515 (python-syntax-context 'paren))
3517 (back-to-indentation)
3520 (defun python-info-continuation-line-p ()
3521 "Check if current line is continuation of another.
3522 When current line is continuation of another return the point
3523 where the continued line ends."
3527 (let* ((context-type (progn
3528 (back-to-indentation)
3529 (python-syntax-context-type)))
3530 (line-start (line-number-at-pos))
3531 (context-start (when context-type
3532 (python-syntax-context context-type))))
3533 (cond ((equal context-type 'paren)
3534 ;; Lines inside a paren are always a continuation line
3535 ;; (except the first one).
3536 (python-util-forward-comment -1)
3538 ((member context-type '(string comment))
3539 ;; move forward an roll again
3540 (goto-char context-start)
3541 (python-util-forward-comment)
3542 (python-info-continuation-line-p))
3544 ;; Not within a paren, string or comment, the only way
3545 ;; we are dealing with a continuation line is that
3546 ;; previous line contains a backslash, and this can
3547 ;; only be the previous line from current
3548 (back-to-indentation)
3549 (python-util-forward-comment -1)
3550 (when (and (equal (1- line-start) (line-number-at-pos))
3551 (python-info-line-ends-backslash-p))
3552 (point-marker))))))))
3554 (defun python-info-block-continuation-line-p ()
3555 "Return non-nil if current line is a continuation of a block."
3557 (when (python-info-continuation-line-p)
3559 (back-to-indentation)
3560 (when (looking-at (python-rx block-start))
3563 (defun python-info-assignment-continuation-line-p ()
3564 "Check if current line is a continuation of an assignment.
3565 When current line is continuation of another with an assignment
3566 return the point of the first non-blank character after the
3569 (when (python-info-continuation-line-p)
3571 (back-to-indentation)
3572 (when (and (not (looking-at (python-rx block-start)))
3573 (and (re-search-forward (python-rx not-simple-operator
3575 not-simple-operator)
3576 (line-end-position) t)
3577 (not (python-syntax-context-type))))
3578 (skip-syntax-forward "\s")
3581 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3582 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3583 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3585 (beginning-of-line 1)
3586 (looking-at python-nav-beginning-of-defun-regexp))))
3588 (defun python-info-current-line-comment-p ()
3589 "Return non-nil if current line is a comment line."
3591 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
3594 (defun python-info-current-line-empty-p ()
3595 "Return non-nil if current line is empty, ignoring whitespace."
3597 (beginning-of-line 1)
3599 (python-rx line-start (* whitespace)
3600 (group (* not-newline))
3601 (* whitespace) line-end))
3602 (string-equal "" (match-string-no-properties 1))))
3605 ;;; Utility functions
3607 (defun python-util-goto-line (line-number)
3608 "Move point to LINE-NUMBER."
3609 (goto-char (point-min))
3610 (forward-line (1- line-number)))
3612 ;; Stolen from org-mode
3613 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3614 "Clone local variables from FROM-BUFFER.
3615 Optional argument REGEXP selects variables to clone and defaults
3619 (and (symbolp (car pair))
3620 (string-match (or regexp "^python-")
3621 (symbol-name (car pair)))
3622 (set (make-local-variable (car pair))
3624 (buffer-local-variables from-buffer)))
3626 (defun python-util-forward-comment (&optional direction)
3627 "Python mode specific version of `forward-comment'.
3628 Optional argument DIRECTION defines the direction to move to."
3629 (let ((comment-start (python-syntax-context 'comment))
3630 (factor (if (< (or direction 0) 0)
3634 (goto-char comment-start))
3635 (forward-comment factor)))
3637 (defun python-util-popn (lst n)
3638 "Return LST first N elements.
3639 N should be an integer, when negative its opposite is used.
3640 When N is bigger than the length of LST, the list is
3642 (let* ((n (min (abs n)))
3648 (setq acc (cons (car lst) acc)
3653 (defun python-util-strip-string (string)
3654 "Strip STRING whitespace and newlines from end and beginning."
3655 (replace-regexp-in-string
3656 (rx (or (: string-start (* (any whitespace ?\r ?\n)))
3657 (: (* (any whitespace ?\r ?\n)) string-end)))
3662 (defun python-electric-pair-string-delimiter ()
3663 (when (and electric-pair-mode
3664 (memq last-command-event '(?\" ?\'))
3666 (while (eq (char-before (- (point) count)) last-command-event)
3669 (eq (char-after) last-command-event))
3670 (save-excursion (insert (make-string 2 last-command-event)))))
3672 (defvar electric-indent-inhibit)
3675 (define-derived-mode python-mode prog-mode "Python"
3676 "Major mode for editing Python files.
3678 \\{python-mode-map}"
3679 (set (make-local-variable 'tab-width) 8)
3680 (set (make-local-variable 'indent-tabs-mode) nil)
3682 (set (make-local-variable 'comment-start) "# ")
3683 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3685 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3686 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3688 (set (make-local-variable 'forward-sexp-function)
3689 'python-nav-forward-sexp)
3691 (set (make-local-variable 'font-lock-defaults)
3692 '(python-font-lock-keywords nil nil nil nil))
3694 (set (make-local-variable 'syntax-propertize-function)
3695 python-syntax-propertize-function)
3697 (set (make-local-variable 'indent-line-function)
3698 #'python-indent-line-function)
3699 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3700 ;; Because indentation is not redundant, we cannot safely reindent code.
3701 (setq-local electric-indent-inhibit t)
3702 (setq-local electric-indent-chars (cons ?: electric-indent-chars))
3704 ;; Add """ ... """ pairing to electric-pair-mode.
3705 (add-hook 'post-self-insert-hook
3706 #'python-electric-pair-string-delimiter 'append t)
3708 (set (make-local-variable 'paragraph-start) "\\s-*$")
3709 (set (make-local-variable 'fill-paragraph-function)
3710 #'python-fill-paragraph)
3712 (set (make-local-variable 'beginning-of-defun-function)
3713 #'python-nav-beginning-of-defun)
3714 (set (make-local-variable 'end-of-defun-function)
3715 #'python-nav-end-of-defun)
3717 (add-hook 'completion-at-point-functions
3718 #'python-completion-complete-at-point nil 'local)
3720 (add-hook 'post-self-insert-hook
3721 #'python-indent-post-self-insert-function 'append 'local)
3723 (set (make-local-variable 'imenu-create-index-function)
3724 #'python-imenu-create-index)
3726 (set (make-local-variable 'add-log-current-defun-function)
3727 #'python-info-current-defun)
3729 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3731 (set (make-local-variable 'skeleton-further-elements)
3733 (< '(backward-delete-char-untabify (min python-indent-offset
3735 (^ '(- (1+ (current-indentation))))))
3737 (set (make-local-variable 'eldoc-documentation-function)
3738 #'python-eldoc-function)
3740 (add-to-list 'hs-special-modes-alist
3741 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3743 (python-nav-end-of-defun)) nil))
3745 (set (make-local-variable 'mode-require-final-newline) t)
3747 (set (make-local-variable 'outline-regexp)
3748 (python-rx (* space) block-start))
3749 (set (make-local-variable 'outline-heading-end-regexp) ":[^\n]*\n")
3750 (set (make-local-variable 'outline-level)
3752 "`outline-level' function for Python mode."
3753 (1+ (/ (current-indentation) python-indent-offset))))
3755 (python-skeleton-add-menu-items)
3757 (make-local-variable 'python-shell-internal-buffer)
3759 (when python-indent-guess-indent-offset
3760 (python-indent-guess-indent-offset)))
3767 ;; indent-tabs-mode: nil
3770 ;;; python.el ends here