In special-display-p signal an error if BUFFER-NAME is not a string (Bug#11713).
[emacs.git] / lisp / progmodes / python.el
blobdfa72a3084a715fbf6f344335c8b2c66dbd7334f
1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
7 ;; Version: 0.24.2
8 ;; Maintainer: FSF
9 ;; Created: Jul 2010
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
27 ;;; Commentary:
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Pdb
35 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
36 ;; imenu.
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements
50 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
51 ;; respectively). Extra functions `python-nav-sentence-start' and
52 ;; `python-nav-sentence-end' are included to move to the beginning and
53 ;; to the end of a sentence while taking care of multiline definitions.
54 ;; `python-nav-jump-to-defun' is provided and allows jumping to a
55 ;; function or class definition quickly in the current buffer.
57 ;; Shell interaction: is provided and allows you to execute easily any
58 ;; block of code of your current buffer in an inferior Python process.
60 ;; Shell completion: hitting tab will try to complete the current
61 ;; word. Shell completion is implemented in a manner that if you
62 ;; change the `python-shell-interpreter' to any other (for example
63 ;; IPython) it should be easy to integrate another way to calculate
64 ;; completions. You just need to specify your custom
65 ;; `python-shell-completion-setup-code' and
66 ;; `python-shell-completion-string-code'.
68 ;; Here is a complete example of the settings you would use for
69 ;; iPython 0.11:
71 ;; (setq
72 ;; python-shell-interpreter "ipython"
73 ;; python-shell-interpreter-args ""
74 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
75 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
76 ;; python-shell-completion-setup-code
77 ;; "from IPython.core.completerlib import module_completion"
78 ;; python-shell-completion-module-string-code
79 ;; "';'.join(module_completion('''%s'''))\n"
80 ;; python-shell-completion-string-code
81 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
83 ;; For iPython 0.10 everything would be the same except for
84 ;; `python-shell-completion-string-code' and
85 ;; `python-shell-completion-module-string-code':
87 ;; (setq python-shell-completion-string-code
88 ;; "';'.join(__IP.complete('''%s'''))\n"
89 ;; python-shell-completion-module-string-code "")
91 ;; Unfortunately running iPython on Windows needs some more tweaking.
92 ;; The way you must set `python-shell-interpreter' and
93 ;; `python-shell-interpreter-args' is as follows:
95 ;; (setq
96 ;; python-shell-interpreter "C:\\Python27\\python.exe"
97 ;; python-shell-interpreter-args
98 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
100 ;; That will spawn the iPython process correctly (Of course you need
101 ;; to modify the paths according to your system).
103 ;; Please note that the default completion system depends on the
104 ;; readline module, so if you are using some Operating System that
105 ;; bundles Python without it (like Windows) just install the
106 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
107 ;; you should be good to go.
109 ;; Shell virtualenv support: The shell also contains support for
110 ;; virtualenvs and other special environment modifications thanks to
111 ;; `python-shell-process-environment' and `python-shell-exec-path'.
112 ;; These two variables allows you to modify execution paths and
113 ;; environment variables to make easy for you to setup virtualenv rules
114 ;; or behavior modifications when running shells. Here is an example
115 ;; of how to make shell processes to be run using the /path/to/env/
116 ;; virtualenv:
118 ;; (setq python-shell-process-environment
119 ;; (list
120 ;; (format "PATH=%s" (mapconcat
121 ;; 'identity
122 ;; (reverse
123 ;; (cons (getenv "PATH")
124 ;; '("/path/to/env/bin/")))
125 ;; ":"))
126 ;; "VIRTUAL_ENV=/path/to/env/"))
127 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
129 ;; Since the above is cumbersome and can be programmatically
130 ;; calculated, the variable `python-shell-virtualenv-path' is
131 ;; provided. When this variable is set with the path of the
132 ;; virtualenv to use, `process-environment' and `exec-path' get proper
133 ;; values in order to run shells inside the specified virtualenv. So
134 ;; the following will achieve the same as the previous example:
136 ;; (setq python-shell-virtualenv-path "/path/to/env/")
138 ;; Also the `python-shell-extra-pythonpaths' variable have been
139 ;; introduced as simple way of adding paths to the PYTHONPATH without
140 ;; affecting existing values.
142 ;; Pdb tracking: when you execute a block of code that contains some
143 ;; call to pdb (or ipdb) it will prompt the block of code and will
144 ;; follow the execution of pdb marking the current line with an arrow.
146 ;; Symbol completion: you can complete the symbol at point. It uses
147 ;; the shell completion in background so you should run
148 ;; `python-shell-send-buffer' from time to time to get better results.
150 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
151 ;; def, for, if, try and while. These skeletons are integrated with
152 ;; dabbrev. If you have `dabbrev-mode' activated and
153 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
154 ;; the name of any of those defined and hit SPC, they will be
155 ;; automatically expanded.
157 ;; FFAP: You can find the filename for a given module when using ffap
158 ;; out of the box. This feature needs an inferior python shell
159 ;; running.
161 ;; Code check: Check the current file for errors with `python-check'
162 ;; using the program defined in `python-check-command'.
164 ;; Eldoc: returns documentation for object at point by using the
165 ;; inferior python subprocess to inspect its documentation. As you
166 ;; might guessed you should run `python-shell-send-buffer' from time
167 ;; to time to get better results too.
169 ;; imenu: This mode supports imenu. It builds a plain or tree menu
170 ;; depending on the value of `python-imenu-make-tree'. Also you can
171 ;; customize if menu items should include its type using
172 ;; `python-imenu-include-defun-type'.
174 ;; If you used python-mode.el you probably will miss auto-indentation
175 ;; when inserting newlines. To achieve the same behavior you have
176 ;; two options:
178 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
180 ;; 2) Add the following hook in your .emacs:
182 ;; (add-hook 'python-mode-hook
183 ;; #'(lambda ()
184 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
186 ;; I'd recommend the first one since you'll get the same behavior for
187 ;; all modes out-of-the-box.
189 ;;; Installation:
191 ;; Add this to your .emacs:
193 ;; (add-to-list 'load-path "/folder/containing/file")
194 ;; (require 'python)
196 ;;; TODO:
198 ;;; Code:
200 (require 'ansi-color)
201 (require 'comint)
203 (eval-when-compile
204 (require 'cl)
205 ;; Avoid compiler warnings
206 (defvar view-return-to-alist)
207 (defvar compilation-error-regexp-alist)
208 (defvar outline-heading-end-regexp))
210 (autoload 'comint-mode "comint")
212 ;;;###autoload
213 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
214 ;;;###autoload
215 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
217 (defgroup python nil
218 "Python Language's flying circus support for Emacs."
219 :group 'languages
220 :version "23.2"
221 :link '(emacs-commentary-link "python"))
224 ;;; Bindings
226 (defvar python-mode-map
227 (let ((map (make-sparse-keymap)))
228 ;; Movement
229 (substitute-key-definition 'backward-sentence
230 'python-nav-backward-sentence
231 map global-map)
232 (substitute-key-definition 'forward-sentence
233 'python-nav-forward-sentence
234 map global-map)
235 (define-key map "\C-c\C-j" 'python-nav-jump-to-defun)
236 ;; Indent specific
237 (define-key map "\177" 'python-indent-dedent-line-backspace)
238 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
239 (define-key map "\C-c<" 'python-indent-shift-left)
240 (define-key map "\C-c>" 'python-indent-shift-right)
241 (define-key map ":" 'python-indent-electric-colon)
242 ;; Skeletons
243 (define-key map "\C-c\C-tc" 'python-skeleton-class)
244 (define-key map "\C-c\C-td" 'python-skeleton-def)
245 (define-key map "\C-c\C-tf" 'python-skeleton-for)
246 (define-key map "\C-c\C-ti" 'python-skeleton-if)
247 (define-key map "\C-c\C-tt" 'python-skeleton-try)
248 (define-key map "\C-c\C-tw" 'python-skeleton-while)
249 ;; Shell interaction
250 (define-key map "\C-c\C-s" 'python-shell-send-string)
251 (define-key map "\C-c\C-r" 'python-shell-send-region)
252 (define-key map "\C-\M-x" 'python-shell-send-defun)
253 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
254 (define-key map "\C-c\C-l" 'python-shell-send-file)
255 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
256 ;; Some util commands
257 (define-key map "\C-c\C-v" 'python-check)
258 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
259 ;; Utilities
260 (substitute-key-definition 'complete-symbol 'completion-at-point
261 map global-map)
262 (easy-menu-define python-menu map "Python Mode menu"
263 `("Python"
264 :help "Python-specific Features"
265 ["Shift region left" python-indent-shift-left :active mark-active
266 :help "Shift region left by a single indentation step"]
267 ["Shift region right" python-indent-shift-right :active mark-active
268 :help "Shift region right by a single indentation step"]
270 ["Start of def/class" beginning-of-defun
271 :help "Go to start of outermost definition around point"]
272 ["End of def/class" end-of-defun
273 :help "Go to end of definition around point"]
274 ["Mark def/class" mark-defun
275 :help "Mark outermost definition around point"]
276 ["Jump to def/class" python-nav-jump-to-defun
277 :help "Jump to a class or function definition"]
278 "--"
279 ("Skeletons")
280 "---"
281 ["Start interpreter" run-python
282 :help "Run inferior Python process in a separate buffer"]
283 ["Switch to shell" python-shell-switch-to-shell
284 :help "Switch to running inferior Python process"]
285 ["Eval string" python-shell-send-string
286 :help "Eval string in inferior Python session"]
287 ["Eval buffer" python-shell-send-buffer
288 :help "Eval buffer in inferior Python session"]
289 ["Eval region" python-shell-send-region
290 :help "Eval region in inferior Python session"]
291 ["Eval defun" python-shell-send-defun
292 :help "Eval defun in inferior Python session"]
293 ["Eval file" python-shell-send-file
294 :help "Eval file in inferior Python session"]
295 ["Debugger" pdb :help "Run pdb under GUD"]
296 "----"
297 ["Check file" python-check
298 :help "Check file for errors"]
299 ["Help on symbol" python-eldoc-at-point
300 :help "Get help on symbol at point"]
301 ["Complete symbol" completion-at-point
302 :help "Complete symbol before point"]))
303 map)
304 "Keymap for `python-mode'.")
307 ;;; Python specialized rx
309 (eval-when-compile
310 (defconst python-rx-constituents
311 (list
312 `(block-start . ,(rx symbol-start
313 (or "def" "class" "if" "elif" "else" "try"
314 "except" "finally" "for" "while" "with")
315 symbol-end))
316 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
317 (* (any word ?_))))
318 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
319 `(if-name-main . ,(rx line-start "if" (+ space) "__name__"
320 (+ space) "==" (+ space)
321 (any ?' ?\") "__main__" (any ?' ?\")
322 (* space) ?:))
323 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
324 `(open-paren . ,(rx (or "{" "[" "(")))
325 `(close-paren . ,(rx (or "}" "]" ")")))
326 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
327 `(not-simple-operator . ,(rx
328 (not
329 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
330 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
331 "=" "%" "**" "//" "<<" ">>" "<=" "!="
332 "==" ">=" "is" "not")))
333 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
334 ">>=" "<<=" "&=" "^=" "|="))))
335 "Additional Python specific sexps for `python-rx'"))
337 (defmacro python-rx (&rest regexps)
338 "Python mode specialized rx macro.
339 This variant of `rx' supports common python named REGEXPS."
340 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
341 (cond ((null regexps)
342 (error "No regexp"))
343 ((cdr regexps)
344 (rx-to-string `(and ,@regexps) t))
346 (rx-to-string (car regexps) t)))))
349 ;;; Font-lock and syntax
350 (defvar python-font-lock-keywords
351 ;; Keywords
352 `(,(rx symbol-start
354 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
355 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
356 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
357 "try"
358 ;; Python 2:
359 "print" "exec"
360 ;; Python 3:
361 ;; False, None, and True are listed as keywords on the Python 3
362 ;; documentation, but since they also qualify as constants they are
363 ;; fontified like that in order to keep font-lock consistent between
364 ;; Python versions.
365 "nonlocal"
366 ;; Extra:
367 "self")
368 symbol-end)
369 ;; functions
370 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
371 (1 font-lock-function-name-face))
372 ;; classes
373 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
374 (1 font-lock-type-face))
375 ;; Constants
376 (,(rx symbol-start
378 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
379 ;; copyright, license, credits, quit and exit are added by the site
380 ;; module and they are not intended to be used in programs
381 "copyright" "credits" "exit" "license" "quit")
382 symbol-end) . font-lock-constant-face)
383 ;; Decorators.
384 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
385 (0+ "." (1+ (or word ?_)))))
386 (1 font-lock-type-face))
387 ;; Builtin Exceptions
388 (,(rx symbol-start
390 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
391 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
392 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
393 "ImportError" "ImportWarning" "IndexError" "KeyError"
394 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
395 "NotImplementedError" "OSError" "OverflowError"
396 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
397 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
398 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
399 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
400 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
401 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
402 ;; Python 2:
403 "StandardError"
404 ;; Python 3:
405 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
406 "TabError")
407 symbol-end) . font-lock-type-face)
408 ;; Builtins
409 (,(rx symbol-start
411 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
412 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
413 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
414 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
415 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
416 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
417 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
418 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
419 "__import__"
420 ;; Python 2:
421 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
422 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
423 "intern"
424 ;; Python 3:
425 "ascii" "bytearray" "bytes" "exec"
426 ;; Extra:
427 "__all__" "__doc__" "__name__" "__package__")
428 symbol-end) . font-lock-builtin-face)
429 ;; assignments
430 ;; support for a = b = c = 5
431 (,(lambda (limit)
432 (let ((re (python-rx (group (+ (any word ?. ?_)))
433 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
434 assignment-operator)))
435 (when (re-search-forward re limit t)
436 (while (and (python-info-ppss-context 'paren)
437 (re-search-forward re limit t)))
438 (if (and (not (python-info-ppss-context 'paren))
439 (not (equal (char-after (point-marker)) ?=)))
441 (set-match-data nil)))))
442 (1 font-lock-variable-name-face nil nil))
443 ;; support for a, b, c = (1, 2, 3)
444 (,(lambda (limit)
445 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
446 (* ?, (* space) (+ (any word ?. ?_)) (* space))
447 ?, (* space) (+ (any word ?. ?_)) (* space)
448 assignment-operator)))
449 (when (and (re-search-forward re limit t)
450 (goto-char (nth 3 (match-data))))
451 (while (and (python-info-ppss-context 'paren)
452 (re-search-forward re limit t))
453 (goto-char (nth 3 (match-data))))
454 (if (not (python-info-ppss-context 'paren))
456 (set-match-data nil)))))
457 (1 font-lock-variable-name-face nil nil))))
459 (defconst python-syntax-propertize-function
460 ;; Make outer chars of matching triple-quote sequences into generic
461 ;; string delimiters. Fixme: Is there a better way?
462 ;; First avoid a sequence preceded by an odd number of backslashes.
463 (syntax-propertize-rules
464 (;; ¡Backrefs don't work in syntax-propertize-rules!
465 (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
466 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
467 (3 (ignore (python-quote-syntax))))))
469 (defun python-quote-syntax ()
470 "Put `syntax-table' property correctly on triple quote.
471 Used for syntactic keywords. N is the match number (1, 2 or 3)."
472 ;; Given a triple quote, we have to check the context to know
473 ;; whether this is an opening or closing triple or whether it's
474 ;; quoted anyhow, and should be ignored. (For that we need to do
475 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
476 ;; to use it here despite initial worries.) We also have to sort
477 ;; out a possible prefix -- well, we don't _have_ to, but I think it
478 ;; should be treated as part of the string.
480 ;; Test cases:
481 ;; ur"""ar""" x='"' # """
482 ;; x = ''' """ ' a
483 ;; '''
484 ;; x '"""' x """ \"""" x
485 (save-excursion
486 (goto-char (match-beginning 0))
487 (let ((syntax (save-match-data (syntax-ppss))))
488 (cond
489 ((eq t (nth 3 syntax)) ; after unclosed fence
490 ;; Consider property for the last char if in a fenced string.
491 (goto-char (nth 8 syntax)) ; fence position
492 (skip-chars-forward "uUrR") ; skip any prefix
493 ;; Is it a matching sequence?
494 (if (eq (char-after) (char-after (match-beginning 2)))
495 (put-text-property (match-beginning 3) (match-end 3)
496 'syntax-table (string-to-syntax "|"))))
497 ((match-end 1)
498 ;; Consider property for initial char, accounting for prefixes.
499 (put-text-property (match-beginning 1) (match-end 1)
500 'syntax-table (string-to-syntax "|")))
502 ;; Consider property for initial char, accounting for prefixes.
503 (put-text-property (match-beginning 2) (match-end 2)
504 'syntax-table (string-to-syntax "|"))))
507 (defvar python-mode-syntax-table
508 (let ((table (make-syntax-table)))
509 ;; Give punctuation syntax to ASCII that normally has symbol
510 ;; syntax or has word syntax and isn't a letter.
511 (let ((symbol (string-to-syntax "_"))
512 (sst (standard-syntax-table)))
513 (dotimes (i 128)
514 (unless (= i ?_)
515 (if (equal symbol (aref sst i))
516 (modify-syntax-entry i "." table)))))
517 (modify-syntax-entry ?$ "." table)
518 (modify-syntax-entry ?% "." table)
519 ;; exceptions
520 (modify-syntax-entry ?# "<" table)
521 (modify-syntax-entry ?\n ">" table)
522 (modify-syntax-entry ?' "\"" table)
523 (modify-syntax-entry ?` "$" table)
524 table)
525 "Syntax table for Python files.")
527 (defvar python-dotty-syntax-table
528 (let ((table (make-syntax-table python-mode-syntax-table)))
529 (modify-syntax-entry ?. "w" table)
530 (modify-syntax-entry ?_ "w" table)
531 table)
532 "Dotty syntax table for Python files.
533 It makes underscores and dots word constituent chars.")
536 ;;; Indentation
538 (defcustom python-indent-offset 4
539 "Default indentation offset for Python."
540 :group 'python
541 :type 'integer
542 :safe 'integerp)
544 (defcustom python-indent-guess-indent-offset t
545 "Non-nil tells Python mode to guess `python-indent-offset' value."
546 :type 'boolean
547 :group 'python
548 :safe 'booleanp)
550 (define-obsolete-variable-alias
551 'python-indent 'python-indent-offset "24.2")
553 (define-obsolete-variable-alias
554 'python-guess-indent 'python-indent-guess-indent-offset "24.2")
556 (defvar python-indent-current-level 0
557 "Current indentation level `python-indent-line-function' is using.")
559 (defvar python-indent-levels '(0)
560 "Levels of indentation available for `python-indent-line-function'.")
562 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
563 "List of words that should be dedented.
564 These make `python-indent-calculate-indentation' subtract the value of
565 `python-indent-offset'.")
567 (defun python-indent-guess-indent-offset ()
568 "Guess and set `python-indent-offset' for the current buffer."
569 (interactive)
570 (save-excursion
571 (save-restriction
572 (widen)
573 (goto-char (point-min))
574 (let ((block-end))
575 (while (and (not block-end)
576 (re-search-forward
577 (python-rx line-start block-start) nil t))
578 (when (and
579 (not (python-info-ppss-context-type))
580 (progn
581 (goto-char (line-end-position))
582 (python-util-forward-comment -1)
583 (if (equal (char-before) ?:)
585 (forward-line 1)
586 (when (python-info-block-continuation-line-p)
587 (while (and (python-info-continuation-line-p)
588 (not (eobp)))
589 (forward-line 1))
590 (python-util-forward-comment -1)
591 (when (equal (char-before) ?:)
592 t)))))
593 (setq block-end (point-marker))))
594 (let ((indentation
595 (when block-end
596 (goto-char block-end)
597 (python-util-forward-comment)
598 (current-indentation))))
599 (if indentation
600 (setq python-indent-offset indentation)
601 (message "Can't guess python-indent-offset, using defaults: %s"
602 python-indent-offset)))))))
604 (defun python-indent-context ()
605 "Get information on indentation context.
606 Context information is returned with a cons with the form:
607 \(STATUS . START)
609 Where status can be any of the following symbols:
610 * inside-paren: If point in between (), {} or []
611 * inside-string: If point is inside a string
612 * after-backslash: Previous line ends in a backslash
613 * after-beginning-of-block: Point is after beginning of block
614 * after-line: Point is after normal line
615 * no-indent: Point is at beginning of buffer or other special case
616 START is the buffer position where the sexp starts."
617 (save-restriction
618 (widen)
619 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
620 (start))
621 (cons
622 (cond
623 ;; Beginning of buffer
624 ((save-excursion
625 (goto-char (line-beginning-position))
626 (bobp))
627 'no-indent)
628 ;; Inside a paren
629 ((setq start (python-info-ppss-context 'paren ppss))
630 'inside-paren)
631 ;; Inside string
632 ((setq start (python-info-ppss-context 'string ppss))
633 'inside-string)
634 ;; After backslash
635 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
636 (python-info-ppss-context 'comment ppss)))
637 (let ((line-beg-pos (line-beginning-position)))
638 (when (python-info-line-ends-backslash-p
639 (1- line-beg-pos))
640 (- line-beg-pos 2)))))
641 'after-backslash)
642 ;; After beginning of block
643 ((setq start (save-excursion
644 (when (progn
645 (back-to-indentation)
646 (python-util-forward-comment -1)
647 (equal (char-before) ?:))
648 ;; Move to the first block start that's not in within
649 ;; a string, comment or paren and that's not a
650 ;; continuation line.
651 (while (and (re-search-backward
652 (python-rx block-start) nil t)
654 (python-info-ppss-context 'string)
655 (python-info-ppss-context 'comment)
656 (python-info-ppss-context 'paren)
657 (python-info-continuation-line-p))))
658 (when (looking-at (python-rx block-start))
659 (point-marker)))))
660 'after-beginning-of-block)
661 ;; After normal line
662 ((setq start (save-excursion
663 (back-to-indentation)
664 (python-util-forward-comment -1)
665 (python-nav-sentence-start)
666 (point-marker)))
667 'after-line)
668 ;; Do not indent
669 (t 'no-indent))
670 start))))
672 (defun python-indent-calculate-indentation ()
673 "Calculate correct indentation offset for the current line."
674 (let* ((indentation-context (python-indent-context))
675 (context-status (car indentation-context))
676 (context-start (cdr indentation-context)))
677 (save-restriction
678 (widen)
679 (save-excursion
680 (case context-status
681 ('no-indent 0)
682 ;; When point is after beginning of block just add one level
683 ;; of indentation relative to the context-start
684 ('after-beginning-of-block
685 (goto-char context-start)
686 (+ (current-indentation) python-indent-offset))
687 ;; When after a simple line just use previous line
688 ;; indentation, in the case current line starts with a
689 ;; `python-indent-dedenters' de-indent one level.
690 ('after-line
692 (save-excursion
693 (goto-char context-start)
694 (current-indentation))
695 (if (progn
696 (back-to-indentation)
697 (looking-at (regexp-opt python-indent-dedenters)))
698 python-indent-offset
699 0)))
700 ;; When inside of a string, do nothing. just use the current
701 ;; indentation. XXX: perhaps it would be a good idea to
702 ;; invoke standard text indentation here
703 ('inside-string
704 (goto-char context-start)
705 (current-indentation))
706 ;; After backslash we have several possibilities.
707 ('after-backslash
708 (cond
709 ;; Check if current line is a dot continuation. For this
710 ;; the current line must start with a dot and previous
711 ;; line must contain a dot too.
712 ((save-excursion
713 (back-to-indentation)
714 (when (looking-at "\\.")
715 ;; If after moving one line back point is inside a paren it
716 ;; needs to move back until it's not anymore
717 (while (prog2
718 (forward-line -1)
719 (and (not (bobp))
720 (python-info-ppss-context 'paren))))
721 (goto-char (line-end-position))
722 (while (and (re-search-backward
723 "\\." (line-beginning-position) t)
724 (or (python-info-ppss-context 'comment)
725 (python-info-ppss-context 'string)
726 (python-info-ppss-context 'paren))))
727 (if (and (looking-at "\\.")
728 (not (or (python-info-ppss-context 'comment)
729 (python-info-ppss-context 'string)
730 (python-info-ppss-context 'paren))))
731 ;; The indentation is the same column of the
732 ;; first matching dot that's not inside a
733 ;; comment, a string or a paren
734 (current-column)
735 ;; No dot found on previous line, just add another
736 ;; indentation level.
737 (+ (current-indentation) python-indent-offset)))))
738 ;; Check if prev line is a block continuation
739 ((let ((block-continuation-start
740 (python-info-block-continuation-line-p)))
741 (when block-continuation-start
742 ;; If block-continuation-start is set jump to that
743 ;; marker and use first column after the block start
744 ;; as indentation value.
745 (goto-char block-continuation-start)
746 (re-search-forward
747 (python-rx block-start (* space))
748 (line-end-position) t)
749 (current-column))))
750 ;; Check if current line is an assignment continuation
751 ((let ((assignment-continuation-start
752 (python-info-assignment-continuation-line-p)))
753 (when assignment-continuation-start
754 ;; If assignment-continuation is set jump to that
755 ;; marker and use first column after the assignment
756 ;; operator as indentation value.
757 (goto-char assignment-continuation-start)
758 (current-column))))
760 (forward-line -1)
761 (goto-char (python-info-beginning-of-backslash))
762 (if (save-excursion
763 (and
764 (forward-line -1)
765 (goto-char
766 (or (python-info-beginning-of-backslash) (point)))
767 (python-info-line-ends-backslash-p)))
768 ;; The two previous lines ended in a backslash so we must
769 ;; respect previous line indentation.
770 (current-indentation)
771 ;; What happens here is that we are dealing with the second
772 ;; line of a backslash continuation, in that case we just going
773 ;; to add one indentation level.
774 (+ (current-indentation) python-indent-offset)))))
775 ;; When inside a paren there's a need to handle nesting
776 ;; correctly
777 ('inside-paren
778 (cond
779 ;; If current line closes the outermost open paren use the
780 ;; current indentation of the context-start line.
781 ((save-excursion
782 (skip-syntax-forward "\s" (line-end-position))
783 (when (and (looking-at (regexp-opt '(")" "]" "}")))
784 (progn
785 (forward-char 1)
786 (not (python-info-ppss-context 'paren))))
787 (goto-char context-start)
788 (current-indentation))))
789 ;; If open paren is contained on a line by itself add another
790 ;; indentation level, else look for the first word after the
791 ;; opening paren and use it's column position as indentation
792 ;; level.
793 ((let* ((content-starts-in-newline)
794 (indent
795 (save-excursion
796 (if (setq content-starts-in-newline
797 (progn
798 (goto-char context-start)
799 (forward-char)
800 (save-restriction
801 (narrow-to-region
802 (line-beginning-position)
803 (line-end-position))
804 (python-util-forward-comment))
805 (looking-at "$")))
806 (+ (current-indentation) python-indent-offset)
807 (current-column)))))
808 ;; Adjustments
809 (cond
810 ;; If current line closes a nested open paren de-indent one
811 ;; level.
812 ((progn
813 (back-to-indentation)
814 (looking-at (regexp-opt '(")" "]" "}"))))
815 (- indent python-indent-offset))
816 ;; If the line of the opening paren that wraps the current
817 ;; line starts a block add another level of indentation to
818 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
819 ((save-excursion
820 (when (and content-starts-in-newline
821 (progn
822 (goto-char context-start)
823 (back-to-indentation)
824 (looking-at (python-rx block-start))))
825 (+ indent python-indent-offset))))
826 (t indent)))))))))))
828 (defun python-indent-calculate-levels ()
829 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
830 (let* ((indentation (python-indent-calculate-indentation))
831 (remainder (% indentation python-indent-offset))
832 (steps (/ (- indentation remainder) python-indent-offset)))
833 (setq python-indent-levels (list 0))
834 (dotimes (step steps)
835 (push (* python-indent-offset (1+ step)) python-indent-levels))
836 (when (not (eq 0 remainder))
837 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
838 (setq python-indent-levels (nreverse python-indent-levels))
839 (setq python-indent-current-level (1- (length python-indent-levels)))))
841 (defun python-indent-toggle-levels ()
842 "Toggle `python-indent-current-level' over `python-indent-levels'."
843 (setq python-indent-current-level (1- python-indent-current-level))
844 (when (< python-indent-current-level 0)
845 (setq python-indent-current-level (1- (length python-indent-levels)))))
847 (defun python-indent-line (&optional force-toggle)
848 "Internal implementation of `python-indent-line-function'.
849 Uses the offset calculated in
850 `python-indent-calculate-indentation' and available levels
851 indicated by the variable `python-indent-levels' to set the
852 current indentation.
854 When the variable `last-command' is equal to
855 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
856 levels indicated in the variable `python-indent-levels' by
857 setting the current level in the variable
858 `python-indent-current-level'.
860 When the variable `last-command' is not equal to
861 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
862 possible indentation levels and saves it in the variable
863 `python-indent-levels'. Afterwards it sets the variable
864 `python-indent-current-level' correctly so offset is equal
865 to (`nth' `python-indent-current-level' `python-indent-levels')"
866 (if (or (and (eq this-command 'indent-for-tab-command)
867 (eq last-command this-command))
868 force-toggle)
869 (if (not (equal python-indent-levels '(0)))
870 (python-indent-toggle-levels)
871 (python-indent-calculate-levels))
872 (python-indent-calculate-levels))
873 (beginning-of-line)
874 (delete-horizontal-space)
875 (indent-to (nth python-indent-current-level python-indent-levels))
876 (python-info-closing-block-message))
878 (defun python-indent-line-function ()
879 "`indent-line-function' for Python mode.
880 See `python-indent-line' for details."
881 (python-indent-line))
883 (defun python-indent-dedent-line ()
884 "De-indent current line."
885 (interactive "*")
886 (when (and (not (or (python-info-ppss-context 'string)
887 (python-info-ppss-context 'comment)))
888 (<= (point-marker) (save-excursion
889 (back-to-indentation)
890 (point-marker)))
891 (> (current-column) 0))
892 (python-indent-line t)
895 (defun python-indent-dedent-line-backspace (arg)
896 "De-indent current line.
897 Argument ARG is passed to `backward-delete-char-untabify' when
898 point is not in between the indentation."
899 (interactive "*p")
900 (when (not (python-indent-dedent-line))
901 (backward-delete-char-untabify arg)))
902 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
904 (defun python-indent-region (start end)
905 "Indent a python region automagically.
907 Called from a program, START and END specify the region to indent."
908 (let ((deactivate-mark nil))
909 (save-excursion
910 (goto-char end)
911 (setq end (point-marker))
912 (goto-char start)
913 (or (bolp) (forward-line 1))
914 (while (< (point) end)
915 (or (and (bolp) (eolp))
916 (let (word)
917 (forward-line -1)
918 (back-to-indentation)
919 (setq word (current-word))
920 (forward-line 1)
921 (when word
922 (beginning-of-line)
923 (delete-horizontal-space)
924 (indent-to (python-indent-calculate-indentation)))))
925 (forward-line 1))
926 (move-marker end nil))))
928 (defun python-indent-shift-left (start end &optional count)
929 "Shift lines contained in region START END by COUNT columns to the left.
930 COUNT defaults to `python-indent-offset'. If region isn't
931 active, the current line is shifted. The shifted region includes
932 the lines in which START and END lie. An error is signaled if
933 any lines in the region are indented less than COUNT columns."
934 (interactive
935 (if mark-active
936 (list (region-beginning) (region-end) current-prefix-arg)
937 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
938 (if count
939 (setq count (prefix-numeric-value count))
940 (setq count python-indent-offset))
941 (when (> count 0)
942 (let ((deactivate-mark nil))
943 (save-excursion
944 (goto-char start)
945 (while (< (point) end)
946 (if (and (< (current-indentation) count)
947 (not (looking-at "[ \t]*$")))
948 (error "Can't shift all lines enough"))
949 (forward-line))
950 (indent-rigidly start end (- count))))))
952 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
954 (defun python-indent-shift-right (start end &optional count)
955 "Shift lines contained in region START END by COUNT columns to the left.
956 COUNT defaults to `python-indent-offset'. If region isn't
957 active, the current line is shifted. The shifted region includes
958 the lines in which START and END lie."
959 (interactive
960 (if mark-active
961 (list (region-beginning) (region-end) current-prefix-arg)
962 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
963 (let ((deactivate-mark nil))
964 (if count
965 (setq count (prefix-numeric-value count))
966 (setq count python-indent-offset))
967 (indent-rigidly start end count)))
969 (defun python-indent-electric-colon (arg)
970 "Insert a colon and maybe de-indent the current line.
971 With numeric ARG, just insert that many colons. With
972 \\[universal-argument], just insert a single colon."
973 (interactive "*P")
974 (self-insert-command (if (not (integerp arg)) 1 arg))
975 (when (and (not arg)
976 (eolp)
977 (not (equal ?: (char-after (- (point-marker) 2))))
978 (not (or (python-info-ppss-context 'string)
979 (python-info-ppss-context 'comment))))
980 (let ((indentation (current-indentation))
981 (calculated-indentation (python-indent-calculate-indentation)))
982 (python-info-closing-block-message)
983 (when (> indentation calculated-indentation)
984 (save-excursion
985 (indent-line-to calculated-indentation)
986 (when (not (python-info-closing-block-message))
987 (indent-line-to indentation)))))))
988 (put 'python-indent-electric-colon 'delete-selection t)
990 (defun python-indent-post-self-insert-function ()
991 "Adjust closing paren line indentation after a char is added.
992 This function is intended to be added to the
993 `post-self-insert-hook.' If a line renders a paren alone, after
994 adding a char before it, the line will be re-indented
995 automatically if needed."
996 (when (and (eq (char-before) last-command-event)
997 (not (bolp))
998 (memq (char-after) '(?\) ?\] ?\})))
999 (save-excursion
1000 (goto-char (line-beginning-position))
1001 ;; If after going to the beginning of line the point
1002 ;; is still inside a paren it's ok to do the trick
1003 (when (python-info-ppss-context 'paren)
1004 (let ((indentation (python-indent-calculate-indentation)))
1005 (when (< (current-indentation) indentation)
1006 (indent-line-to indentation)))))))
1009 ;;; Navigation
1011 (defvar python-nav-beginning-of-defun-regexp
1012 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1013 "Regexp matching class or function definition.
1014 The name of the defun should be grouped so it can be retrieved
1015 via `match-string'.")
1017 (defun python-nav-beginning-of-defun (&optional arg)
1018 "Move point to `beginning-of-defun'.
1019 With positive ARG move search backwards. With negative do the
1020 same but forward. When ARG is nil or 0 defaults to 1. This is
1021 the main part of `python-beginning-of-defun-function'. Return
1022 non-nil if point is moved to `beginning-of-defun'."
1023 (when (or (null arg) (= arg 0)) (setq arg 1))
1024 (let* ((re-search-fn (if (> arg 0)
1025 #'re-search-backward
1026 #'re-search-forward))
1027 (line-beg-pos (line-beginning-position))
1028 (line-content-start (+ line-beg-pos (current-indentation)))
1029 (pos (point-marker))
1030 (found
1031 (progn
1032 (when (and (< arg 0)
1033 (python-info-looking-at-beginning-of-defun))
1034 (end-of-line 1))
1035 (while (and (funcall re-search-fn
1036 python-nav-beginning-of-defun-regexp nil t)
1037 (python-info-ppss-context-type)))
1038 (and (python-info-looking-at-beginning-of-defun)
1039 (or (not (= (line-number-at-pos pos)
1040 (line-number-at-pos)))
1041 (and (>= (point) line-beg-pos)
1042 (<= (point) line-content-start)
1043 (> pos line-content-start)))))))
1044 (if found
1045 (or (beginning-of-line 1) t)
1046 (and (goto-char pos) nil))))
1048 (defun python-beginning-of-defun-function (&optional arg)
1049 "Move point to the beginning of def or class.
1050 With positive ARG move that number of functions backwards. With
1051 negative do the same but forward. When ARG is nil or 0 defaults
1052 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1053 (when (or (null arg) (= arg 0)) (setq arg 1))
1054 (let ((found))
1055 (cond ((and (eq this-command 'mark-defun)
1056 (python-info-looking-at-beginning-of-defun)))
1058 (dotimes (i (if (> arg 0) arg (- arg)))
1059 (when (and (python-nav-beginning-of-defun arg)
1060 (not found))
1061 (setq found t)))))
1062 found))
1064 (defun python-end-of-defun-function ()
1065 "Move point to the end of def or class.
1066 Returns nil if point is not in a def or class."
1067 (interactive)
1068 (let ((beg-defun-indent))
1069 (when (or (python-info-looking-at-beginning-of-defun)
1070 (python-beginning-of-defun-function 1)
1071 (python-beginning-of-defun-function -1))
1072 (setq beg-defun-indent (current-indentation))
1073 (forward-line 1)
1074 ;; Go as forward as possible
1075 (while (and (or
1076 (python-nav-beginning-of-defun -1)
1077 (and (goto-char (point-max)) nil))
1078 (> (current-indentation) beg-defun-indent)))
1079 (beginning-of-line 1)
1080 ;; Go as backwards as possible
1081 (while (and (forward-line -1)
1082 (not (bobp))
1083 (or (not (current-word))
1084 (equal (char-after (+ (point) (current-indentation))) ?#)
1085 (<= (current-indentation) beg-defun-indent)
1086 (looking-at (python-rx decorator))
1087 (python-info-ppss-context-type))))
1088 (forward-line 1)
1089 ;; If point falls inside a paren or string context the point is
1090 ;; forwarded at the end of it (or end of buffer if its not closed)
1091 (let ((context-type (python-info-ppss-context-type)))
1092 (when (memq context-type '(paren string))
1093 ;; Slow but safe.
1094 (while (and (not (eobp))
1095 (python-info-ppss-context-type))
1096 (forward-line 1)))))))
1098 (defun python-nav-sentence-start ()
1099 "Move to start of current sentence."
1100 (interactive "^")
1101 (while (and (not (back-to-indentation))
1102 (not (bobp))
1103 (when (or
1104 (save-excursion
1105 (forward-line -1)
1106 (python-info-line-ends-backslash-p))
1107 (python-info-ppss-context 'string)
1108 (python-info-ppss-context 'paren))
1109 (forward-line -1)))))
1111 (defun python-nav-sentence-end ()
1112 "Move to end of current sentence."
1113 (interactive "^")
1114 (while (and (goto-char (line-end-position))
1115 (not (eobp))
1116 (when (or
1117 (python-info-line-ends-backslash-p)
1118 (python-info-ppss-context 'string)
1119 (python-info-ppss-context 'paren))
1120 (forward-line 1)))))
1122 (defun python-nav-backward-sentence (&optional arg)
1123 "Move backward to start of sentence. With ARG, do it arg times.
1124 See `python-nav-forward-sentence' for more information."
1125 (interactive "^p")
1126 (or arg (setq arg 1))
1127 (python-nav-forward-sentence (- arg)))
1129 (defun python-nav-forward-sentence (&optional arg)
1130 "Move forward to next end of sentence. With ARG, repeat.
1131 With negative argument, move backward repeatedly to start of sentence."
1132 (interactive "^p")
1133 (or arg (setq arg 1))
1134 (while (> arg 0)
1135 (python-util-forward-comment)
1136 (python-nav-sentence-end)
1137 (forward-line 1)
1138 (setq arg (1- arg)))
1139 (while (< arg 0)
1140 (python-nav-sentence-end)
1141 (python-util-forward-comment -1)
1142 (python-nav-sentence-start)
1143 (forward-line -1)
1144 (setq arg (1+ arg))))
1146 (defvar python-nav-list-defun-positions-cache nil)
1147 (make-variable-buffer-local 'python-nav-list-defun-positions-cache)
1149 (defun python-nav-list-defun-positions (&optional include-type rescan)
1150 "Make an Alist of defun names and point markers for current buffer.
1151 When optional argument INCLUDE-TYPE is non-nil the type is
1152 included the defun name. With optional argument RESCAN the
1153 `python-nav-list-defun-positions-cache' is invalidated and the
1154 list of defun is regenerated again."
1155 (if (and python-nav-list-defun-positions-cache (not rescan))
1156 python-nav-list-defun-positions-cache
1157 (let ((defs))
1158 (save-restriction
1159 (widen)
1160 (save-excursion
1161 (goto-char (point-max))
1162 (while (re-search-backward python-nav-beginning-of-defun-regexp nil t)
1163 (when (and (not (python-info-ppss-context 'string))
1164 (not (python-info-ppss-context 'comment))
1165 (not (python-info-ppss-context 'parent)))
1166 (add-to-list
1167 'defs (cons
1168 (python-info-current-defun include-type)
1169 (point-marker)))))
1170 (setq python-nav-list-defun-positions-cache defs))))))
1172 (defun python-nav-read-defun (&optional rescan)
1173 "Read a defun name of current buffer and return its point marker.
1174 A cons cell with the form (DEFUN-NAME . POINT-MARKER) is returned
1175 when defun is completed, else nil. With optional argument RESCAN
1176 forces `python-nav-list-defun-positions' to invalidate its
1177 cache."
1178 (let ((defs (python-nav-list-defun-positions nil rescan)))
1179 (minibuffer-with-setup-hook
1180 (lambda ()
1181 (setq minibuffer-completion-table (mapcar 'car defs)))
1182 (let ((stringdef
1183 (read-from-minibuffer
1184 "Jump to definition: " nil
1185 minibuffer-local-must-match-map)))
1186 (when (not (string= stringdef ""))
1187 (assoc-string stringdef defs))))))
1189 (defun python-nav-jump-to-defun (def)
1190 "Jump to the definition of DEF in current file.
1191 Locations are cached; use a `C-u' prefix argument to force a
1192 rescan."
1193 (interactive
1194 (list (python-nav-read-defun current-prefix-arg)))
1195 (when (not (called-interactively-p 'interactive))
1196 (setq def (assoc-string def (python-nav-list-defun-positions))))
1197 (let ((def-marker (cdr def)))
1198 (when (markerp def-marker)
1199 (goto-char (marker-position def-marker))
1200 (back-to-indentation))))
1203 ;;; Shell integration
1205 (defcustom python-shell-buffer-name "Python"
1206 "Default buffer name for Python interpreter."
1207 :type 'string
1208 :group 'python
1209 :safe 'stringp)
1211 (defcustom python-shell-interpreter "python"
1212 "Default Python interpreter for shell."
1213 :type 'string
1214 :group 'python)
1216 (defcustom python-shell-internal-buffer-name "Python Internal"
1217 "Default buffer name for the Internal Python interpreter."
1218 :type 'string
1219 :group 'python
1220 :safe 'stringp)
1222 (defcustom python-shell-interpreter-args "-i"
1223 "Default arguments for the Python interpreter."
1224 :type 'string
1225 :group 'python)
1227 (defcustom python-shell-prompt-regexp ">>> "
1228 "Regular Expression matching top\-level input prompt of python shell.
1229 It should not contain a caret (^) at the beginning."
1230 :type 'string
1231 :group 'python
1232 :safe 'stringp)
1234 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1235 "Regular Expression matching block input prompt of python shell.
1236 It should not contain a caret (^) at the beginning."
1237 :type 'string
1238 :group 'python
1239 :safe 'stringp)
1241 (defcustom python-shell-prompt-output-regexp ""
1242 "Regular Expression matching output prompt of python shell.
1243 It should not contain a caret (^) at the beginning."
1244 :type 'string
1245 :group 'python
1246 :safe 'stringp)
1248 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1249 "Regular Expression matching pdb input prompt of python shell.
1250 It should not contain a caret (^) at the beginning."
1251 :type 'string
1252 :group 'python
1253 :safe 'stringp)
1255 (defcustom python-shell-enable-font-lock t
1256 "Should syntax highlighting be enabled in the python shell buffer?
1257 Restart the python shell after changing this variable for it to take effect."
1258 :type 'boolean
1259 :group 'python
1260 :safe 'booleanp)
1262 (defcustom python-shell-send-setup-max-wait 5
1263 "Seconds to wait for process output before code setup.
1264 If output is received before the specified time then control is
1265 returned in that moment and not after waiting."
1266 :type 'integer
1267 :group 'python
1268 :safe 'integerp)
1270 (defcustom python-shell-process-environment nil
1271 "List of environment variables for Python shell.
1272 This variable follows the same rules as `process-environment'
1273 since it merges with it before the process creation routines are
1274 called. When this variable is nil, the Python shell is run with
1275 the default `process-environment'."
1276 :type '(repeat string)
1277 :group 'python
1278 :safe 'listp)
1280 (defcustom python-shell-extra-pythonpaths nil
1281 "List of extra pythonpaths for Python shell.
1282 The values of this variable are added to the existing value of
1283 PYTHONPATH in the `process-environment' variable."
1284 :type '(repeat string)
1285 :group 'python
1286 :safe 'listp)
1288 (defcustom python-shell-exec-path nil
1289 "List of path to search for binaries.
1290 This variable follows the same rules as `exec-path' since it
1291 merges with it before the process creation routines are called.
1292 When this variable is nil, the Python shell is run with the
1293 default `exec-path'."
1294 :type '(repeat string)
1295 :group 'python
1296 :safe 'listp)
1298 (defcustom python-shell-virtualenv-path nil
1299 "Path to virtualenv root.
1300 This variable, when set to a string, makes the values stored in
1301 `python-shell-process-environment' and `python-shell-exec-path'
1302 to be modified properly so shells are started with the specified
1303 virtualenv."
1304 :type 'string
1305 :group 'python
1306 :safe 'stringp)
1308 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1309 python-ffap-setup-code
1310 python-eldoc-setup-code)
1311 "List of code run by `python-shell-send-setup-codes'."
1312 :type '(repeat symbol)
1313 :group 'python
1314 :safe 'listp)
1316 (defcustom python-shell-compilation-regexp-alist
1317 `((,(rx line-start (1+ (any " \t")) "File \""
1318 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1319 "\", line " (group (1+ digit)))
1320 1 2)
1321 (,(rx " in file " (group (1+ not-newline)) " on line "
1322 (group (1+ digit)))
1323 1 2)
1324 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1325 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1326 1 2))
1327 "`compilation-error-regexp-alist' for inferior Python."
1328 :type '(alist string)
1329 :group 'python)
1331 (defun python-shell-get-process-name (dedicated)
1332 "Calculate the appropriate process name for inferior Python process.
1333 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1334 returns a string with the form
1335 `python-shell-buffer-name'[variable `buffer-file-name'] else
1336 returns the value of `python-shell-buffer-name'. After
1337 calculating the process name adds the buffer name for the process
1338 in the `same-window-buffer-names' list."
1339 (let ((process-name
1340 (if (and dedicated
1341 buffer-file-name)
1342 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1343 (format "%s" python-shell-buffer-name))))
1344 (add-to-list 'same-window-buffer-names (purecopy
1345 (format "*%s*" process-name)))
1346 process-name))
1348 (defun python-shell-internal-get-process-name ()
1349 "Calculate the appropriate process name for Internal Python process.
1350 The name is calculated from `python-shell-global-buffer-name' and
1351 a hash of all relevant global shell settings in order to ensure
1352 uniqueness for different types of configurations."
1353 (format "%s [%s]"
1354 python-shell-internal-buffer-name
1355 (md5
1356 (concat
1357 (python-shell-parse-command)
1358 python-shell-prompt-regexp
1359 python-shell-prompt-block-regexp
1360 python-shell-prompt-output-regexp
1361 (mapconcat #'symbol-value python-shell-setup-codes "")
1362 (mapconcat #'identity python-shell-process-environment "")
1363 (mapconcat #'identity python-shell-extra-pythonpaths "")
1364 (mapconcat #'identity python-shell-exec-path "")
1365 (or python-shell-virtualenv-path "")
1366 (mapconcat #'identity python-shell-exec-path "")))))
1368 (defun python-shell-parse-command ()
1369 "Calculate the string used to execute the inferior Python process."
1370 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1372 (defun python-shell-calculate-process-environment ()
1373 "Calculate process environment given `python-shell-virtualenv-path'."
1374 (let ((process-environment (append
1375 python-shell-process-environment
1376 process-environment nil))
1377 (virtualenv (if python-shell-virtualenv-path
1378 (directory-file-name python-shell-virtualenv-path)
1379 nil)))
1380 (when python-shell-extra-pythonpaths
1381 (setenv "PYTHONPATH"
1382 (format "%s%s%s"
1383 (mapconcat 'identity
1384 python-shell-extra-pythonpaths
1385 path-separator)
1386 path-separator
1387 (or (getenv "PYTHONPATH") ""))))
1388 (if (not virtualenv)
1389 process-environment
1390 (setenv "PYTHONHOME" nil)
1391 (setenv "PATH" (format "%s/bin%s%s"
1392 virtualenv path-separator
1393 (or (getenv "PATH") "")))
1394 (setenv "VIRTUAL_ENV" virtualenv))
1395 process-environment))
1397 (defun python-shell-calculate-exec-path ()
1398 "Calculate exec path given `python-shell-virtualenv-path'."
1399 (let ((path (append python-shell-exec-path
1400 exec-path nil)))
1401 (if (not python-shell-virtualenv-path)
1402 path
1403 (cons (format "%s/bin"
1404 (directory-file-name python-shell-virtualenv-path))
1405 path))))
1407 (defun python-comint-output-filter-function (output)
1408 "Hook run after content is put into comint buffer.
1409 OUTPUT is a string with the contents of the buffer."
1410 (ansi-color-filter-apply output))
1412 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1413 "Major mode for Python inferior process.
1414 Runs a Python interpreter as a subprocess of Emacs, with Python
1415 I/O through an Emacs buffer. Variables
1416 `python-shell-interpreter' and `python-shell-interpreter-args'
1417 controls which Python interpreter is run. Variables
1418 `python-shell-prompt-regexp',
1419 `python-shell-prompt-output-regexp',
1420 `python-shell-prompt-block-regexp',
1421 `python-shell-enable-font-lock',
1422 `python-shell-completion-setup-code',
1423 `python-shell-completion-string-code',
1424 `python-shell-completion-module-string-code',
1425 `python-eldoc-setup-code', `python-eldoc-string-code',
1426 `python-ffap-setup-code' and `python-ffap-string-code' can
1427 customize this mode for different Python interpreters.
1429 You can also add additional setup code to be run at
1430 initialization of the interpreter via `python-shell-setup-codes'
1431 variable.
1433 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1434 (set-syntax-table python-mode-syntax-table)
1435 (setq mode-line-process '(":%s"))
1436 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1437 python-shell-prompt-regexp
1438 python-shell-prompt-block-regexp
1439 python-shell-prompt-pdb-regexp))
1440 (make-local-variable 'comint-output-filter-functions)
1441 (add-hook 'comint-output-filter-functions
1442 'python-comint-output-filter-function)
1443 (add-hook 'comint-output-filter-functions
1444 'python-pdbtrack-comint-output-filter-function)
1445 (set (make-local-variable 'compilation-error-regexp-alist)
1446 python-shell-compilation-regexp-alist)
1447 (define-key inferior-python-mode-map [remap complete-symbol]
1448 'completion-at-point)
1449 (add-hook 'completion-at-point-functions
1450 'python-shell-completion-complete-at-point nil 'local)
1451 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1452 'python-shell-completion-complete-at-point)
1453 (define-key inferior-python-mode-map (kbd "<tab>")
1454 'python-shell-completion-complete-or-indent)
1455 (when python-shell-enable-font-lock
1456 (set (make-local-variable 'font-lock-defaults)
1457 '(python-font-lock-keywords nil nil nil nil))
1458 (set (make-local-variable 'syntax-propertize-function)
1459 python-syntax-propertize-function))
1460 (compilation-shell-minor-mode 1))
1462 (defun python-shell-make-comint (cmd proc-name &optional pop)
1463 "Create a python shell comint buffer.
1464 CMD is the python command to be executed and PROC-NAME is the
1465 process name the comint buffer will get. After the comint buffer
1466 is created the `inferior-python-mode' is activated. If POP is
1467 non-nil the buffer is shown."
1468 (save-excursion
1469 (let* ((proc-buffer-name (format "*%s*" proc-name))
1470 (process-environment (python-shell-calculate-process-environment))
1471 (exec-path (python-shell-calculate-exec-path)))
1472 (when (not (comint-check-proc proc-buffer-name))
1473 (let* ((cmdlist (split-string-and-unquote cmd))
1474 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1475 (cdr cmdlist)))
1476 (current-buffer (current-buffer)))
1477 (with-current-buffer buffer
1478 (inferior-python-mode)
1479 (python-util-clone-local-variables current-buffer))))
1480 (when pop
1481 (pop-to-buffer proc-buffer-name))
1482 proc-buffer-name)))
1484 (defun run-python (dedicated cmd)
1485 "Run an inferior Python process.
1486 Input and output via buffer named after
1487 `python-shell-buffer-name'. If there is a process already
1488 running in that buffer, just switch to it.
1489 With argument, allows you to define DEDICATED, so a dedicated
1490 process for the current buffer is open, and define CMD so you can
1491 edit the command used to call the interpreter (default is value
1492 of `python-shell-interpreter' and arguments defined in
1493 `python-shell-interpreter-args'). Runs the hook
1494 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1495 run).
1496 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1497 (interactive
1498 (if current-prefix-arg
1499 (list
1500 (y-or-n-p "Make dedicated process? ")
1501 (read-string "Run Python: " (python-shell-parse-command)))
1502 (list nil (python-shell-parse-command))))
1503 (python-shell-make-comint cmd (python-shell-get-process-name dedicated))
1504 dedicated)
1506 (defun run-python-internal ()
1507 "Run an inferior Internal Python process.
1508 Input and output via buffer named after
1509 `python-shell-internal-buffer-name' and what
1510 `python-shell-internal-get-process-name' returns. This new kind
1511 of shell is intended to be used for generic communication related
1512 to defined configurations. The main difference with global or
1513 dedicated shells is that these ones are attached to a
1514 configuration, not a buffer. This means that can be used for
1515 example to retrieve the sys.path and other stuff, without messing
1516 with user shells. Runs the hook
1517 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1518 run). \(Type \\[describe-mode] in the process buffer for a list
1519 of commands.)"
1520 (interactive)
1521 (set-process-query-on-exit-flag
1522 (get-buffer-process
1523 (python-shell-make-comint
1524 (python-shell-parse-command)
1525 (python-shell-internal-get-process-name))) nil))
1527 (defun python-shell-get-process ()
1528 "Get inferior Python process for current buffer and return it."
1529 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1530 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1531 (global-proc-name (python-shell-get-process-name nil))
1532 (global-proc-buffer-name (format "*%s*" global-proc-name))
1533 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1534 (global-running (comint-check-proc global-proc-buffer-name)))
1535 ;; Always prefer dedicated
1536 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1537 (and global-running global-proc-buffer-name)))))
1539 (defun python-shell-get-or-create-process ()
1540 "Get or create an inferior Python process for current buffer and return it."
1541 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1542 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1543 (global-proc-name (python-shell-get-process-name nil))
1544 (global-proc-buffer-name (format "*%s*" global-proc-name))
1545 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1546 (global-running (comint-check-proc global-proc-buffer-name))
1547 (current-prefix-arg 4))
1548 (when (and (not dedicated-running) (not global-running))
1549 (if (call-interactively 'run-python)
1550 (setq dedicated-running t)
1551 (setq global-running t)))
1552 ;; Always prefer dedicated
1553 (get-buffer-process (if dedicated-running
1554 dedicated-proc-buffer-name
1555 global-proc-buffer-name))))
1557 (defvar python-shell-internal-buffer nil
1558 "Current internal shell buffer for the current buffer.
1559 This is really not necessary at all for the code to work but it's
1560 there for compatibility with CEDET.")
1561 (make-variable-buffer-local 'python-shell-internal-buffer)
1563 (defun python-shell-internal-get-or-create-process ()
1564 "Get or create an inferior Internal Python process."
1565 (let* ((proc-name (python-shell-internal-get-process-name))
1566 (proc-buffer-name (format "*%s*" proc-name)))
1567 (run-python-internal)
1568 (setq python-shell-internal-buffer proc-buffer-name)
1569 (get-buffer-process proc-buffer-name)))
1571 (define-obsolete-function-alias
1572 'python-proc 'python-shell-internal-get-or-create-process "23.3")
1574 (define-obsolete-variable-alias
1575 'python-buffer 'python-shell-internal-buffer "23.3")
1577 (defun python-shell-send-string (string &optional process msg)
1578 "Send STRING to inferior Python PROCESS.
1579 When MSG is non-nil messages the first line of STRING."
1580 (interactive "sPython command: ")
1581 (let ((process (or process (python-shell-get-or-create-process)))
1582 (lines (split-string string "\n" t)))
1583 (when msg
1584 (message (format "Sent: %s..." (nth 0 lines))))
1585 (if (> (length lines) 1)
1586 (let* ((temp-file-name (make-temp-file "py"))
1587 (file-name (or (buffer-file-name) temp-file-name)))
1588 (with-temp-file temp-file-name
1589 (insert string)
1590 (delete-trailing-whitespace))
1591 (python-shell-send-file file-name process temp-file-name))
1592 (comint-send-string process string)
1593 (when (or (not (string-match "\n$" string))
1594 (string-match "\n[ \t].*\n?$" string))
1595 (comint-send-string process "\n")))))
1597 (defun python-shell-send-string-no-output (string &optional process msg)
1598 "Send STRING to PROCESS and inhibit output.
1599 When MSG is non-nil messages the first line of STRING. Return
1600 the output."
1601 (let* ((output-buffer)
1602 (process (or process (python-shell-get-or-create-process)))
1603 (comint-preoutput-filter-functions
1604 (append comint-preoutput-filter-functions
1605 '(ansi-color-filter-apply
1606 (lambda (string)
1607 (setq output-buffer (concat output-buffer string))
1608 "")))))
1609 (python-shell-send-string string process msg)
1610 (accept-process-output process)
1611 (replace-regexp-in-string
1612 (if (> (length python-shell-prompt-output-regexp) 0)
1613 (format "\n*%s$\\|^%s\\|\n$"
1614 python-shell-prompt-regexp
1615 (or python-shell-prompt-output-regexp ""))
1616 (format "\n*$\\|^%s\\|\n$"
1617 python-shell-prompt-regexp))
1618 "" output-buffer)))
1620 (defun python-shell-internal-send-string (string)
1621 "Send STRING to the Internal Python interpreter.
1622 Returns the output. See `python-shell-send-string-no-output'."
1623 (python-shell-send-string-no-output
1624 ;; Makes this function compatible with the old
1625 ;; python-send-receive. (At least for CEDET).
1626 (replace-regexp-in-string "_emacs_out +" "" string)
1627 (python-shell-internal-get-or-create-process) nil))
1629 (define-obsolete-function-alias
1630 'python-send-receive 'python-shell-internal-send-string "23.3")
1632 (define-obsolete-function-alias
1633 'python-send-string 'python-shell-internal-send-string "23.3")
1635 (defun python-shell-send-region (start end)
1636 "Send the region delimited by START and END to inferior Python process."
1637 (interactive "r")
1638 (python-shell-send-string (buffer-substring start end) nil t))
1640 (defun python-shell-send-buffer (&optional arg)
1641 "Send the entire buffer to inferior Python process.
1643 With prefix ARG include lines surrounded by \"if __name__ == '__main__':\""
1644 (interactive "P")
1645 (save-restriction
1646 (widen)
1647 (python-shell-send-region
1648 (point-min)
1649 (or (and
1650 (not arg)
1651 (save-excursion
1652 (re-search-forward (python-rx if-name-main) nil t))
1653 (match-beginning 0))
1654 (point-max)))))
1656 (defun python-shell-send-defun (arg)
1657 "Send the current defun to inferior Python process.
1658 When argument ARG is non-nil do not include decorators."
1659 (interactive "P")
1660 (save-excursion
1661 (python-shell-send-region
1662 (progn
1663 (end-of-line 1)
1664 (while (and (or (python-beginning-of-defun-function)
1665 (beginning-of-line 1))
1666 (> (current-indentation) 0)))
1667 (when (not arg)
1668 (while (and (forward-line -1)
1669 (looking-at (python-rx decorator))))
1670 (forward-line 1))
1671 (point-marker))
1672 (progn
1673 (or (python-end-of-defun-function)
1674 (end-of-line 1))
1675 (point-marker)))))
1677 (defun python-shell-send-file (file-name &optional process temp-file-name)
1678 "Send FILE-NAME to inferior Python PROCESS.
1679 If TEMP-FILE-NAME is passed then that file is used for processing
1680 instead, while internally the shell will continue to use
1681 FILE-NAME."
1682 (interactive "fFile to send: ")
1683 (let* ((process (or process (python-shell-get-or-create-process)))
1684 (temp-file-name (when temp-file-name
1685 (expand-file-name temp-file-name)))
1686 (file-name (or (expand-file-name file-name) temp-file-name)))
1687 (when (not file-name)
1688 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1689 (python-shell-send-string
1690 (format
1691 (concat "__pyfile = open('''%s''');"
1692 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1693 "__pyfile.close()")
1694 (or temp-file-name file-name) file-name)
1695 process)))
1697 (defun python-shell-switch-to-shell ()
1698 "Switch to inferior Python process buffer."
1699 (interactive)
1700 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1702 (defun python-shell-send-setup-code ()
1703 "Send all setup code for shell.
1704 This function takes the list of setup code to send from the
1705 `python-shell-setup-codes' list."
1706 (let ((msg "Sent %s")
1707 (process (get-buffer-process (current-buffer))))
1708 (accept-process-output process python-shell-send-setup-max-wait)
1709 (dolist (code python-shell-setup-codes)
1710 (when code
1711 (message (format msg code))
1712 (python-shell-send-string
1713 (symbol-value code) process)))))
1715 (add-hook 'inferior-python-mode-hook
1716 #'python-shell-send-setup-code)
1719 ;;; Shell completion
1721 (defcustom python-shell-completion-setup-code
1722 "try:
1723 import readline
1724 except ImportError:
1725 def __COMPLETER_all_completions(text): []
1726 else:
1727 import rlcompleter
1728 readline.set_completer(rlcompleter.Completer().complete)
1729 def __COMPLETER_all_completions(text):
1730 import sys
1731 completions = []
1732 try:
1733 i = 0
1734 while True:
1735 res = readline.get_completer()(text, i)
1736 if not res: break
1737 i += 1
1738 completions.append(res)
1739 except NameError:
1740 pass
1741 return completions"
1742 "Code used to setup completion in inferior Python processes."
1743 :type 'string
1744 :group 'python)
1746 (defcustom python-shell-completion-string-code
1747 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1748 "Python code used to get a string of completions separated by semicolons."
1749 :type 'string
1750 :group 'python)
1752 (defcustom python-shell-completion-module-string-code ""
1753 "Python code used to get completions separated by semicolons for imports.
1755 For IPython v0.11, add the following line to
1756 `python-shell-completion-setup-code':
1758 from IPython.core.completerlib import module_completion
1760 and use the following as the value of this variable:
1762 ';'.join(module_completion('''%s'''))\n"
1763 :type 'string
1764 :group 'python)
1766 (defcustom python-shell-completion-pdb-string-code
1767 "';'.join(globals().keys() + locals().keys())"
1768 "Python code used to get completions separated by semicolons for [i]pdb."
1769 :type 'string
1770 :group 'python)
1772 (defun python-shell-completion--get-completions (input process completion-code)
1773 "Retrieve available completions for INPUT using PROCESS.
1774 Argument COMPLETION-CODE is the python code used to get
1775 completions on the current context."
1776 (with-current-buffer (process-buffer process)
1777 (let ((completions (python-shell-send-string-no-output
1778 (format completion-code input) process)))
1779 (when (> (length completions) 2)
1780 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1782 (defun python-shell-completion--do-completion-at-point (process)
1783 "Do completion at point for PROCESS."
1784 (with-syntax-table python-dotty-syntax-table
1785 (let* ((beg
1786 (save-excursion
1787 (let* ((paren-depth (car (syntax-ppss)))
1788 (syntax-string "w_")
1789 (syntax-list (string-to-syntax syntax-string)))
1790 ;; Stop scanning for the beginning of the completion subject
1791 ;; after the char before point matches a delimiter
1792 (while (member (car (syntax-after (1- (point)))) syntax-list)
1793 (skip-syntax-backward syntax-string)
1794 (when (or (equal (char-before) ?\))
1795 (equal (char-before) ?\"))
1796 (forward-char -1))
1797 (while (or
1798 ;; honor initial paren depth
1799 (> (car (syntax-ppss)) paren-depth)
1800 (python-info-ppss-context 'string))
1801 (forward-char -1))))
1802 (point)))
1803 (end (point))
1804 (line (buffer-substring-no-properties (point-at-bol) end))
1805 (input (buffer-substring-no-properties beg end))
1806 ;; Get the last prompt for the inferior process buffer. This is
1807 ;; used for the completion code selection heuristic.
1808 (prompt
1809 (with-current-buffer (process-buffer process)
1810 (buffer-substring-no-properties
1811 (overlay-start comint-last-prompt-overlay)
1812 (overlay-end comint-last-prompt-overlay))))
1813 (completion-context
1814 ;; Check whether a prompt matches a pdb string, an import statement
1815 ;; or just the standard prompt and use the correct
1816 ;; python-shell-completion-*-code string
1817 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
1818 (string-match
1819 (concat "^" python-shell-prompt-pdb-regexp) prompt))
1820 'pdb)
1821 ((and (>
1822 (length python-shell-completion-module-string-code) 0)
1823 (string-match
1824 (concat "^" python-shell-prompt-regexp) prompt)
1825 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
1826 'import)
1827 ((string-match
1828 (concat "^" python-shell-prompt-regexp) prompt)
1829 'default)
1830 (t nil)))
1831 (completion-code
1832 (case completion-context
1833 ('pdb python-shell-completion-pdb-string-code)
1834 ('import python-shell-completion-module-string-code)
1835 ('default python-shell-completion-string-code)
1836 (t nil)))
1837 (input
1838 (if (eq completion-context 'import)
1839 (replace-regexp-in-string "^[ \t]+" "" line)
1840 input))
1841 (completions
1842 (and completion-code (> (length input) 0)
1843 (python-shell-completion--get-completions
1844 input process completion-code))))
1845 (list beg end completions))))
1847 (defun python-shell-completion-complete-at-point ()
1848 "Perform completion at point in inferior Python process."
1849 (interactive)
1850 (and comint-last-prompt-overlay
1851 (> (point-marker) (overlay-end comint-last-prompt-overlay))
1852 (python-shell-completion--do-completion-at-point
1853 (get-buffer-process (current-buffer)))))
1855 (defun python-shell-completion-complete-or-indent ()
1856 "Complete or indent depending on the context.
1857 If content before pointer is all whitespace indent. If not try
1858 to complete."
1859 (interactive)
1860 (if (string-match "^[[:space:]]*$"
1861 (buffer-substring (comint-line-beginning-position)
1862 (point-marker)))
1863 (indent-for-tab-command)
1864 (completion-at-point)))
1867 ;;; PDB Track integration
1869 (defcustom python-pdbtrack-activate t
1870 "Non-nil makes python shell enable pdbtracking."
1871 :type 'boolean
1872 :group 'python
1873 :safe 'booleanp)
1875 (defcustom python-pdbtrack-stacktrace-info-regexp
1876 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1877 "Regular Expression matching stacktrace information.
1878 Used to extract the current line and module being inspected."
1879 :type 'string
1880 :group 'python
1881 :safe 'stringp)
1883 (defvar python-pdbtrack-tracked-buffer nil
1884 "Variable containing the value of the current tracked buffer.
1885 Never set this variable directly, use
1886 `python-pdbtrack-set-tracked-buffer' instead.")
1887 (make-variable-buffer-local 'python-pdbtrack-tracked-buffer)
1889 (defvar python-pdbtrack-buffers-to-kill nil
1890 "List of buffers to be deleted after tracking finishes.")
1891 (make-variable-buffer-local 'python-pdbtrack-buffers-to-kill)
1893 (defun python-pdbtrack-set-tracked-buffer (file-name)
1894 "Set the buffer for FILE-NAME as the tracked buffer.
1895 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
1896 Returns the tracked buffer."
1897 (let ((file-buffer (get-file-buffer file-name)))
1898 (if file-buffer
1899 (setq python-pdbtrack-tracked-buffer file-buffer)
1900 (setq file-buffer (find-file-noselect file-name))
1901 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
1902 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
1903 file-buffer))
1905 (defun python-pdbtrack-comint-output-filter-function (output)
1906 "Move overlay arrow to current pdb line in tracked buffer.
1907 Argument OUTPUT is a string with the output from the comint process."
1908 (when (and python-pdbtrack-activate (not (string= output "")))
1909 (let* ((full-output (ansi-color-filter-apply
1910 (buffer-substring comint-last-input-end (point-max))))
1911 (line-number)
1912 (file-name
1913 (with-temp-buffer
1914 (insert full-output)
1915 (goto-char (point-min))
1916 ;; OK, this sucked but now it became a cool hack. The
1917 ;; stacktrace information normally is on the first line
1918 ;; but in some cases (like when doing a step-in) it is
1919 ;; on the second.
1920 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
1921 (and
1922 (forward-line)
1923 (looking-at python-pdbtrack-stacktrace-info-regexp)))
1924 (setq line-number (string-to-number
1925 (match-string-no-properties 2)))
1926 (match-string-no-properties 1)))))
1927 (if (and file-name line-number)
1928 (let* ((tracked-buffer
1929 (python-pdbtrack-set-tracked-buffer file-name))
1930 (shell-buffer (current-buffer))
1931 (tracked-buffer-window (get-buffer-window tracked-buffer))
1932 (tracked-buffer-line-pos))
1933 (with-current-buffer tracked-buffer
1934 (set (make-local-variable 'overlay-arrow-string) "=>")
1935 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1936 (setq tracked-buffer-line-pos (progn
1937 (goto-char (point-min))
1938 (forward-line (1- line-number))
1939 (point-marker)))
1940 (when tracked-buffer-window
1941 (set-window-point
1942 tracked-buffer-window tracked-buffer-line-pos))
1943 (set-marker overlay-arrow-position tracked-buffer-line-pos))
1944 (pop-to-buffer tracked-buffer)
1945 (switch-to-buffer-other-window shell-buffer))
1946 (when python-pdbtrack-tracked-buffer
1947 (with-current-buffer python-pdbtrack-tracked-buffer
1948 (set-marker overlay-arrow-position nil))
1949 (mapc #'(lambda (buffer)
1950 (ignore-errors (kill-buffer buffer)))
1951 python-pdbtrack-buffers-to-kill)
1952 (setq python-pdbtrack-tracked-buffer nil
1953 python-pdbtrack-buffers-to-kill nil)))))
1954 output)
1957 ;;; Symbol completion
1959 (defun python-completion-complete-at-point ()
1960 "Complete current symbol at point.
1961 For this to work the best as possible you should call
1962 `python-shell-send-buffer' from time to time so context in
1963 inferior python process is updated properly."
1964 (interactive)
1965 (let ((process (python-shell-get-process)))
1966 (if (not process)
1967 (error "Completion needs an inferior Python process running")
1968 (python-shell-completion--do-completion-at-point process))))
1970 (add-to-list 'debug-ignored-errors
1971 "^Completion needs an inferior Python process running.")
1974 ;;; Fill paragraph
1976 (defcustom python-fill-comment-function 'python-fill-comment
1977 "Function to fill comments.
1978 This is the function used by `python-fill-paragraph-function' to
1979 fill comments."
1980 :type 'symbol
1981 :group 'python
1982 :safe 'symbolp)
1984 (defcustom python-fill-string-function 'python-fill-string
1985 "Function to fill strings.
1986 This is the function used by `python-fill-paragraph-function' to
1987 fill strings."
1988 :type 'symbol
1989 :group 'python
1990 :safe 'symbolp)
1992 (defcustom python-fill-decorator-function 'python-fill-decorator
1993 "Function to fill decorators.
1994 This is the function used by `python-fill-paragraph-function' to
1995 fill decorators."
1996 :type 'symbol
1997 :group 'python
1998 :safe 'symbolp)
2000 (defcustom python-fill-paren-function 'python-fill-paren
2001 "Function to fill parens.
2002 This is the function used by `python-fill-paragraph-function' to
2003 fill parens."
2004 :type 'symbol
2005 :group 'python
2006 :safe 'symbolp)
2008 (defun python-fill-paragraph-function (&optional justify)
2009 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2010 If any of the current line is in or at the end of a multi-line string,
2011 fill the string or the paragraph of it that point is in, preserving
2012 the string's indentation.
2013 Optional argument JUSTIFY defines if the paragraph should be justified."
2014 (interactive "P")
2015 (save-excursion
2016 (back-to-indentation)
2017 (cond
2018 ;; Comments
2019 ((funcall python-fill-comment-function justify))
2020 ;; Strings/Docstrings
2021 ((save-excursion (skip-chars-forward "\"'uUrR")
2022 (python-info-ppss-context 'string))
2023 (funcall python-fill-string-function justify))
2024 ;; Decorators
2025 ((equal (char-after (save-excursion
2026 (back-to-indentation)
2027 (point-marker))) ?@)
2028 (funcall python-fill-decorator-function justify))
2029 ;; Parens
2030 ((or (python-info-ppss-context 'paren)
2031 (looking-at (python-rx open-paren))
2032 (save-excursion
2033 (skip-syntax-forward "^(" (line-end-position))
2034 (looking-at (python-rx open-paren))))
2035 (funcall python-fill-paren-function justify))
2036 (t t))))
2038 (defun python-fill-comment (&optional justify)
2039 "Comment fill function for `python-fill-paragraph-function'.
2040 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2041 (fill-comment-paragraph justify))
2043 (defun python-fill-string (&optional justify)
2044 "String fill function for `python-fill-paragraph-function'.
2045 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2046 (let ((marker (point-marker))
2047 (string-start-marker
2048 (progn
2049 (skip-chars-forward "\"'uUrR")
2050 (goto-char (python-info-ppss-context 'string))
2051 (skip-chars-forward "\"'uUrR")
2052 (point-marker)))
2053 (reg-start (line-beginning-position))
2054 (string-end-marker
2055 (progn
2056 (while (python-info-ppss-context 'string)
2057 (goto-char (1+ (point-marker))))
2058 (skip-chars-backward "\"'")
2059 (point-marker)))
2060 (reg-end (line-end-position))
2061 (fill-paragraph-function))
2062 (save-restriction
2063 (narrow-to-region reg-start reg-end)
2064 (save-excursion
2065 (goto-char string-start-marker)
2066 (delete-region (point-marker) (progn
2067 (skip-syntax-forward "> ")
2068 (point-marker)))
2069 (goto-char string-end-marker)
2070 (delete-region (point-marker) (progn
2071 (skip-syntax-backward "> ")
2072 (point-marker)))
2073 (save-excursion
2074 (goto-char marker)
2075 (fill-paragraph justify))
2076 ;; If there is a newline in the docstring lets put triple
2077 ;; quote in it's own line to follow pep 8
2078 (when (save-excursion
2079 (re-search-backward "\n" string-start-marker t))
2080 (newline)
2081 (newline-and-indent))
2082 (fill-paragraph justify)))) t)
2084 (defun python-fill-decorator (&optional justify)
2085 "Decorator fill function for `python-fill-paragraph-function'.
2086 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2089 (defun python-fill-paren (&optional justify)
2090 "Paren fill function for `python-fill-paragraph-function'.
2091 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2092 (save-restriction
2093 (narrow-to-region (progn
2094 (while (python-info-ppss-context 'paren)
2095 (goto-char (1- (point-marker))))
2096 (point-marker)
2097 (line-beginning-position))
2098 (progn
2099 (when (not (python-info-ppss-context 'paren))
2100 (end-of-line)
2101 (when (not (python-info-ppss-context 'paren))
2102 (skip-syntax-backward "^)")))
2103 (while (python-info-ppss-context 'paren)
2104 (goto-char (1+ (point-marker))))
2105 (point-marker)))
2106 (let ((paragraph-start "\f\\|[ \t]*$")
2107 (paragraph-separate ",")
2108 (fill-paragraph-function))
2109 (goto-char (point-min))
2110 (fill-paragraph justify))
2111 (while (not (eobp))
2112 (forward-line 1)
2113 (python-indent-line)
2114 (goto-char (line-end-position)))) t)
2117 ;;; Skeletons
2119 (defcustom python-skeleton-autoinsert nil
2120 "Non-nil means template skeletons will be automagically inserted.
2121 This happens when pressing \"if<SPACE>\", for example, to prompt for
2122 the if condition."
2123 :type 'boolean
2124 :group 'python
2125 :safe 'booleanp)
2127 (define-obsolete-variable-alias
2128 'python-use-skeletons 'python-skeleton-autoinsert "24.2")
2130 (defvar python-skeleton-available '()
2131 "Internal list of available skeletons.")
2133 (define-abbrev-table 'python-mode-abbrev-table ()
2134 "Abbrev table for Python mode."
2135 :case-fixed t
2136 ;; Allow / inside abbrevs.
2137 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2138 ;; Only expand in code.
2139 :enable-function (lambda ()
2140 (and
2141 (not (or (python-info-ppss-context 'string)
2142 (python-info-ppss-context 'comment)))
2143 python-skeleton-autoinsert)))
2145 (defmacro python-skeleton-define (name doc &rest skel)
2146 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2147 The skeleton will be bound to python-skeleton-NAME and will
2148 be added to `python-mode-abbrev-table'."
2149 (let* ((name (symbol-name name))
2150 (function-name (intern (concat "python-skeleton-" name))))
2151 `(progn
2152 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
2153 (setq python-skeleton-available
2154 (cons ',function-name python-skeleton-available))
2155 (define-skeleton ,function-name
2156 ,(or doc
2157 (format "Insert %s statement." name))
2158 ,@skel))))
2159 (put 'python-skeleton-define 'lisp-indent-function 2)
2161 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2162 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2163 The skeleton will be bound to python-skeleton-NAME."
2164 (let* ((name (symbol-name name))
2165 (function-name (intern (concat "python-skeleton--" name)))
2166 (msg (format
2167 "Add '%s' clause? " name)))
2168 (when (not skel)
2169 (setq skel
2170 `(< ,(format "%s:" name) \n \n
2171 > _ \n)))
2172 `(define-skeleton ,function-name
2173 ,(or doc
2174 (format "Auxiliary skeleton for %s statement." name))
2176 (unless (y-or-n-p ,msg)
2177 (signal 'quit t))
2178 ,@skel)))
2179 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
2181 (python-define-auxiliary-skeleton else nil)
2183 (python-define-auxiliary-skeleton except nil)
2185 (python-define-auxiliary-skeleton finally nil)
2187 (python-skeleton-define if nil
2188 "Condition: "
2189 "if " str ":" \n
2190 _ \n
2191 ("other condition, %s: "
2193 "elif " str ":" \n
2194 > _ \n nil)
2195 '(python-skeleton--else) | ^)
2197 (python-skeleton-define while nil
2198 "Condition: "
2199 "while " str ":" \n
2200 > _ \n
2201 '(python-skeleton--else) | ^)
2203 (python-skeleton-define for nil
2204 "Iteration spec: "
2205 "for " str ":" \n
2206 > _ \n
2207 '(python-skeleton--else) | ^)
2209 (python-skeleton-define try nil
2211 "try:" \n
2212 > _ \n
2213 ("Exception, %s: "
2215 "except " str ":" \n
2216 > _ \n nil)
2217 resume:
2218 '(python-skeleton--except)
2219 '(python-skeleton--else)
2220 '(python-skeleton--finally) | ^)
2222 (python-skeleton-define def nil
2223 "Function name: "
2224 "def " str " (" ("Parameter, %s: "
2225 (unless (equal ?\( (char-before)) ", ")
2226 str) "):" \n
2227 "\"\"\"" - "\"\"\"" \n
2228 > _ \n)
2230 (python-skeleton-define class nil
2231 "Class name: "
2232 "class " str " (" ("Inheritance, %s: "
2233 (unless (equal ?\( (char-before)) ", ")
2234 str)
2235 & ")" | -2
2236 ":" \n
2237 "\"\"\"" - "\"\"\"" \n
2238 > _ \n)
2240 (defun python-skeleton-add-menu-items ()
2241 "Add menu items to Python->Skeletons menu."
2242 (let ((skeletons (sort python-skeleton-available 'string<))
2243 (items))
2244 (dolist (skeleton skeletons)
2245 (easy-menu-add-item
2246 nil '("Python" "Skeletons")
2247 `[,(format
2248 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2249 ,skeleton t]))))
2251 ;;; FFAP
2253 (defcustom python-ffap-setup-code
2254 "def __FFAP_get_module_path(module):
2255 try:
2256 import os
2257 path = __import__(module).__file__
2258 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2259 path = path[:-1]
2260 return path
2261 except:
2262 return ''"
2263 "Python code to get a module path."
2264 :type 'string
2265 :group 'python)
2267 (defcustom python-ffap-string-code
2268 "__FFAP_get_module_path('''%s''')\n"
2269 "Python code used to get a string with the path of a module."
2270 :type 'string
2271 :group 'python)
2273 (defun python-ffap-module-path (module)
2274 "Function for `ffap-alist' to return path for MODULE."
2275 (let ((process (or
2276 (and (eq major-mode 'inferior-python-mode)
2277 (get-buffer-process (current-buffer)))
2278 (python-shell-get-process))))
2279 (if (not process)
2281 (let ((module-file
2282 (python-shell-send-string-no-output
2283 (format python-ffap-string-code module) process)))
2284 (when module-file
2285 (substring-no-properties module-file 1 -1))))))
2287 (eval-after-load "ffap"
2288 '(progn
2289 (push '(python-mode . python-ffap-module-path) ffap-alist)
2290 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2293 ;;; Code check
2295 (defcustom python-check-command
2296 "pyflakes"
2297 "Command used to check a Python file."
2298 :type 'string
2299 :group 'python)
2301 (defcustom python-check-buffer-name
2302 "*Python check: %s*"
2303 "Buffer name used for check commands."
2304 :type 'string
2305 :group 'python)
2307 (defvar python-check-custom-command nil
2308 "Internal use.")
2310 (defun python-check (command)
2311 "Check a Python file (default current buffer's file).
2312 Runs COMMAND, a shell command, as if by `compile'. See
2313 `python-check-command' for the default."
2314 (interactive
2315 (list (read-string "Check command: "
2316 (or python-check-custom-command
2317 (concat python-check-command " "
2318 (shell-quote-argument
2320 (let ((name (buffer-file-name)))
2321 (and name
2322 (file-name-nondirectory name)))
2323 "")))))))
2324 (setq python-check-custom-command command)
2325 (save-some-buffers (not compilation-ask-about-save) nil)
2326 (let ((process-environment (python-shell-calculate-process-environment))
2327 (exec-path (python-shell-calculate-exec-path)))
2328 (compilation-start command nil
2329 (lambda (mode-name)
2330 (format python-check-buffer-name command)))))
2333 ;;; Eldoc
2335 (defcustom python-eldoc-setup-code
2336 "def __PYDOC_get_help(obj):
2337 try:
2338 import inspect
2339 if hasattr(obj, 'startswith'):
2340 obj = eval(obj, globals())
2341 doc = inspect.getdoc(obj)
2342 if not doc and callable(obj):
2343 target = None
2344 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2345 target = obj.__init__
2346 objtype = 'class'
2347 else:
2348 target = obj
2349 objtype = 'def'
2350 if target:
2351 args = inspect.formatargspec(
2352 *inspect.getargspec(target)
2354 name = obj.__name__
2355 doc = '{objtype} {name}{args}'.format(
2356 objtype=objtype, name=name, args=args
2358 else:
2359 doc = doc.splitlines()[0]
2360 except:
2361 doc = ''
2362 try:
2363 exec('print doc')
2364 except SyntaxError:
2365 print(doc)"
2366 "Python code to setup documentation retrieval."
2367 :type 'string
2368 :group 'python)
2370 (defcustom python-eldoc-string-code
2371 "__PYDOC_get_help('''%s''')\n"
2372 "Python code used to get a string with the documentation of an object."
2373 :type 'string
2374 :group 'python)
2376 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2377 "Internal implementation to get documentation at point.
2378 If not FORCE-INPUT is passed then what `current-word' returns
2379 will be used. If not FORCE-PROCESS is passed what
2380 `python-shell-get-process' returns is used."
2381 (let ((process (or force-process (python-shell-get-process))))
2382 (if (not process)
2383 "Eldoc needs an inferior Python process running."
2384 (let* ((current-defun (python-info-current-defun))
2385 (input (or force-input
2386 (with-syntax-table python-dotty-syntax-table
2387 (if (not current-defun)
2388 (current-word)
2389 (concat current-defun "." (current-word))))))
2390 (ppss (syntax-ppss))
2391 (help (when (and
2392 input
2393 (not (string= input (concat current-defun ".")))
2394 (not (or (python-info-ppss-context 'string ppss)
2395 (python-info-ppss-context 'comment ppss))))
2396 (when (string-match
2397 (concat
2398 (regexp-quote (concat current-defun "."))
2399 "self\\.") input)
2400 (with-temp-buffer
2401 (insert input)
2402 (goto-char (point-min))
2403 (forward-word)
2404 (forward-char)
2405 (delete-region
2406 (point-marker) (search-forward "self."))
2407 (setq input (buffer-substring
2408 (point-min) (point-max)))))
2409 (python-shell-send-string-no-output
2410 (format python-eldoc-string-code input) process))))
2411 (with-current-buffer (process-buffer process)
2412 (when comint-last-prompt-overlay
2413 (delete-region comint-last-input-end
2414 (overlay-start comint-last-prompt-overlay))))
2415 (when (and help
2416 (not (string= help "\n")))
2417 help)))))
2419 (defun python-eldoc-function ()
2420 "`eldoc-documentation-function' for Python.
2421 For this to work the best as possible you should call
2422 `python-shell-send-buffer' from time to time so context in
2423 inferior python process is updated properly."
2424 (python-eldoc--get-doc-at-point))
2426 (defun python-eldoc-at-point (symbol)
2427 "Get help on SYMBOL using `help'.
2428 Interactively, prompt for symbol."
2429 (interactive
2430 (let ((symbol (with-syntax-table python-dotty-syntax-table
2431 (current-word)))
2432 (enable-recursive-minibuffers t))
2433 (list (read-string (if symbol
2434 (format "Describe symbol (default %s): " symbol)
2435 "Describe symbol: ")
2436 nil nil symbol))))
2437 (let ((process (python-shell-get-process)))
2438 (if (not process)
2439 (message "Eldoc needs an inferior Python process running.")
2440 (message (python-eldoc--get-doc-at-point symbol process)))))
2443 ;;; Imenu
2445 (defcustom python-imenu-include-defun-type t
2446 "Non-nil make imenu items to include its type."
2447 :type 'boolean
2448 :group 'python
2449 :safe 'booleanp)
2451 (defcustom python-imenu-make-tree t
2452 "Non-nil make imenu to build a tree menu.
2453 Set to nil for speed."
2454 :type 'boolean
2455 :group 'python
2456 :safe 'booleanp)
2458 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2459 "Label displayed to navigate to root from a subtree.
2460 It can contain a \"%s\" which will be replaced with the root name."
2461 :type 'string
2462 :group 'python
2463 :safe 'stringp)
2465 (defvar python-imenu-index-alist nil
2466 "Calculated index tree for imenu.")
2468 (defun python-imenu-tree-assoc (keylist tree)
2469 "Using KEYLIST traverse TREE."
2470 (if keylist
2471 (python-imenu-tree-assoc (cdr keylist)
2472 (ignore-errors (assoc (car keylist) tree)))
2473 tree))
2475 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2476 "Make a tree from plain alist of module names.
2477 ELEMENT-LIST is the defun name split by \".\" and FULL-ELEMENT
2478 is the same thing, the difference is that FULL-ELEMENT remains
2479 untouched in all recursive calls.
2480 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2481 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2482 (when element-list
2483 (let* ((subelement-point (cdr (assoc
2484 (mapconcat #'identity full-element ".")
2485 plain-index)))
2486 (subelement-name (car element-list))
2487 (subelement-position (python-util-position
2488 subelement-name full-element))
2489 (subelement-path (when subelement-position
2490 (butlast
2491 full-element
2492 (- (length full-element)
2493 subelement-position)))))
2494 (let ((path-ref (python-imenu-tree-assoc subelement-path
2495 python-imenu-index-alist)))
2496 (if (not path-ref)
2497 (push (cons subelement-name subelement-point)
2498 python-imenu-index-alist)
2499 (when (not (listp (cdr path-ref)))
2500 ;; Modify root cdr to be a list.
2501 (setcdr path-ref
2502 (list (cons (format python-imenu-subtree-root-label
2503 (car path-ref))
2504 (cdr (assoc
2505 (mapconcat #'identity
2506 subelement-path ".")
2507 plain-index))))))
2508 (when (not (assoc subelement-name path-ref))
2509 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2510 (python-imenu-make-element-tree (cdr element-list)
2511 full-element plain-index))))
2513 (defun python-imenu-make-tree (index)
2514 "Build the imenu alist tree from plain INDEX.
2516 The idea of this function is that given the alist:
2518 '((\"Test\" . 100)
2519 (\"Test.__init__\" . 200)
2520 (\"Test.some_method\" . 300)
2521 (\"Test.some_method.another\" . 400)
2522 (\"Test.something_else\" . 500)
2523 (\"test\" . 600)
2524 (\"test.reprint\" . 700)
2525 (\"test.reprint\" . 800))
2527 This tree gets built:
2529 '((\"Test\" . ((\"jump to...\" . 100)
2530 (\"__init__\" . 200)
2531 (\"some_method\" . ((\"jump to...\" . 300)
2532 (\"another\" . 400)))
2533 (\"something_else\" . 500)))
2534 (\"test\" . ((\"jump to...\" . 600)
2535 (\"reprint\" . 700)
2536 (\"reprint\" . 800))))
2538 Internally it uses `python-imenu-make-element-tree' to create all
2539 branches for each element."
2540 (setq python-imenu-index-alist nil)
2541 (mapc (lambda (element)
2542 (python-imenu-make-element-tree element element index))
2543 (mapcar (lambda (element)
2544 (split-string (car element) "\\." t)) index))
2545 python-imenu-index-alist)
2547 (defun python-imenu-create-index ()
2548 "`imenu-create-index-function' for Python."
2549 (let ((index
2550 (python-nav-list-defun-positions python-imenu-include-defun-type)))
2551 (if python-imenu-make-tree
2552 (python-imenu-make-tree index)
2553 index)))
2556 ;;; Misc helpers
2558 (defun python-info-current-defun (&optional include-type)
2559 "Return name of surrounding function with Python compatible dotty syntax.
2560 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2561 This function is compatible to be used as
2562 `add-log-current-defun-function' since it returns nil if point is
2563 not inside a defun."
2564 (let ((names '())
2565 (min-indent)
2566 (first-run t))
2567 (save-restriction
2568 (widen)
2569 (save-excursion
2570 (end-of-line 1)
2571 (setq min-indent (current-indentation))
2572 (while (python-beginning-of-defun-function 1)
2573 (when (or (< (current-indentation) min-indent)
2574 first-run)
2575 (setq first-run nil)
2576 (setq min-indent (current-indentation))
2577 (looking-at python-nav-beginning-of-defun-regexp)
2578 (setq names (cons
2579 (if (not include-type)
2580 (match-string-no-properties 1)
2581 (mapconcat 'identity
2582 (split-string
2583 (match-string-no-properties 0)) " "))
2584 names))))))
2585 (when names
2586 (mapconcat (lambda (string) string) names "."))))
2588 (defun python-info-closing-block ()
2589 "Return the point of the block the current line closes."
2590 (let ((closing-word (save-excursion
2591 (back-to-indentation)
2592 (current-word)))
2593 (indentation (current-indentation)))
2594 (when (member closing-word python-indent-dedenters)
2595 (save-excursion
2596 (forward-line -1)
2597 (while (and (> (current-indentation) indentation)
2598 (not (bobp))
2599 (not (back-to-indentation))
2600 (forward-line -1)))
2601 (back-to-indentation)
2602 (cond
2603 ((not (equal indentation (current-indentation))) nil)
2604 ((string= closing-word "elif")
2605 (when (member (current-word) '("if" "elif"))
2606 (point-marker)))
2607 ((string= closing-word "else")
2608 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2609 (point-marker)))
2610 ((string= closing-word "except")
2611 (when (member (current-word) '("try"))
2612 (point-marker)))
2613 ((string= closing-word "finally")
2614 (when (member (current-word) '("except" "else"))
2615 (point-marker))))))))
2617 (defun python-info-closing-block-message (&optional closing-block-point)
2618 "Message the contents of the block the current line closes.
2619 With optional argument CLOSING-BLOCK-POINT use that instead of
2620 recalculating it calling `python-info-closing-block'."
2621 (let ((point (or closing-block-point (python-info-closing-block))))
2622 (when point
2623 (save-restriction
2624 (widen)
2625 (message "Closes %s" (save-excursion
2626 (goto-char point)
2627 (back-to-indentation)
2628 (buffer-substring
2629 (point) (line-end-position))))))))
2631 (defun python-info-line-ends-backslash-p (&optional line-number)
2632 "Return non-nil if current line ends with backslash.
2633 With optional argument LINE-NUMBER, check that line instead."
2634 (save-excursion
2635 (save-restriction
2636 (widen)
2637 (when line-number
2638 (goto-char line-number))
2639 (while (and (not (eobp))
2640 (goto-char (line-end-position))
2641 (python-info-ppss-context 'paren)
2642 (not (equal (char-before (point)) ?\\)))
2643 (forward-line 1))
2644 (when (equal (char-before) ?\\)
2645 (point-marker)))))
2647 (defun python-info-beginning-of-backslash (&optional line-number)
2648 "Return the point where the backslashed line start.
2649 Optional argument LINE-NUMBER forces the line number to check against."
2650 (save-excursion
2651 (save-restriction
2652 (widen)
2653 (when line-number
2654 (goto-char line-number))
2655 (when (python-info-line-ends-backslash-p)
2656 (while (save-excursion
2657 (goto-char (line-beginning-position))
2658 (python-info-ppss-context 'paren))
2659 (forward-line -1))
2660 (back-to-indentation)
2661 (point-marker)))))
2663 (defun python-info-continuation-line-p ()
2664 "Check if current line is continuation of another.
2665 When current line is continuation of another return the point
2666 where the continued line ends."
2667 (save-excursion
2668 (save-restriction
2669 (widen)
2670 (let* ((context-type (progn
2671 (back-to-indentation)
2672 (python-info-ppss-context-type)))
2673 (line-start (line-number-at-pos))
2674 (context-start (when context-type
2675 (python-info-ppss-context context-type))))
2676 (cond ((equal context-type 'paren)
2677 ;; Lines inside a paren are always a continuation line
2678 ;; (except the first one).
2679 (when (equal (python-info-ppss-context-type) 'paren)
2680 (python-util-forward-comment -1)
2681 (python-util-forward-comment -1)
2682 (point-marker)))
2683 ((or (equal context-type 'comment)
2684 (equal context-type 'string))
2685 ;; move forward an roll again
2686 (goto-char context-start)
2687 (python-util-forward-comment)
2688 (python-info-continuation-line-p))
2690 ;; Not within a paren, string or comment, the only way we are
2691 ;; dealing with a continuation line is that previous line
2692 ;; contains a backslash, and this can only be the previous line
2693 ;; from current
2694 (back-to-indentation)
2695 (python-util-forward-comment -1)
2696 (python-util-forward-comment -1)
2697 (when (and (equal (1- line-start) (line-number-at-pos))
2698 (python-info-line-ends-backslash-p))
2699 (point-marker))))))))
2701 (defun python-info-block-continuation-line-p ()
2702 "Return non-nil if current line is a continuation of a block."
2703 (save-excursion
2704 (when (python-info-continuation-line-p)
2705 (forward-line -1)
2706 (back-to-indentation)
2707 (when (looking-at (python-rx block-start))
2708 (point-marker)))))
2710 (defun python-info-assignment-continuation-line-p ()
2711 "Check if current line is a continuation of an assignment.
2712 When current line is continuation of another with an assignment
2713 return the point of the first non-blank character after the
2714 operator."
2715 (save-excursion
2716 (when (python-info-continuation-line-p)
2717 (forward-line -1)
2718 (back-to-indentation)
2719 (when (and (not (looking-at (python-rx block-start)))
2720 (and (re-search-forward (python-rx not-simple-operator
2721 assignment-operator
2722 not-simple-operator)
2723 (line-end-position) t)
2724 (not (or (python-info-ppss-context 'string)
2725 (python-info-ppss-context 'paren)
2726 (python-info-ppss-context 'comment)))))
2727 (skip-syntax-forward "\s")
2728 (point-marker)))))
2730 (defun python-info-ppss-context (type &optional syntax-ppss)
2731 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2732 TYPE can be 'comment, 'string or 'paren. It returns the start
2733 character address of the specified TYPE."
2734 (let ((ppss (or syntax-ppss (syntax-ppss))))
2735 (case type
2736 ('comment
2737 (and (nth 4 ppss)
2738 (nth 8 ppss)))
2739 ('string
2740 (nth 8 ppss))
2741 ('paren
2742 (nth 1 ppss))
2743 (t nil))))
2745 (defun python-info-ppss-context-type (&optional syntax-ppss)
2746 "Return the context type using SYNTAX-PPSS.
2747 The type returned can be 'comment, 'string or 'paren."
2748 (let ((ppss (or syntax-ppss (syntax-ppss))))
2749 (cond
2750 ((and (nth 4 ppss)
2751 (nth 8 ppss))
2752 'comment)
2753 ((nth 8 ppss)
2754 'string)
2755 ((nth 1 ppss)
2756 'paren)
2757 (t nil))))
2759 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
2760 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2761 (and (not (python-info-ppss-context-type (or syntax-ppss (syntax-ppss))))
2762 (save-excursion
2763 (beginning-of-line 1)
2764 (looking-at python-nav-beginning-of-defun-regexp))))
2767 ;;; Utility functions
2769 (defun python-util-position (item seq)
2770 "Find the first occurrence of ITEM in SEQ.
2771 Return the index of the matching item, or nil if not found."
2772 (let ((member-result (member item seq)))
2773 (when member-result
2774 (- (length seq) (length member-result)))))
2776 ;; Stolen from org-mode
2777 (defun python-util-clone-local-variables (from-buffer &optional regexp)
2778 "Clone local variables from FROM-BUFFER.
2779 Optional argument REGEXP selects variables to clone and defaults
2780 to \"^python-\"."
2781 (mapc
2782 (lambda (pair)
2783 (and (symbolp (car pair))
2784 (string-match (or regexp "^python-")
2785 (symbol-name (car pair)))
2786 (set (make-local-variable (car pair))
2787 (cdr pair))))
2788 (buffer-local-variables from-buffer)))
2790 (defun python-util-forward-comment (&optional direction)
2791 "Python mode specific version of `forward-comment'.
2792 Optional argument DIRECTION defines the direction to move to."
2793 (let ((comment-start (python-info-ppss-context 'comment))
2794 (factor (if (< (or direction 0) 0)
2795 -99999
2796 99999)))
2797 (when comment-start
2798 (goto-char comment-start))
2799 (forward-comment factor)))
2802 ;;;###autoload
2803 (define-derived-mode python-mode fundamental-mode "Python"
2804 "Major mode for editing Python files.
2806 \\{python-mode-map}
2807 Entry to this mode calls the value of `python-mode-hook'
2808 if that value is non-nil."
2809 (set (make-local-variable 'tab-width) 8)
2810 (set (make-local-variable 'indent-tabs-mode) nil)
2812 (set (make-local-variable 'comment-start) "# ")
2813 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2815 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2816 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2818 (set (make-local-variable 'font-lock-defaults)
2819 '(python-font-lock-keywords nil nil nil nil))
2821 (set (make-local-variable 'syntax-propertize-function)
2822 python-syntax-propertize-function)
2824 (set (make-local-variable 'indent-line-function)
2825 #'python-indent-line-function)
2826 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2828 (set (make-local-variable 'paragraph-start) "\\s-*$")
2829 (set (make-local-variable 'fill-paragraph-function)
2830 'python-fill-paragraph-function)
2832 (set (make-local-variable 'beginning-of-defun-function)
2833 #'python-beginning-of-defun-function)
2834 (set (make-local-variable 'end-of-defun-function)
2835 #'python-end-of-defun-function)
2837 (add-hook 'completion-at-point-functions
2838 'python-completion-complete-at-point nil 'local)
2840 (add-hook 'post-self-insert-hook
2841 'python-indent-post-self-insert-function nil 'local)
2843 (setq imenu-create-index-function #'python-imenu-create-index)
2845 (set (make-local-variable 'add-log-current-defun-function)
2846 #'python-info-current-defun)
2848 (add-hook 'which-func-functions #'python-info-current-defun nil t)
2850 (set (make-local-variable 'skeleton-further-elements)
2851 '((abbrev-mode nil)
2852 (< '(backward-delete-char-untabify (min python-indent-offset
2853 (current-column))))
2854 (^ '(- (1+ (current-indentation))))))
2856 (set (make-local-variable 'eldoc-documentation-function)
2857 #'python-eldoc-function)
2859 (add-to-list 'hs-special-modes-alist
2860 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2861 ,(lambda (arg)
2862 (python-end-of-defun-function)) nil))
2864 (set (make-local-variable 'mode-require-final-newline) t)
2866 (set (make-local-variable 'outline-regexp)
2867 (python-rx (* space) block-start))
2868 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2869 (set (make-local-variable 'outline-level)
2870 #'(lambda ()
2871 "`outline-level' function for Python mode."
2872 (1+ (/ (current-indentation) python-indent-offset))))
2874 (python-skeleton-add-menu-items)
2876 (when python-indent-guess-indent-offset
2877 (python-indent-guess-indent-offset)))
2880 (provide 'python)
2881 ;;; python.el ends here