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-function' 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)
208 ;; Avoid compiler warnings
209 (defvar view-return-to-alist)
210 (defvar compilation-error-regexp-alist)
211 (defvar outline-heading-end-regexp))
213 (autoload 'comint-mode "comint")
216 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
218 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
221 "Python Language's flying circus support for Emacs."
224 :link '(emacs-commentary-link "python"))
229 (defvar python-mode-map
230 (let ((map (make-sparse-keymap)))
232 (substitute-key-definition 'backward-sentence
233 'python-nav-backward-block
235 (substitute-key-definition 'forward-sentence
236 'python-nav-forward-block
238 (define-key map "\C-c\C-j" 'imenu)
240 (define-key map "\177" 'python-indent-dedent-line-backspace)
241 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
242 (define-key map "\C-c<" 'python-indent-shift-left)
243 (define-key map "\C-c>" 'python-indent-shift-right)
244 (define-key map ":" 'python-indent-electric-colon)
246 (define-key map "\C-c\C-tc" 'python-skeleton-class)
247 (define-key map "\C-c\C-td" 'python-skeleton-def)
248 (define-key map "\C-c\C-tf" 'python-skeleton-for)
249 (define-key map "\C-c\C-ti" 'python-skeleton-if)
250 (define-key map "\C-c\C-tt" 'python-skeleton-try)
251 (define-key map "\C-c\C-tw" 'python-skeleton-while)
253 (define-key map "\C-c\C-p" 'run-python)
254 (define-key map "\C-c\C-s" 'python-shell-send-string)
255 (define-key map "\C-c\C-r" 'python-shell-send-region)
256 (define-key map "\C-\M-x" 'python-shell-send-defun)
257 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
258 (define-key map "\C-c\C-l" 'python-shell-send-file)
259 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
260 ;; Some util commands
261 (define-key map "\C-c\C-v" 'python-check)
262 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
264 (substitute-key-definition 'complete-symbol 'completion-at-point
266 (easy-menu-define python-menu map "Python Mode menu"
268 :help "Python-specific Features"
269 ["Shift region left" python-indent-shift-left :active mark-active
270 :help "Shift region left by a single indentation step"]
271 ["Shift region right" python-indent-shift-right :active mark-active
272 :help "Shift region right by a single indentation step"]
274 ["Start of def/class" beginning-of-defun
275 :help "Go to start of outermost definition around point"]
276 ["End of def/class" end-of-defun
277 :help "Go to end of definition around point"]
278 ["Mark def/class" mark-defun
279 :help "Mark outermost definition around point"]
280 ["Jump to def/class" imenu
281 :help "Jump to a class or function definition"]
285 ["Start interpreter" run-python
286 :help "Run inferior Python process in a separate buffer"]
287 ["Switch to shell" python-shell-switch-to-shell
288 :help "Switch to running inferior Python process"]
289 ["Eval string" python-shell-send-string
290 :help "Eval string in inferior Python session"]
291 ["Eval buffer" python-shell-send-buffer
292 :help "Eval buffer in inferior Python session"]
293 ["Eval region" python-shell-send-region
294 :help "Eval region in inferior Python session"]
295 ["Eval defun" python-shell-send-defun
296 :help "Eval defun in inferior Python session"]
297 ["Eval file" python-shell-send-file
298 :help "Eval file in inferior Python session"]
299 ["Debugger" pdb :help "Run pdb under GUD"]
301 ["Check file" python-check
302 :help "Check file for errors"]
303 ["Help on symbol" python-eldoc-at-point
304 :help "Get help on symbol at point"]
305 ["Complete symbol" completion-at-point
306 :help "Complete symbol before point"]))
308 "Keymap for `python-mode'.")
311 ;;; Python specialized rx
314 (defconst python-rx-constituents
315 `((block-start . ,(rx symbol-start
316 (or "def" "class" "if" "elif" "else" "try"
317 "except" "finally" "for" "while" "with")
319 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
321 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
322 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
323 (+ space) "==" (+ space)
324 (any ?' ?\") "__main__" (any ?' ?\")
326 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
327 (open-paren . ,(rx (or "{" "[" "(")))
328 (close-paren . ,(rx (or "}" "]" ")")))
329 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
330 ;; FIXME: rx should support (not simple-operator).
331 (not-simple-operator . ,(rx
333 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
334 ;; FIXME: Use regexp-opt.
335 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
336 "=" "%" "**" "//" "<<" ">>" "<=" "!="
337 "==" ">=" "is" "not")))
338 ;; FIXME: Use regexp-opt.
339 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
340 ">>=" "<<=" "&=" "^=" "|="))))
341 "Additional Python specific sexps for `python-rx'"))
343 (defmacro python-rx (&rest regexps)
344 "Python mode specialized rx macro.
345 This variant of `rx' supports common python named REGEXPS."
346 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
347 (cond ((null regexps)
350 (rx-to-string `(and ,@regexps) t))
352 (rx-to-string (car regexps) t)))))
355 ;;; Font-lock and syntax
356 (defvar python-font-lock-keywords
360 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
361 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
362 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
367 ;; False, None, and True are listed as keywords on the Python 3
368 ;; documentation, but since they also qualify as constants they are
369 ;; fontified like that in order to keep font-lock consistent between
376 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
377 (1 font-lock-function-name-face))
379 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
380 (1 font-lock-type-face))
384 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
385 ;; copyright, license, credits, quit and exit are added by the site
386 ;; module and they are not intended to be used in programs
387 "copyright" "credits" "exit" "license" "quit")
388 symbol-end) . font-lock-constant-face)
390 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
391 (0+ "." (1+ (or word ?_)))))
392 (1 font-lock-type-face))
393 ;; Builtin Exceptions
396 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
397 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
398 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
399 "ImportError" "ImportWarning" "IndexError" "KeyError"
400 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
401 "NotImplementedError" "OSError" "OverflowError"
402 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
403 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
404 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
405 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
406 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
407 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
411 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
413 symbol-end) . font-lock-type-face)
417 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
418 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
419 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
420 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
421 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
422 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
423 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
424 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
427 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
428 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
431 "ascii" "bytearray" "bytes" "exec"
433 "__all__" "__doc__" "__name__" "__package__")
434 symbol-end) . font-lock-builtin-face)
436 ;; support for a = b = c = 5
438 (let ((re (python-rx (group (+ (any word ?. ?_)))
439 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
440 assignment-operator)))
441 (when (re-search-forward re limit t)
442 (while (and (python-info-ppss-context 'paren)
443 (re-search-forward re limit t)))
444 (if (and (not (python-info-ppss-context 'paren))
445 (not (equal (char-after (point-marker)) ?=)))
447 (set-match-data nil)))))
448 (1 font-lock-variable-name-face nil nil))
449 ;; support for a, b, c = (1, 2, 3)
451 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
452 (* ?, (* space) (+ (any word ?. ?_)) (* space))
453 ?, (* space) (+ (any word ?. ?_)) (* space)
454 assignment-operator)))
455 (when (and (re-search-forward re limit t)
456 (goto-char (nth 3 (match-data))))
457 (while (and (python-info-ppss-context 'paren)
458 (re-search-forward re limit t))
459 (goto-char (nth 3 (match-data))))
460 (if (not (python-info-ppss-context 'paren))
462 (set-match-data nil)))))
463 (1 font-lock-variable-name-face nil nil))))
465 (defconst python-syntax-propertize-function
466 ;; Make outer chars of matching triple-quote sequences into generic
467 ;; string delimiters. Fixme: Is there a better way?
468 ;; First avoid a sequence preceded by an odd number of backslashes.
469 (syntax-propertize-rules
470 (;; ¡Backrefs don't work in syntax-propertize-rules!
471 (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
472 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
473 (3 (ignore (python-quote-syntax))))))
475 (defun python-quote-syntax ()
476 "Put `syntax-table' property correctly on triple quote.
477 Used for syntactic keywords. N is the match number (1, 2 or 3)."
478 ;; Given a triple quote, we have to check the context to know
479 ;; whether this is an opening or closing triple or whether it's
480 ;; quoted anyhow, and should be ignored. (For that we need to do
481 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
482 ;; to use it here despite initial worries.) We also have to sort
483 ;; out a possible prefix -- well, we don't _have_ to, but I think it
484 ;; should be treated as part of the string.
487 ;; ur"""ar""" x='"' # """
490 ;; x '"""' x """ \"""" x
492 (goto-char (match-beginning 0))
493 (let ((syntax (save-match-data (syntax-ppss))))
495 ((eq t (nth 3 syntax)) ; after unclosed fence
496 ;; Consider property for the last char if in a fenced string.
497 (goto-char (nth 8 syntax)) ; fence position
498 (skip-chars-forward "uUrR") ; skip any prefix
499 ;; Is it a matching sequence?
500 (if (eq (char-after) (char-after (match-beginning 2)))
501 (put-text-property (match-beginning 3) (match-end 3)
502 'syntax-table (string-to-syntax "|"))))
504 ;; Consider property for initial char, accounting for prefixes.
505 (put-text-property (match-beginning 1) (match-end 1)
506 'syntax-table (string-to-syntax "|")))
508 ;; Consider property for initial char, accounting for prefixes.
509 (put-text-property (match-beginning 2) (match-end 2)
510 'syntax-table (string-to-syntax "|"))))
513 (defvar python-mode-syntax-table
514 (let ((table (make-syntax-table)))
515 ;; Give punctuation syntax to ASCII that normally has symbol
516 ;; syntax or has word syntax and isn't a letter.
517 (let ((symbol (string-to-syntax "_"))
518 (sst (standard-syntax-table)))
521 (if (equal symbol (aref sst i))
522 (modify-syntax-entry i "." table)))))
523 (modify-syntax-entry ?$ "." table)
524 (modify-syntax-entry ?% "." table)
526 (modify-syntax-entry ?# "<" table)
527 (modify-syntax-entry ?\n ">" table)
528 (modify-syntax-entry ?' "\"" table)
529 (modify-syntax-entry ?` "$" table)
531 "Syntax table for Python files.")
533 (defvar python-dotty-syntax-table
534 (let ((table (make-syntax-table python-mode-syntax-table)))
535 (modify-syntax-entry ?. "w" table)
536 (modify-syntax-entry ?_ "w" table)
538 "Dotty syntax table for Python files.
539 It makes underscores and dots word constituent chars.")
544 (defcustom python-indent-offset 4
545 "Default indentation offset for Python."
550 (defcustom python-indent-guess-indent-offset t
551 "Non-nil tells Python mode to guess `python-indent-offset' value."
556 (define-obsolete-variable-alias
557 'python-indent 'python-indent-offset "24.2")
559 (define-obsolete-variable-alias
560 'python-guess-indent 'python-indent-guess-indent-offset "24.2")
562 (defvar python-indent-current-level 0
563 "Current indentation level `python-indent-line-function' is using.")
565 (defvar python-indent-levels '(0)
566 "Levels of indentation available for `python-indent-line-function'.")
568 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
569 "List of words that should be dedented.
570 These make `python-indent-calculate-indentation' subtract the value of
571 `python-indent-offset'.")
573 (defun python-indent-guess-indent-offset ()
574 "Guess and set `python-indent-offset' for the current buffer."
579 (goto-char (point-min))
581 (while (and (not block-end)
583 (python-rx line-start block-start) nil t))
585 (not (python-info-ppss-context-type))
587 (goto-char (line-end-position))
588 (python-util-forward-comment -1)
589 (if (equal (char-before) ?:)
592 (when (python-info-block-continuation-line-p)
593 (while (and (python-info-continuation-line-p)
596 (python-util-forward-comment -1)
597 (when (equal (char-before) ?:)
599 (setq block-end (point-marker))))
602 (goto-char block-end)
603 (python-util-forward-comment)
604 (current-indentation))))
606 (setq python-indent-offset indentation)
607 (message "Can't guess python-indent-offset, using defaults: %s"
608 python-indent-offset)))))))
610 (defun python-indent-context ()
611 "Get information on indentation context.
612 Context information is returned with a cons with the form:
615 Where status can be any of the following symbols:
616 * inside-paren: If point in between (), {} or []
617 * inside-string: If point is inside a string
618 * after-backslash: Previous line ends in a backslash
619 * after-beginning-of-block: Point is after beginning of block
620 * after-line: Point is after normal line
621 * no-indent: Point is at beginning of buffer or other special case
622 START is the buffer position where the sexp starts."
625 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
629 ;; Beginning of buffer
631 (goto-char (line-beginning-position))
635 ((setq start (python-info-ppss-context 'paren ppss))
638 ((setq start (python-info-ppss-context 'string ppss))
641 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
642 (python-info-ppss-context 'comment ppss)))
643 (let ((line-beg-pos (line-beginning-position)))
644 (when (python-info-line-ends-backslash-p
646 (- line-beg-pos 2)))))
648 ;; After beginning of block
649 ((setq start (save-excursion
651 (back-to-indentation)
652 (python-util-forward-comment -1)
653 (equal (char-before) ?:))
654 ;; Move to the first block start that's not in within
655 ;; a string, comment or paren and that's not a
656 ;; continuation line.
657 (while (and (re-search-backward
658 (python-rx block-start) nil t)
660 (python-info-ppss-context-type)
661 (python-info-continuation-line-p))))
662 (when (looking-at (python-rx block-start))
664 'after-beginning-of-block)
666 ((setq start (save-excursion
667 (back-to-indentation)
668 (python-util-forward-comment -1)
669 (python-nav-beginning-of-statement)
676 (defun python-indent-calculate-indentation ()
677 "Calculate correct indentation offset for the current line."
678 (let* ((indentation-context (python-indent-context))
679 (context-status (car indentation-context))
680 (context-start (cdr indentation-context)))
686 ;; When point is after beginning of block just add one level
687 ;; of indentation relative to the context-start
688 ('after-beginning-of-block
689 (goto-char context-start)
690 (+ (current-indentation) python-indent-offset))
691 ;; When after a simple line just use previous line
692 ;; indentation, in the case current line starts with a
693 ;; `python-indent-dedenters' de-indent one level.
697 (goto-char context-start)
698 (current-indentation))
700 (back-to-indentation)
701 (looking-at (regexp-opt python-indent-dedenters)))
704 ;; When inside of a string, do nothing. just use the current
705 ;; indentation. XXX: perhaps it would be a good idea to
706 ;; invoke standard text indentation here
708 (goto-char context-start)
709 (current-indentation))
710 ;; After backslash we have several possibilities.
713 ;; Check if current line is a dot continuation. For this
714 ;; the current line must start with a dot and previous
715 ;; line must contain a dot too.
717 (back-to-indentation)
718 (when (looking-at "\\.")
719 ;; If after moving one line back point is inside a paren it
720 ;; needs to move back until it's not anymore
724 (python-info-ppss-context 'paren))))
725 (goto-char (line-end-position))
726 (while (and (re-search-backward
727 "\\." (line-beginning-position) t)
728 (python-info-ppss-context-type)))
729 (if (and (looking-at "\\.")
730 (not (python-info-ppss-context-type)))
731 ;; The indentation is the same column of the
732 ;; first matching dot that's not inside a
733 ;; comment, a string or a paren
735 ;; No dot found on previous line, just add another
736 ;; indentation level.
737 (+ (current-indentation) python-indent-offset)))))
738 ;; Check if prev line is a block continuation
739 ((let ((block-continuation-start
740 (python-info-block-continuation-line-p)))
741 (when block-continuation-start
742 ;; If block-continuation-start is set jump to that
743 ;; marker and use first column after the block start
744 ;; as indentation value.
745 (goto-char block-continuation-start)
747 (python-rx block-start (* space))
748 (line-end-position) t)
750 ;; Check if current line is an assignment continuation
751 ((let ((assignment-continuation-start
752 (python-info-assignment-continuation-line-p)))
753 (when assignment-continuation-start
754 ;; If assignment-continuation is set jump to that
755 ;; marker and use first column after the assignment
756 ;; operator as indentation value.
757 (goto-char assignment-continuation-start)
761 (goto-char (python-info-beginning-of-backslash))
766 (or (python-info-beginning-of-backslash) (point)))
767 (python-info-line-ends-backslash-p)))
768 ;; The two previous lines ended in a backslash so we must
769 ;; respect previous line indentation.
770 (current-indentation)
771 ;; What happens here is that we are dealing with the second
772 ;; line of a backslash continuation, in that case we just going
773 ;; to add one indentation level.
774 (+ (current-indentation) python-indent-offset)))))
775 ;; When inside a paren there's a need to handle nesting
779 ;; If current line closes the outermost open paren use the
780 ;; current indentation of the context-start line.
782 (skip-syntax-forward "\s" (line-end-position))
783 (when (and (looking-at (regexp-opt '(")" "]" "}")))
786 (not (python-info-ppss-context 'paren))))
787 (goto-char context-start)
788 (current-indentation))))
789 ;; If open paren is contained on a line by itself add another
790 ;; indentation level, else look for the first word after the
791 ;; opening paren and use it's column position as indentation
793 ((let* ((content-starts-in-newline)
796 (if (setq content-starts-in-newline
798 (goto-char context-start)
802 (line-beginning-position)
804 (python-util-forward-comment))
806 (+ (current-indentation) python-indent-offset)
810 ;; If current line closes a nested open paren de-indent one
813 (back-to-indentation)
814 (looking-at (regexp-opt '(")" "]" "}"))))
815 (- indent python-indent-offset))
816 ;; If the line of the opening paren that wraps the current
817 ;; line starts a block add another level of indentation to
818 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
820 (when (and content-starts-in-newline
822 (goto-char context-start)
823 (back-to-indentation)
824 (looking-at (python-rx block-start))))
825 (+ indent python-indent-offset))))
828 (defun python-indent-calculate-levels ()
829 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
830 (let* ((indentation (python-indent-calculate-indentation))
831 (remainder (% indentation python-indent-offset))
832 (steps (/ (- indentation remainder) python-indent-offset)))
833 (setq python-indent-levels (list 0))
834 (dotimes (step steps)
835 (push (* python-indent-offset (1+ step)) python-indent-levels))
836 (when (not (eq 0 remainder))
837 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
838 (setq python-indent-levels (nreverse python-indent-levels))
839 (setq python-indent-current-level (1- (length python-indent-levels)))))
841 (defun python-indent-toggle-levels ()
842 "Toggle `python-indent-current-level' over `python-indent-levels'."
843 (setq python-indent-current-level (1- python-indent-current-level))
844 (when (< python-indent-current-level 0)
845 (setq python-indent-current-level (1- (length python-indent-levels)))))
847 (defun python-indent-line (&optional force-toggle)
848 "Internal implementation of `python-indent-line-function'.
849 Uses the offset calculated in
850 `python-indent-calculate-indentation' and available levels
851 indicated by the variable `python-indent-levels' to set the
854 When the variable `last-command' is equal to
855 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
856 levels indicated in the variable `python-indent-levels' by
857 setting the current level in the variable
858 `python-indent-current-level'.
860 When the variable `last-command' is not equal to
861 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
862 possible indentation levels and saves it in the variable
863 `python-indent-levels'. Afterwards it sets the variable
864 `python-indent-current-level' correctly so offset is equal
865 to (`nth' `python-indent-current-level' `python-indent-levels')"
866 (if (or (and (eq this-command 'indent-for-tab-command)
867 (eq last-command this-command))
869 (if (not (equal python-indent-levels '(0)))
870 (python-indent-toggle-levels)
871 (python-indent-calculate-levels))
872 (python-indent-calculate-levels))
874 (delete-horizontal-space)
875 (indent-to (nth python-indent-current-level python-indent-levels))
876 (python-info-closing-block-message))
878 (defun python-indent-line-function ()
879 "`indent-line-function' for Python mode.
880 See `python-indent-line' for details."
881 (python-indent-line))
883 (defun python-indent-dedent-line ()
884 "De-indent current line."
886 (when (and (not (python-info-ppss-comment-or-string-p))
887 (<= (point-marker) (save-excursion
888 (back-to-indentation)
890 (> (current-column) 0))
891 (python-indent-line t)
894 (defun python-indent-dedent-line-backspace (arg)
895 "De-indent current line.
896 Argument ARG is passed to `backward-delete-char-untabify' when
897 point is not in between the indentation."
899 (when (not (python-indent-dedent-line))
900 (backward-delete-char-untabify arg)))
901 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
903 (defun python-indent-region (start end)
904 "Indent a python region automagically.
906 Called from a program, START and END specify the region to indent."
907 (let ((deactivate-mark nil))
910 (setq end (point-marker))
912 (or (bolp) (forward-line 1))
913 (while (< (point) end)
914 (or (and (bolp) (eolp))
917 (back-to-indentation)
918 (setq word (current-word))
922 (delete-horizontal-space)
923 (indent-to (python-indent-calculate-indentation)))))
925 (move-marker end nil))))
927 (defun python-indent-shift-left (start end &optional count)
928 "Shift lines contained in region START END by COUNT columns to the left.
929 COUNT defaults to `python-indent-offset'. If region isn't
930 active, the current line is shifted. The shifted region includes
931 the lines in which START and END lie. An error is signaled if
932 any lines in the region are indented less than COUNT columns."
935 (list (region-beginning) (region-end) current-prefix-arg)
936 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
938 (setq count (prefix-numeric-value count))
939 (setq count python-indent-offset))
941 (let ((deactivate-mark nil))
944 (while (< (point) end)
945 (if (and (< (current-indentation) count)
946 (not (looking-at "[ \t]*$")))
947 (error "Can't shift all lines enough"))
949 (indent-rigidly start end (- count))))))
951 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
953 (defun python-indent-shift-right (start end &optional count)
954 "Shift lines contained in region START END by COUNT columns to the left.
955 COUNT defaults to `python-indent-offset'. If region isn't
956 active, the current line is shifted. The shifted region includes
957 the lines in which START and END lie."
960 (list (region-beginning) (region-end) current-prefix-arg)
961 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
962 (let ((deactivate-mark nil))
964 (setq count (prefix-numeric-value count))
965 (setq count python-indent-offset))
966 (indent-rigidly start end count)))
968 (defun python-indent-electric-colon (arg)
969 "Insert a colon and maybe de-indent the current line.
970 With numeric ARG, just insert that many colons. With
971 \\[universal-argument], just insert a single colon."
973 (self-insert-command (if (not (integerp arg)) 1 arg))
976 (not (equal ?: (char-after (- (point-marker) 2))))
977 (not (python-info-ppss-comment-or-string-p)))
978 (let ((indentation (current-indentation))
979 (calculated-indentation (python-indent-calculate-indentation)))
980 (python-info-closing-block-message)
981 (when (> indentation calculated-indentation)
983 (indent-line-to calculated-indentation)
984 (when (not (python-info-closing-block-message))
985 (indent-line-to indentation)))))))
986 (put 'python-indent-electric-colon 'delete-selection t)
988 (defun python-indent-post-self-insert-function ()
989 "Adjust closing paren line indentation after a char is added.
990 This function is intended to be added to the
991 `post-self-insert-hook.' If a line renders a paren alone, after
992 adding a char before it, the line will be re-indented
993 automatically if needed."
994 (when (and (eq (char-before) last-command-event)
996 (memq (char-after) '(?\) ?\] ?\})))
998 (goto-char (line-beginning-position))
999 ;; If after going to the beginning of line the point
1000 ;; is still inside a paren it's ok to do the trick
1001 (when (python-info-ppss-context 'paren)
1002 (let ((indentation (python-indent-calculate-indentation)))
1003 (when (< (current-indentation) indentation)
1004 (indent-line-to indentation)))))))
1009 (defvar python-nav-beginning-of-defun-regexp
1010 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1011 "Regexp matching class or function definition.
1012 The name of the defun should be grouped so it can be retrieved
1013 via `match-string'.")
1015 (defun python-nav-beginning-of-defun (&optional arg)
1016 "Move point to `beginning-of-defun'.
1017 With positive ARG move search backwards. With negative do the
1018 same but forward. When ARG is nil or 0 defaults to 1. This is
1019 the main part of `python-beginning-of-defun-function'. Return
1020 non-nil if point is moved to `beginning-of-defun'."
1021 (when (or (null arg) (= arg 0)) (setq arg 1))
1022 (let* ((re-search-fn (if (> arg 0)
1023 #'re-search-backward
1024 #'re-search-forward))
1025 (line-beg-pos (line-beginning-position))
1026 (line-content-start (+ line-beg-pos (current-indentation)))
1027 (pos (point-marker))
1030 (when (and (< arg 0)
1031 (python-info-looking-at-beginning-of-defun))
1033 (while (and (funcall re-search-fn
1034 python-nav-beginning-of-defun-regexp nil t)
1035 (python-info-ppss-context-type)))
1036 (and (python-info-looking-at-beginning-of-defun)
1037 (or (not (= (line-number-at-pos pos)
1038 (line-number-at-pos)))
1039 (and (>= (point) line-beg-pos)
1040 (<= (point) line-content-start)
1041 (> pos line-content-start)))))))
1043 (or (beginning-of-line 1) t)
1044 (and (goto-char pos) nil))))
1046 (defun python-beginning-of-defun-function (&optional arg)
1047 "Move point to the beginning of def or class.
1048 With positive ARG move that number of functions backwards. With
1049 negative do the same but forward. When ARG is nil or 0 defaults
1050 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1051 (when (or (null arg) (= arg 0)) (setq arg 1))
1053 (cond ((and (eq this-command 'mark-defun)
1054 (python-info-looking-at-beginning-of-defun)))
1056 (dotimes (i (if (> arg 0) arg (- arg)))
1057 (when (and (python-nav-beginning-of-defun arg)
1062 (defun python-end-of-defun-function ()
1063 "Move point to the end of def or class.
1064 Returns nil if point is not in a def or class."
1066 (let ((beg-defun-indent))
1067 (when (or (python-info-looking-at-beginning-of-defun)
1068 (python-beginning-of-defun-function 1)
1069 (python-beginning-of-defun-function -1))
1070 (setq beg-defun-indent (current-indentation))
1072 ;; Go as forward as possible
1074 (python-nav-beginning-of-defun -1)
1075 (and (goto-char (point-max)) nil))
1076 (> (current-indentation) beg-defun-indent)))
1077 (beginning-of-line 1)
1078 ;; Go as backwards as possible
1079 (while (and (forward-line -1)
1081 (or (not (current-word))
1082 (equal (char-after (+ (point) (current-indentation))) ?#)
1083 (<= (current-indentation) beg-defun-indent)
1084 (looking-at (python-rx decorator))
1085 (python-info-ppss-context-type))))
1087 ;; If point falls inside a paren or string context the point is
1088 ;; forwarded at the end of it (or end of buffer if its not closed)
1089 (let ((context-type (python-info-ppss-context-type)))
1090 (when (memq context-type '(paren string))
1092 (while (and (not (eobp))
1093 (python-info-ppss-context-type))
1094 (forward-line 1)))))))
1096 (defun python-nav-beginning-of-statement ()
1097 "Move to start of current statement."
1099 (while (and (or (back-to-indentation) t)
1104 (python-info-line-ends-backslash-p))
1105 (python-info-ppss-context 'string)
1106 (python-info-ppss-context 'paren))
1107 (forward-line -1)))))
1109 (defun python-nav-end-of-statement ()
1110 "Move to end of current statement."
1112 (while (and (goto-char (line-end-position))
1115 (python-info-line-ends-backslash-p)
1116 (python-info-ppss-context 'string)
1117 (python-info-ppss-context 'paren))
1118 (forward-line 1)))))
1120 (defun python-nav-backward-statement (&optional arg)
1121 "Move backward to previous statement.
1122 With ARG, repeat. See `python-nav-forward-statement'."
1124 (or arg (setq arg 1))
1125 (python-nav-forward-statement (- arg)))
1127 (defun python-nav-forward-statement (&optional arg)
1128 "Move forward to next statement.
1129 With ARG, repeat. With negative argument, move ARG times
1130 backward to previous statement."
1132 (or arg (setq arg 1))
1134 (python-nav-end-of-statement)
1135 (python-util-forward-comment)
1136 (python-nav-beginning-of-statement)
1137 (setq arg (1- arg)))
1139 (python-nav-beginning-of-statement)
1140 (python-util-forward-comment -1)
1141 (python-nav-beginning-of-statement)
1142 (setq arg (1+ arg))))
1144 (defun python-nav-beginning-of-block ()
1145 "Move to start of current block."
1147 (let ((starting-pos (point))
1148 (block-regexp (python-rx
1149 line-start (* whitespace) block-start)))
1151 (python-nav-beginning-of-statement)
1152 (looking-at (python-rx block-start)))
1154 ;; Go to first line beginning a statement
1155 (while (and (not (bobp))
1156 (or (and (python-nav-beginning-of-statement) nil)
1157 (python-info-current-line-comment-p)
1158 (python-info-current-line-empty-p)))
1160 (let ((block-matching-indent
1161 (- (current-indentation) python-indent-offset)))
1163 (and (python-nav-backward-block)
1164 (> (current-indentation) block-matching-indent)))
1165 (if (and (looking-at (python-rx block-start))
1166 (= (current-indentation) block-matching-indent))
1168 (and (goto-char starting-pos) nil))))))
1170 (defun python-nav-end-of-block ()
1171 "Move to end of current block."
1173 (when (python-nav-beginning-of-block)
1174 (let ((block-indentation (current-indentation)))
1175 (python-nav-end-of-statement)
1176 (while (and (forward-line 1)
1178 (or (and (> (current-indentation) block-indentation)
1179 (or (python-nav-end-of-statement) t))
1180 (python-info-current-line-comment-p)
1181 (python-info-current-line-empty-p))))
1182 (python-util-forward-comment -1)
1185 (defun python-nav-backward-block (&optional arg)
1186 "Move backward to previous block of code.
1187 With ARG, repeat. See `python-nav-forward-block'."
1189 (or arg (setq arg 1))
1190 (python-nav-forward-block (- arg)))
1192 (defun python-nav-forward-block (&optional arg)
1193 "Move forward to next block of code.
1194 With ARG, repeat. With negative argument, move ARG times
1195 backward to previous block."
1197 (or arg (setq arg 1))
1198 (let ((block-start-regexp
1199 (python-rx line-start (* whitespace) block-start))
1200 (starting-pos (point)))
1202 (python-nav-end-of-statement)
1204 (re-search-forward block-start-regexp nil t)
1205 (python-info-ppss-context-type)))
1206 (setq arg (1- arg)))
1208 (python-nav-beginning-of-statement)
1210 (re-search-backward block-start-regexp nil t)
1211 (python-info-ppss-context-type)))
1212 (setq arg (1+ arg)))
1213 (python-nav-beginning-of-statement)
1214 (if (not (looking-at (python-rx block-start)))
1215 (and (goto-char starting-pos) nil)
1216 (and (not (= (point) starting-pos)) (point-marker)))))
1218 (defun python-nav-forward-sexp-function (&optional arg)
1219 "Move forward across one block of code.
1220 With ARG, do it that many times. Negative arg -N means
1221 move backward N times."
1223 (or arg (setq arg 1))
1225 (let ((block-starting-pos
1226 (save-excursion (python-nav-beginning-of-block)))
1228 (save-excursion (python-nav-end-of-block)))
1229 (next-block-starting-pos
1230 (save-excursion (python-nav-forward-block))))
1231 (cond ((not block-starting-pos)
1232 (python-nav-forward-block))
1233 ((= (point) block-starting-pos)
1234 (if (or (not next-block-starting-pos)
1235 (< block-ending-pos next-block-starting-pos))
1236 (python-nav-end-of-block)
1237 (python-nav-forward-block)))
1238 ((= block-ending-pos (point))
1239 (let ((parent-block-end-pos
1241 (python-util-forward-comment)
1242 (python-nav-beginning-of-block)
1243 (python-nav-end-of-block))))
1244 (if (and parent-block-end-pos
1245 (or (not next-block-starting-pos)
1246 (> next-block-starting-pos parent-block-end-pos)))
1247 (goto-char parent-block-end-pos)
1248 (python-nav-forward-block))))
1249 (t (python-nav-end-of-block))))
1250 (setq arg (1- arg)))
1252 (let* ((block-starting-pos
1253 (save-excursion (python-nav-beginning-of-block)))
1255 (save-excursion (python-nav-end-of-block)))
1256 (prev-block-ending-pos
1257 (save-excursion (when (python-nav-backward-block)
1258 (python-nav-end-of-block))))
1259 (prev-block-parent-ending-pos
1261 (when prev-block-ending-pos
1262 (goto-char prev-block-ending-pos)
1263 (python-util-forward-comment)
1264 (python-nav-beginning-of-block)
1265 (python-nav-end-of-block)))))
1266 (cond ((not block-ending-pos)
1267 (and (python-nav-backward-block)
1268 (python-nav-end-of-block)))
1269 ((= (point) block-ending-pos)
1272 '(prev-block-parent-ending-pos
1273 prev-block-ending-pos
1275 block-starting-pos))
1276 (when (and (symbol-value name)
1277 (< (symbol-value name) (point)))
1278 (add-to-list 'candidates (symbol-value name))))
1279 (goto-char (apply 'max candidates))))
1280 ((> (point) block-ending-pos)
1281 (python-nav-end-of-block))
1282 ((= (point) block-starting-pos)
1283 (if (not (> (point) (or prev-block-ending-pos (point))))
1284 (python-nav-backward-block)
1285 (goto-char prev-block-ending-pos)
1286 (let ((parent-block-ending-pos
1288 (python-nav-forward-sexp-function)
1289 (and (not (looking-at (python-rx block-start)))
1291 (when (and parent-block-ending-pos
1292 (> parent-block-ending-pos prev-block-ending-pos))
1293 (goto-char parent-block-ending-pos)))))
1294 (t (python-nav-beginning-of-block))))
1295 (setq arg (1+ arg))))
1298 ;;; Shell integration
1300 (defcustom python-shell-buffer-name "Python"
1301 "Default buffer name for Python interpreter."
1306 (defcustom python-shell-interpreter "python"
1307 "Default Python interpreter for shell."
1311 (defcustom python-shell-internal-buffer-name "Python Internal"
1312 "Default buffer name for the Internal Python interpreter."
1317 (defcustom python-shell-interpreter-args "-i"
1318 "Default arguments for the Python interpreter."
1322 (defcustom python-shell-prompt-regexp ">>> "
1323 "Regular Expression matching top\-level input prompt of python shell.
1324 It should not contain a caret (^) at the beginning."
1329 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1330 "Regular Expression matching block input prompt of python shell.
1331 It should not contain a caret (^) at the beginning."
1336 (defcustom python-shell-prompt-output-regexp ""
1337 "Regular Expression matching output prompt of python shell.
1338 It should not contain a caret (^) at the beginning."
1343 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1344 "Regular Expression matching pdb input prompt of python shell.
1345 It should not contain a caret (^) at the beginning."
1350 (defcustom python-shell-enable-font-lock t
1351 "Should syntax highlighting be enabled in the python shell buffer?
1352 Restart the python shell after changing this variable for it to take effect."
1357 (defcustom python-shell-send-setup-max-wait 5
1358 "Seconds to wait for process output before code setup.
1359 If output is received before the specified time then control is
1360 returned in that moment and not after waiting."
1365 (defcustom python-shell-process-environment nil
1366 "List of environment variables for Python shell.
1367 This variable follows the same rules as `process-environment'
1368 since it merges with it before the process creation routines are
1369 called. When this variable is nil, the Python shell is run with
1370 the default `process-environment'."
1371 :type '(repeat string)
1375 (defcustom python-shell-extra-pythonpaths nil
1376 "List of extra pythonpaths for Python shell.
1377 The values of this variable are added to the existing value of
1378 PYTHONPATH in the `process-environment' variable."
1379 :type '(repeat string)
1383 (defcustom python-shell-exec-path nil
1384 "List of path to search for binaries.
1385 This variable follows the same rules as `exec-path' since it
1386 merges with it before the process creation routines are called.
1387 When this variable is nil, the Python shell is run with the
1388 default `exec-path'."
1389 :type '(repeat string)
1393 (defcustom python-shell-virtualenv-path nil
1394 "Path to virtualenv root.
1395 This variable, when set to a string, makes the values stored in
1396 `python-shell-process-environment' and `python-shell-exec-path'
1397 to be modified properly so shells are started with the specified
1403 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1404 python-ffap-setup-code
1405 python-eldoc-setup-code)
1406 "List of code run by `python-shell-send-setup-codes'."
1407 :type '(repeat symbol)
1411 (defcustom python-shell-compilation-regexp-alist
1412 `((,(rx line-start (1+ (any " \t")) "File \""
1413 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1414 "\", line " (group (1+ digit)))
1416 (,(rx " in file " (group (1+ not-newline)) " on line "
1419 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1420 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1422 "`compilation-error-regexp-alist' for inferior Python."
1423 :type '(alist string)
1426 (defun python-shell-get-process-name (dedicated)
1427 "Calculate the appropriate process name for inferior Python process.
1428 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1429 returns a string with the form
1430 `python-shell-buffer-name'[variable `buffer-file-name'] else
1431 returns the value of `python-shell-buffer-name'. After
1432 calculating the process name adds the buffer name for the process
1433 in the `same-window-buffer-names' list."
1437 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1438 (format "%s" python-shell-buffer-name))))
1439 (add-to-list 'same-window-buffer-names (purecopy
1440 (format "*%s*" process-name)))
1443 (defun python-shell-internal-get-process-name ()
1444 "Calculate the appropriate process name for Internal Python process.
1445 The name is calculated from `python-shell-global-buffer-name' and
1446 a hash of all relevant global shell settings in order to ensure
1447 uniqueness for different types of configurations."
1449 python-shell-internal-buffer-name
1452 (python-shell-parse-command)
1453 python-shell-prompt-regexp
1454 python-shell-prompt-block-regexp
1455 python-shell-prompt-output-regexp
1456 (mapconcat #'symbol-value python-shell-setup-codes "")
1457 (mapconcat #'identity python-shell-process-environment "")
1458 (mapconcat #'identity python-shell-extra-pythonpaths "")
1459 (mapconcat #'identity python-shell-exec-path "")
1460 (or python-shell-virtualenv-path "")
1461 (mapconcat #'identity python-shell-exec-path "")))))
1463 (defun python-shell-parse-command ()
1464 "Calculate the string used to execute the inferior Python process."
1465 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1467 (defun python-shell-calculate-process-environment ()
1468 "Calculate process environment given `python-shell-virtualenv-path'."
1469 (let ((process-environment (append
1470 python-shell-process-environment
1471 process-environment nil))
1472 (virtualenv (if python-shell-virtualenv-path
1473 (directory-file-name python-shell-virtualenv-path)
1475 (when python-shell-extra-pythonpaths
1476 (setenv "PYTHONPATH"
1478 (mapconcat 'identity
1479 python-shell-extra-pythonpaths
1482 (or (getenv "PYTHONPATH") ""))))
1483 (if (not virtualenv)
1485 (setenv "PYTHONHOME" nil)
1486 (setenv "PATH" (format "%s/bin%s%s"
1487 virtualenv path-separator
1488 (or (getenv "PATH") "")))
1489 (setenv "VIRTUAL_ENV" virtualenv))
1490 process-environment))
1492 (defun python-shell-calculate-exec-path ()
1493 "Calculate exec path given `python-shell-virtualenv-path'."
1494 (let ((path (append python-shell-exec-path
1496 (if (not python-shell-virtualenv-path)
1498 (cons (format "%s/bin"
1499 (directory-file-name python-shell-virtualenv-path))
1502 (defun python-comint-output-filter-function (output)
1503 "Hook run after content is put into comint buffer.
1504 OUTPUT is a string with the contents of the buffer."
1505 (ansi-color-filter-apply output))
1507 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1508 "Major mode for Python inferior process.
1509 Runs a Python interpreter as a subprocess of Emacs, with Python
1510 I/O through an Emacs buffer. Variables
1511 `python-shell-interpreter' and `python-shell-interpreter-args'
1512 controls which Python interpreter is run. Variables
1513 `python-shell-prompt-regexp',
1514 `python-shell-prompt-output-regexp',
1515 `python-shell-prompt-block-regexp',
1516 `python-shell-enable-font-lock',
1517 `python-shell-completion-setup-code',
1518 `python-shell-completion-string-code',
1519 `python-shell-completion-module-string-code',
1520 `python-eldoc-setup-code', `python-eldoc-string-code',
1521 `python-ffap-setup-code' and `python-ffap-string-code' can
1522 customize this mode for different Python interpreters.
1524 You can also add additional setup code to be run at
1525 initialization of the interpreter via `python-shell-setup-codes'
1528 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1529 (set-syntax-table python-mode-syntax-table)
1530 (setq mode-line-process '(":%s"))
1531 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1532 python-shell-prompt-regexp
1533 python-shell-prompt-block-regexp
1534 python-shell-prompt-pdb-regexp))
1535 (make-local-variable 'comint-output-filter-functions)
1536 (add-hook 'comint-output-filter-functions
1537 'python-comint-output-filter-function)
1538 (add-hook 'comint-output-filter-functions
1539 'python-pdbtrack-comint-output-filter-function)
1540 (set (make-local-variable 'compilation-error-regexp-alist)
1541 python-shell-compilation-regexp-alist)
1542 (define-key inferior-python-mode-map [remap complete-symbol]
1543 'completion-at-point)
1544 (add-hook 'completion-at-point-functions
1545 'python-shell-completion-complete-at-point nil 'local)
1546 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1547 'python-shell-completion-complete-at-point)
1548 (define-key inferior-python-mode-map "\t"
1549 'python-shell-completion-complete-or-indent)
1550 (when python-shell-enable-font-lock
1551 (set (make-local-variable 'font-lock-defaults)
1552 '(python-font-lock-keywords nil nil nil nil))
1553 (set (make-local-variable 'syntax-propertize-function)
1554 python-syntax-propertize-function))
1555 (compilation-shell-minor-mode 1))
1557 (defun python-shell-make-comint (cmd proc-name &optional pop)
1558 "Create a python shell comint buffer.
1559 CMD is the python command to be executed and PROC-NAME is the
1560 process name the comint buffer will get. After the comint buffer
1561 is created the `inferior-python-mode' is activated. If POP is
1562 non-nil the buffer is shown."
1564 (let* ((proc-buffer-name (format "*%s*" proc-name))
1565 (process-environment (python-shell-calculate-process-environment))
1566 (exec-path (python-shell-calculate-exec-path)))
1567 (when (not (comint-check-proc proc-buffer-name))
1568 (let* ((cmdlist (split-string-and-unquote cmd))
1569 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1571 (current-buffer (current-buffer)))
1572 (with-current-buffer buffer
1573 (inferior-python-mode)
1574 (python-util-clone-local-variables current-buffer))))
1575 (and pop (pop-to-buffer proc-buffer-name t))
1579 (defun run-python (cmd &optional dedicated show)
1580 "Run an inferior Python process.
1581 Input and output via buffer named after
1582 `python-shell-buffer-name'. If there is a process already
1583 running in that buffer, just switch to it.
1585 With argument, allows you to define CMD so you can edit the
1586 command used to call the interpreter and define DEDICATED, so a
1587 dedicated process for the current buffer is open. When numeric
1588 prefix arg is other than 0 or 4 do not SHOW.
1590 Runs the hook `inferior-python-mode-hook' (after the
1591 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1592 process buffer for a list of commands.)"
1594 (if current-prefix-arg
1596 (read-string "Run Python: " (python-shell-parse-command))
1597 (y-or-n-p "Make dedicated process? ")
1598 (= (prefix-numeric-value current-prefix-arg) 4))
1599 (list (python-shell-parse-command) nil t)))
1600 (python-shell-make-comint
1601 cmd (python-shell-get-process-name dedicated) show)
1604 (defun run-python-internal ()
1605 "Run an inferior Internal Python process.
1606 Input and output via buffer named after
1607 `python-shell-internal-buffer-name' and what
1608 `python-shell-internal-get-process-name' returns. This new kind
1609 of shell is intended to be used for generic communication related
1610 to defined configurations. The main difference with global or
1611 dedicated shells is that these ones are attached to a
1612 configuration, not a buffer. This means that can be used for
1613 example to retrieve the sys.path and other stuff, without messing
1614 with user shells. Runs the hook
1615 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1616 run). \(Type \\[describe-mode] in the process buffer for a list
1618 (let ((python-shell-enable-font-lock nil))
1619 (set-process-query-on-exit-flag
1621 (python-shell-make-comint
1622 (python-shell-parse-command)
1623 (python-shell-internal-get-process-name))) nil)))
1625 (defun python-shell-get-process ()
1626 "Get inferior Python process for current buffer and return it."
1627 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1628 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1629 (global-proc-name (python-shell-get-process-name nil))
1630 (global-proc-buffer-name (format "*%s*" global-proc-name))
1631 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1632 (global-running (comint-check-proc global-proc-buffer-name)))
1633 ;; Always prefer dedicated
1634 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1635 (and global-running global-proc-buffer-name)))))
1637 (defun python-shell-get-or-create-process ()
1638 "Get or create an inferior Python process for current buffer and return it."
1639 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1640 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1641 (global-proc-name (python-shell-get-process-name nil))
1642 (global-proc-buffer-name (format "*%s*" global-proc-name))
1643 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1644 (global-running (comint-check-proc global-proc-buffer-name))
1645 (current-prefix-arg 16))
1646 (when (and (not dedicated-running) (not global-running))
1647 (if (call-interactively 'run-python)
1648 (setq dedicated-running t)
1649 (setq global-running t)))
1650 ;; Always prefer dedicated
1651 (get-buffer-process (if dedicated-running
1652 dedicated-proc-buffer-name
1653 global-proc-buffer-name))))
1655 (defvar python-shell-internal-buffer nil
1656 "Current internal shell buffer for the current buffer.
1657 This is really not necessary at all for the code to work but it's
1658 there for compatibility with CEDET.")
1659 (make-variable-buffer-local 'python-shell-internal-buffer)
1661 (defun python-shell-internal-get-or-create-process ()
1662 "Get or create an inferior Internal Python process."
1663 (let* ((proc-name (python-shell-internal-get-process-name))
1664 (proc-buffer-name (format "*%s*" proc-name)))
1665 (run-python-internal)
1666 (setq python-shell-internal-buffer proc-buffer-name)
1667 (get-buffer-process proc-buffer-name)))
1669 (define-obsolete-function-alias
1670 'python-proc 'python-shell-internal-get-or-create-process "24.2")
1672 (define-obsolete-variable-alias
1673 'python-buffer 'python-shell-internal-buffer "24.2")
1675 (defun python-shell-send-string (string &optional process msg)
1676 "Send STRING to inferior Python PROCESS.
1677 When MSG is non-nil messages the first line of STRING."
1678 (interactive "sPython command: ")
1679 (let ((process (or process (python-shell-get-or-create-process)))
1680 (lines (split-string string "\n" t)))
1682 (message (format "Sent: %s..." (nth 0 lines))))
1683 (if (> (length lines) 1)
1684 (let* ((temp-file-name (make-temp-file "py"))
1685 (file-name (or (buffer-file-name) temp-file-name)))
1686 (with-temp-file temp-file-name
1688 (delete-trailing-whitespace))
1689 (python-shell-send-file file-name process temp-file-name))
1690 (comint-send-string process string)
1691 (when (or (not (string-match "\n$" string))
1692 (string-match "\n[ \t].*\n?$" string))
1693 (comint-send-string process "\n")))))
1695 (defun python-shell-send-string-no-output (string &optional process msg)
1696 "Send STRING to PROCESS and inhibit output.
1697 When MSG is non-nil messages the first line of STRING. Return
1699 (let* ((output-buffer "")
1700 (process (or process (python-shell-get-or-create-process)))
1701 (comint-preoutput-filter-functions
1702 (append comint-preoutput-filter-functions
1703 '(ansi-color-filter-apply
1705 (setq output-buffer (concat output-buffer string))
1710 (python-shell-send-string string process msg)
1711 (accept-process-output process)
1712 (replace-regexp-in-string
1713 (if (> (length python-shell-prompt-output-regexp) 0)
1714 (format "\n*%s$\\|^%s\\|\n$"
1715 python-shell-prompt-regexp
1716 (or python-shell-prompt-output-regexp ""))
1717 (format "\n*$\\|^%s\\|\n$"
1718 python-shell-prompt-regexp))
1720 (with-current-buffer (process-buffer process)
1721 (comint-interrupt-subjob)))))
1723 (defun python-shell-internal-send-string (string)
1724 "Send STRING to the Internal Python interpreter.
1725 Returns the output. See `python-shell-send-string-no-output'."
1726 (python-shell-send-string-no-output
1727 ;; Makes this function compatible with the old
1728 ;; python-send-receive. (At least for CEDET).
1729 (replace-regexp-in-string "_emacs_out +" "" string)
1730 (python-shell-internal-get-or-create-process) nil))
1732 (define-obsolete-function-alias
1733 'python-send-receive 'python-shell-internal-send-string "24.2")
1735 (define-obsolete-function-alias
1736 'python-send-string 'python-shell-internal-send-string "24.2")
1738 (defun python-shell-send-region (start end)
1739 "Send the region delimited by START and END to inferior Python process."
1741 (python-shell-send-string (buffer-substring start end) nil t))
1743 (defun python-shell-send-buffer (&optional arg)
1744 "Send the entire buffer to inferior Python process.
1746 With prefix ARG include lines surrounded by \"if __name__ == '__main__':\""
1750 (python-shell-send-region
1755 (re-search-forward (python-rx if-name-main) nil t))
1756 (match-beginning 0))
1759 (defun python-shell-send-defun (arg)
1760 "Send the current defun to inferior Python process.
1761 When argument ARG is non-nil do not include decorators."
1764 (python-shell-send-region
1767 (while (and (or (python-beginning-of-defun-function)
1768 (beginning-of-line 1))
1769 (> (current-indentation) 0)))
1771 (while (and (forward-line -1)
1772 (looking-at (python-rx decorator))))
1776 (or (python-end-of-defun-function)
1780 (defun python-shell-send-file (file-name &optional process temp-file-name)
1781 "Send FILE-NAME to inferior Python PROCESS.
1782 If TEMP-FILE-NAME is passed then that file is used for processing
1783 instead, while internally the shell will continue to use
1785 (interactive "fFile to send: ")
1786 (let* ((process (or process (python-shell-get-or-create-process)))
1787 (temp-file-name (when temp-file-name
1788 (expand-file-name temp-file-name)))
1789 (file-name (or (expand-file-name file-name) temp-file-name)))
1790 (when (not file-name)
1791 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1792 (python-shell-send-string
1794 (concat "__pyfile = open('''%s''');"
1795 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1797 (or temp-file-name file-name) file-name)
1800 (defun python-shell-switch-to-shell ()
1801 "Switch to inferior Python process buffer."
1803 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1805 (defun python-shell-send-setup-code ()
1806 "Send all setup code for shell.
1807 This function takes the list of setup code to send from the
1808 `python-shell-setup-codes' list."
1809 (let ((msg "Sent %s")
1810 (process (get-buffer-process (current-buffer))))
1811 (accept-process-output process python-shell-send-setup-max-wait)
1812 (dolist (code python-shell-setup-codes)
1814 (message (format msg code))
1815 (python-shell-send-string
1816 (symbol-value code) process)))))
1818 (add-hook 'inferior-python-mode-hook
1819 #'python-shell-send-setup-code)
1822 ;;; Shell completion
1824 (defcustom python-shell-completion-setup-code
1828 def __COMPLETER_all_completions(text): []
1831 readline.set_completer(rlcompleter.Completer().complete)
1832 def __COMPLETER_all_completions(text):
1838 res = readline.get_completer()(text, i)
1841 completions.append(res)
1845 "Code used to setup completion in inferior Python processes."
1849 (defcustom python-shell-completion-string-code
1850 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1851 "Python code used to get a string of completions separated by semicolons."
1855 (defcustom python-shell-completion-module-string-code ""
1856 "Python code used to get completions separated by semicolons for imports.
1858 For IPython v0.11, add the following line to
1859 `python-shell-completion-setup-code':
1861 from IPython.core.completerlib import module_completion
1863 and use the following as the value of this variable:
1865 ';'.join(module_completion('''%s'''))\n"
1869 (defcustom python-shell-completion-pdb-string-code
1870 "';'.join(globals().keys() + locals().keys())"
1871 "Python code used to get completions separated by semicolons for [i]pdb."
1875 (defun python-shell-completion--get-completions (input process completion-code)
1876 "Retrieve available completions for INPUT using PROCESS.
1877 Argument COMPLETION-CODE is the python code used to get
1878 completions on the current context."
1879 (with-current-buffer (process-buffer process)
1880 (let ((completions (python-shell-send-string-no-output
1881 (format completion-code input) process)))
1882 (when (> (length completions) 2)
1883 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1885 (defun python-shell-completion--do-completion-at-point (process)
1886 "Do completion at point for PROCESS."
1887 (with-syntax-table python-dotty-syntax-table
1890 (let* ((paren-depth (car (syntax-ppss)))
1891 (syntax-string "w_")
1892 (syntax-list (string-to-syntax syntax-string)))
1893 ;; Stop scanning for the beginning of the completion subject
1894 ;; after the char before point matches a delimiter
1895 (while (member (car (syntax-after (1- (point)))) syntax-list)
1896 (skip-syntax-backward syntax-string)
1897 (when (or (equal (char-before) ?\))
1898 (equal (char-before) ?\"))
1901 ;; honor initial paren depth
1902 (> (car (syntax-ppss)) paren-depth)
1903 (python-info-ppss-context 'string))
1904 (forward-char -1))))
1907 (line (buffer-substring-no-properties (point-at-bol) end))
1908 (input (buffer-substring-no-properties beg end))
1909 ;; Get the last prompt for the inferior process buffer. This is
1910 ;; used for the completion code selection heuristic.
1912 (with-current-buffer (process-buffer process)
1913 (buffer-substring-no-properties
1914 (overlay-start comint-last-prompt-overlay)
1915 (overlay-end comint-last-prompt-overlay))))
1917 ;; Check whether a prompt matches a pdb string, an import statement
1918 ;; or just the standard prompt and use the correct
1919 ;; python-shell-completion-*-code string
1920 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
1922 (concat "^" python-shell-prompt-pdb-regexp) prompt))
1925 (length python-shell-completion-module-string-code) 0)
1927 (concat "^" python-shell-prompt-regexp) prompt)
1928 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
1931 (concat "^" python-shell-prompt-regexp) prompt)
1935 (case completion-context
1936 ('pdb python-shell-completion-pdb-string-code)
1937 ('import python-shell-completion-module-string-code)
1938 ('default python-shell-completion-string-code)
1941 (if (eq completion-context 'import)
1942 (replace-regexp-in-string "^[ \t]+" "" line)
1945 (and completion-code (> (length input) 0)
1946 (python-shell-completion--get-completions
1947 input process completion-code))))
1948 (list beg end completions))))
1950 (defun python-shell-completion-complete-at-point ()
1951 "Perform completion at point in inferior Python process."
1952 (and comint-last-prompt-overlay
1953 (> (point-marker) (overlay-end comint-last-prompt-overlay))
1954 (python-shell-completion--do-completion-at-point
1955 (get-buffer-process (current-buffer)))))
1957 (defun python-shell-completion-complete-or-indent ()
1958 "Complete or indent depending on the context.
1959 If content before pointer is all whitespace indent. If not try
1962 (if (string-match "^[[:space:]]*$"
1963 (buffer-substring (comint-line-beginning-position)
1965 (indent-for-tab-command)
1966 (completion-at-point)))
1969 ;;; PDB Track integration
1971 (defcustom python-pdbtrack-activate t
1972 "Non-nil makes python shell enable pdbtracking."
1977 (defcustom python-pdbtrack-stacktrace-info-regexp
1978 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1979 "Regular Expression matching stacktrace information.
1980 Used to extract the current line and module being inspected."
1985 (defvar python-pdbtrack-tracked-buffer nil
1986 "Variable containing the value of the current tracked buffer.
1987 Never set this variable directly, use
1988 `python-pdbtrack-set-tracked-buffer' instead.")
1989 (make-variable-buffer-local 'python-pdbtrack-tracked-buffer)
1991 (defvar python-pdbtrack-buffers-to-kill nil
1992 "List of buffers to be deleted after tracking finishes.")
1993 (make-variable-buffer-local 'python-pdbtrack-buffers-to-kill)
1995 (defun python-pdbtrack-set-tracked-buffer (file-name)
1996 "Set the buffer for FILE-NAME as the tracked buffer.
1997 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
1998 Returns the tracked buffer."
1999 (let ((file-buffer (get-file-buffer file-name)))
2001 (setq python-pdbtrack-tracked-buffer file-buffer)
2002 (setq file-buffer (find-file-noselect file-name))
2003 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2004 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2007 (defun python-pdbtrack-comint-output-filter-function (output)
2008 "Move overlay arrow to current pdb line in tracked buffer.
2009 Argument OUTPUT is a string with the output from the comint process."
2010 (when (and python-pdbtrack-activate (not (string= output "")))
2011 (let* ((full-output (ansi-color-filter-apply
2012 (buffer-substring comint-last-input-end (point-max))))
2016 (insert full-output)
2017 (goto-char (point-min))
2018 ;; OK, this sucked but now it became a cool hack. The
2019 ;; stacktrace information normally is on the first line
2020 ;; but in some cases (like when doing a step-in) it is
2022 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
2025 (looking-at python-pdbtrack-stacktrace-info-regexp)))
2026 (setq line-number (string-to-number
2027 (match-string-no-properties 2)))
2028 (match-string-no-properties 1)))))
2029 (if (and file-name line-number)
2030 (let* ((tracked-buffer
2031 (python-pdbtrack-set-tracked-buffer file-name))
2032 (shell-buffer (current-buffer))
2033 (tracked-buffer-window (get-buffer-window tracked-buffer))
2034 (tracked-buffer-line-pos))
2035 (with-current-buffer tracked-buffer
2036 (set (make-local-variable 'overlay-arrow-string) "=>")
2037 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2038 (setq tracked-buffer-line-pos (progn
2039 (goto-char (point-min))
2040 (forward-line (1- line-number))
2042 (when tracked-buffer-window
2044 tracked-buffer-window tracked-buffer-line-pos))
2045 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2046 (pop-to-buffer tracked-buffer)
2047 (switch-to-buffer-other-window shell-buffer))
2048 (when python-pdbtrack-tracked-buffer
2049 (with-current-buffer python-pdbtrack-tracked-buffer
2050 (set-marker overlay-arrow-position nil))
2051 (mapc #'(lambda (buffer)
2052 (ignore-errors (kill-buffer buffer)))
2053 python-pdbtrack-buffers-to-kill)
2054 (setq python-pdbtrack-tracked-buffer nil
2055 python-pdbtrack-buffers-to-kill nil)))))
2059 ;;; Symbol completion
2061 (defun python-completion-complete-at-point ()
2062 "Complete current symbol at point.
2063 For this to work the best as possible you should call
2064 `python-shell-send-buffer' from time to time so context in
2065 inferior python process is updated properly."
2066 (let ((process (python-shell-get-process)))
2068 (error "Completion needs an inferior Python process running")
2069 (python-shell-completion--do-completion-at-point process))))
2071 (add-to-list 'debug-ignored-errors
2072 "^Completion needs an inferior Python process running.")
2077 (defcustom python-fill-comment-function 'python-fill-comment
2078 "Function to fill comments.
2079 This is the function used by `python-fill-paragraph-function' to
2085 (defcustom python-fill-string-function 'python-fill-string
2086 "Function to fill strings.
2087 This is the function used by `python-fill-paragraph-function' to
2093 (defcustom python-fill-decorator-function 'python-fill-decorator
2094 "Function to fill decorators.
2095 This is the function used by `python-fill-paragraph-function' to
2101 (defcustom python-fill-paren-function 'python-fill-paren
2102 "Function to fill parens.
2103 This is the function used by `python-fill-paragraph-function' to
2109 (defun python-fill-paragraph-function (&optional justify)
2110 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2111 If any of the current line is in or at the end of a multi-line string,
2112 fill the string or the paragraph of it that point is in, preserving
2113 the string's indentation.
2114 Optional argument JUSTIFY defines if the paragraph should be justified."
2117 (back-to-indentation)
2120 ((funcall python-fill-comment-function justify))
2121 ;; Strings/Docstrings
2122 ((save-excursion (skip-chars-forward "\"'uUrR")
2123 (python-info-ppss-context 'string))
2124 (funcall python-fill-string-function justify))
2126 ((equal (char-after (save-excursion
2127 (back-to-indentation)
2128 (point-marker))) ?@)
2129 (funcall python-fill-decorator-function justify))
2131 ((or (python-info-ppss-context 'paren)
2132 (looking-at (python-rx open-paren))
2134 (skip-syntax-forward "^(" (line-end-position))
2135 (looking-at (python-rx open-paren))))
2136 (funcall python-fill-paren-function justify))
2139 (defun python-fill-comment (&optional justify)
2140 "Comment fill function for `python-fill-paragraph-function'.
2141 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2142 (fill-comment-paragraph justify))
2144 (defun python-fill-string (&optional justify)
2145 "String fill function for `python-fill-paragraph-function'.
2146 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2147 (let ((marker (point-marker))
2148 (string-start-marker
2150 (skip-chars-forward "\"'uUrR")
2151 (goto-char (python-info-ppss-context 'string))
2152 (skip-chars-forward "\"'uUrR")
2154 (reg-start (line-beginning-position))
2157 (while (python-info-ppss-context 'string)
2158 (goto-char (1+ (point-marker))))
2159 (skip-chars-backward "\"'")
2161 (reg-end (line-end-position))
2162 (fill-paragraph-function))
2164 (narrow-to-region reg-start reg-end)
2166 (goto-char string-start-marker)
2167 (delete-region (point-marker) (progn
2168 (skip-syntax-forward "> ")
2170 (goto-char string-end-marker)
2171 (delete-region (point-marker) (progn
2172 (skip-syntax-backward "> ")
2176 (fill-paragraph justify))
2177 ;; If there is a newline in the docstring lets put triple
2178 ;; quote in it's own line to follow pep 8
2179 (when (save-excursion
2180 (re-search-backward "\n" string-start-marker t))
2182 (newline-and-indent))
2183 (fill-paragraph justify)))) t)
2185 (defun python-fill-decorator (&optional justify)
2186 "Decorator fill function for `python-fill-paragraph-function'.
2187 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2190 (defun python-fill-paren (&optional justify)
2191 "Paren fill function for `python-fill-paragraph-function'.
2192 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2194 (narrow-to-region (progn
2195 (while (python-info-ppss-context 'paren)
2196 (goto-char (1- (point-marker))))
2198 (line-beginning-position))
2200 (when (not (python-info-ppss-context 'paren))
2202 (when (not (python-info-ppss-context 'paren))
2203 (skip-syntax-backward "^)")))
2204 (while (python-info-ppss-context 'paren)
2205 (goto-char (1+ (point-marker))))
2207 (let ((paragraph-start "\f\\|[ \t]*$")
2208 (paragraph-separate ",")
2209 (fill-paragraph-function))
2210 (goto-char (point-min))
2211 (fill-paragraph justify))
2214 (python-indent-line)
2215 (goto-char (line-end-position)))) t)
2220 (defcustom python-skeleton-autoinsert nil
2221 "Non-nil means template skeletons will be automagically inserted.
2222 This happens when pressing \"if<SPACE>\", for example, to prompt for
2228 (define-obsolete-variable-alias
2229 'python-use-skeletons 'python-skeleton-autoinsert "24.2")
2231 (defvar python-skeleton-available '()
2232 "Internal list of available skeletons.")
2234 (define-abbrev-table 'python-mode-abbrev-table ()
2235 "Abbrev table for Python mode."
2237 ;; Allow / inside abbrevs.
2238 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2239 ;; Only expand in code.
2240 :enable-function (lambda ()
2242 (not (python-info-ppss-comment-or-string-p))
2243 python-skeleton-autoinsert)))
2245 (defmacro python-skeleton-define (name doc &rest skel)
2246 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2247 The skeleton will be bound to python-skeleton-NAME and will
2248 be added to `python-mode-abbrev-table'."
2249 (declare (indent 2))
2250 (let* ((name (symbol-name name))
2251 (function-name (intern (concat "python-skeleton-" name))))
2253 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
2255 (setq python-skeleton-available
2256 (cons ',function-name python-skeleton-available))
2257 (define-skeleton ,function-name
2259 (format "Insert %s statement." name))
2262 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2263 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2264 The skeleton will be bound to python-skeleton-NAME."
2265 (declare (indent 2))
2266 (let* ((name (symbol-name name))
2267 (function-name (intern (concat "python-skeleton--" name)))
2269 "Add '%s' clause? " name)))
2272 `(< ,(format "%s:" name) \n \n
2274 `(define-skeleton ,function-name
2276 (format "Auxiliary skeleton for %s statement." name))
2278 (unless (y-or-n-p ,msg)
2282 (python-define-auxiliary-skeleton else nil)
2284 (python-define-auxiliary-skeleton except nil)
2286 (python-define-auxiliary-skeleton finally nil)
2288 (python-skeleton-define if nil
2292 ("other condition, %s: "
2296 '(python-skeleton--else) | ^)
2298 (python-skeleton-define while nil
2302 '(python-skeleton--else) | ^)
2304 (python-skeleton-define for nil
2308 '(python-skeleton--else) | ^)
2310 (python-skeleton-define try nil
2316 "except " str ":" \n
2319 '(python-skeleton--except)
2320 '(python-skeleton--else)
2321 '(python-skeleton--finally) | ^)
2323 (python-skeleton-define def nil
2325 "def " str " (" ("Parameter, %s: "
2326 (unless (equal ?\( (char-before)) ", ")
2328 "\"\"\"" - "\"\"\"" \n
2331 (python-skeleton-define class nil
2333 "class " str " (" ("Inheritance, %s: "
2334 (unless (equal ?\( (char-before)) ", ")
2338 "\"\"\"" - "\"\"\"" \n
2341 (defun python-skeleton-add-menu-items ()
2342 "Add menu items to Python->Skeletons menu."
2343 (let ((skeletons (sort python-skeleton-available 'string<))
2345 (dolist (skeleton skeletons)
2347 nil '("Python" "Skeletons")
2349 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2354 (defcustom python-ffap-setup-code
2355 "def __FFAP_get_module_path(module):
2358 path = __import__(module).__file__
2359 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2364 "Python code to get a module path."
2368 (defcustom python-ffap-string-code
2369 "__FFAP_get_module_path('''%s''')\n"
2370 "Python code used to get a string with the path of a module."
2374 (defun python-ffap-module-path (module)
2375 "Function for `ffap-alist' to return path for MODULE."
2377 (and (eq major-mode 'inferior-python-mode)
2378 (get-buffer-process (current-buffer)))
2379 (python-shell-get-process))))
2383 (python-shell-send-string-no-output
2384 (format python-ffap-string-code module) process)))
2386 (substring-no-properties module-file 1 -1))))))
2388 (eval-after-load "ffap"
2390 (push '(python-mode . python-ffap-module-path) ffap-alist)
2391 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2396 (defcustom python-check-command
2398 "Command used to check a Python file."
2402 (defcustom python-check-buffer-name
2403 "*Python check: %s*"
2404 "Buffer name used for check commands."
2408 (defvar python-check-custom-command nil
2411 (defun python-check (command)
2412 "Check a Python file (default current buffer's file).
2413 Runs COMMAND, a shell command, as if by `compile'. See
2414 `python-check-command' for the default."
2416 (list (read-string "Check command: "
2417 (or python-check-custom-command
2418 (concat python-check-command " "
2419 (shell-quote-argument
2421 (let ((name (buffer-file-name)))
2423 (file-name-nondirectory name)))
2425 (setq python-check-custom-command command)
2426 (save-some-buffers (not compilation-ask-about-save) nil)
2427 (let ((process-environment (python-shell-calculate-process-environment))
2428 (exec-path (python-shell-calculate-exec-path)))
2429 (compilation-start command nil
2431 (format python-check-buffer-name command)))))
2436 (defcustom python-eldoc-setup-code
2437 "def __PYDOC_get_help(obj):
2440 if hasattr(obj, 'startswith'):
2441 obj = eval(obj, globals())
2442 doc = inspect.getdoc(obj)
2443 if not doc and callable(obj):
2445 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2446 target = obj.__init__
2452 args = inspect.formatargspec(
2453 *inspect.getargspec(target)
2456 doc = '{objtype} {name}{args}'.format(
2457 objtype=objtype, name=name, args=args
2460 doc = doc.splitlines()[0]
2467 "Python code to setup documentation retrieval."
2471 (defcustom python-eldoc-string-code
2472 "__PYDOC_get_help('''%s''')\n"
2473 "Python code used to get a string with the documentation of an object."
2477 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2478 "Internal implementation to get documentation at point.
2479 If not FORCE-INPUT is passed then what
2480 `python-info-current-symbol' returns will be used. If not
2481 FORCE-PROCESS is passed what `python-shell-get-process' returns
2483 (let ((process (or force-process (python-shell-get-process))))
2485 (error "Eldoc needs an inferior Python process running")
2486 (let ((input (or force-input
2487 (python-info-current-symbol t))))
2489 (python-shell-send-string-no-output
2490 (format python-eldoc-string-code input)
2493 (defun python-eldoc-function ()
2494 "`eldoc-documentation-function' for Python.
2495 For this to work the best as possible you should call
2496 `python-shell-send-buffer' from time to time so context in
2497 inferior python process is updated properly."
2498 (python-eldoc--get-doc-at-point))
2500 (defun python-eldoc-at-point (symbol)
2501 "Get help on SYMBOL using `help'.
2502 Interactively, prompt for symbol."
2504 (let ((symbol (python-info-current-symbol t))
2505 (enable-recursive-minibuffers t))
2506 (list (read-string (if symbol
2507 (format "Describe symbol (default %s): " symbol)
2508 "Describe symbol: ")
2510 (message (python-eldoc--get-doc-at-point symbol)))
2512 (add-to-list 'debug-ignored-errors
2513 "^Eldoc needs an inferior Python process running.")
2518 (defun python-info-current-defun (&optional include-type)
2519 "Return name of surrounding function with Python compatible dotty syntax.
2520 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2521 This function is compatible to be used as
2522 `add-log-current-defun-function' since it returns nil if point is
2523 not inside a defun."
2525 (starting-indentation)
2531 (setq starting-point (point-marker))
2532 (setq starting-indentation (save-excursion
2533 (python-nav-beginning-of-statement)
2534 (current-indentation)))
2536 (while (python-beginning-of-defun-function 1)
2537 (when (or (< (current-indentation) starting-indentation)
2542 (python-end-of-defun-function)
2544 (setq first-run nil)
2545 (setq starting-indentation (current-indentation))
2546 (looking-at python-nav-beginning-of-defun-regexp)
2548 (if (not include-type)
2549 (match-string-no-properties 1)
2550 (mapconcat 'identity
2552 (match-string-no-properties 0)) " "))
2555 (mapconcat (lambda (string) string) names "."))))
2557 (defun python-info-current-symbol (&optional replace-self)
2558 "Return current symbol using dotty syntax.
2559 With optional argument REPLACE-SELF convert \"self\" to current
2562 (and (not (python-info-ppss-comment-or-string-p))
2563 (with-syntax-table python-dotty-syntax-table
2564 (let ((sym (symbol-at-point)))
2566 (substring-no-properties (symbol-name sym))))))))
2568 (if (not replace-self)
2570 (let ((current-defun (python-info-current-defun)))
2571 (if (not current-defun)
2573 (replace-regexp-in-string
2574 (python-rx line-start word-start "self" word-end ?.)
2576 (mapconcat 'identity
2577 (butlast (split-string current-defun "\\."))
2581 (defsubst python-info-beginning-of-block-statement-p ()
2582 "Return non-nil if current statement opens a block."
2584 (python-nav-beginning-of-statement)
2585 (looking-at (python-rx block-start))))
2587 (defun python-info-closing-block ()
2588 "Return the point of the block the current line closes."
2589 (let ((closing-word (save-excursion
2590 (back-to-indentation)
2592 (indentation (current-indentation)))
2593 (when (member closing-word python-indent-dedenters)
2596 (while (and (> (current-indentation) indentation)
2598 (not (back-to-indentation))
2600 (back-to-indentation)
2602 ((not (equal indentation (current-indentation))) nil)
2603 ((string= closing-word "elif")
2604 (when (member (current-word) '("if" "elif"))
2606 ((string= closing-word "else")
2607 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2609 ((string= closing-word "except")
2610 (when (member (current-word) '("try"))
2612 ((string= closing-word "finally")
2613 (when (member (current-word) '("except" "else"))
2614 (point-marker))))))))
2616 (defun python-info-closing-block-message (&optional closing-block-point)
2617 "Message the contents of the block the current line closes.
2618 With optional argument CLOSING-BLOCK-POINT use that instead of
2619 recalculating it calling `python-info-closing-block'."
2620 (let ((point (or closing-block-point (python-info-closing-block))))
2624 (message "Closes %s" (save-excursion
2626 (back-to-indentation)
2628 (point) (line-end-position))))))))
2630 (defun python-info-line-ends-backslash-p (&optional line-number)
2631 "Return non-nil if current line ends with backslash.
2632 With optional argument LINE-NUMBER, check that line instead."
2637 (goto-char line-number))
2638 (while (and (not (eobp))
2639 (goto-char (line-end-position))
2640 (python-info-ppss-context 'paren)
2641 (not (equal (char-before (point)) ?\\)))
2643 (when (equal (char-before) ?\\)
2646 (defun python-info-beginning-of-backslash (&optional line-number)
2647 "Return the point where the backslashed line start.
2648 Optional argument LINE-NUMBER forces the line number to check against."
2653 (goto-char line-number))
2654 (when (python-info-line-ends-backslash-p)
2655 (while (save-excursion
2656 (goto-char (line-beginning-position))
2657 (python-info-ppss-context 'paren))
2659 (back-to-indentation)
2662 (defun python-info-continuation-line-p ()
2663 "Check if current line is continuation of another.
2664 When current line is continuation of another return the point
2665 where the continued line ends."
2669 (let* ((context-type (progn
2670 (back-to-indentation)
2671 (python-info-ppss-context-type)))
2672 (line-start (line-number-at-pos))
2673 (context-start (when context-type
2674 (python-info-ppss-context context-type))))
2675 (cond ((equal context-type 'paren)
2676 ;; Lines inside a paren are always a continuation line
2677 ;; (except the first one).
2678 (python-util-forward-comment -1)
2680 ((member context-type '(string comment))
2681 ;; move forward an roll again
2682 (goto-char context-start)
2683 (python-util-forward-comment)
2684 (python-info-continuation-line-p))
2686 ;; Not within a paren, string or comment, the only way
2687 ;; we are dealing with a continuation line is that
2688 ;; previous line contains a backslash, and this can
2689 ;; only be the previous line from current
2690 (back-to-indentation)
2691 (python-util-forward-comment -1)
2692 (when (and (equal (1- line-start) (line-number-at-pos))
2693 (python-info-line-ends-backslash-p))
2694 (point-marker))))))))
2696 (defun python-info-block-continuation-line-p ()
2697 "Return non-nil if current line is a continuation of a block."
2699 (when (python-info-continuation-line-p)
2701 (back-to-indentation)
2702 (when (looking-at (python-rx block-start))
2705 (defun python-info-assignment-continuation-line-p ()
2706 "Check if current line is a continuation of an assignment.
2707 When current line is continuation of another with an assignment
2708 return the point of the first non-blank character after the
2711 (when (python-info-continuation-line-p)
2713 (back-to-indentation)
2714 (when (and (not (looking-at (python-rx block-start)))
2715 (and (re-search-forward (python-rx not-simple-operator
2717 not-simple-operator)
2718 (line-end-position) t)
2719 (not (python-info-ppss-context-type))))
2720 (skip-syntax-forward "\s")
2723 (defun python-info-ppss-context (type &optional syntax-ppss)
2724 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2725 TYPE can be `comment', `string' or `paren'. It returns the start
2726 character address of the specified TYPE."
2727 (let ((ppss (or syntax-ppss (syntax-ppss))))
2733 (and (not (nth 4 ppss))
2739 (defun python-info-ppss-context-type (&optional syntax-ppss)
2740 "Return the context type using SYNTAX-PPSS.
2741 The type returned can be `comment', `string' or `paren'."
2742 (let ((ppss (or syntax-ppss (syntax-ppss))))
2744 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
2745 ((nth 1 ppss) 'paren))))
2747 (defsubst python-info-ppss-comment-or-string-p ()
2748 "Return non-nil if point is inside 'comment or 'string."
2749 (nth 8 (syntax-ppss)))
2751 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
2752 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2753 (and (not (python-info-ppss-context-type (or syntax-ppss (syntax-ppss))))
2755 (beginning-of-line 1)
2756 (looking-at python-nav-beginning-of-defun-regexp))))
2758 (defun python-info-current-line-comment-p ()
2759 "Check if current line is a comment line."
2760 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
2762 (defun python-info-current-line-empty-p ()
2763 "Check if current line is empty, ignoring whitespace."
2765 (beginning-of-line 1)
2767 (python-rx line-start (* whitespace)
2768 (group (* not-newline))
2769 (* whitespace) line-end))
2770 (string-equal "" (match-string-no-properties 1))))
2773 ;;; Utility functions
2775 (defun python-util-position (item seq)
2776 "Find the first occurrence of ITEM in SEQ.
2777 Return the index of the matching item, or nil if not found."
2778 (let ((member-result (member item seq)))
2780 (- (length seq) (length member-result)))))
2782 ;; Stolen from org-mode
2783 (defun python-util-clone-local-variables (from-buffer &optional regexp)
2784 "Clone local variables from FROM-BUFFER.
2785 Optional argument REGEXP selects variables to clone and defaults
2789 (and (symbolp (car pair))
2790 (string-match (or regexp "^python-")
2791 (symbol-name (car pair)))
2792 (set (make-local-variable (car pair))
2794 (buffer-local-variables from-buffer)))
2796 (defun python-util-forward-comment (&optional direction)
2797 "Python mode specific version of `forward-comment'.
2798 Optional argument DIRECTION defines the direction to move to."
2799 (let ((comment-start (python-info-ppss-context 'comment))
2800 (factor (if (< (or direction 0) 0)
2804 (goto-char comment-start))
2805 (forward-comment factor)))
2809 (define-derived-mode python-mode prog-mode "Python"
2810 "Major mode for editing Python files.
2813 Entry to this mode calls the value of `python-mode-hook'
2814 if that value is non-nil."
2815 (set (make-local-variable 'tab-width) 8)
2816 (set (make-local-variable 'indent-tabs-mode) nil)
2818 (set (make-local-variable 'comment-start) "# ")
2819 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2821 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2822 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2824 (set (make-local-variable 'forward-sexp-function)
2825 'python-nav-forward-sexp-function)
2827 (set (make-local-variable 'font-lock-defaults)
2828 '(python-font-lock-keywords nil nil nil nil))
2830 (set (make-local-variable 'syntax-propertize-function)
2831 python-syntax-propertize-function)
2833 (set (make-local-variable 'indent-line-function)
2834 #'python-indent-line-function)
2835 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2837 (set (make-local-variable 'paragraph-start) "\\s-*$")
2838 (set (make-local-variable 'fill-paragraph-function)
2839 'python-fill-paragraph-function)
2841 (set (make-local-variable 'beginning-of-defun-function)
2842 #'python-beginning-of-defun-function)
2843 (set (make-local-variable 'end-of-defun-function)
2844 #'python-end-of-defun-function)
2846 (add-hook 'completion-at-point-functions
2847 'python-completion-complete-at-point nil 'local)
2849 (add-hook 'post-self-insert-hook
2850 'python-indent-post-self-insert-function nil 'local)
2852 (set (make-local-variable 'imenu-extract-index-name-function)
2853 #'python-info-current-defun)
2855 (set (make-local-variable 'add-log-current-defun-function)
2856 #'python-info-current-defun)
2858 (add-hook 'which-func-functions #'python-info-current-defun nil t)
2860 (set (make-local-variable 'skeleton-further-elements)
2862 (< '(backward-delete-char-untabify (min python-indent-offset
2864 (^ '(- (1+ (current-indentation))))))
2866 (set (make-local-variable 'eldoc-documentation-function)
2867 #'python-eldoc-function)
2869 (add-to-list 'hs-special-modes-alist
2870 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2872 (python-end-of-defun-function)) nil))
2874 (set (make-local-variable 'mode-require-final-newline) t)
2876 (set (make-local-variable 'outline-regexp)
2877 (python-rx (* space) block-start))
2878 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2879 (set (make-local-variable 'outline-level)
2881 "`outline-level' function for Python mode."
2882 (1+ (/ (current-indentation) python-indent-offset))))
2884 (python-skeleton-add-menu-items)
2886 (when python-indent-guess-indent-offset
2887 (python-indent-guess-indent-offset)))
2894 ;; indent-tabs-mode: nil
2897 ;;; python.el ends here