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(get_ipython().Completer.all_completions('''%s'''))\n")
82 ;; For iPython 0.10 everything would be the same except for
83 ;; `python-shell-completion-string-code':
85 ;; (setq python-shell-completion-string-code
86 ;; "';'.join(__IP.complete('''%s'''))\n")
88 ;; Please note that the default completion system depends on the
89 ;; readline module, so if you are using some Operating System that
90 ;; bundles Python without it (like Windows) just install the
91 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
92 ;; you should be good to go.
94 ;; Shell virtualenv support: The shell also contains support for
95 ;; virtualenvs and other special environment modifications thanks to
96 ;; `python-shell-process-environment' and `python-shell-exec-path'.
97 ;; These two variables allows you to modify execution paths and
98 ;; environment variables to make easy for you to setup virtualenv rules
99 ;; or behavior modifications when running shells. Here is an example
100 ;; of how to make shell processes to be run using the /path/to/env/
103 ;; (setq python-shell-process-environment
105 ;; (format "PATH=%s" (mapconcat
108 ;; (cons (getenv "PATH")
109 ;; '("/path/to/env/bin/")))
111 ;; "VIRTUAL_ENV=/path/to/env/"))
112 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
114 ;; Since the above is cumbersome and can be programatically
115 ;; calculated, the variable `python-shell-virtualenv-path' is
116 ;; provided. When this variable is set with the path of the
117 ;; virtualenv to use, `process-environment' and `exec-path' get proper
118 ;; values in order to run shells inside the specified virtualenv. So
119 ;; the following will achieve the same as the previous example:
121 ;; (setq python-shell-virtualenv-path "/path/to/env/")
123 ;; Pdb tracking: when you execute a block of code that contains some
124 ;; call to pdb (or ipdb) it will prompt the block of code and will
125 ;; follow the execution of pdb marking the current line with an arrow.
127 ;; Symbol completion: you can complete the symbol at point. It uses
128 ;; the shell completion in background so you should run
129 ;; `python-shell-send-buffer' from time to time to get better results.
131 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
132 ;; def, for, if, try and while. These skeletons are integrated with
133 ;; dabbrev. If you have `dabbrev-mode' activated and
134 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
135 ;; the name of any of those defined and hit SPC, they will be
136 ;; automatically expanded.
138 ;; FFAP: You can find the filename for a given module when using ffap
139 ;; out of the box. This feature needs an inferior python shell
142 ;; Code check: Check the current file for errors with `python-check'
143 ;; using the program defined in `python-check-command'.
145 ;; Eldoc: returns documentation for object at point by using the
146 ;; inferior python subprocess to inspect its documentation. As you
147 ;; might guessed you should run `python-shell-send-buffer' from time
148 ;; to time to get better results too.
150 ;; imenu: This mode supports imenu. It builds a plain or tree menu
151 ;; depending on the value of `python-imenu-make-tree'. Also you can
152 ;; customize if menu items should include its type using
153 ;; `python-imenu-include-defun-type'.
155 ;; If you used python-mode.el you probably will miss auto-indentation
156 ;; when inserting newlines. To achieve the same behavior you have
159 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
161 ;; 2) Add the following hook in your .emacs:
163 ;; (add-hook 'python-mode-hook
165 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
167 ;; I'd recommend the first one since you'll get the same behavior for
168 ;; all modes out-of-the-box.
172 ;; Add this to your .emacs:
174 ;; (add-to-list 'load-path "/folder/containing/file")
181 (require 'ansi-color)
186 ;; Avoid compiler warnings
187 (defvar view-return-to-alist)
188 (defvar compilation-error-regexp-alist)
189 (defvar outline-heading-end-regexp))
191 (autoload 'comint-mode "comint")
194 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
196 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
199 "Python Language's flying circus support for Emacs."
202 :link '(emacs-commentary-link "python"))
207 (defvar python-mode-map
208 (let ((map (make-sparse-keymap)))
210 (substitute-key-definition 'backward-sentence
211 'python-nav-backward-sentence
213 (substitute-key-definition 'forward-sentence
214 'python-nav-forward-sentence
217 (define-key map "\177" 'python-indent-dedent-line-backspace)
218 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
219 (define-key map "\C-c<" 'python-indent-shift-left)
220 (define-key map "\C-c>" 'python-indent-shift-right)
221 (define-key map ":" 'python-indent-electric-colon)
223 (define-key map "\C-c\C-tc" 'python-skeleton-class)
224 (define-key map "\C-c\C-td" 'python-skeleton-def)
225 (define-key map "\C-c\C-tf" 'python-skeleton-for)
226 (define-key map "\C-c\C-ti" 'python-skeleton-if)
227 (define-key map "\C-c\C-tt" 'python-skeleton-try)
228 (define-key map "\C-c\C-tw" 'python-skeleton-while)
230 (define-key map "\C-c\C-s" 'python-shell-send-string)
231 (define-key map "\C-c\C-r" 'python-shell-send-region)
232 (define-key map "\C-\M-x" 'python-shell-send-defun)
233 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
234 (define-key map "\C-c\C-l" 'python-shell-send-file)
235 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
236 ;; Some util commands
237 (define-key map "\C-c\C-v" 'python-check)
238 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
240 (substitute-key-definition 'complete-symbol 'completion-at-point
242 (easy-menu-define python-menu map "Python Mode menu"
244 :help "Python-specific Features"
245 ["Shift region left" python-indent-shift-left :active mark-active
246 :help "Shift region left by a single indentation step"]
247 ["Shift region right" python-indent-shift-right :active mark-active
248 :help "Shift region right by a single indentation step"]
250 ["Mark def/class" mark-defun
251 :help "Mark outermost definition around point"]
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"]
260 ["Start interpreter" run-python
261 :help "Run inferior Python process in a separate buffer"]
262 ["Switch to shell" python-shell-switch-to-shell
263 :help "Switch to running inferior Python process"]
264 ["Eval string" python-shell-send-string
265 :help "Eval string in inferior Python session"]
266 ["Eval buffer" python-shell-send-buffer
267 :help "Eval buffer in inferior Python session"]
268 ["Eval region" python-shell-send-region
269 :help "Eval region in inferior Python session"]
270 ["Eval defun" python-shell-send-defun
271 :help "Eval defun in inferior Python session"]
272 ["Eval file" python-shell-send-file
273 :help "Eval file in inferior Python session"]
274 ["Debugger" pdb :help "Run pdb under GUD"]
276 ["Check file" python-check
277 :help "Check file for errors"]
278 ["Help on symbol" python-eldoc-at-point
279 :help "Get help on symbol at point"]
280 ["Complete symbol" completion-at-point
281 :help "Complete symbol before point"]))
283 "Keymap for `python-mode'.")
286 ;;; Python specialized rx
289 (defconst python-rx-constituents
291 `(block-start . ,(rx symbol-start
292 (or "def" "class" "if" "elif" "else" "try"
293 "except" "finally" "for" "while" "with")
295 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
297 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
298 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
299 `(open-paren . ,(rx (or "{" "[" "(")))
300 `(close-paren . ,(rx (or "}" "]" ")")))
301 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
302 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
303 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
304 "=" "%" "**" "//" "<<" ">>" "<=" "!="
305 "==" ">=" "is" "not")))
306 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
307 ">>=" "<<=" "&=" "^=" "|="))))
308 "Additional Python specific sexps for `python-rx'"))
310 (defmacro python-rx (&rest regexps)
311 "Python mode specialized rx macro which supports common python named REGEXPS."
312 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
313 (cond ((null regexps)
316 (rx-to-string `(and ,@regexps) t))
318 (rx-to-string (car regexps) t)))))
321 ;;; Font-lock and syntax
323 (defvar python-font-lock-keywords
326 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
327 "assert" "else" "if" "pass" "yield" "break" "except" "import"
328 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
329 "return" "def" "for" "lambda" "try" "self")
332 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
333 (1 font-lock-function-name-face))
335 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
336 (1 font-lock-type-face))
339 ;; copyright, license, credits, quit, exit are added by the
340 ;; site module and since they are not intended to be used in
341 ;; programs they are not added here either.
342 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
343 symbol-end) . font-lock-constant-face)
345 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
346 (0+ "." (1+ (or word ?_)))))
347 (1 font-lock-type-face))
348 ;; Builtin Exceptions
350 (or "ArithmeticError" "AssertionError" "AttributeError"
351 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
352 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
353 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
354 "ImportWarning" "IndentationError" "IndexError" "KeyError"
355 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
356 "NotImplementedError" "OSError" "OverflowError"
357 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
358 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
359 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
360 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
361 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
362 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
363 symbol-end) . font-lock-type-face)
366 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
367 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
368 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
369 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
370 "execfile" "file" "filter" "float" "format" "frozenset"
371 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
372 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
373 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
374 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
375 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
376 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
377 "unichr" "unicode" "vars" "xrange" "zip")
378 symbol-end) . font-lock-builtin-face)
380 ;; support for a = b = c = 5
382 (let ((re (python-rx (group (+ (any word ?. ?_)))
383 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
384 assignment-operator)))
385 (when (re-search-forward re limit t)
386 (while (and (python-info-ppss-context 'paren)
387 (re-search-forward re limit t)))
388 (if (and (not (python-info-ppss-context 'paren))
389 (not (equal (char-after (point-marker)) ?=)))
391 (set-match-data nil)))))
392 (1 font-lock-variable-name-face nil nil))
393 ;; support for a, b, c = (1, 2, 3)
395 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
396 (* ?, (* space) (+ (any word ?. ?_)) (* space))
397 ?, (* space) (+ (any word ?. ?_)) (* space)
398 assignment-operator)))
399 (when (and (re-search-forward re limit t)
400 (goto-char (nth 3 (match-data))))
401 (while (and (python-info-ppss-context 'paren)
402 (re-search-forward re limit t))
403 (goto-char (nth 3 (match-data))))
404 (if (not (python-info-ppss-context 'paren))
406 (set-match-data nil)))))
407 (1 font-lock-variable-name-face nil nil))))
409 (defconst python-font-lock-syntactic-keywords
410 ;; Make outer chars of matching triple-quote sequences into generic
411 ;; string delimiters. Fixme: Is there a better way?
412 ;; First avoid a sequence preceded by an odd number of backslashes.
413 `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
414 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
415 (3 (python-quote-syntax)))))
417 (defun python-quote-syntax ()
418 "Put `syntax-table' property correctly on triple quote.
419 Used for syntactic keywords. N is the match number (1, 2 or 3)."
420 ;; Given a triple quote, we have to check the context to know
421 ;; whether this is an opening or closing triple or whether it's
422 ;; quoted anyhow, and should be ignored. (For that we need to do
423 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
424 ;; to use it here despite initial worries.) We also have to sort
425 ;; out a possible prefix -- well, we don't _have_ to, but I think it
426 ;; should be treated as part of the string.
429 ;; ur"""ar""" x='"' # """
432 ;; x '"""' x """ \"""" x
434 (goto-char (match-beginning 0))
435 (let ((syntax (save-match-data (syntax-ppss))))
437 ((eq t (nth 3 syntax)) ; after unclosed fence
438 ;; Consider property for the last char if in a fenced string.
439 (goto-char (nth 8 syntax)) ; fence position
440 (skip-chars-forward "uUrR") ; skip any prefix
441 ;; Is it a matching sequence?
442 (if (eq (char-after) (char-after (match-beginning 2)))
443 (put-text-property (match-beginning 3) (match-end 3)
444 'syntax-table (string-to-syntax "|"))))
446 ;; Consider property for initial char, accounting for prefixes.
447 (put-text-property (match-beginning 1) (match-end 1)
448 'syntax-table (string-to-syntax "|")))
450 ;; Consider property for initial char, accounting for prefixes.
451 (put-text-property (match-beginning 2) (match-end 2)
452 'syntax-table (string-to-syntax "|"))))
455 (defvar python-mode-syntax-table
456 (let ((table (make-syntax-table)))
457 ;; Give punctuation syntax to ASCII that normally has symbol
458 ;; syntax or has word syntax and isn't a letter.
459 (let ((symbol (string-to-syntax "_"))
460 (sst (standard-syntax-table)))
463 (if (equal symbol (aref sst i))
464 (modify-syntax-entry i "." table)))))
465 (modify-syntax-entry ?$ "." table)
466 (modify-syntax-entry ?% "." table)
468 (modify-syntax-entry ?# "<" table)
469 (modify-syntax-entry ?\n ">" table)
470 (modify-syntax-entry ?' "\"" table)
471 (modify-syntax-entry ?` "$" table)
473 "Syntax table for Python files.")
475 (defvar python-dotty-syntax-table
476 (let ((table (make-syntax-table python-mode-syntax-table)))
477 (modify-syntax-entry ?. "w" table)
478 (modify-syntax-entry ?_ "w" table)
480 "Dotty syntax table for Python files.
481 It makes underscores and dots word constituent chars.")
486 (defcustom python-indent-offset 4
487 "Default indentation offset for Python."
492 (defcustom python-indent-guess-indent-offset t
493 "Non-nil tells Python mode to guess `python-indent-offset' value."
498 (defvar python-indent-current-level 0
499 "Current indentation level `python-indent-line-function' is using.")
501 (defvar python-indent-levels '(0)
502 "Levels of indentation available for `python-indent-line-function'.")
504 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
505 "List of words that should be dedented.
506 These make `python-indent-calculate-indentation' subtract the value of
507 `python-indent-offset'.")
509 (defun python-indent-guess-indent-offset ()
510 "Guess and set `python-indent-offset' for the current buffer."
514 (goto-char (point-min))
516 (while (and (not found-block)
518 (python-rx line-start block-start) nil t))
519 (when (and (not (python-info-ppss-context 'string))
520 (not (python-info-ppss-context 'comment))
522 (goto-char (line-end-position))
523 (forward-comment -9999)
524 (eq ?: (char-before))))
525 (setq found-block t)))
526 (if (not found-block)
527 (message "Can't guess python-indent-offset, using defaults: %s"
528 python-indent-offset)
530 (goto-char (line-end-position))
531 (python-info-continuation-line-p))
535 (forward-comment 9999)
536 (let ((indent-offset (current-indentation)))
537 (when (> indent-offset 0)
538 (setq python-indent-offset indent-offset))))))))
540 (defun python-indent-context ()
541 "Get information on indentation context.
542 Context information is returned with a cons with the form:
545 Where status can be any of the following symbols:
546 * inside-paren: If point in between (), {} or []
547 * inside-string: If point is inside a string
548 * after-backslash: Previous line ends in a backslash
549 * after-beginning-of-block: Point is after beginning of block
550 * after-line: Point is after normal line
551 * no-indent: Point is at beginning of buffer or other special case
552 START is the buffer position where the sexp starts."
555 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
559 ;; Beginning of buffer
561 (goto-char (line-beginning-position))
565 ((setq start (python-info-ppss-context 'paren ppss))
568 ((setq start (python-info-ppss-context 'string ppss))
571 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
572 (python-info-ppss-context 'comment ppss)))
573 (let ((line-beg-pos (line-beginning-position)))
574 (when (eq ?\\ (char-before (1- line-beg-pos)))
575 (- line-beg-pos 2)))))
577 ;; After beginning of block
578 ((setq start (save-excursion
579 (let ((block-regexp (python-rx block-start))
580 (block-start-line-end ":[[:space:]]*$"))
581 (back-to-indentation)
582 (forward-comment -9999)
583 (back-to-indentation)
584 (when (or (python-info-continuation-line-p)
585 (and (not (looking-at block-regexp))
589 (line-end-position) t))))
590 (while (and (forward-line -1)
591 (python-info-continuation-line-p)
593 (back-to-indentation)
594 (when (not (looking-at block-regexp))
596 (back-to-indentation)
597 (when (and (looking-at block-regexp)
598 (or (re-search-forward
600 (line-end-position) t)
602 (goto-char (line-end-position))
603 (python-info-continuation-line-p))))
605 'after-beginning-of-block)
607 ((setq start (save-excursion
608 (back-to-indentation)
609 (forward-comment -9999)
610 (python-nav-sentence-start)
617 (defun python-indent-calculate-indentation ()
618 "Calculate correct indentation offset for the current line."
619 (let* ((indentation-context (python-indent-context))
620 (context-status (car indentation-context))
621 (context-start (cdr indentation-context)))
627 ('after-beginning-of-block
628 (goto-char context-start)
629 (+ (current-indentation) python-indent-offset))
633 (goto-char context-start)
634 (current-indentation))
636 (back-to-indentation)
637 (looking-at (regexp-opt python-indent-dedenters)))
641 (goto-char context-start)
642 (current-indentation))
644 (let* ((block-continuation
647 (python-info-block-continuation-line-p)))
648 (assignment-continuation
651 (python-info-assignment-continuation-line-p)))
654 (back-to-indentation)
655 (when (looking-at "\\.")
657 (goto-char (line-end-position))
658 (while (and (re-search-backward "\\." (line-beginning-position) t)
659 (or (python-info-ppss-context 'comment)
660 (python-info-ppss-context 'string)
661 (python-info-ppss-context 'paren))))
662 (if (and (looking-at "\\.")
663 (not (or (python-info-ppss-context 'comment)
664 (python-info-ppss-context 'string)
665 (python-info-ppss-context 'paren))))
667 (+ (current-indentation) python-indent-offset)))))
672 (goto-char block-continuation)
674 (python-rx block-start (* space))
675 (line-end-position) t)
677 (assignment-continuation
678 (goto-char assignment-continuation)
680 (python-rx simple-operator)
681 (line-end-position) t)
684 (python-rx (* space))
685 (line-end-position) t)
688 (goto-char context-start)
691 (back-to-indentation)
693 "\\(?:return\\|from\\|import\\)\s+")))
694 (current-indentation)
695 (+ (current-indentation)
697 (match-string-no-properties 0))))))))
701 (skip-syntax-forward "\s" (line-end-position))
702 (when (and (looking-at (regexp-opt '(")" "]" "}")))
703 (not (forward-char 1))
704 (not (python-info-ppss-context 'paren)))
705 (goto-char context-start)
706 (back-to-indentation)
710 (goto-char context-start)
714 (line-beginning-position)
716 (forward-comment 9999))
718 (+ (current-indentation) python-indent-offset)
719 (forward-comment 9999)
722 (back-to-indentation)
723 (looking-at (regexp-opt '(")" "]" "}"))))
727 (defun python-indent-calculate-levels ()
728 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
729 (let* ((indentation (python-indent-calculate-indentation))
730 (remainder (% indentation python-indent-offset))
731 (steps (/ (- indentation remainder) python-indent-offset)))
732 (setq python-indent-levels (list 0))
733 (dotimes (step steps)
734 (push (* python-indent-offset (1+ step)) python-indent-levels))
735 (when (not (eq 0 remainder))
736 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
737 (setq python-indent-levels (nreverse python-indent-levels))
738 (setq python-indent-current-level (1- (length python-indent-levels)))))
740 (defun python-indent-toggle-levels ()
741 "Toggle `python-indent-current-level' over `python-indent-levels'."
742 (setq python-indent-current-level (1- python-indent-current-level))
743 (when (< python-indent-current-level 0)
744 (setq python-indent-current-level (1- (length python-indent-levels)))))
746 (defun python-indent-line (&optional force-toggle)
747 "Internal implementation of `python-indent-line-function'.
748 Uses the offset calculated in
749 `python-indent-calculate-indentation' and available levels
750 indicated by the variable `python-indent-levels' to set the
753 When the variable `last-command' is equal to
754 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
755 levels indicated in the variable `python-indent-levels' by
756 setting the current level in the variable
757 `python-indent-current-level'.
759 When the variable `last-command' is not equal to
760 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
761 possible indentation levels and saves it in the variable
762 `python-indent-levels'. Afterwards it sets the variable
763 `python-indent-current-level' correctly so offset is equal
764 to (`nth' `python-indent-current-level' `python-indent-levels')"
765 (if (or (and (eq this-command 'indent-for-tab-command)
766 (eq last-command this-command))
768 (if (not (equal python-indent-levels '(0)))
769 (python-indent-toggle-levels)
770 (python-indent-calculate-levels))
771 (python-indent-calculate-levels))
773 (delete-horizontal-space)
774 (indent-to (nth python-indent-current-level python-indent-levels))
777 (let ((closing-block-point (python-info-closing-block)))
778 (when closing-block-point
779 (message "Closes %s" (buffer-substring
782 (goto-char closing-block-point)
783 (line-end-position))))))))
785 (defun python-indent-line-function ()
786 "`indent-line-function' for Python mode.
787 See `python-indent-line' for details."
788 (python-indent-line))
790 (defun python-indent-dedent-line ()
791 "De-indent current line."
793 (when (and (not (or (python-info-ppss-context 'string)
794 (python-info-ppss-context 'comment)))
795 (<= (point-marker) (save-excursion
796 (back-to-indentation)
798 (> (current-column) 0))
799 (python-indent-line t)
802 (defun python-indent-dedent-line-backspace (arg)
803 "De-indent current line.
804 Argument ARG is passed to `backward-delete-char-untabify' when
805 point is not in between the indentation."
807 (when (not (python-indent-dedent-line))
808 (backward-delete-char-untabify arg)))
809 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
811 (defun python-indent-region (start end)
812 "Indent a python region automagically.
814 Called from a program, START and END specify the region to indent."
815 (let ((deactivate-mark nil))
818 (setq end (point-marker))
820 (or (bolp) (forward-line 1))
821 (while (< (point) end)
822 (or (and (bolp) (eolp))
825 (back-to-indentation)
826 (setq word (current-word))
830 (delete-horizontal-space)
831 (indent-to (python-indent-calculate-indentation)))))
833 (move-marker end nil))))
835 (defun python-indent-shift-left (start end &optional count)
836 "Shift lines contained in region START END by COUNT columns to the left.
837 COUNT defaults to `python-indent-offset'. If region isn't
838 active, the current line is shifted. The shifted region includes
839 the lines in which START and END lie. An error is signaled if
840 any lines in the region are indented less than COUNT columns."
843 (list (region-beginning) (region-end) current-prefix-arg)
844 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
846 (setq count (prefix-numeric-value count))
847 (setq count python-indent-offset))
849 (let ((deactivate-mark nil))
852 (while (< (point) end)
853 (if (and (< (current-indentation) count)
854 (not (looking-at "[ \t]*$")))
855 (error "Can't shift all lines enough"))
857 (indent-rigidly start end (- count))))))
859 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
861 (defun python-indent-shift-right (start end &optional count)
862 "Shift lines contained in region START END by COUNT columns to the left.
863 COUNT defaults to `python-indent-offset'. If region isn't
864 active, the current line is shifted. The shifted region includes
865 the lines in which START and END lie."
868 (list (region-beginning) (region-end) current-prefix-arg)
869 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
870 (let ((deactivate-mark nil))
872 (setq count (prefix-numeric-value count))
873 (setq count python-indent-offset))
874 (indent-rigidly start end count)))
876 (defun python-indent-electric-colon (arg)
877 "Insert a colon and maybe de-indent the current line.
878 With numeric ARG, just insert that many colons. With
879 \\[universal-argument], just insert a single colon."
881 (self-insert-command (if (not (integerp arg)) 1 arg))
884 (not (equal ?: (char-after (- (point-marker) 2))))
885 (not (or (python-info-ppss-context 'string)
886 (python-info-ppss-context 'comment))))
887 (let ((indentation (current-indentation))
888 (calculated-indentation (python-indent-calculate-indentation)))
889 (when (> indentation calculated-indentation)
891 (indent-line-to calculated-indentation)
892 (when (not (python-info-closing-block))
893 (indent-line-to indentation)))))))
894 (put 'python-indent-electric-colon 'delete-selection t)
899 (defvar python-nav-beginning-of-defun-regexp
900 (python-rx line-start (* space) defun (+ space) (group symbol-name))
901 "Regular expresion matching beginning of class or function.
902 The name of the defun should be grouped so it can be retrieved
903 via `match-string'.")
905 (defun python-nav-beginning-of-defun (&optional nodecorators)
906 "Move point to `beginning-of-defun'.
907 When NODECORATORS is non-nil decorators are not included. This
908 is the main part of`python-beginning-of-defun-function'
909 implementation. Return non-nil if point is moved to the
910 `beginning-of-defun'."
911 (let ((indent-pos (save-excursion
912 (back-to-indentation)
917 (when (not nodecorators)
918 (when (save-excursion
920 (looking-at (python-rx decorator)))
921 (while (and (not (bobp))
923 (looking-at (python-rx decorator))))
924 (when (not (bobp)) (forward-line 1)))))))
925 (if (and (> (point) indent-pos)
927 (goto-char (line-beginning-position))
928 (looking-at python-nav-beginning-of-defun-regexp)))
930 (goto-char (line-beginning-position))
931 (funcall include-decorators)
933 (goto-char (line-beginning-position))
934 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
936 (goto-char (or (python-info-ppss-context 'string) (point)))
937 (funcall include-decorators))
940 (defun python-beginning-of-defun-function (&optional arg nodecorators)
941 "Move point to the beginning of def or class.
942 With positive ARG move that number of functions forward. With
943 negative do the same but backwards. When NODECORATORS is non-nil
944 decorators are not included. Return non-nil if point is moved to the
945 `beginning-of-defun'."
946 (when (or (null arg) (= arg 0)) (setq arg 1))
948 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
950 (dotimes (i (- arg) found)
951 (python-end-of-defun-function)
952 (forward-comment 9999)
953 (goto-char (line-end-position))
956 (python-nav-beginning-of-defun nodecorators)))))))
958 (defun python-end-of-defun-function ()
959 "Move point to the end of def or class.
960 Returns nil if point is not in a def or class."
962 (let ((beg-defun-indent)
963 (decorator-regexp "[[:space:]]*@"))
964 (when (looking-at decorator-regexp)
965 (while (and (not (eobp))
967 (looking-at decorator-regexp))))
968 (when (not (looking-at python-nav-beginning-of-defun-regexp))
969 (python-beginning-of-defun-function))
970 (setq beg-defun-indent (current-indentation))
972 (while (and (forward-line 1)
974 (or (not (current-word))
975 (> (current-indentation) beg-defun-indent))))
976 (forward-comment 9999)
977 (goto-char (line-beginning-position))))
979 (defun python-nav-sentence-start ()
980 "Move to start of current sentence."
982 (while (and (not (back-to-indentation))
987 (python-info-line-ends-backslash-p))
988 (python-info-ppss-context 'string)
989 (python-info-ppss-context 'paren))
990 (forward-line -1)))))
992 (defun python-nav-sentence-end ()
993 "Move to end of current sentence."
995 (while (and (goto-char (line-end-position))
998 (python-info-line-ends-backslash-p)
999 (python-info-ppss-context 'string)
1000 (python-info-ppss-context 'paren))
1001 (forward-line 1)))))
1003 (defun python-nav-backward-sentence (&optional arg)
1004 "Move backward to start of sentence. With ARG, do it arg times.
1005 See `python-nav-forward-sentence' for more information."
1007 (or arg (setq arg 1))
1008 (python-nav-forward-sentence (- arg)))
1010 (defun python-nav-forward-sentence (&optional arg)
1011 "Move forward to next end of sentence. With ARG, repeat.
1012 With negative argument, move backward repeatedly to start of sentence."
1014 (or arg (setq arg 1))
1016 (forward-comment 9999)
1017 (python-nav-sentence-end)
1019 (setq arg (1- arg)))
1021 (python-nav-sentence-end)
1022 (forward-comment -9999)
1023 (python-nav-sentence-start)
1025 (setq arg (1+ arg))))
1028 ;;; Shell integration
1030 (defcustom python-shell-buffer-name "Python"
1031 "Default buffer name for Python interpreter."
1036 (defcustom python-shell-interpreter "python"
1037 "Default Python interpreter for shell."
1042 (defcustom python-shell-internal-buffer-name "Python Internal"
1043 "Default buffer name for the Internal Python interpreter."
1048 (defcustom python-shell-interpreter-args "-i"
1049 "Default arguments for the Python interpreter."
1054 (defcustom python-shell-prompt-regexp ">>> "
1055 "Regular Expression matching top\-level input prompt of python shell.
1056 It should not contain a caret (^) at the beginning."
1061 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1062 "Regular Expression matching block input prompt of python shell.
1063 It should not contain a caret (^) at the beginning."
1068 (defcustom python-shell-prompt-output-regexp ""
1069 "Regular Expression matching output prompt of python shell.
1070 It should not contain a caret (^) at the beginning."
1075 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1076 "Regular Expression matching pdb input prompt of python shell.
1077 It should not contain a caret (^) at the beginning."
1082 (defcustom python-shell-send-setup-max-wait 5
1083 "Seconds to wait for process output before code setup.
1084 If output is received before the especified time then control is
1085 returned in that moment and not after waiting."
1090 (defcustom python-shell-process-environment nil
1091 "List of environment variables for Python shell.
1092 This variable follows the same rules as `process-environment'
1093 since it merges with it before the process creation routines are
1094 called. When this variable is nil, the Python shell is run with
1095 the default `process-environment'."
1096 :type '(repeat string)
1100 (defcustom python-shell-exec-path nil
1101 "List of path to search for binaries.
1102 This variable follows the same rules as `exec-path' since it
1103 merges with it before the process creation routines are called.
1104 When this variable is nil, the Python shell is run with the
1105 default `exec-path'."
1106 :type '(repeat string)
1110 (defcustom python-shell-virtualenv-path nil
1111 "Path to virtualenv root.
1112 This variable, when set to a string, makes the values stored in
1113 `python-shell-process-environment' and `python-shell-exec-path'
1114 to be modified properly so shells are started with the specified
1120 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1121 python-ffap-setup-code
1122 python-eldoc-setup-code)
1123 "List of code run by `python-shell-send-setup-codes'.
1124 Each variable can contain either a simple string with the code to
1125 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1126 is a string with the code to execute and DESCRIPTION is the
1128 :type '(repeat symbol)
1132 (defcustom python-shell-compilation-regexp-alist
1133 `((,(rx line-start (1+ (any " \t")) "File \""
1134 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1135 "\", line " (group (1+ digit)))
1137 (,(rx " in file " (group (1+ not-newline)) " on line "
1140 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1141 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1143 "`compilation-error-regexp-alist' for inferior Python."
1144 :type '(alist string)
1147 (defun python-shell-get-process-name (dedicated)
1148 "Calculate the appropiate process name for inferior Python process.
1149 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1150 returns a string with the form
1151 `python-shell-buffer-name'[variable `buffer-file-name'] else
1152 returns the value of `python-shell-buffer-name'. After
1153 calculating the process name adds the buffer name for the process
1154 in the `same-window-buffer-names' list."
1158 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1159 (format "%s" python-shell-buffer-name))))
1160 (add-to-list 'same-window-buffer-names (purecopy
1161 (format "*%s*" process-name)))
1164 (defun python-shell-internal-get-process-name ()
1165 "Calculate the appropiate process name for Internal Python process.
1166 The name is calculated from `python-shell-global-buffer-name' and
1167 a hash of all relevant global shell settings in order to ensure
1168 uniqueness for different types of configurations."
1170 python-shell-internal-buffer-name
1173 (python-shell-parse-command)
1174 (mapconcat #'symbol-value python-shell-setup-codes "")
1175 (mapconcat #'indentity python-shell-process-environment "")
1176 (or python-shell-virtualenv-path "")
1177 (mapconcat #'indentity python-shell-exec-path "")))))
1179 (defun python-shell-parse-command ()
1180 "Calculate the string used to execute the inferior Python process."
1181 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1183 (defun python-shell-calculate-process-environment ()
1184 "Calculate process environment given `python-shell-virtualenv-path'."
1185 (let ((env (python-util-merge 'list python-shell-process-environment
1186 process-environment 'string=))
1187 (virtualenv (if python-shell-virtualenv-path
1188 (directory-file-name python-shell-virtualenv-path)
1190 (if (not virtualenv)
1192 (dolist (envvar env)
1193 (let* ((split (split-string envvar "=" t))
1194 (name (nth 0 split))
1195 (value (nth 1 split)))
1196 (when (not (string= name "PYTHONHOME"))
1197 (when (string= name "PATH")
1198 (setq value (format "%s/bin:%s" virtualenv value)))
1199 (setq env (cons (format "%s=%s" name value) env)))))
1200 (cons (format "VIRTUAL_ENV=%s" virtualenv) env))))
1202 (defun python-shell-calculate-exec-path ()
1203 "Calculate exec path given `python-shell-virtualenv-path'."
1204 (let ((path (python-util-merge 'list python-shell-exec-path
1205 exec-path 'string=)))
1206 (if (not python-shell-virtualenv-path)
1208 (cons (format "%s/bin"
1209 (directory-file-name python-shell-virtualenv-path))
1212 (defun python-comint-output-filter-function (output)
1213 "Hook run after content is put into comint buffer.
1214 OUTPUT is a string with the contents of the buffer."
1215 (ansi-color-filter-apply output))
1217 (defvar inferior-python-mode-current-file nil
1218 "Current file from which a region was sent.")
1219 (make-variable-buffer-local 'inferior-python-mode-current-file)
1221 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1222 "Major mode for Python inferior process.
1223 Runs a Python interpreter as a subprocess of Emacs, with Python
1224 I/O through an Emacs buffer. Variables
1225 `python-shell-interpreter' and `python-shell-interpreter-args'
1226 controls which Python interpreter is run. Variables
1227 `python-shell-prompt-regexp',
1228 `python-shell-prompt-output-regexp',
1229 `python-shell-prompt-block-regexp',
1230 `python-shell-completion-setup-code',
1231 `python-shell-completion-string-code', `python-eldoc-setup-code',
1232 `python-eldoc-string-code', `python-ffap-setup-code' and
1233 `python-ffap-string-code' can customize this mode for different
1234 Python interpreters.
1236 You can also add additional setup code to be run at
1237 initialization of the interpreter via `python-shell-setup-codes'
1240 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1241 (set-syntax-table python-mode-syntax-table)
1242 (setq mode-line-process '(":%s"))
1243 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1244 python-shell-prompt-regexp
1245 python-shell-prompt-block-regexp
1246 python-shell-prompt-pdb-regexp))
1247 (make-local-variable 'comint-output-filter-functions)
1248 (add-hook 'comint-output-filter-functions
1249 'python-comint-output-filter-function)
1250 (add-hook 'comint-output-filter-functions
1251 'python-pdbtrack-comint-output-filter-function)
1252 (set (make-local-variable 'compilation-error-regexp-alist)
1253 python-shell-compilation-regexp-alist)
1254 (define-key inferior-python-mode-map [remap complete-symbol]
1255 'completion-at-point)
1256 (add-hook 'completion-at-point-functions
1257 'python-shell-completion-complete-at-point nil 'local)
1258 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1259 'python-shell-completion-complete-at-point)
1260 (define-key inferior-python-mode-map (kbd "<tab>")
1261 'python-shell-completion-complete-or-indent)
1262 (compilation-shell-minor-mode 1))
1264 (defun python-shell-make-comint (cmd proc-name &optional pop)
1265 "Create a python shell comint buffer.
1266 CMD is the python command to be executed and PROC-NAME is the
1267 process name the comint buffer will get. After the comint buffer
1268 is created the `inferior-python-mode' is activated. If POP is
1269 non-nil the buffer is shown."
1271 (let* ((proc-buffer-name (format "*%s*" proc-name))
1272 (process-environment (python-shell-calculate-process-environment))
1273 (exec-path (python-shell-calculate-exec-path)))
1274 (when (not (comint-check-proc proc-buffer-name))
1275 (let* ((cmdlist (split-string-and-unquote cmd))
1276 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1278 (current-buffer (current-buffer)))
1279 (with-current-buffer buffer
1280 (inferior-python-mode)
1281 (python-util-clone-local-variables current-buffer))))
1283 (pop-to-buffer proc-buffer-name))
1286 (defun run-python (dedicated cmd)
1287 "Run an inferior Python process.
1288 Input and output via buffer named after
1289 `python-shell-buffer-name'. If there is a process already
1290 running in that buffer, just switch to it.
1291 With argument, allows you to define DEDICATED, so a dedicated
1292 process for the current buffer is open, and define CMD so you can
1293 edit the command used to call the interpreter (default is value
1294 of `python-shell-interpreter' and arguments defined in
1295 `python-shell-interpreter-args'). Runs the hook
1296 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1298 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1300 (if current-prefix-arg
1302 (y-or-n-p "Make dedicated process? ")
1303 (read-string "Run Python: " (python-shell-parse-command)))
1304 (list nil (python-shell-parse-command))))
1305 (python-shell-make-comint cmd (python-shell-get-process-name dedicated) t)
1308 (defun run-python-internal ()
1309 "Run an inferior Internal Python process.
1310 Input and output via buffer named after
1311 `python-shell-internal-buffer-name' and what
1312 `python-shell-internal-get-process-name' returns. This new kind
1313 of shell is intended to be used for generic communication related
1314 to defined configurations. The main difference with global or
1315 dedicated shells is that these ones are attached to a
1316 configuration, not a buffer. This means that can be used for
1317 example to retrieve the sys.path and other stuff, without messing
1318 with user shells. Runs the hook
1319 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1320 run). \(Type \\[describe-mode] in the process buffer for a list
1323 (set-process-query-on-exit-flag
1325 (python-shell-make-comint
1326 (python-shell-parse-command)
1327 (python-shell-internal-get-process-name))) nil))
1329 (defun python-shell-get-process ()
1330 "Get inferior Python process for current buffer and return it."
1331 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1332 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1333 (global-proc-name (python-shell-get-process-name nil))
1334 (global-proc-buffer-name (format "*%s*" global-proc-name))
1335 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1336 (global-running (comint-check-proc global-proc-buffer-name)))
1337 ;; Always prefer dedicated
1338 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1339 (and global-running global-proc-buffer-name)))))
1341 (defun python-shell-get-or-create-process ()
1342 "Get or create an inferior Python process for current buffer and return it."
1343 (let* ((old-buffer (current-buffer))
1344 (dedicated-proc-name (python-shell-get-process-name t))
1345 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1346 (global-proc-name (python-shell-get-process-name nil))
1347 (global-proc-buffer-name (format "*%s*" global-proc-name))
1348 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1349 (global-running (comint-check-proc global-proc-buffer-name))
1350 (current-prefix-arg 4))
1351 (when (and (not dedicated-running) (not global-running))
1352 (if (call-interactively 'run-python)
1353 (setq dedicated-running t)
1354 (setq global-running t)))
1355 ;; Always prefer dedicated
1356 (switch-to-buffer old-buffer)
1357 (get-buffer-process (if dedicated-running
1358 dedicated-proc-buffer-name
1359 global-proc-buffer-name))))
1361 (defun python-shell-internal-get-or-create-process ()
1362 "Get or create an inferior Internal Python process."
1363 (let* ((proc-name (python-shell-internal-get-process-name))
1364 (proc-buffer-name (format "*%s*" proc-name)))
1365 (run-python-internal)
1366 (get-buffer-process proc-buffer-name)))
1368 (defun python-shell-send-string (string &optional process msg)
1369 "Send STRING to inferior Python PROCESS.
1370 When MSG is non-nil messages the first line of STRING."
1371 (interactive "sPython command: ")
1372 (let ((process (or process (python-shell-get-or-create-process)))
1373 (lines (split-string string "\n" t)))
1375 (message (format "Sent: %s..." (nth 0 lines))))
1376 (if (> (length lines) 1)
1377 (let* ((temp-file-name (make-temp-file "py"))
1378 (file-name (or (buffer-file-name) temp-file-name)))
1379 (with-temp-file temp-file-name
1381 (delete-trailing-whitespace))
1382 (python-shell-send-file file-name process temp-file-name))
1383 (comint-send-string process string)
1384 (when (or (not (string-match "\n$" string))
1385 (string-match "\n[ \t].*\n?$" string))
1386 (comint-send-string process "\n")))))
1388 (defun python-shell-send-string-no-output (string &optional process msg)
1389 "Send STRING to PROCESS and inhibit output.
1390 When MSG is non-nil messages the first line of STRING. Return
1392 (let* ((output-buffer)
1393 (process (or process (python-shell-get-or-create-process)))
1394 (comint-preoutput-filter-functions
1395 (append comint-preoutput-filter-functions
1396 '(ansi-color-filter-apply
1398 (setq output-buffer (concat output-buffer string))
1400 (python-shell-send-string string process msg)
1401 (accept-process-output process)
1403 (lambda (string) string)
1406 (if (> (length python-shell-prompt-output-regexp) 0)
1407 (format "\n*%s$\\|^%s"
1408 python-shell-prompt-regexp
1409 (or python-shell-prompt-output-regexp ""))
1411 python-shell-prompt-regexp)) t) "\n")))
1413 (defun python-shell-internal-send-string (string)
1414 "Send STRING to the Internal Python interpreter.
1415 Returns the output. See `python-shell-send-string-no-output'."
1416 (python-shell-send-string-no-output
1417 ;; Makes this function compatible with the old
1418 ;; python-send-receive. (At least for CEDET).
1419 (replace-regexp-in-string "_emacs_out +" "" string)
1420 (python-shell-internal-get-or-create-process) nil))
1422 (define-obsolete-function-alias
1423 'python-send-receive 'python-shell-internal-send-string "23.3"
1424 "Send STRING to inferior Python (if any) and return result.
1425 The result is what follows `_emacs_out' in the output.
1426 This is a no-op if `python-check-comint-prompt' returns nil.")
1428 (defun python-shell-send-region (start end)
1429 "Send the region delimited by START and END to inferior Python process."
1431 (let ((deactivate-mark nil))
1432 (python-shell-send-string (buffer-substring start end) nil t)))
1434 (defun python-shell-send-buffer ()
1435 "Send the entire buffer to inferior Python process."
1439 (python-shell-send-region (point-min) (point-max))))
1441 (defun python-shell-send-defun (arg)
1442 "Send the current defun to inferior Python process.
1443 When argument ARG is non-nil sends the innermost defun."
1446 (python-shell-send-region
1448 (or (python-beginning-of-defun-function)
1449 (progn (beginning-of-line) (point-marker))))
1451 (or (python-end-of-defun-function)
1452 (progn (end-of-line) (point-marker)))))))
1454 (defun python-shell-send-file (file-name &optional process temp-file-name)
1455 "Send FILE-NAME to inferior Python PROCESS.
1456 If TEMP-FILE-NAME is passed then that file is used for processing
1457 instead, while internally the shell will continue to use
1459 (interactive "fFile to send: ")
1460 (let* ((process (or process (python-shell-get-or-create-process)))
1461 (temp-file-name (when temp-file-name
1462 (expand-file-name temp-file-name)))
1463 (file-name (or (expand-file-name file-name) temp-file-name)))
1464 (when (not file-name)
1465 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1466 (with-current-buffer (process-buffer process)
1467 (setq inferior-python-mode-current-file
1468 (convert-standard-filename file-name)))
1469 (python-shell-send-string
1471 (concat "__pyfile = open('''%s''');"
1472 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1474 (or temp-file-name file-name) file-name)
1477 (defun python-shell-switch-to-shell ()
1478 "Switch to inferior Python process buffer."
1480 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1482 (defun python-shell-send-setup-code ()
1483 "Send all setup code for shell.
1484 This function takes the list of setup code to send from the
1485 `python-shell-setup-codes' list."
1486 (let ((msg "Sent %s")
1487 (process (get-buffer-process (current-buffer))))
1488 (accept-process-output process python-shell-send-setup-max-wait)
1489 (dolist (code python-shell-setup-codes)
1492 (setq msg (cdr code)))
1493 (message (format msg code))
1494 (python-shell-send-string-no-output
1495 (symbol-value code) process)))))
1497 (add-hook 'inferior-python-mode-hook
1498 #'python-shell-send-setup-code)
1501 ;;; Shell completion
1503 (defcustom python-shell-completion-setup-code
1507 def __COMPLETER_all_completions(text): []
1510 readline.set_completer(rlcompleter.Completer().complete)
1511 def __COMPLETER_all_completions(text):
1517 res = readline.get_completer()(text, i)
1520 completions.append(res)
1524 "Code used to setup completion in inferior Python processes."
1529 (defcustom python-shell-completion-string-code
1530 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1531 "Python code used to get a string of completions separated by semicolons."
1536 (defun python-shell-completion--get-completions (input process)
1537 "Retrieve available completions for INPUT using PROCESS."
1538 (with-current-buffer (process-buffer process)
1539 (let ((completions (python-shell-send-string-no-output
1540 (format python-shell-completion-string-code input)
1542 (when (> (length completions) 2)
1543 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1545 (defun python-shell-completion--get-completion (input completions)
1546 "Get completion for INPUT using COMPLETIONS."
1547 (let ((completion (when completions
1548 (try-completion input completions))))
1549 (cond ((eq completion t)
1552 (message "Can't find completion for \"%s\"" input)
1555 ((not (string= input completion))
1558 (message "Making completion list...")
1559 (with-output-to-temp-buffer "*Python Completions*"
1560 (display-completion-list
1561 (all-completions input completions)))
1564 (defun python-shell-completion-complete-at-point ()
1565 "Perform completion at point in inferior Python process."
1567 (with-syntax-table python-dotty-syntax-table
1568 (when (and comint-last-prompt-overlay
1569 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1570 (let* ((process (get-buffer-process (current-buffer)))
1571 (input (substring-no-properties
1572 (or (comint-word (current-word)) "") nil nil)))
1573 (delete-char (- (length input)))
1575 (python-shell-completion--get-completion
1576 input (python-shell-completion--get-completions input process)))))))
1578 (defun python-shell-completion-complete-or-indent ()
1579 "Complete or indent depending on the context.
1580 If content before pointer is all whitespace indent. If not try
1583 (if (string-match "^[[:space:]]*$"
1584 (buffer-substring (comint-line-beginning-position)
1586 (indent-for-tab-command)
1587 (comint-dynamic-complete)))
1590 ;;; PDB Track integration
1592 (defcustom python-pdbtrack-stacktrace-info-regexp
1593 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1594 "Regular Expression matching stacktrace information.
1595 Used to extract the current line and module being inspected. The
1596 regexp should not start with a caret (^) and can contain a string
1597 placeholder (\%s) which is replaced with the filename beign
1598 inspected (so other files in the debugging process are not
1604 (defvar python-pdbtrack-tracking-buffers '()
1605 "Alist containing elements of form (#<buffer> . #<buffer>).
1606 The car of each element of the alist is the tracking buffer and
1607 the cdr is the tracked buffer.")
1609 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1610 "Get/Add a tracked buffer for the current buffer.
1611 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1612 Returns a cons with the form:
1613 * (#<tracking buffer> . #< tracked buffer>)."
1615 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1616 (let* ((file (with-current-buffer (current-buffer)
1617 inferior-python-mode-current-file))
1619 `(,(current-buffer) .
1620 ,(or (get-file-buffer file)
1621 (find-file-noselect file)))))
1622 (set-buffer (cdr tracking-buffers))
1624 (set-buffer (car tracking-buffers))
1625 (setq python-pdbtrack-tracking-buffers
1626 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1629 (defun python-pdbtrack-comint-output-filter-function (output)
1630 "Move overlay arrow to current pdb line in tracked buffer.
1631 Argument OUTPUT is a string with the output from the comint process."
1632 (when (not (string= output ""))
1633 (let ((full-output (ansi-color-filter-apply
1634 (buffer-substring comint-last-input-end
1636 (if (string-match python-shell-prompt-pdb-regexp full-output)
1637 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1641 (format python-pdbtrack-stacktrace-info-regexp
1643 inferior-python-mode-current-file))
1645 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1646 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1647 (tracked-buffer-line-pos))
1649 (with-current-buffer (cdr tracking-buffers)
1650 (set (make-local-variable 'overlay-arrow-string) "=>")
1651 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1652 (setq tracked-buffer-line-pos (progn
1653 (goto-char (point-min))
1654 (forward-line (1- line-num))
1656 (when tracked-buffer-window
1657 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1658 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1659 (pop-to-buffer (cdr tracking-buffers))
1660 (switch-to-buffer-other-window (car tracking-buffers)))
1661 (let ((tracking-buffers (assq (current-buffer)
1662 python-pdbtrack-tracking-buffers)))
1663 (when tracking-buffers
1664 (if inferior-python-mode-current-file
1665 (with-current-buffer (cdr tracking-buffers)
1666 (set-marker overlay-arrow-position nil))
1667 (kill-buffer (cdr tracking-buffers)))
1668 (setq python-pdbtrack-tracking-buffers
1669 (assq-delete-all (current-buffer)
1670 python-pdbtrack-tracking-buffers)))))))
1674 ;;; Symbol completion
1676 (defun python-completion-complete-at-point ()
1677 "Complete current symbol at point.
1678 For this to work the best as possible you should call
1679 `python-shell-send-buffer' from time to time so context in
1680 inferior python process is updated properly."
1682 (let ((process (python-shell-get-process)))
1684 (error "Completion needs an inferior Python process running")
1685 (with-syntax-table python-dotty-syntax-table
1686 (let* ((input (substring-no-properties
1687 (or (comint-word (current-word)) "") nil nil))
1688 (completions (python-shell-completion--get-completions
1690 (delete-char (- (length input)))
1692 (python-shell-completion--get-completion
1693 input completions)))))))
1695 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1700 (defcustom python-fill-comment-function 'python-fill-comment
1701 "Function to fill comments.
1702 This is the function used by `python-fill-paragraph-function' to
1708 (defcustom python-fill-string-function 'python-fill-string
1709 "Function to fill strings.
1710 This is the function used by `python-fill-paragraph-function' to
1716 (defcustom python-fill-decorator-function 'python-fill-decorator
1717 "Function to fill decorators.
1718 This is the function used by `python-fill-paragraph-function' to
1724 (defcustom python-fill-paren-function 'python-fill-paren
1725 "Function to fill parens.
1726 This is the function used by `python-fill-paragraph-function' to
1732 (defun python-fill-paragraph-function (&optional justify)
1733 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1734 If any of the current line is in or at the end of a multi-line string,
1735 fill the string or the paragraph of it that point is in, preserving
1736 the string's indentation.
1737 Optional argument JUSTIFY defines if the paragraph should be justified."
1740 (back-to-indentation)
1743 ((funcall python-fill-comment-function justify))
1744 ;; Strings/Docstrings
1745 ((save-excursion (skip-chars-forward "\"'uUrR")
1746 (python-info-ppss-context 'string))
1747 (funcall python-fill-string-function justify))
1749 ((equal (char-after (save-excursion
1750 (back-to-indentation)
1751 (point-marker))) ?@)
1752 (funcall python-fill-decorator-function justify))
1754 ((or (python-info-ppss-context 'paren)
1755 (looking-at (python-rx open-paren))
1757 (skip-syntax-forward "^(" (line-end-position))
1758 (looking-at (python-rx open-paren))))
1759 (funcall python-fill-paren-function justify))
1762 (defun python-fill-comment (&optional justify)
1763 "Comment fill function for `python-fill-paragraph-function'.
1764 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1765 (fill-comment-paragraph justify))
1767 (defun python-fill-string (&optional justify)
1768 "String fill function for `python-fill-paragraph-function'.
1769 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1770 (let ((marker (point-marker))
1771 (string-start-marker
1773 (skip-chars-forward "\"'uUrR")
1774 (goto-char (python-info-ppss-context 'string))
1775 (skip-chars-forward "\"'uUrR")
1777 (reg-start (line-beginning-position))
1780 (while (python-info-ppss-context 'string)
1781 (goto-char (1+ (point-marker))))
1782 (skip-chars-backward "\"'")
1784 (reg-end (line-end-position))
1785 (fill-paragraph-function))
1787 (narrow-to-region reg-start reg-end)
1789 (goto-char string-start-marker)
1790 (delete-region (point-marker) (progn
1791 (skip-syntax-forward "> ")
1793 (goto-char string-end-marker)
1794 (delete-region (point-marker) (progn
1795 (skip-syntax-backward "> ")
1799 (fill-paragraph justify))
1800 ;; If there is a newline in the docstring lets put triple
1801 ;; quote in it's own line to follow pep 8
1802 (when (save-excursion
1803 (re-search-backward "\n" string-start-marker t))
1805 (newline-and-indent))
1806 (fill-paragraph justify)))) t)
1808 (defun python-fill-decorator (&optional justify)
1809 "Decorator fill function for `python-fill-paragraph-function'.
1810 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1813 (defun python-fill-paren (&optional justify)
1814 "Paren fill function for `python-fill-paragraph-function'.
1815 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1817 (narrow-to-region (progn
1818 (while (python-info-ppss-context 'paren)
1819 (goto-char (1- (point-marker))))
1821 (line-beginning-position))
1823 (when (not (python-info-ppss-context 'paren))
1825 (when (not (python-info-ppss-context 'paren))
1826 (skip-syntax-backward "^)")))
1827 (while (python-info-ppss-context 'paren)
1828 (goto-char (1+ (point-marker))))
1830 (let ((paragraph-start "\f\\|[ \t]*$")
1831 (paragraph-separate ",")
1832 (fill-paragraph-function))
1833 (goto-char (point-min))
1834 (fill-paragraph justify))
1837 (python-indent-line)
1838 (goto-char (line-end-position)))) t)
1843 (defcustom python-skeleton-autoinsert nil
1844 "Non-nil means template skeletons will be automagically inserted.
1845 This happens when pressing \"if<SPACE>\", for example, to prompt for
1851 (defvar python-skeleton-available '()
1852 "Internal list of available skeletons.")
1854 (define-abbrev-table 'python-mode-abbrev-table ()
1855 "Abbrev table for Python mode."
1857 ;; Allow / inside abbrevs.
1858 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1859 ;; Only expand in code.
1860 :enable-function (lambda ()
1862 (not (or (python-info-ppss-context 'string)
1863 (python-info-ppss-context 'comment)))
1864 python-skeleton-autoinsert)))
1866 (defmacro python-skeleton-define (name doc &rest skel)
1867 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1868 The skeleton will be bound to python-skeleton-NAME and will
1869 be added to `python-mode-abbrev-table'."
1870 (let* ((name (symbol-name name))
1871 (function-name (intern (concat "python-skeleton-" name))))
1873 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1874 (setq python-skeleton-available
1875 (cons ',function-name python-skeleton-available))
1876 (define-skeleton ,function-name
1878 (format "Insert %s statement." name))
1880 (put 'python-skeleton-define 'lisp-indent-function 2)
1882 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1883 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1884 The skeleton will be bound to python-skeleton-NAME."
1885 (let* ((name (symbol-name name))
1886 (function-name (intern (concat "python-skeleton--" name)))
1888 "Add '%s' clause? " name)))
1891 `(< ,(format "%s:" name) \n \n
1893 `(define-skeleton ,function-name
1895 (format "Auxiliary skeleton for %s statement." name))
1897 (unless (y-or-n-p ,msg)
1900 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1902 (python-define-auxiliary-skeleton else nil)
1904 (python-define-auxiliary-skeleton except nil)
1906 (python-define-auxiliary-skeleton finally nil)
1908 (python-skeleton-define if nil
1912 ("other condition, %s: "
1916 '(python-skeleton--else) | ^)
1918 (python-skeleton-define while nil
1922 '(python-skeleton--else) | ^)
1924 (python-skeleton-define for nil
1928 '(python-skeleton--else) | ^)
1930 (python-skeleton-define try nil
1936 "except " str ":" \n
1939 '(python-skeleton--except)
1940 '(python-skeleton--else)
1941 '(python-skeleton--finally) | ^)
1943 (python-skeleton-define def nil
1945 "def " str " (" ("Parameter, %s: "
1946 (unless (equal ?\( (char-before)) ", ")
1948 "\"\"\"" - "\"\"\"" \n
1951 (python-skeleton-define class nil
1953 "class " str " (" ("Inheritance, %s: "
1954 (unless (equal ?\( (char-before)) ", ")
1958 "\"\"\"" - "\"\"\"" \n
1961 (defun python-skeleton-add-menu-items ()
1962 "Add menu items to Python->Skeletons menu."
1963 (let ((skeletons (sort python-skeleton-available 'string<))
1965 (dolist (skeleton skeletons)
1967 nil '("Python" "Skeletons")
1969 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1974 (defcustom python-ffap-setup-code
1975 "def __FFAP_get_module_path(module):
1978 path = __import__(module).__file__
1979 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1984 "Python code to get a module path."
1989 (defcustom python-ffap-string-code
1990 "__FFAP_get_module_path('''%s''')\n"
1991 "Python code used to get a string with the path of a module."
1996 (defun python-ffap-module-path (module)
1997 "Function for `ffap-alist' to return path for MODULE."
1999 (and (eq major-mode 'inferior-python-mode)
2000 (get-buffer-process (current-buffer)))
2001 (python-shell-get-process))))
2005 (python-shell-send-string-no-output
2006 (format python-ffap-string-code module) process)))
2008 (substring-no-properties module-file 1 -1))))))
2010 (eval-after-load "ffap"
2012 (push '(python-mode . python-ffap-module-path) ffap-alist)
2013 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2018 (defcustom python-check-command
2019 "pychecker --stdlib"
2020 "Command used to check a Python file."
2025 (defvar python-check-custom-command nil
2028 (defun python-check (command)
2029 "Check a Python file (default current buffer's file).
2030 Runs COMMAND, a shell command, as if by `compile'. See
2031 `python-check-command' for the default."
2033 (list (read-string "Check command: "
2034 (or python-check-custom-command
2035 (concat python-check-command " "
2036 (shell-quote-argument
2038 (let ((name (buffer-file-name)))
2040 (file-name-nondirectory name)))
2042 (setq python-check-custom-command command)
2043 (save-some-buffers (not compilation-ask-about-save) nil)
2044 (compilation-start command))
2049 (defcustom python-eldoc-setup-code
2050 "def __PYDOC_get_help(obj):
2053 if hasattr(obj, 'startswith'):
2054 obj = eval(obj, globals())
2055 doc = inspect.getdoc(obj)
2056 if not doc and callable(obj):
2058 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2059 target = obj.__init__
2065 args = inspect.formatargspec(
2066 *inspect.getargspec(target)
2069 doc = '{objtype} {name}{args}'.format(
2070 objtype=objtype, name=name, args=args
2073 doc = doc.splitlines()[0]
2080 "Python code to setup documentation retrieval."
2085 (defcustom python-eldoc-string-code
2086 "__PYDOC_get_help('''%s''')\n"
2087 "Python code used to get a string with the documentation of an object."
2092 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2093 "Internal implementation to get documentation at point.
2094 If not FORCE-INPUT is passed then what `current-word' returns
2095 will be used. If not FORCE-PROCESS is passed what
2096 `python-shell-get-process' returns is used."
2097 (let ((process (or force-process (python-shell-get-process))))
2099 "Eldoc needs an inferior Python process running."
2100 (let* ((current-defun (python-info-current-defun))
2101 (input (or force-input
2102 (with-syntax-table python-dotty-syntax-table
2103 (if (not current-defun)
2105 (concat current-defun "." (current-word))))))
2106 (ppss (syntax-ppss))
2107 (help (when (and input
2108 (not (string= input (concat current-defun ".")))
2109 (not (or (python-info-ppss-context 'string ppss)
2110 (python-info-ppss-context 'comment ppss))))
2111 (when (string-match (concat
2112 (regexp-quote (concat current-defun "."))
2116 (goto-char (point-min))
2119 (delete-region (point-marker) (search-forward "self."))
2120 (setq input (buffer-substring (point-min) (point-max)))))
2121 (python-shell-send-string-no-output
2122 (format python-eldoc-string-code input) process))))
2123 (with-current-buffer (process-buffer process)
2124 (when comint-last-prompt-overlay
2125 (delete-region comint-last-input-end
2126 (overlay-start comint-last-prompt-overlay))))
2128 (not (string= help "\n")))
2131 (defun python-eldoc-function ()
2132 "`eldoc-documentation-function' for Python.
2133 For this to work the best as possible you should call
2134 `python-shell-send-buffer' from time to time so context in
2135 inferior python process is updated properly."
2136 (python-eldoc--get-doc-at-point))
2138 (defun python-eldoc-at-point (symbol)
2139 "Get help on SYMBOL using `help'.
2140 Interactively, prompt for symbol."
2142 (let ((symbol (with-syntax-table python-dotty-syntax-table
2144 (enable-recursive-minibuffers t))
2145 (list (read-string (if symbol
2146 (format "Describe symbol (default %s): " symbol)
2147 "Describe symbol: ")
2149 (let ((process (python-shell-get-process)))
2151 (message "Eldoc needs an inferior Python process running.")
2152 (message (python-eldoc--get-doc-at-point symbol process)))))
2157 (defcustom python-imenu-include-defun-type t
2158 "Non-nil make imenu items to include its type."
2163 (defcustom python-imenu-make-tree t
2164 "Non-nil make imenu to build a tree menu.
2165 Set to nil for speed."
2170 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2171 "Label displayed to navigate to root from a subtree.
2172 It can contain a \"%s\" which will be replaced with the root name."
2177 (defvar python-imenu-index-alist nil
2178 "Calculated index tree for imenu.")
2180 (defun python-imenu-tree-assoc (keylist tree)
2181 "Using KEYLIST traverse TREE."
2183 (python-imenu-tree-assoc (cdr keylist)
2184 (ignore-errors (assoc (car keylist) tree)))
2187 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2188 "Make a tree from plain alist of module names.
2189 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2190 is the same thing, the difference is that FULL-ELEMENT remains
2191 untouched in all recursive calls.
2192 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2193 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2195 (let* ((subelement-point (cdr (assoc
2196 (mapconcat #'identity full-element ".")
2198 (subelement-name (car element-list))
2199 (subelement-position (python-util-position
2200 subelement-name full-element))
2201 (subelement-path (when subelement-position
2204 (- (length full-element)
2205 subelement-position)))))
2206 (let ((path-ref (python-imenu-tree-assoc subelement-path
2207 python-imenu-index-alist)))
2209 (push (cons subelement-name subelement-point)
2210 python-imenu-index-alist)
2211 (when (not (listp (cdr path-ref)))
2212 ;; Modifiy root cdr to be a list
2214 (list (cons (format python-imenu-subtree-root-label
2217 (mapconcat #'identity
2218 subelement-path ".")
2220 (when (not (assoc subelement-name path-ref))
2221 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2222 (python-imenu-make-element-tree (cdr element-list)
2223 full-element plain-index))))
2225 (defun python-imenu-make-tree (index)
2226 "Build the imenu alist tree from plain INDEX.
2228 The idea of this function is that given the alist:
2231 (\"Test.__init__\" . 200)
2232 (\"Test.some_method\" . 300)
2233 (\"Test.some_method.another\" . 400)
2234 (\"Test.something_else\" . 500)
2236 (\"test.reprint\" . 700)
2237 (\"test.reprint\" . 800))
2239 This tree gets built:
2241 '((\"Test\" . ((\"jump to...\" . 100)
2242 (\"__init__\" . 200)
2243 (\"some_method\" . ((\"jump to...\" . 300)
2244 (\"another\" . 400)))
2245 (\"something_else\" . 500)))
2246 (\"test\" . ((\"jump to...\" . 600)
2248 (\"reprint\" . 800))))
2250 Internally it uses `python-imenu-make-element-tree' to create all
2251 branches for each element."
2252 (setq python-imenu-index-alist nil)
2253 (mapc (lambda (element)
2254 (python-imenu-make-element-tree element element index))
2255 (mapcar (lambda (element)
2256 (split-string (car element) "\\." t)) index))
2257 python-imenu-index-alist)
2259 (defun python-imenu-create-index ()
2260 "`imenu-create-index-function' for Python."
2262 (goto-char (point-max))
2263 (while (python-beginning-of-defun-function 1 t)
2264 (let ((defun-dotted-name
2265 (python-info-current-defun python-imenu-include-defun-type)))
2266 (push (cons defun-dotted-name (point)) index)))
2267 (if python-imenu-make-tree
2268 (python-imenu-make-tree index)
2274 (defun python-info-current-defun (&optional include-type)
2275 "Return name of surrounding function with Python compatible dotty syntax.
2276 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2277 This function is compatible to be used as
2278 `add-log-current-defun-function' since it returns nil if point is
2279 not inside a defun."
2286 (goto-char (line-end-position))
2287 (forward-comment -9999)
2288 (setq min-indent (current-indentation))
2289 (while (python-beginning-of-defun-function 1 t)
2290 (when (or (< (current-indentation) min-indent)
2292 (setq first-run nil)
2293 (setq min-indent (current-indentation))
2294 (looking-at python-nav-beginning-of-defun-regexp)
2296 (if (not include-type)
2297 (match-string-no-properties 1)
2298 (mapconcat 'identity
2300 (match-string-no-properties 0)) " "))
2303 (mapconcat (lambda (string) string) names "."))))
2305 (defun python-info-closing-block ()
2306 "Return the point of the block the current line closes."
2307 (let ((closing-word (save-excursion
2308 (back-to-indentation)
2310 (indentation (current-indentation)))
2311 (when (member closing-word python-indent-dedenters)
2314 (while (and (> (current-indentation) indentation)
2316 (not (back-to-indentation))
2318 (back-to-indentation)
2320 ((not (equal indentation (current-indentation))) nil)
2321 ((string= closing-word "elif")
2322 (when (member (current-word) '("if" "elif"))
2324 ((string= closing-word "else")
2325 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2327 ((string= closing-word "except")
2328 (when (member (current-word) '("try"))
2330 ((string= closing-word "finally")
2331 (when (member (current-word) '("except" "else"))
2332 (point-marker))))))))
2334 (defun python-info-line-ends-backslash-p ()
2335 "Return non-nil if current line ends with backslash."
2336 (string= (or (ignore-errors
2339 (- (line-end-position) 1))) "") "\\"))
2341 (defun python-info-continuation-line-p ()
2342 "Return non-nil if current line is continuation of another."
2343 (let ((current-ppss-context-type (python-info-ppss-context-type)))
2345 (equal (save-excursion
2346 (goto-char (line-end-position))
2347 (forward-comment 9999)
2348 (python-info-ppss-context-type))
2349 current-ppss-context-type)
2350 (or (python-info-line-ends-backslash-p)
2351 (string-match ",[[:space:]]*$" (buffer-substring
2352 (line-beginning-position)
2353 (line-end-position)))
2355 (let ((innermost-paren (progn
2356 (goto-char (line-end-position))
2357 (python-info-ppss-context 'paren))))
2358 (when (and innermost-paren
2359 (and (<= (line-beginning-position) innermost-paren)
2360 (>= (line-end-position) innermost-paren)))
2361 (goto-char innermost-paren)
2362 (looking-at (python-rx open-paren (* space) line-end)))))
2364 (back-to-indentation)
2365 (python-info-ppss-context 'paren))))))
2367 (defun python-info-block-continuation-line-p ()
2368 "Return non-nil if current line is a continuation of a block."
2370 (while (and (not (bobp))
2371 (python-info-continuation-line-p))
2374 (back-to-indentation)
2375 (when (looking-at (python-rx block-start))
2378 (defun python-info-assignment-continuation-line-p ()
2379 "Return non-nil if current line is a continuation of an assignment."
2381 (while (and (not (bobp))
2382 (python-info-continuation-line-p))
2385 (back-to-indentation)
2386 (when (and (not (looking-at (python-rx block-start)))
2388 (and (re-search-forward (python-rx not-simple-operator
2390 not-simple-operator)
2391 (line-end-position) t)
2392 (not (or (python-info-ppss-context 'string)
2393 (python-info-ppss-context 'paren)
2394 (python-info-ppss-context 'comment))))))
2397 (defun python-info-ppss-context (type &optional syntax-ppss)
2398 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2399 TYPE can be 'comment, 'string or 'paren. It returns the start
2400 character address of the specified TYPE."
2401 (let ((ppss (or syntax-ppss (syntax-ppss))))
2412 (defun python-info-ppss-context-type (&optional syntax-ppss)
2413 "Return the context type using SYNTAX-PPSS.
2414 The type returned can be 'comment, 'string or 'paren."
2415 (let ((ppss (or syntax-ppss (syntax-ppss))))
2427 ;;; Utility functions
2430 (defun python-util-merge (type list1 list2 pred)
2431 "Destructively merge lists to produce a new one.
2432 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2433 are the list to be merged. Ordering of the elements is preserved
2434 according to PRED, a `less-than' predicate on the elements."
2436 (while (and list1 list2)
2437 (if (funcall pred (car list2) (car list1))
2438 (push (pop list2) res)
2439 (push (pop list1) res)))
2440 (nconc (nreverse res) list1 list2)))
2442 (defun python-util-position (item seq)
2443 "Find the first occurrence of ITEM in SEQ.
2444 Return the index of the matching item, or nil if not found."
2445 (let ((member-result (member item seq)))
2447 (- (length seq) (length member-result)))))
2449 ;; Stolen from org-mode
2450 (defun python-util-clone-local-variables (from-buffer &optional regexp)
2451 "Clone local variables from FROM-BUFFER.
2452 Optional argument REGEXP selects variables to clone and defaults
2456 (and (symbolp (car pair))
2457 (string-match (or regexp "^python-")
2458 (symbol-name (car pair)))
2459 (set (make-local-variable (car pair))
2461 (buffer-local-variables from-buffer)))
2465 (define-derived-mode python-mode fundamental-mode "Python"
2466 "Major mode for editing Python files.
2469 Entry to this mode calls the value of `python-mode-hook'
2470 if that value is non-nil."
2471 (set (make-local-variable 'tab-width) 8)
2472 (set (make-local-variable 'indent-tabs-mode) nil)
2474 (set (make-local-variable 'comment-start) "# ")
2475 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2477 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2478 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2480 (set (make-local-variable 'font-lock-defaults)
2481 '(python-font-lock-keywords
2483 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2485 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2486 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2488 (set (make-local-variable 'paragraph-start) "\\s-*$")
2489 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2491 (set (make-local-variable 'beginning-of-defun-function)
2492 #'python-beginning-of-defun-function)
2493 (set (make-local-variable 'end-of-defun-function)
2494 #'python-end-of-defun-function)
2496 (add-hook 'completion-at-point-functions
2497 'python-completion-complete-at-point nil 'local)
2499 (setq imenu-create-index-function #'python-imenu-create-index)
2501 (set (make-local-variable 'add-log-current-defun-function)
2502 #'python-info-current-defun)
2504 (set (make-local-variable 'skeleton-further-elements)
2506 (< '(backward-delete-char-untabify (min python-indent-offset
2508 (^ '(- (1+ (current-indentation))))))
2510 (set (make-local-variable 'eldoc-documentation-function)
2511 #'python-eldoc-function)
2513 (add-to-list 'hs-special-modes-alist
2514 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2516 (python-end-of-defun-function)) nil))
2518 (set (make-local-variable 'mode-require-final-newline) t)
2520 (set (make-local-variable 'outline-regexp)
2521 (python-rx (* space) block-start))
2522 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2523 (set (make-local-variable 'outline-level)
2525 "`outline-level' function for Python mode."
2526 (1+ (/ (current-indentation) python-indent-offset))))
2528 (python-skeleton-add-menu-items)
2530 (when python-indent-guess-indent-offset
2531 (python-indent-guess-indent-offset)))
2535 ;;; python.el ends here