1 ;;; python.el -- Python's flying circus support for Emacs
3 ;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
10 ;; Keywords: languages
12 ;; This file is NOT part of GNU Emacs.
14 ;; python.el is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; python.el is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with python.el. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; While it probably has less features than Dave Love's python.el and
34 ;; PSF's python-mode.el it provides the main stuff you'll need while
35 ;; keeping it simple :)
37 ;; Implements Syntax highlighting, Indentation, Movement, Shell
38 ;; interaction, Shell completion, Pdb tracking, Symbol completion,
39 ;; Skeletons, FFAP, Code Check, Eldoc, imenu.
41 ;; Syntax highlighting: Fontification of code is provided and supports
42 ;; python's triple quoted strings properly.
44 ;; Indentation: Automatic indentation with indentation cycling is
45 ;; provided, it allows you to navigate different available levels of
46 ;; indentation by hitting <tab> several times. Also when inserting a
47 ;; colon the `python-indent-electric-colon' command is invoked and
48 ;; causes the current line to be dedented automatically if needed.
50 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
51 ;; properly implemented. Also there are specialized
52 ;; `forward-sentence' and `backward-sentence' replacements
53 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
54 ;; respectively). Extra functions `python-nav-sentence-start' and
55 ;; `python-nav-sentence-end' are included to move to the beginning and
56 ;; to the end of a setence while taking care of multiline definitions.
58 ;; Shell interaction: is provided and allows you easily execute any
59 ;; block of code of your current buffer in an inferior Python process.
61 ;; Shell completion: hitting tab will try to complete the current
62 ;; word. Shell completion is implemented in a manner that if you
63 ;; change the `python-shell-interpreter' to any other (for example
64 ;; IPython) it should be easy to integrate another way to calculate
65 ;; completions. You just need to specify your custom
66 ;; `python-shell-completion-setup-code' and
67 ;; `python-shell-completion-string-code'.
69 ;; Here is a complete example of the settings you would use for
73 ;; python-shell-interpreter "ipython"
74 ;; python-shell-interpreter-args ""
75 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
76 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
77 ;; python-shell-completion-setup-code ""
78 ;; python-shell-completion-string-code
79 ;; "';'.join(__IP.complete('''%s'''))\n")
81 ;; Please note that the default completion system depends on the
82 ;; readline module, so if you are using some Operating System that
83 ;; bundles Python without it (like Windows) just install the
84 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
85 ;; you should be good to go.
87 ;; The shell also contains support for virtualenvs and other special
88 ;; environment modification thanks to
89 ;; `python-shell-process-environment' and `python-shell-exec-path'.
90 ;; These two variables allows you to modify execution paths and
91 ;; enviroment variables to make easy for you to setup virtualenv rules
92 ;; or behaviors modifications when running shells. Here is an example
93 ;; of how to make shell processes to be run using the /path/to/env/
96 ;; (setq python-shell-process-environment
98 ;; (format "PATH=%s" (mapconcat
101 ;; (cons (getenv "PATH")
102 ;; '("/path/to/env/bin/")))
104 ;; "VIRTUAL_ENV=/path/to/env/"))
105 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
107 ;; Pdb tracking: when you execute a block of code that contains some
108 ;; call to pdb (or ipdb) it will prompt the block of code and will
109 ;; follow the execution of pdb marking the current line with an arrow.
111 ;; Symbol completion: you can complete the symbol at point. It uses
112 ;; the shell completion in background so you should run
113 ;; `python-shell-send-buffer' from time to time to get better results.
115 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
116 ;; def, for, if, try and while. These skeletons are integrated with
117 ;; dabbrev. If you have `dabbrev-mode' activated and
118 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
119 ;; the name of any of those defined and hit SPC, they will be
120 ;; automatically expanded.
122 ;; FFAP: You can find the filename for a given module when using ffap
123 ;; out of the box. This feature needs an inferior python shell
126 ;; Code check: Check the current file for errors with `python-check'
127 ;; using the program defined in `python-check-command'.
129 ;; Eldoc: returns documentation for object at point by using the
130 ;; inferior python subprocess to inspect its documentation. As you
131 ;; might guessed you should run `python-shell-send-buffer' from time
132 ;; to time to get better results too.
134 ;; imenu: This mode supports imenu. It builds a plain or tree menu
135 ;; depending on the value of `python-imenu-make-tree'. Also you can
136 ;; customize if menu items should include its type using
137 ;; `python-imenu-include-defun-type'.
139 ;; If you used python-mode.el you probably will miss auto-indentation
140 ;; when inserting newlines. To achieve the same behavior you have
143 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
145 ;; 2) Add the following hook in your .emacs:
147 ;; (add-hook 'python-mode-hook
149 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
151 ;; I'd recommend the first one since you'll get the same behavior for
152 ;; all modes out-of-the-box.
156 ;; Add this to your .emacs:
158 ;; (add-to-list 'load-path "/folder/containing/file")
163 ;; Ordered by priority:
165 ;; Better decorator support for beginning of defun
167 ;; Review code and cleanup
171 (require 'ansi-color)
176 ;; Avoid compiler warnings
177 (defvar view-return-to-alist)
178 (defvar compilation-error-regexp-alist)
179 (defvar outline-heading-end-regexp))
181 (autoload 'comint-mode "comint")
184 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
186 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
189 "Python Language's flying circus support for Emacs."
192 :link '(emacs-commentary-link "python"))
197 (defvar python-mode-map
198 (let ((map (make-sparse-keymap)))
200 (substitute-key-definition 'backward-sentence
201 'python-nav-backward-sentence
203 (substitute-key-definition 'forward-sentence
204 'python-nav-forward-sentence
207 (define-key map "\177" 'python-indent-dedent-line-backspace)
208 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
209 (define-key map "\C-c<" 'python-indent-shift-left)
210 (define-key map "\C-c>" 'python-indent-shift-right)
211 (define-key map ":" 'python-indent-electric-colon)
213 (define-key map "\C-c\C-tc" 'python-skeleton-class)
214 (define-key map "\C-c\C-td" 'python-skeleton-def)
215 (define-key map "\C-c\C-tf" 'python-skeleton-for)
216 (define-key map "\C-c\C-ti" 'python-skeleton-if)
217 (define-key map "\C-c\C-tt" 'python-skeleton-try)
218 (define-key map "\C-c\C-tw" 'python-skeleton-while)
220 (define-key map "\C-c\C-s" 'python-shell-send-string)
221 (define-key map "\C-c\C-r" 'python-shell-send-region)
222 (define-key map "\C-\M-x" 'python-shell-send-defun)
223 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
224 (define-key map "\C-c\C-l" 'python-shell-send-file)
225 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
226 ;; Some util commands
227 (define-key map "\C-c\C-v" 'python-check)
228 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
230 (substitute-key-definition 'complete-symbol 'completion-at-point
232 (easy-menu-define python-menu map "Python Mode menu"
234 :help "Python-specific Features"
235 ["Shift region left" python-indent-shift-left :active mark-active
236 :help "Shift region left by a single indentation step"]
237 ["Shift region right" python-indent-shift-right :active mark-active
238 :help "Shift region right by a single indentation step"]
240 ["Mark def/class" mark-defun
241 :help "Mark outermost definition around point"]
243 ["Start of def/class" beginning-of-defun
244 :help "Go to start of outermost definition around point"]
245 ["End of def/class" end-of-defun
246 :help "Go to end of definition around point"]
250 ["Start interpreter" run-python
251 :help "Run inferior Python process in a separate buffer"]
252 ["Switch to shell" python-shell-switch-to-shell
253 :help "Switch to running inferior Python process"]
254 ["Eval string" python-shell-send-string
255 :help "Eval string in inferior Python session"]
256 ["Eval buffer" python-shell-send-buffer
257 :help "Eval buffer in inferior Python session"]
258 ["Eval region" python-shell-send-region
259 :help "Eval region in inferior Python session"]
260 ["Eval defun" python-shell-send-defun
261 :help "Eval defun in inferior Python session"]
262 ["Eval file" python-shell-send-file
263 :help "Eval file in inferior Python session"]
264 ["Debugger" pdb :help "Run pdb under GUD"]
266 ["Check file" python-check
267 :help "Check file for errors"]
268 ["Help on symbol" python-eldoc-at-point
269 :help "Get help on symbol at point"]
270 ["Complete symbol" completion-at-point
271 :help "Complete symbol before point"]))
273 "Keymap for `python-mode'.")
276 ;;; Python specialized rx
279 (defconst python-rx-constituents
281 `(block-start . ,(rx symbol-start
282 (or "def" "class" "if" "elif" "else" "try"
283 "except" "finally" "for" "while" "with")
285 `(decorator . ,(rx line-start (* space) ?@ (any letter ?_)
287 `(defun . ,(rx symbol-start (or "def" "class") symbol-end))
288 `(symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
289 `(open-paren . ,(rx (or "{" "[" "(")))
290 `(close-paren . ,(rx (or "}" "]" ")")))
291 `(simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
292 `(not-simple-operator . ,(rx (not (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
293 `(operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
294 "=" "%" "**" "//" "<<" ">>" "<=" "!="
295 "==" ">=" "is" "not")))
296 `(assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
297 ">>=" "<<=" "&=" "^=" "|="))))
298 "Additional Python specific sexps for `python-rx'"))
300 (defmacro python-rx (&rest regexps)
301 "Python mode specialized rx macro which supports common python named REGEXPS."
302 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
303 (cond ((null regexps)
306 (rx-to-string `(and ,@regexps) t))
308 (rx-to-string (car regexps) t)))))
311 ;;; Font-lock and syntax
313 (defvar python-font-lock-keywords
316 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
317 "assert" "else" "if" "pass" "yield" "break" "except" "import"
318 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
319 "return" "def" "for" "lambda" "try" "self")
322 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
323 (1 font-lock-function-name-face))
325 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
326 (1 font-lock-type-face))
328 (,(rx symbol-start (group "None" symbol-end))
329 (1 font-lock-constant-face))
331 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
332 (0+ "." (1+ (or word ?_)))))
333 (1 font-lock-type-face))
334 ;; Builtin Exceptions
336 (or "ArithmeticError" "AssertionError" "AttributeError"
337 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
338 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
339 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
340 "ImportWarning" "IndentationError" "IndexError" "KeyError"
341 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
342 "NotImplemented" "NotImplementedError" "OSError" "OverflowError"
343 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
344 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
345 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
346 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
347 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
348 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
349 symbol-end) . font-lock-type-face)
351 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
353 (or "_" "__debug__" "__doc__" "__import__" "__name__" "__package__"
354 "abs" "all" "any" "apply" "basestring" "bin" "bool" "buffer"
355 "bytearray" "bytes" "callable" "chr" "classmethod" "cmp" "coerce"
356 "compile" "complex" "copyright" "credits" "delattr" "dict" "dir"
357 "divmod" "enumerate" "eval" "execfile" "exit" "file" "filter"
358 "float" "format" "frozenset" "getattr" "globals" "hasattr" "hash"
359 "help" "hex" "id" "input" "int" "intern" "isinstance" "issubclass"
360 "iter" "len" "license" "list" "locals" "long" "map" "max" "min"
361 "next" "object" "oct" "open" "ord" "pow" "print" "property" "quit"
362 "range" "raw_input" "reduce" "reload" "repr" "reversed" "round"
363 "set" "setattr" "slice" "sorted" "staticmethod" "str" "sum"
364 "super" "tuple" "type" "unichr" "unicode" "vars" "xrange" "zip"
365 "True" "False" "Ellipsis")) symbol-end)
366 (1 font-lock-builtin-face))
368 ;; support for a = b = c = 5
370 (let ((re (python-rx (group (+ (any word ?. ?_)))
371 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
372 assignment-operator)))
373 (when (re-search-forward re limit t)
374 (while (and (python-info-ppss-context 'paren)
375 (re-search-forward re limit t)))
376 (if (and (not (python-info-ppss-context 'paren))
377 (not (equal (char-after (point-marker)) ?=)))
379 (set-match-data nil)))))
380 (1 font-lock-variable-name-face nil nil))
381 ;; support for a, b, c = (1, 2, 3)
383 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
384 (* ?, (* space) (+ (any word ?. ?_)) (* space))
385 ?, (* space) (+ (any word ?. ?_)) (* space)
386 assignment-operator)))
387 (when (and (re-search-forward re limit t)
388 (goto-char (nth 3 (match-data))))
389 (while (and (python-info-ppss-context 'paren)
390 (re-search-forward re limit t))
391 (goto-char (nth 3 (match-data))))
392 (if (not (python-info-ppss-context 'paren))
394 (set-match-data nil)))))
395 (1 font-lock-variable-name-face nil nil))))
397 ;; Fixme: Is there a better way?
398 (defconst python-font-lock-syntactic-keywords
399 ;; First avoid a sequence preceded by an odd number of backslashes.
400 `((,(rx (not (any ?\\))
401 ?\\ (* (and ?\\ ?\\))
402 (group (syntax string-quote))
405 (2 ,(string-to-syntax "\""))) ; dummy
406 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
407 (optional (any "rR")) ; possible second prefix
408 (group (syntax string-quote)) ; maybe gets property
409 (backref 2) ; per first quote
410 (group (backref 2))) ; maybe gets property
411 (1 (python-quote-syntax 1))
412 (2 (python-quote-syntax 2))
413 (3 (python-quote-syntax 3))))
414 "Make outer chars of triple-quote strings into generic string delimiters.")
416 (defun python-quote-syntax (n)
417 "Put `syntax-table' property correctly on triple quote.
418 Used for syntactic keywords. N is the match number (1, 2 or 3)."
419 ;; Given a triple quote, we have to check the context to know
420 ;; whether this is an opening or closing triple or whether it's
421 ;; quoted anyhow, and should be ignored. (For that we need to do
422 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
423 ;; to use it here despite initial worries.) We also have to sort
424 ;; out a possible prefix -- well, we don't _have_ to, but I think it
425 ;; should be treated as part of the string.
428 ;; ur"""ar""" x='"' # """
431 ;; x '"""' x """ \"""" x
433 (goto-char (match-beginning 0))
435 ;; Consider property for the last char if in a fenced string.
437 (let* ((font-lock-syntactic-keywords nil)
438 (syntax (syntax-ppss)))
439 (when (eq t (nth 3 syntax)) ; after unclosed fence
440 (goto-char (nth 8 syntax)) ; fence position
441 (skip-chars-forward "uUrR") ; skip any prefix
442 ;; Is it a matching sequence?
443 (if (eq (char-after) (char-after (match-beginning 2)))
444 (eval-when-compile (string-to-syntax "|"))))))
445 ;; Consider property for initial char, accounting for prefixes.
446 ((or (and (= n 2) ; leading quote (not prefix)
447 (= (match-beginning 1) (match-end 1))) ; prefix is null
448 (and (= n 1) ; prefix
449 (/= (match-beginning 1) (match-end 1)))) ; non-empty
450 (let ((font-lock-syntactic-keywords nil))
451 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
452 (eval-when-compile (string-to-syntax "|")))))
453 ;; Otherwise (we're in a non-matching string) the property is
457 (defvar python-mode-syntax-table
458 (let ((table (make-syntax-table)))
459 ;; Give punctuation syntax to ASCII that normally has symbol
460 ;; syntax or has word syntax and isn't a letter.
461 (let ((symbol (string-to-syntax "_"))
462 (sst (standard-syntax-table)))
465 (if (equal symbol (aref sst i))
466 (modify-syntax-entry i "." table)))))
467 (modify-syntax-entry ?$ "." table)
468 (modify-syntax-entry ?% "." table)
470 (modify-syntax-entry ?# "<" table)
471 (modify-syntax-entry ?\n ">" table)
472 (modify-syntax-entry ?' "\"" table)
473 (modify-syntax-entry ?` "$" table)
475 "Syntax table for Python files.")
477 (defvar python-dotty-syntax-table
478 (let ((table (make-syntax-table python-mode-syntax-table)))
479 (modify-syntax-entry ?. "w" table)
480 (modify-syntax-entry ?_ "w" table)
482 "Dotty syntax table for Python files.
483 It makes underscores and dots word constituent chars.")
488 (defcustom python-indent-offset 4
489 "Default indentation offset for Python."
494 (defcustom python-indent-guess-indent-offset t
495 "Non-nil tells Python mode to guess `python-indent-offset' value."
499 (defvar python-indent-current-level 0
500 "Current indentation level `python-indent-line-function' is using.")
502 (defvar python-indent-levels '(0)
503 "Levels of indentation available for `python-indent-line-function'.")
505 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
506 "List of words that should be dedented.
507 These make `python-indent-calculate-indentation' subtract the value of
508 `python-indent-offset'.")
510 (defun python-indent-guess-indent-offset ()
511 "Guess and set `python-indent-offset' for the current buffer."
515 (goto-char (point-min))
517 (while (and (not found-block)
519 (python-rx line-start block-start) nil t))
520 (when (and (not (python-info-ppss-context 'string))
521 (not (python-info-ppss-context 'comment))
523 (goto-char (line-end-position))
524 (forward-comment -9999)
525 (eq ?: (char-before))))
526 (setq found-block t)))
527 (if (not found-block)
528 (message "Can't guess python-indent-offset, using defaults: %s"
529 python-indent-offset)
531 (goto-char (line-end-position))
532 (python-info-continuation-line-p))
536 (forward-comment 9999)
537 (let ((indent-offset (current-indentation)))
538 (when (> indent-offset 0)
539 (setq python-indent-offset indent-offset))))))))
541 (defun python-indent-context ()
542 "Get information on indentation context.
543 Context information is returned with a cons with the form:
546 Where status can be any of the following symbols:
547 * inside-paren: If point in between (), {} or []
548 * inside-string: If point is inside a string
549 * after-backslash: Previous line ends in a backslash
550 * after-beginning-of-block: Point is after beginning of block
551 * after-line: Point is after normal line
552 * no-indent: Point is at beginning of buffer or other special case
553 START is the buffer position where the sexp starts."
556 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
560 ;; Beginning of buffer
562 (goto-char (line-beginning-position))
566 ((setq start (python-info-ppss-context 'paren ppss))
569 ((setq start (python-info-ppss-context 'string ppss))
572 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
573 (python-info-ppss-context 'comment ppss)))
574 (let ((line-beg-pos (line-beginning-position)))
575 (when (eq ?\\ (char-before (1- line-beg-pos)))
576 (- line-beg-pos 2)))))
578 ;; After beginning of block
579 ((setq start (save-excursion
580 (let ((block-regexp (python-rx block-start))
581 (block-start-line-end ":[[:space:]]*$"))
582 (back-to-indentation)
583 (while (and (forward-comment -9999) (not (bobp))))
584 (back-to-indentation)
585 (when (or (python-info-continuation-line-p)
586 (and (not (looking-at block-regexp))
590 (line-end-position) t))))
591 (while (and (forward-line -1)
592 (python-info-continuation-line-p)
594 (when (not (looking-at block-regexp))
596 (back-to-indentation)
597 (when (and (looking-at block-regexp)
598 (or (re-search-forward
600 (line-end-position) t)
601 (python-info-continuation-line-p)))
603 'after-beginning-of-block)
605 ((setq start (save-excursion
606 (while (and (forward-comment -9999) (not (bobp))))
607 (python-nav-sentence-start)
614 (defun python-indent-calculate-indentation ()
615 "Calculate correct indentation offset for the current line."
616 (let* ((indentation-context (python-indent-context))
617 (context-status (car indentation-context))
618 (context-start (cdr indentation-context)))
624 ('after-beginning-of-block
625 (goto-char context-start)
626 (+ (current-indentation) python-indent-offset))
630 (goto-char context-start)
631 (current-indentation))
633 (back-to-indentation)
634 (looking-at (regexp-opt python-indent-dedenters)))
638 (goto-char context-start)
639 (current-indentation))
641 (let* ((block-continuation
644 (python-info-block-continuation-line-p)))
645 (assignment-continuation
648 (python-info-assignment-continuation-line-p)))
651 (back-to-indentation)
652 (when (looking-at "\\.")
654 (goto-char (line-end-position))
655 (while (and (re-search-backward "\\." (line-beginning-position) t)
656 (or (python-info-ppss-context 'comment)
657 (python-info-ppss-context 'string)
658 (python-info-ppss-context 'paren))))
659 (if (and (looking-at "\\.")
660 (not (or (python-info-ppss-context 'comment)
661 (python-info-ppss-context 'string)
662 (python-info-ppss-context 'paren))))
664 (+ (current-indentation) python-indent-offset)))))
669 (goto-char block-continuation)
671 (python-rx block-start (* space))
672 (line-end-position) t)
674 (assignment-continuation
675 (goto-char assignment-continuation)
677 (python-rx simple-operator)
678 (line-end-position) t)
681 (python-rx (* space))
682 (line-end-position) t)
685 (goto-char context-start)
688 (back-to-indentation)
690 "\\(?:return\\|from\\|import\\)\s+")))
691 (current-indentation)
692 (+ (current-indentation)
694 (match-string-no-properties 0))))))))
698 (skip-syntax-forward "\s" (line-end-position))
699 (when (and (looking-at (regexp-opt '(")" "]" "}")))
700 (not (forward-char 1))
701 (not (python-info-ppss-context 'paren)))
702 (goto-char context-start)
703 (back-to-indentation)
707 (goto-char context-start)
711 (line-beginning-position)
713 (forward-comment 9999))
715 (+ (current-indentation) python-indent-offset)
716 (forward-comment 9999)
719 (back-to-indentation)
720 (looking-at (regexp-opt '(")" "]" "}"))))
724 (defun python-indent-calculate-levels ()
725 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
726 (let* ((indentation (python-indent-calculate-indentation))
727 (remainder (% indentation python-indent-offset))
728 (steps (/ (- indentation remainder) python-indent-offset)))
729 (setq python-indent-levels (list 0))
730 (dotimes (step steps)
731 (push (* python-indent-offset (1+ step)) python-indent-levels))
732 (when (not (eq 0 remainder))
733 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
734 (setq python-indent-levels (nreverse python-indent-levels))
735 (setq python-indent-current-level (1- (length python-indent-levels)))))
737 (defun python-indent-toggle-levels ()
738 "Toggle `python-indent-current-level' over `python-indent-levels'."
739 (setq python-indent-current-level (1- python-indent-current-level))
740 (when (< python-indent-current-level 0)
741 (setq python-indent-current-level (1- (length python-indent-levels)))))
743 (defun python-indent-line (&optional force-toggle)
744 "Internal implementation of `python-indent-line-function'.
745 Uses the offset calculated in
746 `python-indent-calculate-indentation' and available levels
747 indicated by the variable `python-indent-levels' to set the
750 When the variable `last-command' is equal to
751 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
752 levels indicated in the variable `python-indent-levels' by
753 setting the current level in the variable
754 `python-indent-current-level'.
756 When the variable `last-command' is not equal to
757 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
758 possible indentation levels and saves it in the variable
759 `python-indent-levels'. Afterwards it sets the variable
760 `python-indent-current-level' correctly so offset is equal
761 to (`nth' `python-indent-current-level' `python-indent-levels')"
762 (if (or (and (eq this-command 'indent-for-tab-command)
763 (eq last-command this-command))
765 (if (not (equal python-indent-levels '(0)))
766 (python-indent-toggle-levels)
767 (python-indent-calculate-levels))
768 (python-indent-calculate-levels))
770 (delete-horizontal-space)
771 (indent-to (nth python-indent-current-level python-indent-levels))
774 (let ((closing-block-point (python-info-closing-block)))
775 (when closing-block-point
776 (message "Closes %s" (buffer-substring
779 (goto-char closing-block-point)
780 (line-end-position))))))))
782 (defun python-indent-line-function ()
783 "`indent-line-function' for Python mode.
784 See `python-indent-line' for details."
785 (python-indent-line))
787 (defun python-indent-dedent-line ()
788 "De-indent current line."
790 (when (and (not (or (python-info-ppss-context 'string)
791 (python-info-ppss-context 'comment)))
792 (<= (point-marker) (save-excursion
793 (back-to-indentation)
795 (> (current-column) 0))
796 (python-indent-line t)
799 (defun python-indent-dedent-line-backspace (arg)
800 "De-indent current line.
801 Argument ARG is passed to `backward-delete-char-untabify' when
802 point is not in between the indentation."
804 (when (not (python-indent-dedent-line))
805 (backward-delete-char-untabify arg)))
806 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
808 (defun python-indent-region (start end)
809 "Indent a python region automagically.
811 Called from a program, START and END specify the region to indent."
812 (let ((deactivate-mark nil))
815 (setq end (point-marker))
817 (or (bolp) (forward-line 1))
818 (while (< (point) end)
819 (or (and (bolp) (eolp))
822 (back-to-indentation)
823 (setq word (current-word))
827 (delete-horizontal-space)
828 (indent-to (python-indent-calculate-indentation)))))
830 (move-marker end nil))))
832 (defun python-indent-shift-left (start end &optional count)
833 "Shift lines contained in region START END by COUNT columns to the left.
834 COUNT defaults to `python-indent-offset'. If region isn't
835 active, the current line is shifted. The shifted region includes
836 the lines in which START and END lie. An error is signaled if
837 any lines in the region are indented less than COUNT columns."
840 (list (region-beginning) (region-end) current-prefix-arg)
841 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
843 (setq count (prefix-numeric-value count))
844 (setq count python-indent-offset))
846 (let ((deactivate-mark nil))
849 (while (< (point) end)
850 (if (and (< (current-indentation) count)
851 (not (looking-at "[ \t]*$")))
852 (error "Can't shift all lines enough"))
854 (indent-rigidly start end (- count))))))
856 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
858 (defun python-indent-shift-right (start end &optional count)
859 "Shift lines contained in region START END by COUNT columns to the left.
860 COUNT defaults to `python-indent-offset'. If region isn't
861 active, the current line is shifted. The shifted region includes
862 the lines in which START and END lie."
865 (list (region-beginning) (region-end) current-prefix-arg)
866 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
867 (let ((deactivate-mark nil))
869 (setq count (prefix-numeric-value count))
870 (setq count python-indent-offset))
871 (indent-rigidly start end count)))
873 (defun python-indent-electric-colon (arg)
874 "Insert a colon and maybe de-indent the current line.
875 With numeric ARG, just insert that many colons. With
876 \\[universal-argument], just insert a single colon."
878 (self-insert-command (if (not (integerp arg)) 1 arg))
881 (not (equal ?: (char-after (- (point-marker) 2))))
882 (not (or (python-info-ppss-context 'string)
883 (python-info-ppss-context 'comment))))
884 (let ((indentation (current-indentation))
885 (calculated-indentation (python-indent-calculate-indentation)))
886 (when (> indentation calculated-indentation)
888 (indent-line-to calculated-indentation)
889 (when (not (python-info-closing-block))
890 (indent-line-to indentation)))))))
891 (put 'python-indent-electric-colon 'delete-selection t)
896 (defvar python-nav-beginning-of-defun-regexp
897 (python-rx line-start (* space) defun (+ space) (group symbol-name))
898 "Regular expresion matching beginning of class or function.
899 The name of the defun should be grouped so it can be retrieved
900 via `match-string'.")
902 (defun python-nav-beginning-of-defun (&optional nodecorators)
903 "Move point to `beginning-of-defun'.
904 When NODECORATORS is non-nil decorators are not included. This
905 is the main part of`python-beginning-of-defun-function'
906 implementation. Return non-nil if point is moved to the
907 `beginning-of-defun'."
908 (let ((indent-pos (save-excursion
909 (back-to-indentation)
914 (when (not nodecorators)
915 (when (save-excursion
917 (looking-at (python-rx decorator)))
918 (while (and (not (bobp))
920 (looking-at (python-rx decorator))))
921 (when (not (bobp)) (forward-line 1)))))))
922 (if (and (> (point) indent-pos)
924 (goto-char (line-beginning-position))
925 (looking-at python-nav-beginning-of-defun-regexp)))
927 (goto-char (line-beginning-position))
928 (funcall include-decorators)
930 (goto-char (line-beginning-position))
931 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
933 (goto-char (or (python-info-ppss-context 'string) (point)))
934 (funcall include-decorators))
937 (defun python-beginning-of-defun-function (&optional arg nodecorators)
938 "Move point to the beginning of def or class.
939 With positive ARG move that number of functions forward. With
940 negative do the same but backwards. When NODECORATORS is non-nil
941 decorators are not included. Return non-nil if point is moved to the
942 `beginning-of-defun'."
943 (when (or (null arg) (= arg 0)) (setq arg 1))
945 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
947 (dotimes (i (- arg) found)
948 (python-end-of-defun-function)
949 (forward-comment 9999)
950 (goto-char (line-end-position))
953 (python-nav-beginning-of-defun nodecorators)))))))
955 (defun python-end-of-defun-function ()
956 "Move point to the end of def or class.
957 Returns nil if point is not in a def or class."
959 (let ((beg-defun-indent)
960 (decorator-regexp "[[:space:]]*@"))
961 (when (looking-at decorator-regexp)
962 (while (and (not (eobp))
964 (looking-at decorator-regexp))))
965 (when (not (looking-at python-nav-beginning-of-defun-regexp))
966 (python-beginning-of-defun-function))
967 (setq beg-defun-indent (current-indentation))
969 (while (and (forward-line 1)
971 (or (not (current-word))
972 (> (current-indentation) beg-defun-indent))))
973 (forward-comment 9999)
974 (goto-char (line-beginning-position))))
976 (defun python-nav-sentence-start ()
977 "Move to start of current sentence."
979 (while (and (not (back-to-indentation))
984 (python-info-line-ends-backslash-p))
985 (python-info-ppss-context 'string)
986 (python-info-ppss-context 'paren))
987 (forward-line -1)))))
989 (defun python-nav-sentence-end ()
990 "Move to end of current sentence."
992 (while (and (goto-char (line-end-position))
995 (python-info-line-ends-backslash-p)
996 (python-info-ppss-context 'string)
997 (python-info-ppss-context 'paren))
1000 (defun python-nav-backward-sentence (&optional arg)
1001 "Move backward to start of sentence. With ARG, do it arg times.
1002 See `python-nav-forward-sentence' for more information."
1004 (or arg (setq arg 1))
1005 (python-nav-forward-sentence (- arg)))
1007 (defun python-nav-forward-sentence (&optional arg)
1008 "Move forward to next end of sentence. With ARG, repeat.
1009 With negative argument, move backward repeatedly to start of sentence."
1011 (or arg (setq arg 1))
1013 (forward-comment 9999)
1014 (python-nav-sentence-end)
1016 (setq arg (1- arg)))
1018 (python-nav-sentence-end)
1019 (forward-comment -9999)
1020 (python-nav-sentence-start)
1022 (setq arg (1+ arg))))
1025 ;;; Shell integration
1027 (defvar python-shell-buffer-name "Python"
1028 "Default buffer name for Python interpreter.")
1030 (defcustom python-shell-interpreter "python"
1031 "Default Python interpreter for shell."
1036 (defcustom python-shell-interpreter-args "-i"
1037 "Default arguments for the Python interpreter."
1042 (defcustom python-shell-prompt-regexp ">>> "
1043 "Regular Expression matching top\-level input prompt of python shell.
1044 It should not contain a caret (^) at the beginning."
1049 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1050 "Regular Expression matching block input prompt of python shell.
1051 It should not contain a caret (^) at the beginning."
1056 (defcustom python-shell-prompt-output-regexp nil
1057 "Regular Expression matching output prompt of python shell.
1058 It should not contain a caret (^) at the beginning."
1063 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1064 "Regular Expression matching pdb input prompt of python shell.
1065 It should not contain a caret (^) at the beginning."
1070 (defcustom python-shell-send-setup-max-wait 5
1071 "Seconds to wait for process output before code setup.
1072 If output is received before the especified time then control is
1073 returned in that moment and not after waiting."
1078 (defcustom python-shell-process-environment nil
1079 "List of enviroment variables for Python shell.
1080 This variable follows the same rules as `process-enviroment'
1081 since it merges with it before the process creation routines are
1082 called. When this variable is nil, the Python shell is run with
1083 the default `process-enviroment'."
1084 :type '(repeat string)
1088 (defcustom python-shell-exec-path nil
1089 "List of path to search for binaries.
1090 This variable follows the same rules as `exec-path' since it
1091 merges with it before the process creation routines are called.
1092 When this variable is nil, the Python shell is run with the
1093 default `exec-path'."
1094 :type '(repeat string)
1098 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1099 python-ffap-setup-code
1100 python-eldoc-setup-code)
1101 "List of code run by `python-shell-send-setup-codes'.
1102 Each variable can contain either a simple string with the code to
1103 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1104 is a string with the code to execute and DESCRIPTION is the
1106 :type '(repeat symbol)
1110 (defcustom python-shell-compilation-regexp-alist
1111 `((,(rx line-start (1+ (any " \t")) "File \""
1112 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1113 "\", line " (group (1+ digit)))
1115 (,(rx " in file " (group (1+ not-newline)) " on line "
1118 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1119 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1121 "`compilation-error-regexp-alist' for inferior Python."
1122 :type '(alist string)
1125 (defun python-shell-get-process-name (dedicated)
1126 "Calculate the appropiate process name for inferior Python process.
1127 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1128 returns a string with the form
1129 `python-shell-buffer-name'[variable `buffer-file-name'] else
1130 returns the value of `python-shell-buffer-name'. After
1131 calculating the process name adds the buffer name for the process
1132 in the `same-window-buffer-names' list."
1136 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1137 (format "%s" python-shell-buffer-name))))
1138 (add-to-list 'same-window-buffer-names (purecopy
1139 (format "*%s*" process-name)))
1142 (defun python-shell-parse-command ()
1143 "Calculate the string used to execute the inferior Python process."
1144 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1146 (defun python-comint-output-filter-function (output)
1147 "Hook run after content is put into comint buffer.
1148 OUTPUT is a string with the contents of the buffer."
1149 (ansi-color-filter-apply output))
1151 (defvar inferior-python-mode-current-file nil
1152 "Current file from which a region was sent.")
1153 (make-variable-buffer-local 'inferior-python-mode-current-file)
1155 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1156 "Major mode for Python inferior process.
1157 Runs a Python interpreter as a subprocess of Emacs, with Python
1158 I/O through an Emacs buffer. Variables
1159 `python-shell-interpreter' and `python-shell-interpreter-args'
1160 controls which Python interpreter is run. Variables
1161 `python-shell-prompt-regexp',
1162 `python-shell-prompt-output-regexp',
1163 `python-shell-prompt-block-regexp',
1164 `python-shell-completion-setup-code',
1165 `python-shell-completion-string-code', `python-eldoc-setup-code',
1166 `python-eldoc-string-code', `python-ffap-setup-code' and
1167 `python-ffap-string-code' can customize this mode for different
1168 Python interpreters.
1170 You can also add additional setup code to be run at
1171 initialization of the interpreter via `python-shell-setup-codes'
1174 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1175 (set-syntax-table python-mode-syntax-table)
1176 (setq mode-line-process '(":%s"))
1177 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1178 python-shell-prompt-regexp
1179 python-shell-prompt-block-regexp
1180 python-shell-prompt-pdb-regexp))
1181 (make-local-variable 'comint-output-filter-functions)
1182 (add-hook 'comint-output-filter-functions
1183 'python-comint-output-filter-function)
1184 (add-hook 'comint-output-filter-functions
1185 'python-pdbtrack-comint-output-filter-function)
1186 (set (make-local-variable 'compilation-error-regexp-alist)
1187 python-shell-compilation-regexp-alist)
1188 (define-key inferior-python-mode-map [remap complete-symbol]
1189 'completion-at-point)
1190 (add-hook 'completion-at-point-functions
1191 'python-shell-completion-complete-at-point nil 'local)
1192 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1193 'python-shell-completion-complete-at-point)
1194 (define-key inferior-python-mode-map (kbd "<tab>")
1195 'python-shell-completion-complete-or-indent)
1196 (compilation-shell-minor-mode 1))
1198 (defun run-python (dedicated cmd)
1199 "Run an inferior Python process.
1200 Input and output via buffer named after
1201 `python-shell-buffer-name'. If there is a process already
1202 running in that buffer, just switch to it.
1203 With argument, allows you to define DEDICATED, so a dedicated
1204 process for the current buffer is open, and define CMD so you can
1205 edit the command used to call the interpreter (default is value
1206 of `python-shell-interpreter' and arguments defined in
1207 `python-shell-interpreter-args'). Runs the hook
1208 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1210 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1212 (if current-prefix-arg
1214 (y-or-n-p "Make dedicated process? ")
1215 (read-string "Run Python: " (python-shell-parse-command)))
1216 (list nil (python-shell-parse-command))))
1217 (let* ((proc-name (python-shell-get-process-name dedicated))
1218 (proc-buffer-name (format "*%s*" proc-name))
1219 (process-environment
1220 (if python-shell-process-environment
1221 (python-util-merge 'list python-shell-process-environment
1222 process-environment 'string=)
1223 process-environment))
1225 (if python-shell-exec-path
1226 (python-util-merge 'list python-shell-exec-path
1229 (when (not (comint-check-proc proc-buffer-name))
1230 (let ((cmdlist (split-string-and-unquote cmd)))
1232 (apply 'make-comint proc-name (car cmdlist) nil
1234 (inferior-python-mode)))
1235 (pop-to-buffer proc-buffer-name))
1238 (defun python-shell-get-process ()
1239 "Get inferior Python process for current buffer and return it."
1240 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1241 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1242 (global-proc-name (python-shell-get-process-name nil))
1243 (global-proc-buffer-name (format "*%s*" global-proc-name))
1244 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1245 (global-running (comint-check-proc global-proc-buffer-name)))
1246 ;; Always prefer dedicated
1247 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1248 (and global-running global-proc-buffer-name)))))
1250 (defun python-shell-get-or-create-process ()
1251 "Get or create an inferior Python process for current buffer and return it."
1252 (let* ((old-buffer (current-buffer))
1253 (dedicated-proc-name (python-shell-get-process-name t))
1254 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1255 (global-proc-name (python-shell-get-process-name nil))
1256 (global-proc-buffer-name (format "*%s*" global-proc-name))
1257 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1258 (global-running (comint-check-proc global-proc-buffer-name))
1259 (current-prefix-arg 4))
1260 (when (and (not dedicated-running) (not global-running))
1261 (if (call-interactively 'run-python)
1262 (setq dedicated-running t)
1263 (setq global-running t)))
1264 ;; Always prefer dedicated
1265 (switch-to-buffer old-buffer)
1266 (get-buffer-process (if dedicated-running
1267 dedicated-proc-buffer-name
1268 global-proc-buffer-name))))
1270 (defun python-shell-send-string (string &optional process msg)
1271 "Send STRING to inferior Python PROCESS.
1272 When MSG is non-nil messages the first line of STRING."
1273 (interactive "sPython command: ")
1274 (let ((process (or process (python-shell-get-or-create-process)))
1275 (lines (split-string string "\n" t)))
1277 (message (format "Sent: %s..." (nth 0 lines))))
1278 (if (> (length lines) 1)
1279 (let* ((temp-file-name (make-temp-file "py"))
1280 (file-name (or (buffer-file-name) temp-file-name)))
1281 (with-temp-file temp-file-name
1283 (delete-trailing-whitespace))
1284 (python-shell-send-file file-name process temp-file-name))
1285 (comint-send-string process string)
1286 (when (or (not (string-match "\n$" string))
1287 (string-match "\n[ \t].*\n?$" string))
1288 (comint-send-string process "\n")))))
1290 (defun python-shell-send-string-no-output (string &optional process msg)
1291 "Send STRING to PROCESS and inhibit output.
1292 When MSG is non-nil messages the first line of STRING. Return
1294 (let* ((output-buffer)
1295 (process (or process (python-shell-get-or-create-process)))
1296 (comint-preoutput-filter-functions
1297 (append comint-preoutput-filter-functions
1298 '(ansi-color-filter-apply
1300 (setq output-buffer (concat output-buffer string))
1302 (python-shell-send-string string process msg)
1303 (accept-process-output process)
1304 ;; Cleanup output prompt regexp
1305 (when (and (not (string= "" output-buffer))
1306 (> (length python-shell-prompt-output-regexp) 0))
1309 (insert output-buffer)
1310 (goto-char (point-min))
1311 (forward-comment 9999)
1312 (buffer-substring-no-properties
1314 (and (looking-at python-shell-prompt-output-regexp)
1316 python-shell-prompt-output-regexp nil t 1))
1320 (lambda (string) string)
1321 (butlast (split-string output-buffer "\n")) "\n")))
1323 (defun python-shell-send-region (start end)
1324 "Send the region delimited by START and END to inferior Python process."
1326 (let ((deactivate-mark nil))
1327 (python-shell-send-string (buffer-substring start end) nil t)))
1329 (defun python-shell-send-buffer ()
1330 "Send the entire buffer to inferior Python process."
1334 (python-shell-send-region (point-min) (point-max))))
1336 (defun python-shell-send-defun (arg)
1337 "Send the current defun to inferior Python process.
1338 When argument ARG is non-nil sends the innermost defun."
1341 (python-shell-send-region
1343 (or (python-beginning-of-defun-function)
1344 (progn (beginning-of-line) (point-marker))))
1346 (or (python-end-of-defun-function)
1347 (progn (end-of-line) (point-marker)))))))
1349 (defun python-shell-send-file (file-name &optional process temp-file-name)
1350 "Send FILE-NAME to inferior Python PROCESS.
1351 If TEMP-FILE-NAME is passed then that file is used for processing
1352 instead, while internally the shell will continue to use
1354 (interactive "fFile to send: ")
1355 (let* ((process (or process (python-shell-get-or-create-process)))
1356 (temp-file-name (when temp-file-name
1357 (expand-file-name temp-file-name)))
1358 (file-name (or (expand-file-name file-name) temp-file-name)))
1359 (when (not file-name)
1360 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1361 (with-current-buffer (process-buffer process)
1362 (setq inferior-python-mode-current-file
1363 (convert-standard-filename file-name)))
1364 (python-shell-send-string
1366 (concat "__pyfile = open('''%s''');"
1367 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1369 (or temp-file-name file-name) file-name)
1372 (defun python-shell-switch-to-shell ()
1373 "Switch to inferior Python process buffer."
1375 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1377 (defun python-shell-send-setup-code ()
1378 "Send all setup code for shell.
1379 This function takes the list of setup code to send from the
1380 `python-shell-setup-codes' list."
1381 (let ((msg "Sent %s")
1382 (process (get-buffer-process (current-buffer))))
1383 (accept-process-output process python-shell-send-setup-max-wait)
1384 (dolist (code python-shell-setup-codes)
1387 (setq msg (cdr code)))
1388 (message (format msg code))
1389 (python-shell-send-string-no-output
1390 (symbol-value code) process)))))
1392 (add-hook 'inferior-python-mode-hook
1393 #'python-shell-send-setup-code)
1396 ;;; Shell completion
1398 (defvar python-shell-completion-setup-code
1402 def __COMPLETER_all_completions(text): []
1405 readline.set_completer(rlcompleter.Completer().complete)
1406 def __COMPLETER_all_completions(text):
1412 res = readline.get_completer()(text, i)
1415 completions.append(res)
1419 "Code used to setup completion in inferior Python processes.")
1421 (defvar python-shell-completion-string-code
1422 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1423 "Python code used to get a string of completions separated by semicolons.")
1425 (defun python-shell-completion--get-completions (input process)
1426 "Retrieve available completions for INPUT using PROCESS."
1427 (with-current-buffer (process-buffer process)
1428 (let ((completions (python-shell-send-string-no-output
1429 (format python-shell-completion-string-code input)
1431 (when (> (length completions) 2)
1432 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1434 (defun python-shell-completion--get-completion (input completions)
1435 "Get completion for INPUT using COMPLETIONS."
1436 (let ((completion (when completions
1437 (try-completion input completions))))
1438 (cond ((eq completion t)
1441 (message "Can't find completion for \"%s\"" input)
1444 ((not (string= input completion))
1447 (message "Making completion list...")
1448 (with-output-to-temp-buffer "*Python Completions*"
1449 (display-completion-list
1450 (all-completions input completions)))
1453 (defun python-shell-completion-complete-at-point ()
1454 "Perform completion at point in inferior Python process."
1456 (with-syntax-table python-dotty-syntax-table
1457 (when (and comint-last-prompt-overlay
1458 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1459 (let* ((process (get-buffer-process (current-buffer)))
1460 (input (substring-no-properties
1461 (or (comint-word (current-word)) "") nil nil)))
1462 (delete-char (- (length input)))
1464 (python-shell-completion--get-completion
1465 input (python-shell-completion--get-completions input process)))))))
1467 (defun python-shell-completion-complete-or-indent ()
1468 "Complete or indent depending on the context.
1469 If content before pointer is all whitespace indent. If not try
1472 (if (string-match "^[[:space:]]*$"
1473 (buffer-substring (comint-line-beginning-position)
1475 (indent-for-tab-command)
1476 (comint-dynamic-complete)))
1479 ;;; PDB Track integration
1481 (defvar python-pdbtrack-stacktrace-info-regexp
1482 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1483 "Regular Expression matching stacktrace information.
1484 Used to extract the current line and module beign inspected. The
1485 regexp should not start with a caret (^) and can contain a string
1486 placeholder (\%s) which is replaced with the filename beign
1487 inspected (so other files in the debugging process are not
1490 (defvar python-pdbtrack-tracking-buffers '()
1491 "Alist containing elements of form (#<buffer> . #<buffer>).
1492 The car of each element of the alist is the tracking buffer and
1493 the cdr is the tracked buffer.")
1495 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1496 "Get/Add a tracked buffer for the current buffer.
1497 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1498 Returns a cons with the form:
1499 * (#<tracking buffer> . #< tracked buffer>)."
1501 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1502 (let* ((file (with-current-buffer (current-buffer)
1503 inferior-python-mode-current-file))
1505 `(,(current-buffer) .
1506 ,(or (get-file-buffer file)
1507 (find-file-noselect file)))))
1508 (set-buffer (cdr tracking-buffers))
1510 (set-buffer (car tracking-buffers))
1511 (setq python-pdbtrack-tracking-buffers
1512 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1515 (defun python-pdbtrack-comint-output-filter-function (output)
1516 "Move overlay arrow to current pdb line in tracked buffer.
1517 Argument OUTPUT is a string with the output from the comint process."
1518 (when (not (string= output ""))
1519 (let ((full-output (ansi-color-filter-apply
1520 (buffer-substring comint-last-input-end
1522 (if (string-match python-shell-prompt-pdb-regexp full-output)
1523 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1527 (format python-pdbtrack-stacktrace-info-regexp
1529 inferior-python-mode-current-file))
1531 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1532 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1533 (tracked-buffer-line-pos))
1535 (with-current-buffer (cdr tracking-buffers)
1536 (set (make-local-variable 'overlay-arrow-string) "=>")
1537 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1538 (setq tracked-buffer-line-pos (progn
1539 (goto-char (point-min))
1540 (forward-line (1- line-num))
1542 (when tracked-buffer-window
1543 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1544 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1545 (pop-to-buffer (cdr tracking-buffers))
1546 (switch-to-buffer-other-window (car tracking-buffers)))
1547 (let ((tracking-buffers (assq (current-buffer)
1548 python-pdbtrack-tracking-buffers)))
1549 (when tracking-buffers
1550 (if inferior-python-mode-current-file
1551 (with-current-buffer (cdr tracking-buffers)
1552 (set-marker overlay-arrow-position nil))
1553 (kill-buffer (cdr tracking-buffers)))
1554 (setq python-pdbtrack-tracking-buffers
1555 (assq-delete-all (current-buffer)
1556 python-pdbtrack-tracking-buffers)))))))
1560 ;;; Symbol completion
1562 (defun python-completion-complete-at-point ()
1563 "Complete current symbol at point.
1564 For this to work the best as possible you should call
1565 `python-shell-send-buffer' from time to time so context in
1566 inferior python process is updated properly."
1568 (let ((process (python-shell-get-process)))
1570 (error "Completion needs an inferior Python process running")
1571 (with-syntax-table python-dotty-syntax-table
1572 (let* ((input (substring-no-properties
1573 (or (comint-word (current-word)) "") nil nil))
1574 (completions (python-shell-completion--get-completions
1576 (delete-char (- (length input)))
1578 (python-shell-completion--get-completion
1579 input completions)))))))
1581 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1586 (defcustom python-fill-comment-function 'python-fill-comment
1587 "Function to fill comments.
1588 This is the function used by `python-fill-paragraph-function' to
1594 (defcustom python-fill-string-function 'python-fill-string
1595 "Function to fill strings.
1596 This is the function used by `python-fill-paragraph-function' to
1602 (defcustom python-fill-decorator-function 'python-fill-decorator
1603 "Function to fill decorators.
1604 This is the function used by `python-fill-paragraph-function' to
1610 (defcustom python-fill-paren-function 'python-fill-paren
1611 "Function to fill parens.
1612 This is the function used by `python-fill-paragraph-function' to
1618 (defun python-fill-paragraph-function (&optional justify)
1619 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1620 If any of the current line is in or at the end of a multi-line string,
1621 fill the string or the paragraph of it that point is in, preserving
1622 the string's indentation.
1623 Optional argument JUSTIFY defines if the paragraph should be justified."
1626 (back-to-indentation)
1629 ((funcall python-fill-comment-function justify))
1630 ;; Strings/Docstrings
1631 ((save-excursion (skip-chars-forward "\"'uUrR")
1632 (python-info-ppss-context 'string))
1633 (funcall python-fill-string-function justify))
1635 ((equal (char-after (save-excursion
1636 (back-to-indentation)
1637 (point-marker))) ?@)
1638 (funcall python-fill-decorator-function justify))
1640 ((or (python-info-ppss-context 'paren)
1641 (looking-at (python-rx open-paren))
1643 (skip-syntax-forward "^(" (line-end-position))
1644 (looking-at (python-rx open-paren))))
1645 (funcall python-fill-paren-function justify))
1648 (defun python-fill-comment (&optional justify)
1649 "Comment fill function for `python-fill-paragraph-function'.
1650 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1651 (fill-comment-paragraph justify))
1653 (defun python-fill-string (&optional justify)
1654 "String fill function for `python-fill-paragraph-function'.
1655 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1656 (let ((marker (point-marker))
1657 (string-start-marker
1659 (skip-chars-forward "\"'uUrR")
1660 (goto-char (python-info-ppss-context 'string))
1661 (skip-chars-forward "\"'uUrR")
1663 (reg-start (line-beginning-position))
1666 (while (python-info-ppss-context 'string)
1667 (goto-char (1+ (point-marker))))
1668 (skip-chars-backward "\"'")
1670 (reg-end (line-end-position))
1671 (fill-paragraph-function))
1673 (narrow-to-region reg-start reg-end)
1675 (goto-char string-start-marker)
1676 (delete-region (point-marker) (progn
1677 (skip-syntax-forward "> ")
1679 (goto-char string-end-marker)
1680 (delete-region (point-marker) (progn
1681 (skip-syntax-backward "> ")
1685 (fill-paragraph justify))
1686 ;; If there is a newline in the docstring lets put triple
1687 ;; quote in it's own line to follow pep 8
1688 (when (save-excursion
1689 (re-search-backward "\n" string-start-marker t))
1691 (newline-and-indent))
1692 (fill-paragraph justify)))) t)
1694 (defun python-fill-decorator (&optional justify)
1695 "Decorator fill function for `python-fill-paragraph-function'.
1696 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1699 (defun python-fill-paren (&optional justify)
1700 "Paren fill function for `python-fill-paragraph-function'.
1701 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1703 (narrow-to-region (progn
1704 (while (python-info-ppss-context 'paren)
1705 (goto-char (1- (point-marker))))
1707 (line-beginning-position))
1709 (when (not (python-info-ppss-context 'paren))
1711 (when (not (python-info-ppss-context 'paren))
1712 (skip-syntax-backward "^)")))
1713 (while (python-info-ppss-context 'paren)
1714 (goto-char (1+ (point-marker))))
1716 (let ((paragraph-start "\f\\|[ \t]*$")
1717 (paragraph-separate ",")
1718 (fill-paragraph-function))
1719 (goto-char (point-min))
1720 (fill-paragraph justify))
1723 (python-indent-line)
1724 (goto-char (line-end-position)))) t)
1729 (defcustom python-skeleton-autoinsert nil
1730 "Non-nil means template skeletons will be automagically inserted.
1731 This happens when pressing \"if<SPACE>\", for example, to prompt for
1736 (defvar python-skeleton-available '()
1737 "Internal list of available skeletons.")
1738 (make-variable-buffer-local 'inferior-python-mode-current-file)
1740 (define-abbrev-table 'python-mode-abbrev-table ()
1741 "Abbrev table for Python mode."
1743 ;; Allow / inside abbrevs.
1744 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1745 ;; Only expand in code.
1746 :enable-function (lambda ()
1748 (not (or (python-info-ppss-context 'string)
1749 (python-info-ppss-context 'comment)))
1750 python-skeleton-autoinsert)))
1752 (defmacro python-skeleton-define (name doc &rest skel)
1753 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1754 The skeleton will be bound to python-skeleton-NAME and will
1755 be added to `python-mode-abbrev-table'."
1756 (let* ((name (symbol-name name))
1757 (function-name (intern (concat "python-skeleton-" name))))
1759 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1760 (setq python-skeleton-available
1761 (cons ',function-name python-skeleton-available))
1762 (define-skeleton ,function-name
1764 (format "Insert %s statement." name))
1766 (put 'python-skeleton-define 'lisp-indent-function 2)
1768 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1769 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1770 The skeleton will be bound to python-skeleton-NAME."
1771 (let* ((name (symbol-name name))
1772 (function-name (intern (concat "python-skeleton--" name)))
1774 "Add '%s' clause? " name)))
1777 `(< ,(format "%s:" name) \n \n
1779 `(define-skeleton ,function-name
1781 (format "Auxiliary skeleton for %s statement." name))
1783 (unless (y-or-n-p ,msg)
1786 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1788 (python-define-auxiliary-skeleton else nil)
1790 (python-define-auxiliary-skeleton except nil)
1792 (python-define-auxiliary-skeleton finally nil)
1794 (python-skeleton-define if nil
1798 ("other condition, %s: "
1802 '(python-skeleton--else) | ^)
1804 (python-skeleton-define while nil
1808 '(python-skeleton--else) | ^)
1810 (python-skeleton-define for nil
1814 '(python-skeleton--else) | ^)
1816 (python-skeleton-define try nil
1822 "except " str ":" \n
1825 '(python-skeleton--except)
1826 '(python-skeleton--else)
1827 '(python-skeleton--finally) | ^)
1829 (python-skeleton-define def nil
1831 "def " str " (" ("Parameter, %s: "
1832 (unless (equal ?\( (char-before)) ", ")
1834 "\"\"\"" - "\"\"\"" \n
1837 (python-skeleton-define class nil
1839 "class " str " (" ("Inheritance, %s: "
1840 (unless (equal ?\( (char-before)) ", ")
1844 "\"\"\"" - "\"\"\"" \n
1847 (defun python-skeleton-add-menu-items ()
1848 "Add menu items to Python->Skeletons menu."
1849 (let ((skeletons (sort python-skeleton-available 'string<))
1851 (dolist (skeleton skeletons)
1853 nil '("Python" "Skeletons")
1855 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1860 (defvar python-ffap-setup-code
1861 "def __FFAP_get_module_path(module):
1864 path = __import__(module).__file__
1865 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1870 "Python code to get a module path.")
1872 (defvar python-ffap-string-code
1873 "__FFAP_get_module_path('''%s''')\n"
1874 "Python code used to get a string with the path of a module.")
1876 (defun python-ffap-module-path (module)
1877 "Function for `ffap-alist' to return path for MODULE."
1879 (and (eq major-mode 'inferior-python-mode)
1880 (get-buffer-process (current-buffer)))
1881 (python-shell-get-process))))
1885 (python-shell-send-string-no-output
1886 (format python-ffap-string-code module) process)))
1888 (substring-no-properties module-file 1 -1))))))
1890 (eval-after-load "ffap"
1892 (push '(python-mode . python-ffap-module-path) ffap-alist)
1893 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
1898 (defvar python-check-command
1899 "pychecker --stdlib"
1900 "Command used to check a Python file.")
1902 (defvar python-check-custom-command nil
1905 (defun python-check (command)
1906 "Check a Python file (default current buffer's file).
1907 Runs COMMAND, a shell command, as if by `compile'. See
1908 `python-check-command' for the default."
1910 (list (read-string "Check command: "
1911 (or python-check-custom-command
1912 (concat python-check-command " "
1913 (shell-quote-argument
1915 (let ((name (buffer-file-name)))
1917 (file-name-nondirectory name)))
1919 (setq python-check-custom-command command)
1920 (save-some-buffers (not compilation-ask-about-save) nil)
1921 (compilation-start command))
1926 (defvar python-eldoc-setup-code
1927 "def __PYDOC_get_help(obj):
1930 if hasattr(obj, 'startswith'):
1931 obj = eval(obj, globals())
1932 doc = inspect.getdoc(obj)
1933 if not doc and callable(obj):
1935 if inspect.isclass(obj) and hasattr(obj, '__init__'):
1936 target = obj.__init__
1942 args = inspect.formatargspec(
1943 *inspect.getargspec(target)
1946 doc = '{objtype} {name}{args}'.format(
1947 objtype=objtype, name=name, args=args
1950 doc = doc.splitlines()[0]
1957 "Python code to setup documentation retrieval.")
1959 (defvar python-eldoc-string-code
1960 "__PYDOC_get_help('''%s''')\n"
1961 "Python code used to get a string with the documentation of an object.")
1963 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
1964 "Internal implementation to get documentation at point.
1965 If not FORCE-INPUT is passed then what `current-word' returns
1966 will be used. If not FORCE-PROCESS is passed what
1967 `python-shell-get-process' returns is used."
1968 (let ((process (or force-process (python-shell-get-process))))
1970 "Eldoc needs an inferior Python process running."
1971 (let* ((current-defun (python-info-current-defun))
1972 (input (or force-input
1973 (with-syntax-table python-dotty-syntax-table
1974 (if (not current-defun)
1976 (concat current-defun "." (current-word))))))
1977 (ppss (syntax-ppss))
1978 (help (when (and input
1979 (not (string= input (concat current-defun ".")))
1980 (not (or (python-info-ppss-context 'string ppss)
1981 (python-info-ppss-context 'comment ppss))))
1982 (when (string-match (concat
1983 (regexp-quote (concat current-defun "."))
1987 (goto-char (point-min))
1990 (delete-region (point-marker) (search-forward "self."))
1991 (setq input (buffer-substring (point-min) (point-max)))))
1992 (python-shell-send-string-no-output
1993 (format python-eldoc-string-code input) process))))
1994 (with-current-buffer (process-buffer process)
1995 (when comint-last-prompt-overlay
1996 (delete-region comint-last-input-end
1997 (overlay-start comint-last-prompt-overlay))))
1999 (not (string= help "\n")))
2002 (defun python-eldoc-function ()
2003 "`eldoc-documentation-function' for Python.
2004 For this to work the best as possible you should call
2005 `python-shell-send-buffer' from time to time so context in
2006 inferior python process is updated properly."
2007 (python-eldoc--get-doc-at-point))
2009 (defun python-eldoc-at-point (symbol)
2010 "Get help on SYMBOL using `help'.
2011 Interactively, prompt for symbol."
2013 (let ((symbol (with-syntax-table python-dotty-syntax-table
2015 (enable-recursive-minibuffers t))
2016 (list (read-string (if symbol
2017 (format "Describe symbol (default %s): " symbol)
2018 "Describe symbol: ")
2020 (let ((process (python-shell-get-process)))
2022 (message "Eldoc needs an inferior Python process running.")
2023 (message (python-eldoc--get-doc-at-point symbol process)))))
2028 (defcustom python-imenu-include-defun-type t
2029 "Non-nil make imenu items to include its type."
2034 (defcustom python-imenu-make-tree t
2035 "Non-nil make imenu to build a tree menu.
2036 Set to nil for speed."
2041 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2042 "Label displayed to navigate to root from a subtree.
2043 It can contain a \"%s\" which will be replaced with the root name."
2048 (defvar python-imenu-index-alist nil
2049 "Calculated index tree for imenu.")
2051 (defun python-imenu-tree-assoc (keylist tree)
2052 "Using KEYLIST traverse TREE."
2054 (python-imenu-tree-assoc (cdr keylist)
2055 (ignore-errors (assoc (car keylist) tree)))
2058 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2059 "Make a tree from plain alist of module names.
2060 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2061 is the same thing, the difference is that FULL-ELEMENT remains
2062 untouched in all recursive calls.
2063 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2064 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2066 (let* ((subelement-point (cdr (assoc
2067 (mapconcat #'identity full-element ".")
2069 (subelement-name (car element-list))
2070 (subelement-position (python-util-position
2071 subelement-name full-element))
2072 (subelement-path (when subelement-position
2075 (- (length full-element)
2076 subelement-position)))))
2077 (let ((path-ref (python-imenu-tree-assoc subelement-path
2078 python-imenu-index-alist)))
2080 (push (cons subelement-name subelement-point)
2081 python-imenu-index-alist)
2082 (when (not (listp (cdr path-ref)))
2083 ;; Modifiy root cdr to be a list
2085 (list (cons (format python-imenu-subtree-root-label
2088 (mapconcat #'identity
2089 subelement-path ".")
2091 (when (not (assoc subelement-name path-ref))
2092 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2093 (python-imenu-make-element-tree (cdr element-list)
2094 full-element plain-index))))
2096 (defun python-imenu-make-tree (index)
2097 "Build the imenu alist tree from plain INDEX.
2099 The idea of this function is that given the alist:
2102 (\"Test.__init__\" . 200)
2103 (\"Test.some_method\" . 300)
2104 (\"Test.some_method.another\" . 400)
2105 (\"Test.something_else\" . 500)
2107 (\"test.reprint\" . 700)
2108 (\"test.reprint\" . 800))
2110 This tree gets built:
2112 '((\"Test\" . ((\"jump to...\" . 100)
2113 (\"__init__\" . 200)
2114 (\"some_method\" . ((\"jump to...\" . 300)
2115 (\"another\" . 400)))
2116 (\"something_else\" . 500)))
2117 (\"test\" . ((\"jump to...\" . 600)
2119 (\"reprint\" . 800))))
2121 Internally it uses `python-imenu-make-element-tree' to create all
2122 branches for each element."
2123 (setq python-imenu-index-alist nil)
2124 (mapc (lambda (element)
2125 (python-imenu-make-element-tree element element index))
2126 (mapcar (lambda (element)
2127 (split-string (car element) "\\." t)) index))
2128 python-imenu-index-alist)
2130 (defun python-imenu-create-index ()
2131 "`imenu-create-index-function' for Python."
2133 (goto-char (point-max))
2134 (while (python-beginning-of-defun-function 1 t)
2135 (let ((defun-dotted-name
2136 (python-info-current-defun python-imenu-include-defun-type)))
2137 (push (cons defun-dotted-name (point)) index)))
2138 (if python-imenu-make-tree
2139 (python-imenu-make-tree index)
2145 (defun python-info-current-defun (&optional include-type)
2146 "Return name of surrounding function with Python compatible dotty syntax.
2147 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2148 This function is compatible to be used as
2149 `add-log-current-defun-function' since it returns nil if point is
2150 not inside a defun."
2156 (goto-char (line-end-position))
2157 (forward-comment -9999)
2158 (setq min-indent (current-indentation))
2159 (while (python-beginning-of-defun-function 1 t)
2160 (when (< (current-indentation) min-indent)
2161 (setq min-indent (current-indentation))
2162 (looking-at python-nav-beginning-of-defun-regexp)
2164 (if (not include-type)
2165 (match-string-no-properties 1)
2166 (mapconcat 'identity
2168 (match-string-no-properties 0)) " "))
2171 (mapconcat (lambda (string) string) names "."))))
2173 (defun python-info-closing-block ()
2174 "Return the point of the block the current line closes."
2175 (let ((closing-word (save-excursion
2176 (back-to-indentation)
2178 (indentation (current-indentation)))
2179 (when (member closing-word python-indent-dedenters)
2182 (while (and (> (current-indentation) indentation)
2184 (not (back-to-indentation))
2186 (back-to-indentation)
2188 ((not (equal indentation (current-indentation))) nil)
2189 ((string= closing-word "elif")
2190 (when (member (current-word) '("if" "elif"))
2192 ((string= closing-word "else")
2193 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2195 ((string= closing-word "except")
2196 (when (member (current-word) '("try"))
2198 ((string= closing-word "finally")
2199 (when (member (current-word) '("except" "else"))
2200 (point-marker))))))))
2202 (defun python-info-line-ends-backslash-p ()
2203 "Return non-nil if current line ends with backslash."
2204 (string= (or (ignore-errors
2207 (- (line-end-position) 1))) "") "\\"))
2209 (defun python-info-continuation-line-p ()
2210 "Return non-nil if current line is continuation of another."
2211 (or (python-info-line-ends-backslash-p)
2212 (string-match ",[[:space:]]*$" (buffer-substring
2213 (line-beginning-position)
2214 (line-end-position)))
2216 (let ((innermost-paren (progn
2217 (goto-char (line-end-position))
2218 (python-info-ppss-context 'paren))))
2219 (when (and innermost-paren
2220 (and (<= (line-beginning-position) innermost-paren)
2221 (>= (line-end-position) innermost-paren)))
2222 (goto-char innermost-paren)
2223 (looking-at (python-rx open-paren (* space) line-end)))))
2225 (back-to-indentation)
2226 (python-info-ppss-context 'paren))))
2228 (defun python-info-block-continuation-line-p ()
2229 "Return non-nil if current line is a continuation of a block."
2231 (while (and (not (bobp))
2232 (python-info-continuation-line-p))
2235 (back-to-indentation)
2236 (when (looking-at (python-rx block-start))
2239 (defun python-info-assignment-continuation-line-p ()
2240 "Return non-nil if current line is a continuation of an assignment."
2242 (while (and (not (bobp))
2243 (python-info-continuation-line-p))
2246 (back-to-indentation)
2247 (when (and (not (looking-at (python-rx block-start)))
2249 (and (re-search-forward (python-rx not-simple-operator
2251 not-simple-operator)
2252 (line-end-position) t)
2253 (not (or (python-info-ppss-context 'string)
2254 (python-info-ppss-context 'paren)
2255 (python-info-ppss-context 'comment))))))
2258 (defun python-info-ppss-context (type &optional syntax-ppss)
2259 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2260 TYPE can be 'comment, 'string or 'parent. It returns the start
2261 character address of the specified TYPE."
2262 (let ((ppss (or syntax-ppss (syntax-ppss))))
2274 ;;; Utility functions
2277 (defun python-util-merge (type list1 list2 pred)
2278 "Destructively merge lists to produce a new one.
2279 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2280 are the list to be merged. Ordering of the elements is preserved
2281 according to PRED, a `less-than' predicate on the elements."
2283 (while (and list1 list2)
2284 (if (funcall pred (car list2) (car list1))
2285 (push (pop list2) res)
2286 (push (pop list1) res)))
2287 (nconc (nreverse res) list1 list2)))
2289 (defun python-util-position (item seq)
2290 "Find the first occurrence of ITEM in SEQ.
2291 Return the index of the matching item, or nil if not found."
2292 (let ((member-result (member item seq)))
2294 (- (length seq) (length member-result)))))
2298 (define-derived-mode python-mode fundamental-mode "Python"
2299 "Major mode for editing Python files.
2302 Entry to this mode calls the value of `python-mode-hook'
2303 if that value is non-nil."
2304 (set (make-local-variable 'tab-width) 8)
2305 (set (make-local-variable 'indent-tabs-mode) nil)
2307 (set (make-local-variable 'comment-start) "# ")
2308 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2310 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2311 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2313 (set (make-local-variable 'font-lock-defaults)
2314 '(python-font-lock-keywords
2316 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2318 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2319 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2321 (set (make-local-variable 'paragraph-start) "\\s-*$")
2322 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2324 (set (make-local-variable 'beginning-of-defun-function)
2325 #'python-beginning-of-defun-function)
2326 (set (make-local-variable 'end-of-defun-function)
2327 #'python-end-of-defun-function)
2329 (add-hook 'completion-at-point-functions
2330 'python-completion-complete-at-point nil 'local)
2332 (setq imenu-create-index-function #'python-imenu-create-index)
2334 (set (make-local-variable 'add-log-current-defun-function)
2335 #'python-info-current-defun)
2337 (set (make-local-variable 'skeleton-further-elements)
2339 (< '(backward-delete-char-untabify (min python-indent-offset
2341 (^ '(- (1+ (current-indentation))))))
2343 (set (make-local-variable 'eldoc-documentation-function)
2344 #'python-eldoc-function)
2346 (add-to-list 'hs-special-modes-alist
2347 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2349 (python-end-of-defun-function)) nil))
2351 (set (make-local-variable 'outline-regexp)
2352 (python-rx (* space) block-start))
2353 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2354 (set (make-local-variable 'outline-level)
2356 "`outline-level' function for Python mode."
2357 (1+ (/ (current-indentation) python-indent-offset))))
2359 (python-skeleton-add-menu-items)
2361 (when python-indent-guess-indent-offset
2362 (python-indent-guess-indent-offset)))
2366 ;;; python.el ends here