1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2010, 2011 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 NOT part of GNU Emacs.
14 ;; python.el is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; python.el is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with python.el. 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 ;; While it probably has less features than Dave Love's python.el and
34 ;; PSF's python-mode.el it provides the main stuff you'll need while
35 ;; keeping it simple :)
37 ;; Implements Syntax highlighting, Indentation, Movement, Shell
38 ;; interaction, Shell completion, Shell virtualenv support, Pdb
39 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
42 ;; Syntax highlighting: Fontification of code is provided and supports
43 ;; python's triple quoted strings properly.
45 ;; Indentation: Automatic indentation with indentation cycling is
46 ;; provided, it allows you to navigate different available levels of
47 ;; indentation by hitting <tab> several times. Also when inserting a
48 ;; colon the `python-indent-electric-colon' command is invoked and
49 ;; causes the current line to be dedented automatically if needed.
51 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
52 ;; properly implemented. Also there are specialized
53 ;; `forward-sentence' and `backward-sentence' replacements
54 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
55 ;; respectively). Extra functions `python-nav-sentence-start' and
56 ;; `python-nav-sentence-end' are included to move to the beginning and
57 ;; to the end of a setence while taking care of multiline definitions.
59 ;; Shell interaction: is provided and allows you easily execute any
60 ;; block of code of your current buffer in an inferior Python process.
62 ;; Shell completion: hitting tab will try to complete the current
63 ;; word. Shell completion is implemented in a manner that if you
64 ;; change the `python-shell-interpreter' to any other (for example
65 ;; IPython) it should be easy to integrate another way to calculate
66 ;; completions. You just need to specify your custom
67 ;; `python-shell-completion-setup-code' and
68 ;; `python-shell-completion-string-code'.
70 ;; Here is a complete example of the settings you would use for
74 ;; python-shell-interpreter "ipython"
75 ;; python-shell-interpreter-args ""
76 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
77 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
78 ;; python-shell-completion-setup-code ""
79 ;; python-shell-completion-string-code
80 ;; "';'.join(__IP.complete('''%s'''))\n")
82 ;; Please note that the default completion system depends on the
83 ;; readline module, so if you are using some Operating System that
84 ;; bundles Python without it (like Windows) just install the
85 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
86 ;; you should be good to go.
88 ;; Shell virtualenv support: The shell also contains support for
89 ;; virtualenvs and other special environment modifications thanks to
90 ;; `python-shell-process-environment' and `python-shell-exec-path'.
91 ;; These two variables allows you to modify execution paths and
92 ;; environment variables to make easy for you to setup virtualenv rules
93 ;; or behavior modifications when running shells. Here is an example
94 ;; of how to make shell processes to be run using the /path/to/env/
97 ;; (setq python-shell-process-environment
99 ;; (format "PATH=%s" (mapconcat
102 ;; (cons (getenv "PATH")
103 ;; '("/path/to/env/bin/")))
105 ;; "VIRTUAL_ENV=/path/to/env/"))
106 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
108 ;; Since the above is cumbersome and can be programatically
109 ;; calculated, the variable `python-shell-virtualenv-path' is
110 ;; provided. When this variable is set with the path of the
111 ;; virtualenv to use, `process-environment' and `exec-path' get proper
112 ;; values in order to run shells inside the specified virtualenv. So
113 ;; the following will achieve the same as the previous example:
115 ;; (setq python-shell-virtualenv-path "/path/to/env/")
117 ;; Pdb tracking: when you execute a block of code that contains some
118 ;; call to pdb (or ipdb) it will prompt the block of code and will
119 ;; follow the execution of pdb marking the current line with an arrow.
121 ;; Symbol completion: you can complete the symbol at point. It uses
122 ;; the shell completion in background so you should run
123 ;; `python-shell-send-buffer' from time to time to get better results.
125 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
126 ;; def, for, if, try and while. These skeletons are integrated with
127 ;; dabbrev. If you have `dabbrev-mode' activated and
128 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
129 ;; the name of any of those defined and hit SPC, they will be
130 ;; automatically expanded.
132 ;; FFAP: You can find the filename for a given module when using ffap
133 ;; out of the box. This feature needs an inferior python shell
136 ;; Code check: Check the current file for errors with `python-check'
137 ;; using the program defined in `python-check-command'.
139 ;; Eldoc: returns documentation for object at point by using the
140 ;; inferior python subprocess to inspect its documentation. As you
141 ;; might guessed you should run `python-shell-send-buffer' from time
142 ;; to time to get better results too.
144 ;; imenu: This mode supports imenu. It builds a plain or tree menu
145 ;; depending on the value of `python-imenu-make-tree'. Also you can
146 ;; customize if menu items should include its type using
147 ;; `python-imenu-include-defun-type'.
149 ;; If you used python-mode.el you probably will miss auto-indentation
150 ;; when inserting newlines. To achieve the same behavior you have
153 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
155 ;; 2) Add the following hook in your .emacs:
157 ;; (add-hook 'python-mode-hook
159 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
161 ;; I'd recommend the first one since you'll get the same behavior for
162 ;; all modes out-of-the-box.
166 ;; Add this to your .emacs:
168 ;; (add-to-list 'load-path "/folder/containing/file")
175 (require 'ansi-color)
180 ;; Avoid compiler warnings
181 (defvar view-return-to-alist)
182 (defvar compilation-error-regexp-alist)
183 (defvar outline-heading-end-regexp))
185 (autoload 'comint-mode "comint")
188 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
190 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
193 "Python Language's flying circus support for Emacs."
196 :link '(emacs-commentary-link "python"))
201 (defvar python-mode-map
202 (let ((map (make-sparse-keymap)))
204 (substitute-key-definition 'backward-sentence
205 'python-nav-backward-sentence
207 (substitute-key-definition 'forward-sentence
208 'python-nav-forward-sentence
211 (define-key map "\177" 'python-indent-dedent-line-backspace)
212 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
213 (define-key map "\C-c<" 'python-indent-shift-left)
214 (define-key map "\C-c>" 'python-indent-shift-right)
215 (define-key map ":" 'python-indent-electric-colon)
217 (define-key map "\C-c\C-tc" 'python-skeleton-class)
218 (define-key map "\C-c\C-td" 'python-skeleton-def)
219 (define-key map "\C-c\C-tf" 'python-skeleton-for)
220 (define-key map "\C-c\C-ti" 'python-skeleton-if)
221 (define-key map "\C-c\C-tt" 'python-skeleton-try)
222 (define-key map "\C-c\C-tw" 'python-skeleton-while)
224 (define-key map "\C-c\C-s" 'python-shell-send-string)
225 (define-key map "\C-c\C-r" 'python-shell-send-region)
226 (define-key map "\C-\M-x" 'python-shell-send-defun)
227 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
228 (define-key map "\C-c\C-l" 'python-shell-send-file)
229 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
230 ;; Some util commands
231 (define-key map "\C-c\C-v" 'python-check)
232 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
234 (substitute-key-definition 'complete-symbol 'completion-at-point
236 (easy-menu-define python-menu map "Python Mode menu"
238 :help "Python-specific Features"
239 ["Shift region left" python-indent-shift-left :active mark-active
240 :help "Shift region left by a single indentation step"]
241 ["Shift region right" python-indent-shift-right :active mark-active
242 :help "Shift region right by a single indentation step"]
244 ["Mark def/class" mark-defun
245 :help "Mark outermost definition around point"]
247 ["Start of def/class" beginning-of-defun
248 :help "Go to start of outermost definition around point"]
249 ["End of def/class" end-of-defun
250 :help "Go to end of definition around point"]
254 ["Start interpreter" run-python
255 :help "Run inferior Python process in a separate buffer"]
256 ["Switch to shell" python-shell-switch-to-shell
257 :help "Switch to running inferior Python process"]
258 ["Eval string" python-shell-send-string
259 :help "Eval string in inferior Python session"]
260 ["Eval buffer" python-shell-send-buffer
261 :help "Eval buffer in inferior Python session"]
262 ["Eval region" python-shell-send-region
263 :help "Eval region in inferior Python session"]
264 ["Eval defun" python-shell-send-defun
265 :help "Eval defun in inferior Python session"]
266 ["Eval file" python-shell-send-file
267 :help "Eval file in inferior Python session"]
268 ["Debugger" pdb :help "Run pdb under GUD"]
270 ["Check file" python-check
271 :help "Check file for errors"]
272 ["Help on symbol" python-eldoc-at-point
273 :help "Get help on symbol at point"]
274 ["Complete symbol" completion-at-point
275 :help "Complete symbol before point"]))
277 "Keymap for `python-mode'.")
280 ;;; Python specialized rx
283 (defconst python-rx-constituents
285 `(block-start . ,(rx symbol-start
286 (or "def" "class" "if" "elif" "else" "try"
287 "except" "finally" "for" "while" "with")
289 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
291 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
292 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
293 `(open-paren . ,(rx (or "{" "[" "(")))
294 `(close-paren . ,(rx (or "}" "]" ")")))
295 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
296 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
297 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
298 "=" "%" "**" "//" "<<" ">>" "<=" "!="
299 "==" ">=" "is" "not")))
300 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
301 ">>=" "<<=" "&=" "^=" "|="))))
302 "Additional Python specific sexps for `python-rx'"))
304 (defmacro python-rx (&rest regexps)
305 "Python mode specialized rx macro which supports common python named REGEXPS."
306 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
307 (cond ((null regexps)
310 (rx-to-string `(and ,@regexps) t))
312 (rx-to-string (car regexps) t)))))
315 ;;; Font-lock and syntax
317 (defvar python-font-lock-keywords
320 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
321 "assert" "else" "if" "pass" "yield" "break" "except" "import"
322 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
323 "return" "def" "for" "lambda" "try" "self")
326 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
327 (1 font-lock-function-name-face))
329 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
330 (1 font-lock-type-face))
333 ;; copyright, license, credits, quit, exit are added by the
334 ;; site module and since they are not intended to be used in
335 ;; programs they are not added here either.
336 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
337 symbol-end) . font-lock-constant-face)
339 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
340 (0+ "." (1+ (or word ?_)))))
341 (1 font-lock-type-face))
342 ;; Builtin Exceptions
344 (or "ArithmeticError" "AssertionError" "AttributeError"
345 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
346 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
347 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
348 "ImportWarning" "IndentationError" "IndexError" "KeyError"
349 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
350 "NotImplementedError" "OSError" "OverflowError"
351 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
352 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
353 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
354 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
355 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
356 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
357 symbol-end) . font-lock-type-face)
360 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
361 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
362 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
363 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
364 "execfile" "file" "filter" "float" "format" "frozenset"
365 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
366 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
367 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
368 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
369 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
370 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
371 "unichr" "unicode" "vars" "xrange" "zip")
372 symbol-end) . font-lock-builtin-face)
374 ;; support for a = b = c = 5
376 (let ((re (python-rx (group (+ (any word ?. ?_)))
377 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
378 assignment-operator)))
379 (when (re-search-forward re limit t)
380 (while (and (python-info-ppss-context 'paren)
381 (re-search-forward re limit t)))
382 (if (and (not (python-info-ppss-context 'paren))
383 (not (equal (char-after (point-marker)) ?=)))
385 (set-match-data nil)))))
386 (1 font-lock-variable-name-face nil nil))
387 ;; support for a, b, c = (1, 2, 3)
389 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
390 (* ?, (* space) (+ (any word ?. ?_)) (* space))
391 ?, (* space) (+ (any word ?. ?_)) (* space)
392 assignment-operator)))
393 (when (and (re-search-forward re limit t)
394 (goto-char (nth 3 (match-data))))
395 (while (and (python-info-ppss-context 'paren)
396 (re-search-forward re limit t))
397 (goto-char (nth 3 (match-data))))
398 (if (not (python-info-ppss-context 'paren))
400 (set-match-data nil)))))
401 (1 font-lock-variable-name-face nil nil))))
403 (defconst python-font-lock-syntactic-keywords
404 ;; Make outer chars of matching triple-quote sequences into generic
405 ;; string delimiters. Fixme: Is there a better way?
406 ;; First avoid a sequence preceded by an odd number of backslashes.
407 `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
408 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
409 (3 (python-quote-syntax)))))
411 (defun python-quote-syntax ()
412 "Put `syntax-table' property correctly on triple quote.
413 Used for syntactic keywords. N is the match number (1, 2 or 3)."
414 ;; Given a triple quote, we have to check the context to know
415 ;; whether this is an opening or closing triple or whether it's
416 ;; quoted anyhow, and should be ignored. (For that we need to do
417 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
418 ;; to use it here despite initial worries.) We also have to sort
419 ;; out a possible prefix -- well, we don't _have_ to, but I think it
420 ;; should be treated as part of the string.
423 ;; ur"""ar""" x='"' # """
426 ;; x '"""' x """ \"""" x
428 (goto-char (match-beginning 0))
429 (let ((syntax (save-match-data (syntax-ppss))))
431 ((eq t (nth 3 syntax)) ; after unclosed fence
432 ;; Consider property for the last char if in a fenced string.
433 (goto-char (nth 8 syntax)) ; fence position
434 (skip-chars-forward "uUrR") ; skip any prefix
435 ;; Is it a matching sequence?
436 (if (eq (char-after) (char-after (match-beginning 2)))
437 (put-text-property (match-beginning 3) (match-end 3)
438 'syntax-table (string-to-syntax "|"))))
440 ;; Consider property for initial char, accounting for prefixes.
441 (put-text-property (match-beginning 1) (match-end 1)
442 'syntax-table (string-to-syntax "|")))
444 ;; Consider property for initial char, accounting for prefixes.
445 (put-text-property (match-beginning 2) (match-end 2)
446 'syntax-table (string-to-syntax "|"))))
449 (defvar python-mode-syntax-table
450 (let ((table (make-syntax-table)))
451 ;; Give punctuation syntax to ASCII that normally has symbol
452 ;; syntax or has word syntax and isn't a letter.
453 (let ((symbol (string-to-syntax "_"))
454 (sst (standard-syntax-table)))
457 (if (equal symbol (aref sst i))
458 (modify-syntax-entry i "." table)))))
459 (modify-syntax-entry ?$ "." table)
460 (modify-syntax-entry ?% "." table)
462 (modify-syntax-entry ?# "<" table)
463 (modify-syntax-entry ?\n ">" table)
464 (modify-syntax-entry ?' "\"" table)
465 (modify-syntax-entry ?` "$" table)
467 "Syntax table for Python files.")
469 (defvar python-dotty-syntax-table
470 (let ((table (make-syntax-table python-mode-syntax-table)))
471 (modify-syntax-entry ?. "w" table)
472 (modify-syntax-entry ?_ "w" table)
474 "Dotty syntax table for Python files.
475 It makes underscores and dots word constituent chars.")
480 (defcustom python-indent-offset 4
481 "Default indentation offset for Python."
486 (defcustom python-indent-guess-indent-offset t
487 "Non-nil tells Python mode to guess `python-indent-offset' value."
492 (defvar python-indent-current-level 0
493 "Current indentation level `python-indent-line-function' is using.")
495 (defvar python-indent-levels '(0)
496 "Levels of indentation available for `python-indent-line-function'.")
498 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
499 "List of words that should be dedented.
500 These make `python-indent-calculate-indentation' subtract the value of
501 `python-indent-offset'.")
503 (defun python-indent-guess-indent-offset ()
504 "Guess and set `python-indent-offset' for the current buffer."
508 (goto-char (point-min))
510 (while (and (not found-block)
512 (python-rx line-start block-start) nil t))
513 (when (and (not (python-info-ppss-context 'string))
514 (not (python-info-ppss-context 'comment))
516 (goto-char (line-end-position))
517 (forward-comment -9999)
518 (eq ?: (char-before))))
519 (setq found-block t)))
520 (if (not found-block)
521 (message "Can't guess python-indent-offset, using defaults: %s"
522 python-indent-offset)
524 (goto-char (line-end-position))
525 (python-info-continuation-line-p))
529 (forward-comment 9999)
530 (let ((indent-offset (current-indentation)))
531 (when (> indent-offset 0)
532 (setq python-indent-offset indent-offset))))))))
534 (defun python-indent-context ()
535 "Get information on indentation context.
536 Context information is returned with a cons with the form:
539 Where status can be any of the following symbols:
540 * inside-paren: If point in between (), {} or []
541 * inside-string: If point is inside a string
542 * after-backslash: Previous line ends in a backslash
543 * after-beginning-of-block: Point is after beginning of block
544 * after-line: Point is after normal line
545 * no-indent: Point is at beginning of buffer or other special case
546 START is the buffer position where the sexp starts."
549 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
553 ;; Beginning of buffer
555 (goto-char (line-beginning-position))
559 ((setq start (python-info-ppss-context 'paren ppss))
562 ((setq start (python-info-ppss-context 'string ppss))
565 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
566 (python-info-ppss-context 'comment ppss)))
567 (let ((line-beg-pos (line-beginning-position)))
568 (when (eq ?\\ (char-before (1- line-beg-pos)))
569 (- line-beg-pos 2)))))
571 ;; After beginning of block
572 ((setq start (save-excursion
573 (let ((block-regexp (python-rx block-start))
574 (block-start-line-end ":[[:space:]]*$"))
575 (back-to-indentation)
576 (forward-comment -9999)
577 (back-to-indentation)
578 (when (or (python-info-continuation-line-p)
579 (and (not (looking-at block-regexp))
583 (line-end-position) t))))
584 (while (and (forward-line -1)
585 (python-info-continuation-line-p)
587 (when (not (looking-at block-regexp))
589 (back-to-indentation)
590 (when (and (looking-at block-regexp)
591 (or (re-search-forward
593 (line-end-position) t)
594 (python-info-continuation-line-p)))
596 'after-beginning-of-block)
598 ((setq start (save-excursion
599 (back-to-indentation)
600 (forward-comment -9999)
601 (python-nav-sentence-start)
608 (defun python-indent-calculate-indentation ()
609 "Calculate correct indentation offset for the current line."
610 (let* ((indentation-context (python-indent-context))
611 (context-status (car indentation-context))
612 (context-start (cdr indentation-context)))
618 ('after-beginning-of-block
619 (goto-char context-start)
620 (+ (current-indentation) python-indent-offset))
624 (goto-char context-start)
625 (current-indentation))
627 (back-to-indentation)
628 (looking-at (regexp-opt python-indent-dedenters)))
632 (goto-char context-start)
633 (current-indentation))
635 (let* ((block-continuation
638 (python-info-block-continuation-line-p)))
639 (assignment-continuation
642 (python-info-assignment-continuation-line-p)))
645 (back-to-indentation)
646 (when (looking-at "\\.")
648 (goto-char (line-end-position))
649 (while (and (re-search-backward "\\." (line-beginning-position) t)
650 (or (python-info-ppss-context 'comment)
651 (python-info-ppss-context 'string)
652 (python-info-ppss-context 'paren))))
653 (if (and (looking-at "\\.")
654 (not (or (python-info-ppss-context 'comment)
655 (python-info-ppss-context 'string)
656 (python-info-ppss-context 'paren))))
658 (+ (current-indentation) python-indent-offset)))))
663 (goto-char block-continuation)
665 (python-rx block-start (* space))
666 (line-end-position) t)
668 (assignment-continuation
669 (goto-char assignment-continuation)
671 (python-rx simple-operator)
672 (line-end-position) t)
675 (python-rx (* space))
676 (line-end-position) t)
679 (goto-char context-start)
682 (back-to-indentation)
684 "\\(?:return\\|from\\|import\\)\s+")))
685 (current-indentation)
686 (+ (current-indentation)
688 (match-string-no-properties 0))))))))
692 (skip-syntax-forward "\s" (line-end-position))
693 (when (and (looking-at (regexp-opt '(")" "]" "}")))
694 (not (forward-char 1))
695 (not (python-info-ppss-context 'paren)))
696 (goto-char context-start)
697 (back-to-indentation)
701 (goto-char context-start)
705 (line-beginning-position)
707 (forward-comment 9999))
709 (+ (current-indentation) python-indent-offset)
710 (forward-comment 9999)
713 (back-to-indentation)
714 (looking-at (regexp-opt '(")" "]" "}"))))
718 (defun python-indent-calculate-levels ()
719 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
720 (let* ((indentation (python-indent-calculate-indentation))
721 (remainder (% indentation python-indent-offset))
722 (steps (/ (- indentation remainder) python-indent-offset)))
723 (setq python-indent-levels (list 0))
724 (dotimes (step steps)
725 (push (* python-indent-offset (1+ step)) python-indent-levels))
726 (when (not (eq 0 remainder))
727 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
728 (setq python-indent-levels (nreverse python-indent-levels))
729 (setq python-indent-current-level (1- (length python-indent-levels)))))
731 (defun python-indent-toggle-levels ()
732 "Toggle `python-indent-current-level' over `python-indent-levels'."
733 (setq python-indent-current-level (1- python-indent-current-level))
734 (when (< python-indent-current-level 0)
735 (setq python-indent-current-level (1- (length python-indent-levels)))))
737 (defun python-indent-line (&optional force-toggle)
738 "Internal implementation of `python-indent-line-function'.
739 Uses the offset calculated in
740 `python-indent-calculate-indentation' and available levels
741 indicated by the variable `python-indent-levels' to set the
744 When the variable `last-command' is equal to
745 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
746 levels indicated in the variable `python-indent-levels' by
747 setting the current level in the variable
748 `python-indent-current-level'.
750 When the variable `last-command' is not equal to
751 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
752 possible indentation levels and saves it in the variable
753 `python-indent-levels'. Afterwards it sets the variable
754 `python-indent-current-level' correctly so offset is equal
755 to (`nth' `python-indent-current-level' `python-indent-levels')"
756 (if (or (and (eq this-command 'indent-for-tab-command)
757 (eq last-command this-command))
759 (if (not (equal python-indent-levels '(0)))
760 (python-indent-toggle-levels)
761 (python-indent-calculate-levels))
762 (python-indent-calculate-levels))
764 (delete-horizontal-space)
765 (indent-to (nth python-indent-current-level python-indent-levels))
768 (let ((closing-block-point (python-info-closing-block)))
769 (when closing-block-point
770 (message "Closes %s" (buffer-substring
773 (goto-char closing-block-point)
774 (line-end-position))))))))
776 (defun python-indent-line-function ()
777 "`indent-line-function' for Python mode.
778 See `python-indent-line' for details."
779 (python-indent-line))
781 (defun python-indent-dedent-line ()
782 "De-indent current line."
784 (when (and (not (or (python-info-ppss-context 'string)
785 (python-info-ppss-context 'comment)))
786 (<= (point-marker) (save-excursion
787 (back-to-indentation)
789 (> (current-column) 0))
790 (python-indent-line t)
793 (defun python-indent-dedent-line-backspace (arg)
794 "De-indent current line.
795 Argument ARG is passed to `backward-delete-char-untabify' when
796 point is not in between the indentation."
798 (when (not (python-indent-dedent-line))
799 (backward-delete-char-untabify arg)))
800 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
802 (defun python-indent-region (start end)
803 "Indent a python region automagically.
805 Called from a program, START and END specify the region to indent."
806 (let ((deactivate-mark nil))
809 (setq end (point-marker))
811 (or (bolp) (forward-line 1))
812 (while (< (point) end)
813 (or (and (bolp) (eolp))
816 (back-to-indentation)
817 (setq word (current-word))
821 (delete-horizontal-space)
822 (indent-to (python-indent-calculate-indentation)))))
824 (move-marker end nil))))
826 (defun python-indent-shift-left (start end &optional count)
827 "Shift lines contained in region START END by COUNT columns to the left.
828 COUNT defaults to `python-indent-offset'. If region isn't
829 active, the current line is shifted. The shifted region includes
830 the lines in which START and END lie. An error is signaled if
831 any lines in the region are indented less than COUNT columns."
834 (list (region-beginning) (region-end) current-prefix-arg)
835 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
837 (setq count (prefix-numeric-value count))
838 (setq count python-indent-offset))
840 (let ((deactivate-mark nil))
843 (while (< (point) end)
844 (if (and (< (current-indentation) count)
845 (not (looking-at "[ \t]*$")))
846 (error "Can't shift all lines enough"))
848 (indent-rigidly start end (- count))))))
850 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
852 (defun python-indent-shift-right (start end &optional count)
853 "Shift lines contained in region START END by COUNT columns to the left.
854 COUNT defaults to `python-indent-offset'. If region isn't
855 active, the current line is shifted. The shifted region includes
856 the lines in which START and END lie."
859 (list (region-beginning) (region-end) current-prefix-arg)
860 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
861 (let ((deactivate-mark nil))
863 (setq count (prefix-numeric-value count))
864 (setq count python-indent-offset))
865 (indent-rigidly start end count)))
867 (defun python-indent-electric-colon (arg)
868 "Insert a colon and maybe de-indent the current line.
869 With numeric ARG, just insert that many colons. With
870 \\[universal-argument], just insert a single colon."
872 (self-insert-command (if (not (integerp arg)) 1 arg))
875 (not (equal ?: (char-after (- (point-marker) 2))))
876 (not (or (python-info-ppss-context 'string)
877 (python-info-ppss-context 'comment))))
878 (let ((indentation (current-indentation))
879 (calculated-indentation (python-indent-calculate-indentation)))
880 (when (> indentation calculated-indentation)
882 (indent-line-to calculated-indentation)
883 (when (not (python-info-closing-block))
884 (indent-line-to indentation)))))))
885 (put 'python-indent-electric-colon 'delete-selection t)
890 (defvar python-nav-beginning-of-defun-regexp
891 (python-rx line-start (* space) defun (+ space) (group symbol-name))
892 "Regular expresion matching beginning of class or function.
893 The name of the defun should be grouped so it can be retrieved
894 via `match-string'.")
896 (defun python-nav-beginning-of-defun (&optional nodecorators)
897 "Move point to `beginning-of-defun'.
898 When NODECORATORS is non-nil decorators are not included. This
899 is the main part of`python-beginning-of-defun-function'
900 implementation. Return non-nil if point is moved to the
901 `beginning-of-defun'."
902 (let ((indent-pos (save-excursion
903 (back-to-indentation)
908 (when (not nodecorators)
909 (when (save-excursion
911 (looking-at (python-rx decorator)))
912 (while (and (not (bobp))
914 (looking-at (python-rx decorator))))
915 (when (not (bobp)) (forward-line 1)))))))
916 (if (and (> (point) indent-pos)
918 (goto-char (line-beginning-position))
919 (looking-at python-nav-beginning-of-defun-regexp)))
921 (goto-char (line-beginning-position))
922 (funcall include-decorators)
924 (goto-char (line-beginning-position))
925 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
927 (goto-char (or (python-info-ppss-context 'string) (point)))
928 (funcall include-decorators))
931 (defun python-beginning-of-defun-function (&optional arg nodecorators)
932 "Move point to the beginning of def or class.
933 With positive ARG move that number of functions forward. With
934 negative do the same but backwards. When NODECORATORS is non-nil
935 decorators are not included. Return non-nil if point is moved to the
936 `beginning-of-defun'."
937 (when (or (null arg) (= arg 0)) (setq arg 1))
939 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
941 (dotimes (i (- arg) found)
942 (python-end-of-defun-function)
943 (forward-comment 9999)
944 (goto-char (line-end-position))
947 (python-nav-beginning-of-defun nodecorators)))))))
949 (defun python-end-of-defun-function ()
950 "Move point to the end of def or class.
951 Returns nil if point is not in a def or class."
953 (let ((beg-defun-indent)
954 (decorator-regexp "[[:space:]]*@"))
955 (when (looking-at decorator-regexp)
956 (while (and (not (eobp))
958 (looking-at decorator-regexp))))
959 (when (not (looking-at python-nav-beginning-of-defun-regexp))
960 (python-beginning-of-defun-function))
961 (setq beg-defun-indent (current-indentation))
963 (while (and (forward-line 1)
965 (or (not (current-word))
966 (> (current-indentation) beg-defun-indent))))
967 (forward-comment 9999)
968 (goto-char (line-beginning-position))))
970 (defun python-nav-sentence-start ()
971 "Move to start of current sentence."
973 (while (and (not (back-to-indentation))
978 (python-info-line-ends-backslash-p))
979 (python-info-ppss-context 'string)
980 (python-info-ppss-context 'paren))
981 (forward-line -1)))))
983 (defun python-nav-sentence-end ()
984 "Move to end of current sentence."
986 (while (and (goto-char (line-end-position))
989 (python-info-line-ends-backslash-p)
990 (python-info-ppss-context 'string)
991 (python-info-ppss-context 'paren))
994 (defun python-nav-backward-sentence (&optional arg)
995 "Move backward to start of sentence. With ARG, do it arg times.
996 See `python-nav-forward-sentence' for more information."
998 (or arg (setq arg 1))
999 (python-nav-forward-sentence (- arg)))
1001 (defun python-nav-forward-sentence (&optional arg)
1002 "Move forward to next end of sentence. With ARG, repeat.
1003 With negative argument, move backward repeatedly to start of sentence."
1005 (or arg (setq arg 1))
1007 (forward-comment 9999)
1008 (python-nav-sentence-end)
1010 (setq arg (1- arg)))
1012 (python-nav-sentence-end)
1013 (forward-comment -9999)
1014 (python-nav-sentence-start)
1016 (setq arg (1+ arg))))
1019 ;;; Shell integration
1021 (defcustom python-shell-buffer-name "Python"
1022 "Default buffer name for Python interpreter."
1027 (defcustom python-shell-interpreter "python"
1028 "Default Python interpreter for shell."
1033 (defcustom python-shell-internal-buffer-name "Python Internal"
1034 "Default buffer name for the Internal Python interpreter."
1039 (defcustom python-shell-interpreter-args "-i"
1040 "Default arguments for the Python interpreter."
1045 (defcustom python-shell-prompt-regexp ">>> "
1046 "Regular Expression matching top\-level input prompt of python shell.
1047 It should not contain a caret (^) at the beginning."
1052 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1053 "Regular Expression matching block input prompt of python shell.
1054 It should not contain a caret (^) at the beginning."
1059 (defcustom python-shell-prompt-output-regexp ""
1060 "Regular Expression matching output prompt of python shell.
1061 It should not contain a caret (^) at the beginning."
1066 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1067 "Regular Expression matching pdb input prompt of python shell.
1068 It should not contain a caret (^) at the beginning."
1073 (defcustom python-shell-send-setup-max-wait 5
1074 "Seconds to wait for process output before code setup.
1075 If output is received before the especified time then control is
1076 returned in that moment and not after waiting."
1081 (defcustom python-shell-process-environment nil
1082 "List of environment variables for Python shell.
1083 This variable follows the same rules as `process-environment'
1084 since it merges with it before the process creation routines are
1085 called. When this variable is nil, the Python shell is run with
1086 the default `process-environment'."
1087 :type '(repeat string)
1091 (defcustom python-shell-exec-path nil
1092 "List of path to search for binaries.
1093 This variable follows the same rules as `exec-path' since it
1094 merges with it before the process creation routines are called.
1095 When this variable is nil, the Python shell is run with the
1096 default `exec-path'."
1097 :type '(repeat string)
1101 (defcustom python-shell-virtualenv-path nil
1102 "Path to virtualenv root.
1103 This variable, when set to a string, makes the values stored in
1104 `python-shell-process-environment' and `python-shell-exec-path'
1105 to be modified properly so shells are started with the specified
1111 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1112 python-ffap-setup-code
1113 python-eldoc-setup-code)
1114 "List of code run by `python-shell-send-setup-codes'.
1115 Each variable can contain either a simple string with the code to
1116 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1117 is a string with the code to execute and DESCRIPTION is the
1119 :type '(repeat symbol)
1123 (defcustom python-shell-compilation-regexp-alist
1124 `((,(rx line-start (1+ (any " \t")) "File \""
1125 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1126 "\", line " (group (1+ digit)))
1128 (,(rx " in file " (group (1+ not-newline)) " on line "
1131 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1132 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1134 "`compilation-error-regexp-alist' for inferior Python."
1135 :type '(alist string)
1138 (defun python-shell-get-process-name (dedicated)
1139 "Calculate the appropiate process name for inferior Python process.
1140 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1141 returns a string with the form
1142 `python-shell-buffer-name'[variable `buffer-file-name'] else
1143 returns the value of `python-shell-buffer-name'. After
1144 calculating the process name adds the buffer name for the process
1145 in the `same-window-buffer-names' list."
1149 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1150 (format "%s" python-shell-buffer-name))))
1151 (add-to-list 'same-window-buffer-names (purecopy
1152 (format "*%s*" process-name)))
1155 (defun python-shell-internal-get-process-name ()
1156 "Calculate the appropiate process name for Internal Python process.
1157 The name is calculated from `python-shell-global-buffer-name' and
1158 a hash of all relevant global shell settings in order to ensure
1159 uniqueness for different types of configurations."
1161 python-shell-internal-buffer-name
1164 (python-shell-parse-command)
1165 (mapconcat #'symbol-value python-shell-setup-codes "")
1166 (mapconcat #'indentity python-shell-process-environment "")
1167 (or python-shell-virtualenv-path "")
1168 (mapconcat #'indentity python-shell-exec-path "")))))
1170 (defun python-shell-parse-command ()
1171 "Calculate the string used to execute the inferior Python process."
1172 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1174 (defun python-shell-calculate-process-environment ()
1175 "Calculate process environment given `python-shell-virtualenv-path'."
1176 (let ((env (python-util-merge 'list python-shell-process-environment
1177 process-environment 'string=))
1178 (virtualenv (if python-shell-virtualenv-path
1179 (directory-file-name python-shell-virtualenv-path)
1181 (if (not virtualenv)
1183 (dolist (envvar env)
1184 (let* ((split (split-string envvar "=" t))
1185 (name (nth 0 split))
1186 (value (nth 1 split)))
1187 (when (not (string= name "PYTHONHOME"))
1188 (when (string= name "PATH")
1189 (setq value (format "%s/bin:%s" virtualenv value)))
1190 (setq env (cons (format "%s=%s" name value) env)))))
1191 (cons (format "VIRTUAL_ENV=%s" virtualenv) env))))
1193 (defun python-shell-calculate-exec-path ()
1194 "Calculate exec path given `python-shell-virtualenv-path'."
1195 (let ((path (python-util-merge 'list python-shell-exec-path
1196 exec-path 'string=)))
1197 (if (not python-shell-virtualenv-path)
1199 (cons (format "%s/bin"
1200 (directory-file-name python-shell-virtualenv-path))
1203 (defun python-comint-output-filter-function (output)
1204 "Hook run after content is put into comint buffer.
1205 OUTPUT is a string with the contents of the buffer."
1206 (ansi-color-filter-apply output))
1208 (defvar inferior-python-mode-current-file nil
1209 "Current file from which a region was sent.")
1210 (make-variable-buffer-local 'inferior-python-mode-current-file)
1212 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1213 "Major mode for Python inferior process.
1214 Runs a Python interpreter as a subprocess of Emacs, with Python
1215 I/O through an Emacs buffer. Variables
1216 `python-shell-interpreter' and `python-shell-interpreter-args'
1217 controls which Python interpreter is run. Variables
1218 `python-shell-prompt-regexp',
1219 `python-shell-prompt-output-regexp',
1220 `python-shell-prompt-block-regexp',
1221 `python-shell-completion-setup-code',
1222 `python-shell-completion-string-code', `python-eldoc-setup-code',
1223 `python-eldoc-string-code', `python-ffap-setup-code' and
1224 `python-ffap-string-code' can customize this mode for different
1225 Python interpreters.
1227 You can also add additional setup code to be run at
1228 initialization of the interpreter via `python-shell-setup-codes'
1231 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1232 (set-syntax-table python-mode-syntax-table)
1233 (setq mode-line-process '(":%s"))
1234 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1235 python-shell-prompt-regexp
1236 python-shell-prompt-block-regexp
1237 python-shell-prompt-pdb-regexp))
1238 (make-local-variable 'comint-output-filter-functions)
1239 (add-hook 'comint-output-filter-functions
1240 'python-comint-output-filter-function)
1241 (add-hook 'comint-output-filter-functions
1242 'python-pdbtrack-comint-output-filter-function)
1243 (set (make-local-variable 'compilation-error-regexp-alist)
1244 python-shell-compilation-regexp-alist)
1245 (define-key inferior-python-mode-map [remap complete-symbol]
1246 'completion-at-point)
1247 (add-hook 'completion-at-point-functions
1248 'python-shell-completion-complete-at-point nil 'local)
1249 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1250 'python-shell-completion-complete-at-point)
1251 (define-key inferior-python-mode-map (kbd "<tab>")
1252 'python-shell-completion-complete-or-indent)
1253 (compilation-shell-minor-mode 1))
1255 (defun python-shell-make-comint (cmd proc-name &optional pop)
1256 "Create a python shell comint buffer.
1257 CMD is the python command to be executed and PROC-NAME is the
1258 process name the comint buffer will get. After the comint buffer
1259 is created the `inferior-python-mode' is activated. If POP is
1260 non-nil the buffer is shown."
1262 (let* ((proc-buffer-name (format "*%s*" proc-name))
1263 (process-environment (python-shell-calculate-process-environment))
1264 (exec-path (python-shell-calculate-exec-path)))
1265 (when (not (comint-check-proc proc-buffer-name))
1266 (let* ((cmdlist (split-string-and-unquote cmd))
1267 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1269 (python-shell-interpreter-1 python-shell-interpreter)
1270 (python-shell-interpreter-args-1 python-shell-interpreter-args)
1271 (python-shell-prompt-regexp-1 python-shell-prompt-regexp)
1272 (python-shell-prompt-output-regexp-1
1273 python-shell-prompt-output-regexp)
1274 (python-shell-prompt-block-regexp-1
1275 python-shell-prompt-block-regexp)
1276 (python-shell-completion-setup-code-1
1277 python-shell-completion-setup-code)
1278 (python-shell-completion-string-code-1
1279 python-shell-completion-string-code)
1280 (python-eldoc-setup-code-1 python-eldoc-setup-code)
1281 (python-eldoc-string-code-1 python-eldoc-string-code)
1282 (python-ffap-setup-code-1 python-ffap-setup-code)
1283 (python-ffap-string-code-1 python-ffap-string-code)
1284 (python-shell-setup-codes-1 python-shell-setup-codes))
1285 (with-current-buffer buffer
1286 (inferior-python-mode)
1287 (set (make-local-variable 'python-shell-interpreter)
1288 python-shell-interpreter-1)
1289 (set (make-local-variable 'python-shell-interpreter-args)
1290 python-shell-interpreter-args-1)
1291 (set (make-local-variable 'python-shell-prompt-regexp)
1292 python-shell-prompt-regexp-1)
1293 (set (make-local-variable 'python-shell-prompt-output-regexp)
1294 python-shell-prompt-output-regexp-1)
1295 (set (make-local-variable 'python-shell-prompt-block-regexp)
1296 python-shell-prompt-block-regexp-1)
1297 (set (make-local-variable 'python-shell-completion-setup-code)
1298 python-shell-completion-setup-code-1)
1299 (set (make-local-variable 'python-shell-completion-string-code)
1300 python-shell-completion-string-code-1)
1301 (set (make-local-variable 'python-eldoc-setup-code)
1302 python-eldoc-setup-code-1)
1303 (set (make-local-variable 'python-eldoc-string-code)
1304 python-eldoc-string-code-1)
1305 (set (make-local-variable 'python-ffap-setup-code)
1306 python-ffap-setup-code-1)
1307 (set (make-local-variable 'python-ffap-string-code)
1308 python-ffap-string-code-1)
1309 (set (make-local-variable 'python-shell-setup-codes)
1310 python-shell-setup-codes-1))))
1312 (pop-to-buffer proc-buffer-name)))))
1314 (defun run-python (dedicated cmd)
1315 "Run an inferior Python process.
1316 Input and output via buffer named after
1317 `python-shell-buffer-name'. If there is a process already
1318 running in that buffer, just switch to it.
1319 With argument, allows you to define DEDICATED, so a dedicated
1320 process for the current buffer is open, and define CMD so you can
1321 edit the command used to call the interpreter (default is value
1322 of `python-shell-interpreter' and arguments defined in
1323 `python-shell-interpreter-args'). Runs the hook
1324 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1326 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1328 (if current-prefix-arg
1330 (y-or-n-p "Make dedicated process? ")
1331 (read-string "Run Python: " (python-shell-parse-command)))
1332 (list nil (python-shell-parse-command))))
1333 (python-shell-make-comint cmd (python-shell-get-process-name dedicated) t)
1336 (defun run-python-internal ()
1337 "Run an inferior Internal Python process.
1338 Input and output via buffer named after
1339 `python-shell-internal-buffer-name' and what
1340 `python-shell-internal-get-process-name' returns. This new kind
1341 of shell is intended to be used for generic communication related
1342 to defined configurations. The main difference with global or
1343 dedicated shells is that these ones are attached to a
1344 configuration, not a buffer. This means that can be used for
1345 example to retrieve the sys.path and other stuff, without messing
1346 with user shells. Runs the hook
1347 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1348 run). \(Type \\[describe-mode] in the process buffer for a list
1351 (python-shell-make-comint
1352 (python-shell-parse-command)
1353 (python-shell-internal-get-process-name)))
1355 (defun python-shell-get-process ()
1356 "Get inferior Python process for current buffer and return it."
1357 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1358 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1359 (global-proc-name (python-shell-get-process-name nil))
1360 (global-proc-buffer-name (format "*%s*" global-proc-name))
1361 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1362 (global-running (comint-check-proc global-proc-buffer-name)))
1363 ;; Always prefer dedicated
1364 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1365 (and global-running global-proc-buffer-name)))))
1367 (defun python-shell-get-or-create-process ()
1368 "Get or create an inferior Python process for current buffer and return it."
1369 (let* ((old-buffer (current-buffer))
1370 (dedicated-proc-name (python-shell-get-process-name t))
1371 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1372 (global-proc-name (python-shell-get-process-name nil))
1373 (global-proc-buffer-name (format "*%s*" global-proc-name))
1374 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1375 (global-running (comint-check-proc global-proc-buffer-name))
1376 (current-prefix-arg 4))
1377 (when (and (not dedicated-running) (not global-running))
1378 (if (call-interactively 'run-python)
1379 (setq dedicated-running t)
1380 (setq global-running t)))
1381 ;; Always prefer dedicated
1382 (switch-to-buffer old-buffer)
1383 (get-buffer-process (if dedicated-running
1384 dedicated-proc-buffer-name
1385 global-proc-buffer-name))))
1387 (defun python-shell-internal-get-or-create-process ()
1388 "Get or create an inferior Internal Python process."
1389 (let* ((proc-name (python-shell-internal-get-process-name))
1390 (proc-buffer-name (format "*%s*" proc-name)))
1391 (run-python-internal)
1392 (get-buffer-process proc-buffer-name)))
1394 (defun python-shell-send-string (string &optional process msg)
1395 "Send STRING to inferior Python PROCESS.
1396 When MSG is non-nil messages the first line of STRING."
1397 (interactive "sPython command: ")
1398 (let ((process (or process (python-shell-get-or-create-process)))
1399 (lines (split-string string "\n" t)))
1401 (message (format "Sent: %s..." (nth 0 lines))))
1402 (if (> (length lines) 1)
1403 (let* ((temp-file-name (make-temp-file "py"))
1404 (file-name (or (buffer-file-name) temp-file-name)))
1405 (with-temp-file temp-file-name
1407 (delete-trailing-whitespace))
1408 (python-shell-send-file file-name process temp-file-name))
1409 (comint-send-string process string)
1410 (when (or (not (string-match "\n$" string))
1411 (string-match "\n[ \t].*\n?$" string))
1412 (comint-send-string process "\n")))))
1414 (defun python-shell-send-string-no-output (string &optional process msg)
1415 "Send STRING to PROCESS and inhibit output.
1416 When MSG is non-nil messages the first line of STRING. Return
1418 (let* ((output-buffer)
1419 (process (or process (python-shell-get-or-create-process)))
1420 (comint-preoutput-filter-functions
1421 (append comint-preoutput-filter-functions
1422 '(ansi-color-filter-apply
1424 (setq output-buffer (concat output-buffer string))
1426 (python-shell-send-string string process msg)
1427 (accept-process-output process)
1428 ;; Cleanup output prompt regexp
1429 (when (and (not (string= "" output-buffer))
1430 (> (length python-shell-prompt-output-regexp) 0))
1433 (insert output-buffer)
1434 (goto-char (point-min))
1435 (forward-comment 9999)
1436 (buffer-substring-no-properties
1438 (and (looking-at python-shell-prompt-output-regexp)
1440 python-shell-prompt-output-regexp nil t 1))
1444 (lambda (string) string)
1445 (butlast (split-string output-buffer "\n")) "\n")))
1447 (defun python-shell-internal-send-string (string)
1448 "Send STRING to the Internal Python interpreter.
1449 Returns the output. See `python-shell-send-string-no-output'."
1450 (python-shell-send-string-no-output
1451 ;; Makes this function compatible with the old
1452 ;; python-send-receive. (At least for CEDET).
1453 (replace-regexp-in-string "_emacs_out +" "" string)
1454 (python-shell-internal-get-or-create-process) nil))
1456 (define-obsolete-function-alias
1457 'python-send-receive 'python-shell-internal-send-string "23.3"
1458 "Send STRING to inferior Python (if any) and return result.
1459 The result is what follows `_emacs_out' in the output.
1460 This is a no-op if `python-check-comint-prompt' returns nil.")
1462 (defun python-shell-send-region (start end)
1463 "Send the region delimited by START and END to inferior Python process."
1465 (let ((deactivate-mark nil))
1466 (python-shell-send-string (buffer-substring start end) nil t)))
1468 (defun python-shell-send-buffer ()
1469 "Send the entire buffer to inferior Python process."
1473 (python-shell-send-region (point-min) (point-max))))
1475 (defun python-shell-send-defun (arg)
1476 "Send the current defun to inferior Python process.
1477 When argument ARG is non-nil sends the innermost defun."
1480 (python-shell-send-region
1482 (or (python-beginning-of-defun-function)
1483 (progn (beginning-of-line) (point-marker))))
1485 (or (python-end-of-defun-function)
1486 (progn (end-of-line) (point-marker)))))))
1488 (defun python-shell-send-file (file-name &optional process temp-file-name)
1489 "Send FILE-NAME to inferior Python PROCESS.
1490 If TEMP-FILE-NAME is passed then that file is used for processing
1491 instead, while internally the shell will continue to use
1493 (interactive "fFile to send: ")
1494 (let* ((process (or process (python-shell-get-or-create-process)))
1495 (temp-file-name (when temp-file-name
1496 (expand-file-name temp-file-name)))
1497 (file-name (or (expand-file-name file-name) temp-file-name)))
1498 (when (not file-name)
1499 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1500 (with-current-buffer (process-buffer process)
1501 (setq inferior-python-mode-current-file
1502 (convert-standard-filename file-name)))
1503 (python-shell-send-string
1505 (concat "__pyfile = open('''%s''');"
1506 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1508 (or temp-file-name file-name) file-name)
1511 (defun python-shell-switch-to-shell ()
1512 "Switch to inferior Python process buffer."
1514 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1516 (defun python-shell-send-setup-code ()
1517 "Send all setup code for shell.
1518 This function takes the list of setup code to send from the
1519 `python-shell-setup-codes' list."
1520 (let ((msg "Sent %s")
1521 (process (get-buffer-process (current-buffer))))
1522 (accept-process-output process python-shell-send-setup-max-wait)
1523 (dolist (code python-shell-setup-codes)
1526 (setq msg (cdr code)))
1527 (message (format msg code))
1528 (python-shell-send-string-no-output
1529 (symbol-value code) process)))))
1531 (add-hook 'inferior-python-mode-hook
1532 #'python-shell-send-setup-code)
1535 ;;; Shell completion
1537 (defcustom python-shell-completion-setup-code
1541 def __COMPLETER_all_completions(text): []
1544 readline.set_completer(rlcompleter.Completer().complete)
1545 def __COMPLETER_all_completions(text):
1551 res = readline.get_completer()(text, i)
1554 completions.append(res)
1558 "Code used to setup completion in inferior Python processes."
1563 (defcustom python-shell-completion-string-code
1564 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1565 "Python code used to get a string of completions separated by semicolons."
1570 (defun python-shell-completion--get-completions (input process)
1571 "Retrieve available completions for INPUT using PROCESS."
1572 (with-current-buffer (process-buffer process)
1573 (let ((completions (python-shell-send-string-no-output
1574 (format python-shell-completion-string-code input)
1576 (when (> (length completions) 2)
1577 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1579 (defun python-shell-completion--get-completion (input completions)
1580 "Get completion for INPUT using COMPLETIONS."
1581 (let ((completion (when completions
1582 (try-completion input completions))))
1583 (cond ((eq completion t)
1586 (message "Can't find completion for \"%s\"" input)
1589 ((not (string= input completion))
1592 (message "Making completion list...")
1593 (with-output-to-temp-buffer "*Python Completions*"
1594 (display-completion-list
1595 (all-completions input completions)))
1598 (defun python-shell-completion-complete-at-point ()
1599 "Perform completion at point in inferior Python process."
1601 (with-syntax-table python-dotty-syntax-table
1602 (when (and comint-last-prompt-overlay
1603 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1604 (let* ((process (get-buffer-process (current-buffer)))
1605 (input (substring-no-properties
1606 (or (comint-word (current-word)) "") nil nil)))
1607 (delete-char (- (length input)))
1609 (python-shell-completion--get-completion
1610 input (python-shell-completion--get-completions input process)))))))
1612 (defun python-shell-completion-complete-or-indent ()
1613 "Complete or indent depending on the context.
1614 If content before pointer is all whitespace indent. If not try
1617 (if (string-match "^[[:space:]]*$"
1618 (buffer-substring (comint-line-beginning-position)
1620 (indent-for-tab-command)
1621 (comint-dynamic-complete)))
1624 ;;; PDB Track integration
1626 (defcustom python-pdbtrack-stacktrace-info-regexp
1627 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1628 "Regular Expression matching stacktrace information.
1629 Used to extract the current line and module being inspected. The
1630 regexp should not start with a caret (^) and can contain a string
1631 placeholder (\%s) which is replaced with the filename beign
1632 inspected (so other files in the debugging process are not
1638 (defvar python-pdbtrack-tracking-buffers '()
1639 "Alist containing elements of form (#<buffer> . #<buffer>).
1640 The car of each element of the alist is the tracking buffer and
1641 the cdr is the tracked buffer.")
1643 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1644 "Get/Add a tracked buffer for the current buffer.
1645 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1646 Returns a cons with the form:
1647 * (#<tracking buffer> . #< tracked buffer>)."
1649 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1650 (let* ((file (with-current-buffer (current-buffer)
1651 inferior-python-mode-current-file))
1653 `(,(current-buffer) .
1654 ,(or (get-file-buffer file)
1655 (find-file-noselect file)))))
1656 (set-buffer (cdr tracking-buffers))
1658 (set-buffer (car tracking-buffers))
1659 (setq python-pdbtrack-tracking-buffers
1660 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1663 (defun python-pdbtrack-comint-output-filter-function (output)
1664 "Move overlay arrow to current pdb line in tracked buffer.
1665 Argument OUTPUT is a string with the output from the comint process."
1666 (when (not (string= output ""))
1667 (let ((full-output (ansi-color-filter-apply
1668 (buffer-substring comint-last-input-end
1670 (if (string-match python-shell-prompt-pdb-regexp full-output)
1671 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1675 (format python-pdbtrack-stacktrace-info-regexp
1677 inferior-python-mode-current-file))
1679 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1680 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1681 (tracked-buffer-line-pos))
1683 (with-current-buffer (cdr tracking-buffers)
1684 (set (make-local-variable 'overlay-arrow-string) "=>")
1685 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1686 (setq tracked-buffer-line-pos (progn
1687 (goto-char (point-min))
1688 (forward-line (1- line-num))
1690 (when tracked-buffer-window
1691 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1692 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1693 (pop-to-buffer (cdr tracking-buffers))
1694 (switch-to-buffer-other-window (car tracking-buffers)))
1695 (let ((tracking-buffers (assq (current-buffer)
1696 python-pdbtrack-tracking-buffers)))
1697 (when tracking-buffers
1698 (if inferior-python-mode-current-file
1699 (with-current-buffer (cdr tracking-buffers)
1700 (set-marker overlay-arrow-position nil))
1701 (kill-buffer (cdr tracking-buffers)))
1702 (setq python-pdbtrack-tracking-buffers
1703 (assq-delete-all (current-buffer)
1704 python-pdbtrack-tracking-buffers)))))))
1708 ;;; Symbol completion
1710 (defun python-completion-complete-at-point ()
1711 "Complete current symbol at point.
1712 For this to work the best as possible you should call
1713 `python-shell-send-buffer' from time to time so context in
1714 inferior python process is updated properly."
1716 (let ((process (python-shell-get-process)))
1718 (error "Completion needs an inferior Python process running")
1719 (with-syntax-table python-dotty-syntax-table
1720 (let* ((input (substring-no-properties
1721 (or (comint-word (current-word)) "") nil nil))
1722 (completions (python-shell-completion--get-completions
1724 (delete-char (- (length input)))
1726 (python-shell-completion--get-completion
1727 input completions)))))))
1729 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1734 (defcustom python-fill-comment-function 'python-fill-comment
1735 "Function to fill comments.
1736 This is the function used by `python-fill-paragraph-function' to
1742 (defcustom python-fill-string-function 'python-fill-string
1743 "Function to fill strings.
1744 This is the function used by `python-fill-paragraph-function' to
1750 (defcustom python-fill-decorator-function 'python-fill-decorator
1751 "Function to fill decorators.
1752 This is the function used by `python-fill-paragraph-function' to
1758 (defcustom python-fill-paren-function 'python-fill-paren
1759 "Function to fill parens.
1760 This is the function used by `python-fill-paragraph-function' to
1766 (defun python-fill-paragraph-function (&optional justify)
1767 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1768 If any of the current line is in or at the end of a multi-line string,
1769 fill the string or the paragraph of it that point is in, preserving
1770 the string's indentation.
1771 Optional argument JUSTIFY defines if the paragraph should be justified."
1774 (back-to-indentation)
1777 ((funcall python-fill-comment-function justify))
1778 ;; Strings/Docstrings
1779 ((save-excursion (skip-chars-forward "\"'uUrR")
1780 (python-info-ppss-context 'string))
1781 (funcall python-fill-string-function justify))
1783 ((equal (char-after (save-excursion
1784 (back-to-indentation)
1785 (point-marker))) ?@)
1786 (funcall python-fill-decorator-function justify))
1788 ((or (python-info-ppss-context 'paren)
1789 (looking-at (python-rx open-paren))
1791 (skip-syntax-forward "^(" (line-end-position))
1792 (looking-at (python-rx open-paren))))
1793 (funcall python-fill-paren-function justify))
1796 (defun python-fill-comment (&optional justify)
1797 "Comment fill function for `python-fill-paragraph-function'.
1798 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1799 (fill-comment-paragraph justify))
1801 (defun python-fill-string (&optional justify)
1802 "String fill function for `python-fill-paragraph-function'.
1803 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1804 (let ((marker (point-marker))
1805 (string-start-marker
1807 (skip-chars-forward "\"'uUrR")
1808 (goto-char (python-info-ppss-context 'string))
1809 (skip-chars-forward "\"'uUrR")
1811 (reg-start (line-beginning-position))
1814 (while (python-info-ppss-context 'string)
1815 (goto-char (1+ (point-marker))))
1816 (skip-chars-backward "\"'")
1818 (reg-end (line-end-position))
1819 (fill-paragraph-function))
1821 (narrow-to-region reg-start reg-end)
1823 (goto-char string-start-marker)
1824 (delete-region (point-marker) (progn
1825 (skip-syntax-forward "> ")
1827 (goto-char string-end-marker)
1828 (delete-region (point-marker) (progn
1829 (skip-syntax-backward "> ")
1833 (fill-paragraph justify))
1834 ;; If there is a newline in the docstring lets put triple
1835 ;; quote in it's own line to follow pep 8
1836 (when (save-excursion
1837 (re-search-backward "\n" string-start-marker t))
1839 (newline-and-indent))
1840 (fill-paragraph justify)))) t)
1842 (defun python-fill-decorator (&optional justify)
1843 "Decorator fill function for `python-fill-paragraph-function'.
1844 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1847 (defun python-fill-paren (&optional justify)
1848 "Paren fill function for `python-fill-paragraph-function'.
1849 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1851 (narrow-to-region (progn
1852 (while (python-info-ppss-context 'paren)
1853 (goto-char (1- (point-marker))))
1855 (line-beginning-position))
1857 (when (not (python-info-ppss-context 'paren))
1859 (when (not (python-info-ppss-context 'paren))
1860 (skip-syntax-backward "^)")))
1861 (while (python-info-ppss-context 'paren)
1862 (goto-char (1+ (point-marker))))
1864 (let ((paragraph-start "\f\\|[ \t]*$")
1865 (paragraph-separate ",")
1866 (fill-paragraph-function))
1867 (goto-char (point-min))
1868 (fill-paragraph justify))
1871 (python-indent-line)
1872 (goto-char (line-end-position)))) t)
1877 (defcustom python-skeleton-autoinsert nil
1878 "Non-nil means template skeletons will be automagically inserted.
1879 This happens when pressing \"if<SPACE>\", for example, to prompt for
1885 (defvar python-skeleton-available '()
1886 "Internal list of available skeletons.")
1888 (define-abbrev-table 'python-mode-abbrev-table ()
1889 "Abbrev table for Python mode."
1891 ;; Allow / inside abbrevs.
1892 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1893 ;; Only expand in code.
1894 :enable-function (lambda ()
1896 (not (or (python-info-ppss-context 'string)
1897 (python-info-ppss-context 'comment)))
1898 python-skeleton-autoinsert)))
1900 (defmacro python-skeleton-define (name doc &rest skel)
1901 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1902 The skeleton will be bound to python-skeleton-NAME and will
1903 be added to `python-mode-abbrev-table'."
1904 (let* ((name (symbol-name name))
1905 (function-name (intern (concat "python-skeleton-" name))))
1907 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1908 (setq python-skeleton-available
1909 (cons ',function-name python-skeleton-available))
1910 (define-skeleton ,function-name
1912 (format "Insert %s statement." name))
1914 (put 'python-skeleton-define 'lisp-indent-function 2)
1916 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1917 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1918 The skeleton will be bound to python-skeleton-NAME."
1919 (let* ((name (symbol-name name))
1920 (function-name (intern (concat "python-skeleton--" name)))
1922 "Add '%s' clause? " name)))
1925 `(< ,(format "%s:" name) \n \n
1927 `(define-skeleton ,function-name
1929 (format "Auxiliary skeleton for %s statement." name))
1931 (unless (y-or-n-p ,msg)
1934 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1936 (python-define-auxiliary-skeleton else nil)
1938 (python-define-auxiliary-skeleton except nil)
1940 (python-define-auxiliary-skeleton finally nil)
1942 (python-skeleton-define if nil
1946 ("other condition, %s: "
1950 '(python-skeleton--else) | ^)
1952 (python-skeleton-define while nil
1956 '(python-skeleton--else) | ^)
1958 (python-skeleton-define for nil
1962 '(python-skeleton--else) | ^)
1964 (python-skeleton-define try nil
1970 "except " str ":" \n
1973 '(python-skeleton--except)
1974 '(python-skeleton--else)
1975 '(python-skeleton--finally) | ^)
1977 (python-skeleton-define def nil
1979 "def " str " (" ("Parameter, %s: "
1980 (unless (equal ?\( (char-before)) ", ")
1982 "\"\"\"" - "\"\"\"" \n
1985 (python-skeleton-define class nil
1987 "class " str " (" ("Inheritance, %s: "
1988 (unless (equal ?\( (char-before)) ", ")
1992 "\"\"\"" - "\"\"\"" \n
1995 (defun python-skeleton-add-menu-items ()
1996 "Add menu items to Python->Skeletons menu."
1997 (let ((skeletons (sort python-skeleton-available 'string<))
1999 (dolist (skeleton skeletons)
2001 nil '("Python" "Skeletons")
2003 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2008 (defcustom python-ffap-setup-code
2009 "def __FFAP_get_module_path(module):
2012 path = __import__(module).__file__
2013 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2018 "Python code to get a module path."
2023 (defcustom python-ffap-string-code
2024 "__FFAP_get_module_path('''%s''')\n"
2025 "Python code used to get a string with the path of a module."
2030 (defun python-ffap-module-path (module)
2031 "Function for `ffap-alist' to return path for MODULE."
2033 (and (eq major-mode 'inferior-python-mode)
2034 (get-buffer-process (current-buffer)))
2035 (python-shell-get-process))))
2039 (python-shell-send-string-no-output
2040 (format python-ffap-string-code module) process)))
2042 (substring-no-properties module-file 1 -1))))))
2044 (eval-after-load "ffap"
2046 (push '(python-mode . python-ffap-module-path) ffap-alist)
2047 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2052 (defcustom python-check-command
2053 "pychecker --stdlib"
2054 "Command used to check a Python file."
2059 (defvar python-check-custom-command nil
2062 (defun python-check (command)
2063 "Check a Python file (default current buffer's file).
2064 Runs COMMAND, a shell command, as if by `compile'. See
2065 `python-check-command' for the default."
2067 (list (read-string "Check command: "
2068 (or python-check-custom-command
2069 (concat python-check-command " "
2070 (shell-quote-argument
2072 (let ((name (buffer-file-name)))
2074 (file-name-nondirectory name)))
2076 (setq python-check-custom-command command)
2077 (save-some-buffers (not compilation-ask-about-save) nil)
2078 (compilation-start command))
2083 (defcustom python-eldoc-setup-code
2084 "def __PYDOC_get_help(obj):
2087 if hasattr(obj, 'startswith'):
2088 obj = eval(obj, globals())
2089 doc = inspect.getdoc(obj)
2090 if not doc and callable(obj):
2092 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2093 target = obj.__init__
2099 args = inspect.formatargspec(
2100 *inspect.getargspec(target)
2103 doc = '{objtype} {name}{args}'.format(
2104 objtype=objtype, name=name, args=args
2107 doc = doc.splitlines()[0]
2114 "Python code to setup documentation retrieval."
2119 (defcustom python-eldoc-string-code
2120 "__PYDOC_get_help('''%s''')\n"
2121 "Python code used to get a string with the documentation of an object."
2126 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2127 "Internal implementation to get documentation at point.
2128 If not FORCE-INPUT is passed then what `current-word' returns
2129 will be used. If not FORCE-PROCESS is passed what
2130 `python-shell-get-process' returns is used."
2131 (let ((process (or force-process (python-shell-get-process))))
2133 "Eldoc needs an inferior Python process running."
2134 (let* ((current-defun (python-info-current-defun))
2135 (input (or force-input
2136 (with-syntax-table python-dotty-syntax-table
2137 (if (not current-defun)
2139 (concat current-defun "." (current-word))))))
2140 (ppss (syntax-ppss))
2141 (help (when (and input
2142 (not (string= input (concat current-defun ".")))
2143 (not (or (python-info-ppss-context 'string ppss)
2144 (python-info-ppss-context 'comment ppss))))
2145 (when (string-match (concat
2146 (regexp-quote (concat current-defun "."))
2150 (goto-char (point-min))
2153 (delete-region (point-marker) (search-forward "self."))
2154 (setq input (buffer-substring (point-min) (point-max)))))
2155 (python-shell-send-string-no-output
2156 (format python-eldoc-string-code input) process))))
2157 (with-current-buffer (process-buffer process)
2158 (when comint-last-prompt-overlay
2159 (delete-region comint-last-input-end
2160 (overlay-start comint-last-prompt-overlay))))
2162 (not (string= help "\n")))
2165 (defun python-eldoc-function ()
2166 "`eldoc-documentation-function' for Python.
2167 For this to work the best as possible you should call
2168 `python-shell-send-buffer' from time to time so context in
2169 inferior python process is updated properly."
2170 (python-eldoc--get-doc-at-point))
2172 (defun python-eldoc-at-point (symbol)
2173 "Get help on SYMBOL using `help'.
2174 Interactively, prompt for symbol."
2176 (let ((symbol (with-syntax-table python-dotty-syntax-table
2178 (enable-recursive-minibuffers t))
2179 (list (read-string (if symbol
2180 (format "Describe symbol (default %s): " symbol)
2181 "Describe symbol: ")
2183 (let ((process (python-shell-get-process)))
2185 (message "Eldoc needs an inferior Python process running.")
2186 (message (python-eldoc--get-doc-at-point symbol process)))))
2191 (defcustom python-imenu-include-defun-type t
2192 "Non-nil make imenu items to include its type."
2197 (defcustom python-imenu-make-tree t
2198 "Non-nil make imenu to build a tree menu.
2199 Set to nil for speed."
2204 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2205 "Label displayed to navigate to root from a subtree.
2206 It can contain a \"%s\" which will be replaced with the root name."
2211 (defvar python-imenu-index-alist nil
2212 "Calculated index tree for imenu.")
2214 (defun python-imenu-tree-assoc (keylist tree)
2215 "Using KEYLIST traverse TREE."
2217 (python-imenu-tree-assoc (cdr keylist)
2218 (ignore-errors (assoc (car keylist) tree)))
2221 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2222 "Make a tree from plain alist of module names.
2223 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2224 is the same thing, the difference is that FULL-ELEMENT remains
2225 untouched in all recursive calls.
2226 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2227 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2229 (let* ((subelement-point (cdr (assoc
2230 (mapconcat #'identity full-element ".")
2232 (subelement-name (car element-list))
2233 (subelement-position (python-util-position
2234 subelement-name full-element))
2235 (subelement-path (when subelement-position
2238 (- (length full-element)
2239 subelement-position)))))
2240 (let ((path-ref (python-imenu-tree-assoc subelement-path
2241 python-imenu-index-alist)))
2243 (push (cons subelement-name subelement-point)
2244 python-imenu-index-alist)
2245 (when (not (listp (cdr path-ref)))
2246 ;; Modifiy root cdr to be a list
2248 (list (cons (format python-imenu-subtree-root-label
2251 (mapconcat #'identity
2252 subelement-path ".")
2254 (when (not (assoc subelement-name path-ref))
2255 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2256 (python-imenu-make-element-tree (cdr element-list)
2257 full-element plain-index))))
2259 (defun python-imenu-make-tree (index)
2260 "Build the imenu alist tree from plain INDEX.
2262 The idea of this function is that given the alist:
2265 (\"Test.__init__\" . 200)
2266 (\"Test.some_method\" . 300)
2267 (\"Test.some_method.another\" . 400)
2268 (\"Test.something_else\" . 500)
2270 (\"test.reprint\" . 700)
2271 (\"test.reprint\" . 800))
2273 This tree gets built:
2275 '((\"Test\" . ((\"jump to...\" . 100)
2276 (\"__init__\" . 200)
2277 (\"some_method\" . ((\"jump to...\" . 300)
2278 (\"another\" . 400)))
2279 (\"something_else\" . 500)))
2280 (\"test\" . ((\"jump to...\" . 600)
2282 (\"reprint\" . 800))))
2284 Internally it uses `python-imenu-make-element-tree' to create all
2285 branches for each element."
2286 (setq python-imenu-index-alist nil)
2287 (mapc (lambda (element)
2288 (python-imenu-make-element-tree element element index))
2289 (mapcar (lambda (element)
2290 (split-string (car element) "\\." t)) index))
2291 python-imenu-index-alist)
2293 (defun python-imenu-create-index ()
2294 "`imenu-create-index-function' for Python."
2296 (goto-char (point-max))
2297 (while (python-beginning-of-defun-function 1 t)
2298 (let ((defun-dotted-name
2299 (python-info-current-defun python-imenu-include-defun-type)))
2300 (push (cons defun-dotted-name (point)) index)))
2301 (if python-imenu-make-tree
2302 (python-imenu-make-tree index)
2308 (defun python-info-current-defun (&optional include-type)
2309 "Return name of surrounding function with Python compatible dotty syntax.
2310 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2311 This function is compatible to be used as
2312 `add-log-current-defun-function' since it returns nil if point is
2313 not inside a defun."
2320 (goto-char (line-end-position))
2321 (forward-comment -9999)
2322 (setq min-indent (current-indentation))
2323 (while (python-beginning-of-defun-function 1 t)
2324 (when (or (< (current-indentation) min-indent)
2326 (setq first-run nil)
2327 (setq min-indent (current-indentation))
2328 (looking-at python-nav-beginning-of-defun-regexp)
2330 (if (not include-type)
2331 (match-string-no-properties 1)
2332 (mapconcat 'identity
2334 (match-string-no-properties 0)) " "))
2337 (mapconcat (lambda (string) string) names "."))))
2339 (defun python-info-closing-block ()
2340 "Return the point of the block the current line closes."
2341 (let ((closing-word (save-excursion
2342 (back-to-indentation)
2344 (indentation (current-indentation)))
2345 (when (member closing-word python-indent-dedenters)
2348 (while (and (> (current-indentation) indentation)
2350 (not (back-to-indentation))
2352 (back-to-indentation)
2354 ((not (equal indentation (current-indentation))) nil)
2355 ((string= closing-word "elif")
2356 (when (member (current-word) '("if" "elif"))
2358 ((string= closing-word "else")
2359 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2361 ((string= closing-word "except")
2362 (when (member (current-word) '("try"))
2364 ((string= closing-word "finally")
2365 (when (member (current-word) '("except" "else"))
2366 (point-marker))))))))
2368 (defun python-info-line-ends-backslash-p ()
2369 "Return non-nil if current line ends with backslash."
2370 (string= (or (ignore-errors
2373 (- (line-end-position) 1))) "") "\\"))
2375 (defun python-info-continuation-line-p ()
2376 "Return non-nil if current line is continuation of another."
2377 (let ((current-ppss-context-type (python-info-ppss-context-type)))
2379 (equal (save-excursion
2380 (goto-char (line-end-position))
2381 (forward-comment 9999)
2382 (python-info-ppss-context-type))
2383 current-ppss-context-type)
2384 (or (python-info-line-ends-backslash-p)
2385 (string-match ",[[:space:]]*$" (buffer-substring
2386 (line-beginning-position)
2387 (line-end-position)))
2389 (let ((innermost-paren (progn
2390 (goto-char (line-end-position))
2391 (python-info-ppss-context 'paren))))
2392 (when (and innermost-paren
2393 (and (<= (line-beginning-position) innermost-paren)
2394 (>= (line-end-position) innermost-paren)))
2395 (goto-char innermost-paren)
2396 (looking-at (python-rx open-paren (* space) line-end)))))
2398 (back-to-indentation)
2399 (python-info-ppss-context 'paren))))))
2401 (defun python-info-block-continuation-line-p ()
2402 "Return non-nil if current line is a continuation of a block."
2404 (while (and (not (bobp))
2405 (python-info-continuation-line-p))
2408 (back-to-indentation)
2409 (when (looking-at (python-rx block-start))
2412 (defun python-info-assignment-continuation-line-p ()
2413 "Return non-nil if current line is a continuation of an assignment."
2415 (while (and (not (bobp))
2416 (python-info-continuation-line-p))
2419 (back-to-indentation)
2420 (when (and (not (looking-at (python-rx block-start)))
2422 (and (re-search-forward (python-rx not-simple-operator
2424 not-simple-operator)
2425 (line-end-position) t)
2426 (not (or (python-info-ppss-context 'string)
2427 (python-info-ppss-context 'paren)
2428 (python-info-ppss-context 'comment))))))
2431 (defun python-info-ppss-context (type &optional syntax-ppss)
2432 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2433 TYPE can be 'comment, 'string or 'paren. It returns the start
2434 character address of the specified TYPE."
2435 (let ((ppss (or syntax-ppss (syntax-ppss))))
2446 (defun python-info-ppss-context-type (&optional syntax-ppss)
2447 "Return the context type using SYNTAX-PPSS.
2448 The type returned can be 'comment, 'string or 'paren."
2449 (let ((ppss (or syntax-ppss (syntax-ppss))))
2461 ;;; Utility functions
2464 (defun python-util-merge (type list1 list2 pred)
2465 "Destructively merge lists to produce a new one.
2466 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2467 are the list to be merged. Ordering of the elements is preserved
2468 according to PRED, a `less-than' predicate on the elements."
2470 (while (and list1 list2)
2471 (if (funcall pred (car list2) (car list1))
2472 (push (pop list2) res)
2473 (push (pop list1) res)))
2474 (nconc (nreverse res) list1 list2)))
2476 (defun python-util-position (item seq)
2477 "Find the first occurrence of ITEM in SEQ.
2478 Return the index of the matching item, or nil if not found."
2479 (let ((member-result (member item seq)))
2481 (- (length seq) (length member-result)))))
2485 (define-derived-mode python-mode fundamental-mode "Python"
2486 "Major mode for editing Python files.
2489 Entry to this mode calls the value of `python-mode-hook'
2490 if that value is non-nil."
2491 (set (make-local-variable 'tab-width) 8)
2492 (set (make-local-variable 'indent-tabs-mode) nil)
2494 (set (make-local-variable 'comment-start) "# ")
2495 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2497 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2498 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2500 (set (make-local-variable 'font-lock-defaults)
2501 '(python-font-lock-keywords
2503 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2505 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2506 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2508 (set (make-local-variable 'paragraph-start) "\\s-*$")
2509 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2511 (set (make-local-variable 'beginning-of-defun-function)
2512 #'python-beginning-of-defun-function)
2513 (set (make-local-variable 'end-of-defun-function)
2514 #'python-end-of-defun-function)
2516 (add-hook 'completion-at-point-functions
2517 'python-completion-complete-at-point nil 'local)
2519 (setq imenu-create-index-function #'python-imenu-create-index)
2521 (set (make-local-variable 'add-log-current-defun-function)
2522 #'python-info-current-defun)
2524 (set (make-local-variable 'skeleton-further-elements)
2526 (< '(backward-delete-char-untabify (min python-indent-offset
2528 (^ '(- (1+ (current-indentation))))))
2530 (set (make-local-variable 'eldoc-documentation-function)
2531 #'python-eldoc-function)
2533 (add-to-list 'hs-special-modes-alist
2534 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2536 (python-end-of-defun-function)) nil))
2538 (set (make-local-variable 'mode-require-final-newline) t)
2540 (set (make-local-variable 'outline-regexp)
2541 (python-rx (* space) block-start))
2542 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2543 (set (make-local-variable 'outline-level)
2545 "`outline-level' function for Python mode."
2546 (1+ (/ (current-indentation) python-indent-offset))))
2548 (python-skeleton-add-menu-items)
2550 (when python-indent-guess-indent-offset
2551 (python-indent-guess-indent-offset)))
2555 ;;; python.el ends here