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