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. There are also 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.
58 ;; `python-nav-jump-to-defun' is provided and allows jumping to a
59 ;; function or class definition quickly in the current buffer.
61 ;; Shell interaction: is provided and allows you to execute easily any
62 ;; block of code of your current buffer in an inferior Python process.
64 ;; Shell completion: hitting tab will try to complete the current
65 ;; word. Shell completion is implemented in a manner that if you
66 ;; change the `python-shell-interpreter' to any other (for example
67 ;; IPython) it should be easy to integrate another way to calculate
68 ;; completions. You just need to specify your custom
69 ;; `python-shell-completion-setup-code' and
70 ;; `python-shell-completion-string-code'.
72 ;; Here is a complete example of the settings you would use for
76 ;; python-shell-interpreter "ipython"
77 ;; python-shell-interpreter-args ""
78 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
79 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
80 ;; python-shell-completion-setup-code ""
81 ;; python-shell-completion-string-code
82 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
84 ;; For iPython 0.10 everything would be the same except for
85 ;; `python-shell-completion-string-code':
87 ;; (setq python-shell-completion-string-code
88 ;; "';'.join(__IP.complete('''%s'''))\n")
90 ;; Please note that the default completion system depends on the
91 ;; readline module, so if you are using some Operating System that
92 ;; bundles Python without it (like Windows) just install the
93 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
94 ;; you should be good to go.
96 ;; Shell virtualenv support: The shell also contains support for
97 ;; virtualenvs and other special environment modifications thanks to
98 ;; `python-shell-process-environment' and `python-shell-exec-path'.
99 ;; These two variables allows you to modify execution paths and
100 ;; environment variables to make easy for you to setup virtualenv rules
101 ;; or behavior modifications when running shells. Here is an example
102 ;; of how to make shell processes to be run using the /path/to/env/
105 ;; (setq python-shell-process-environment
107 ;; (format "PATH=%s" (mapconcat
110 ;; (cons (getenv "PATH")
111 ;; '("/path/to/env/bin/")))
113 ;; "VIRTUAL_ENV=/path/to/env/"))
114 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
116 ;; Since the above is cumbersome and can be programatically
117 ;; calculated, the variable `python-shell-virtualenv-path' is
118 ;; provided. When this variable is set with the path of the
119 ;; virtualenv to use, `process-environment' and `exec-path' get proper
120 ;; values in order to run shells inside the specified virtualenv. So
121 ;; the following will achieve the same as the previous example:
123 ;; (setq python-shell-virtualenv-path "/path/to/env/")
125 ;; Pdb tracking: when you execute a block of code that contains some
126 ;; call to pdb (or ipdb) it will prompt the block of code and will
127 ;; follow the execution of pdb marking the current line with an arrow.
129 ;; Symbol completion: you can complete the symbol at point. It uses
130 ;; the shell completion in background so you should run
131 ;; `python-shell-send-buffer' from time to time to get better results.
133 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
134 ;; def, for, if, try and while. These skeletons are integrated with
135 ;; dabbrev. If you have `dabbrev-mode' activated and
136 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
137 ;; the name of any of those defined and hit SPC, they will be
138 ;; automatically expanded.
140 ;; FFAP: You can find the filename for a given module when using ffap
141 ;; out of the box. This feature needs an inferior python shell
144 ;; Code check: Check the current file for errors with `python-check'
145 ;; using the program defined in `python-check-command'.
147 ;; Eldoc: returns documentation for object at point by using the
148 ;; inferior python subprocess to inspect its documentation. As you
149 ;; might guessed you should run `python-shell-send-buffer' from time
150 ;; to time to get better results too.
152 ;; imenu: This mode supports imenu. It builds a plain or tree menu
153 ;; depending on the value of `python-imenu-make-tree'. Also you can
154 ;; customize if menu items should include its type using
155 ;; `python-imenu-include-defun-type'.
157 ;; If you used python-mode.el you probably will miss auto-indentation
158 ;; when inserting newlines. To achieve the same behavior you have
161 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
163 ;; 2) Add the following hook in your .emacs:
165 ;; (add-hook 'python-mode-hook
167 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
169 ;; I'd recommend the first one since you'll get the same behavior for
170 ;; all modes out-of-the-box.
174 ;; Add this to your .emacs:
176 ;; (add-to-list 'load-path "/folder/containing/file")
183 (require 'ansi-color)
188 ;; Avoid compiler warnings
189 (defvar view-return-to-alist)
190 (defvar compilation-error-regexp-alist)
191 (defvar outline-heading-end-regexp))
193 (autoload 'comint-mode "comint")
196 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
198 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
201 "Python Language's flying circus support for Emacs."
204 :link '(emacs-commentary-link "python"))
209 (defvar python-mode-map
210 (let ((map (make-sparse-keymap)))
212 (substitute-key-definition 'backward-sentence
213 'python-nav-backward-sentence
215 (substitute-key-definition 'forward-sentence
216 'python-nav-forward-sentence
218 (define-key map "\C-c\C-j" 'python-nav-jump-to-defun)
220 (define-key map "\177" 'python-indent-dedent-line-backspace)
221 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
222 (define-key map "\C-c<" 'python-indent-shift-left)
223 (define-key map "\C-c>" 'python-indent-shift-right)
224 (define-key map ":" 'python-indent-electric-colon)
226 (define-key map "\C-c\C-tc" 'python-skeleton-class)
227 (define-key map "\C-c\C-td" 'python-skeleton-def)
228 (define-key map "\C-c\C-tf" 'python-skeleton-for)
229 (define-key map "\C-c\C-ti" 'python-skeleton-if)
230 (define-key map "\C-c\C-tt" 'python-skeleton-try)
231 (define-key map "\C-c\C-tw" 'python-skeleton-while)
233 (define-key map "\C-c\C-s" 'python-shell-send-string)
234 (define-key map "\C-c\C-r" 'python-shell-send-region)
235 (define-key map "\C-\M-x" 'python-shell-send-defun)
236 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
237 (define-key map "\C-c\C-l" 'python-shell-send-file)
238 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
239 ;; Some util commands
240 (define-key map "\C-c\C-v" 'python-check)
241 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
243 (substitute-key-definition 'complete-symbol 'completion-at-point
245 (easy-menu-define python-menu map "Python Mode menu"
247 :help "Python-specific Features"
248 ["Shift region left" python-indent-shift-left :active mark-active
249 :help "Shift region left by a single indentation step"]
250 ["Shift region right" python-indent-shift-right :active mark-active
251 :help "Shift region right by a single indentation step"]
253 ["Start of def/class" beginning-of-defun
254 :help "Go to start of outermost definition around point"]
255 ["End of def/class" end-of-defun
256 :help "Go to end of definition around point"]
257 ["Mark def/class" mark-defun
258 :help "Mark outermost definition around point"]
259 ["Jump to def/class" python-nav-jump-to-defun
260 :help "Jump to a class or function definition"]
264 ["Start interpreter" run-python
265 :help "Run inferior Python process in a separate buffer"]
266 ["Switch to shell" python-shell-switch-to-shell
267 :help "Switch to running inferior Python process"]
268 ["Eval string" python-shell-send-string
269 :help "Eval string in inferior Python session"]
270 ["Eval buffer" python-shell-send-buffer
271 :help "Eval buffer in inferior Python session"]
272 ["Eval region" python-shell-send-region
273 :help "Eval region in inferior Python session"]
274 ["Eval defun" python-shell-send-defun
275 :help "Eval defun in inferior Python session"]
276 ["Eval file" python-shell-send-file
277 :help "Eval file in inferior Python session"]
278 ["Debugger" pdb :help "Run pdb under GUD"]
280 ["Check file" python-check
281 :help "Check file for errors"]
282 ["Help on symbol" python-eldoc-at-point
283 :help "Get help on symbol at point"]
284 ["Complete symbol" completion-at-point
285 :help "Complete symbol before point"]))
287 "Keymap for `python-mode'.")
290 ;;; Python specialized rx
293 (defconst python-rx-constituents
295 `(block-start . ,(rx symbol-start
296 (or "def" "class" "if" "elif" "else" "try"
297 "except" "finally" "for" "while" "with")
299 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
301 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
302 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
303 `(open-paren . ,(rx (or "{" "[" "(")))
304 `(close-paren . ,(rx (or "}" "]" ")")))
305 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
306 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
307 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
308 "=" "%" "**" "//" "<<" ">>" "<=" "!="
309 "==" ">=" "is" "not")))
310 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
311 ">>=" "<<=" "&=" "^=" "|="))))
312 "Additional Python specific sexps for `python-rx'"))
314 (defmacro python-rx (&rest regexps)
315 "Python mode specialized rx macro which supports common python named REGEXPS."
316 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
317 (cond ((null regexps)
320 (rx-to-string `(and ,@regexps) t))
322 (rx-to-string (car regexps) t)))))
325 ;;; Font-lock and syntax
327 (defvar python-font-lock-keywords
330 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
331 "assert" "else" "if" "pass" "yield" "break" "except" "import"
332 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
333 "return" "def" "for" "lambda" "try" "self")
336 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
337 (1 font-lock-function-name-face))
339 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
340 (1 font-lock-type-face))
343 ;; copyright, license, credits, quit, exit are added by the
344 ;; site module and since they are not intended to be used in
345 ;; programs they are not added here either.
346 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
347 symbol-end) . font-lock-constant-face)
349 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
350 (0+ "." (1+ (or word ?_)))))
351 (1 font-lock-type-face))
352 ;; Builtin Exceptions
354 (or "ArithmeticError" "AssertionError" "AttributeError"
355 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
356 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
357 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
358 "ImportWarning" "IndentationError" "IndexError" "KeyError"
359 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
360 "NotImplementedError" "OSError" "OverflowError"
361 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
362 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
363 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
364 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
365 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
366 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
367 symbol-end) . font-lock-type-face)
370 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
371 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
372 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
373 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
374 "execfile" "file" "filter" "float" "format" "frozenset"
375 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
376 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
377 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
378 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
379 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
380 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
381 "unichr" "unicode" "vars" "xrange" "zip")
382 symbol-end) . font-lock-builtin-face)
384 ;; support for a = b = c = 5
386 (let ((re (python-rx (group (+ (any word ?. ?_)))
387 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
388 assignment-operator)))
389 (when (re-search-forward re limit t)
390 (while (and (python-info-ppss-context 'paren)
391 (re-search-forward re limit t)))
392 (if (and (not (python-info-ppss-context 'paren))
393 (not (equal (char-after (point-marker)) ?=)))
395 (set-match-data nil)))))
396 (1 font-lock-variable-name-face nil nil))
397 ;; support for a, b, c = (1, 2, 3)
399 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
400 (* ?, (* space) (+ (any word ?. ?_)) (* space))
401 ?, (* space) (+ (any word ?. ?_)) (* space)
402 assignment-operator)))
403 (when (and (re-search-forward re limit t)
404 (goto-char (nth 3 (match-data))))
405 (while (and (python-info-ppss-context 'paren)
406 (re-search-forward re limit t))
407 (goto-char (nth 3 (match-data))))
408 (if (not (python-info-ppss-context 'paren))
410 (set-match-data nil)))))
411 (1 font-lock-variable-name-face nil nil))))
413 (defconst python-font-lock-syntactic-keywords
414 ;; Make outer chars of matching triple-quote sequences into generic
415 ;; string delimiters. Fixme: Is there a better way?
416 ;; First avoid a sequence preceded by an odd number of backslashes.
417 `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
418 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
419 (3 (python-quote-syntax)))))
421 (defun python-quote-syntax ()
422 "Put `syntax-table' property correctly on triple quote.
423 Used for syntactic keywords. N is the match number (1, 2 or 3)."
424 ;; Given a triple quote, we have to check the context to know
425 ;; whether this is an opening or closing triple or whether it's
426 ;; quoted anyhow, and should be ignored. (For that we need to do
427 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
428 ;; to use it here despite initial worries.) We also have to sort
429 ;; out a possible prefix -- well, we don't _have_ to, but I think it
430 ;; should be treated as part of the string.
433 ;; ur"""ar""" x='"' # """
436 ;; x '"""' x """ \"""" x
438 (goto-char (match-beginning 0))
439 (let ((syntax (save-match-data (syntax-ppss))))
441 ((eq t (nth 3 syntax)) ; after unclosed fence
442 ;; Consider property for the last char if in a fenced string.
443 (goto-char (nth 8 syntax)) ; fence position
444 (skip-chars-forward "uUrR") ; skip any prefix
445 ;; Is it a matching sequence?
446 (if (eq (char-after) (char-after (match-beginning 2)))
447 (put-text-property (match-beginning 3) (match-end 3)
448 'syntax-table (string-to-syntax "|"))))
450 ;; Consider property for initial char, accounting for prefixes.
451 (put-text-property (match-beginning 1) (match-end 1)
452 'syntax-table (string-to-syntax "|")))
454 ;; Consider property for initial char, accounting for prefixes.
455 (put-text-property (match-beginning 2) (match-end 2)
456 'syntax-table (string-to-syntax "|"))))
459 (defvar python-mode-syntax-table
460 (let ((table (make-syntax-table)))
461 ;; Give punctuation syntax to ASCII that normally has symbol
462 ;; syntax or has word syntax and isn't a letter.
463 (let ((symbol (string-to-syntax "_"))
464 (sst (standard-syntax-table)))
467 (if (equal symbol (aref sst i))
468 (modify-syntax-entry i "." table)))))
469 (modify-syntax-entry ?$ "." table)
470 (modify-syntax-entry ?% "." table)
472 (modify-syntax-entry ?# "<" table)
473 (modify-syntax-entry ?\n ">" table)
474 (modify-syntax-entry ?' "\"" table)
475 (modify-syntax-entry ?` "$" table)
477 "Syntax table for Python files.")
479 (defvar python-dotty-syntax-table
480 (let ((table (make-syntax-table python-mode-syntax-table)))
481 (modify-syntax-entry ?. "w" table)
482 (modify-syntax-entry ?_ "w" table)
484 "Dotty syntax table for Python files.
485 It makes underscores and dots word constituent chars.")
490 (defcustom python-indent-offset 4
491 "Default indentation offset for Python."
496 (defcustom python-indent-guess-indent-offset t
497 "Non-nil tells Python mode to guess `python-indent-offset' value."
502 (defvar python-indent-current-level 0
503 "Current indentation level `python-indent-line-function' is using.")
505 (defvar python-indent-levels '(0)
506 "Levels of indentation available for `python-indent-line-function'.")
508 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
509 "List of words that should be dedented.
510 These make `python-indent-calculate-indentation' subtract the value of
511 `python-indent-offset'.")
513 (defun python-indent-guess-indent-offset ()
514 "Guess and set `python-indent-offset' for the current buffer."
518 (goto-char (point-min))
520 (while (and (not found-block)
522 (python-rx line-start block-start) nil t))
523 (when (and (not (python-info-ppss-context 'string))
524 (not (python-info-ppss-context 'comment))
526 (goto-char (line-end-position))
527 (forward-comment -9999)
528 (eq ?: (char-before))))
529 (setq found-block t)))
530 (if (not found-block)
531 (message "Can't guess python-indent-offset, using defaults: %s"
532 python-indent-offset)
534 (goto-char (line-end-position))
535 (python-info-continuation-line-p))
539 (forward-comment 9999)
540 (let ((indent-offset (current-indentation)))
541 (when (> indent-offset 0)
542 (setq python-indent-offset indent-offset))))))))
544 (defun python-indent-context ()
545 "Get information on indentation context.
546 Context information is returned with a cons with the form:
549 Where status can be any of the following symbols:
550 * inside-paren: If point in between (), {} or []
551 * inside-string: If point is inside a string
552 * after-backslash: Previous line ends in a backslash
553 * after-beginning-of-block: Point is after beginning of block
554 * after-line: Point is after normal line
555 * no-indent: Point is at beginning of buffer or other special case
556 START is the buffer position where the sexp starts."
559 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
563 ;; Beginning of buffer
565 (goto-char (line-beginning-position))
569 ((setq start (python-info-ppss-context 'paren ppss))
572 ((setq start (python-info-ppss-context 'string ppss))
575 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
576 (python-info-ppss-context 'comment ppss)))
577 (let ((line-beg-pos (line-beginning-position)))
578 (when (eq ?\\ (char-before (1- line-beg-pos)))
579 (- line-beg-pos 2)))))
581 ;; After beginning of block
582 ((setq start (save-excursion
583 (let ((block-regexp (python-rx block-start))
584 (block-start-line-end ":[[:space:]]*$"))
585 (back-to-indentation)
586 (forward-comment -9999)
587 (back-to-indentation)
588 (when (or (python-info-continuation-line-p)
589 (and (not (looking-at block-regexp))
593 (line-end-position) t))))
594 (while (and (forward-line -1)
595 (python-info-continuation-line-p)
597 (back-to-indentation)
598 (when (not (looking-at block-regexp))
600 (back-to-indentation)
601 (when (and (looking-at block-regexp)
602 (or (re-search-forward
604 (line-end-position) t)
606 (goto-char (line-end-position))
607 (python-info-continuation-line-p))))
609 'after-beginning-of-block)
611 ((setq start (save-excursion
612 (back-to-indentation)
613 (forward-comment -9999)
614 (python-nav-sentence-start)
621 (defun python-indent-calculate-indentation ()
622 "Calculate correct indentation offset for the current line."
623 (let* ((indentation-context (python-indent-context))
624 (context-status (car indentation-context))
625 (context-start (cdr indentation-context)))
631 ('after-beginning-of-block
632 (goto-char context-start)
633 (+ (current-indentation) python-indent-offset))
637 (goto-char context-start)
638 (current-indentation))
640 (back-to-indentation)
641 (looking-at (regexp-opt python-indent-dedenters)))
645 (goto-char context-start)
646 (current-indentation))
648 (let* ((block-continuation
651 (python-info-block-continuation-line-p)))
652 (assignment-continuation
655 (python-info-assignment-continuation-line-p)))
658 (back-to-indentation)
659 (when (looking-at "\\.")
661 (goto-char (line-end-position))
662 (while (and (re-search-backward "\\." (line-beginning-position) t)
663 (or (python-info-ppss-context 'comment)
664 (python-info-ppss-context 'string)
665 (python-info-ppss-context 'paren))))
666 (if (and (looking-at "\\.")
667 (not (or (python-info-ppss-context 'comment)
668 (python-info-ppss-context 'string)
669 (python-info-ppss-context 'paren))))
671 (+ (current-indentation) python-indent-offset)))))
676 (goto-char block-continuation)
678 (python-rx block-start (* space))
679 (line-end-position) t)
681 (assignment-continuation
682 (goto-char assignment-continuation)
684 (python-rx simple-operator)
685 (line-end-position) t)
688 (python-rx (* space))
689 (line-end-position) t)
692 (goto-char context-start)
695 (back-to-indentation)
697 "\\(?:return\\|from\\|import\\)\s+")))
698 (current-indentation)
699 (+ (current-indentation)
701 (match-string-no-properties 0))))))))
705 (skip-syntax-forward "\s" (line-end-position))
706 (when (and (looking-at (regexp-opt '(")" "]" "}")))
707 (not (forward-char 1))
708 (not (python-info-ppss-context 'paren)))
709 (goto-char context-start)
710 (back-to-indentation)
714 (goto-char context-start)
718 (line-beginning-position)
720 (forward-comment 9999))
722 (+ (current-indentation) python-indent-offset)
723 (forward-comment 9999)
726 (back-to-indentation)
727 (looking-at (regexp-opt '(")" "]" "}"))))
731 (defun python-indent-calculate-levels ()
732 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
733 (let* ((indentation (python-indent-calculate-indentation))
734 (remainder (% indentation python-indent-offset))
735 (steps (/ (- indentation remainder) python-indent-offset)))
736 (setq python-indent-levels (list 0))
737 (dotimes (step steps)
738 (push (* python-indent-offset (1+ step)) python-indent-levels))
739 (when (not (eq 0 remainder))
740 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
741 (setq python-indent-levels (nreverse python-indent-levels))
742 (setq python-indent-current-level (1- (length python-indent-levels)))))
744 (defun python-indent-toggle-levels ()
745 "Toggle `python-indent-current-level' over `python-indent-levels'."
746 (setq python-indent-current-level (1- python-indent-current-level))
747 (when (< python-indent-current-level 0)
748 (setq python-indent-current-level (1- (length python-indent-levels)))))
750 (defun python-indent-line (&optional force-toggle)
751 "Internal implementation of `python-indent-line-function'.
752 Uses the offset calculated in
753 `python-indent-calculate-indentation' and available levels
754 indicated by the variable `python-indent-levels' to set the
757 When the variable `last-command' is equal to
758 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
759 levels indicated in the variable `python-indent-levels' by
760 setting the current level in the variable
761 `python-indent-current-level'.
763 When the variable `last-command' is not equal to
764 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
765 possible indentation levels and saves it in the variable
766 `python-indent-levels'. Afterwards it sets the variable
767 `python-indent-current-level' correctly so offset is equal
768 to (`nth' `python-indent-current-level' `python-indent-levels')"
769 (if (or (and (eq this-command 'indent-for-tab-command)
770 (eq last-command this-command))
772 (if (not (equal python-indent-levels '(0)))
773 (python-indent-toggle-levels)
774 (python-indent-calculate-levels))
775 (python-indent-calculate-levels))
777 (delete-horizontal-space)
778 (indent-to (nth python-indent-current-level python-indent-levels))
781 (let ((closing-block-point (python-info-closing-block)))
782 (when closing-block-point
783 (message "Closes %s" (buffer-substring
786 (goto-char closing-block-point)
787 (line-end-position))))))))
789 (defun python-indent-line-function ()
790 "`indent-line-function' for Python mode.
791 See `python-indent-line' for details."
792 (python-indent-line))
794 (defun python-indent-dedent-line ()
795 "De-indent current line."
797 (when (and (not (or (python-info-ppss-context 'string)
798 (python-info-ppss-context 'comment)))
799 (<= (point-marker) (save-excursion
800 (back-to-indentation)
802 (> (current-column) 0))
803 (python-indent-line t)
806 (defun python-indent-dedent-line-backspace (arg)
807 "De-indent current line.
808 Argument ARG is passed to `backward-delete-char-untabify' when
809 point is not in between the indentation."
811 (when (not (python-indent-dedent-line))
812 (backward-delete-char-untabify arg)))
813 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
815 (defun python-indent-region (start end)
816 "Indent a python region automagically.
818 Called from a program, START and END specify the region to indent."
819 (let ((deactivate-mark nil))
822 (setq end (point-marker))
824 (or (bolp) (forward-line 1))
825 (while (< (point) end)
826 (or (and (bolp) (eolp))
829 (back-to-indentation)
830 (setq word (current-word))
834 (delete-horizontal-space)
835 (indent-to (python-indent-calculate-indentation)))))
837 (move-marker end nil))))
839 (defun python-indent-shift-left (start end &optional count)
840 "Shift lines contained in region START END by COUNT columns to the left.
841 COUNT defaults to `python-indent-offset'. If region isn't
842 active, the current line is shifted. The shifted region includes
843 the lines in which START and END lie. An error is signaled if
844 any lines in the region are indented less than COUNT columns."
847 (list (region-beginning) (region-end) current-prefix-arg)
848 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
850 (setq count (prefix-numeric-value count))
851 (setq count python-indent-offset))
853 (let ((deactivate-mark nil))
856 (while (< (point) end)
857 (if (and (< (current-indentation) count)
858 (not (looking-at "[ \t]*$")))
859 (error "Can't shift all lines enough"))
861 (indent-rigidly start end (- count))))))
863 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
865 (defun python-indent-shift-right (start end &optional count)
866 "Shift lines contained in region START END by COUNT columns to the left.
867 COUNT defaults to `python-indent-offset'. If region isn't
868 active, the current line is shifted. The shifted region includes
869 the lines in which START and END lie."
872 (list (region-beginning) (region-end) current-prefix-arg)
873 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
874 (let ((deactivate-mark nil))
876 (setq count (prefix-numeric-value count))
877 (setq count python-indent-offset))
878 (indent-rigidly start end count)))
880 (defun python-indent-electric-colon (arg)
881 "Insert a colon and maybe de-indent the current line.
882 With numeric ARG, just insert that many colons. With
883 \\[universal-argument], just insert a single colon."
885 (self-insert-command (if (not (integerp arg)) 1 arg))
888 (not (equal ?: (char-after (- (point-marker) 2))))
889 (not (or (python-info-ppss-context 'string)
890 (python-info-ppss-context 'comment))))
891 (let ((indentation (current-indentation))
892 (calculated-indentation (python-indent-calculate-indentation)))
893 (when (> indentation calculated-indentation)
895 (indent-line-to calculated-indentation)
896 (when (not (python-info-closing-block))
897 (indent-line-to indentation)))))))
898 (put 'python-indent-electric-colon 'delete-selection t)
903 (defvar python-nav-beginning-of-defun-regexp
904 (python-rx line-start (* space) defun (+ space) (group symbol-name))
905 "Regexp matching class or function definition.
906 The name of the defun should be grouped so it can be retrieved
907 via `match-string'.")
909 (defun python-nav-beginning-of-defun (&optional nodecorators)
910 "Move point to `beginning-of-defun'.
911 When NODECORATORS is non-nil decorators are not included. This
912 is the main part of`python-beginning-of-defun-function'
913 implementation. Return non-nil if point is moved to the
914 `beginning-of-defun'."
915 (let ((indent-pos (save-excursion
916 (back-to-indentation)
921 (when (not nodecorators)
922 (when (save-excursion
924 (looking-at (python-rx decorator)))
925 (while (and (not (bobp))
927 (looking-at (python-rx decorator))))
928 (when (not (bobp)) (forward-line 1)))))))
929 (if (and (> (point) indent-pos)
931 (goto-char (line-beginning-position))
932 (looking-at python-nav-beginning-of-defun-regexp)))
934 (goto-char (line-beginning-position))
935 (funcall include-decorators)
937 (goto-char (line-beginning-position))
938 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
940 (goto-char (or (python-info-ppss-context 'string) (point)))
941 (funcall include-decorators))
944 (defun python-beginning-of-defun-function (&optional arg nodecorators)
945 "Move point to the beginning of def or class.
946 With positive ARG move that number of functions forward. With
947 negative do the same but backwards. When NODECORATORS is non-nil
948 decorators are not included. Return non-nil if point is moved to the
949 `beginning-of-defun'."
950 (when (or (null arg) (= arg 0)) (setq arg 1))
952 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
954 (dotimes (i (- arg) found)
955 (python-end-of-defun-function)
956 (forward-comment 9999)
957 (goto-char (line-end-position))
960 (python-nav-beginning-of-defun nodecorators)))))))
962 (defun python-end-of-defun-function ()
963 "Move point to the end of def or class.
964 Returns nil if point is not in a def or class."
966 (let ((beg-defun-indent)
967 (decorator-regexp "[[:space:]]*@"))
968 (when (looking-at decorator-regexp)
969 (while (and (not (eobp))
971 (looking-at decorator-regexp))))
972 (when (not (looking-at python-nav-beginning-of-defun-regexp))
973 (python-beginning-of-defun-function))
974 (setq beg-defun-indent (current-indentation))
976 (while (and (forward-line 1)
978 (or (not (current-word))
979 (> (current-indentation) beg-defun-indent))))
980 (forward-comment 9999)
981 (goto-char (line-beginning-position))))
983 (defun python-nav-sentence-start ()
984 "Move to start of current sentence."
986 (while (and (not (back-to-indentation))
991 (python-info-line-ends-backslash-p))
992 (python-info-ppss-context 'string)
993 (python-info-ppss-context 'paren))
994 (forward-line -1)))))
996 (defun python-nav-sentence-end ()
997 "Move to end of current sentence."
999 (while (and (goto-char (line-end-position))
1002 (python-info-line-ends-backslash-p)
1003 (python-info-ppss-context 'string)
1004 (python-info-ppss-context 'paren))
1005 (forward-line 1)))))
1007 (defun python-nav-backward-sentence (&optional arg)
1008 "Move backward to start of sentence. With ARG, do it arg times.
1009 See `python-nav-forward-sentence' for more information."
1011 (or arg (setq arg 1))
1012 (python-nav-forward-sentence (- arg)))
1014 (defun python-nav-forward-sentence (&optional arg)
1015 "Move forward to next end of sentence. With ARG, repeat.
1016 With negative argument, move backward repeatedly to start of sentence."
1018 (or arg (setq arg 1))
1020 (forward-comment 9999)
1021 (python-nav-sentence-end)
1023 (setq arg (1- arg)))
1025 (python-nav-sentence-end)
1026 (forward-comment -9999)
1027 (python-nav-sentence-start)
1029 (setq arg (1+ arg))))
1031 (defun python-nav-list-defun-positions (&optional include-type)
1032 "Make an Alist of defun names and point markers for current buffer.
1033 When optional argument INCLUDE-TYPE is non-nil the type is
1034 included the defun name."
1039 (goto-char (point-max))
1040 (while (re-search-backward python-nav-beginning-of-defun-regexp nil t)
1041 (when (and (not (python-info-ppss-context 'string))
1042 (not (python-info-ppss-context 'comment))
1043 (not (python-info-ppss-context 'parent)))
1046 (python-info-current-defun include-type)
1050 (defun python-nav-read-defun ()
1051 "Read a defun name of current buffer and return its point marker.
1052 A cons cell with the form (DEFUN-NAME . POINT-MARKER) is returned
1053 when defun is completed, else nil."
1054 (let ((defs (python-nav-list-defun-positions)))
1055 (minibuffer-with-setup-hook
1057 (setq minibuffer-completion-table (mapcar 'car defs)))
1059 (read-from-minibuffer
1060 "Jump to definition: " nil
1061 minibuffer-local-must-match-map)))
1062 (when (not (string= stringdef ""))
1063 (assoc-string stringdef defs))))))
1065 (defun python-nav-jump-to-defun (def)
1066 "Jump to the definition of DEF in current file."
1068 (list (python-nav-read-defun)))
1069 (when (not (called-interactively-p 'interactive))
1070 (setq def (assoc-string def (python-nav-list-defun-positions))))
1071 (let ((def-marker (cdr def)))
1072 (when (markerp def-marker)
1073 (goto-char (marker-position def-marker))
1074 (back-to-indentation))))
1077 ;;; Shell integration
1079 (defcustom python-shell-buffer-name "Python"
1080 "Default buffer name for Python interpreter."
1085 (defcustom python-shell-interpreter "python"
1086 "Default Python interpreter for shell."
1091 (defcustom python-shell-internal-buffer-name "Python Internal"
1092 "Default buffer name for the Internal Python interpreter."
1097 (defcustom python-shell-interpreter-args "-i"
1098 "Default arguments for the Python interpreter."
1103 (defcustom python-shell-prompt-regexp ">>> "
1104 "Regular Expression matching top\-level input prompt of python shell.
1105 It should not contain a caret (^) at the beginning."
1110 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1111 "Regular Expression matching block input prompt of python shell.
1112 It should not contain a caret (^) at the beginning."
1117 (defcustom python-shell-prompt-output-regexp ""
1118 "Regular Expression matching output prompt of python shell.
1119 It should not contain a caret (^) at the beginning."
1124 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1125 "Regular Expression matching pdb input prompt of python shell.
1126 It should not contain a caret (^) at the beginning."
1131 (defcustom python-shell-send-setup-max-wait 5
1132 "Seconds to wait for process output before code setup.
1133 If output is received before the especified time then control is
1134 returned in that moment and not after waiting."
1139 (defcustom python-shell-process-environment nil
1140 "List of environment variables for Python shell.
1141 This variable follows the same rules as `process-environment'
1142 since it merges with it before the process creation routines are
1143 called. When this variable is nil, the Python shell is run with
1144 the default `process-environment'."
1145 :type '(repeat string)
1149 (defcustom python-shell-exec-path nil
1150 "List of path to search for binaries.
1151 This variable follows the same rules as `exec-path' since it
1152 merges with it before the process creation routines are called.
1153 When this variable is nil, the Python shell is run with the
1154 default `exec-path'."
1155 :type '(repeat string)
1159 (defcustom python-shell-virtualenv-path nil
1160 "Path to virtualenv root.
1161 This variable, when set to a string, makes the values stored in
1162 `python-shell-process-environment' and `python-shell-exec-path'
1163 to be modified properly so shells are started with the specified
1169 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1170 python-ffap-setup-code
1171 python-eldoc-setup-code)
1172 "List of code run by `python-shell-send-setup-codes'.
1173 Each variable can contain either a simple string with the code to
1174 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1175 is a string with the code to execute and DESCRIPTION is the
1177 :type '(repeat symbol)
1181 (defcustom python-shell-compilation-regexp-alist
1182 `((,(rx line-start (1+ (any " \t")) "File \""
1183 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1184 "\", line " (group (1+ digit)))
1186 (,(rx " in file " (group (1+ not-newline)) " on line "
1189 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1190 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1192 "`compilation-error-regexp-alist' for inferior Python."
1193 :type '(alist string)
1196 (defun python-shell-get-process-name (dedicated)
1197 "Calculate the appropiate process name for inferior Python process.
1198 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1199 returns a string with the form
1200 `python-shell-buffer-name'[variable `buffer-file-name'] else
1201 returns the value of `python-shell-buffer-name'. After
1202 calculating the process name adds the buffer name for the process
1203 in the `same-window-buffer-names' list."
1207 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1208 (format "%s" python-shell-buffer-name))))
1209 (add-to-list 'same-window-buffer-names (purecopy
1210 (format "*%s*" process-name)))
1213 (defun python-shell-internal-get-process-name ()
1214 "Calculate the appropiate process name for Internal Python process.
1215 The name is calculated from `python-shell-global-buffer-name' and
1216 a hash of all relevant global shell settings in order to ensure
1217 uniqueness for different types of configurations."
1219 python-shell-internal-buffer-name
1222 (python-shell-parse-command)
1223 (mapconcat #'symbol-value python-shell-setup-codes "")
1224 (mapconcat #'indentity python-shell-process-environment "")
1225 (or python-shell-virtualenv-path "")
1226 (mapconcat #'indentity python-shell-exec-path "")))))
1228 (defun python-shell-parse-command ()
1229 "Calculate the string used to execute the inferior Python process."
1230 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1232 (defun python-shell-calculate-process-environment ()
1233 "Calculate process environment given `python-shell-virtualenv-path'."
1234 (let ((env (python-util-merge 'list python-shell-process-environment
1235 process-environment 'string=))
1236 (virtualenv (if python-shell-virtualenv-path
1237 (directory-file-name python-shell-virtualenv-path)
1239 (if (not virtualenv)
1241 (dolist (envvar env)
1242 (let* ((split (split-string envvar "=" t))
1243 (name (nth 0 split))
1244 (value (nth 1 split)))
1245 (when (not (string= name "PYTHONHOME"))
1246 (when (string= name "PATH")
1247 (setq value (format "%s/bin:%s" virtualenv value)))
1248 (setq env (cons (format "%s=%s" name value) env)))))
1249 (cons (format "VIRTUAL_ENV=%s" virtualenv) env))))
1251 (defun python-shell-calculate-exec-path ()
1252 "Calculate exec path given `python-shell-virtualenv-path'."
1253 (let ((path (python-util-merge 'list python-shell-exec-path
1254 exec-path 'string=)))
1255 (if (not python-shell-virtualenv-path)
1257 (cons (format "%s/bin"
1258 (directory-file-name python-shell-virtualenv-path))
1261 (defun python-comint-output-filter-function (output)
1262 "Hook run after content is put into comint buffer.
1263 OUTPUT is a string with the contents of the buffer."
1264 (ansi-color-filter-apply output))
1266 (defvar inferior-python-mode-current-file nil
1267 "Current file from which a region was sent.")
1268 (make-variable-buffer-local 'inferior-python-mode-current-file)
1270 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1271 "Major mode for Python inferior process.
1272 Runs a Python interpreter as a subprocess of Emacs, with Python
1273 I/O through an Emacs buffer. Variables
1274 `python-shell-interpreter' and `python-shell-interpreter-args'
1275 controls which Python interpreter is run. Variables
1276 `python-shell-prompt-regexp',
1277 `python-shell-prompt-output-regexp',
1278 `python-shell-prompt-block-regexp',
1279 `python-shell-completion-setup-code',
1280 `python-shell-completion-string-code', `python-eldoc-setup-code',
1281 `python-eldoc-string-code', `python-ffap-setup-code' and
1282 `python-ffap-string-code' can customize this mode for different
1283 Python interpreters.
1285 You can also add additional setup code to be run at
1286 initialization of the interpreter via `python-shell-setup-codes'
1289 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1290 (set-syntax-table python-mode-syntax-table)
1291 (setq mode-line-process '(":%s"))
1292 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1293 python-shell-prompt-regexp
1294 python-shell-prompt-block-regexp
1295 python-shell-prompt-pdb-regexp))
1296 (make-local-variable 'comint-output-filter-functions)
1297 (add-hook 'comint-output-filter-functions
1298 'python-comint-output-filter-function)
1299 (add-hook 'comint-output-filter-functions
1300 'python-pdbtrack-comint-output-filter-function)
1301 (set (make-local-variable 'compilation-error-regexp-alist)
1302 python-shell-compilation-regexp-alist)
1303 (define-key inferior-python-mode-map [remap complete-symbol]
1304 'completion-at-point)
1305 (add-hook 'completion-at-point-functions
1306 'python-shell-completion-complete-at-point nil 'local)
1307 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1308 'python-shell-completion-complete-at-point)
1309 (define-key inferior-python-mode-map (kbd "<tab>")
1310 'python-shell-completion-complete-or-indent)
1311 (compilation-shell-minor-mode 1))
1313 (defun python-shell-make-comint (cmd proc-name &optional pop)
1314 "Create a python shell comint buffer.
1315 CMD is the python command to be executed and PROC-NAME is the
1316 process name the comint buffer will get. After the comint buffer
1317 is created the `inferior-python-mode' is activated. If POP is
1318 non-nil the buffer is shown."
1320 (let* ((proc-buffer-name (format "*%s*" proc-name))
1321 (process-environment (python-shell-calculate-process-environment))
1322 (exec-path (python-shell-calculate-exec-path)))
1323 (when (not (comint-check-proc proc-buffer-name))
1324 (let* ((cmdlist (split-string-and-unquote cmd))
1325 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1327 (current-buffer (current-buffer)))
1328 (with-current-buffer buffer
1329 (inferior-python-mode)
1330 (python-util-clone-local-variables current-buffer))))
1332 (pop-to-buffer proc-buffer-name))
1335 (defun run-python (dedicated cmd)
1336 "Run an inferior Python process.
1337 Input and output via buffer named after
1338 `python-shell-buffer-name'. If there is a process already
1339 running in that buffer, just switch to it.
1340 With argument, allows you to define DEDICATED, so a dedicated
1341 process for the current buffer is open, and define CMD so you can
1342 edit the command used to call the interpreter (default is value
1343 of `python-shell-interpreter' and arguments defined in
1344 `python-shell-interpreter-args'). Runs the hook
1345 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1347 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1349 (if current-prefix-arg
1351 (y-or-n-p "Make dedicated process? ")
1352 (read-string "Run Python: " (python-shell-parse-command)))
1353 (list nil (python-shell-parse-command))))
1354 (python-shell-make-comint cmd (python-shell-get-process-name dedicated) t)
1357 (defun run-python-internal ()
1358 "Run an inferior Internal Python process.
1359 Input and output via buffer named after
1360 `python-shell-internal-buffer-name' and what
1361 `python-shell-internal-get-process-name' returns. This new kind
1362 of shell is intended to be used for generic communication related
1363 to defined configurations. The main difference with global or
1364 dedicated shells is that these ones are attached to a
1365 configuration, not a buffer. This means that can be used for
1366 example to retrieve the sys.path and other stuff, without messing
1367 with user shells. Runs the hook
1368 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1369 run). \(Type \\[describe-mode] in the process buffer for a list
1372 (set-process-query-on-exit-flag
1374 (python-shell-make-comint
1375 (python-shell-parse-command)
1376 (python-shell-internal-get-process-name))) nil))
1378 (defun python-shell-get-process ()
1379 "Get inferior Python process for current buffer and return it."
1380 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1381 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1382 (global-proc-name (python-shell-get-process-name nil))
1383 (global-proc-buffer-name (format "*%s*" global-proc-name))
1384 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1385 (global-running (comint-check-proc global-proc-buffer-name)))
1386 ;; Always prefer dedicated
1387 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1388 (and global-running global-proc-buffer-name)))))
1390 (defun python-shell-get-or-create-process ()
1391 "Get or create an inferior Python process for current buffer and return it."
1392 (let* ((old-buffer (current-buffer))
1393 (dedicated-proc-name (python-shell-get-process-name t))
1394 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1395 (global-proc-name (python-shell-get-process-name nil))
1396 (global-proc-buffer-name (format "*%s*" global-proc-name))
1397 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1398 (global-running (comint-check-proc global-proc-buffer-name))
1399 (current-prefix-arg 4))
1400 (when (and (not dedicated-running) (not global-running))
1401 (if (call-interactively 'run-python)
1402 (setq dedicated-running t)
1403 (setq global-running t)))
1404 ;; Always prefer dedicated
1405 (switch-to-buffer old-buffer)
1406 (get-buffer-process (if dedicated-running
1407 dedicated-proc-buffer-name
1408 global-proc-buffer-name))))
1410 (defun python-shell-internal-get-or-create-process ()
1411 "Get or create an inferior Internal Python process."
1412 (let* ((proc-name (python-shell-internal-get-process-name))
1413 (proc-buffer-name (format "*%s*" proc-name)))
1414 (run-python-internal)
1415 (get-buffer-process proc-buffer-name)))
1417 (defun python-shell-send-string (string &optional process msg)
1418 "Send STRING to inferior Python PROCESS.
1419 When MSG is non-nil messages the first line of STRING."
1420 (interactive "sPython command: ")
1421 (let ((process (or process (python-shell-get-or-create-process)))
1422 (lines (split-string string "\n" t)))
1424 (message (format "Sent: %s..." (nth 0 lines))))
1425 (if (> (length lines) 1)
1426 (let* ((temp-file-name (make-temp-file "py"))
1427 (file-name (or (buffer-file-name) temp-file-name)))
1428 (with-temp-file temp-file-name
1430 (delete-trailing-whitespace))
1431 (python-shell-send-file file-name process temp-file-name))
1432 (comint-send-string process string)
1433 (when (or (not (string-match "\n$" string))
1434 (string-match "\n[ \t].*\n?$" string))
1435 (comint-send-string process "\n")))))
1437 (defun python-shell-send-string-no-output (string &optional process msg)
1438 "Send STRING to PROCESS and inhibit output.
1439 When MSG is non-nil messages the first line of STRING. Return
1441 (let* ((output-buffer)
1442 (process (or process (python-shell-get-or-create-process)))
1443 (comint-preoutput-filter-functions
1444 (append comint-preoutput-filter-functions
1445 '(ansi-color-filter-apply
1447 (setq output-buffer (concat output-buffer string))
1449 (python-shell-send-string string process msg)
1450 (accept-process-output process)
1452 (lambda (string) string)
1455 (if (> (length python-shell-prompt-output-regexp) 0)
1456 (format "\n*%s$\\|^%s"
1457 python-shell-prompt-regexp
1458 (or python-shell-prompt-output-regexp ""))
1460 python-shell-prompt-regexp)) t) "\n")))
1462 (defun python-shell-internal-send-string (string)
1463 "Send STRING to the Internal Python interpreter.
1464 Returns the output. See `python-shell-send-string-no-output'."
1465 (python-shell-send-string-no-output
1466 ;; Makes this function compatible with the old
1467 ;; python-send-receive. (At least for CEDET).
1468 (replace-regexp-in-string "_emacs_out +" "" string)
1469 (python-shell-internal-get-or-create-process) nil))
1471 (define-obsolete-function-alias
1472 'python-send-receive 'python-shell-internal-send-string "23.3"
1473 "Send STRING to inferior Python (if any) and return result.
1474 The result is what follows `_emacs_out' in the output.
1475 This is a no-op if `python-check-comint-prompt' returns nil.")
1477 (defun python-shell-send-region (start end)
1478 "Send the region delimited by START and END to inferior Python process."
1480 (let ((deactivate-mark nil))
1481 (python-shell-send-string (buffer-substring start end) nil t)))
1483 (defun python-shell-send-buffer ()
1484 "Send the entire buffer to inferior Python process."
1488 (python-shell-send-region (point-min) (point-max))))
1490 (defun python-shell-send-defun (arg)
1491 "Send the current defun to inferior Python process.
1492 When argument ARG is non-nil sends the innermost defun."
1495 (python-shell-send-region
1497 (or (python-beginning-of-defun-function)
1498 (progn (beginning-of-line) (point-marker))))
1500 (or (python-end-of-defun-function)
1501 (progn (end-of-line) (point-marker)))))))
1503 (defun python-shell-send-file (file-name &optional process temp-file-name)
1504 "Send FILE-NAME to inferior Python PROCESS.
1505 If TEMP-FILE-NAME is passed then that file is used for processing
1506 instead, while internally the shell will continue to use
1508 (interactive "fFile to send: ")
1509 (let* ((process (or process (python-shell-get-or-create-process)))
1510 (temp-file-name (when temp-file-name
1511 (expand-file-name temp-file-name)))
1512 (file-name (or (expand-file-name file-name) temp-file-name)))
1513 (when (not file-name)
1514 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1515 (with-current-buffer (process-buffer process)
1516 (setq inferior-python-mode-current-file
1517 (convert-standard-filename file-name)))
1518 (python-shell-send-string
1520 (concat "__pyfile = open('''%s''');"
1521 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1523 (or temp-file-name file-name) file-name)
1526 (defun python-shell-switch-to-shell ()
1527 "Switch to inferior Python process buffer."
1529 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1531 (defun python-shell-send-setup-code ()
1532 "Send all setup code for shell.
1533 This function takes the list of setup code to send from the
1534 `python-shell-setup-codes' list."
1535 (let ((msg "Sent %s")
1536 (process (get-buffer-process (current-buffer))))
1537 (accept-process-output process python-shell-send-setup-max-wait)
1538 (dolist (code python-shell-setup-codes)
1541 (setq msg (cdr code)))
1542 (message (format msg code))
1543 (python-shell-send-string-no-output
1544 (symbol-value code) process)))))
1546 (add-hook 'inferior-python-mode-hook
1547 #'python-shell-send-setup-code)
1550 ;;; Shell completion
1552 (defcustom python-shell-completion-setup-code
1556 def __COMPLETER_all_completions(text): []
1559 readline.set_completer(rlcompleter.Completer().complete)
1560 def __COMPLETER_all_completions(text):
1566 res = readline.get_completer()(text, i)
1569 completions.append(res)
1573 "Code used to setup completion in inferior Python processes."
1578 (defcustom python-shell-completion-string-code
1579 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1580 "Python code used to get a string of completions separated by semicolons."
1585 (defun python-shell-completion--get-completions (input process)
1586 "Retrieve available completions for INPUT using PROCESS."
1587 (with-current-buffer (process-buffer process)
1588 (let ((completions (python-shell-send-string-no-output
1589 (format python-shell-completion-string-code input)
1591 (when (> (length completions) 2)
1592 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1594 (defun python-shell-completion--get-completion (input completions)
1595 "Get completion for INPUT using COMPLETIONS."
1596 (let ((completion (when completions
1597 (try-completion input completions))))
1598 (cond ((eq completion t)
1601 (message "Can't find completion for \"%s\"" input)
1604 ((not (string= input completion))
1607 (message "Making completion list...")
1608 (with-output-to-temp-buffer "*Python Completions*"
1609 (display-completion-list
1610 (all-completions input completions)))
1613 (defun python-shell-completion-complete-at-point ()
1614 "Perform completion at point in inferior Python process."
1616 (with-syntax-table python-dotty-syntax-table
1617 (when (and comint-last-prompt-overlay
1618 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1619 (let* ((process (get-buffer-process (current-buffer)))
1620 (input (substring-no-properties
1621 (or (comint-word (current-word)) "") nil nil)))
1622 (delete-char (- (length input)))
1624 (python-shell-completion--get-completion
1625 input (python-shell-completion--get-completions input process)))))))
1627 (defun python-shell-completion-complete-or-indent ()
1628 "Complete or indent depending on the context.
1629 If content before pointer is all whitespace indent. If not try
1632 (if (string-match "^[[:space:]]*$"
1633 (buffer-substring (comint-line-beginning-position)
1635 (indent-for-tab-command)
1636 (comint-dynamic-complete)))
1639 ;;; PDB Track integration
1641 (defcustom python-pdbtrack-stacktrace-info-regexp
1642 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1643 "Regular Expression matching stacktrace information.
1644 Used to extract the current line and module being inspected. The
1645 regexp should not start with a caret (^) and can contain a string
1646 placeholder (\%s) which is replaced with the filename beign
1647 inspected (so other files in the debugging process are not
1653 (defvar python-pdbtrack-tracking-buffers '()
1654 "Alist containing elements of form (#<buffer> . #<buffer>).
1655 The car of each element of the alist is the tracking buffer and
1656 the cdr is the tracked buffer.")
1658 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1659 "Get/Add a tracked buffer for the current buffer.
1660 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1661 Returns a cons with the form:
1662 * (#<tracking buffer> . #< tracked buffer>)."
1664 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1665 (let* ((file (with-current-buffer (current-buffer)
1666 inferior-python-mode-current-file))
1668 `(,(current-buffer) .
1669 ,(or (get-file-buffer file)
1670 (find-file-noselect file)))))
1671 (set-buffer (cdr tracking-buffers))
1673 (set-buffer (car tracking-buffers))
1674 (setq python-pdbtrack-tracking-buffers
1675 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1678 (defun python-pdbtrack-comint-output-filter-function (output)
1679 "Move overlay arrow to current pdb line in tracked buffer.
1680 Argument OUTPUT is a string with the output from the comint process."
1681 (when (not (string= output ""))
1682 (let ((full-output (ansi-color-filter-apply
1683 (buffer-substring comint-last-input-end
1685 (if (string-match python-shell-prompt-pdb-regexp full-output)
1686 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1690 (format python-pdbtrack-stacktrace-info-regexp
1692 inferior-python-mode-current-file))
1694 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1695 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1696 (tracked-buffer-line-pos))
1698 (with-current-buffer (cdr tracking-buffers)
1699 (set (make-local-variable 'overlay-arrow-string) "=>")
1700 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1701 (setq tracked-buffer-line-pos (progn
1702 (goto-char (point-min))
1703 (forward-line (1- line-num))
1705 (when tracked-buffer-window
1706 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1707 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1708 (pop-to-buffer (cdr tracking-buffers))
1709 (switch-to-buffer-other-window (car tracking-buffers)))
1710 (let ((tracking-buffers (assq (current-buffer)
1711 python-pdbtrack-tracking-buffers)))
1712 (when tracking-buffers
1713 (if inferior-python-mode-current-file
1714 (with-current-buffer (cdr tracking-buffers)
1715 (set-marker overlay-arrow-position nil))
1716 (kill-buffer (cdr tracking-buffers)))
1717 (setq python-pdbtrack-tracking-buffers
1718 (assq-delete-all (current-buffer)
1719 python-pdbtrack-tracking-buffers)))))))
1723 ;;; Symbol completion
1725 (defun python-completion-complete-at-point ()
1726 "Complete current symbol at point.
1727 For this to work the best as possible you should call
1728 `python-shell-send-buffer' from time to time so context in
1729 inferior python process is updated properly."
1731 (let ((process (python-shell-get-process)))
1733 (error "Completion needs an inferior Python process running")
1734 (with-syntax-table python-dotty-syntax-table
1735 (let* ((input (substring-no-properties
1736 (or (comint-word (current-word)) "") nil nil))
1737 (completions (python-shell-completion--get-completions
1739 (delete-char (- (length input)))
1741 (python-shell-completion--get-completion
1742 input completions)))))))
1744 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1749 (defcustom python-fill-comment-function 'python-fill-comment
1750 "Function to fill comments.
1751 This is the function used by `python-fill-paragraph-function' to
1757 (defcustom python-fill-string-function 'python-fill-string
1758 "Function to fill strings.
1759 This is the function used by `python-fill-paragraph-function' to
1765 (defcustom python-fill-decorator-function 'python-fill-decorator
1766 "Function to fill decorators.
1767 This is the function used by `python-fill-paragraph-function' to
1773 (defcustom python-fill-paren-function 'python-fill-paren
1774 "Function to fill parens.
1775 This is the function used by `python-fill-paragraph-function' to
1781 (defun python-fill-paragraph-function (&optional justify)
1782 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1783 If any of the current line is in or at the end of a multi-line string,
1784 fill the string or the paragraph of it that point is in, preserving
1785 the string's indentation.
1786 Optional argument JUSTIFY defines if the paragraph should be justified."
1789 (back-to-indentation)
1792 ((funcall python-fill-comment-function justify))
1793 ;; Strings/Docstrings
1794 ((save-excursion (skip-chars-forward "\"'uUrR")
1795 (python-info-ppss-context 'string))
1796 (funcall python-fill-string-function justify))
1798 ((equal (char-after (save-excursion
1799 (back-to-indentation)
1800 (point-marker))) ?@)
1801 (funcall python-fill-decorator-function justify))
1803 ((or (python-info-ppss-context 'paren)
1804 (looking-at (python-rx open-paren))
1806 (skip-syntax-forward "^(" (line-end-position))
1807 (looking-at (python-rx open-paren))))
1808 (funcall python-fill-paren-function justify))
1811 (defun python-fill-comment (&optional justify)
1812 "Comment fill function for `python-fill-paragraph-function'.
1813 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1814 (fill-comment-paragraph justify))
1816 (defun python-fill-string (&optional justify)
1817 "String fill function for `python-fill-paragraph-function'.
1818 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1819 (let ((marker (point-marker))
1820 (string-start-marker
1822 (skip-chars-forward "\"'uUrR")
1823 (goto-char (python-info-ppss-context 'string))
1824 (skip-chars-forward "\"'uUrR")
1826 (reg-start (line-beginning-position))
1829 (while (python-info-ppss-context 'string)
1830 (goto-char (1+ (point-marker))))
1831 (skip-chars-backward "\"'")
1833 (reg-end (line-end-position))
1834 (fill-paragraph-function))
1836 (narrow-to-region reg-start reg-end)
1838 (goto-char string-start-marker)
1839 (delete-region (point-marker) (progn
1840 (skip-syntax-forward "> ")
1842 (goto-char string-end-marker)
1843 (delete-region (point-marker) (progn
1844 (skip-syntax-backward "> ")
1848 (fill-paragraph justify))
1849 ;; If there is a newline in the docstring lets put triple
1850 ;; quote in it's own line to follow pep 8
1851 (when (save-excursion
1852 (re-search-backward "\n" string-start-marker t))
1854 (newline-and-indent))
1855 (fill-paragraph justify)))) t)
1857 (defun python-fill-decorator (&optional justify)
1858 "Decorator fill function for `python-fill-paragraph-function'.
1859 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1862 (defun python-fill-paren (&optional justify)
1863 "Paren fill function for `python-fill-paragraph-function'.
1864 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1866 (narrow-to-region (progn
1867 (while (python-info-ppss-context 'paren)
1868 (goto-char (1- (point-marker))))
1870 (line-beginning-position))
1872 (when (not (python-info-ppss-context 'paren))
1874 (when (not (python-info-ppss-context 'paren))
1875 (skip-syntax-backward "^)")))
1876 (while (python-info-ppss-context 'paren)
1877 (goto-char (1+ (point-marker))))
1879 (let ((paragraph-start "\f\\|[ \t]*$")
1880 (paragraph-separate ",")
1881 (fill-paragraph-function))
1882 (goto-char (point-min))
1883 (fill-paragraph justify))
1886 (python-indent-line)
1887 (goto-char (line-end-position)))) t)
1892 (defcustom python-skeleton-autoinsert nil
1893 "Non-nil means template skeletons will be automagically inserted.
1894 This happens when pressing \"if<SPACE>\", for example, to prompt for
1900 (defvar python-skeleton-available '()
1901 "Internal list of available skeletons.")
1903 (define-abbrev-table 'python-mode-abbrev-table ()
1904 "Abbrev table for Python mode."
1906 ;; Allow / inside abbrevs.
1907 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1908 ;; Only expand in code.
1909 :enable-function (lambda ()
1911 (not (or (python-info-ppss-context 'string)
1912 (python-info-ppss-context 'comment)))
1913 python-skeleton-autoinsert)))
1915 (defmacro python-skeleton-define (name doc &rest skel)
1916 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1917 The skeleton will be bound to python-skeleton-NAME and will
1918 be added to `python-mode-abbrev-table'."
1919 (let* ((name (symbol-name name))
1920 (function-name (intern (concat "python-skeleton-" name))))
1922 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1923 (setq python-skeleton-available
1924 (cons ',function-name python-skeleton-available))
1925 (define-skeleton ,function-name
1927 (format "Insert %s statement." name))
1929 (put 'python-skeleton-define 'lisp-indent-function 2)
1931 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1932 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1933 The skeleton will be bound to python-skeleton-NAME."
1934 (let* ((name (symbol-name name))
1935 (function-name (intern (concat "python-skeleton--" name)))
1937 "Add '%s' clause? " name)))
1940 `(< ,(format "%s:" name) \n \n
1942 `(define-skeleton ,function-name
1944 (format "Auxiliary skeleton for %s statement." name))
1946 (unless (y-or-n-p ,msg)
1949 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1951 (python-define-auxiliary-skeleton else nil)
1953 (python-define-auxiliary-skeleton except nil)
1955 (python-define-auxiliary-skeleton finally nil)
1957 (python-skeleton-define if nil
1961 ("other condition, %s: "
1965 '(python-skeleton--else) | ^)
1967 (python-skeleton-define while nil
1971 '(python-skeleton--else) | ^)
1973 (python-skeleton-define for nil
1977 '(python-skeleton--else) | ^)
1979 (python-skeleton-define try nil
1985 "except " str ":" \n
1988 '(python-skeleton--except)
1989 '(python-skeleton--else)
1990 '(python-skeleton--finally) | ^)
1992 (python-skeleton-define def nil
1994 "def " str " (" ("Parameter, %s: "
1995 (unless (equal ?\( (char-before)) ", ")
1997 "\"\"\"" - "\"\"\"" \n
2000 (python-skeleton-define class nil
2002 "class " str " (" ("Inheritance, %s: "
2003 (unless (equal ?\( (char-before)) ", ")
2007 "\"\"\"" - "\"\"\"" \n
2010 (defun python-skeleton-add-menu-items ()
2011 "Add menu items to Python->Skeletons menu."
2012 (let ((skeletons (sort python-skeleton-available 'string<))
2014 (dolist (skeleton skeletons)
2016 nil '("Python" "Skeletons")
2018 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2023 (defcustom python-ffap-setup-code
2024 "def __FFAP_get_module_path(module):
2027 path = __import__(module).__file__
2028 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2033 "Python code to get a module path."
2038 (defcustom python-ffap-string-code
2039 "__FFAP_get_module_path('''%s''')\n"
2040 "Python code used to get a string with the path of a module."
2045 (defun python-ffap-module-path (module)
2046 "Function for `ffap-alist' to return path for MODULE."
2048 (and (eq major-mode 'inferior-python-mode)
2049 (get-buffer-process (current-buffer)))
2050 (python-shell-get-process))))
2054 (python-shell-send-string-no-output
2055 (format python-ffap-string-code module) process)))
2057 (substring-no-properties module-file 1 -1))))))
2059 (eval-after-load "ffap"
2061 (push '(python-mode . python-ffap-module-path) ffap-alist)
2062 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2067 (defcustom python-check-command
2068 "pychecker --stdlib"
2069 "Command used to check a Python file."
2074 (defvar python-check-custom-command nil
2077 (defun python-check (command)
2078 "Check a Python file (default current buffer's file).
2079 Runs COMMAND, a shell command, as if by `compile'. See
2080 `python-check-command' for the default."
2082 (list (read-string "Check command: "
2083 (or python-check-custom-command
2084 (concat python-check-command " "
2085 (shell-quote-argument
2087 (let ((name (buffer-file-name)))
2089 (file-name-nondirectory name)))
2091 (setq python-check-custom-command command)
2092 (save-some-buffers (not compilation-ask-about-save) nil)
2093 (compilation-start command))
2098 (defcustom python-eldoc-setup-code
2099 "def __PYDOC_get_help(obj):
2102 if hasattr(obj, 'startswith'):
2103 obj = eval(obj, globals())
2104 doc = inspect.getdoc(obj)
2105 if not doc and callable(obj):
2107 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2108 target = obj.__init__
2114 args = inspect.formatargspec(
2115 *inspect.getargspec(target)
2118 doc = '{objtype} {name}{args}'.format(
2119 objtype=objtype, name=name, args=args
2122 doc = doc.splitlines()[0]
2129 "Python code to setup documentation retrieval."
2134 (defcustom python-eldoc-string-code
2135 "__PYDOC_get_help('''%s''')\n"
2136 "Python code used to get a string with the documentation of an object."
2141 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2142 "Internal implementation to get documentation at point.
2143 If not FORCE-INPUT is passed then what `current-word' returns
2144 will be used. If not FORCE-PROCESS is passed what
2145 `python-shell-get-process' returns is used."
2146 (let ((process (or force-process (python-shell-get-process))))
2148 "Eldoc needs an inferior Python process running."
2149 (let* ((current-defun (python-info-current-defun))
2150 (input (or force-input
2151 (with-syntax-table python-dotty-syntax-table
2152 (if (not current-defun)
2154 (concat current-defun "." (current-word))))))
2155 (ppss (syntax-ppss))
2156 (help (when (and input
2157 (not (string= input (concat current-defun ".")))
2158 (not (or (python-info-ppss-context 'string ppss)
2159 (python-info-ppss-context 'comment ppss))))
2160 (when (string-match (concat
2161 (regexp-quote (concat current-defun "."))
2165 (goto-char (point-min))
2168 (delete-region (point-marker) (search-forward "self."))
2169 (setq input (buffer-substring (point-min) (point-max)))))
2170 (python-shell-send-string-no-output
2171 (format python-eldoc-string-code input) process))))
2172 (with-current-buffer (process-buffer process)
2173 (when comint-last-prompt-overlay
2174 (delete-region comint-last-input-end
2175 (overlay-start comint-last-prompt-overlay))))
2177 (not (string= help "\n")))
2180 (defun python-eldoc-function ()
2181 "`eldoc-documentation-function' for Python.
2182 For this to work the best as possible you should call
2183 `python-shell-send-buffer' from time to time so context in
2184 inferior python process is updated properly."
2185 (python-eldoc--get-doc-at-point))
2187 (defun python-eldoc-at-point (symbol)
2188 "Get help on SYMBOL using `help'.
2189 Interactively, prompt for symbol."
2191 (let ((symbol (with-syntax-table python-dotty-syntax-table
2193 (enable-recursive-minibuffers t))
2194 (list (read-string (if symbol
2195 (format "Describe symbol (default %s): " symbol)
2196 "Describe symbol: ")
2198 (let ((process (python-shell-get-process)))
2200 (message "Eldoc needs an inferior Python process running.")
2201 (message (python-eldoc--get-doc-at-point symbol process)))))
2206 (defcustom python-imenu-include-defun-type t
2207 "Non-nil make imenu items to include its type."
2212 (defcustom python-imenu-make-tree t
2213 "Non-nil make imenu to build a tree menu.
2214 Set to nil for speed."
2219 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2220 "Label displayed to navigate to root from a subtree.
2221 It can contain a \"%s\" which will be replaced with the root name."
2226 (defvar python-imenu-index-alist nil
2227 "Calculated index tree for imenu.")
2229 (defun python-imenu-tree-assoc (keylist tree)
2230 "Using KEYLIST traverse TREE."
2232 (python-imenu-tree-assoc (cdr keylist)
2233 (ignore-errors (assoc (car keylist) tree)))
2236 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2237 "Make a tree from plain alist of module names.
2238 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2239 is the same thing, the difference is that FULL-ELEMENT remains
2240 untouched in all recursive calls.
2241 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2242 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2244 (let* ((subelement-point (cdr (assoc
2245 (mapconcat #'identity full-element ".")
2247 (subelement-name (car element-list))
2248 (subelement-position (python-util-position
2249 subelement-name full-element))
2250 (subelement-path (when subelement-position
2253 (- (length full-element)
2254 subelement-position)))))
2255 (let ((path-ref (python-imenu-tree-assoc subelement-path
2256 python-imenu-index-alist)))
2258 (push (cons subelement-name subelement-point)
2259 python-imenu-index-alist)
2260 (when (not (listp (cdr path-ref)))
2261 ;; Modifiy root cdr to be a list
2263 (list (cons (format python-imenu-subtree-root-label
2266 (mapconcat #'identity
2267 subelement-path ".")
2269 (when (not (assoc subelement-name path-ref))
2270 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2271 (python-imenu-make-element-tree (cdr element-list)
2272 full-element plain-index))))
2274 (defun python-imenu-make-tree (index)
2275 "Build the imenu alist tree from plain INDEX.
2277 The idea of this function is that given the alist:
2280 (\"Test.__init__\" . 200)
2281 (\"Test.some_method\" . 300)
2282 (\"Test.some_method.another\" . 400)
2283 (\"Test.something_else\" . 500)
2285 (\"test.reprint\" . 700)
2286 (\"test.reprint\" . 800))
2288 This tree gets built:
2290 '((\"Test\" . ((\"jump to...\" . 100)
2291 (\"__init__\" . 200)
2292 (\"some_method\" . ((\"jump to...\" . 300)
2293 (\"another\" . 400)))
2294 (\"something_else\" . 500)))
2295 (\"test\" . ((\"jump to...\" . 600)
2297 (\"reprint\" . 800))))
2299 Internally it uses `python-imenu-make-element-tree' to create all
2300 branches for each element."
2301 (setq python-imenu-index-alist nil)
2302 (mapc (lambda (element)
2303 (python-imenu-make-element-tree element element index))
2304 (mapcar (lambda (element)
2305 (split-string (car element) "\\." t)) index))
2306 python-imenu-index-alist)
2308 (defun python-imenu-create-index ()
2309 "`imenu-create-index-function' for Python."
2311 (python-nav-list-defun-positions python-imenu-include-defun-type)))
2312 (if python-imenu-make-tree
2313 (python-imenu-make-tree index)
2319 (defun python-info-current-defun (&optional include-type)
2320 "Return name of surrounding function with Python compatible dotty syntax.
2321 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2322 This function is compatible to be used as
2323 `add-log-current-defun-function' since it returns nil if point is
2324 not inside a defun."
2331 (goto-char (line-end-position))
2332 (forward-comment -9999)
2333 (setq min-indent (current-indentation))
2334 (while (python-beginning-of-defun-function 1 t)
2335 (when (or (< (current-indentation) min-indent)
2337 (setq first-run nil)
2338 (setq min-indent (current-indentation))
2339 (looking-at python-nav-beginning-of-defun-regexp)
2341 (if (not include-type)
2342 (match-string-no-properties 1)
2343 (mapconcat 'identity
2345 (match-string-no-properties 0)) " "))
2348 (mapconcat (lambda (string) string) names "."))))
2350 (defun python-info-closing-block ()
2351 "Return the point of the block the current line closes."
2352 (let ((closing-word (save-excursion
2353 (back-to-indentation)
2355 (indentation (current-indentation)))
2356 (when (member closing-word python-indent-dedenters)
2359 (while (and (> (current-indentation) indentation)
2361 (not (back-to-indentation))
2363 (back-to-indentation)
2365 ((not (equal indentation (current-indentation))) nil)
2366 ((string= closing-word "elif")
2367 (when (member (current-word) '("if" "elif"))
2369 ((string= closing-word "else")
2370 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2372 ((string= closing-word "except")
2373 (when (member (current-word) '("try"))
2375 ((string= closing-word "finally")
2376 (when (member (current-word) '("except" "else"))
2377 (point-marker))))))))
2379 (defun python-info-line-ends-backslash-p ()
2380 "Return non-nil if current line ends with backslash."
2381 (string= (or (ignore-errors
2384 (- (line-end-position) 1))) "") "\\"))
2386 (defun python-info-continuation-line-p ()
2387 "Return non-nil if current line is continuation of another."
2388 (let ((current-ppss-context-type (python-info-ppss-context-type)))
2390 (equal (save-excursion
2391 (goto-char (line-end-position))
2392 (forward-comment 9999)
2393 (python-info-ppss-context-type))
2394 current-ppss-context-type)
2395 (or (python-info-line-ends-backslash-p)
2396 (string-match ",[[:space:]]*$" (buffer-substring
2397 (line-beginning-position)
2398 (line-end-position)))
2400 (let ((innermost-paren (progn
2401 (goto-char (line-end-position))
2402 (python-info-ppss-context 'paren))))
2403 (when (and innermost-paren
2404 (and (<= (line-beginning-position) innermost-paren)
2405 (>= (line-end-position) innermost-paren)))
2406 (goto-char innermost-paren)
2407 (looking-at (python-rx open-paren (* space) line-end)))))
2409 (back-to-indentation)
2410 (python-info-ppss-context 'paren))))))
2412 (defun python-info-block-continuation-line-p ()
2413 "Return non-nil if current line is a continuation of a block."
2415 (while (and (not (bobp))
2416 (python-info-continuation-line-p))
2419 (back-to-indentation)
2420 (when (looking-at (python-rx block-start))
2423 (defun python-info-assignment-continuation-line-p ()
2424 "Return non-nil if current line is a continuation of an assignment."
2426 (while (and (not (bobp))
2427 (python-info-continuation-line-p))
2430 (back-to-indentation)
2431 (when (and (not (looking-at (python-rx block-start)))
2433 (and (re-search-forward (python-rx not-simple-operator
2435 not-simple-operator)
2436 (line-end-position) t)
2437 (not (or (python-info-ppss-context 'string)
2438 (python-info-ppss-context 'paren)
2439 (python-info-ppss-context 'comment))))))
2442 (defun python-info-ppss-context (type &optional syntax-ppss)
2443 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2444 TYPE can be 'comment, 'string or 'paren. It returns the start
2445 character address of the specified TYPE."
2446 (let ((ppss (or syntax-ppss (syntax-ppss))))
2457 (defun python-info-ppss-context-type (&optional syntax-ppss)
2458 "Return the context type using SYNTAX-PPSS.
2459 The type returned can be 'comment, 'string or 'paren."
2460 (let ((ppss (or syntax-ppss (syntax-ppss))))
2472 ;;; Utility functions
2475 (defun python-util-merge (type list1 list2 pred)
2476 "Destructively merge lists to produce a new one.
2477 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2478 are the list to be merged. Ordering of the elements is preserved
2479 according to PRED, a `less-than' predicate on the elements."
2481 (while (and list1 list2)
2482 (if (funcall pred (car list2) (car list1))
2483 (push (pop list2) res)
2484 (push (pop list1) res)))
2485 (nconc (nreverse res) list1 list2)))
2487 (defun python-util-position (item seq)
2488 "Find the first occurrence of ITEM in SEQ.
2489 Return the index of the matching item, or nil if not found."
2490 (let ((member-result (member item seq)))
2492 (- (length seq) (length member-result)))))
2494 ;; Stolen from org-mode
2495 (defun python-util-clone-local-variables (from-buffer &optional regexp)
2496 "Clone local variables from FROM-BUFFER.
2497 Optional argument REGEXP selects variables to clone and defaults
2501 (and (symbolp (car pair))
2502 (string-match (or regexp "^python-")
2503 (symbol-name (car pair)))
2504 (set (make-local-variable (car pair))
2506 (buffer-local-variables from-buffer)))
2510 (define-derived-mode python-mode fundamental-mode "Python"
2511 "Major mode for editing Python files.
2514 Entry to this mode calls the value of `python-mode-hook'
2515 if that value is non-nil."
2516 (set (make-local-variable 'tab-width) 8)
2517 (set (make-local-variable 'indent-tabs-mode) nil)
2519 (set (make-local-variable 'comment-start) "# ")
2520 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2522 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2523 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2525 (set (make-local-variable 'font-lock-defaults)
2526 '(python-font-lock-keywords
2528 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2530 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2531 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2533 (set (make-local-variable 'paragraph-start) "\\s-*$")
2534 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2536 (set (make-local-variable 'beginning-of-defun-function)
2537 #'python-beginning-of-defun-function)
2538 (set (make-local-variable 'end-of-defun-function)
2539 #'python-end-of-defun-function)
2541 (add-hook 'completion-at-point-functions
2542 'python-completion-complete-at-point nil 'local)
2544 (setq imenu-create-index-function #'python-imenu-create-index)
2546 (set (make-local-variable 'add-log-current-defun-function)
2547 #'python-info-current-defun)
2549 (set (make-local-variable 'skeleton-further-elements)
2551 (< '(backward-delete-char-untabify (min python-indent-offset
2553 (^ '(- (1+ (current-indentation))))))
2555 (set (make-local-variable 'eldoc-documentation-function)
2556 #'python-eldoc-function)
2558 (add-to-list 'hs-special-modes-alist
2559 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2561 (python-end-of-defun-function)) nil))
2563 (set (make-local-variable 'mode-require-final-newline) t)
2565 (set (make-local-variable 'outline-regexp)
2566 (python-rx (* space) block-start))
2567 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2568 (set (make-local-variable 'outline-level)
2570 "`outline-level' function for Python mode."
2571 (1+ (/ (current-indentation) python-indent-offset))))
2573 (python-skeleton-add-menu-items)
2575 (when python-indent-guess-indent-offset
2576 (python-indent-guess-indent-offset)))
2580 ;;; python.el ends here