1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
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 when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp' allows easy
58 ;; navigation between code blocks.
60 ;; Shell interaction: is provided and allows you to execute easily any
61 ;; block of code of your current buffer in an inferior Python process.
63 ;; Shell completion: hitting tab will try to complete the current
64 ;; word. Shell completion is implemented in a manner that if you
65 ;; change the `python-shell-interpreter' to any other (for example
66 ;; IPython) it should be easy to integrate another way to calculate
67 ;; completions. You just need to specify your custom
68 ;; `python-shell-completion-setup-code' and
69 ;; `python-shell-completion-string-code'.
71 ;; Here is a complete example of the settings you would use for
75 ;; python-shell-interpreter "ipython"
76 ;; python-shell-interpreter-args ""
77 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
78 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
79 ;; python-shell-completion-setup-code
80 ;; "from IPython.core.completerlib import module_completion"
81 ;; python-shell-completion-module-string-code
82 ;; "';'.join(module_completion('''%s'''))\n"
83 ;; python-shell-completion-string-code
84 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
86 ;; For iPython 0.10 everything would be the same except for
87 ;; `python-shell-completion-string-code' and
88 ;; `python-shell-completion-module-string-code':
90 ;; (setq python-shell-completion-string-code
91 ;; "';'.join(__IP.complete('''%s'''))\n"
92 ;; python-shell-completion-module-string-code "")
94 ;; Unfortunately running iPython on Windows needs some more tweaking.
95 ;; The way you must set `python-shell-interpreter' and
96 ;; `python-shell-interpreter-args' is as follows:
99 ;; python-shell-interpreter "C:\\Python27\\python.exe"
100 ;; python-shell-interpreter-args
101 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
103 ;; That will spawn the iPython process correctly (Of course you need
104 ;; to modify the paths according to your system).
106 ;; Please note that the default completion system depends on the
107 ;; readline module, so if you are using some Operating System that
108 ;; bundles Python without it (like Windows) just install the
109 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
110 ;; you should be good to go.
112 ;; Shell virtualenv support: The shell also contains support for
113 ;; virtualenvs and other special environment modifications thanks to
114 ;; `python-shell-process-environment' and `python-shell-exec-path'.
115 ;; These two variables allows you to modify execution paths and
116 ;; environment variables to make easy for you to setup virtualenv rules
117 ;; or behavior modifications when running shells. Here is an example
118 ;; of how to make shell processes to be run using the /path/to/env/
121 ;; (setq python-shell-process-environment
123 ;; (format "PATH=%s" (mapconcat
126 ;; (cons (getenv "PATH")
127 ;; '("/path/to/env/bin/")))
129 ;; "VIRTUAL_ENV=/path/to/env/"))
130 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
132 ;; Since the above is cumbersome and can be programmatically
133 ;; calculated, the variable `python-shell-virtualenv-path' is
134 ;; provided. When this variable is set with the path of the
135 ;; virtualenv to use, `process-environment' and `exec-path' get proper
136 ;; values in order to run shells inside the specified virtualenv. So
137 ;; the following will achieve the same as the previous example:
139 ;; (setq python-shell-virtualenv-path "/path/to/env/")
141 ;; Also the `python-shell-extra-pythonpaths' variable have been
142 ;; introduced as simple way of adding paths to the PYTHONPATH without
143 ;; affecting existing values.
145 ;; Pdb tracking: when you execute a block of code that contains some
146 ;; call to pdb (or ipdb) it will prompt the block of code and will
147 ;; follow the execution of pdb marking the current line with an arrow.
149 ;; Symbol completion: you can complete the symbol at point. It uses
150 ;; the shell completion in background so you should run
151 ;; `python-shell-send-buffer' from time to time to get better results.
153 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
154 ;; def, for, if, try and while. These skeletons are integrated with
155 ;; dabbrev. If you have `dabbrev-mode' activated and
156 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
157 ;; the name of any of those defined and hit SPC, they will be
158 ;; automatically expanded.
160 ;; FFAP: You can find the filename for a given module when using ffap
161 ;; out of the box. This feature needs an inferior python shell
164 ;; Code check: Check the current file for errors with `python-check'
165 ;; using the program defined in `python-check-command'.
167 ;; Eldoc: returns documentation for object at point by using the
168 ;; inferior python subprocess to inspect its documentation. As you
169 ;; might guessed you should run `python-shell-send-buffer' from time
170 ;; to time to get better results too.
172 ;; imenu: This mode supports imenu in its most basic form, letting it
173 ;; build the necessary alist via `imenu-default-create-index-function'
174 ;; by having set `imenu-extract-index-name-function' to
175 ;; `python-info-current-defun'.
177 ;; If you used python-mode.el you probably will miss auto-indentation
178 ;; when inserting newlines. To achieve the same behavior you have
181 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
183 ;; 2) Add the following hook in your .emacs:
185 ;; (add-hook 'python-mode-hook
187 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
189 ;; I'd recommend the first one since you'll get the same behavior for
190 ;; all modes out-of-the-box.
194 ;; Add this to your .emacs:
196 ;; (add-to-list 'load-path "/folder/containing/file")
203 (require 'ansi-color)
205 (eval-when-compile (require 'cl-lib))
207 ;; Avoid compiler warnings
208 (defvar view-return-to-alist)
209 (defvar compilation-error-regexp-alist)
210 (defvar outline-heading-end-regexp)
212 (autoload 'comint-mode "comint")
215 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
217 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
220 "Python Language's flying circus support for Emacs."
223 :link '(emacs-commentary-link "python"))
228 (defvar python-mode-map
229 (let ((map (make-sparse-keymap)))
231 (define-key map [remap backward-sentence] 'python-nav-backward-block)
232 (define-key map [remap forward-sentence] 'python-nav-forward-block)
233 (define-key map [remap backward-up-list] 'python-nav-backward-up-list)
234 (define-key map "\C-c\C-j" 'imenu)
236 (define-key map "\177" 'python-indent-dedent-line-backspace)
237 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
238 (define-key map "\C-c<" 'python-indent-shift-left)
239 (define-key map "\C-c>" 'python-indent-shift-right)
240 (define-key map ":" 'python-indent-electric-colon)
242 (define-key map "\C-c\C-tc" 'python-skeleton-class)
243 (define-key map "\C-c\C-td" 'python-skeleton-def)
244 (define-key map "\C-c\C-tf" 'python-skeleton-for)
245 (define-key map "\C-c\C-ti" 'python-skeleton-if)
246 (define-key map "\C-c\C-tt" 'python-skeleton-try)
247 (define-key map "\C-c\C-tw" 'python-skeleton-while)
249 (define-key map "\C-c\C-p" 'run-python)
250 (define-key map "\C-c\C-s" 'python-shell-send-string)
251 (define-key map "\C-c\C-r" 'python-shell-send-region)
252 (define-key map "\C-\M-x" 'python-shell-send-defun)
253 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
254 (define-key map "\C-c\C-l" 'python-shell-send-file)
255 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
256 ;; Some util commands
257 (define-key map "\C-c\C-v" 'python-check)
258 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
260 (substitute-key-definition 'complete-symbol 'completion-at-point
262 (easy-menu-define python-menu map "Python Mode menu"
264 :help "Python-specific Features"
265 ["Shift region left" python-indent-shift-left :active mark-active
266 :help "Shift region left by a single indentation step"]
267 ["Shift region right" python-indent-shift-right :active mark-active
268 :help "Shift region right by a single indentation step"]
270 ["Start of def/class" beginning-of-defun
271 :help "Go to start of outermost definition around point"]
272 ["End of def/class" end-of-defun
273 :help "Go to end of definition around point"]
274 ["Mark def/class" mark-defun
275 :help "Mark outermost definition around point"]
276 ["Jump to def/class" imenu
277 :help "Jump to a class or function definition"]
281 ["Start interpreter" run-python
282 :help "Run inferior Python process in a separate buffer"]
283 ["Switch to shell" python-shell-switch-to-shell
284 :help "Switch to running inferior Python process"]
285 ["Eval string" python-shell-send-string
286 :help "Eval string in inferior Python session"]
287 ["Eval buffer" python-shell-send-buffer
288 :help "Eval buffer in inferior Python session"]
289 ["Eval region" python-shell-send-region
290 :help "Eval region in inferior Python session"]
291 ["Eval defun" python-shell-send-defun
292 :help "Eval defun in inferior Python session"]
293 ["Eval file" python-shell-send-file
294 :help "Eval file in inferior Python session"]
295 ["Debugger" pdb :help "Run pdb under GUD"]
297 ["Check file" python-check
298 :help "Check file for errors"]
299 ["Help on symbol" python-eldoc-at-point
300 :help "Get help on symbol at point"]
301 ["Complete symbol" completion-at-point
302 :help "Complete symbol before point"]))
304 "Keymap for `python-mode'.")
307 ;;; Python specialized rx
310 (defconst python-rx-constituents
311 `((block-start . ,(rx symbol-start
312 (or "def" "class" "if" "elif" "else" "try"
313 "except" "finally" "for" "while" "with")
315 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
317 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
318 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
319 (+ space) "==" (+ space)
320 (any ?' ?\") "__main__" (any ?' ?\")
322 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
323 (open-paren . ,(rx (or "{" "[" "(")))
324 (close-paren . ,(rx (or "}" "]" ")")))
325 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
326 ;; FIXME: rx should support (not simple-operator).
327 (not-simple-operator . ,(rx
329 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
330 ;; FIXME: Use regexp-opt.
331 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
332 "=" "%" "**" "//" "<<" ">>" "<=" "!="
333 "==" ">=" "is" "not")))
334 ;; FIXME: Use regexp-opt.
335 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
336 ">>=" "<<=" "&=" "^=" "|=")))
337 (string-delimiter . ,(rx (and
338 ;; Match even number of backslashes.
339 (or (not (any ?\\ ?\' ?\")) point
340 ;; Quotes might be preceded by a escaped quote.
341 (and (or (not (any ?\\)) point) ?\\
342 (* ?\\ ?\\) (any ?\' ?\")))
344 ;; Match single or triple quotes of any kind.
345 (group (or "\"" "\"\"\"" "'" "'''"))))))
346 "Additional Python specific sexps for `python-rx'")
348 (defmacro python-rx (&rest regexps)
349 "Python mode specialized rx macro.
350 This variant of `rx' supports common python named REGEXPS."
351 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
352 (cond ((null regexps)
355 (rx-to-string `(and ,@regexps) t))
357 (rx-to-string (car regexps) t))))))
360 ;;; Font-lock and syntax
362 (defun python-syntax-context (type &optional syntax-ppss)
363 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
364 TYPE can be `comment', `string' or `paren'. It returns the start
365 character address of the specified TYPE."
366 (declare (compiler-macro
370 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
371 (and (nth 4 ppss) (nth 8 ppss))))
373 `(let ((ppss (or ,syntax-ppss (syntax-ppss))))
374 (and (nth 3 ppss) (nth 8 ppss))))
376 `(nth 1 (or ,syntax-ppss (syntax-ppss))))
378 (let ((ppss (or syntax-ppss (syntax-ppss))))
380 (`comment (and (nth 4 ppss) (nth 8 ppss)))
381 (`string (and (nth 3 ppss) (nth 8 ppss)))
382 (`paren (nth 1 ppss))
385 (defun python-syntax-context-type (&optional syntax-ppss)
386 "Return the context type using SYNTAX-PPSS.
387 The type returned can be `comment', `string' or `paren'."
388 (let ((ppss (or syntax-ppss (syntax-ppss))))
390 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
391 ((nth 1 ppss) 'paren))))
393 (defsubst python-syntax-comment-or-string-p ()
394 "Return non-nil if point is inside 'comment or 'string."
395 (nth 8 (syntax-ppss)))
397 (define-obsolete-function-alias
398 'python-info-ppss-context #'python-syntax-context "24.3")
400 (define-obsolete-function-alias
401 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
403 (define-obsolete-function-alias
404 'python-info-ppss-comment-or-string-p
405 #'python-syntax-comment-or-string-p "24.3")
407 (defvar python-font-lock-keywords
411 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
412 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
413 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
418 ;; False, None, and True are listed as keywords on the Python 3
419 ;; documentation, but since they also qualify as constants they are
420 ;; fontified like that in order to keep font-lock consistent between
427 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
428 (1 font-lock-function-name-face))
430 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
431 (1 font-lock-type-face))
435 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
436 ;; copyright, license, credits, quit and exit are added by the site
437 ;; module and they are not intended to be used in programs
438 "copyright" "credits" "exit" "license" "quit")
439 symbol-end) . font-lock-constant-face)
441 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
442 (0+ "." (1+ (or word ?_)))))
443 (1 font-lock-type-face))
444 ;; Builtin Exceptions
447 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
448 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
449 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
450 "ImportError" "ImportWarning" "IndexError" "KeyError"
451 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
452 "NotImplementedError" "OSError" "OverflowError"
453 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
454 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
455 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
456 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
457 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
458 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
462 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
464 symbol-end) . font-lock-type-face)
468 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
469 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
470 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
471 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
472 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
473 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
474 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
475 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
478 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
479 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
482 "ascii" "bytearray" "bytes" "exec"
484 "__all__" "__doc__" "__name__" "__package__")
485 symbol-end) . font-lock-builtin-face)
487 ;; support for a = b = c = 5
489 (let ((re (python-rx (group (+ (any word ?. ?_)))
490 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
491 assignment-operator)))
492 (when (re-search-forward re limit t)
493 (while (and (python-syntax-context 'paren)
494 (re-search-forward re limit t)))
495 (if (not (or (python-syntax-context 'paren)
496 (equal (char-after (point-marker)) ?=)))
498 (set-match-data nil)))))
499 (1 font-lock-variable-name-face nil nil))
500 ;; support for a, b, c = (1, 2, 3)
502 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
503 (* ?, (* space) (+ (any word ?. ?_)) (* space))
504 ?, (* space) (+ (any word ?. ?_)) (* space)
505 assignment-operator)))
506 (when (and (re-search-forward re limit t)
507 (goto-char (nth 3 (match-data))))
508 (while (and (python-syntax-context 'paren)
509 (re-search-forward re limit t))
510 (goto-char (nth 3 (match-data))))
511 (if (not (python-syntax-context 'paren))
513 (set-match-data nil)))))
514 (1 font-lock-variable-name-face nil nil))))
516 (defconst python-syntax-propertize-function
517 (syntax-propertize-rules
518 ((python-rx string-delimiter)
519 (0 (ignore (python-syntax-stringify))))))
521 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
522 "Count number of quotes around point (max is 3).
523 QUOTE-CHAR is the quote char to count. Optional argument POINT is
524 the point where scan starts (defaults to current point) and LIMIT
525 is used to limit the scan."
528 (or (not limit) (< (+ point i) limit))
529 (eq (char-after (+ point i)) quote-char))
533 (defun python-syntax-stringify ()
534 "Put `syntax-table' property correctly on single/triple quotes."
535 (let* ((num-quotes (length (match-string-no-properties 1)))
537 (backward-char num-quotes)
539 (forward-char num-quotes)))
540 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
541 (quote-starting-pos (- (point) num-quotes))
542 (quote-ending-pos (point))
545 (python-syntax-count-quotes
546 (char-before) string-start quote-starting-pos))))
547 (cond ((and string-start (= num-closing-quotes 0))
548 ;; This set of quotes doesn't match the string starting
552 ;; This set of quotes delimit the start of a string.
553 (put-text-property quote-starting-pos (1+ quote-starting-pos)
554 'syntax-table (string-to-syntax "|")))
555 ((= num-quotes num-closing-quotes)
556 ;; This set of quotes delimit the end of a string.
557 (put-text-property (1- quote-ending-pos) quote-ending-pos
558 'syntax-table (string-to-syntax "|")))
559 ((> num-quotes num-closing-quotes)
560 ;; This may only happen whenever a triple quote is closing
561 ;; a single quoted string. Add string delimiter syntax to
563 (put-text-property quote-starting-pos quote-ending-pos
564 'syntax-table (string-to-syntax "|"))))))
566 (defvar python-mode-syntax-table
567 (let ((table (make-syntax-table)))
568 ;; Give punctuation syntax to ASCII that normally has symbol
569 ;; syntax or has word syntax and isn't a letter.
570 (let ((symbol (string-to-syntax "_"))
571 (sst (standard-syntax-table)))
574 (if (equal symbol (aref sst i))
575 (modify-syntax-entry i "." table)))))
576 (modify-syntax-entry ?$ "." table)
577 (modify-syntax-entry ?% "." table)
579 (modify-syntax-entry ?# "<" table)
580 (modify-syntax-entry ?\n ">" table)
581 (modify-syntax-entry ?' "\"" table)
582 (modify-syntax-entry ?` "$" table)
584 "Syntax table for Python files.")
586 (defvar python-dotty-syntax-table
587 (let ((table (make-syntax-table python-mode-syntax-table)))
588 (modify-syntax-entry ?. "w" table)
589 (modify-syntax-entry ?_ "w" table)
591 "Dotty syntax table for Python files.
592 It makes underscores and dots word constituent chars.")
597 (defcustom python-indent-offset 4
598 "Default indentation offset for Python."
603 (defcustom python-indent-guess-indent-offset t
604 "Non-nil tells Python mode to guess `python-indent-offset' value."
609 (define-obsolete-variable-alias
610 'python-indent 'python-indent-offset "24.3")
612 (define-obsolete-variable-alias
613 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
615 (defvar python-indent-current-level 0
616 "Current indentation level `python-indent-line-function' is using.")
618 (defvar python-indent-levels '(0)
619 "Levels of indentation available for `python-indent-line-function'.")
621 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
622 "List of words that should be dedented.
623 These make `python-indent-calculate-indentation' subtract the value of
624 `python-indent-offset'.")
626 (defun python-indent-guess-indent-offset ()
627 "Guess and set `python-indent-offset' for the current buffer."
632 (goto-char (point-min))
634 (while (and (not block-end)
636 (python-rx line-start block-start) nil t))
638 (not (python-syntax-context-type))
640 (goto-char (line-end-position))
641 (python-util-forward-comment -1)
642 (if (equal (char-before) ?:)
645 (when (python-info-block-continuation-line-p)
646 (while (and (python-info-continuation-line-p)
649 (python-util-forward-comment -1)
650 (when (equal (char-before) ?:)
652 (setq block-end (point-marker))))
655 (goto-char block-end)
656 (python-util-forward-comment)
657 (current-indentation))))
659 (setq python-indent-offset indentation)
660 (message "Can't guess python-indent-offset, using defaults: %s"
661 python-indent-offset)))))))
663 (defun python-indent-context ()
664 "Get information on indentation context.
665 Context information is returned with a cons with the form:
668 Where status can be any of the following symbols:
669 * inside-paren: If point in between (), {} or []
670 * inside-string: If point is inside a string
671 * after-backslash: Previous line ends in a backslash
672 * after-beginning-of-block: Point is after beginning of block
673 * after-line: Point is after normal line
674 * no-indent: Point is at beginning of buffer or other special case
675 START is the buffer position where the sexp starts."
678 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
682 ;; Beginning of buffer
684 (goto-char (line-beginning-position))
688 ((setq start (python-syntax-context 'string ppss))
691 ((setq start (python-syntax-context 'paren ppss))
694 ((setq start (when (not (or (python-syntax-context 'string ppss)
695 (python-syntax-context 'comment ppss)))
696 (let ((line-beg-pos (line-beginning-position)))
697 (when (python-info-line-ends-backslash-p
699 (- line-beg-pos 2)))))
701 ;; After beginning of block
702 ((setq start (save-excursion
704 (back-to-indentation)
705 (python-util-forward-comment -1)
706 (equal (char-before) ?:))
707 ;; Move to the first block start that's not in within
708 ;; a string, comment or paren and that's not a
709 ;; continuation line.
710 (while (and (re-search-backward
711 (python-rx block-start) nil t)
713 (python-syntax-context-type)
714 (python-info-continuation-line-p))))
715 (when (looking-at (python-rx block-start))
717 'after-beginning-of-block)
719 ((setq start (save-excursion
720 (back-to-indentation)
721 (skip-chars-backward (rx (or whitespace ?\n)))
722 (python-nav-beginning-of-statement)
729 (defun python-indent-calculate-indentation ()
730 "Calculate correct indentation offset for the current line."
731 (let* ((indentation-context (python-indent-context))
732 (context-status (car indentation-context))
733 (context-start (cdr indentation-context)))
737 (pcase context-status
739 ;; When point is after beginning of block just add one level
740 ;; of indentation relative to the context-start
741 (`after-beginning-of-block
742 (goto-char context-start)
743 (+ (current-indentation) python-indent-offset))
744 ;; When after a simple line just use previous line
745 ;; indentation, in the case current line starts with a
746 ;; `python-indent-dedenters' de-indent one level.
750 (goto-char context-start)
751 (current-indentation))
753 (back-to-indentation)
754 (looking-at (regexp-opt python-indent-dedenters)))
757 ;; When inside of a string, do nothing. just use the current
758 ;; indentation. XXX: perhaps it would be a good idea to
759 ;; invoke standard text indentation here
761 (goto-char context-start)
762 (current-indentation))
763 ;; After backslash we have several possibilities.
766 ;; Check if current line is a dot continuation. For this
767 ;; the current line must start with a dot and previous
768 ;; line must contain a dot too.
770 (back-to-indentation)
771 (when (looking-at "\\.")
772 ;; If after moving one line back point is inside a paren it
773 ;; needs to move back until it's not anymore
777 (python-syntax-context 'paren))))
778 (goto-char (line-end-position))
779 (while (and (re-search-backward
780 "\\." (line-beginning-position) t)
781 (python-syntax-context-type)))
782 (if (and (looking-at "\\.")
783 (not (python-syntax-context-type)))
784 ;; The indentation is the same column of the
785 ;; first matching dot that's not inside a
786 ;; comment, a string or a paren
788 ;; No dot found on previous line, just add another
789 ;; indentation level.
790 (+ (current-indentation) python-indent-offset)))))
791 ;; Check if prev line is a block continuation
792 ((let ((block-continuation-start
793 (python-info-block-continuation-line-p)))
794 (when block-continuation-start
795 ;; If block-continuation-start is set jump to that
796 ;; marker and use first column after the block start
797 ;; as indentation value.
798 (goto-char block-continuation-start)
800 (python-rx block-start (* space))
801 (line-end-position) t)
803 ;; Check if current line is an assignment continuation
804 ((let ((assignment-continuation-start
805 (python-info-assignment-continuation-line-p)))
806 (when assignment-continuation-start
807 ;; If assignment-continuation is set jump to that
808 ;; marker and use first column after the assignment
809 ;; operator as indentation value.
810 (goto-char assignment-continuation-start)
814 (goto-char (python-info-beginning-of-backslash))
819 (or (python-info-beginning-of-backslash) (point)))
820 (python-info-line-ends-backslash-p)))
821 ;; The two previous lines ended in a backslash so we must
822 ;; respect previous line indentation.
823 (current-indentation)
824 ;; What happens here is that we are dealing with the second
825 ;; line of a backslash continuation, in that case we just going
826 ;; to add one indentation level.
827 (+ (current-indentation) python-indent-offset)))))
828 ;; When inside a paren there's a need to handle nesting
832 ;; If current line closes the outermost open paren use the
833 ;; current indentation of the context-start line.
835 (skip-syntax-forward "\s" (line-end-position))
836 (when (and (looking-at (regexp-opt '(")" "]" "}")))
839 (not (python-syntax-context 'paren))))
840 (goto-char context-start)
841 (current-indentation))))
842 ;; If open paren is contained on a line by itself add another
843 ;; indentation level, else look for the first word after the
844 ;; opening paren and use it's column position as indentation
846 ((let* ((content-starts-in-newline)
849 (if (setq content-starts-in-newline
851 (goto-char context-start)
855 (line-beginning-position)
857 (python-util-forward-comment))
859 (+ (current-indentation) python-indent-offset)
863 ;; If current line closes a nested open paren de-indent one
866 (back-to-indentation)
867 (looking-at (regexp-opt '(")" "]" "}"))))
868 (- indent python-indent-offset))
869 ;; If the line of the opening paren that wraps the current
870 ;; line starts a block add another level of indentation to
871 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
873 (when (and content-starts-in-newline
875 (goto-char context-start)
876 (back-to-indentation)
877 (looking-at (python-rx block-start))))
878 (+ indent python-indent-offset))))
881 (defun python-indent-calculate-levels ()
882 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
883 (let* ((indentation (python-indent-calculate-indentation))
884 (remainder (% indentation python-indent-offset))
885 (steps (/ (- indentation remainder) python-indent-offset)))
886 (setq python-indent-levels (list 0))
887 (dotimes (step steps)
888 (push (* python-indent-offset (1+ step)) python-indent-levels))
889 (when (not (eq 0 remainder))
890 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
891 (setq python-indent-levels (nreverse python-indent-levels))
892 (setq python-indent-current-level (1- (length python-indent-levels)))))
894 (defun python-indent-toggle-levels ()
895 "Toggle `python-indent-current-level' over `python-indent-levels'."
896 (setq python-indent-current-level (1- python-indent-current-level))
897 (when (< python-indent-current-level 0)
898 (setq python-indent-current-level (1- (length python-indent-levels)))))
900 (defun python-indent-line (&optional force-toggle)
901 "Internal implementation of `python-indent-line-function'.
902 Uses the offset calculated in
903 `python-indent-calculate-indentation' and available levels
904 indicated by the variable `python-indent-levels' to set the
907 When the variable `last-command' is equal to
908 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
909 levels indicated in the variable `python-indent-levels' by
910 setting the current level in the variable
911 `python-indent-current-level'.
913 When the variable `last-command' is not equal to
914 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
915 possible indentation levels and saves it in the variable
916 `python-indent-levels'. Afterwards it sets the variable
917 `python-indent-current-level' correctly so offset is equal
918 to (`nth' `python-indent-current-level' `python-indent-levels')"
920 (and (or (and (eq this-command 'indent-for-tab-command)
921 (eq last-command this-command))
923 (not (equal python-indent-levels '(0)))
924 (or (python-indent-toggle-levels) t))
925 (python-indent-calculate-levels))
926 (let* ((starting-pos (point-marker))
927 (indent-ending-position
928 (+ (line-beginning-position) (current-indentation)))
929 (follow-indentation-p
931 (and (<= (line-beginning-position) starting-pos)
932 (>= indent-ending-position starting-pos))))
933 (next-indent (nth python-indent-current-level python-indent-levels)))
934 (unless (= next-indent (current-indentation))
936 (delete-horizontal-space)
937 (indent-to next-indent)
938 (goto-char starting-pos))
939 (and follow-indentation-p (back-to-indentation)))
940 (python-info-closing-block-message))
942 (defun python-indent-line-function ()
943 "`indent-line-function' for Python mode.
944 See `python-indent-line' for details."
945 (python-indent-line))
947 (defun python-indent-dedent-line ()
948 "De-indent current line."
950 (when (and (not (python-syntax-comment-or-string-p))
951 (<= (point-marker) (save-excursion
952 (back-to-indentation)
954 (> (current-column) 0))
955 (python-indent-line t)
958 (defun python-indent-dedent-line-backspace (arg)
959 "De-indent current line.
960 Argument ARG is passed to `backward-delete-char-untabify' when
961 point is not in between the indentation."
963 (when (not (python-indent-dedent-line))
964 (backward-delete-char-untabify arg)))
965 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
967 (defun python-indent-region (start end)
968 "Indent a python region automagically.
970 Called from a program, START and END specify the region to indent."
971 (let ((deactivate-mark nil))
974 (setq end (point-marker))
976 (or (bolp) (forward-line 1))
977 (while (< (point) end)
978 (or (and (bolp) (eolp))
981 (back-to-indentation)
982 (setq word (current-word))
985 ;; Don't mess with strings, unless it's the
986 ;; enclosing set of quotes.
987 (or (not (python-syntax-context 'string))
991 (current-indentation)
992 (python-syntax-count-quotes (char-after) (point))))
993 (string-to-syntax "|"))))
995 (delete-horizontal-space)
996 (indent-to (python-indent-calculate-indentation)))))
998 (move-marker end nil))))
1000 (defun python-indent-shift-left (start end &optional count)
1001 "Shift lines contained in region START END by COUNT columns to the left.
1002 COUNT defaults to `python-indent-offset'. If region isn't
1003 active, the current line is shifted. The shifted region includes
1004 the lines in which START and END lie. An error is signaled if
1005 any lines in the region are indented less than COUNT columns."
1008 (list (region-beginning) (region-end) current-prefix-arg)
1009 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1011 (setq count (prefix-numeric-value count))
1012 (setq count python-indent-offset))
1014 (let ((deactivate-mark nil))
1017 (while (< (point) end)
1018 (if (and (< (current-indentation) count)
1019 (not (looking-at "[ \t]*$")))
1020 (error "Can't shift all lines enough"))
1022 (indent-rigidly start end (- count))))))
1024 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1026 (defun python-indent-shift-right (start end &optional count)
1027 "Shift lines contained in region START END by COUNT columns to the left.
1028 COUNT defaults to `python-indent-offset'. If region isn't
1029 active, the current line is shifted. The shifted region includes
1030 the lines in which START and END lie."
1033 (list (region-beginning) (region-end) current-prefix-arg)
1034 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1035 (let ((deactivate-mark nil))
1037 (setq count (prefix-numeric-value count))
1038 (setq count python-indent-offset))
1039 (indent-rigidly start end count)))
1041 (defun python-indent-electric-colon (arg)
1042 "Insert a colon and maybe de-indent the current line.
1043 With numeric ARG, just insert that many colons. With
1044 \\[universal-argument], just insert a single colon."
1046 (self-insert-command (if (not (integerp arg)) 1 arg))
1047 (when (and (not arg)
1049 (not (equal ?: (char-after (- (point-marker) 2))))
1050 (not (python-syntax-comment-or-string-p)))
1051 (let ((indentation (current-indentation))
1052 (calculated-indentation (python-indent-calculate-indentation)))
1053 (python-info-closing-block-message)
1054 (when (> indentation calculated-indentation)
1056 (indent-line-to calculated-indentation)
1057 (when (not (python-info-closing-block-message))
1058 (indent-line-to indentation)))))))
1059 (put 'python-indent-electric-colon 'delete-selection t)
1061 (defun python-indent-post-self-insert-function ()
1062 "Adjust closing paren line indentation after a char is added.
1063 This function is intended to be added to the
1064 `post-self-insert-hook.' If a line renders a paren alone, after
1065 adding a char before it, the line will be re-indented
1066 automatically if needed."
1067 (when (and (eq (char-before) last-command-event)
1069 (memq (char-after) '(?\) ?\] ?\})))
1071 (goto-char (line-beginning-position))
1072 ;; If after going to the beginning of line the point
1073 ;; is still inside a paren it's ok to do the trick
1074 (when (python-syntax-context 'paren)
1075 (let ((indentation (python-indent-calculate-indentation)))
1076 (when (< (current-indentation) indentation)
1077 (indent-line-to indentation)))))))
1082 (defvar python-nav-beginning-of-defun-regexp
1083 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1084 "Regexp matching class or function definition.
1085 The name of the defun should be grouped so it can be retrieved
1086 via `match-string'.")
1088 (defun python-nav--beginning-of-defun (&optional arg)
1089 "Internal implementation of `python-nav-beginning-of-defun'.
1090 With positive ARG search backwards, else search forwards."
1091 (when (or (null arg) (= arg 0)) (setq arg 1))
1092 (let* ((re-search-fn (if (> arg 0)
1093 #'re-search-backward
1094 #'re-search-forward))
1095 (line-beg-pos (line-beginning-position))
1096 (line-content-start (+ line-beg-pos (current-indentation)))
1097 (pos (point-marker))
1101 (and (python-info-current-line-empty-p)
1102 (python-util-forward-comment -1))
1103 (python-nav-beginning-of-statement)
1104 (if (python-info-looking-at-beginning-of-defun)
1105 (+ (current-indentation) python-indent-offset)
1106 (current-indentation)))))
1109 (when (and (< arg 0)
1110 (python-info-looking-at-beginning-of-defun))
1112 (while (and (funcall re-search-fn
1113 python-nav-beginning-of-defun-regexp nil t)
1114 (or (python-syntax-context-type)
1115 ;; Handle nested defuns when moving
1116 ;; backwards by checking indentation.
1118 (not (= (current-indentation) 0))
1119 (>= (current-indentation) beg-indentation)))))
1120 (and (python-info-looking-at-beginning-of-defun)
1121 (or (not (= (line-number-at-pos pos)
1122 (line-number-at-pos)))
1123 (and (>= (point) line-beg-pos)
1124 (<= (point) line-content-start)
1125 (> pos line-content-start)))))))
1127 (or (beginning-of-line 1) t)
1128 (and (goto-char pos) nil))))
1130 (defun python-nav-beginning-of-defun (&optional arg)
1131 "Move point to `beginning-of-defun'.
1132 With positive ARG search backwards else search forward. When ARG
1133 is nil or 0 defaults to 1. When searching backwards nested
1134 defuns are handled with care depending on current point
1135 position. Return non-nil if point is moved to
1136 `beginning-of-defun'."
1137 (when (or (null arg) (= arg 0)) (setq arg 1))
1139 (cond ((and (eq this-command 'mark-defun)
1140 (python-info-looking-at-beginning-of-defun)))
1142 (dotimes (i (if (> arg 0) arg (- arg)))
1143 (when (and (python-nav--beginning-of-defun arg)
1148 (defun python-nav-end-of-defun ()
1149 "Move point to the end of def or class.
1150 Returns nil if point is not in a def or class."
1152 (let ((beg-defun-indent)
1154 (when (or (python-info-looking-at-beginning-of-defun)
1155 (python-nav-beginning-of-defun 1)
1156 (python-nav-beginning-of-defun -1))
1157 (setq beg-defun-indent (current-indentation))
1159 (python-nav-end-of-statement)
1160 (python-util-forward-comment 1)
1161 (and (> (current-indentation) beg-defun-indent)
1163 (python-util-forward-comment -1)
1165 ;; Ensure point moves forward.
1166 (and (> beg-pos (point)) (goto-char beg-pos)))))
1168 (defun python-nav-beginning-of-statement ()
1169 "Move to start of current statement."
1171 (while (and (or (back-to-indentation) t)
1176 (python-info-line-ends-backslash-p))
1177 (python-syntax-context 'string)
1178 (python-syntax-context 'paren))
1179 (forward-line -1))))
1182 (defun python-nav-end-of-statement ()
1183 "Move to end of current statement."
1185 (while (and (goto-char (line-end-position))
1188 (python-info-line-ends-backslash-p)
1189 (python-syntax-context 'string)
1190 (python-syntax-context 'paren))
1194 (defun python-nav-backward-statement (&optional arg)
1195 "Move backward to previous statement.
1196 With ARG, repeat. See `python-nav-forward-statement'."
1198 (or arg (setq arg 1))
1199 (python-nav-forward-statement (- arg)))
1201 (defun python-nav-forward-statement (&optional arg)
1202 "Move forward to next statement.
1203 With ARG, repeat. With negative argument, move ARG times
1204 backward to previous statement."
1206 (or arg (setq arg 1))
1208 (python-nav-end-of-statement)
1209 (python-util-forward-comment)
1210 (python-nav-beginning-of-statement)
1211 (setq arg (1- arg)))
1213 (python-nav-beginning-of-statement)
1214 (python-util-forward-comment -1)
1215 (python-nav-beginning-of-statement)
1216 (setq arg (1+ arg))))
1218 (defun python-nav-beginning-of-block ()
1219 "Move to start of current block."
1221 (let ((starting-pos (point))
1222 (block-regexp (python-rx
1223 line-start (* whitespace) block-start)))
1225 (python-nav-beginning-of-statement)
1226 (looking-at (python-rx block-start)))
1228 ;; Go to first line beginning a statement
1229 (while (and (not (bobp))
1230 (or (and (python-nav-beginning-of-statement) nil)
1231 (python-info-current-line-comment-p)
1232 (python-info-current-line-empty-p)))
1234 (let ((block-matching-indent
1235 (- (current-indentation) python-indent-offset)))
1237 (and (python-nav-backward-block)
1238 (> (current-indentation) block-matching-indent)))
1239 (if (and (looking-at (python-rx block-start))
1240 (= (current-indentation) block-matching-indent))
1242 (and (goto-char starting-pos) nil))))))
1244 (defun python-nav-end-of-block ()
1245 "Move to end of current block."
1247 (when (python-nav-beginning-of-block)
1248 (let ((block-indentation (current-indentation)))
1249 (python-nav-end-of-statement)
1250 (while (and (forward-line 1)
1252 (or (and (> (current-indentation) block-indentation)
1253 (or (python-nav-end-of-statement) t))
1254 (python-info-current-line-comment-p)
1255 (python-info-current-line-empty-p))))
1256 (python-util-forward-comment -1)
1259 (defun python-nav-backward-block (&optional arg)
1260 "Move backward to previous block of code.
1261 With ARG, repeat. See `python-nav-forward-block'."
1263 (or arg (setq arg 1))
1264 (python-nav-forward-block (- arg)))
1266 (defun python-nav-forward-block (&optional arg)
1267 "Move forward to next block of code.
1268 With ARG, repeat. With negative argument, move ARG times
1269 backward to previous block."
1271 (or arg (setq arg 1))
1272 (let ((block-start-regexp
1273 (python-rx line-start (* whitespace) block-start))
1274 (starting-pos (point)))
1276 (python-nav-end-of-statement)
1278 (re-search-forward block-start-regexp nil t)
1279 (python-syntax-context-type)))
1280 (setq arg (1- arg)))
1282 (python-nav-beginning-of-statement)
1284 (re-search-backward block-start-regexp nil t)
1285 (python-syntax-context-type)))
1286 (setq arg (1+ arg)))
1287 (python-nav-beginning-of-statement)
1288 (if (not (looking-at (python-rx block-start)))
1289 (and (goto-char starting-pos) nil)
1290 (and (not (= (point) starting-pos)) (point-marker)))))
1292 (defun python-nav-lisp-forward-sexp-safe (&optional arg)
1293 "Safe version of standard `forward-sexp'.
1294 When ARG > 0 move forward, else if ARG is < 0."
1295 (or arg (setq arg 1))
1296 (let ((forward-sexp-function nil)
1298 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1300 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1304 (while (and (funcall search-fn paren-regexp nil t)
1305 (python-syntax-context 'paren)))))))
1307 (defun python-nav--forward-sexp (&optional dir)
1308 "Move to forward sexp.
1309 With positive Optional argument DIR direction move forward, else
1311 (setq dir (or dir 1))
1313 (let* ((forward-p (if (> dir 0)
1314 (and (setq dir 1) t)
1315 (and (setq dir -1) nil)))
1316 (re-search-fn (if forward-p
1318 're-search-backward))
1319 (context-type (python-syntax-context-type)))
1321 ((eq context-type 'string)
1322 ;; Inside of a string, get out of it.
1323 (while (and (funcall re-search-fn "[\"']" nil t)
1324 (python-syntax-context 'string))))
1325 ((eq context-type 'comment)
1326 ;; Inside of a comment, just move forward.
1327 (python-util-forward-comment dir))
1328 ((or (eq context-type 'paren)
1329 (and forward-p (looking-at (python-rx open-paren)))
1330 (and (not forward-p)
1331 (eq (syntax-class (syntax-after (1- (point))))
1332 (car (string-to-syntax ")")))))
1333 ;; Inside a paren or looking at it, lisp knows what to do.
1334 (python-nav-lisp-forward-sexp-safe dir))
1336 ;; This part handles the lispy feel of
1337 ;; `python-nav-forward-sexp'. Knowing everything about the
1338 ;; current context and the context of the next sexp tries to
1339 ;; follow the lisp sexp motion commands in a symmetric manner.
1342 ((python-info-beginning-of-block-p) 'block-start)
1343 ((python-info-end-of-block-p) 'block-end)
1344 ((python-info-beginning-of-statement-p) 'statement-start)
1345 ((python-info-end-of-statement-p) 'statement-end)))
1348 (python-nav-lisp-forward-sexp-safe dir)
1352 (goto-char next-sexp-pos)
1354 ((python-info-beginning-of-block-p) 'block-start)
1355 ((python-info-end-of-block-p) 'block-end)
1356 ((python-info-beginning-of-statement-p) 'statement-start)
1357 ((python-info-end-of-statement-p) 'statement-end)
1358 ((python-info-statement-starts-block-p) 'starts-block)
1359 ((python-info-statement-ends-block-p) 'ends-block)))))
1361 (cond ((and (not (eobp))
1362 (python-info-current-line-empty-p))
1363 (python-util-forward-comment dir)
1364 (python-nav--forward-sexp dir))
1365 ((eq context 'block-start)
1366 (python-nav-end-of-block))
1367 ((eq context 'statement-start)
1368 (python-nav-end-of-statement))
1369 ((and (memq context '(statement-end block-end))
1370 (eq next-sexp-context 'ends-block))
1371 (goto-char next-sexp-pos)
1372 (python-nav-end-of-block))
1373 ((and (memq context '(statement-end block-end))
1374 (eq next-sexp-context 'starts-block))
1375 (goto-char next-sexp-pos)
1376 (python-nav-end-of-block))
1377 ((memq context '(statement-end block-end))
1378 (goto-char next-sexp-pos)
1379 (python-nav-end-of-statement))
1380 (t (goto-char next-sexp-pos)))
1381 (cond ((and (not (bobp))
1382 (python-info-current-line-empty-p))
1383 (python-util-forward-comment dir)
1384 (python-nav--forward-sexp dir))
1385 ((eq context 'block-end)
1386 (python-nav-beginning-of-block))
1387 ((eq context 'statement-end)
1388 (python-nav-beginning-of-statement))
1389 ((and (memq context '(statement-start block-start))
1390 (eq next-sexp-context 'starts-block))
1391 (goto-char next-sexp-pos)
1392 (python-nav-beginning-of-block))
1393 ((and (memq context '(statement-start block-start))
1394 (eq next-sexp-context 'ends-block))
1395 (goto-char next-sexp-pos)
1396 (python-nav-beginning-of-block))
1397 ((memq context '(statement-start block-start))
1398 (goto-char next-sexp-pos)
1399 (python-nav-beginning-of-statement))
1400 (t (goto-char next-sexp-pos))))))))))
1402 (defun python-nav--backward-sexp ()
1403 "Move to backward sexp."
1404 (python-nav--forward-sexp -1))
1406 (defun python-nav-forward-sexp (&optional arg)
1407 "Move forward across one block of code.
1408 With ARG, do it that many times. Negative arg -N means
1409 move backward N times."
1411 (or arg (setq arg 1))
1413 (python-nav--forward-sexp)
1414 (setq arg (1- arg)))
1416 (python-nav--backward-sexp)
1417 (setq arg (1+ arg))))
1419 (defun python-nav--up-list (&optional dir)
1420 "Internal implementation of `python-nav-up-list'.
1421 DIR is always 1 or -1 and comes sanitized from
1422 `python-nav-up-list' calls."
1423 (let ((context (python-syntax-context-type))
1424 (forward-p (> dir 0)))
1426 ((memq context '(string comment)))
1427 ((eq context 'paren)
1428 (let ((forward-sexp-function))
1430 ((and forward-p (python-info-end-of-block-p))
1431 (let ((parent-end-pos
1433 (let ((indentation (and
1434 (python-nav-beginning-of-block)
1435 (current-indentation))))
1436 (while (and indentation
1438 (>= (current-indentation) indentation)
1439 (python-nav-backward-block)))
1440 (python-nav-end-of-block)))))
1441 (and (> (or parent-end-pos (point)) (point))
1442 (goto-char parent-end-pos))))
1443 (forward-p (python-nav-end-of-block))
1444 ((and (not forward-p)
1445 (> (current-indentation) 0)
1446 (python-info-beginning-of-block-p))
1447 (let ((prev-block-pos
1449 (let ((indentation (current-indentation)))
1450 (while (and (python-nav-backward-block)
1451 (>= (current-indentation) indentation))))
1453 (and (> (point) prev-block-pos)
1454 (goto-char prev-block-pos))))
1455 ((not forward-p) (python-nav-beginning-of-block)))))
1457 (defun python-nav-up-list (&optional arg)
1458 "Move forward out of one level of parentheses (or blocks).
1459 With ARG, do this that many times.
1460 A negative argument means move backward but still to a less deep spot.
1461 This command assumes point is not in a string or comment."
1463 (or arg (setq arg 1))
1465 (python-nav--up-list 1)
1466 (setq arg (1- arg)))
1468 (python-nav--up-list -1)
1469 (setq arg (1+ arg))))
1471 (defun python-nav-backward-up-list (&optional arg)
1472 "Move backward out of one level of parentheses (or blocks).
1473 With ARG, do this that many times.
1474 A negative argument means move backward but still to a less deep spot.
1475 This command assumes point is not in a string or comment."
1477 (or arg (setq arg 1))
1478 (python-nav-up-list (- arg)))
1481 ;;; Shell integration
1483 (defcustom python-shell-buffer-name "Python"
1484 "Default buffer name for Python interpreter."
1489 (defcustom python-shell-interpreter "python"
1490 "Default Python interpreter for shell."
1494 (defcustom python-shell-internal-buffer-name "Python Internal"
1495 "Default buffer name for the Internal Python interpreter."
1500 (defcustom python-shell-interpreter-args "-i"
1501 "Default arguments for the Python interpreter."
1505 (defcustom python-shell-prompt-regexp ">>> "
1506 "Regular Expression matching top\-level input prompt of python shell.
1507 It should not contain a caret (^) at the beginning."
1512 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1513 "Regular Expression matching block input prompt of python shell.
1514 It should not contain a caret (^) at the beginning."
1519 (defcustom python-shell-prompt-output-regexp ""
1520 "Regular Expression matching output prompt of python shell.
1521 It should not contain a caret (^) at the beginning."
1526 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1527 "Regular Expression matching pdb input prompt of python shell.
1528 It should not contain a caret (^) at the beginning."
1533 (defcustom python-shell-enable-font-lock t
1534 "Should syntax highlighting be enabled in the python shell buffer?
1535 Restart the python shell after changing this variable for it to take effect."
1540 (defcustom python-shell-process-environment nil
1541 "List of environment variables for Python shell.
1542 This variable follows the same rules as `process-environment'
1543 since it merges with it before the process creation routines are
1544 called. When this variable is nil, the Python shell is run with
1545 the default `process-environment'."
1546 :type '(repeat string)
1550 (defcustom python-shell-extra-pythonpaths nil
1551 "List of extra pythonpaths for Python shell.
1552 The values of this variable are added to the existing value of
1553 PYTHONPATH in the `process-environment' variable."
1554 :type '(repeat string)
1558 (defcustom python-shell-exec-path nil
1559 "List of path to search for binaries.
1560 This variable follows the same rules as `exec-path' since it
1561 merges with it before the process creation routines are called.
1562 When this variable is nil, the Python shell is run with the
1563 default `exec-path'."
1564 :type '(repeat string)
1568 (defcustom python-shell-virtualenv-path nil
1569 "Path to virtualenv root.
1570 This variable, when set to a string, makes the values stored in
1571 `python-shell-process-environment' and `python-shell-exec-path'
1572 to be modified properly so shells are started with the specified
1578 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1579 python-ffap-setup-code
1580 python-eldoc-setup-code)
1581 "List of code run by `python-shell-send-setup-codes'."
1582 :type '(repeat symbol)
1586 (defcustom python-shell-compilation-regexp-alist
1587 `((,(rx line-start (1+ (any " \t")) "File \""
1588 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1589 "\", line " (group (1+ digit)))
1591 (,(rx " in file " (group (1+ not-newline)) " on line "
1594 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1595 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1597 "`compilation-error-regexp-alist' for inferior Python."
1598 :type '(alist string)
1601 (defun python-shell-get-process-name (dedicated)
1602 "Calculate the appropriate process name for inferior Python process.
1603 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1604 returns a string with the form
1605 `python-shell-buffer-name'[variable `buffer-file-name'] else
1606 returns the value of `python-shell-buffer-name'."
1610 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1611 (format "%s" python-shell-buffer-name))))
1614 (defun python-shell-internal-get-process-name ()
1615 "Calculate the appropriate process name for Internal Python process.
1616 The name is calculated from `python-shell-global-buffer-name' and
1617 a hash of all relevant global shell settings in order to ensure
1618 uniqueness for different types of configurations."
1620 python-shell-internal-buffer-name
1623 (python-shell-parse-command)
1624 python-shell-prompt-regexp
1625 python-shell-prompt-block-regexp
1626 python-shell-prompt-output-regexp
1627 (mapconcat #'symbol-value python-shell-setup-codes "")
1628 (mapconcat #'identity python-shell-process-environment "")
1629 (mapconcat #'identity python-shell-extra-pythonpaths "")
1630 (mapconcat #'identity python-shell-exec-path "")
1631 (or python-shell-virtualenv-path "")
1632 (mapconcat #'identity python-shell-exec-path "")))))
1634 (defun python-shell-parse-command ()
1635 "Calculate the string used to execute the inferior Python process."
1636 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1638 (defun python-shell-calculate-process-environment ()
1639 "Calculate process environment given `python-shell-virtualenv-path'."
1640 (let ((process-environment (append
1641 python-shell-process-environment
1642 process-environment nil))
1643 (virtualenv (if python-shell-virtualenv-path
1644 (directory-file-name python-shell-virtualenv-path)
1646 (when python-shell-extra-pythonpaths
1647 (setenv "PYTHONPATH"
1649 (mapconcat 'identity
1650 python-shell-extra-pythonpaths
1653 (or (getenv "PYTHONPATH") ""))))
1654 (if (not virtualenv)
1656 (setenv "PYTHONHOME" nil)
1657 (setenv "PATH" (format "%s/bin%s%s"
1658 virtualenv path-separator
1659 (or (getenv "PATH") "")))
1660 (setenv "VIRTUAL_ENV" virtualenv))
1661 process-environment))
1663 (defun python-shell-calculate-exec-path ()
1664 "Calculate exec path given `python-shell-virtualenv-path'."
1665 (let ((path (append python-shell-exec-path
1667 (if (not python-shell-virtualenv-path)
1669 (cons (format "%s/bin"
1670 (directory-file-name python-shell-virtualenv-path))
1673 (defun python-comint-output-filter-function (output)
1674 "Hook run after content is put into comint buffer.
1675 OUTPUT is a string with the contents of the buffer."
1676 (ansi-color-filter-apply output))
1678 (defvar python-shell--parent-buffer nil)
1680 (defvar python-shell-output-syntax-table
1681 (let ((table (make-syntax-table python-dotty-syntax-table)))
1682 (modify-syntax-entry ?\' "." table)
1683 (modify-syntax-entry ?\" "." table)
1684 (modify-syntax-entry ?\( "." table)
1685 (modify-syntax-entry ?\[ "." table)
1686 (modify-syntax-entry ?\{ "." table)
1687 (modify-syntax-entry ?\) "." table)
1688 (modify-syntax-entry ?\] "." table)
1689 (modify-syntax-entry ?\} "." table)
1691 "Syntax table for shell output.
1692 It makes parens and quotes be treated as punctuation chars.")
1694 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1695 "Major mode for Python inferior process.
1696 Runs a Python interpreter as a subprocess of Emacs, with Python
1697 I/O through an Emacs buffer. Variables
1698 `python-shell-interpreter' and `python-shell-interpreter-args'
1699 controls which Python interpreter is run. Variables
1700 `python-shell-prompt-regexp',
1701 `python-shell-prompt-output-regexp',
1702 `python-shell-prompt-block-regexp',
1703 `python-shell-enable-font-lock',
1704 `python-shell-completion-setup-code',
1705 `python-shell-completion-string-code',
1706 `python-shell-completion-module-string-code',
1707 `python-eldoc-setup-code', `python-eldoc-string-code',
1708 `python-ffap-setup-code' and `python-ffap-string-code' can
1709 customize this mode for different Python interpreters.
1711 You can also add additional setup code to be run at
1712 initialization of the interpreter via `python-shell-setup-codes'
1715 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1716 (and python-shell--parent-buffer
1717 (python-util-clone-local-variables python-shell--parent-buffer))
1718 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1719 python-shell-prompt-regexp
1720 python-shell-prompt-block-regexp
1721 python-shell-prompt-pdb-regexp))
1722 (setq mode-line-process '(":%s"))
1723 (make-local-variable 'comint-output-filter-functions)
1724 (add-hook 'comint-output-filter-functions
1725 'python-comint-output-filter-function)
1726 (add-hook 'comint-output-filter-functions
1727 'python-pdbtrack-comint-output-filter-function)
1728 (set (make-local-variable 'compilation-error-regexp-alist)
1729 python-shell-compilation-regexp-alist)
1730 (define-key inferior-python-mode-map [remap complete-symbol]
1731 'completion-at-point)
1732 (add-hook 'completion-at-point-functions
1733 'python-shell-completion-complete-at-point nil 'local)
1734 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1735 'python-shell-completion-complete-at-point)
1736 (define-key inferior-python-mode-map "\t"
1737 'python-shell-completion-complete-or-indent)
1738 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1739 (make-local-variable 'python-pdbtrack-tracked-buffer)
1740 (make-local-variable 'python-shell-internal-last-output)
1741 (when python-shell-enable-font-lock
1742 (set-syntax-table python-mode-syntax-table)
1743 (set (make-local-variable 'font-lock-defaults)
1744 '(python-font-lock-keywords nil nil nil nil))
1745 (set (make-local-variable 'syntax-propertize-function)
1747 ;; XXX: Unfortunately eval is needed here to make use of the
1748 ;; dynamic value of `comint-prompt-regexp'.
1749 `(syntax-propertize-rules
1750 (,comint-prompt-regexp
1753 comint-last-input-start end 'syntax-table
1754 python-shell-output-syntax-table)
1755 ;; XXX: This might look weird, but it is the easiest
1756 ;; way to ensure font lock gets cleaned up before the
1757 ;; current prompt, which is needed for unclosed
1758 ;; strings to not mess up with current input.
1759 (font-lock-unfontify-region comint-last-input-start end))))
1760 (,(python-rx string-delimiter)
1762 (and (not (eq (get-text-property start 'field) 'output))
1763 (python-syntax-stringify)))))))))
1764 (compilation-shell-minor-mode 1))
1766 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
1767 "Create a python shell comint buffer.
1768 CMD is the python command to be executed and PROC-NAME is the
1769 process name the comint buffer will get. After the comint buffer
1770 is created the `inferior-python-mode' is activated. When
1771 optional argument POP is non-nil the buffer is shown. When
1772 optional argument INTERNAL is non-nil this process is run on a
1773 buffer with a name that starts with a space, following the Emacs
1774 convention for temporary/internal buffers, and also makes sure
1775 the user is not queried for confirmation when the process is
1778 (let* ((proc-buffer-name
1779 (format (if (not internal) "*%s*" " *%s*") proc-name))
1780 (process-environment (python-shell-calculate-process-environment))
1781 (exec-path (python-shell-calculate-exec-path)))
1782 (when (not (comint-check-proc proc-buffer-name))
1783 (let* ((cmdlist (split-string-and-unquote cmd))
1784 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1785 (car cmdlist) nil (cdr cmdlist)))
1786 (python-shell--parent-buffer (current-buffer))
1787 (process (get-buffer-process buffer)))
1788 (with-current-buffer buffer
1789 (inferior-python-mode))
1790 (accept-process-output process)
1791 (and pop (pop-to-buffer buffer t))
1792 (and internal (set-process-query-on-exit-flag process nil))))
1796 (defun run-python (cmd &optional dedicated show)
1797 "Run an inferior Python process.
1798 Input and output via buffer named after
1799 `python-shell-buffer-name'. If there is a process already
1800 running in that buffer, just switch to it.
1802 With argument, allows you to define CMD so you can edit the
1803 command used to call the interpreter and define DEDICATED, so a
1804 dedicated process for the current buffer is open. When numeric
1805 prefix arg is other than 0 or 4 do not SHOW.
1807 Runs the hook `inferior-python-mode-hook' (after the
1808 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1809 process buffer for a list of commands.)"
1811 (if current-prefix-arg
1813 (read-string "Run Python: " (python-shell-parse-command))
1814 (y-or-n-p "Make dedicated process? ")
1815 (= (prefix-numeric-value current-prefix-arg) 4))
1816 (list (python-shell-parse-command) nil t)))
1817 (python-shell-make-comint
1818 cmd (python-shell-get-process-name dedicated) show)
1821 (defun run-python-internal ()
1822 "Run an inferior Internal Python process.
1823 Input and output via buffer named after
1824 `python-shell-internal-buffer-name' and what
1825 `python-shell-internal-get-process-name' returns.
1827 This new kind of shell is intended to be used for generic
1828 communication related to defined configurations, the main
1829 difference with global or dedicated shells is that these ones are
1830 attached to a configuration, not a buffer. This means that can
1831 be used for example to retrieve the sys.path and other stuff,
1832 without messing with user shells. Note that
1833 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1834 are set to nil for these shells, so setup codes are not sent at
1836 (let ((python-shell-enable-font-lock nil)
1837 (inferior-python-mode-hook nil))
1839 (python-shell-make-comint
1840 (python-shell-parse-command)
1841 (python-shell-internal-get-process-name) nil t))))
1843 (defun python-shell-get-process ()
1844 "Get inferior Python process for current buffer and return it."
1845 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1846 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1847 (global-proc-name (python-shell-get-process-name nil))
1848 (global-proc-buffer-name (format "*%s*" global-proc-name))
1849 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1850 (global-running (comint-check-proc global-proc-buffer-name)))
1851 ;; Always prefer dedicated
1852 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1853 (and global-running global-proc-buffer-name)))))
1855 (defun python-shell-get-or-create-process ()
1856 "Get or create an inferior Python process for current buffer and return it."
1857 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1858 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1859 (global-proc-name (python-shell-get-process-name nil))
1860 (global-proc-buffer-name (format "*%s*" global-proc-name))
1861 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1862 (global-running (comint-check-proc global-proc-buffer-name))
1863 (current-prefix-arg 16))
1864 (when (and (not dedicated-running) (not global-running))
1865 (if (call-interactively 'run-python)
1866 (setq dedicated-running t)
1867 (setq global-running t)))
1868 ;; Always prefer dedicated
1869 (get-buffer-process (if dedicated-running
1870 dedicated-proc-buffer-name
1871 global-proc-buffer-name))))
1873 (defvar python-shell-internal-buffer nil
1874 "Current internal shell buffer for the current buffer.
1875 This is really not necessary at all for the code to work but it's
1876 there for compatibility with CEDET.")
1878 (defvar python-shell-internal-last-output nil
1879 "Last output captured by the internal shell.
1880 This is really not necessary at all for the code to work but it's
1881 there for compatibility with CEDET.")
1883 (defun python-shell-internal-get-or-create-process ()
1884 "Get or create an inferior Internal Python process."
1885 (let* ((proc-name (python-shell-internal-get-process-name))
1886 (proc-buffer-name (format " *%s*" proc-name)))
1887 (when (not (process-live-p proc-name))
1888 (run-python-internal)
1889 (setq python-shell-internal-buffer proc-buffer-name)
1890 ;; XXX: Why is this `sit-for' needed?
1891 ;; `python-shell-make-comint' calls `accept-process-output'
1892 ;; already but it is not helping to get proper output on
1893 ;; 'gnu/linux when the internal shell process is not running and
1894 ;; a call to `python-shell-internal-send-string' is issued.
1896 (get-buffer-process proc-buffer-name)))
1898 (define-obsolete-function-alias
1899 'python-proc 'python-shell-internal-get-or-create-process "24.3")
1901 (define-obsolete-variable-alias
1902 'python-buffer 'python-shell-internal-buffer "24.3")
1904 (define-obsolete-variable-alias
1905 'python-preoutput-result 'python-shell-internal-last-output "24.3")
1907 (defun python-shell-send-string (string &optional process msg)
1908 "Send STRING to inferior Python PROCESS.
1909 When MSG is non-nil messages the first line of STRING."
1910 (interactive "sPython command: ")
1911 (let ((process (or process (python-shell-get-or-create-process)))
1912 (lines (split-string string "\n" t)))
1913 (and msg (message "Sent: %s..." (nth 0 lines)))
1914 (if (> (length lines) 1)
1915 (let* ((temporary-file-directory
1916 (if (file-remote-p default-directory)
1917 (concat (file-remote-p default-directory) "/tmp")
1918 temporary-file-directory))
1919 (temp-file-name (make-temp-file "py"))
1920 (file-name (or (buffer-file-name) temp-file-name)))
1921 (with-temp-file temp-file-name
1923 (delete-trailing-whitespace))
1924 (python-shell-send-file file-name process temp-file-name))
1925 (comint-send-string process string)
1926 (when (or (not (string-match "\n$" string))
1927 (string-match "\n[ \t].*\n?$" string))
1928 (comint-send-string process "\n")))))
1930 (defvar python-shell-output-filter-in-progress nil)
1931 (defvar python-shell-output-filter-buffer nil)
1933 (defun python-shell-output-filter (string)
1934 "Filter used in `python-shell-send-string-no-output' to grab output.
1935 STRING is the output received to this point from the process.
1936 This filter saves received output from the process in
1937 `python-shell-output-filter-buffer' and stops receiving it after
1938 detecting a prompt at the end of the buffer."
1940 string (ansi-color-filter-apply string)
1941 python-shell-output-filter-buffer
1942 (concat python-shell-output-filter-buffer string))
1944 ;; XXX: It seems on OSX an extra carriage return is attached
1945 ;; at the end of output, this handles that too.
1946 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1947 python-shell-prompt-regexp
1948 python-shell-prompt-block-regexp
1949 python-shell-prompt-pdb-regexp)
1950 python-shell-output-filter-buffer)
1951 ;; Output ends when `python-shell-output-filter-buffer' contains
1952 ;; the prompt attached at the end of it.
1953 (setq python-shell-output-filter-in-progress nil
1954 python-shell-output-filter-buffer
1955 (substring python-shell-output-filter-buffer
1956 0 (match-beginning 0)))
1957 (when (and (> (length python-shell-prompt-output-regexp) 0)
1958 (string-match (concat "^" python-shell-prompt-output-regexp)
1959 python-shell-output-filter-buffer))
1960 ;; Some shells, like iPython might append a prompt before the
1961 ;; output, clean that.
1962 (setq python-shell-output-filter-buffer
1963 (substring python-shell-output-filter-buffer (match-end 0)))))
1966 (defun python-shell-send-string-no-output (string &optional process msg)
1967 "Send STRING to PROCESS and inhibit output.
1968 When MSG is non-nil messages the first line of STRING. Return
1970 (let ((process (or process (python-shell-get-or-create-process)))
1971 (comint-preoutput-filter-functions
1972 '(python-shell-output-filter))
1973 (python-shell-output-filter-in-progress t)
1977 (python-shell-send-string string process msg)
1978 (while python-shell-output-filter-in-progress
1979 ;; `python-shell-output-filter' takes care of setting
1980 ;; `python-shell-output-filter-in-progress' to NIL after it
1981 ;; detects end of output.
1982 (accept-process-output process))
1984 python-shell-output-filter-buffer
1985 (setq python-shell-output-filter-buffer nil)))
1986 (with-current-buffer (process-buffer process)
1987 (comint-interrupt-subjob)))))
1989 (defun python-shell-internal-send-string (string)
1990 "Send STRING to the Internal Python interpreter.
1991 Returns the output. See `python-shell-send-string-no-output'."
1992 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1993 ;; updated to support this new mode.
1994 (setq python-shell-internal-last-output
1995 (python-shell-send-string-no-output
1996 ;; Makes this function compatible with the old
1997 ;; python-send-receive. (At least for CEDET).
1998 (replace-regexp-in-string "_emacs_out +" "" string)
1999 (python-shell-internal-get-or-create-process) nil)))
2001 (define-obsolete-function-alias
2002 'python-send-receive 'python-shell-internal-send-string "24.3")
2004 (define-obsolete-function-alias
2005 'python-send-string 'python-shell-internal-send-string "24.3")
2007 (defun python-shell-send-region (start end)
2008 "Send the region delimited by START and END to inferior Python process."
2010 (python-shell-send-string (buffer-substring start end) nil t))
2012 (defun python-shell-send-buffer (&optional arg)
2013 "Send the entire buffer to inferior Python process.
2014 With prefix ARG allow execution of code inside blocks delimited
2015 by \"if __name__== '__main__':\""
2019 (let ((str (buffer-substring (point-min) (point-max))))
2022 (setq str (replace-regexp-in-string
2023 (python-rx if-name-main)
2024 "if __name__ == '__main__ ':" str)))
2025 (python-shell-send-string str))))
2027 (defun python-shell-send-defun (arg)
2028 "Send the current defun to inferior Python process.
2029 When argument ARG is non-nil do not include decorators."
2032 (python-shell-send-region
2035 (while (and (or (python-nav-beginning-of-defun)
2036 (beginning-of-line 1))
2037 (> (current-indentation) 0)))
2039 (while (and (forward-line -1)
2040 (looking-at (python-rx decorator))))
2044 (or (python-nav-end-of-defun)
2048 (defun python-shell-send-file (file-name &optional process temp-file-name)
2049 "Send FILE-NAME to inferior Python PROCESS.
2050 If TEMP-FILE-NAME is passed then that file is used for processing
2051 instead, while internally the shell will continue to use
2053 (interactive "fFile to send: ")
2054 (let* ((process (or process (python-shell-get-or-create-process)))
2055 (temp-file-name (when temp-file-name
2057 (or (file-remote-p temp-file-name 'localname)
2059 (file-name (or (when file-name
2061 (or (file-remote-p file-name 'localname)
2064 (when (not file-name)
2065 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2066 (python-shell-send-string
2068 (concat "__pyfile = open('''%s''');"
2069 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2071 (or temp-file-name file-name) file-name)
2074 (defun python-shell-switch-to-shell ()
2075 "Switch to inferior Python process buffer."
2077 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2079 (defun python-shell-send-setup-code ()
2080 "Send all setup code for shell.
2081 This function takes the list of setup code to send from the
2082 `python-shell-setup-codes' list."
2083 (let ((process (get-buffer-process (current-buffer))))
2084 (dolist (code python-shell-setup-codes)
2086 (message "Sent %s" code)
2087 (python-shell-send-string
2088 (symbol-value code) process)))))
2090 (add-hook 'inferior-python-mode-hook
2091 #'python-shell-send-setup-code)
2094 ;;; Shell completion
2096 (defcustom python-shell-completion-setup-code
2100 def __COMPLETER_all_completions(text): []
2103 readline.set_completer(rlcompleter.Completer().complete)
2104 def __COMPLETER_all_completions(text):
2110 res = readline.get_completer()(text, i)
2113 completions.append(res)
2117 "Code used to setup completion in inferior Python processes."
2121 (defcustom python-shell-completion-string-code
2122 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2123 "Python code used to get a string of completions separated by semicolons."
2127 (defcustom python-shell-completion-module-string-code ""
2128 "Python code used to get completions separated by semicolons for imports.
2130 For IPython v0.11, add the following line to
2131 `python-shell-completion-setup-code':
2133 from IPython.core.completerlib import module_completion
2135 and use the following as the value of this variable:
2137 ';'.join(module_completion('''%s'''))\n"
2141 (defcustom python-shell-completion-pdb-string-code
2142 "';'.join(globals().keys() + locals().keys())"
2143 "Python code used to get completions separated by semicolons for [i]pdb."
2147 (defun python-shell-completion-get-completions (process line input)
2148 "Do completion at point for PROCESS.
2149 LINE is used to detect the context on how to complete given
2152 ;; Get the last prompt for the inferior process
2153 ;; buffer. This is used for the completion code selection
2155 (with-current-buffer (process-buffer process)
2156 (buffer-substring-no-properties
2157 (overlay-start comint-last-prompt-overlay)
2158 (overlay-end comint-last-prompt-overlay))))
2160 ;; Check whether a prompt matches a pdb string, an import
2161 ;; statement or just the standard prompt and use the
2162 ;; correct python-shell-completion-*-code string
2163 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2165 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2168 (length python-shell-completion-module-string-code) 0)
2170 (concat "^" python-shell-prompt-regexp) prompt)
2171 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2174 (concat "^" python-shell-prompt-regexp) prompt)
2178 (pcase completion-context
2179 (`pdb python-shell-completion-pdb-string-code)
2180 (`import python-shell-completion-module-string-code)
2181 (`default python-shell-completion-string-code)
2184 (if (eq completion-context 'import)
2185 (replace-regexp-in-string "^[ \t]+" "" line)
2187 (and completion-code
2188 (> (length input) 0)
2189 (with-current-buffer (process-buffer process)
2190 (let ((completions (python-shell-send-string-no-output
2191 (format completion-code input) process)))
2192 (and (> (length completions) 2)
2193 (split-string completions
2194 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2196 (defun python-shell-completion-complete-at-point (&optional process)
2197 "Perform completion at point in inferior Python.
2198 Optional argument PROCESS forces completions to be retrieved
2199 using that one instead of current buffer's process."
2200 (setq process (or process (get-buffer-process (current-buffer))))
2203 (with-syntax-table python-dotty-syntax-table
2204 (let* ((paren-depth (car (syntax-ppss)))
2205 (syntax-string "w_")
2206 (syntax-list (string-to-syntax syntax-string)))
2207 ;; Stop scanning for the beginning of the completion
2208 ;; subject after the char before point matches a
2211 (car (syntax-after (1- (point)))) syntax-list)
2212 (skip-syntax-backward syntax-string)
2213 (when (or (equal (char-before) ?\))
2214 (equal (char-before) ?\"))
2217 ;; honor initial paren depth
2218 (> (car (syntax-ppss)) paren-depth)
2219 (python-syntax-context 'string))
2224 (completion-table-dynamic
2226 #'python-shell-completion-get-completions
2227 process (buffer-substring-no-properties
2228 (line-beginning-position) end))))))
2230 (defun python-shell-completion-complete-or-indent ()
2231 "Complete or indent depending on the context.
2232 If content before pointer is all whitespace indent. If not try
2235 (if (string-match "^[[:space:]]*$"
2236 (buffer-substring (comint-line-beginning-position)
2238 (indent-for-tab-command)
2239 (completion-at-point)))
2242 ;;; PDB Track integration
2244 (defcustom python-pdbtrack-activate t
2245 "Non-nil makes python shell enable pdbtracking."
2250 (defcustom python-pdbtrack-stacktrace-info-regexp
2251 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2252 "Regular Expression matching stacktrace information.
2253 Used to extract the current line and module being inspected."
2258 (defvar python-pdbtrack-tracked-buffer nil
2259 "Variable containing the value of the current tracked buffer.
2260 Never set this variable directly, use
2261 `python-pdbtrack-set-tracked-buffer' instead.")
2263 (defvar python-pdbtrack-buffers-to-kill nil
2264 "List of buffers to be deleted after tracking finishes.")
2266 (defun python-pdbtrack-set-tracked-buffer (file-name)
2267 "Set the buffer for FILE-NAME as the tracked buffer.
2268 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2269 Returns the tracked buffer."
2270 (let ((file-buffer (get-file-buffer file-name)))
2272 (setq python-pdbtrack-tracked-buffer file-buffer)
2273 (setq file-buffer (find-file-noselect file-name))
2274 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2275 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2278 (defun python-pdbtrack-comint-output-filter-function (output)
2279 "Move overlay arrow to current pdb line in tracked buffer.
2280 Argument OUTPUT is a string with the output from the comint process."
2281 (when (and python-pdbtrack-activate (not (string= output "")))
2282 (let* ((full-output (ansi-color-filter-apply
2283 (buffer-substring comint-last-input-end (point-max))))
2287 (insert full-output)
2288 (goto-char (point-min))
2289 ;; OK, this sucked but now it became a cool hack. The
2290 ;; stacktrace information normally is on the first line
2291 ;; but in some cases (like when doing a step-in) it is
2293 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
2296 (looking-at python-pdbtrack-stacktrace-info-regexp)))
2297 (setq line-number (string-to-number
2298 (match-string-no-properties 2)))
2299 (match-string-no-properties 1)))))
2300 (if (and file-name line-number)
2301 (let* ((tracked-buffer
2302 (python-pdbtrack-set-tracked-buffer file-name))
2303 (shell-buffer (current-buffer))
2304 (tracked-buffer-window (get-buffer-window tracked-buffer))
2305 (tracked-buffer-line-pos))
2306 (with-current-buffer tracked-buffer
2307 (set (make-local-variable 'overlay-arrow-string) "=>")
2308 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2309 (setq tracked-buffer-line-pos (progn
2310 (goto-char (point-min))
2311 (forward-line (1- line-number))
2313 (when tracked-buffer-window
2315 tracked-buffer-window tracked-buffer-line-pos))
2316 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2317 (pop-to-buffer tracked-buffer)
2318 (switch-to-buffer-other-window shell-buffer))
2319 (when python-pdbtrack-tracked-buffer
2320 (with-current-buffer python-pdbtrack-tracked-buffer
2321 (set-marker overlay-arrow-position nil))
2322 (mapc #'(lambda (buffer)
2323 (ignore-errors (kill-buffer buffer)))
2324 python-pdbtrack-buffers-to-kill)
2325 (setq python-pdbtrack-tracked-buffer nil
2326 python-pdbtrack-buffers-to-kill nil)))))
2330 ;;; Symbol completion
2332 (defun python-completion-complete-at-point ()
2333 "Complete current symbol at point.
2334 For this to work the best as possible you should call
2335 `python-shell-send-buffer' from time to time so context in
2336 inferior python process is updated properly."
2337 (let ((process (python-shell-get-process)))
2339 (error "Completion needs an inferior Python process running")
2340 (python-shell-completion-complete-at-point process))))
2342 (add-to-list 'debug-ignored-errors
2343 "^Completion needs an inferior Python process running.")
2348 (defcustom python-fill-comment-function 'python-fill-comment
2349 "Function to fill comments.
2350 This is the function used by `python-fill-paragraph' to
2355 (defcustom python-fill-string-function 'python-fill-string
2356 "Function to fill strings.
2357 This is the function used by `python-fill-paragraph' to
2362 (defcustom python-fill-decorator-function 'python-fill-decorator
2363 "Function to fill decorators.
2364 This is the function used by `python-fill-paragraph' to
2369 (defcustom python-fill-paren-function 'python-fill-paren
2370 "Function to fill parens.
2371 This is the function used by `python-fill-paragraph' to
2376 (defcustom python-fill-docstring-style 'pep-257
2377 "Style used to fill docstrings.
2378 This affects `python-fill-string' behavior with regards to
2379 triple quotes positioning.
2381 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2382 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2383 position and will treat docstrings a normal string, any other
2384 value may result in one of the following docstring styles:
2389 Process foo, return bar.
2393 Process foo, return bar.
2395 If processing fails throw ProcessingError.
2400 \"\"\"Process foo, return bar.\"\"\"
2403 Process foo, return bar.
2405 If processing fails throw ProcessingError.
2411 \"\"\"Process foo, return bar.\"\"\"
2413 \"\"\"Process foo, return bar.
2415 If processing fails throw ProcessingError.
2421 \"\"\"Process foo, return bar.\"\"\"
2423 \"\"\"Process foo, return bar.
2425 If processing fails throw ProcessingError.
2430 \"\"\"Process foo, return bar.\"\"\"
2433 Process foo, return bar.
2435 If processing fails throw ProcessingError.
2438 (const :tag "Don't format docstrings" nil)
2439 (const :tag "Django's coding standards style." django)
2440 (const :tag "One newline and start and Two at end style." onetwo)
2441 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2442 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2443 (const :tag "Symmetric style." symmetric))
2446 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2448 (defun python-fill-paragraph (&optional justify)
2449 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2450 If any of the current line is in or at the end of a multi-line string,
2451 fill the string or the paragraph of it that point is in, preserving
2452 the string's indentation.
2453 Optional argument JUSTIFY defines if the paragraph should be justified."
2458 ((python-syntax-context 'comment)
2459 (funcall python-fill-comment-function justify))
2460 ;; Strings/Docstrings
2461 ((save-excursion (or (python-syntax-context 'string)
2462 (equal (string-to-syntax "|")
2463 (syntax-after (point)))))
2464 (funcall python-fill-string-function justify))
2466 ((equal (char-after (save-excursion
2467 (python-nav-beginning-of-statement))) ?@)
2468 (funcall python-fill-decorator-function justify))
2470 ((or (python-syntax-context 'paren)
2471 (looking-at (python-rx open-paren))
2473 (skip-syntax-forward "^(" (line-end-position))
2474 (looking-at (python-rx open-paren))))
2475 (funcall python-fill-paren-function justify))
2478 (defun python-fill-comment (&optional justify)
2479 "Comment fill function for `python-fill-paragraph'.
2480 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2481 (fill-comment-paragraph justify))
2483 (defun python-fill-string (&optional justify)
2484 "String fill function for `python-fill-paragraph'.
2485 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2486 (let* ((marker (point-marker))
2488 (let ((m (make-marker)))
2489 (setf (marker-position m)
2490 (or (python-syntax-context 'string)
2491 (and (equal (string-to-syntax "|")
2492 (syntax-after (point)))
2494 (num-quotes (python-syntax-count-quotes
2495 (char-after str-start-pos) str-start-pos))
2498 (goto-char (+ str-start-pos num-quotes))
2499 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2500 (goto-char (point-max)))
2503 ;; Docstring styles may vary for oneliners and multi-liners.
2504 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2506 (pcase python-fill-docstring-style
2507 ;; delimiters-style is a cons cell with the form
2508 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2509 ;; is NIL means to not add any newlines for start or end
2510 ;; of docstring. See `python-fill-docstring-style' for a
2511 ;; graphic idea of each style.
2512 (`django (cons 1 1))
2513 (`onetwo (and multi-line-p (cons 1 2)))
2514 (`pep-257 (and multi-line-p (cons nil 2)))
2515 (`pep-257-nn (and multi-line-p (cons nil 1)))
2516 (`symmetric (and multi-line-p (cons 1 1)))))
2517 (docstring-p (save-excursion
2518 ;; Consider docstrings those strings which
2519 ;; start on a line by themselves.
2520 (python-nav-beginning-of-statement)
2521 (and (= (point) str-start-pos))))
2522 (fill-paragraph-function))
2524 (narrow-to-region str-start-pos str-end-pos)
2525 (fill-paragraph justify))
2527 (when (and docstring-p python-fill-docstring-style)
2528 ;; Add the number of newlines indicated by the selected style
2529 ;; at the start of the docstring.
2530 (goto-char (+ str-start-pos num-quotes))
2531 (delete-region (point) (progn
2532 (skip-syntax-forward "> ")
2534 (and (car delimiters-style)
2535 (or (newline (car delimiters-style)) t)
2536 ;; Indent only if a newline is added.
2537 (indent-according-to-mode))
2538 ;; Add the number of newlines indicated by the selected style
2539 ;; at the end of the docstring.
2540 (goto-char (if (not (= str-end-pos (point-max)))
2541 (- str-end-pos num-quotes)
2543 (delete-region (point) (progn
2544 (skip-syntax-backward "> ")
2546 (and (cdr delimiters-style)
2547 ;; Add newlines only if string ends.
2548 (not (= str-end-pos (point-max)))
2549 (or (newline (cdr delimiters-style)) t)
2550 ;; Again indent only if a newline is added.
2551 (indent-according-to-mode))))) t)
2553 (defun python-fill-decorator (&optional justify)
2554 "Decorator fill function for `python-fill-paragraph'.
2555 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2558 (defun python-fill-paren (&optional justify)
2559 "Paren fill function for `python-fill-paragraph'.
2560 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2562 (narrow-to-region (progn
2563 (while (python-syntax-context 'paren)
2564 (goto-char (1- (point-marker))))
2566 (line-beginning-position))
2568 (when (not (python-syntax-context 'paren))
2570 (when (not (python-syntax-context 'paren))
2571 (skip-syntax-backward "^)")))
2572 (while (python-syntax-context 'paren)
2573 (goto-char (1+ (point-marker))))
2575 (let ((paragraph-start "\f\\|[ \t]*$")
2576 (paragraph-separate ",")
2577 (fill-paragraph-function))
2578 (goto-char (point-min))
2579 (fill-paragraph justify))
2582 (python-indent-line)
2583 (goto-char (line-end-position)))) t)
2588 (defcustom python-skeleton-autoinsert nil
2589 "Non-nil means template skeletons will be automagically inserted.
2590 This happens when pressing \"if<SPACE>\", for example, to prompt for
2596 (define-obsolete-variable-alias
2597 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2599 (defvar python-skeleton-available '()
2600 "Internal list of available skeletons.")
2602 (define-abbrev-table 'python-mode-abbrev-table ()
2603 "Abbrev table for Python mode."
2605 ;; Allow / inside abbrevs.
2606 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2607 ;; Only expand in code.
2608 :enable-function (lambda ()
2610 (not (python-syntax-comment-or-string-p))
2611 python-skeleton-autoinsert)))
2613 (defmacro python-skeleton-define (name doc &rest skel)
2614 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2615 The skeleton will be bound to python-skeleton-NAME and will
2616 be added to `python-mode-abbrev-table'."
2617 (declare (indent 2))
2618 (let* ((name (symbol-name name))
2619 (function-name (intern (concat "python-skeleton-" name))))
2621 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
2623 (setq python-skeleton-available
2624 (cons ',function-name python-skeleton-available))
2625 (define-skeleton ,function-name
2627 (format "Insert %s statement." name))
2630 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2631 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2632 The skeleton will be bound to python-skeleton-NAME."
2633 (declare (indent 2))
2634 (let* ((name (symbol-name name))
2635 (function-name (intern (concat "python-skeleton--" name)))
2637 "Add '%s' clause? " name)))
2640 `(< ,(format "%s:" name) \n \n
2642 `(define-skeleton ,function-name
2644 (format "Auxiliary skeleton for %s statement." name))
2646 (unless (y-or-n-p ,msg)
2650 (python-define-auxiliary-skeleton else nil)
2652 (python-define-auxiliary-skeleton except nil)
2654 (python-define-auxiliary-skeleton finally nil)
2656 (python-skeleton-define if nil
2660 ("other condition, %s: "
2664 '(python-skeleton--else) | ^)
2666 (python-skeleton-define while nil
2670 '(python-skeleton--else) | ^)
2672 (python-skeleton-define for nil
2676 '(python-skeleton--else) | ^)
2678 (python-skeleton-define try nil
2684 "except " str ":" \n
2687 '(python-skeleton--except)
2688 '(python-skeleton--else)
2689 '(python-skeleton--finally) | ^)
2691 (python-skeleton-define def nil
2693 "def " str " (" ("Parameter, %s: "
2694 (unless (equal ?\( (char-before)) ", ")
2696 "\"\"\"" - "\"\"\"" \n
2699 (python-skeleton-define class nil
2701 "class " str " (" ("Inheritance, %s: "
2702 (unless (equal ?\( (char-before)) ", ")
2706 "\"\"\"" - "\"\"\"" \n
2709 (defun python-skeleton-add-menu-items ()
2710 "Add menu items to Python->Skeletons menu."
2711 (let ((skeletons (sort python-skeleton-available 'string<))
2713 (dolist (skeleton skeletons)
2715 nil '("Python" "Skeletons")
2717 "Insert %s" (nth 2 (split-string (symbol-name skeleton) "-")))
2722 (defcustom python-ffap-setup-code
2723 "def __FFAP_get_module_path(module):
2726 path = __import__(module).__file__
2727 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2732 "Python code to get a module path."
2736 (defcustom python-ffap-string-code
2737 "__FFAP_get_module_path('''%s''')\n"
2738 "Python code used to get a string with the path of a module."
2742 (defun python-ffap-module-path (module)
2743 "Function for `ffap-alist' to return path for MODULE."
2745 (and (eq major-mode 'inferior-python-mode)
2746 (get-buffer-process (current-buffer)))
2747 (python-shell-get-process))))
2751 (python-shell-send-string-no-output
2752 (format python-ffap-string-code module) process)))
2754 (substring-no-properties module-file 1 -1))))))
2756 (eval-after-load "ffap"
2758 (push '(python-mode . python-ffap-module-path) ffap-alist)
2759 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2764 (defcustom python-check-command
2766 "Command used to check a Python file."
2770 (defcustom python-check-buffer-name
2771 "*Python check: %s*"
2772 "Buffer name used for check commands."
2776 (defvar python-check-custom-command nil
2779 (defun python-check (command)
2780 "Check a Python file (default current buffer's file).
2781 Runs COMMAND, a shell command, as if by `compile'. See
2782 `python-check-command' for the default."
2784 (list (read-string "Check command: "
2785 (or python-check-custom-command
2786 (concat python-check-command " "
2787 (shell-quote-argument
2789 (let ((name (buffer-file-name)))
2791 (file-name-nondirectory name)))
2793 (setq python-check-custom-command command)
2794 (save-some-buffers (not compilation-ask-about-save) nil)
2795 (let ((process-environment (python-shell-calculate-process-environment))
2796 (exec-path (python-shell-calculate-exec-path)))
2797 (compilation-start command nil
2799 (format python-check-buffer-name command)))))
2804 (defcustom python-eldoc-setup-code
2805 "def __PYDOC_get_help(obj):
2808 if hasattr(obj, 'startswith'):
2809 obj = eval(obj, globals())
2810 doc = inspect.getdoc(obj)
2811 if not doc and callable(obj):
2813 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2814 target = obj.__init__
2820 args = inspect.formatargspec(
2821 *inspect.getargspec(target)
2824 doc = '{objtype} {name}{args}'.format(
2825 objtype=objtype, name=name, args=args
2828 doc = doc.splitlines()[0]
2835 "Python code to setup documentation retrieval."
2839 (defcustom python-eldoc-string-code
2840 "__PYDOC_get_help('''%s''')\n"
2841 "Python code used to get a string with the documentation of an object."
2845 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2846 "Internal implementation to get documentation at point.
2847 If not FORCE-INPUT is passed then what
2848 `python-info-current-symbol' returns will be used. If not
2849 FORCE-PROCESS is passed what `python-shell-get-process' returns
2851 (let ((process (or force-process (python-shell-get-process))))
2853 (error "Eldoc needs an inferior Python process running")
2854 (let ((input (or force-input
2855 (python-info-current-symbol t))))
2857 (python-shell-send-string-no-output
2858 (format python-eldoc-string-code input)
2861 (defun python-eldoc-function ()
2862 "`eldoc-documentation-function' for Python.
2863 For this to work the best as possible you should call
2864 `python-shell-send-buffer' from time to time so context in
2865 inferior python process is updated properly."
2866 (python-eldoc--get-doc-at-point))
2868 (defun python-eldoc-at-point (symbol)
2869 "Get help on SYMBOL using `help'.
2870 Interactively, prompt for symbol."
2872 (let ((symbol (python-info-current-symbol t))
2873 (enable-recursive-minibuffers t))
2874 (list (read-string (if symbol
2875 (format "Describe symbol (default %s): " symbol)
2876 "Describe symbol: ")
2878 (message (python-eldoc--get-doc-at-point symbol)))
2880 (add-to-list 'debug-ignored-errors
2881 "^Eldoc needs an inferior Python process running.")
2886 (defun python-info-current-defun (&optional include-type)
2887 "Return name of surrounding function with Python compatible dotty syntax.
2888 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2889 This function is compatible to be used as
2890 `add-log-current-defun-function' since it returns nil if point is
2891 not inside a defun."
2897 (starting-indentation
2900 (python-nav-beginning-of-defun 1)
2901 ;; This extra number is just for checking code
2902 ;; against indentation to work well on first run.
2903 (+ (current-indentation) 4))))
2904 (starting-point (point)))
2905 ;; Check point is inside a defun.
2906 (when (and starting-indentation
2909 (python-nav-end-of-defun)
2912 (while (python-nav-beginning-of-defun 1)
2913 (when (< (current-indentation) starting-indentation)
2914 (setq starting-indentation (current-indentation))
2917 (if (not include-type)
2918 (match-string-no-properties 1)
2919 (mapconcat 'identity
2921 (match-string-no-properties 0)) " "))
2923 (and (= (current-indentation) 0) (throw 'exit t)))))
2925 (mapconcat (lambda (string) string) names "."))))))
2927 (defun python-info-current-symbol (&optional replace-self)
2928 "Return current symbol using dotty syntax.
2929 With optional argument REPLACE-SELF convert \"self\" to current
2932 (and (not (python-syntax-comment-or-string-p))
2933 (with-syntax-table python-dotty-syntax-table
2934 (let ((sym (symbol-at-point)))
2936 (substring-no-properties (symbol-name sym))))))))
2938 (if (not replace-self)
2940 (let ((current-defun (python-info-current-defun)))
2941 (if (not current-defun)
2943 (replace-regexp-in-string
2944 (python-rx line-start word-start "self" word-end ?.)
2946 (mapconcat 'identity
2947 (butlast (split-string current-defun "\\."))
2951 (defun python-info-statement-starts-block-p ()
2952 "Return non-nil if current statement opens a block."
2954 (python-nav-beginning-of-statement)
2955 (looking-at (python-rx block-start))))
2957 (defun python-info-statement-ends-block-p ()
2958 "Return non-nil if point is at end of block."
2959 (let ((end-of-block-pos (save-excursion
2960 (python-nav-end-of-block)))
2961 (end-of-statement-pos (save-excursion
2962 (python-nav-end-of-statement))))
2963 (and end-of-block-pos end-of-statement-pos
2964 (= end-of-block-pos end-of-statement-pos))))
2966 (defun python-info-beginning-of-statement-p ()
2967 "Return non-nil if point is at beginning of statement."
2968 (= (point) (save-excursion
2969 (python-nav-beginning-of-statement)
2972 (defun python-info-end-of-statement-p ()
2973 "Return non-nil if point is at end of statement."
2974 (= (point) (save-excursion
2975 (python-nav-end-of-statement)
2978 (defun python-info-beginning-of-block-p ()
2979 "Return non-nil if point is at beginning of block."
2980 (and (python-info-beginning-of-statement-p)
2981 (python-info-statement-starts-block-p)))
2983 (defun python-info-end-of-block-p ()
2984 "Return non-nil if point is at end of block."
2985 (and (python-info-end-of-statement-p)
2986 (python-info-statement-ends-block-p)))
2988 (defun python-info-closing-block ()
2989 "Return the point of the block the current line closes."
2990 (let ((closing-word (save-excursion
2991 (back-to-indentation)
2993 (indentation (current-indentation)))
2994 (when (member closing-word python-indent-dedenters)
2997 (while (and (> (current-indentation) indentation)
2999 (not (back-to-indentation))
3001 (back-to-indentation)
3003 ((not (equal indentation (current-indentation))) nil)
3004 ((string= closing-word "elif")
3005 (when (member (current-word) '("if" "elif"))
3007 ((string= closing-word "else")
3008 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3010 ((string= closing-word "except")
3011 (when (member (current-word) '("try"))
3013 ((string= closing-word "finally")
3014 (when (member (current-word) '("except" "else"))
3015 (point-marker))))))))
3017 (defun python-info-closing-block-message (&optional closing-block-point)
3018 "Message the contents of the block the current line closes.
3019 With optional argument CLOSING-BLOCK-POINT use that instead of
3020 recalculating it calling `python-info-closing-block'."
3021 (let ((point (or closing-block-point (python-info-closing-block))))
3025 (message "Closes %s" (save-excursion
3027 (back-to-indentation)
3029 (point) (line-end-position))))))))
3031 (defun python-info-line-ends-backslash-p (&optional line-number)
3032 "Return non-nil if current line ends with backslash.
3033 With optional argument LINE-NUMBER, check that line instead."
3038 (goto-char line-number))
3039 (while (and (not (eobp))
3040 (goto-char (line-end-position))
3041 (python-syntax-context 'paren)
3042 (not (equal (char-before (point)) ?\\)))
3044 (when (equal (char-before) ?\\)
3047 (defun python-info-beginning-of-backslash (&optional line-number)
3048 "Return the point where the backslashed line start.
3049 Optional argument LINE-NUMBER forces the line number to check against."
3054 (goto-char line-number))
3055 (when (python-info-line-ends-backslash-p)
3056 (while (save-excursion
3057 (goto-char (line-beginning-position))
3058 (python-syntax-context 'paren))
3060 (back-to-indentation)
3063 (defun python-info-continuation-line-p ()
3064 "Check if current line is continuation of another.
3065 When current line is continuation of another return the point
3066 where the continued line ends."
3070 (let* ((context-type (progn
3071 (back-to-indentation)
3072 (python-syntax-context-type)))
3073 (line-start (line-number-at-pos))
3074 (context-start (when context-type
3075 (python-syntax-context context-type))))
3076 (cond ((equal context-type 'paren)
3077 ;; Lines inside a paren are always a continuation line
3078 ;; (except the first one).
3079 (python-util-forward-comment -1)
3081 ((member context-type '(string comment))
3082 ;; move forward an roll again
3083 (goto-char context-start)
3084 (python-util-forward-comment)
3085 (python-info-continuation-line-p))
3087 ;; Not within a paren, string or comment, the only way
3088 ;; we are dealing with a continuation line is that
3089 ;; previous line contains a backslash, and this can
3090 ;; only be the previous line from current
3091 (back-to-indentation)
3092 (python-util-forward-comment -1)
3093 (when (and (equal (1- line-start) (line-number-at-pos))
3094 (python-info-line-ends-backslash-p))
3095 (point-marker))))))))
3097 (defun python-info-block-continuation-line-p ()
3098 "Return non-nil if current line is a continuation of a block."
3100 (when (python-info-continuation-line-p)
3102 (back-to-indentation)
3103 (when (looking-at (python-rx block-start))
3106 (defun python-info-assignment-continuation-line-p ()
3107 "Check if current line is a continuation of an assignment.
3108 When current line is continuation of another with an assignment
3109 return the point of the first non-blank character after the
3112 (when (python-info-continuation-line-p)
3114 (back-to-indentation)
3115 (when (and (not (looking-at (python-rx block-start)))
3116 (and (re-search-forward (python-rx not-simple-operator
3118 not-simple-operator)
3119 (line-end-position) t)
3120 (not (python-syntax-context-type))))
3121 (skip-syntax-forward "\s")
3124 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3125 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3126 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3128 (beginning-of-line 1)
3129 (looking-at python-nav-beginning-of-defun-regexp))))
3131 (defun python-info-current-line-comment-p ()
3132 "Check if current line is a comment line."
3133 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
3135 (defun python-info-current-line-empty-p ()
3136 "Check if current line is empty, ignoring whitespace."
3138 (beginning-of-line 1)
3140 (python-rx line-start (* whitespace)
3141 (group (* not-newline))
3142 (* whitespace) line-end))
3143 (string-equal "" (match-string-no-properties 1))))
3146 ;;; Utility functions
3148 (defun python-util-position (item seq)
3149 "Find the first occurrence of ITEM in SEQ.
3150 Return the index of the matching item, or nil if not found."
3151 (let ((member-result (member item seq)))
3153 (- (length seq) (length member-result)))))
3155 ;; Stolen from org-mode
3156 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3157 "Clone local variables from FROM-BUFFER.
3158 Optional argument REGEXP selects variables to clone and defaults
3162 (and (symbolp (car pair))
3163 (string-match (or regexp "^python-")
3164 (symbol-name (car pair)))
3165 (set (make-local-variable (car pair))
3167 (buffer-local-variables from-buffer)))
3169 (defun python-util-forward-comment (&optional direction)
3170 "Python mode specific version of `forward-comment'.
3171 Optional argument DIRECTION defines the direction to move to."
3172 (let ((comment-start (python-syntax-context 'comment))
3173 (factor (if (< (or direction 0) 0)
3177 (goto-char comment-start))
3178 (forward-comment factor)))
3182 (define-derived-mode python-mode prog-mode "Python"
3183 "Major mode for editing Python files.
3186 Entry to this mode calls the value of `python-mode-hook'
3187 if that value is non-nil."
3188 (set (make-local-variable 'tab-width) 8)
3189 (set (make-local-variable 'indent-tabs-mode) nil)
3191 (set (make-local-variable 'comment-start) "# ")
3192 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3194 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3195 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3197 (set (make-local-variable 'forward-sexp-function)
3198 'python-nav-forward-sexp)
3200 (set (make-local-variable 'font-lock-defaults)
3201 '(python-font-lock-keywords nil nil nil nil))
3203 (set (make-local-variable 'syntax-propertize-function)
3204 python-syntax-propertize-function)
3206 (set (make-local-variable 'indent-line-function)
3207 #'python-indent-line-function)
3208 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3210 (set (make-local-variable 'paragraph-start) "\\s-*$")
3211 (set (make-local-variable 'fill-paragraph-function)
3212 'python-fill-paragraph)
3214 (set (make-local-variable 'beginning-of-defun-function)
3215 #'python-nav-beginning-of-defun)
3216 (set (make-local-variable 'end-of-defun-function)
3217 #'python-nav-end-of-defun)
3219 (add-hook 'completion-at-point-functions
3220 'python-completion-complete-at-point nil 'local)
3222 (add-hook 'post-self-insert-hook
3223 'python-indent-post-self-insert-function nil 'local)
3225 (set (make-local-variable 'imenu-extract-index-name-function)
3226 #'python-info-current-defun)
3228 (set (make-local-variable 'add-log-current-defun-function)
3229 #'python-info-current-defun)
3231 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3233 (set (make-local-variable 'skeleton-further-elements)
3235 (< '(backward-delete-char-untabify (min python-indent-offset
3237 (^ '(- (1+ (current-indentation))))))
3239 (set (make-local-variable 'eldoc-documentation-function)
3240 #'python-eldoc-function)
3242 (add-to-list 'hs-special-modes-alist
3243 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3245 (python-nav-end-of-defun)) nil))
3247 (set (make-local-variable 'mode-require-final-newline) t)
3249 (set (make-local-variable 'outline-regexp)
3250 (python-rx (* space) block-start))
3251 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3252 (set (make-local-variable 'outline-level)
3254 "`outline-level' function for Python mode."
3255 (1+ (/ (current-indentation) python-indent-offset))))
3257 (python-skeleton-add-menu-items)
3259 (make-local-variable 'python-shell-internal-buffer)
3261 (when python-indent-guess-indent-offset
3262 (python-indent-guess-indent-offset)))
3269 ;; indent-tabs-mode: nil
3272 ;;; python.el ends here