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))
329 ;; copyright, license, credits, quit, exit are added by the
330 ;; site module and since they are not intended to be used in
331 ;; programs they are not added here either.
332 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
333 symbol-end) . font-lock-constant-face)
335 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
336 (0+ "." (1+ (or word ?_)))))
337 (1 font-lock-type-face))
338 ;; Builtin Exceptions
340 (or "ArithmeticError" "AssertionError" "AttributeError"
341 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
342 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
343 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
344 "ImportWarning" "IndentationError" "IndexError" "KeyError"
345 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
346 "NotImplementedError" "OSError" "OverflowError"
347 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
348 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
349 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
350 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
351 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
352 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
353 symbol-end) . font-lock-type-face)
355 (,(rx (or line-start (not (any ". \t"))) (* (any " \t")) symbol-start
357 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
358 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
359 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
360 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
361 "execfile" "file" "filter" "float" "format" "frozenset"
362 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
363 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
364 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
365 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
366 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
367 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
368 "unichr" "unicode" "vars" "xrange" "zip")) symbol-end)
369 (1 font-lock-builtin-face))
371 ;; support for a = b = c = 5
373 (let ((re (python-rx (group (+ (any word ?. ?_)))
374 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
375 assignment-operator)))
376 (when (re-search-forward re limit t)
377 (while (and (python-info-ppss-context 'paren)
378 (re-search-forward re limit t)))
379 (if (and (not (python-info-ppss-context 'paren))
380 (not (equal (char-after (point-marker)) ?=)))
382 (set-match-data nil)))))
383 (1 font-lock-variable-name-face nil nil))
384 ;; support for a, b, c = (1, 2, 3)
386 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
387 (* ?, (* space) (+ (any word ?. ?_)) (* space))
388 ?, (* space) (+ (any word ?. ?_)) (* space)
389 assignment-operator)))
390 (when (and (re-search-forward re limit t)
391 (goto-char (nth 3 (match-data))))
392 (while (and (python-info-ppss-context 'paren)
393 (re-search-forward re limit t))
394 (goto-char (nth 3 (match-data))))
395 (if (not (python-info-ppss-context 'paren))
397 (set-match-data nil)))))
398 (1 font-lock-variable-name-face nil nil))))
400 ;; Fixme: Is there a better way?
401 (defconst python-font-lock-syntactic-keywords
402 ;; First avoid a sequence preceded by an odd number of backslashes.
403 `((,(rx (not (any ?\\))
404 ?\\ (* (and ?\\ ?\\))
405 (group (syntax string-quote))
408 (2 ,(string-to-syntax "\""))) ; dummy
409 (,(rx (group (optional (any "uUrR"))) ; prefix gets syntax property
410 (optional (any "rR")) ; possible second prefix
411 (group (syntax string-quote)) ; maybe gets property
412 (backref 2) ; per first quote
413 (group (backref 2))) ; maybe gets property
414 (1 (python-quote-syntax 1))
415 (2 (python-quote-syntax 2))
416 (3 (python-quote-syntax 3))))
417 "Make outer chars of triple-quote strings into generic string delimiters.")
419 (defun python-quote-syntax (n)
420 "Put `syntax-table' property correctly on triple quote.
421 Used for syntactic keywords. N is the match number (1, 2 or 3)."
422 ;; Given a triple quote, we have to check the context to know
423 ;; whether this is an opening or closing triple or whether it's
424 ;; quoted anyhow, and should be ignored. (For that we need to do
425 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
426 ;; to use it here despite initial worries.) We also have to sort
427 ;; out a possible prefix -- well, we don't _have_ to, but I think it
428 ;; should be treated as part of the string.
431 ;; ur"""ar""" x='"' # """
434 ;; x '"""' x """ \"""" x
436 (goto-char (match-beginning 0))
438 ;; Consider property for the last char if in a fenced string.
440 (let* ((font-lock-syntactic-keywords nil)
441 (syntax (syntax-ppss)))
442 (when (eq t (nth 3 syntax)) ; after unclosed fence
443 (goto-char (nth 8 syntax)) ; fence position
444 (skip-chars-forward "uUrR") ; skip any prefix
445 ;; Is it a matching sequence?
446 (if (eq (char-after) (char-after (match-beginning 2)))
447 (eval-when-compile (string-to-syntax "|"))))))
448 ;; Consider property for initial char, accounting for prefixes.
449 ((or (and (= n 2) ; leading quote (not prefix)
450 (= (match-beginning 1) (match-end 1))) ; prefix is null
451 (and (= n 1) ; prefix
452 (/= (match-beginning 1) (match-end 1)))) ; non-empty
453 (let ((font-lock-syntactic-keywords nil))
454 (unless (eq 'string (syntax-ppss-context (syntax-ppss)))
455 (eval-when-compile (string-to-syntax "|")))))
456 ;; Otherwise (we're in a non-matching string) the property is
460 (defvar python-mode-syntax-table
461 (let ((table (make-syntax-table)))
462 ;; Give punctuation syntax to ASCII that normally has symbol
463 ;; syntax or has word syntax and isn't a letter.
464 (let ((symbol (string-to-syntax "_"))
465 (sst (standard-syntax-table)))
468 (if (equal symbol (aref sst i))
469 (modify-syntax-entry i "." table)))))
470 (modify-syntax-entry ?$ "." table)
471 (modify-syntax-entry ?% "." table)
473 (modify-syntax-entry ?# "<" table)
474 (modify-syntax-entry ?\n ">" table)
475 (modify-syntax-entry ?' "\"" table)
476 (modify-syntax-entry ?` "$" table)
478 "Syntax table for Python files.")
480 (defvar python-dotty-syntax-table
481 (let ((table (make-syntax-table python-mode-syntax-table)))
482 (modify-syntax-entry ?. "w" table)
483 (modify-syntax-entry ?_ "w" table)
485 "Dotty syntax table for Python files.
486 It makes underscores and dots word constituent chars.")
491 (defcustom python-indent-offset 4
492 "Default indentation offset for Python."
497 (defcustom python-indent-guess-indent-offset t
498 "Non-nil tells Python mode to guess `python-indent-offset' value."
502 (defvar python-indent-current-level 0
503 "Current indentation level `python-indent-line-function' is using.")
505 (defvar python-indent-levels '(0)
506 "Levels of indentation available for `python-indent-line-function'.")
508 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
509 "List of words that should be dedented.
510 These make `python-indent-calculate-indentation' subtract the value of
511 `python-indent-offset'.")
513 (defun python-indent-guess-indent-offset ()
514 "Guess and set `python-indent-offset' for the current buffer."
518 (goto-char (point-min))
520 (while (and (not found-block)
522 (python-rx line-start block-start) nil t))
523 (when (and (not (python-info-ppss-context 'string))
524 (not (python-info-ppss-context 'comment))
526 (goto-char (line-end-position))
527 (forward-comment -9999)
528 (eq ?: (char-before))))
529 (setq found-block t)))
530 (if (not found-block)
531 (message "Can't guess python-indent-offset, using defaults: %s"
532 python-indent-offset)
534 (goto-char (line-end-position))
535 (python-info-continuation-line-p))
539 (forward-comment 9999)
540 (let ((indent-offset (current-indentation)))
541 (when (> indent-offset 0)
542 (setq python-indent-offset indent-offset))))))))
544 (defun python-indent-context ()
545 "Get information on indentation context.
546 Context information is returned with a cons with the form:
549 Where status can be any of the following symbols:
550 * inside-paren: If point in between (), {} or []
551 * inside-string: If point is inside a string
552 * after-backslash: Previous line ends in a backslash
553 * after-beginning-of-block: Point is after beginning of block
554 * after-line: Point is after normal line
555 * no-indent: Point is at beginning of buffer or other special case
556 START is the buffer position where the sexp starts."
559 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
563 ;; Beginning of buffer
565 (goto-char (line-beginning-position))
569 ((setq start (python-info-ppss-context 'paren ppss))
572 ((setq start (python-info-ppss-context 'string ppss))
575 ((setq start (when (not (or (python-info-ppss-context 'string ppss)
576 (python-info-ppss-context 'comment ppss)))
577 (let ((line-beg-pos (line-beginning-position)))
578 (when (eq ?\\ (char-before (1- line-beg-pos)))
579 (- line-beg-pos 2)))))
581 ;; After beginning of block
582 ((setq start (save-excursion
583 (let ((block-regexp (python-rx block-start))
584 (block-start-line-end ":[[:space:]]*$"))
585 (back-to-indentation)
586 (while (and (forward-comment -9999) (not (bobp))))
587 (back-to-indentation)
588 (when (or (python-info-continuation-line-p)
589 (and (not (looking-at block-regexp))
593 (line-end-position) t))))
594 (while (and (forward-line -1)
595 (python-info-continuation-line-p)
597 (when (not (looking-at block-regexp))
599 (back-to-indentation)
600 (when (and (looking-at block-regexp)
601 (or (re-search-forward
603 (line-end-position) t)
604 (python-info-continuation-line-p)))
606 'after-beginning-of-block)
608 ((setq start (save-excursion
609 (while (and (forward-comment -9999) (not (bobp))))
610 (python-nav-sentence-start)
617 (defun python-indent-calculate-indentation ()
618 "Calculate correct indentation offset for the current line."
619 (let* ((indentation-context (python-indent-context))
620 (context-status (car indentation-context))
621 (context-start (cdr indentation-context)))
627 ('after-beginning-of-block
628 (goto-char context-start)
629 (+ (current-indentation) python-indent-offset))
633 (goto-char context-start)
634 (current-indentation))
636 (back-to-indentation)
637 (looking-at (regexp-opt python-indent-dedenters)))
641 (goto-char context-start)
642 (current-indentation))
644 (let* ((block-continuation
647 (python-info-block-continuation-line-p)))
648 (assignment-continuation
651 (python-info-assignment-continuation-line-p)))
654 (back-to-indentation)
655 (when (looking-at "\\.")
657 (goto-char (line-end-position))
658 (while (and (re-search-backward "\\." (line-beginning-position) t)
659 (or (python-info-ppss-context 'comment)
660 (python-info-ppss-context 'string)
661 (python-info-ppss-context 'paren))))
662 (if (and (looking-at "\\.")
663 (not (or (python-info-ppss-context 'comment)
664 (python-info-ppss-context 'string)
665 (python-info-ppss-context 'paren))))
667 (+ (current-indentation) python-indent-offset)))))
672 (goto-char block-continuation)
674 (python-rx block-start (* space))
675 (line-end-position) t)
677 (assignment-continuation
678 (goto-char assignment-continuation)
680 (python-rx simple-operator)
681 (line-end-position) t)
684 (python-rx (* space))
685 (line-end-position) t)
688 (goto-char context-start)
691 (back-to-indentation)
693 "\\(?:return\\|from\\|import\\)\s+")))
694 (current-indentation)
695 (+ (current-indentation)
697 (match-string-no-properties 0))))))))
701 (skip-syntax-forward "\s" (line-end-position))
702 (when (and (looking-at (regexp-opt '(")" "]" "}")))
703 (not (forward-char 1))
704 (not (python-info-ppss-context 'paren)))
705 (goto-char context-start)
706 (back-to-indentation)
710 (goto-char context-start)
714 (line-beginning-position)
716 (forward-comment 9999))
718 (+ (current-indentation) python-indent-offset)
719 (forward-comment 9999)
722 (back-to-indentation)
723 (looking-at (regexp-opt '(")" "]" "}"))))
727 (defun python-indent-calculate-levels ()
728 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
729 (let* ((indentation (python-indent-calculate-indentation))
730 (remainder (% indentation python-indent-offset))
731 (steps (/ (- indentation remainder) python-indent-offset)))
732 (setq python-indent-levels (list 0))
733 (dotimes (step steps)
734 (push (* python-indent-offset (1+ step)) python-indent-levels))
735 (when (not (eq 0 remainder))
736 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
737 (setq python-indent-levels (nreverse python-indent-levels))
738 (setq python-indent-current-level (1- (length python-indent-levels)))))
740 (defun python-indent-toggle-levels ()
741 "Toggle `python-indent-current-level' over `python-indent-levels'."
742 (setq python-indent-current-level (1- python-indent-current-level))
743 (when (< python-indent-current-level 0)
744 (setq python-indent-current-level (1- (length python-indent-levels)))))
746 (defun python-indent-line (&optional force-toggle)
747 "Internal implementation of `python-indent-line-function'.
748 Uses the offset calculated in
749 `python-indent-calculate-indentation' and available levels
750 indicated by the variable `python-indent-levels' to set the
753 When the variable `last-command' is equal to
754 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
755 levels indicated in the variable `python-indent-levels' by
756 setting the current level in the variable
757 `python-indent-current-level'.
759 When the variable `last-command' is not equal to
760 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
761 possible indentation levels and saves it in the variable
762 `python-indent-levels'. Afterwards it sets the variable
763 `python-indent-current-level' correctly so offset is equal
764 to (`nth' `python-indent-current-level' `python-indent-levels')"
765 (if (or (and (eq this-command 'indent-for-tab-command)
766 (eq last-command this-command))
768 (if (not (equal python-indent-levels '(0)))
769 (python-indent-toggle-levels)
770 (python-indent-calculate-levels))
771 (python-indent-calculate-levels))
773 (delete-horizontal-space)
774 (indent-to (nth python-indent-current-level python-indent-levels))
777 (let ((closing-block-point (python-info-closing-block)))
778 (when closing-block-point
779 (message "Closes %s" (buffer-substring
782 (goto-char closing-block-point)
783 (line-end-position))))))))
785 (defun python-indent-line-function ()
786 "`indent-line-function' for Python mode.
787 See `python-indent-line' for details."
788 (python-indent-line))
790 (defun python-indent-dedent-line ()
791 "De-indent current line."
793 (when (and (not (or (python-info-ppss-context 'string)
794 (python-info-ppss-context 'comment)))
795 (<= (point-marker) (save-excursion
796 (back-to-indentation)
798 (> (current-column) 0))
799 (python-indent-line t)
802 (defun python-indent-dedent-line-backspace (arg)
803 "De-indent current line.
804 Argument ARG is passed to `backward-delete-char-untabify' when
805 point is not in between the indentation."
807 (when (not (python-indent-dedent-line))
808 (backward-delete-char-untabify arg)))
809 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
811 (defun python-indent-region (start end)
812 "Indent a python region automagically.
814 Called from a program, START and END specify the region to indent."
815 (let ((deactivate-mark nil))
818 (setq end (point-marker))
820 (or (bolp) (forward-line 1))
821 (while (< (point) end)
822 (or (and (bolp) (eolp))
825 (back-to-indentation)
826 (setq word (current-word))
830 (delete-horizontal-space)
831 (indent-to (python-indent-calculate-indentation)))))
833 (move-marker end nil))))
835 (defun python-indent-shift-left (start end &optional count)
836 "Shift lines contained in region START END by COUNT columns to the left.
837 COUNT defaults to `python-indent-offset'. If region isn't
838 active, the current line is shifted. The shifted region includes
839 the lines in which START and END lie. An error is signaled if
840 any lines in the region are indented less than COUNT columns."
843 (list (region-beginning) (region-end) current-prefix-arg)
844 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
846 (setq count (prefix-numeric-value count))
847 (setq count python-indent-offset))
849 (let ((deactivate-mark nil))
852 (while (< (point) end)
853 (if (and (< (current-indentation) count)
854 (not (looking-at "[ \t]*$")))
855 (error "Can't shift all lines enough"))
857 (indent-rigidly start end (- count))))))
859 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
861 (defun python-indent-shift-right (start end &optional count)
862 "Shift lines contained in region START END by COUNT columns to the left.
863 COUNT defaults to `python-indent-offset'. If region isn't
864 active, the current line is shifted. The shifted region includes
865 the lines in which START and END lie."
868 (list (region-beginning) (region-end) current-prefix-arg)
869 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
870 (let ((deactivate-mark nil))
872 (setq count (prefix-numeric-value count))
873 (setq count python-indent-offset))
874 (indent-rigidly start end count)))
876 (defun python-indent-electric-colon (arg)
877 "Insert a colon and maybe de-indent the current line.
878 With numeric ARG, just insert that many colons. With
879 \\[universal-argument], just insert a single colon."
881 (self-insert-command (if (not (integerp arg)) 1 arg))
884 (not (equal ?: (char-after (- (point-marker) 2))))
885 (not (or (python-info-ppss-context 'string)
886 (python-info-ppss-context 'comment))))
887 (let ((indentation (current-indentation))
888 (calculated-indentation (python-indent-calculate-indentation)))
889 (when (> indentation calculated-indentation)
891 (indent-line-to calculated-indentation)
892 (when (not (python-info-closing-block))
893 (indent-line-to indentation)))))))
894 (put 'python-indent-electric-colon 'delete-selection t)
899 (defvar python-nav-beginning-of-defun-regexp
900 (python-rx line-start (* space) defun (+ space) (group symbol-name))
901 "Regular expresion matching beginning of class or function.
902 The name of the defun should be grouped so it can be retrieved
903 via `match-string'.")
905 (defun python-nav-beginning-of-defun (&optional nodecorators)
906 "Move point to `beginning-of-defun'.
907 When NODECORATORS is non-nil decorators are not included. This
908 is the main part of`python-beginning-of-defun-function'
909 implementation. Return non-nil if point is moved to the
910 `beginning-of-defun'."
911 (let ((indent-pos (save-excursion
912 (back-to-indentation)
917 (when (not nodecorators)
918 (when (save-excursion
920 (looking-at (python-rx decorator)))
921 (while (and (not (bobp))
923 (looking-at (python-rx decorator))))
924 (when (not (bobp)) (forward-line 1)))))))
925 (if (and (> (point) indent-pos)
927 (goto-char (line-beginning-position))
928 (looking-at python-nav-beginning-of-defun-regexp)))
930 (goto-char (line-beginning-position))
931 (funcall include-decorators)
933 (goto-char (line-beginning-position))
934 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t)
936 (goto-char (or (python-info-ppss-context 'string) (point)))
937 (funcall include-decorators))
940 (defun python-beginning-of-defun-function (&optional arg nodecorators)
941 "Move point to the beginning of def or class.
942 With positive ARG move that number of functions forward. With
943 negative do the same but backwards. When NODECORATORS is non-nil
944 decorators are not included. Return non-nil if point is moved to the
945 `beginning-of-defun'."
946 (when (or (null arg) (= arg 0)) (setq arg 1))
948 (dotimes (i arg (python-nav-beginning-of-defun nodecorators)))
950 (dotimes (i (- arg) found)
951 (python-end-of-defun-function)
952 (forward-comment 9999)
953 (goto-char (line-end-position))
956 (python-nav-beginning-of-defun nodecorators)))))))
958 (defun python-end-of-defun-function ()
959 "Move point to the end of def or class.
960 Returns nil if point is not in a def or class."
962 (let ((beg-defun-indent)
963 (decorator-regexp "[[:space:]]*@"))
964 (when (looking-at decorator-regexp)
965 (while (and (not (eobp))
967 (looking-at decorator-regexp))))
968 (when (not (looking-at python-nav-beginning-of-defun-regexp))
969 (python-beginning-of-defun-function))
970 (setq beg-defun-indent (current-indentation))
972 (while (and (forward-line 1)
974 (or (not (current-word))
975 (> (current-indentation) beg-defun-indent))))
976 (forward-comment 9999)
977 (goto-char (line-beginning-position))))
979 (defun python-nav-sentence-start ()
980 "Move to start of current sentence."
982 (while (and (not (back-to-indentation))
987 (python-info-line-ends-backslash-p))
988 (python-info-ppss-context 'string)
989 (python-info-ppss-context 'paren))
990 (forward-line -1)))))
992 (defun python-nav-sentence-end ()
993 "Move to end of current sentence."
995 (while (and (goto-char (line-end-position))
998 (python-info-line-ends-backslash-p)
999 (python-info-ppss-context 'string)
1000 (python-info-ppss-context 'paren))
1001 (forward-line 1)))))
1003 (defun python-nav-backward-sentence (&optional arg)
1004 "Move backward to start of sentence. With ARG, do it arg times.
1005 See `python-nav-forward-sentence' for more information."
1007 (or arg (setq arg 1))
1008 (python-nav-forward-sentence (- arg)))
1010 (defun python-nav-forward-sentence (&optional arg)
1011 "Move forward to next end of sentence. With ARG, repeat.
1012 With negative argument, move backward repeatedly to start of sentence."
1014 (or arg (setq arg 1))
1016 (forward-comment 9999)
1017 (python-nav-sentence-end)
1019 (setq arg (1- arg)))
1021 (python-nav-sentence-end)
1022 (forward-comment -9999)
1023 (python-nav-sentence-start)
1025 (setq arg (1+ arg))))
1028 ;;; Shell integration
1030 (defvar python-shell-buffer-name "Python"
1031 "Default buffer name for Python interpreter.")
1033 (defcustom python-shell-interpreter "python"
1034 "Default Python interpreter for shell."
1039 (defcustom python-shell-interpreter-args "-i"
1040 "Default arguments for the Python interpreter."
1045 (defcustom python-shell-prompt-regexp ">>> "
1046 "Regular Expression matching top\-level input prompt of python shell.
1047 It should not contain a caret (^) at the beginning."
1052 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1053 "Regular Expression matching block input prompt of python shell.
1054 It should not contain a caret (^) at the beginning."
1059 (defcustom python-shell-prompt-output-regexp nil
1060 "Regular Expression matching output prompt of python shell.
1061 It should not contain a caret (^) at the beginning."
1066 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1067 "Regular Expression matching pdb input prompt of python shell.
1068 It should not contain a caret (^) at the beginning."
1073 (defcustom python-shell-send-setup-max-wait 5
1074 "Seconds to wait for process output before code setup.
1075 If output is received before the especified time then control is
1076 returned in that moment and not after waiting."
1081 (defcustom python-shell-process-environment nil
1082 "List of enviroment variables for Python shell.
1083 This variable follows the same rules as `process-enviroment'
1084 since it merges with it before the process creation routines are
1085 called. When this variable is nil, the Python shell is run with
1086 the default `process-enviroment'."
1087 :type '(repeat string)
1091 (defcustom python-shell-exec-path nil
1092 "List of path to search for binaries.
1093 This variable follows the same rules as `exec-path' since it
1094 merges with it before the process creation routines are called.
1095 When this variable is nil, the Python shell is run with the
1096 default `exec-path'."
1097 :type '(repeat string)
1101 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1102 python-ffap-setup-code
1103 python-eldoc-setup-code)
1104 "List of code run by `python-shell-send-setup-codes'.
1105 Each variable can contain either a simple string with the code to
1106 execute or a cons with the form (CODE . DESCRIPTION), where CODE
1107 is a string with the code to execute and DESCRIPTION is the
1109 :type '(repeat symbol)
1113 (defcustom python-shell-compilation-regexp-alist
1114 `((,(rx line-start (1+ (any " \t")) "File \""
1115 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1116 "\", line " (group (1+ digit)))
1118 (,(rx " in file " (group (1+ not-newline)) " on line "
1121 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1122 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1124 "`compilation-error-regexp-alist' for inferior Python."
1125 :type '(alist string)
1128 (defun python-shell-get-process-name (dedicated)
1129 "Calculate the appropiate process name for inferior Python process.
1130 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1131 returns a string with the form
1132 `python-shell-buffer-name'[variable `buffer-file-name'] else
1133 returns the value of `python-shell-buffer-name'. After
1134 calculating the process name adds the buffer name for the process
1135 in the `same-window-buffer-names' list."
1139 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1140 (format "%s" python-shell-buffer-name))))
1141 (add-to-list 'same-window-buffer-names (purecopy
1142 (format "*%s*" process-name)))
1145 (defun python-shell-parse-command ()
1146 "Calculate the string used to execute the inferior Python process."
1147 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1149 (defun python-comint-output-filter-function (output)
1150 "Hook run after content is put into comint buffer.
1151 OUTPUT is a string with the contents of the buffer."
1152 (ansi-color-filter-apply output))
1154 (defvar inferior-python-mode-current-file nil
1155 "Current file from which a region was sent.")
1156 (make-variable-buffer-local 'inferior-python-mode-current-file)
1158 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1159 "Major mode for Python inferior process.
1160 Runs a Python interpreter as a subprocess of Emacs, with Python
1161 I/O through an Emacs buffer. Variables
1162 `python-shell-interpreter' and `python-shell-interpreter-args'
1163 controls which Python interpreter is run. Variables
1164 `python-shell-prompt-regexp',
1165 `python-shell-prompt-output-regexp',
1166 `python-shell-prompt-block-regexp',
1167 `python-shell-completion-setup-code',
1168 `python-shell-completion-string-code', `python-eldoc-setup-code',
1169 `python-eldoc-string-code', `python-ffap-setup-code' and
1170 `python-ffap-string-code' can customize this mode for different
1171 Python interpreters.
1173 You can also add additional setup code to be run at
1174 initialization of the interpreter via `python-shell-setup-codes'
1177 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1178 (set-syntax-table python-mode-syntax-table)
1179 (setq mode-line-process '(":%s"))
1180 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1181 python-shell-prompt-regexp
1182 python-shell-prompt-block-regexp
1183 python-shell-prompt-pdb-regexp))
1184 (make-local-variable 'comint-output-filter-functions)
1185 (add-hook 'comint-output-filter-functions
1186 'python-comint-output-filter-function)
1187 (add-hook 'comint-output-filter-functions
1188 'python-pdbtrack-comint-output-filter-function)
1189 (set (make-local-variable 'compilation-error-regexp-alist)
1190 python-shell-compilation-regexp-alist)
1191 (define-key inferior-python-mode-map [remap complete-symbol]
1192 'completion-at-point)
1193 (add-hook 'completion-at-point-functions
1194 'python-shell-completion-complete-at-point nil 'local)
1195 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1196 'python-shell-completion-complete-at-point)
1197 (define-key inferior-python-mode-map (kbd "<tab>")
1198 'python-shell-completion-complete-or-indent)
1199 (compilation-shell-minor-mode 1))
1201 (defun run-python (dedicated cmd)
1202 "Run an inferior Python process.
1203 Input and output via buffer named after
1204 `python-shell-buffer-name'. If there is a process already
1205 running in that buffer, just switch to it.
1206 With argument, allows you to define DEDICATED, so a dedicated
1207 process for the current buffer is open, and define CMD so you can
1208 edit the command used to call the interpreter (default is value
1209 of `python-shell-interpreter' and arguments defined in
1210 `python-shell-interpreter-args'). Runs the hook
1211 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1213 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1215 (if current-prefix-arg
1217 (y-or-n-p "Make dedicated process? ")
1218 (read-string "Run Python: " (python-shell-parse-command)))
1219 (list nil (python-shell-parse-command))))
1220 (let* ((proc-name (python-shell-get-process-name dedicated))
1221 (proc-buffer-name (format "*%s*" proc-name))
1222 (process-environment
1223 (if python-shell-process-environment
1224 (python-util-merge 'list python-shell-process-environment
1225 process-environment 'string=)
1226 process-environment))
1228 (if python-shell-exec-path
1229 (python-util-merge 'list python-shell-exec-path
1232 (when (not (comint-check-proc proc-buffer-name))
1233 (let ((cmdlist (split-string-and-unquote cmd)))
1235 (apply 'make-comint proc-name (car cmdlist) nil
1237 (inferior-python-mode)))
1238 (pop-to-buffer proc-buffer-name))
1241 (defun python-shell-get-process ()
1242 "Get inferior Python process for current buffer and return it."
1243 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1244 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1245 (global-proc-name (python-shell-get-process-name nil))
1246 (global-proc-buffer-name (format "*%s*" global-proc-name))
1247 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1248 (global-running (comint-check-proc global-proc-buffer-name)))
1249 ;; Always prefer dedicated
1250 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1251 (and global-running global-proc-buffer-name)))))
1253 (defun python-shell-get-or-create-process ()
1254 "Get or create an inferior Python process for current buffer and return it."
1255 (let* ((old-buffer (current-buffer))
1256 (dedicated-proc-name (python-shell-get-process-name t))
1257 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1258 (global-proc-name (python-shell-get-process-name nil))
1259 (global-proc-buffer-name (format "*%s*" global-proc-name))
1260 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1261 (global-running (comint-check-proc global-proc-buffer-name))
1262 (current-prefix-arg 4))
1263 (when (and (not dedicated-running) (not global-running))
1264 (if (call-interactively 'run-python)
1265 (setq dedicated-running t)
1266 (setq global-running t)))
1267 ;; Always prefer dedicated
1268 (switch-to-buffer old-buffer)
1269 (get-buffer-process (if dedicated-running
1270 dedicated-proc-buffer-name
1271 global-proc-buffer-name))))
1273 (defun python-shell-send-string (string &optional process msg)
1274 "Send STRING to inferior Python PROCESS.
1275 When MSG is non-nil messages the first line of STRING."
1276 (interactive "sPython command: ")
1277 (let ((process (or process (python-shell-get-or-create-process)))
1278 (lines (split-string string "\n" t)))
1280 (message (format "Sent: %s..." (nth 0 lines))))
1281 (if (> (length lines) 1)
1282 (let* ((temp-file-name (make-temp-file "py"))
1283 (file-name (or (buffer-file-name) temp-file-name)))
1284 (with-temp-file temp-file-name
1286 (delete-trailing-whitespace))
1287 (python-shell-send-file file-name process temp-file-name))
1288 (comint-send-string process string)
1289 (when (or (not (string-match "\n$" string))
1290 (string-match "\n[ \t].*\n?$" string))
1291 (comint-send-string process "\n")))))
1293 (defun python-shell-send-string-no-output (string &optional process msg)
1294 "Send STRING to PROCESS and inhibit output.
1295 When MSG is non-nil messages the first line of STRING. Return
1297 (let* ((output-buffer)
1298 (process (or process (python-shell-get-or-create-process)))
1299 (comint-preoutput-filter-functions
1300 (append comint-preoutput-filter-functions
1301 '(ansi-color-filter-apply
1303 (setq output-buffer (concat output-buffer string))
1305 (python-shell-send-string string process msg)
1306 (accept-process-output process)
1307 ;; Cleanup output prompt regexp
1308 (when (and (not (string= "" output-buffer))
1309 (> (length python-shell-prompt-output-regexp) 0))
1312 (insert output-buffer)
1313 (goto-char (point-min))
1314 (forward-comment 9999)
1315 (buffer-substring-no-properties
1317 (and (looking-at python-shell-prompt-output-regexp)
1319 python-shell-prompt-output-regexp nil t 1))
1323 (lambda (string) string)
1324 (butlast (split-string output-buffer "\n")) "\n")))
1326 (defun python-shell-send-region (start end)
1327 "Send the region delimited by START and END to inferior Python process."
1329 (let ((deactivate-mark nil))
1330 (python-shell-send-string (buffer-substring start end) nil t)))
1332 (defun python-shell-send-buffer ()
1333 "Send the entire buffer to inferior Python process."
1337 (python-shell-send-region (point-min) (point-max))))
1339 (defun python-shell-send-defun (arg)
1340 "Send the current defun to inferior Python process.
1341 When argument ARG is non-nil sends the innermost defun."
1344 (python-shell-send-region
1346 (or (python-beginning-of-defun-function)
1347 (progn (beginning-of-line) (point-marker))))
1349 (or (python-end-of-defun-function)
1350 (progn (end-of-line) (point-marker)))))))
1352 (defun python-shell-send-file (file-name &optional process temp-file-name)
1353 "Send FILE-NAME to inferior Python PROCESS.
1354 If TEMP-FILE-NAME is passed then that file is used for processing
1355 instead, while internally the shell will continue to use
1357 (interactive "fFile to send: ")
1358 (let* ((process (or process (python-shell-get-or-create-process)))
1359 (temp-file-name (when temp-file-name
1360 (expand-file-name temp-file-name)))
1361 (file-name (or (expand-file-name file-name) temp-file-name)))
1362 (when (not file-name)
1363 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1364 (with-current-buffer (process-buffer process)
1365 (setq inferior-python-mode-current-file
1366 (convert-standard-filename file-name)))
1367 (python-shell-send-string
1369 (concat "__pyfile = open('''%s''');"
1370 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1372 (or temp-file-name file-name) file-name)
1375 (defun python-shell-switch-to-shell ()
1376 "Switch to inferior Python process buffer."
1378 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1380 (defun python-shell-send-setup-code ()
1381 "Send all setup code for shell.
1382 This function takes the list of setup code to send from the
1383 `python-shell-setup-codes' list."
1384 (let ((msg "Sent %s")
1385 (process (get-buffer-process (current-buffer))))
1386 (accept-process-output process python-shell-send-setup-max-wait)
1387 (dolist (code python-shell-setup-codes)
1390 (setq msg (cdr code)))
1391 (message (format msg code))
1392 (python-shell-send-string-no-output
1393 (symbol-value code) process)))))
1395 (add-hook 'inferior-python-mode-hook
1396 #'python-shell-send-setup-code)
1399 ;;; Shell completion
1401 (defvar python-shell-completion-setup-code
1405 def __COMPLETER_all_completions(text): []
1408 readline.set_completer(rlcompleter.Completer().complete)
1409 def __COMPLETER_all_completions(text):
1415 res = readline.get_completer()(text, i)
1418 completions.append(res)
1422 "Code used to setup completion in inferior Python processes.")
1424 (defvar python-shell-completion-string-code
1425 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1426 "Python code used to get a string of completions separated by semicolons.")
1428 (defun python-shell-completion--get-completions (input process)
1429 "Retrieve available completions for INPUT using PROCESS."
1430 (with-current-buffer (process-buffer process)
1431 (let ((completions (python-shell-send-string-no-output
1432 (format python-shell-completion-string-code input)
1434 (when (> (length completions) 2)
1435 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
1437 (defun python-shell-completion--get-completion (input completions)
1438 "Get completion for INPUT using COMPLETIONS."
1439 (let ((completion (when completions
1440 (try-completion input completions))))
1441 (cond ((eq completion t)
1444 (message "Can't find completion for \"%s\"" input)
1447 ((not (string= input completion))
1450 (message "Making completion list...")
1451 (with-output-to-temp-buffer "*Python Completions*"
1452 (display-completion-list
1453 (all-completions input completions)))
1456 (defun python-shell-completion-complete-at-point ()
1457 "Perform completion at point in inferior Python process."
1459 (with-syntax-table python-dotty-syntax-table
1460 (when (and comint-last-prompt-overlay
1461 (> (point-marker) (overlay-end comint-last-prompt-overlay)))
1462 (let* ((process (get-buffer-process (current-buffer)))
1463 (input (substring-no-properties
1464 (or (comint-word (current-word)) "") nil nil)))
1465 (delete-char (- (length input)))
1467 (python-shell-completion--get-completion
1468 input (python-shell-completion--get-completions input process)))))))
1470 (defun python-shell-completion-complete-or-indent ()
1471 "Complete or indent depending on the context.
1472 If content before pointer is all whitespace indent. If not try
1475 (if (string-match "^[[:space:]]*$"
1476 (buffer-substring (comint-line-beginning-position)
1478 (indent-for-tab-command)
1479 (comint-dynamic-complete)))
1482 ;;; PDB Track integration
1484 (defvar python-pdbtrack-stacktrace-info-regexp
1485 "> %s(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1486 "Regular Expression matching stacktrace information.
1487 Used to extract the current line and module beign inspected. The
1488 regexp should not start with a caret (^) and can contain a string
1489 placeholder (\%s) which is replaced with the filename beign
1490 inspected (so other files in the debugging process are not
1493 (defvar python-pdbtrack-tracking-buffers '()
1494 "Alist containing elements of form (#<buffer> . #<buffer>).
1495 The car of each element of the alist is the tracking buffer and
1496 the cdr is the tracked buffer.")
1498 (defun python-pdbtrack-get-or-add-tracking-buffers ()
1499 "Get/Add a tracked buffer for the current buffer.
1500 Internally it uses the `python-pdbtrack-tracking-buffers' alist.
1501 Returns a cons with the form:
1502 * (#<tracking buffer> . #< tracked buffer>)."
1504 (assq (current-buffer) python-pdbtrack-tracking-buffers)
1505 (let* ((file (with-current-buffer (current-buffer)
1506 inferior-python-mode-current-file))
1508 `(,(current-buffer) .
1509 ,(or (get-file-buffer file)
1510 (find-file-noselect file)))))
1511 (set-buffer (cdr tracking-buffers))
1513 (set-buffer (car tracking-buffers))
1514 (setq python-pdbtrack-tracking-buffers
1515 (cons tracking-buffers python-pdbtrack-tracking-buffers))
1518 (defun python-pdbtrack-comint-output-filter-function (output)
1519 "Move overlay arrow to current pdb line in tracked buffer.
1520 Argument OUTPUT is a string with the output from the comint process."
1521 (when (not (string= output ""))
1522 (let ((full-output (ansi-color-filter-apply
1523 (buffer-substring comint-last-input-end
1525 (if (string-match python-shell-prompt-pdb-regexp full-output)
1526 (let* ((tracking-buffers (python-pdbtrack-get-or-add-tracking-buffers))
1530 (format python-pdbtrack-stacktrace-info-regexp
1532 inferior-python-mode-current-file))
1534 (string-to-number (or (match-string-no-properties 1 full-output) ""))))
1535 (tracked-buffer-window (get-buffer-window (cdr tracking-buffers)))
1536 (tracked-buffer-line-pos))
1538 (with-current-buffer (cdr tracking-buffers)
1539 (set (make-local-variable 'overlay-arrow-string) "=>")
1540 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1541 (setq tracked-buffer-line-pos (progn
1542 (goto-char (point-min))
1543 (forward-line (1- line-num))
1545 (when tracked-buffer-window
1546 (set-window-point tracked-buffer-window tracked-buffer-line-pos))
1547 (set-marker overlay-arrow-position tracked-buffer-line-pos)))
1548 (pop-to-buffer (cdr tracking-buffers))
1549 (switch-to-buffer-other-window (car tracking-buffers)))
1550 (let ((tracking-buffers (assq (current-buffer)
1551 python-pdbtrack-tracking-buffers)))
1552 (when tracking-buffers
1553 (if inferior-python-mode-current-file
1554 (with-current-buffer (cdr tracking-buffers)
1555 (set-marker overlay-arrow-position nil))
1556 (kill-buffer (cdr tracking-buffers)))
1557 (setq python-pdbtrack-tracking-buffers
1558 (assq-delete-all (current-buffer)
1559 python-pdbtrack-tracking-buffers)))))))
1563 ;;; Symbol completion
1565 (defun python-completion-complete-at-point ()
1566 "Complete current symbol at point.
1567 For this to work the best as possible you should call
1568 `python-shell-send-buffer' from time to time so context in
1569 inferior python process is updated properly."
1571 (let ((process (python-shell-get-process)))
1573 (error "Completion needs an inferior Python process running")
1574 (with-syntax-table python-dotty-syntax-table
1575 (let* ((input (substring-no-properties
1576 (or (comint-word (current-word)) "") nil nil))
1577 (completions (python-shell-completion--get-completions
1579 (delete-char (- (length input)))
1581 (python-shell-completion--get-completion
1582 input completions)))))))
1584 (add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1589 (defcustom python-fill-comment-function 'python-fill-comment
1590 "Function to fill comments.
1591 This is the function used by `python-fill-paragraph-function' to
1597 (defcustom python-fill-string-function 'python-fill-string
1598 "Function to fill strings.
1599 This is the function used by `python-fill-paragraph-function' to
1605 (defcustom python-fill-decorator-function 'python-fill-decorator
1606 "Function to fill decorators.
1607 This is the function used by `python-fill-paragraph-function' to
1613 (defcustom python-fill-paren-function 'python-fill-paren
1614 "Function to fill parens.
1615 This is the function used by `python-fill-paragraph-function' to
1621 (defun python-fill-paragraph-function (&optional justify)
1622 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1623 If any of the current line is in or at the end of a multi-line string,
1624 fill the string or the paragraph of it that point is in, preserving
1625 the string's indentation.
1626 Optional argument JUSTIFY defines if the paragraph should be justified."
1629 (back-to-indentation)
1632 ((funcall python-fill-comment-function justify))
1633 ;; Strings/Docstrings
1634 ((save-excursion (skip-chars-forward "\"'uUrR")
1635 (python-info-ppss-context 'string))
1636 (funcall python-fill-string-function justify))
1638 ((equal (char-after (save-excursion
1639 (back-to-indentation)
1640 (point-marker))) ?@)
1641 (funcall python-fill-decorator-function justify))
1643 ((or (python-info-ppss-context 'paren)
1644 (looking-at (python-rx open-paren))
1646 (skip-syntax-forward "^(" (line-end-position))
1647 (looking-at (python-rx open-paren))))
1648 (funcall python-fill-paren-function justify))
1651 (defun python-fill-comment (&optional justify)
1652 "Comment fill function for `python-fill-paragraph-function'.
1653 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1654 (fill-comment-paragraph justify))
1656 (defun python-fill-string (&optional justify)
1657 "String fill function for `python-fill-paragraph-function'.
1658 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1659 (let ((marker (point-marker))
1660 (string-start-marker
1662 (skip-chars-forward "\"'uUrR")
1663 (goto-char (python-info-ppss-context 'string))
1664 (skip-chars-forward "\"'uUrR")
1666 (reg-start (line-beginning-position))
1669 (while (python-info-ppss-context 'string)
1670 (goto-char (1+ (point-marker))))
1671 (skip-chars-backward "\"'")
1673 (reg-end (line-end-position))
1674 (fill-paragraph-function))
1676 (narrow-to-region reg-start reg-end)
1678 (goto-char string-start-marker)
1679 (delete-region (point-marker) (progn
1680 (skip-syntax-forward "> ")
1682 (goto-char string-end-marker)
1683 (delete-region (point-marker) (progn
1684 (skip-syntax-backward "> ")
1688 (fill-paragraph justify))
1689 ;; If there is a newline in the docstring lets put triple
1690 ;; quote in it's own line to follow pep 8
1691 (when (save-excursion
1692 (re-search-backward "\n" string-start-marker t))
1694 (newline-and-indent))
1695 (fill-paragraph justify)))) t)
1697 (defun python-fill-decorator (&optional justify)
1698 "Decorator fill function for `python-fill-paragraph-function'.
1699 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1702 (defun python-fill-paren (&optional justify)
1703 "Paren fill function for `python-fill-paragraph-function'.
1704 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1706 (narrow-to-region (progn
1707 (while (python-info-ppss-context 'paren)
1708 (goto-char (1- (point-marker))))
1710 (line-beginning-position))
1712 (when (not (python-info-ppss-context 'paren))
1714 (when (not (python-info-ppss-context 'paren))
1715 (skip-syntax-backward "^)")))
1716 (while (python-info-ppss-context 'paren)
1717 (goto-char (1+ (point-marker))))
1719 (let ((paragraph-start "\f\\|[ \t]*$")
1720 (paragraph-separate ",")
1721 (fill-paragraph-function))
1722 (goto-char (point-min))
1723 (fill-paragraph justify))
1726 (python-indent-line)
1727 (goto-char (line-end-position)))) t)
1732 (defcustom python-skeleton-autoinsert nil
1733 "Non-nil means template skeletons will be automagically inserted.
1734 This happens when pressing \"if<SPACE>\", for example, to prompt for
1739 (defvar python-skeleton-available '()
1740 "Internal list of available skeletons.")
1741 (make-variable-buffer-local 'inferior-python-mode-current-file)
1743 (define-abbrev-table 'python-mode-abbrev-table ()
1744 "Abbrev table for Python mode."
1746 ;; Allow / inside abbrevs.
1747 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1748 ;; Only expand in code.
1749 :enable-function (lambda ()
1751 (not (or (python-info-ppss-context 'string)
1752 (python-info-ppss-context 'comment)))
1753 python-skeleton-autoinsert)))
1755 (defmacro python-skeleton-define (name doc &rest skel)
1756 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1757 The skeleton will be bound to python-skeleton-NAME and will
1758 be added to `python-mode-abbrev-table'."
1759 (let* ((name (symbol-name name))
1760 (function-name (intern (concat "python-skeleton-" name))))
1762 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
1763 (setq python-skeleton-available
1764 (cons ',function-name python-skeleton-available))
1765 (define-skeleton ,function-name
1767 (format "Insert %s statement." name))
1769 (put 'python-skeleton-define 'lisp-indent-function 2)
1771 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
1772 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
1773 The skeleton will be bound to python-skeleton-NAME."
1774 (let* ((name (symbol-name name))
1775 (function-name (intern (concat "python-skeleton--" name)))
1777 "Add '%s' clause? " name)))
1780 `(< ,(format "%s:" name) \n \n
1782 `(define-skeleton ,function-name
1784 (format "Auxiliary skeleton for %s statement." name))
1786 (unless (y-or-n-p ,msg)
1789 (put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
1791 (python-define-auxiliary-skeleton else nil)
1793 (python-define-auxiliary-skeleton except nil)
1795 (python-define-auxiliary-skeleton finally nil)
1797 (python-skeleton-define if nil
1801 ("other condition, %s: "
1805 '(python-skeleton--else) | ^)
1807 (python-skeleton-define while nil
1811 '(python-skeleton--else) | ^)
1813 (python-skeleton-define for nil
1817 '(python-skeleton--else) | ^)
1819 (python-skeleton-define try nil
1825 "except " str ":" \n
1828 '(python-skeleton--except)
1829 '(python-skeleton--else)
1830 '(python-skeleton--finally) | ^)
1832 (python-skeleton-define def nil
1834 "def " str " (" ("Parameter, %s: "
1835 (unless (equal ?\( (char-before)) ", ")
1837 "\"\"\"" - "\"\"\"" \n
1840 (python-skeleton-define class nil
1842 "class " str " (" ("Inheritance, %s: "
1843 (unless (equal ?\( (char-before)) ", ")
1847 "\"\"\"" - "\"\"\"" \n
1850 (defun python-skeleton-add-menu-items ()
1851 "Add menu items to Python->Skeletons menu."
1852 (let ((skeletons (sort python-skeleton-available 'string<))
1854 (dolist (skeleton skeletons)
1856 nil '("Python" "Skeletons")
1858 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
1863 (defvar python-ffap-setup-code
1864 "def __FFAP_get_module_path(module):
1867 path = __import__(module).__file__
1868 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
1873 "Python code to get a module path.")
1875 (defvar python-ffap-string-code
1876 "__FFAP_get_module_path('''%s''')\n"
1877 "Python code used to get a string with the path of a module.")
1879 (defun python-ffap-module-path (module)
1880 "Function for `ffap-alist' to return path for MODULE."
1882 (and (eq major-mode 'inferior-python-mode)
1883 (get-buffer-process (current-buffer)))
1884 (python-shell-get-process))))
1888 (python-shell-send-string-no-output
1889 (format python-ffap-string-code module) process)))
1891 (substring-no-properties module-file 1 -1))))))
1893 (eval-after-load "ffap"
1895 (push '(python-mode . python-ffap-module-path) ffap-alist)
1896 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
1901 (defvar python-check-command
1902 "pychecker --stdlib"
1903 "Command used to check a Python file.")
1905 (defvar python-check-custom-command nil
1908 (defun python-check (command)
1909 "Check a Python file (default current buffer's file).
1910 Runs COMMAND, a shell command, as if by `compile'. See
1911 `python-check-command' for the default."
1913 (list (read-string "Check command: "
1914 (or python-check-custom-command
1915 (concat python-check-command " "
1916 (shell-quote-argument
1918 (let ((name (buffer-file-name)))
1920 (file-name-nondirectory name)))
1922 (setq python-check-custom-command command)
1923 (save-some-buffers (not compilation-ask-about-save) nil)
1924 (compilation-start command))
1929 (defvar python-eldoc-setup-code
1930 "def __PYDOC_get_help(obj):
1933 if hasattr(obj, 'startswith'):
1934 obj = eval(obj, globals())
1935 doc = inspect.getdoc(obj)
1936 if not doc and callable(obj):
1938 if inspect.isclass(obj) and hasattr(obj, '__init__'):
1939 target = obj.__init__
1945 args = inspect.formatargspec(
1946 *inspect.getargspec(target)
1949 doc = '{objtype} {name}{args}'.format(
1950 objtype=objtype, name=name, args=args
1953 doc = doc.splitlines()[0]
1960 "Python code to setup documentation retrieval.")
1962 (defvar python-eldoc-string-code
1963 "__PYDOC_get_help('''%s''')\n"
1964 "Python code used to get a string with the documentation of an object.")
1966 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
1967 "Internal implementation to get documentation at point.
1968 If not FORCE-INPUT is passed then what `current-word' returns
1969 will be used. If not FORCE-PROCESS is passed what
1970 `python-shell-get-process' returns is used."
1971 (let ((process (or force-process (python-shell-get-process))))
1973 "Eldoc needs an inferior Python process running."
1974 (let* ((current-defun (python-info-current-defun))
1975 (input (or force-input
1976 (with-syntax-table python-dotty-syntax-table
1977 (if (not current-defun)
1979 (concat current-defun "." (current-word))))))
1980 (ppss (syntax-ppss))
1981 (help (when (and input
1982 (not (string= input (concat current-defun ".")))
1983 (not (or (python-info-ppss-context 'string ppss)
1984 (python-info-ppss-context 'comment ppss))))
1985 (when (string-match (concat
1986 (regexp-quote (concat current-defun "."))
1990 (goto-char (point-min))
1993 (delete-region (point-marker) (search-forward "self."))
1994 (setq input (buffer-substring (point-min) (point-max)))))
1995 (python-shell-send-string-no-output
1996 (format python-eldoc-string-code input) process))))
1997 (with-current-buffer (process-buffer process)
1998 (when comint-last-prompt-overlay
1999 (delete-region comint-last-input-end
2000 (overlay-start comint-last-prompt-overlay))))
2002 (not (string= help "\n")))
2005 (defun python-eldoc-function ()
2006 "`eldoc-documentation-function' for Python.
2007 For this to work the best as possible you should call
2008 `python-shell-send-buffer' from time to time so context in
2009 inferior python process is updated properly."
2010 (python-eldoc--get-doc-at-point))
2012 (defun python-eldoc-at-point (symbol)
2013 "Get help on SYMBOL using `help'.
2014 Interactively, prompt for symbol."
2016 (let ((symbol (with-syntax-table python-dotty-syntax-table
2018 (enable-recursive-minibuffers t))
2019 (list (read-string (if symbol
2020 (format "Describe symbol (default %s): " symbol)
2021 "Describe symbol: ")
2023 (let ((process (python-shell-get-process)))
2025 (message "Eldoc needs an inferior Python process running.")
2026 (message (python-eldoc--get-doc-at-point symbol process)))))
2031 (defcustom python-imenu-include-defun-type t
2032 "Non-nil make imenu items to include its type."
2037 (defcustom python-imenu-make-tree t
2038 "Non-nil make imenu to build a tree menu.
2039 Set to nil for speed."
2044 (defcustom python-imenu-subtree-root-label "<Jump to %s>"
2045 "Label displayed to navigate to root from a subtree.
2046 It can contain a \"%s\" which will be replaced with the root name."
2051 (defvar python-imenu-index-alist nil
2052 "Calculated index tree for imenu.")
2054 (defun python-imenu-tree-assoc (keylist tree)
2055 "Using KEYLIST traverse TREE."
2057 (python-imenu-tree-assoc (cdr keylist)
2058 (ignore-errors (assoc (car keylist) tree)))
2061 (defun python-imenu-make-element-tree (element-list full-element plain-index)
2062 "Make a tree from plain alist of module names.
2063 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2064 is the same thing, the difference is that FULL-ELEMENT remains
2065 untouched in all recursive calls.
2066 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2067 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2069 (let* ((subelement-point (cdr (assoc
2070 (mapconcat #'identity full-element ".")
2072 (subelement-name (car element-list))
2073 (subelement-position (python-util-position
2074 subelement-name full-element))
2075 (subelement-path (when subelement-position
2078 (- (length full-element)
2079 subelement-position)))))
2080 (let ((path-ref (python-imenu-tree-assoc subelement-path
2081 python-imenu-index-alist)))
2083 (push (cons subelement-name subelement-point)
2084 python-imenu-index-alist)
2085 (when (not (listp (cdr path-ref)))
2086 ;; Modifiy root cdr to be a list
2088 (list (cons (format python-imenu-subtree-root-label
2091 (mapconcat #'identity
2092 subelement-path ".")
2094 (when (not (assoc subelement-name path-ref))
2095 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2096 (python-imenu-make-element-tree (cdr element-list)
2097 full-element plain-index))))
2099 (defun python-imenu-make-tree (index)
2100 "Build the imenu alist tree from plain INDEX.
2102 The idea of this function is that given the alist:
2105 (\"Test.__init__\" . 200)
2106 (\"Test.some_method\" . 300)
2107 (\"Test.some_method.another\" . 400)
2108 (\"Test.something_else\" . 500)
2110 (\"test.reprint\" . 700)
2111 (\"test.reprint\" . 800))
2113 This tree gets built:
2115 '((\"Test\" . ((\"jump to...\" . 100)
2116 (\"__init__\" . 200)
2117 (\"some_method\" . ((\"jump to...\" . 300)
2118 (\"another\" . 400)))
2119 (\"something_else\" . 500)))
2120 (\"test\" . ((\"jump to...\" . 600)
2122 (\"reprint\" . 800))))
2124 Internally it uses `python-imenu-make-element-tree' to create all
2125 branches for each element."
2126 (setq python-imenu-index-alist nil)
2127 (mapc (lambda (element)
2128 (python-imenu-make-element-tree element element index))
2129 (mapcar (lambda (element)
2130 (split-string (car element) "\\." t)) index))
2131 python-imenu-index-alist)
2133 (defun python-imenu-create-index ()
2134 "`imenu-create-index-function' for Python."
2136 (goto-char (point-max))
2137 (while (python-beginning-of-defun-function 1 t)
2138 (let ((defun-dotted-name
2139 (python-info-current-defun python-imenu-include-defun-type)))
2140 (push (cons defun-dotted-name (point)) index)))
2141 (if python-imenu-make-tree
2142 (python-imenu-make-tree index)
2148 (defun python-info-current-defun (&optional include-type)
2149 "Return name of surrounding function with Python compatible dotty syntax.
2150 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2151 This function is compatible to be used as
2152 `add-log-current-defun-function' since it returns nil if point is
2153 not inside a defun."
2160 (goto-char (line-end-position))
2161 (forward-comment -9999)
2162 (setq min-indent (current-indentation))
2163 (while (python-beginning-of-defun-function 1 t)
2164 (when (or (< (current-indentation) min-indent)
2166 (setq first-run nil)
2167 (setq min-indent (current-indentation))
2168 (looking-at python-nav-beginning-of-defun-regexp)
2170 (if (not include-type)
2171 (match-string-no-properties 1)
2172 (mapconcat 'identity
2174 (match-string-no-properties 0)) " "))
2177 (mapconcat (lambda (string) string) names "."))))
2179 (defun python-info-closing-block ()
2180 "Return the point of the block the current line closes."
2181 (let ((closing-word (save-excursion
2182 (back-to-indentation)
2184 (indentation (current-indentation)))
2185 (when (member closing-word python-indent-dedenters)
2188 (while (and (> (current-indentation) indentation)
2190 (not (back-to-indentation))
2192 (back-to-indentation)
2194 ((not (equal indentation (current-indentation))) nil)
2195 ((string= closing-word "elif")
2196 (when (member (current-word) '("if" "elif"))
2198 ((string= closing-word "else")
2199 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2201 ((string= closing-word "except")
2202 (when (member (current-word) '("try"))
2204 ((string= closing-word "finally")
2205 (when (member (current-word) '("except" "else"))
2206 (point-marker))))))))
2208 (defun python-info-line-ends-backslash-p ()
2209 "Return non-nil if current line ends with backslash."
2210 (string= (or (ignore-errors
2213 (- (line-end-position) 1))) "") "\\"))
2215 (defun python-info-continuation-line-p ()
2216 "Return non-nil if current line is continuation of another."
2217 (or (python-info-line-ends-backslash-p)
2218 (string-match ",[[:space:]]*$" (buffer-substring
2219 (line-beginning-position)
2220 (line-end-position)))
2222 (let ((innermost-paren (progn
2223 (goto-char (line-end-position))
2224 (python-info-ppss-context 'paren))))
2225 (when (and innermost-paren
2226 (and (<= (line-beginning-position) innermost-paren)
2227 (>= (line-end-position) innermost-paren)))
2228 (goto-char innermost-paren)
2229 (looking-at (python-rx open-paren (* space) line-end)))))
2231 (back-to-indentation)
2232 (python-info-ppss-context 'paren))))
2234 (defun python-info-block-continuation-line-p ()
2235 "Return non-nil if current line is a continuation of a block."
2237 (while (and (not (bobp))
2238 (python-info-continuation-line-p))
2241 (back-to-indentation)
2242 (when (looking-at (python-rx block-start))
2245 (defun python-info-assignment-continuation-line-p ()
2246 "Return non-nil if current line is a continuation of an assignment."
2248 (while (and (not (bobp))
2249 (python-info-continuation-line-p))
2252 (back-to-indentation)
2253 (when (and (not (looking-at (python-rx block-start)))
2255 (and (re-search-forward (python-rx not-simple-operator
2257 not-simple-operator)
2258 (line-end-position) t)
2259 (not (or (python-info-ppss-context 'string)
2260 (python-info-ppss-context 'paren)
2261 (python-info-ppss-context 'comment))))))
2264 (defun python-info-ppss-context (type &optional syntax-ppss)
2265 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2266 TYPE can be 'comment, 'string or 'parent. It returns the start
2267 character address of the specified TYPE."
2268 (let ((ppss (or syntax-ppss (syntax-ppss))))
2280 ;;; Utility functions
2283 (defun python-util-merge (type list1 list2 pred)
2284 "Destructively merge lists to produce a new one.
2285 Argument TYPE is for compatibility and ignored. LIST1 and LIST2
2286 are the list to be merged. Ordering of the elements is preserved
2287 according to PRED, a `less-than' predicate on the elements."
2289 (while (and list1 list2)
2290 (if (funcall pred (car list2) (car list1))
2291 (push (pop list2) res)
2292 (push (pop list1) res)))
2293 (nconc (nreverse res) list1 list2)))
2295 (defun python-util-position (item seq)
2296 "Find the first occurrence of ITEM in SEQ.
2297 Return the index of the matching item, or nil if not found."
2298 (let ((member-result (member item seq)))
2300 (- (length seq) (length member-result)))))
2304 (define-derived-mode python-mode fundamental-mode "Python"
2305 "Major mode for editing Python files.
2308 Entry to this mode calls the value of `python-mode-hook'
2309 if that value is non-nil."
2310 (set (make-local-variable 'tab-width) 8)
2311 (set (make-local-variable 'indent-tabs-mode) nil)
2313 (set (make-local-variable 'comment-start) "# ")
2314 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2316 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2317 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2319 (set (make-local-variable 'font-lock-defaults)
2320 '(python-font-lock-keywords
2322 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2324 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2325 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2327 (set (make-local-variable 'paragraph-start) "\\s-*$")
2328 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2330 (set (make-local-variable 'beginning-of-defun-function)
2331 #'python-beginning-of-defun-function)
2332 (set (make-local-variable 'end-of-defun-function)
2333 #'python-end-of-defun-function)
2335 (add-hook 'completion-at-point-functions
2336 'python-completion-complete-at-point nil 'local)
2338 (setq imenu-create-index-function #'python-imenu-create-index)
2340 (set (make-local-variable 'add-log-current-defun-function)
2341 #'python-info-current-defun)
2343 (set (make-local-variable 'skeleton-further-elements)
2345 (< '(backward-delete-char-untabify (min python-indent-offset
2347 (^ '(- (1+ (current-indentation))))))
2349 (set (make-local-variable 'eldoc-documentation-function)
2350 #'python-eldoc-function)
2352 (add-to-list 'hs-special-modes-alist
2353 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2355 (python-end-of-defun-function)) nil))
2357 (set (make-local-variable 'mode-require-final-newline) t)
2359 (set (make-local-variable 'outline-regexp)
2360 (python-rx (* space) block-start))
2361 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2362 (set (make-local-variable 'outline-level)
2364 "`outline-level' function for Python mode."
2365 (1+ (/ (current-indentation) python-indent-offset))))
2367 (python-skeleton-add-menu-items)
2369 (when python-indent-guess-indent-offset
2370 (python-indent-guess-indent-offset)))
2374 ;;; python.el ends here