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>
10 ;; This file is NOT part of GNU Emacs.
12 ;; python.el is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; python.el is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with python.el. If not, see <http://www.gnu.org/licenses/>.
27 ;; Major mode for editing Python files with some fontification and
28 ;; indentation bits extracted from original Dave Love's python.el
29 ;; found in GNU/Emacs.
31 ;; While it probably has less features than Dave Love's python.el and
32 ;; PSF's python-mode.el it provides the main stuff you'll need while
33 ;; keeping it simple :)
35 ;; Implements Syntax highlighting, Indentation, Movement, Shell
36 ;; interaction, Shell completion, Pdb tracking, Symbol completion,
37 ;; Skeletons, FFAP, Code Check, Eldoc, imenu.
39 ;; Syntax highlighting: Fontification of code is provided and supports
40 ;; python's triple quoted strings properly.
42 ;; Indentation: Automatic indentation with indentation cycling is
43 ;; provided, it allows you to navigate different available levels of
44 ;; indentation by hitting <tab> several times. Also when inserting a
45 ;; colon the `python-indent-electric-colon' command is invoked and
46 ;; causes the current line to be dedented automatically if needed.
48 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
49 ;; properly implemented. Also there are specialized
50 ;; `forward-sentence' and `backward-sentence' replacements
51 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
52 ;; respectively). Extra functions `python-nav-sentence-start' and
53 ;; `python-nav-sentence-end' are included to move to the beginning and
54 ;; to the end of a setence while taking care of multiline definitions.
56 ;; Shell interaction: is provided and allows you easily execute any
57 ;; block of code of your current buffer in an inferior Python process.
59 ;; Shell completion: hitting tab will try to complete the current
60 ;; word. Shell completion is implemented in a manner that if you
61 ;; change the `python-shell-interpreter' to any other (for example
62 ;; IPython) it should be easy to integrate another way to calculate
63 ;; completions. You just need to specify your custom
64 ;; `python-shell-completion-setup-code' and
65 ;; `python-shell-completion-string-code'.
67 ;; Here is a complete example of the settings you would use for
71 ;; python-shell-interpreter "ipython"
72 ;; python-shell-interpreter-args ""
73 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
74 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
75 ;; python-shell-completion-setup-code ""
76 ;; python-shell-completion-string-code
77 ;; "';'.join(__IP.complete('''%s'''))\n")
79 ;; Please note that the default completion system depends on the
80 ;; readline module, so if you are using some Operating System that
81 ;; bundles Python without it (like Windows) just install the
82 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
83 ;; you should be good to go.
85 ;; The shell also contains support for virtualenvs and other special
86 ;; environment modification thanks to
87 ;; `python-shell-process-environment' and `python-shell-exec-path'.
88 ;; These two variables allows you to modify execution paths and
89 ;; enviroment variables to make easy for you to setup virtualenv rules
90 ;; or behaviors modifications when running shells. Here is an example
91 ;; of how to make shell processes to be run using the /path/to/env/
94 ;; (setq python-shell-process-environment
96 ;; (format "PATH=%s" (mapconcat
99 ;; (cons (getenv "PATH")
100 ;; '("/path/to/env/bin/")))
102 ;; "VIRTUAL_ENV=/path/to/env/"))
103 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
105 ;; Pdb tracking: when you execute a block of code that contains some
106 ;; call to pdb (or ipdb) it will prompt the block of code and will
107 ;; follow the execution of pdb marking the current line with an arrow.
109 ;; Symbol completion: you can complete the symbol at point. It uses
110 ;; the shell completion in background so you should run
111 ;; `python-shell-send-buffer' from time to time to get better results.
113 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
114 ;; def, for, if, try and while. These skeletons are integrated with
115 ;; dabbrev. If you have `dabbrev-mode' activated and
116 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
117 ;; the name of any of those defined and hit SPC, they will be
118 ;; automatically expanded.
120 ;; FFAP: You can find the filename for a given module when using ffap
121 ;; out of the box. This feature needs an inferior python shell
124 ;; Code check: Check the current file for errors with `python-check'
125 ;; using the program defined in `python-check-command'.
127 ;; Eldoc: returns documentation for object at point by using the
128 ;; inferior python subprocess to inspect its documentation. As you
129 ;; might guessed you should run `python-shell-send-buffer' from time
130 ;; to time to get better results too.
132 ;; imenu: This mode supports imenu. It builds a plain or tree menu
133 ;; depending on the value of `python-imenu-make-tree'. Also you can
134 ;; customize if menu items should include its type using
135 ;; `python-imenu-include-defun-type'.
137 ;; If you used python-mode.el you probably will miss auto-indentation
138 ;; when inserting newlines. To achieve the same behavior you have
141 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
143 ;; 2) Add the following hook in your .emacs:
145 ;; (add-hook 'python-mode-hook
147 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
149 ;; I'd recommend the first one since you'll get the same behavior for
150 ;; all modes out-of-the-box.
154 ;; Add this to your .emacs:
156 ;; (add-to-list 'load-path "/folder/containing/file")
161 ;; Ordered by priority:
163 ;; Better decorator support for beginning of defun
165 ;; Review code and cleanup
169 (require 'ansi-color)
174 ;; Avoid compiler warnings
175 (defvar view-return-to-alist)
176 (defvar compilation-error-regexp-alist)
177 (defvar outline-heading-end-regexp))
179 (autoload 'comint-mode "comint")
182 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
184 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
187 "Python Language's flying circus support for Emacs."
190 :link '(emacs-commentary-link "python"))
195 (defvar python-mode-map
196 (let ((map (make-sparse-keymap)))
198 (substitute-key-definition 'backward-sentence
199 'python-nav-backward-sentence
201 (substitute-key-definition 'forward-sentence
202 'python-nav-forward-sentence
205 (define-key map "\177" 'python-indent-dedent-line-backspace)
206 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
207 (define-key map "\C-c<" 'python-indent-shift-left)
208 (define-key map "\C-c>" 'python-indent-shift-right)
209 (define-key map ":" 'python-indent-electric-colon)
211 (define-key map "\C-c\C-tc" 'python-skeleton-class)
212 (define-key map "\C-c\C-td" 'python-skeleton-def)
213 (define-key map "\C-c\C-tf" 'python-skeleton-for)
214 (define-key map "\C-c\C-ti" 'python-skeleton-if)
215 (define-key map "\C-c\C-tt" 'python-skeleton-try)
216 (define-key map "\C-c\C-tw" 'python-skeleton-while)
218 (define-key map "\C-c\C-s" 'python-shell-send-string)
219 (define-key map "\C-c\C-r" 'python-shell-send-region)
220 (define-key map "\C-\M-x" 'python-shell-send-defun)
221 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
222 (define-key map "\C-c\C-l" 'python-shell-send-file)
223 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
224 ;; Some util commands
225 (define-key map "\C-c\C-v" 'python-check)
226 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
228 (substitute-key-definition 'complete-symbol 'completion-at-point
230 (easy-menu-define python-menu map "Python Mode menu"
232 :help "Python-specific Features"
233 ["Shift region left" python-indent-shift-left :active mark-active
234 :help "Shift region left by a single indentation step"]
235 ["Shift region right" python-indent-shift-right :active mark-active
236 :help "Shift region right by a single indentation step"]
238 ["Mark def/class" mark-defun
239 :help "Mark outermost definition around point"]
241 ["Start of def/class" beginning-of-defun
242 :help "Go to start of outermost definition around point"]
243 ["End of def/class" end-of-defun
244 :help "Go to end of definition around point"]
248 ["Start interpreter" run-python
249 :help "Run inferior Python process in a separate buffer"]
250 ["Switch to shell" python-shell-switch-to-shell
251 :help "Switch to running inferior Python process"]
252 ["Eval string" python-shell-send-string
253 :help "Eval string in inferior Python session"]
254 ["Eval buffer" python-shell-send-buffer
255 :help "Eval buffer in inferior Python session"]
256 ["Eval region" python-shell-send-region
257 :help "Eval region in inferior Python session"]
258 ["Eval defun" python-shell-send-defun
259 :help "Eval defun in inferior Python session"]
260 ["Eval file" python-shell-send-file
261 :help "Eval file in inferior Python session"]
262 ["Debugger" pdb :help "Run pdb under GUD"]
264 ["Check file" python-check
265 :help "Check file for errors"]
266 ["Help on symbol" python-eldoc-at-point
267 :help "Get help on symbol at point"]
268 ["Complete symbol" completion-at-point
269 :help "Complete symbol before point"]))
271 "Keymap for `python-mode'.")
274 ;;; Python specialized rx
277 (defconst python-rx-constituents
279 `(block-start . ,(rx symbol-start
280 (or "def" "class" "if" "elif" "else" "try"
281 "except" "finally" "for" "while" "with")
283 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
285 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
286 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
287 `(open-paren . ,(rx (or "{" "[" "(")))
288 `(close-paren . ,(rx (or "}" "]" ")")))
289 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
290 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
291 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
292 "=" "%" "**" "//" "<<" ">>" "<=" "!="
293 "==" ">=" "is" "not")))
294 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
295 ">>=" "<<=" "&=" "^=" "|="))))
296 "Additional Python specific sexps for `python-rx'"))
298 (defmacro python-rx (&rest regexps)
299 "Python mode specialized rx macro which supports common python named REGEXPS."
300 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
301 (cond ((null regexps)
304 (rx-to-string `(and ,@regexps) t))
306 (rx-to-string (car regexps) t)))))
309 ;;; Font-lock and syntax
311 (defvar python-font-lock-keywords
314 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
315 "assert" "else" "if" "pass" "yield" "break" "except" "import"
316 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
317 "return" "def" "for" "lambda" "try" "self")
320 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
321 (1 font-lock-function-name-face))
323 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
324 (1 font-lock-type-face))
326 (,(rx symbol-start (group "None" symbol-end))
327 (1 font-lock-constant-face))
329 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
330 (0+ "." (1+ (or word ?_)))))
331 (1 font-lock-type-face))
332 ;; Builtin Exceptions
334 (or "ArithmeticError" "AssertionError" "AttributeError"
335 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
336 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
337 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
338 "ImportWarning" "IndentationError" "IndexError" "KeyError"
339 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
340 "NotImplemented" "NotImplementedError" "OSError" "OverflowError"
341 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
342 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
343 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
344 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
345 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
346 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
347 symbol-end) . font-lock-type-face)
349 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
351 (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
352 "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer"
353 "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce"
354 "compile" "complex" "copyright" "credits" "delattr" "dict" "dir"
355 "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter"
356 "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash"
357 "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
358 "iter" "len" "license" "list" "locals" "long" "map" "max" "min"
359 "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit"
360 "range" "raw_input" "reduce" "reload" "repr" "reversed" "round"
361 "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum"
362 "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip"
363 "True" "False" "Ellipsis")) symbol-end)
364 (1 font-lock-builtin-face))
366 ;; support for a = b = c = 5
368 (let ((re (python-rx (group (+ (any word ?. ?_)))
369 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
370 assignment-operator)))
371 (when (re-search-forward re limit t)
372 (while (and (python-info-ppss-context 'paren)
373 (re-search-forward re limit t)))
374 (if (and (not (python-info-ppss-context 'paren))
375 (not (equal (char-after (point-marker)) ?=)))
377 (set-match-data nil)))))
378 (1 font-lock-variable-name-face nil nil))
379 ;; support for a, b, c = (1, 2, 3)
381 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
382 (* ?, (* space) (+ (any word ?. ?_)) (* space))
383 ?, (* space) (+ (any word ?. ?_)) (* space)
384 assignment-operator)))
385 (when (and (re-search-forward re limit t)
386 (goto-char (nth 3 (match-data))))
387 (while (and (python-info-ppss-context 'paren)
388 (re-search-forward re limit t))
389 (goto-char (nth 3 (match-data))))
390 (if (not (python-info-ppss-context 'paren))
392 (set-match-data nil)))))
393 (1 font-lock-variable-name-face nil nil))))
395 ;; Fixme: Is there a better way?
396 (defconst python-font-lock-syntactic-keywords
397 ;; First avoid a sequence preceded by an odd number of backslashes.
398 `((,(rx (not (any ?\\))
399 ?\\ (* (and ?\\ ?\\))
400 (group (syntax string-quote))
403 (2 ,(string-to-syntax "\""))) ; dummy
404 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
405 (optional (any "rR")) ; possible second prefix
406 (group (syntax string-quote)) ; maybe gets property
407 (backref 2) ; per first quote
408 (group (backref 2))) ; maybe gets property
409 (1 (python-quote-syntax 1))
410 (2 (python-quote-syntax 2))
411 (3 (python-quote-syntax 3))))
412 "Make outer chars of triple-quote strings into generic string delimiters.")
414 (defun python-quote-syntax (n)
415 "Put `syntax-table' property correctly on triple quote.
416 Used for syntactic keywords. N is the match number (1, 2 or 3)."
417 ;; Given a triple quote, we have to check the context to know
418 ;; whether this is an opening or closing triple or whether it's
419 ;; quoted anyhow, and should be ignored. (For that we need to do
420 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
421 ;; to use it here despite initial worries.) We also have to sort
422 ;; out a possible prefix -- well, we don't _have_ to, but I think it
423 ;; should be treated as part of the string.
426 ;; ur"""ar""" x='"' # """
429 ;; x '"""' x """ \"""" x
431 (goto-char (match-beginning 0))
433 ;; Consider property for the last char if in a fenced string.
435 (let* ((font-lock-syntactic-keywords nil)
436 (syntax (syntax-ppss)))
437 (when (eq t (nth 3 syntax)) ; after unclosed fence
438 (goto-char (nth 8 syntax)) ; fence position
439 (skip-chars-forward "uUrR") ; skip any prefix
440 ;; Is it a matching sequence?
441 (if (eq (char-after) (char-after (match-beginning 2)))
442 (eval-when-compile (string-to-syntax "|"))))))
443 ;; Consider property for initial char, accounting for prefixes.
444 ((or (and (= n 2) ; leading quote (not prefix)
445 (= (match-beginning 1) (match-end 1))) ; prefix is null
446 (and (= n 1) ; prefix
447 (/= (match-beginning 1) (match-end 1)))) ; non-empty
448 (let ((font-lock-syntactic-keywords nil))
449 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
450 (eval-when-compile (string-to-syntax "|")))))
451 ;; Otherwise (we're in a non-matching string) the property is
455 (defvar python-mode-syntax-table
456 (let ((table (make-syntax-table)))
457 ;; Give punctuation syntax to ASCII that normally has symbol
458 ;; syntax or has word syntax and isn't a letter.
459 (let ((symbol (string-to-syntax "_"))
460 (sst (standard-syntax-table)))
463 (if (equal symbol (aref sst i))
464 (modify-syntax-entry i "." table)))))
465 (modify-syntax-entry ?$ "." table)
466 (modify-syntax-entry ?% "." table)
468 (modify-syntax-entry ?# "<" table)
469 (modify-syntax-entry ?\n ">" table)
470 (modify-syntax-entry ?' "\"" table)
471 (modify-syntax-entry ?` "$" table)
473 "Syntax table for Python files.")
475 (defvar python-dotty-syntax-table
476 (let ((table (make-syntax-table python-mode-syntax-table)))
477 (modify-syntax-entry ?. "w" table)
478 (modify-syntax-entry ?_ "w" table)
480 "Dotty syntax table for Python files.
481 It makes underscores and dots word constituent chars.")
486 (defcustom python-indent-offset 4
487 "Default indentation offset for Python."
492 (defcustom python-indent-guess-indent-offset t
493 "Non-nil tells Python mode to guess `python-indent-offset' value."
497 (defvar python-indent-current-level 0
498 "Current indentation level `python-indent-line-function' is using.")
500 (defvar python-indent-levels '(0)
501 "Levels of indentation available for `python-indent-line-function'.")
503 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
504 "List of words that should be dedented.
505 These make `python-indent-calculate-indentation' subtract the value of
506 `python-indent-offset'.")
508 (defun python-indent-guess-indent-offset ()
509 "Guess and set `python-indent-offset' for the current buffer."
513 (goto-char (point-min))
515 (while (and (not found-block)
517 (python-rx line-start block-start) nil t))
518 (when (and (not (python-info-ppss-context 'string))
519 (not (python-info-ppss-context 'comment))
521 (goto-char (line-end-position))
522 (forward-comment -9999)
523 (eq ?: (char-before))))
524 (setq found-block t)))
525 (if (not found-block)
526 (message "Can't guess python-indent-offset, using defaults: %s"
527 python-indent-offset)
529 (goto-char (line-end-position))
530 (python-info-continuation-line-p))
534 (forward-comment 9999)
535 (let ((indent-offset (current-indentation)))
536 (when (> indent-offset 0)
537 (setq python-indent-offset indent-offset))))))))
539 (defun python-indent-context ()
540 "Get information on indentation context.
541 Context information is returned with a cons with the form:
544 Where status can be any of the following symbols:
545 * inside-paren: If point in between (), {} or []
546 * inside-string: If point is inside a string
547 * after-backslash: Previous line ends in a backslash
548 * after-beginning-of-block: Point is after beginning of block
549 * after-line: Point is after normal line
550 * no-indent: Point is at beginning of buffer or other special case
551 START is the buffer position where the sexp starts."
554 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
558 ;; Beginning of buffer
560 (goto-char (line-beginning-position))
564 ((setq start (python-info-ppss-context 'paren ppss))
567 ((setq start (python-info-ppss-context 'string ppss))
570 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
571 (python-info-ppss-context 'comment ppss)))
572 (let ((line-beg-pos (line-beginning-position)))
573 (when (eq ?\\ (char-before (1- line-beg-pos)))
574 (- line-beg-pos 2)))))
576 ;; After beginning of block
577 ((setq start (save-excursion
578 (let ((block-regexp (python-rx block-start))
579 (block-start-line-end ":[[:space:]]*$"))
580 (back-to-indentation)
581 (while (and (forward-comment -9999) (not (bobp))))
582 (back-to-indentation)
583 (when (or (python-info-continuation-line-p)
584 (and (not (looking-at block-regexp))
588 (line-end-position) t))))
589 (while (and (forward-line -1)
590 (python-info-continuation-line-p)
592 (when (not (looking-at block-regexp))
594 (back-to-indentation)
595 (when (and (looking-at block-regexp)
596 (or (re-search-forward
598 (line-end-position) t)
599 (python-info-continuation-line-p)))
601 'after-beginning-of-block)
603 ((setq start (save-excursion
604 (while (and (forward-comment -9999) (not (bobp))))
605 (python-nav-sentence-start)
612 (defun python-indent-calculate-indentation ()
613 "Calculate correct indentation offset for the current line."
614 (let* ((indentation-context (python-indent-context))
615 (context-status (car indentation-context))
616 (context-start (cdr indentation-context)))
622 ('after-beginning-of-block
623 (goto-char context-start)
624 (+ (current-indentation) python-indent-offset))
628 (goto-char context-start)
629 (current-indentation))
631 (back-to-indentation)
632 (looking-at (regexp-opt python-indent-dedenters)))
636 (goto-char context-start)
637 (current-indentation))
639 (let* ((block-continuation
642 (python-info-block-continuation-line-p)))
643 (assignment-continuation
646 (python-info-assignment-continuation-line-p)))
649 (back-to-indentation)
650 (when (looking-at "\\.")
652 (goto-char (line-end-position))
653 (while (and (re-search-backward "\\." (line-beginning-position) t)
654 (or (python-info-ppss-context 'comment)
655 (python-info-ppss-context 'string)
656 (python-info-ppss-context 'paren))))
657 (if (and (looking-at "\\.")
658 (not (or (python-info-ppss-context 'comment)
659 (python-info-ppss-context 'string)
660 (python-info-ppss-context 'paren))))
662 (+ (current-indentation) python-indent-offset)))))
667 (goto-char block-continuation)
669 (python-rx block-start (* space))
670 (line-end-position) t)
672 (assignment-continuation
673 (goto-char assignment-continuation)
675 (python-rx simple-operator)
676 (line-end-position) t)
679 (python-rx (* space))
680 (line-end-position) t)
683 (goto-char context-start)
686 (back-to-indentation)
688 "\\(?:return\\|from\\|import\\)\s+")))
689 (current-indentation)
690 (+ (current-indentation)
692 (match-string-no-properties 0))))))))
696 (skip-syntax-forward "\s" (line-end-position))
697 (when (and (looking-at (regexp-opt '(")" "]" "}")))
698 (not (forward-char 1))
699 (not (python-info-ppss-context 'paren)))
700 (goto-char context-start)
701 (back-to-indentation)
705 (goto-char context-start)
709 (line-beginning-position)
711 (forward-comment 9999))
713 (+ (current-indentation) python-indent-offset)
714 (forward-comment 9999)
717 (back-to-indentation)
718 (looking-at (regexp-opt '(")" "]" "}"))))
722 (defun python-indent-calculate-levels ()
723 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
724 (let* ((indentation (python-indent-calculate-indentation))
725 (remainder (% indentation python-indent-offset))
726 (steps (/ (- indentation remainder) python-indent-offset)))
727 (setq python-indent-levels (list 0))
728 (dotimes (step steps)
729 (push (* python-indent-offset (1+ step)) python-indent-levels))
730 (when (not (eq 0 remainder))
731 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
732 (setq python-indent-levels (nreverse python-indent-levels))
733 (setq python-indent-current-level (1- (length python-indent-levels)))))
735 (defun python-indent-toggle-levels ()
736 "Toggle `python-indent-current-level' over `python-indent-levels'."
737 (setq python-indent-current-level (1- python-indent-current-level))
738 (when (< python-indent-current-level 0)
739 (setq python-indent-current-level (1- (length python-indent-levels)))))
741 (defun python-indent-line (&optional force-toggle)
742 "Internal implementation of `python-indent-line-function'.
743 Uses the offset calculated in
744 `python-indent-calculate-indentation' and available levels
745 indicated by the variable `python-indent-levels' to set the
748 When the variable `last-command' is equal to
749 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
750 levels indicated in the variable `python-indent-levels' by
751 setting the current level in the variable
752 `python-indent-current-level'.
754 When the variable `last-command' is not equal to
755 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
756 possible indentation levels and saves it in the variable
757 `python-indent-levels'. Afterwards it sets the variable
758 `python-indent-current-level' correctly so offset is equal
759 to (`nth' `python-indent-current-level' `python-indent-levels')"
760 (if (or (and (eq this-command 'indent-for-tab-command)
761 (eq last-command this-command))
763 (if (not (equal python-indent-levels '(0)))
764 (python-indent-toggle-levels)
765 (python-indent-calculate-levels))
766 (python-indent-calculate-levels))
768 (delete-horizontal-space)
769 (indent-to (nth python-indent-current-level python-indent-levels))
772 (let ((closing-block-point (python-info-closing-block)))
773 (when closing-block-point
774 (message "Closes %s" (buffer-substring
777 (goto-char closing-block-point)
778 (line-end-position))))))))
780 (defun python-indent-line-function ()
781 "`indent-line-function' for Python mode.
782 See `python-indent-line' for details."
783 (python-indent-line))
785 (defun python-indent-dedent-line ()
786 "De-indent current line."
788 (when (and (not (or (python-info-ppss-context 'string)
789 (python-info-ppss-context 'comment)))
790 (<= (point-marker) (save-excursion
791 (back-to-indentation)
793 (> (current-column) 0))
794 (python-indent-line t)
797 (defun python-indent-dedent-line-backspace (arg)
798 "De-indent current line.
799 Argument ARG is passed to `backward-delete-char-untabify' when
800 point is not in between the indentation."
802 (when (not (python-indent-dedent-line))
803 (backward-delete-char-untabify arg)))
804 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
806 (defun python-indent-region (start end)
807 "Indent a python region automagically.
809 Called from a program, START and END specify the region to indent."
810 (let ((deactivate-mark nil))
813 (setq end (point-marker))
815 (or (bolp) (forward-line 1))
816 (while (< (point) end)
817 (or (and (bolp) (eolp))
820 (back-to-indentation)
821 (setq word (current-word))
825 (delete-horizontal-space)
826 (indent-to (python-indent-calculate-indentation)))))
828 (move-marker end nil))))
830 (defun python-indent-shift-left (start end &optional count)
831 "Shift lines contained in region START END by COUNT columns to the left.
832 COUNT defaults to `python-indent-offset'. If region isn't
833 active, the current line is shifted. The shifted region includes
834 the lines in which START and END lie. An error is signaled if
835 any lines in the region are indented less than COUNT columns."
838 (list (region-beginning) (region-end) current-prefix-arg)
839 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
841 (setq count (prefix-numeric-value count))
842 (setq count python-indent-offset))
844 (let ((deactivate-mark nil))
847 (while (< (point) end)
848 (if (and (< (current-indentation) count)
849 (not (looking-at "[ \t]*$")))
850 (error "Can't shift all lines enough"))
852 (indent-rigidly start end (- count))))))
854 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
856 (defun python-indent-shift-right (start end &optional count)
857 "Shift lines contained in region START END by COUNT columns to the left.
858 COUNT defaults to `python-indent-offset'. If region isn't
859 active, the current line is shifted. The shifted region includes
860 the lines in which START and END lie."
863 (list (region-beginning) (region-end) current-prefix-arg)
864 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
865 (let ((deactivate-mark nil))
867 (setq count (prefix-numeric-value count))
868 (setq count python-indent-offset))
869 (indent-rigidly start end count)))
871 (defun python-indent-electric-colon (arg)
872 "Insert a colon and maybe de-indent the current line.
873 With numeric ARG, just insert that many colons. With
874 \\[universal-argument], just insert a single colon."
876 (self-insert-command (if (not (integerp arg)) 1 arg))
879 (not (equal ?: (char-after (- (point-marker) 2))))
880 (not (or (python-info-ppss-context 'string)
881 (python-info-ppss-context 'comment))))
882 (let ((indentation (current-indentation))
883 (calculated-indentation (python-indent-calculate-indentation)))
884 (when (> indentation calculated-indentation)
886 (indent-line-to calculated-indentation)
887 (when (not (python-info-closing-block))
888 (indent-line-to indentation)))))))
889 (put 'python-indent-electric-colon 'delete-selection t)
894 (defvar python-nav-beginning-of-defun-regexp
895 (python-rx line-start (* space) defun (+ space) (group symbol-name))
896 "Regular expresion matching beginning of class or function.
897 The name of the defun should be grouped so it can be retrieved
898 via `match-string'.")
900 (defun python-nav-beginning-of-defun (&optional nodecorators)
901 "Move point to `beginning-of-defun'.
902 When NODECORATORS is non-nil decorators are not included. This
903 is the main part of`python-beginning-of-defun-function'
904 implementation. Return non-nil if point is moved to the
905 `beginning-of-defun'."
906 (let ((indent-pos (save-excursion
907 (back-to-indentation)
912 (when (not nodecorators)
913 (when (save-excursion
915 (looking-at (python-rx decorator)))
916 (while (and (not (bobp))
918 (looking-at (python-rx decorator))))
919 (when (not (bobp)) (forward-line 1)))))))
920 (if (and (> (point) indent-pos)
922 (goto-char (line-beginning-position))
923 (looking-at python-nav-beginning-of-defun-regexp)))
925 (goto-char (line-beginning-position))
926 (funcall include-decorators)
928 (goto-char (line-beginning-position))
929 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
931 (goto-char (or (python-info-ppss-context 'string) (point)))
932 (funcall include-decorators))
935 (defun python-beginning-of-defun-function (&optional arg nodecorators)
936 "Move point to the beginning of def or class.
937 With positive ARG move that number of functions forward. With
938 negative do the same but backwards. When NODECORATORS is non-nil
939 decorators are not included. Return non-nil if point is moved to the
940 `beginning-of-defun'."
941 (when (or (null arg) (= arg 0)) (setq arg 1))
943 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
945 (dotimes (i (- arg) found)
946 (python-end-of-defun-function)
947 (forward-comment 9999)
948 (goto-char (line-end-position))
951 (python-nav-beginning-of-defun nodecorators)))))))
953 (defun python-end-of-defun-function ()
954 "Move point to the end of def or class.
955 Returns nil if point is not in a def or class."
957 (let ((beg-defun-indent)
958 (decorator-regexp "[[:space:]]*@"))
959 (when (looking-at decorator-regexp)
960 (while (and (not (eobp))
962 (looking-at decorator-regexp))))
963 (when (not (looking-at python-nav-beginning-of-defun-regexp))
964 (python-beginning-of-defun-function))
965 (setq beg-defun-indent (current-indentation))
967 (while (and (forward-line 1)
969 (or (not (current-word))
970 (> (current-indentation) beg-defun-indent))))
971 (forward-comment 9999)
972 (goto-char (line-beginning-position))))
974 (defun python-nav-sentence-start ()
975 "Move to start of current sentence."
977 (while (and (not (back-to-indentation))
982 (python-info-line-ends-backslash-p))
983 (python-info-ppss-context 'string)
984 (python-info-ppss-context 'paren))
985 (forward-line -1)))))
987 (defun python-nav-sentence-end ()
988 "Move to end of current sentence."
990 (while (and (goto-char (line-end-position))
993 (python-info-line-ends-backslash-p)
994 (python-info-ppss-context 'string)
995 (python-info-ppss-context 'paren))
998 (defun python-nav-backward-sentence (&optional arg)
999 "Move backward to start of sentence. With ARG, do it arg times.
1000 See `python-nav-forward-sentence' for more information."
1002 (or arg (setq arg 1))
1003 (python-nav-forward-sentence (- arg)))
1005 (defun python-nav-forward-sentence (&optional arg)
1006 "Move forward to next end of sentence. With ARG, repeat.
1007 With negative argument, move backward repeatedly to start of sentence."
1009 (or arg (setq arg 1))
1011 (forward-comment 9999)
1012 (python-nav-sentence-end)
1014 (setq arg (1- arg)))
1016 (python-nav-sentence-end)
1017 (forward-comment -9999)
1018 (python-nav-sentence-start)
1020 (setq arg (1+ arg))))
1023 ;;; Shell integration
1025 (defvar python-shell-buffer-name "Python"
1026 "Default buffer name for Python interpreter.")
1028 (defcustom python-shell-interpreter "python"
1029 "Default Python interpreter for shell."
1034 (defcustom python-shell-interpreter-args "-i"
1035 "Default arguments for the Python interpreter."
1040 (defcustom python-shell-prompt-regexp ">>> "
1041 "Regular Expression matching top\-level input prompt of python shell.
1042 It should not contain a caret (^) at the beginning."
1047 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1048 "Regular Expression matching block input prompt of python shell.
1049 It should not contain a caret (^) at the beginning."
1054 (defcustom python-shell-prompt-output-regexp nil
1055 "Regular Expression matching output prompt of python shell.
1056 It should not contain a caret (^) at the beginning."
1061 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1062 "Regular Expression matching pdb input prompt of python shell.
1063 It should not contain a caret (^) at the beginning."
1068 (defcustom python-shell-send-setup-max-wait 5
1069 "Seconds to wait for process output before code setup.
1070 If output is received before the especified time then control is
1071 returned in that moment and not after waiting."
1076 (defcustom python-shell-process-environment nil
1077 "List of enviroment variables for Python shell.
1078 This variable follows the same rules as `process-enviroment'
1079 since it merges with it before the process creation routines are
1080 called. When this variable is nil, the Python shell is run with
1081 the default `process-enviroment'."
1082 :type '(repeat string)
1086 (defcustom python-shell-exec-path nil
1087 "List of path to search for binaries.
1088 This variable follows the same rules as `exec-path' since it
1089 merges with it before the process creation routines are called.
1090 When this variable is nil, the Python shell is run with the
1091 default `exec-path'."
1092 :type '(repeat string)
1096 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1097 python-ffap-setup-code
1098 python-eldoc-setup-code)
1099 "List of code run by `python-shell-send-setup-codes'.
1100 Each variable can contain either a simple string with the code to
1101 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1102 is a string with the code to execute and DESCRIPTION is the
1104 :type '(repeat symbol)
1108 (defcustom python-shell-compilation-regexp-alist
1109 `((,(rx line-start (1+ (any " \t")) "File \""
1110 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1111 "\", line " (group (1+ digit)))
1113 (,(rx " in file " (group (1+ not-newline)) " on line "
1116 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1117 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1119 "`compilation-error-regexp-alist' for inferior Python."
1120 :type '(alist string)
1123 (defun python-shell-get-process-name (dedicated)
1124 "Calculate the appropiate process name for inferior Python process.
1125 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1126 returns a string with the form
1127 `python-shell-buffer-name'[variable `buffer-file-name'] else
1128 returns the value of `python-shell-buffer-name'. After
1129 calculating the process name adds the buffer name for the process
1130 in the `same-window-buffer-names' list."
1134 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1135 (format "%s" python-shell-buffer-name))))
1136 (add-to-list 'same-window-buffer-names (purecopy
1137 (format "*%s*" process-name)))
1140 (defun python-shell-parse-command ()
1141 "Calculate the string used to execute the inferior Python process."
1142 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1144 (defun python-comint-output-filter-function (output)
1145 "Hook run after content is put into comint buffer.
1146 OUTPUT is a string with the contents of the buffer."
1147 (ansi-color-filter-apply output))
1149 (defvar inferior-python-mode-current-file nil
1150 "Current file from which a region was sent.")
1151 (make-variable-buffer-local 'inferior-python-mode-current-file)
1153 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1154 "Major mode for Python inferior process.
1155 Runs a Python interpreter as a subprocess of Emacs, with Python
1156 I/O through an Emacs buffer. Variables
1157 `python-shell-interpreter' and `python-shell-interpreter-args'
1158 controls which Python interpreter is run. Variables
1159 `python-shell-prompt-regexp',
1160 `python-shell-prompt-output-regexp',
1161 `python-shell-prompt-block-regexp',
1162 `python-shell-completion-setup-code',
1163 `python-shell-completion-string-code', `python-eldoc-setup-code',
1164 `python-eldoc-string-code', `python-ffap-setup-code' and
1165 `python-ffap-string-code' can customize this mode for different
1166 Python interpreters.
1168 You can also add additional setup code to be run at
1169 initialization of the interpreter via `python-shell-setup-codes'
1172 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1173 (set-syntax-table python-mode-syntax-table)
1174 (setq mode-line-process '(":%s"))
1175 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1176 python-shell-prompt-regexp
1177 python-shell-prompt-block-regexp
1178 python-shell-prompt-pdb-regexp))
1179 (make-local-variable 'comint-output-filter-functions)
1180 (add-hook 'comint-output-filter-functions
1181 'python-comint-output-filter-function)
1182 (add-hook 'comint-output-filter-functions
1183 'python-pdbtrack-comint-output-filter-function)
1184 (set (make-local-variable 'compilation-error-regexp-alist)
1185 python-shell-compilation-regexp-alist)
1186 (define-key inferior-python-mode-map [remap complete-symbol]
1187 'completion-at-point)
1188 (add-hook 'completion-at-point-functions
1189 'python-shell-completion-complete-at-point nil 'local)
1190 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1191 'python-shell-completion-complete-at-point)
1192 (define-key inferior-python-mode-map (kbd "<tab>")
1193 'python-shell-completion-complete-or-indent)
1194 (compilation-shell-minor-mode 1))
1196 (defun run-python (dedicated cmd)
1197 "Run an inferior Python process.
1198 Input and output via buffer named after
1199 `python-shell-buffer-name'. If there is a process already
1200 running in that buffer, just switch to it.
1201 With argument, allows you to define DEDICATED, so a dedicated
1202 process for the current buffer is open, and define CMD so you can
1203 edit the command used to call the interpreter (default is value
1204 of `python-shell-interpreter' and arguments defined in
1205 `python-shell-interpreter-args'). Runs the hook
1206 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1208 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1210 (if current-prefix-arg
1212 (y-or-n-p "Make dedicated process? ")
1213 (read-string "Run Python: " (python-shell-parse-command)))
1214 (list nil (python-shell-parse-command))))
1215 (let* ((proc-name (python-shell-get-process-name dedicated))
1216 (proc-buffer-name (format "*%s*" proc-name))
1217 (process-environment
1218 (if python-shell-process-environment
1219 (python-util-merge 'list python-shell-process-environment
1220 process-environment 'string=)
1221 process-environment))
1223 (if python-shell-exec-path
1224 (python-util-merge 'list python-shell-exec-path
1227 (when (not (comint-check-proc proc-buffer-name))
1228 (let ((cmdlist (split-string-and-unquote cmd)))
1230 (apply 'make-comint proc-name (car cmdlist) nil
1232 (inferior-python-mode)))
1233 (pop-to-buffer proc-buffer-name))
1236 (defun python-shell-get-process ()
1237 "Get inferior Python process for current buffer and return it."
1238 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1239 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1240 (global-proc-name (python-shell-get-process-name nil))
1241 (global-proc-buffer-name (format "*%s*" global-proc-name))
1242 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1243 (global-running (comint-check-proc global-proc-buffer-name)))
1244 ;; Always prefer dedicated
1245 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1246 (and global-running global-proc-buffer-name)))))
1248 (defun python-shell-get-or-create-process ()
1249 "Get or create an inferior Python process for current buffer and return it."
1250 (let* ((old-buffer (current-buffer))
1251 (dedicated-proc-name (python-shell-get-process-name t))
1252 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1253 (global-proc-name (python-shell-get-process-name nil))
1254 (global-proc-buffer-name (format "*%s*" global-proc-name))
1255 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1256 (global-running (comint-check-proc global-proc-buffer-name))
1257 (current-prefix-arg 4))
1258 (when (and (not dedicated-running) (not global-running))
1259 (if (call-interactively 'run-python)
1260 (setq dedicated-running t)
1261 (setq global-running t)))
1262 ;; Always prefer dedicated
1263 (switch-to-buffer old-buffer)
1264 (get-buffer-process (if dedicated-running
1265 dedicated-proc-buffer-name
1266 global-proc-buffer-name))))
1268 (defun python-shell-send-string (string &optional process msg)
1269 "Send STRING to inferior Python PROCESS.
1270 When MSG is non-nil messages the first line of STRING."
1271 (interactive "sPython command: ")
1272 (let ((process (or process (python-shell-get-or-create-process)))
1273 (lines (split-string string "\n" t)))
1275 (message (format "Sent: %s..." (nth 0 lines))))
1276 (if (> (length lines) 1)
1277 (let* ((temp-file-name (make-temp-file "py"))
1278 (file-name (or (buffer-file-name) temp-file-name)))
1279 (with-temp-file temp-file-name
1281 (delete-trailing-whitespace))
1282 (python-shell-send-file file-name process temp-file-name))
1283 (comint-send-string process string)
1284 (when (or (not (string-match "\n$" string))
1285 (string-match "\n[ \t].*\n?$" string))
1286 (comint-send-string process "\n")))))
1288 (defun python-shell-send-string-no-output (string &optional process msg)
1289 "Send STRING to PROCESS and inhibit output.
1290 When MSG is non-nil messages the first line of STRING. Return
1292 (let* ((output-buffer)
1293 (process (or process (python-shell-get-or-create-process)))
1294 (comint-preoutput-filter-functions
1295 (append comint-preoutput-filter-functions
1296 '(ansi-color-filter-apply
1298 (setq output-buffer (concat output-buffer string))
1300 (python-shell-send-string string process msg)
1301 (accept-process-output process)
1302 ;; Cleanup output prompt regexp
1303 (when (and (not (string= "" output-buffer))
1304 (> (length python-shell-prompt-output-regexp) 0))
1307 (insert output-buffer)
1308 (goto-char (point-min))
1309 (forward-comment 9999)
1310 (buffer-substring-no-properties
1312 (and (looking-at python-shell-prompt-output-regexp)
1314 python-shell-prompt-output-regexp nil t 1))
1318 (lambda (string) string)
1319 (butlast (split-string output-buffer "\n")) "\n")))
1321 (defun python-shell-send-region (start end)
1322 "Send the region delimited by START and END to inferior Python process."
1324 (let ((deactivate-mark nil))
1325 (python-shell-send-string (buffer-substring start end) nil t)))
1327 (defun python-shell-send-buffer ()
1328 "Send the entire buffer to inferior Python process."
1332 (python-shell-send-region (point-min) (point-max))))
1334 (defun python-shell-send-defun (arg)
1335 "Send the current defun to inferior Python process.
1336 When argument ARG is non-nil sends the innermost defun."
1339 (python-shell-send-region
1341 (or (python-beginning-of-defun-function)
1342 (progn (beginning-of-line) (point-marker))))
1344 (or (python-end-of-defun-function)
1345 (progn (end-of-line) (point-marker)))))))
1347 (defun python-shell-send-file (file-name &optional process temp-file-name)
1348 "Send FILE-NAME to inferior Python PROCESS.
1349 If TEMP-FILE-NAME is passed then that file is used for processing
1350 instead, while internally the shell will continue to use
1352 (interactive "fFile to send: ")
1353 (let* ((process (or process (python-shell-get-or-create-process)))
1354 (temp-file-name (when temp-file-name
1355 (expand-file-name temp-file-name)))
1356 (file-name (or (expand-file-name file-name) temp-file-name)))
1357 (when (not file-name)
1358 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1359 (with-current-buffer (process-buffer process)
1360 (setq inferior-python-mode-current-file
1361 (convert-standard-filename file-name)))
1362 (python-shell-send-string
1364 (concat "__pyfile = open('''%s''');"
1365 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1367 (or temp-file-name file-name) file-name)
1370 (defun python-shell-switch-to-shell ()
1371 "Switch to inferior Python process buffer."
1373 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1375 (defun python-shell-send-setup-code ()
1376 "Send all setup code for shell.
1377 This function takes the list of setup code to send from the
1378 `python-shell-setup-codes' list."
1379 (let ((msg "Sent %s")
1380 (process (get-buffer-process (current-buffer))))
1381 (accept-process-output process python-shell-send-setup-max-wait)
1382 (dolist (code python-shell-setup-codes)
1385 (setq msg (cdr code)))
1386 (message (format msg code))
1387 (python-shell-send-string-no-output
1388 (symbol-value code) process)))))
1390 (add-hook 'inferior-python-mode-hook
1391 #'python-shell-send-setup-code)
1394 ;;; Shell completion
1396 (defvar python-shell-completion-setup-code
1400 def __COMPLETER_all_completions(text): []
1403 readline.set_completer(rlcompleter.Completer().complete)
1404 def __COMPLETER_all_completions(text):
1410 res = readline.get_completer()(text, i)
1413 completions.append(res)
1417 "Code used to setup completion in inferior Python processes.")
1419 (defvar python-shell-completion-string-code
1420 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1421 "Python code used to get a string of completions separated by semicolons.")
1423 (defun python-shell-completion--get-completions (input process)
1424 "Retrieve available completions for INPUT using PROCESS."
1425 (with-current-buffer (process-buffer process)
1426 (let ((completions (python-shell-send-string-no-output
1427 (format python-shell-completion-string-code input)
1429 (when (> (length completions) 2)
1430 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1432 (defun python-shell-completion--get-completion (input completions)
1433 "Get completion for INPUT using COMPLETIONS."
1434 (let ((completion (when completions
1435 (try-completion input completions))))
1436 (cond ((eq completion t)
1439 (message "Can't find completion for \"%s\"" input)
1442 ((not (string= input completion))
1445 (message "Making completion list...")
1446 (with-output-to-temp-buffer "*Python Completions*"
1447 (display-completion-list
1448 (all-completions input completions)))
1451 (defun python-shell-completion-complete-at-point ()
1452 "Perform completion at point in inferior Python process."
1454 (with-syntax-table python-dotty-syntax-table
1455 (when (and comint-last-prompt-overlay
1456 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1457 (let* ((process (get-buffer-process (current-buffer)))
1458 (input (substring-no-properties
1459 (or (comint-word (current-word)) "") nil nil)))
1460 (delete-char (- (length input)))
1462 (python-shell-completion--get-completion
1463 input (python-shell-completion--get-completions input process)))))))
1465 (defun python-shell-completion-complete-or-indent ()
1466 "Complete or indent depending on the context.
1467 If content before pointer is all whitespace indent. If not try
1470 (if (string-match "^[[:space:]]*$"
1471 (buffer-substring (comint-line-beginning-position)
1473 (indent-for-tab-command)
1474 (comint-dynamic-complete)))
1477 ;;; PDB Track integration
1479 (defvar python-pdbtrack-stacktrace-info-regexp
1480 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1481 "Regular Expression matching stacktrace information.
1482 Used to extract the current line and module beign inspected. The
1483 regexp should not start with a caret (^) and can contain a string
1484 placeholder (\%s) which is replaced with the filename beign
1485 inspected (so other files in the debugging process are not
1488 (defvar python-pdbtrack-tracking-buffers '()
1489 "Alist containing elements of form (#<buffer> . #<buffer>).
1490 The car of each element of the alist is the tracking buffer and
1491 the cdr is the tracked buffer.")
1493 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1494 "Get/Add a tracked buffer for the current buffer.
1495 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1496 Returns a cons with the form:
1497 * (#<tracking buffer> . #< tracked buffer>)."
1499 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1500 (let* ((file (with-current-buffer (current-buffer)
1501 inferior-python-mode-current-file))
1503 `(,(current-buffer) .
1504 ,(or (get-file-buffer file)
1505 (find-file-noselect file)))))
1506 (set-buffer (cdr tracking-buffers))
1508 (set-buffer (car tracking-buffers))
1509 (setq python-pdbtrack-tracking-buffers
1510 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1513 (defun python-pdbtrack-comint-output-filter-function (output)
1514 "Move overlay arrow to current pdb line in tracked buffer.
1515 Argument OUTPUT is a string with the output from the comint process."
1516 (when (not (string= output ""))
1517 (let ((full-output (ansi-color-filter-apply
1518 (buffer-substring comint-last-input-end
1520 (if (string-match python-shell-prompt-pdb-regexp full-output)
1521 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1525 (format python-pdbtrack-stacktrace-info-regexp
1527 inferior-python-mode-current-file))
1529 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1530 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1531 (tracked-buffer-line-pos))
1533 (with-current-buffer (cdr tracking-buffers)
1534 (set (make-local-variable 'overlay-arrow-string) "=>")
1535 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1536 (setq tracked-buffer-line-pos (progn
1537 (goto-char (point-min))
1538 (forward-line (1- line-num))
1540 (when tracked-buffer-window
1541 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1542 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1543 (pop-to-buffer (cdr tracking-buffers))
1544 (switch-to-buffer-other-window (car tracking-buffers)))
1545 (let ((tracking-buffers (assq (current-buffer)
1546 python-pdbtrack-tracking-buffers)))
1547 (when tracking-buffers
1548 (if inferior-python-mode-current-file
1549 (with-current-buffer (cdr tracking-buffers)
1550 (set-marker overlay-arrow-position nil))
1551 (kill-buffer (cdr tracking-buffers)))
1552 (setq python-pdbtrack-tracking-buffers
1553 (assq-delete-all (current-buffer)
1554 python-pdbtrack-tracking-buffers)))))))
1558 ;;; Symbol completion
1560 (defun python-completion-complete-at-point ()
1561 "Complete current symbol at point.
1562 For this to work the best as possible you should call
1563 `python-shell-send-buffer' from time to time so context in
1564 inferior python process is updated properly."
1566 (let ((process (python-shell-get-process)))
1568 (error "Completion needs an inferior Python process running")
1569 (with-syntax-table python-dotty-syntax-table
1570 (let* ((input (substring-no-properties
1571 (or (comint-word (current-word)) "") nil nil))
1572 (completions (python-shell-completion--get-completions
1574 (delete-char (- (length input)))
1576 (python-shell-completion--get-completion
1577 input completions)))))))
1579 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1584 (defcustom python-fill-comment-function 'python-fill-comment
1585 "Function to fill comments.
1586 This is the function used by `python-fill-paragraph-function' to
1592 (defcustom python-fill-string-function 'python-fill-string
1593 "Function to fill strings.
1594 This is the function used by `python-fill-paragraph-function' to
1600 (defcustom python-fill-decorator-function 'python-fill-decorator
1601 "Function to fill decorators.
1602 This is the function used by `python-fill-paragraph-function' to
1608 (defcustom python-fill-paren-function 'python-fill-paren
1609 "Function to fill parens.
1610 This is the function used by `python-fill-paragraph-function' to
1616 (defun python-fill-paragraph-function (&optional justify)
1617 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1618 If any of the current line is in or at the end of a multi-line string,
1619 fill the string or the paragraph of it that point is in, preserving
1620 the string's indentation.
1621 Optional argument JUSTIFY defines if the paragraph should be justified."
1624 (back-to-indentation)
1627 ((funcall python-fill-comment-function justify))
1628 ;; Strings/Docstrings
1629 ((save-excursion (skip-chars-forward "\"'uUrR")
1630 (python-info-ppss-context 'string))
1631 (funcall python-fill-string-function justify))
1633 ((equal (char-after (save-excursion
1634 (back-to-indentation)
1635 (point-marker))) ?@)
1636 (funcall python-fill-decorator-function justify))
1638 ((or (python-info-ppss-context 'paren)
1639 (looking-at (python-rx open-paren))
1641 (skip-syntax-forward "^(" (line-end-position))
1642 (looking-at (python-rx open-paren))))
1643 (funcall python-fill-paren-function justify))
1646 (defun python-fill-comment (&optional justify)
1647 "Comment fill function for `python-fill-paragraph-function'.
1648 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1649 (fill-comment-paragraph justify))
1651 (defun python-fill-string (&optional justify)
1652 "String fill function for `python-fill-paragraph-function'.
1653 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1654 (let ((marker (point-marker))
1655 (string-start-marker
1657 (skip-chars-forward "\"'uUrR")
1658 (goto-char (python-info-ppss-context 'string))
1659 (skip-chars-forward "\"'uUrR")
1661 (reg-start (line-beginning-position))
1664 (while (python-info-ppss-context 'string)
1665 (goto-char (1+ (point-marker))))
1666 (skip-chars-backward "\"'")
1668 (reg-end (line-end-position))
1669 (fill-paragraph-function))
1671 (narrow-to-region reg-start reg-end)
1673 (goto-char string-start-marker)
1674 (delete-region (point-marker) (progn
1675 (skip-syntax-forward "> ")
1677 (goto-char string-end-marker)
1678 (delete-region (point-marker) (progn
1679 (skip-syntax-backward "> ")
1683 (fill-paragraph justify))
1684 ;; If there is a newline in the docstring lets put triple
1685 ;; quote in it's own line to follow pep 8
1686 (when (save-excursion
1687 (re-search-backward "\n" string-start-marker t))
1689 (newline-and-indent))
1690 (fill-paragraph justify)))) t)
1692 (defun python-fill-decorator (&optional justify)
1693 "Decorator fill function for `python-fill-paragraph-function'.
1694 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1697 (defun python-fill-paren (&optional justify)
1698 "Paren fill function for `python-fill-paragraph-function'.
1699 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1701 (narrow-to-region (progn
1702 (while (python-info-ppss-context 'paren)
1703 (goto-char (1- (point-marker))))
1705 (line-beginning-position))
1707 (when (not (python-info-ppss-context 'paren))
1709 (when (not (python-info-ppss-context 'paren))
1710 (skip-syntax-backward "^)")))
1711 (while (python-info-ppss-context 'paren)
1712 (goto-char (1+ (point-marker))))
1714 (let ((paragraph-start "\f\\|[ \t]*$")
1715 (paragraph-separate ",")
1716 (fill-paragraph-function))
1717 (goto-char (point-min))
1718 (fill-paragraph justify))
1721 (python-indent-line)
1722 (goto-char (line-end-position)))) t)
1727 (defcustom python-skeleton-autoinsert nil
1728 "Non-nil means template skeletons will be automagically inserted.
1729 This happens when pressing \"if<SPACE>\", for example, to prompt for
1734 (defvar python-skeleton-available '()
1735 "Internal list of available skeletons.")
1736 (make-variable-buffer-local 'inferior-python-mode-current-file)
1738 (define-abbrev-table 'python-mode-abbrev-table ()
1739 "Abbrev table for Python mode."
1741 ;; Allow / inside abbrevs.
1742 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1743 ;; Only expand in code.
1744 :enable-function (lambda ()
1746 (not (or (python-info-ppss-context 'string)
1747 (python-info-ppss-context 'comment)))
1748 python-skeleton-autoinsert)))
1750 (defmacro python-skeleton-define (name doc &rest skel)
1751 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1752 The skeleton will be bound to python-skeleton-NAME and will
1753 be added to `python-mode-abbrev-table'."
1754 (let* ((name (symbol-name name))
1755 (function-name (intern (concat "python-skeleton-" name))))
1757 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1758 (setq python-skeleton-available
1759 (cons ',function-name python-skeleton-available))
1760 (define-skeleton ,function-name
1762 (format "Insert %s statement." name))
1764 (put 'python-skeleton-define 'lisp-indent-function 2)
1766 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1767 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1768 The skeleton will be bound to python-skeleton-NAME."
1769 (let* ((name (symbol-name name))
1770 (function-name (intern (concat "python-skeleton--" name)))
1772 "Add '%s' clause? " name)))
1775 `(< ,(format "%s:" name) \n \n
1777 `(define-skeleton ,function-name
1779 (format "Auxiliary skeleton for %s statement." name))
1781 (unless (y-or-n-p ,msg)
1784 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1786 (python-define-auxiliary-skeleton else nil)
1788 (python-define-auxiliary-skeleton except nil)
1790 (python-define-auxiliary-skeleton finally nil)
1792 (python-skeleton-define if nil
1796 ("other condition, %s: "
1800 '(python-skeleton--else) | ^)
1802 (python-skeleton-define while nil
1806 '(python-skeleton--else) | ^)
1808 (python-skeleton-define for nil
1812 '(python-skeleton--else) | ^)
1814 (python-skeleton-define try nil
1820 "except " str ":" \n
1823 '(python-skeleton--except)
1824 '(python-skeleton--else)
1825 '(python-skeleton--finally) | ^)
1827 (python-skeleton-define def nil
1829 "def " str " (" ("Parameter, %s: "
1830 (unless (equal ?\( (char-before)) ", ")
1832 "\"\"\"" - "\"\"\"" \n
1835 (python-skeleton-define class nil
1837 "class " str " (" ("Inheritance, %s: "
1838 (unless (equal ?\( (char-before)) ", ")
1842 "\"\"\"" - "\"\"\"" \n
1845 (defun python-skeleton-add-menu-items ()
1846 "Add menu items to Python->Skeletons menu."
1847 (let ((skeletons (sort python-skeleton-available 'string<))
1849 (dolist (skeleton skeletons)
1851 nil '("Python" "Skeletons")
1853 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1858 (defvar python-ffap-setup-code
1859 "def __FFAP_get_module_path(module):
1862 path = __import__(module).__file__
1863 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1868 "Python code to get a module path.")
1870 (defvar python-ffap-string-code
1871 "__FFAP_get_module_path('''%s''')\n"
1872 "Python code used to get a string with the path of a module.")
1874 (defun python-ffap-module-path (module)
1875 "Function for `ffap-alist' to return path for MODULE."
1877 (and (eq major-mode 'inferior-python-mode)
1878 (get-buffer-process (current-buffer)))
1879 (python-shell-get-process))))
1883 (python-shell-send-string-no-output
1884 (format python-ffap-string-code module) process)))
1886 (substring-no-properties module-file 1 -1))))))
1888 (eval-after-load "ffap"
1890 (push '(python-mode . python-ffap-module-path) ffap-alist)
1891 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
1896 (defvar python-check-command
1897 "pychecker --stdlib"
1898 "Command used to check a Python file.")
1900 (defvar python-check-custom-command nil
1903 (defun python-check (command)
1904 "Check a Python file (default current buffer's file).
1905 Runs COMMAND, a shell command, as if by `compile'. See
1906 `python-check-command' for the default."
1908 (list (read-string "Check command: "
1909 (or python-check-custom-command
1910 (concat python-check-command " "
1911 (shell-quote-argument
1913 (let ((name (buffer-file-name)))
1915 (file-name-nondirectory name)))
1917 (setq python-check-custom-command command)
1918 (save-some-buffers (not compilation-ask-about-save) nil)
1919 (compilation-start command))
1924 (defvar python-eldoc-setup-code
1925 "def __PYDOC_get_help(obj):
1928 if hasattr(obj, 'startswith'):
1929 obj = eval(obj, globals())
1930 doc = inspect.getdoc(obj)
1931 if not doc and callable(obj):
1933 if inspect.isclass(obj) and hasattr(obj, '__init__'):
1934 target = obj.__init__
1940 args = inspect.formatargspec(
1941 *inspect.getargspec(target)
1944 doc = '{objtype} {name}{args}'.format(
1945 objtype=objtype, name=name, args=args
1948 doc = doc.splitlines()[0]
1955 "Python code to setup documentation retrieval.")
1957 (defvar python-eldoc-string-code
1958 "__PYDOC_get_help('''%s''')\n"
1959 "Python code used to get a string with the documentation of an object.")
1961 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
1962 "Internal implementation to get documentation at point.
1963 If not FORCE-INPUT is passed then what `current-word' returns
1964 will be used. If not FORCE-PROCESS is passed what
1965 `python-shell-get-process' returns is used."
1966 (let ((process (or force-process (python-shell-get-process))))
1968 "Eldoc needs an inferior Python process running."
1969 (let* ((current-defun (python-info-current-defun))
1970 (input (or force-input
1971 (with-syntax-table python-dotty-syntax-table
1972 (if (not current-defun)
1974 (concat current-defun "." (current-word))))))
1975 (ppss (syntax-ppss))
1976 (help (when (and input
1977 (not (string= input (concat current-defun ".")))
1978 (not (or (python-info-ppss-context 'string ppss)
1979 (python-info-ppss-context 'comment ppss))))
1980 (when (string-match (concat
1981 (regexp-quote (concat current-defun "."))
1985 (goto-char (point-min))
1988 (delete-region (point-marker) (search-forward "self."))
1989 (setq input (buffer-substring (point-min) (point-max)))))
1990 (python-shell-send-string-no-output
1991 (format python-eldoc-string-code input) process))))
1992 (with-current-buffer (process-buffer process)
1993 (when comint-last-prompt-overlay
1994 (delete-region comint-last-input-end
1995 (overlay-start comint-last-prompt-overlay))))
1997 (not (string= help "\n")))
2000 (defun python-eldoc-function ()
2001 "`eldoc-documentation-function' for Python.
2002 For this to work the best as possible you should call
2003 `python-shell-send-buffer' from time to time so context in
2004 inferior python process is updated properly."
2005 (python-eldoc--get-doc-at-point))
2007 (defun python-eldoc-at-point (symbol)
2008 "Get help on SYMBOL using `help'.
2009 Interactively, prompt for symbol."
2011 (let ((symbol (with-syntax-table python-dotty-syntax-table
2013 (enable-recursive-minibuffers t))
2014 (list (read-string (if symbol
2015 (format "Describe symbol (default %s): " symbol)
2016 "Describe symbol: ")
2018 (let ((process (python-shell-get-process)))
2020 (message "Eldoc needs an inferior Python process running.")
2021 (message (python-eldoc--get-doc-at-point symbol process)))))
2026 (defcustom python-imenu-include-defun-type t
2027 "Non-nil make imenu items to include its type."
2032 (defcustom python-imenu-make-tree t
2033 "Non-nil make imenu to build a tree menu.
2034 Set to nil for speed."
2039 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2040 "Label displayed to navigate to root from a subtree.
2041 It can contain a \"%s\" which will be replaced with the root name."
2046 (defvar python-imenu-index-alist nil
2047 "Calculated index tree for imenu.")
2049 (defun python-imenu-tree-assoc (keylist tree)
2050 "Using KEYLIST traverse TREE."
2052 (python-imenu-tree-assoc (cdr keylist)
2053 (ignore-errors (assoc (car keylist) tree)))
2056 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2057 "Make a tree from plain alist of module names.
2058 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2059 is the same thing, the difference is that FULL-ELEMENT remains
2060 untouched in all recursive calls.
2061 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2062 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2064 (let* ((subelement-point (cdr (assoc
2065 (mapconcat #'identity full-element ".")
2067 (subelement-name (car element-list))
2068 (subelement-position (python-util-position
2069 subelement-name full-element))
2070 (subelement-path (when subelement-position
2073 (- (length full-element)
2074 subelement-position)))))
2075 (let ((path-ref (python-imenu-tree-assoc subelement-path
2076 python-imenu-index-alist)))
2078 (push (cons subelement-name subelement-point)
2079 python-imenu-index-alist)
2080 (when (not (listp (cdr path-ref)))
2081 ;; Modifiy root cdr to be a list
2083 (list (cons (format python-imenu-subtree-root-label
2086 (mapconcat #'identity
2087 subelement-path ".")
2089 (when (not (assoc subelement-name path-ref))
2090 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2091 (python-imenu-make-element-tree (cdr element-list)
2092 full-element plain-index))))
2094 (defun python-imenu-make-tree (index)
2095 "Build the imenu alist tree from plain INDEX.
2097 The idea of this function is that given the alist:
2100 (\"Test.__init__\" . 200)
2101 (\"Test.some_method\" . 300)
2102 (\"Test.some_method.another\" . 400)
2103 (\"Test.something_else\" . 500)
2105 (\"test.reprint\" . 700)
2106 (\"test.reprint\" . 800))
2108 This tree gets built:
2110 '((\"Test\" . ((\"jump to...\" . 100)
2111 (\"__init__\" . 200)
2112 (\"some_method\" . ((\"jump to...\" . 300)
2113 (\"another\" . 400)))
2114 (\"something_else\" . 500)))
2115 (\"test\" . ((\"jump to...\" . 600)
2117 (\"reprint\" . 800))))
2119 Internally it uses `python-imenu-make-element-tree' to create all
2120 branches for each element."
2121 (setq python-imenu-index-alist nil)
2122 (mapc (lambda (element)
2123 (python-imenu-make-element-tree element element index))
2124 (mapcar (lambda (element)
2125 (split-string (car element) "\\." t)) index))
2126 python-imenu-index-alist)
2128 (defun python-imenu-create-index ()
2129 "`imenu-create-index-function' for Python."
2131 (goto-char (point-max))
2132 (while (python-beginning-of-defun-function 1 t)
2133 (let ((defun-dotted-name
2134 (python-info-current-defun python-imenu-include-defun-type)))
2135 (push (cons defun-dotted-name (point)) index)))
2136 (if python-imenu-make-tree
2137 (python-imenu-make-tree index)
2143 (defun python-info-current-defun (&optional include-type)
2144 "Return name of surrounding function with Python compatible dotty syntax.
2145 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2146 This function is compatible to be used as
2147 `add-log-current-defun-function' since it returns nil if point is
2148 not inside a defun."
2154 (goto-char (line-end-position))
2155 (forward-comment -9999)
2156 (setq min-indent (current-indentation))
2157 (while (python-beginning-of-defun-function 1 t)
2158 (when (< (current-indentation) min-indent)
2159 (setq min-indent (current-indentation))
2160 (looking-at python-nav-beginning-of-defun-regexp)
2162 (if (not include-type)
2163 (match-string-no-properties 1)
2164 (mapconcat 'identity
2166 (match-string-no-properties 0)) " "))
2169 (mapconcat (lambda (string) string) names "."))))
2171 (defun python-info-closing-block ()
2172 "Return the point of the block the current line closes."
2173 (let ((closing-word (save-excursion
2174 (back-to-indentation)
2176 (indentation (current-indentation)))
2177 (when (member closing-word python-indent-dedenters)
2180 (while (and (> (current-indentation) indentation)
2182 (not (back-to-indentation))
2184 (back-to-indentation)
2186 ((not (equal indentation (current-indentation))) nil)
2187 ((string= closing-word "elif")
2188 (when (member (current-word) '("if" "elif"))
2190 ((string= closing-word "else")
2191 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2193 ((string= closing-word "except")
2194 (when (member (current-word) '("try"))
2196 ((string= closing-word "finally")
2197 (when (member (current-word) '("except" "else"))
2198 (point-marker))))))))
2200 (defun python-info-line-ends-backslash-p ()
2201 "Return non-nil if current line ends with backslash."
2202 (string= (or (ignore-errors
2205 (- (line-end-position) 1))) "") "\\"))
2207 (defun python-info-continuation-line-p ()
2208 "Return non-nil if current line is continuation of another."
2209 (or (python-info-line-ends-backslash-p)
2210 (string-match ",[[:space:]]*$" (buffer-substring
2211 (line-beginning-position)
2212 (line-end-position)))
2214 (let ((innermost-paren (progn
2215 (goto-char (line-end-position))
2216 (python-info-ppss-context 'paren))))
2217 (when (and innermost-paren
2218 (and (<= (line-beginning-position) innermost-paren)
2219 (>= (line-end-position) innermost-paren)))
2220 (goto-char innermost-paren)
2221 (looking-at (python-rx open-paren (* space) line-end)))))
2223 (back-to-indentation)
2224 (python-info-ppss-context 'paren))))
2226 (defun python-info-block-continuation-line-p ()
2227 "Return non-nil if current line is a continuation of a block."
2229 (while (and (not (bobp))
2230 (python-info-continuation-line-p))
2233 (back-to-indentation)
2234 (when (looking-at (python-rx block-start))
2237 (defun python-info-assignment-continuation-line-p ()
2238 "Return non-nil if current line is a continuation of an assignment."
2240 (while (and (not (bobp))
2241 (python-info-continuation-line-p))
2244 (back-to-indentation)
2245 (when (and (not (looking-at (python-rx block-start)))
2247 (and (re-search-forward (python-rx not-simple-operator
2249 not-simple-operator)
2250 (line-end-position) t)
2251 (not (or (python-info-ppss-context 'string)
2252 (python-info-ppss-context 'paren)
2253 (python-info-ppss-context 'comment))))))
2256 (defun python-info-ppss-context (type &optional syntax-ppss)
2257 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2258 TYPE can be 'comment, 'string or 'parent. It returns the start
2259 character address of the specified TYPE."
2260 (let ((ppss (or syntax-ppss (syntax-ppss))))
2272 ;;; Utility functions
2275 (defun python-util-merge (type list1 list2 pred)
2276 "Destructively merge lists to produce a new one.
2277 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2278 are the list to be merged. Ordering of the elements is preserved
2279 according to PRED, a `less-than' predicate on the elements."
2281 (while (and list1 list2)
2282 (if (funcall pred (car list2) (car list1))
2283 (push (pop list2) res)
2284 (push (pop list1) res)))
2285 (nconc (nreverse res) list1 list2)))
2287 (defun python-util-position (item seq)
2288 "Find the first occurrence of ITEM in SEQ.
2289 Return the index of the matching item, or nil if not found."
2290 (let ((member-result (member item seq)))
2292 (- (length seq) (length member-result)))))
2296 (define-derived-mode python-mode fundamental-mode "Python"
2297 "Major mode for editing Python files.
2300 Entry to this mode calls the value of `python-mode-hook'
2301 if that value is non-nil."
2302 (set (make-local-variable 'tab-width) 8)
2303 (set (make-local-variable 'indent-tabs-mode) nil)
2305 (set (make-local-variable 'comment-start) "# ")
2306 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2308 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2309 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2311 (set (make-local-variable 'font-lock-defaults)
2312 '(python-font-lock-keywords
2314 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2316 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2317 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2319 (set (make-local-variable 'paragraph-start) "\\s-*$")
2320 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2322 (set (make-local-variable 'beginning-of-defun-function)
2323 #'python-beginning-of-defun-function)
2324 (set (make-local-variable 'end-of-defun-function)
2325 #'python-end-of-defun-function)
2327 (add-hook 'completion-at-point-functions
2328 'python-completion-complete-at-point nil 'local)
2330 (setq imenu-create-index-function #'python-imenu-create-index)
2332 (set (make-local-variable 'add-log-current-defun-function)
2333 #'python-info-current-defun)
2335 (set (make-local-variable 'skeleton-further-elements)
2337 (< '(backward-delete-char-untabify (min python-indent-offset
2339 (^ '(- (1+ (current-indentation))))))
2341 (set (make-local-variable 'eldoc-documentation-function)
2342 #'python-eldoc-function)
2344 (add-to-list 'hs-special-modes-alist
2345 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2347 (python-end-of-defun-function)) nil))
2349 (set (make-local-variable 'outline-regexp)
2350 (python-rx (* space) block-start))
2351 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2352 (set (make-local-variable 'outline-level)
2354 "`outline-level' function for Python mode."
2355 (1+ (/ (current-indentation) python-indent-offset))))
2357 (python-skeleton-add-menu-items)
2359 (when python-indent-guess-indent-offset
2360 (python-indent-guess-indent-offset)))
2364 ;;; python.el ends here