1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29 ;; Major mode for editing Python files with some fontification and
30 ;; indentation bits extracted from original Dave Love's python.el
31 ;; found in GNU/Emacs.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Pdb
35 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp' allows easy
58 ;; navigation between code blocks.
60 ;; Shell interaction: is provided and allows you to execute easily any
61 ;; block of code of your current buffer in an inferior Python process.
63 ;; Shell completion: hitting tab will try to complete the current
64 ;; word. Shell completion is implemented in a manner that if you
65 ;; change the `python-shell-interpreter' to any other (for example
66 ;; IPython) it should be easy to integrate another way to calculate
67 ;; completions. You just need to specify your custom
68 ;; `python-shell-completion-setup-code' and
69 ;; `python-shell-completion-string-code'.
71 ;; Here is a complete example of the settings you would use for
75 ;; python-shell-interpreter "ipython"
76 ;; python-shell-interpreter-args ""
77 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
78 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
79 ;; python-shell-completion-setup-code
80 ;; "from IPython.core.completerlib import module_completion"
81 ;; python-shell-completion-module-string-code
82 ;; "';'.join(module_completion('''%s'''))\n"
83 ;; python-shell-completion-string-code
84 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
86 ;; For iPython 0.10 everything would be the same except for
87 ;; `python-shell-completion-string-code' and
88 ;; `python-shell-completion-module-string-code':
90 ;; (setq python-shell-completion-string-code
91 ;; "';'.join(__IP.complete('''%s'''))\n"
92 ;; python-shell-completion-module-string-code "")
94 ;; Unfortunately running iPython on Windows needs some more tweaking.
95 ;; The way you must set `python-shell-interpreter' and
96 ;; `python-shell-interpreter-args' is as follows:
99 ;; python-shell-interpreter "C:\\Python27\\python.exe"
100 ;; python-shell-interpreter-args
101 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
103 ;; That will spawn the iPython process correctly (Of course you need
104 ;; to modify the paths according to your system).
106 ;; Please note that the default completion system depends on the
107 ;; readline module, so if you are using some Operating System that
108 ;; bundles Python without it (like Windows) just install the
109 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
110 ;; you should be good to go.
112 ;; Shell virtualenv support: The shell also contains support for
113 ;; virtualenvs and other special environment modifications thanks to
114 ;; `python-shell-process-environment' and `python-shell-exec-path'.
115 ;; These two variables allows you to modify execution paths and
116 ;; environment variables to make easy for you to setup virtualenv rules
117 ;; or behavior modifications when running shells. Here is an example
118 ;; of how to make shell processes to be run using the /path/to/env/
121 ;; (setq python-shell-process-environment
123 ;; (format "PATH=%s" (mapconcat
126 ;; (cons (getenv "PATH")
127 ;; '("/path/to/env/bin/")))
129 ;; "VIRTUAL_ENV=/path/to/env/"))
130 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
132 ;; Since the above is cumbersome and can be programmatically
133 ;; calculated, the variable `python-shell-virtualenv-path' is
134 ;; provided. When this variable is set with the path of the
135 ;; virtualenv to use, `process-environment' and `exec-path' get proper
136 ;; values in order to run shells inside the specified virtualenv. So
137 ;; the following will achieve the same as the previous example:
139 ;; (setq python-shell-virtualenv-path "/path/to/env/")
141 ;; Also the `python-shell-extra-pythonpaths' variable have been
142 ;; introduced as simple way of adding paths to the PYTHONPATH without
143 ;; affecting existing values.
145 ;; Pdb tracking: when you execute a block of code that contains some
146 ;; call to pdb (or ipdb) it will prompt the block of code and will
147 ;; follow the execution of pdb marking the current line with an arrow.
149 ;; Symbol completion: you can complete the symbol at point. It uses
150 ;; the shell completion in background so you should run
151 ;; `python-shell-send-buffer' from time to time to get better results.
153 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
154 ;; def, for, if, try and while. These skeletons are integrated with
155 ;; dabbrev. If you have `dabbrev-mode' activated and
156 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
157 ;; the name of any of those defined and hit SPC, they will be
158 ;; automatically expanded.
160 ;; FFAP: You can find the filename for a given module when using ffap
161 ;; out of the box. This feature needs an inferior python shell
164 ;; Code check: Check the current file for errors with `python-check'
165 ;; using the program defined in `python-check-command'.
167 ;; Eldoc: returns documentation for object at point by using the
168 ;; inferior python subprocess to inspect its documentation. As you
169 ;; might guessed you should run `python-shell-send-buffer' from time
170 ;; to time to get better results too.
172 ;; imenu: This mode supports imenu in its most basic form, letting it
173 ;; build the necessary alist via `imenu-default-create-index-function'
174 ;; by having set `imenu-extract-index-name-function' to
175 ;; `python-info-current-defun'.
177 ;; If you used python-mode.el you probably will miss auto-indentation
178 ;; when inserting newlines. To achieve the same behavior you have
181 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
183 ;; 2) Add the following hook in your .emacs:
185 ;; (add-hook 'python-mode-hook
187 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
189 ;; I'd recommend the first one since you'll get the same behavior for
190 ;; all modes out-of-the-box.
194 ;; Add this to your .emacs:
196 ;; (add-to-list 'load-path "/folder/containing/file")
203 (require 'ansi-color)
208 ;; Avoid compiler warnings
209 (defvar view-return-to-alist)
210 (defvar compilation-error-regexp-alist)
211 (defvar outline-heading-end-regexp))
213 (autoload 'comint-mode "comint")
216 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
218 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
221 "Python Language's flying circus support for Emacs."
224 :link '(emacs-commentary-link "python"))
229 (defvar python-mode-map
230 (let ((map (make-sparse-keymap)))
232 (substitute-key-definition 'backward-sentence
233 'python-nav-backward-block
235 (substitute-key-definition 'forward-sentence
236 'python-nav-forward-block
238 (define-key map "\C-c\C-j" 'imenu)
240 (define-key map "\177" 'python-indent-dedent-line-backspace)
241 (define-key map (kbd "<backtab>") 'python-indent-dedent-line)
242 (define-key map "\C-c<" 'python-indent-shift-left)
243 (define-key map "\C-c>" 'python-indent-shift-right)
244 (define-key map ":" 'python-indent-electric-colon)
246 (define-key map "\C-c\C-tc" 'python-skeleton-class)
247 (define-key map "\C-c\C-td" 'python-skeleton-def)
248 (define-key map "\C-c\C-tf" 'python-skeleton-for)
249 (define-key map "\C-c\C-ti" 'python-skeleton-if)
250 (define-key map "\C-c\C-tt" 'python-skeleton-try)
251 (define-key map "\C-c\C-tw" 'python-skeleton-while)
253 (define-key map "\C-c\C-p" 'run-python)
254 (define-key map "\C-c\C-s" 'python-shell-send-string)
255 (define-key map "\C-c\C-r" 'python-shell-send-region)
256 (define-key map "\C-\M-x" 'python-shell-send-defun)
257 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
258 (define-key map "\C-c\C-l" 'python-shell-send-file)
259 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
260 ;; Some util commands
261 (define-key map "\C-c\C-v" 'python-check)
262 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
264 (substitute-key-definition 'complete-symbol 'completion-at-point
266 (easy-menu-define python-menu map "Python Mode menu"
268 :help "Python-specific Features"
269 ["Shift region left" python-indent-shift-left :active mark-active
270 :help "Shift region left by a single indentation step"]
271 ["Shift region right" python-indent-shift-right :active mark-active
272 :help "Shift region right by a single indentation step"]
274 ["Start of def/class" beginning-of-defun
275 :help "Go to start of outermost definition around point"]
276 ["End of def/class" end-of-defun
277 :help "Go to end of definition around point"]
278 ["Mark def/class" mark-defun
279 :help "Mark outermost definition around point"]
280 ["Jump to def/class" imenu
281 :help "Jump to a class or function definition"]
285 ["Start interpreter" run-python
286 :help "Run inferior Python process in a separate buffer"]
287 ["Switch to shell" python-shell-switch-to-shell
288 :help "Switch to running inferior Python process"]
289 ["Eval string" python-shell-send-string
290 :help "Eval string in inferior Python session"]
291 ["Eval buffer" python-shell-send-buffer
292 :help "Eval buffer in inferior Python session"]
293 ["Eval region" python-shell-send-region
294 :help "Eval region in inferior Python session"]
295 ["Eval defun" python-shell-send-defun
296 :help "Eval defun in inferior Python session"]
297 ["Eval file" python-shell-send-file
298 :help "Eval file in inferior Python session"]
299 ["Debugger" pdb :help "Run pdb under GUD"]
301 ["Check file" python-check
302 :help "Check file for errors"]
303 ["Help on symbol" python-eldoc-at-point
304 :help "Get help on symbol at point"]
305 ["Complete symbol" completion-at-point
306 :help "Complete symbol before point"]))
308 "Keymap for `python-mode'.")
311 ;;; Python specialized rx
314 (defconst python-rx-constituents
315 `((block-start . ,(rx symbol-start
316 (or "def" "class" "if" "elif" "else" "try"
317 "except" "finally" "for" "while" "with")
319 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
321 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
322 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
323 (+ space) "==" (+ space)
324 (any ?' ?\") "__main__" (any ?' ?\")
326 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
327 (open-paren . ,(rx (or "{" "[" "(")))
328 (close-paren . ,(rx (or "}" "]" ")")))
329 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
330 ;; FIXME: rx should support (not simple-operator).
331 (not-simple-operator . ,(rx
333 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
334 ;; FIXME: Use regexp-opt.
335 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
336 "=" "%" "**" "//" "<<" ">>" "<=" "!="
337 "==" ">=" "is" "not")))
338 ;; FIXME: Use regexp-opt.
339 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
340 ">>=" "<<=" "&=" "^=" "|="))))
341 "Additional Python specific sexps for `python-rx'"))
343 (defmacro python-rx (&rest regexps)
344 "Python mode specialized rx macro.
345 This variant of `rx' supports common python named REGEXPS."
346 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
347 (cond ((null regexps)
350 (rx-to-string `(and ,@regexps) t))
352 (rx-to-string (car regexps) t)))))
355 ;;; Font-lock and syntax
357 (defun python-syntax-context (type &optional syntax-ppss)
358 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
359 TYPE can be `comment', `string' or `paren'. It returns the start
360 character address of the specified TYPE."
361 (let ((ppss (or syntax-ppss (syntax-ppss))))
363 (comment (and (nth 4 ppss) (nth 8 ppss)))
364 (string (and (not (nth 4 ppss)) (nth 8 ppss)))
368 (defun python-syntax-context-type (&optional syntax-ppss)
369 "Return the context type using SYNTAX-PPSS.
370 The type returned can be `comment', `string' or `paren'."
371 (let ((ppss (or syntax-ppss (syntax-ppss))))
373 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
374 ((nth 1 ppss) 'paren))))
376 (defsubst python-syntax-comment-or-string-p ()
377 "Return non-nil if point is inside 'comment or 'string."
378 (nth 8 (syntax-ppss)))
380 (define-obsolete-function-alias
381 'python-info-ppss-context #'python-syntax-context "24.3")
383 (define-obsolete-function-alias
384 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
386 (define-obsolete-function-alias
387 'python-info-ppss-comment-or-string-p
388 #'python-syntax-comment-or-string-p "24.3")
390 (defvar python-font-lock-keywords
394 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
395 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
396 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
401 ;; False, None, and True are listed as keywords on the Python 3
402 ;; documentation, but since they also qualify as constants they are
403 ;; fontified like that in order to keep font-lock consistent between
410 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
411 (1 font-lock-function-name-face))
413 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
414 (1 font-lock-type-face))
418 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
419 ;; copyright, license, credits, quit and exit are added by the site
420 ;; module and they are not intended to be used in programs
421 "copyright" "credits" "exit" "license" "quit")
422 symbol-end) . font-lock-constant-face)
424 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
425 (0+ "." (1+ (or word ?_)))))
426 (1 font-lock-type-face))
427 ;; Builtin Exceptions
430 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
431 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
432 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
433 "ImportError" "ImportWarning" "IndexError" "KeyError"
434 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
435 "NotImplementedError" "OSError" "OverflowError"
436 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
437 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
438 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
439 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
440 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
441 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
445 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
447 symbol-end) . font-lock-type-face)
451 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
452 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
453 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
454 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
455 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
456 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
457 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
458 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
461 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
462 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
465 "ascii" "bytearray" "bytes" "exec"
467 "__all__" "__doc__" "__name__" "__package__")
468 symbol-end) . font-lock-builtin-face)
470 ;; support for a = b = c = 5
472 (let ((re (python-rx (group (+ (any word ?. ?_)))
473 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
474 assignment-operator)))
475 (when (re-search-forward re limit t)
476 (while (and (python-syntax-context 'paren)
477 (re-search-forward re limit t)))
478 (if (and (not (python-syntax-context 'paren))
479 (not (equal (char-after (point-marker)) ?=)))
481 (set-match-data nil)))))
482 (1 font-lock-variable-name-face nil nil))
483 ;; support for a, b, c = (1, 2, 3)
485 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
486 (* ?, (* space) (+ (any word ?. ?_)) (* space))
487 ?, (* space) (+ (any word ?. ?_)) (* space)
488 assignment-operator)))
489 (when (and (re-search-forward re limit t)
490 (goto-char (nth 3 (match-data))))
491 (while (and (python-syntax-context 'paren)
492 (re-search-forward re limit t))
493 (goto-char (nth 3 (match-data))))
494 (if (not (python-syntax-context 'paren))
496 (set-match-data nil)))))
497 (1 font-lock-variable-name-face nil nil))))
499 (defconst python-syntax-propertize-function
500 (syntax-propertize-rules
503 ;; Match even number of backslashes.
504 (or (not (any ?\\ ?\' ?\")) point
505 ;; Quotes might be preceded by a escaped quote.
506 (and (or (not (any ?\\)) point) ?\\
507 (* ?\\ ?\\) (any ?\' ?\")))
509 ;; Match single or triple quotes of any kind.
510 (group (or "\"" "\"\"\"" "'" "'''"))))
511 (0 (ignore (python-syntax-stringify))))))
513 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
514 "Count number of quotes around point (max is 3).
515 QUOTE-CHAR is the quote char to count. Optional argument POINT is
516 the point where scan starts (defaults to current point) and LIMIT
517 is used to limit the scan."
520 (or (not limit) (< (+ point i) limit))
521 (eq (char-after (+ point i)) quote-char))
525 (defun python-syntax-stringify ()
526 "Put `syntax-table' property correctly on single/triple quotes."
527 (let* ((num-quotes (length (match-string-no-properties 1)))
529 (backward-char num-quotes)
531 (forward-char num-quotes)))
532 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
533 (quote-starting-pos (- (point) num-quotes))
534 (quote-ending-pos (point))
537 (python-syntax-count-quotes
538 (char-before) string-start quote-starting-pos))))
539 (cond ((and string-start (= num-closing-quotes 0))
540 ;; This set of quotes doesn't match the string starting
544 ;; This set of quotes delimit the start of a string.
545 (put-text-property quote-starting-pos (1+ quote-starting-pos)
546 'syntax-table (string-to-syntax "|")))
547 ((= num-quotes num-closing-quotes)
548 ;; This set of quotes delimit the end of a string.
549 (put-text-property (1- quote-ending-pos) quote-ending-pos
550 'syntax-table (string-to-syntax "|")))
551 ((> num-quotes num-closing-quotes)
552 ;; This may only happen whenever a triple quote is closing
553 ;; a single quoted string. Add string delimiter syntax to
555 (put-text-property quote-starting-pos quote-ending-pos
556 'syntax-table (string-to-syntax "|"))))))
558 (defvar python-mode-syntax-table
559 (let ((table (make-syntax-table)))
560 ;; Give punctuation syntax to ASCII that normally has symbol
561 ;; syntax or has word syntax and isn't a letter.
562 (let ((symbol (string-to-syntax "_"))
563 (sst (standard-syntax-table)))
566 (if (equal symbol (aref sst i))
567 (modify-syntax-entry i "." table)))))
568 (modify-syntax-entry ?$ "." table)
569 (modify-syntax-entry ?% "." table)
571 (modify-syntax-entry ?# "<" table)
572 (modify-syntax-entry ?\n ">" table)
573 (modify-syntax-entry ?' "\"" table)
574 (modify-syntax-entry ?` "$" table)
576 "Syntax table for Python files.")
578 (defvar python-dotty-syntax-table
579 (let ((table (make-syntax-table python-mode-syntax-table)))
580 (modify-syntax-entry ?. "w" table)
581 (modify-syntax-entry ?_ "w" table)
583 "Dotty syntax table for Python files.
584 It makes underscores and dots word constituent chars.")
589 (defcustom python-indent-offset 4
590 "Default indentation offset for Python."
595 (defcustom python-indent-guess-indent-offset t
596 "Non-nil tells Python mode to guess `python-indent-offset' value."
601 (define-obsolete-variable-alias
602 'python-indent 'python-indent-offset "24.3")
604 (define-obsolete-variable-alias
605 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
607 (defvar python-indent-current-level 0
608 "Current indentation level `python-indent-line-function' is using.")
610 (defvar python-indent-levels '(0)
611 "Levels of indentation available for `python-indent-line-function'.")
613 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
614 "List of words that should be dedented.
615 These make `python-indent-calculate-indentation' subtract the value of
616 `python-indent-offset'.")
618 (defun python-indent-guess-indent-offset ()
619 "Guess and set `python-indent-offset' for the current buffer."
624 (goto-char (point-min))
626 (while (and (not block-end)
628 (python-rx line-start block-start) nil t))
630 (not (python-syntax-context-type))
632 (goto-char (line-end-position))
633 (python-util-forward-comment -1)
634 (if (equal (char-before) ?:)
637 (when (python-info-block-continuation-line-p)
638 (while (and (python-info-continuation-line-p)
641 (python-util-forward-comment -1)
642 (when (equal (char-before) ?:)
644 (setq block-end (point-marker))))
647 (goto-char block-end)
648 (python-util-forward-comment)
649 (current-indentation))))
651 (setq python-indent-offset indentation)
652 (message "Can't guess python-indent-offset, using defaults: %s"
653 python-indent-offset)))))))
655 (defun python-indent-context ()
656 "Get information on indentation context.
657 Context information is returned with a cons with the form:
660 Where status can be any of the following symbols:
661 * inside-paren: If point in between (), {} or []
662 * inside-string: If point is inside a string
663 * after-backslash: Previous line ends in a backslash
664 * after-beginning-of-block: Point is after beginning of block
665 * after-line: Point is after normal line
666 * no-indent: Point is at beginning of buffer or other special case
667 START is the buffer position where the sexp starts."
670 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
674 ;; Beginning of buffer
676 (goto-char (line-beginning-position))
680 ((setq start (python-syntax-context 'string ppss))
683 ((setq start (python-syntax-context 'paren ppss))
686 ((setq start (when (not (or (python-syntax-context 'string ppss)
687 (python-syntax-context 'comment ppss)))
688 (let ((line-beg-pos (line-beginning-position)))
689 (when (python-info-line-ends-backslash-p
691 (- line-beg-pos 2)))))
693 ;; After beginning of block
694 ((setq start (save-excursion
696 (back-to-indentation)
697 (python-util-forward-comment -1)
698 (equal (char-before) ?:))
699 ;; Move to the first block start that's not in within
700 ;; a string, comment or paren and that's not a
701 ;; continuation line.
702 (while (and (re-search-backward
703 (python-rx block-start) nil t)
705 (python-syntax-context-type)
706 (python-info-continuation-line-p))))
707 (when (looking-at (python-rx block-start))
709 'after-beginning-of-block)
711 ((setq start (save-excursion
712 (back-to-indentation)
713 (skip-chars-backward (rx (or whitespace ?\n)))
714 (python-nav-beginning-of-statement)
721 (defun python-indent-calculate-indentation ()
722 "Calculate correct indentation offset for the current line."
723 (let* ((indentation-context (python-indent-context))
724 (context-status (car indentation-context))
725 (context-start (cdr indentation-context)))
731 ;; When point is after beginning of block just add one level
732 ;; of indentation relative to the context-start
733 ('after-beginning-of-block
734 (goto-char context-start)
735 (+ (current-indentation) python-indent-offset))
736 ;; When after a simple line just use previous line
737 ;; indentation, in the case current line starts with a
738 ;; `python-indent-dedenters' de-indent one level.
742 (goto-char context-start)
743 (current-indentation))
745 (back-to-indentation)
746 (looking-at (regexp-opt python-indent-dedenters)))
749 ;; When inside of a string, do nothing. just use the current
750 ;; indentation. XXX: perhaps it would be a good idea to
751 ;; invoke standard text indentation here
753 (goto-char context-start)
754 (current-indentation))
755 ;; After backslash we have several possibilities.
758 ;; Check if current line is a dot continuation. For this
759 ;; the current line must start with a dot and previous
760 ;; line must contain a dot too.
762 (back-to-indentation)
763 (when (looking-at "\\.")
764 ;; If after moving one line back point is inside a paren it
765 ;; needs to move back until it's not anymore
769 (python-syntax-context 'paren))))
770 (goto-char (line-end-position))
771 (while (and (re-search-backward
772 "\\." (line-beginning-position) t)
773 (python-syntax-context-type)))
774 (if (and (looking-at "\\.")
775 (not (python-syntax-context-type)))
776 ;; The indentation is the same column of the
777 ;; first matching dot that's not inside a
778 ;; comment, a string or a paren
780 ;; No dot found on previous line, just add another
781 ;; indentation level.
782 (+ (current-indentation) python-indent-offset)))))
783 ;; Check if prev line is a block continuation
784 ((let ((block-continuation-start
785 (python-info-block-continuation-line-p)))
786 (when block-continuation-start
787 ;; If block-continuation-start is set jump to that
788 ;; marker and use first column after the block start
789 ;; as indentation value.
790 (goto-char block-continuation-start)
792 (python-rx block-start (* space))
793 (line-end-position) t)
795 ;; Check if current line is an assignment continuation
796 ((let ((assignment-continuation-start
797 (python-info-assignment-continuation-line-p)))
798 (when assignment-continuation-start
799 ;; If assignment-continuation is set jump to that
800 ;; marker and use first column after the assignment
801 ;; operator as indentation value.
802 (goto-char assignment-continuation-start)
806 (goto-char (python-info-beginning-of-backslash))
811 (or (python-info-beginning-of-backslash) (point)))
812 (python-info-line-ends-backslash-p)))
813 ;; The two previous lines ended in a backslash so we must
814 ;; respect previous line indentation.
815 (current-indentation)
816 ;; What happens here is that we are dealing with the second
817 ;; line of a backslash continuation, in that case we just going
818 ;; to add one indentation level.
819 (+ (current-indentation) python-indent-offset)))))
820 ;; When inside a paren there's a need to handle nesting
824 ;; If current line closes the outermost open paren use the
825 ;; current indentation of the context-start line.
827 (skip-syntax-forward "\s" (line-end-position))
828 (when (and (looking-at (regexp-opt '(")" "]" "}")))
831 (not (python-syntax-context 'paren))))
832 (goto-char context-start)
833 (current-indentation))))
834 ;; If open paren is contained on a line by itself add another
835 ;; indentation level, else look for the first word after the
836 ;; opening paren and use it's column position as indentation
838 ((let* ((content-starts-in-newline)
841 (if (setq content-starts-in-newline
843 (goto-char context-start)
847 (line-beginning-position)
849 (python-util-forward-comment))
851 (+ (current-indentation) python-indent-offset)
855 ;; If current line closes a nested open paren de-indent one
858 (back-to-indentation)
859 (looking-at (regexp-opt '(")" "]" "}"))))
860 (- indent python-indent-offset))
861 ;; If the line of the opening paren that wraps the current
862 ;; line starts a block add another level of indentation to
863 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
865 (when (and content-starts-in-newline
867 (goto-char context-start)
868 (back-to-indentation)
869 (looking-at (python-rx block-start))))
870 (+ indent python-indent-offset))))
873 (defun python-indent-calculate-levels ()
874 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
875 (let* ((indentation (python-indent-calculate-indentation))
876 (remainder (% indentation python-indent-offset))
877 (steps (/ (- indentation remainder) python-indent-offset)))
878 (setq python-indent-levels (list 0))
879 (dotimes (step steps)
880 (push (* python-indent-offset (1+ step)) python-indent-levels))
881 (when (not (eq 0 remainder))
882 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
883 (setq python-indent-levels (nreverse python-indent-levels))
884 (setq python-indent-current-level (1- (length python-indent-levels)))))
886 (defun python-indent-toggle-levels ()
887 "Toggle `python-indent-current-level' over `python-indent-levels'."
888 (setq python-indent-current-level (1- python-indent-current-level))
889 (when (< python-indent-current-level 0)
890 (setq python-indent-current-level (1- (length python-indent-levels)))))
892 (defun python-indent-line (&optional force-toggle)
893 "Internal implementation of `python-indent-line-function'.
894 Uses the offset calculated in
895 `python-indent-calculate-indentation' and available levels
896 indicated by the variable `python-indent-levels' to set the
899 When the variable `last-command' is equal to
900 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
901 levels indicated in the variable `python-indent-levels' by
902 setting the current level in the variable
903 `python-indent-current-level'.
905 When the variable `last-command' is not equal to
906 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
907 possible indentation levels and saves it in the variable
908 `python-indent-levels'. Afterwards it sets the variable
909 `python-indent-current-level' correctly so offset is equal
910 to (`nth' `python-indent-current-level' `python-indent-levels')"
912 (and (or (and (eq this-command 'indent-for-tab-command)
913 (eq last-command this-command))
915 (not (equal python-indent-levels '(0)))
916 (or (python-indent-toggle-levels) t))
917 (python-indent-calculate-levels))
918 (let* ((starting-pos (point-marker))
919 (indent-ending-position
920 (+ (line-beginning-position) (current-indentation)))
921 (follow-indentation-p
923 (and (<= (line-beginning-position) starting-pos)
924 (>= indent-ending-position starting-pos))))
925 (next-indent (nth python-indent-current-level python-indent-levels)))
926 (unless (= next-indent (current-indentation))
928 (delete-horizontal-space)
929 (indent-to next-indent)
930 (goto-char starting-pos))
931 (and follow-indentation-p (back-to-indentation)))
932 (python-info-closing-block-message))
934 (defun python-indent-line-function ()
935 "`indent-line-function' for Python mode.
936 See `python-indent-line' for details."
937 (python-indent-line))
939 (defun python-indent-dedent-line ()
940 "De-indent current line."
942 (when (and (not (python-syntax-comment-or-string-p))
943 (<= (point-marker) (save-excursion
944 (back-to-indentation)
946 (> (current-column) 0))
947 (python-indent-line t)
950 (defun python-indent-dedent-line-backspace (arg)
951 "De-indent current line.
952 Argument ARG is passed to `backward-delete-char-untabify' when
953 point is not in between the indentation."
955 (when (not (python-indent-dedent-line))
956 (backward-delete-char-untabify arg)))
957 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
959 (defun python-indent-region (start end)
960 "Indent a python region automagically.
962 Called from a program, START and END specify the region to indent."
963 (let ((deactivate-mark nil))
966 (setq end (point-marker))
968 (or (bolp) (forward-line 1))
969 (while (< (point) end)
970 (or (and (bolp) (eolp))
973 (back-to-indentation)
974 (setq word (current-word))
977 ;; Don't mess with strings, unless it's the
978 ;; enclosing set of quotes.
979 (or (not (python-syntax-context 'string))
983 (current-indentation)
984 (python-syntax-count-quotes (char-after) (point))))
985 (string-to-syntax "|"))))
987 (delete-horizontal-space)
988 (indent-to (python-indent-calculate-indentation)))))
990 (move-marker end nil))))
992 (defun python-indent-shift-left (start end &optional count)
993 "Shift lines contained in region START END by COUNT columns to the left.
994 COUNT defaults to `python-indent-offset'. If region isn't
995 active, the current line is shifted. The shifted region includes
996 the lines in which START and END lie. An error is signaled if
997 any lines in the region are indented less than COUNT columns."
1000 (list (region-beginning) (region-end) current-prefix-arg)
1001 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1003 (setq count (prefix-numeric-value count))
1004 (setq count python-indent-offset))
1006 (let ((deactivate-mark nil))
1009 (while (< (point) end)
1010 (if (and (< (current-indentation) count)
1011 (not (looking-at "[ \t]*$")))
1012 (error "Can't shift all lines enough"))
1014 (indent-rigidly start end (- count))))))
1016 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1018 (defun python-indent-shift-right (start end &optional count)
1019 "Shift lines contained in region START END by COUNT columns to the left.
1020 COUNT defaults to `python-indent-offset'. If region isn't
1021 active, the current line is shifted. The shifted region includes
1022 the lines in which START and END lie."
1025 (list (region-beginning) (region-end) current-prefix-arg)
1026 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1027 (let ((deactivate-mark nil))
1029 (setq count (prefix-numeric-value count))
1030 (setq count python-indent-offset))
1031 (indent-rigidly start end count)))
1033 (defun python-indent-electric-colon (arg)
1034 "Insert a colon and maybe de-indent the current line.
1035 With numeric ARG, just insert that many colons. With
1036 \\[universal-argument], just insert a single colon."
1038 (self-insert-command (if (not (integerp arg)) 1 arg))
1039 (when (and (not arg)
1041 (not (equal ?: (char-after (- (point-marker) 2))))
1042 (not (python-syntax-comment-or-string-p)))
1043 (let ((indentation (current-indentation))
1044 (calculated-indentation (python-indent-calculate-indentation)))
1045 (python-info-closing-block-message)
1046 (when (> indentation calculated-indentation)
1048 (indent-line-to calculated-indentation)
1049 (when (not (python-info-closing-block-message))
1050 (indent-line-to indentation)))))))
1051 (put 'python-indent-electric-colon 'delete-selection t)
1053 (defun python-indent-post-self-insert-function ()
1054 "Adjust closing paren line indentation after a char is added.
1055 This function is intended to be added to the
1056 `post-self-insert-hook.' If a line renders a paren alone, after
1057 adding a char before it, the line will be re-indented
1058 automatically if needed."
1059 (when (and (eq (char-before) last-command-event)
1061 (memq (char-after) '(?\) ?\] ?\})))
1063 (goto-char (line-beginning-position))
1064 ;; If after going to the beginning of line the point
1065 ;; is still inside a paren it's ok to do the trick
1066 (when (python-syntax-context 'paren)
1067 (let ((indentation (python-indent-calculate-indentation)))
1068 (when (< (current-indentation) indentation)
1069 (indent-line-to indentation)))))))
1074 (defvar python-nav-beginning-of-defun-regexp
1075 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1076 "Regexp matching class or function definition.
1077 The name of the defun should be grouped so it can be retrieved
1078 via `match-string'.")
1080 (defun python-nav-beginning-of-defun (&optional arg)
1081 "Move point to `beginning-of-defun'.
1082 With positive ARG move search backwards. With negative do the
1083 same but forward. When ARG is nil or 0 defaults to 1. This is
1084 the main part of `python-beginning-of-defun-function'. Return
1085 non-nil if point is moved to `beginning-of-defun'."
1086 (when (or (null arg) (= arg 0)) (setq arg 1))
1087 (let* ((re-search-fn (if (> arg 0)
1088 #'re-search-backward
1089 #'re-search-forward))
1090 (line-beg-pos (line-beginning-position))
1091 (line-content-start (+ line-beg-pos (current-indentation)))
1092 (pos (point-marker))
1095 (when (and (< arg 0)
1096 (python-info-looking-at-beginning-of-defun))
1098 (while (and (funcall re-search-fn
1099 python-nav-beginning-of-defun-regexp nil t)
1100 (python-syntax-context-type)))
1101 (and (python-info-looking-at-beginning-of-defun)
1102 (or (not (= (line-number-at-pos pos)
1103 (line-number-at-pos)))
1104 (and (>= (point) line-beg-pos)
1105 (<= (point) line-content-start)
1106 (> pos line-content-start)))))))
1108 (or (beginning-of-line 1) t)
1109 (and (goto-char pos) nil))))
1111 (defun python-beginning-of-defun-function (&optional arg)
1112 "Move point to the beginning of def or class.
1113 With positive ARG move that number of functions backwards. With
1114 negative do the same but forward. When ARG is nil or 0 defaults
1115 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1116 (when (or (null arg) (= arg 0)) (setq arg 1))
1118 (cond ((and (eq this-command 'mark-defun)
1119 (python-info-looking-at-beginning-of-defun)))
1121 (dotimes (i (if (> arg 0) arg (- arg)))
1122 (when (and (python-nav-beginning-of-defun arg)
1127 (defun python-end-of-defun-function ()
1128 "Move point to the end of def or class.
1129 Returns nil if point is not in a def or class."
1131 (let ((beg-defun-indent))
1132 (when (or (python-info-looking-at-beginning-of-defun)
1133 (python-beginning-of-defun-function 1)
1134 (python-beginning-of-defun-function -1))
1135 (setq beg-defun-indent (current-indentation))
1137 ;; Go as forward as possible
1139 (python-nav-beginning-of-defun -1)
1140 (and (goto-char (point-max)) nil))
1141 (> (current-indentation) beg-defun-indent)))
1142 (beginning-of-line 1)
1143 ;; Go as backwards as possible
1144 (while (and (forward-line -1)
1146 (or (not (current-word))
1147 (equal (char-after (+ (point) (current-indentation))) ?#)
1148 (<= (current-indentation) beg-defun-indent)
1149 (looking-at (python-rx decorator))
1150 (python-syntax-context-type))))
1152 ;; If point falls inside a paren or string context the point is
1153 ;; forwarded at the end of it (or end of buffer if its not closed)
1154 (let ((context-type (python-syntax-context-type)))
1155 (when (memq context-type '(paren string))
1157 (while (and (not (eobp))
1158 (python-syntax-context-type))
1159 (forward-line 1)))))))
1161 (defun python-nav-beginning-of-statement ()
1162 "Move to start of current statement."
1164 (while (and (or (back-to-indentation) t)
1169 (python-info-line-ends-backslash-p))
1170 (python-syntax-context 'string)
1171 (python-syntax-context 'paren))
1172 (forward-line -1))))
1175 (defun python-nav-end-of-statement ()
1176 "Move to end of current statement."
1178 (while (and (goto-char (line-end-position))
1181 (python-info-line-ends-backslash-p)
1182 (python-syntax-context 'string)
1183 (python-syntax-context 'paren))
1187 (defun python-nav-backward-statement (&optional arg)
1188 "Move backward to previous statement.
1189 With ARG, repeat. See `python-nav-forward-statement'."
1191 (or arg (setq arg 1))
1192 (python-nav-forward-statement (- arg)))
1194 (defun python-nav-forward-statement (&optional arg)
1195 "Move forward to next statement.
1196 With ARG, repeat. With negative argument, move ARG times
1197 backward to previous statement."
1199 (or arg (setq arg 1))
1201 (python-nav-end-of-statement)
1202 (python-util-forward-comment)
1203 (python-nav-beginning-of-statement)
1204 (setq arg (1- arg)))
1206 (python-nav-beginning-of-statement)
1207 (python-util-forward-comment -1)
1208 (python-nav-beginning-of-statement)
1209 (setq arg (1+ arg))))
1211 (defun python-nav-beginning-of-block ()
1212 "Move to start of current block."
1214 (let ((starting-pos (point))
1215 (block-regexp (python-rx
1216 line-start (* whitespace) block-start)))
1218 (python-nav-beginning-of-statement)
1219 (looking-at (python-rx block-start)))
1221 ;; Go to first line beginning a statement
1222 (while (and (not (bobp))
1223 (or (and (python-nav-beginning-of-statement) nil)
1224 (python-info-current-line-comment-p)
1225 (python-info-current-line-empty-p)))
1227 (let ((block-matching-indent
1228 (- (current-indentation) python-indent-offset)))
1230 (and (python-nav-backward-block)
1231 (> (current-indentation) block-matching-indent)))
1232 (if (and (looking-at (python-rx block-start))
1233 (= (current-indentation) block-matching-indent))
1235 (and (goto-char starting-pos) nil))))))
1237 (defun python-nav-end-of-block ()
1238 "Move to end of current block."
1240 (when (python-nav-beginning-of-block)
1241 (let ((block-indentation (current-indentation)))
1242 (python-nav-end-of-statement)
1243 (while (and (forward-line 1)
1245 (or (and (> (current-indentation) block-indentation)
1246 (or (python-nav-end-of-statement) t))
1247 (python-info-current-line-comment-p)
1248 (python-info-current-line-empty-p))))
1249 (python-util-forward-comment -1)
1252 (defun python-nav-backward-block (&optional arg)
1253 "Move backward to previous block of code.
1254 With ARG, repeat. See `python-nav-forward-block'."
1256 (or arg (setq arg 1))
1257 (python-nav-forward-block (- arg)))
1259 (defun python-nav-forward-block (&optional arg)
1260 "Move forward to next block of code.
1261 With ARG, repeat. With negative argument, move ARG times
1262 backward to previous block."
1264 (or arg (setq arg 1))
1265 (let ((block-start-regexp
1266 (python-rx line-start (* whitespace) block-start))
1267 (starting-pos (point)))
1269 (python-nav-end-of-statement)
1271 (re-search-forward block-start-regexp nil t)
1272 (python-syntax-context-type)))
1273 (setq arg (1- arg)))
1275 (python-nav-beginning-of-statement)
1277 (re-search-backward block-start-regexp nil t)
1278 (python-syntax-context-type)))
1279 (setq arg (1+ arg)))
1280 (python-nav-beginning-of-statement)
1281 (if (not (looking-at (python-rx block-start)))
1282 (and (goto-char starting-pos) nil)
1283 (and (not (= (point) starting-pos)) (point-marker)))))
1285 (defun python-nav-lisp-forward-sexp-safe (&optional arg)
1286 "Safe version of standard `forward-sexp'.
1287 When ARG > 0 move forward, else if ARG is < 0."
1288 (or arg (setq arg 1))
1289 (let ((forward-sexp-function nil)
1291 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1293 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1297 (while (and (funcall search-fn paren-regexp nil t)
1298 (python-syntax-context 'paren)))))))
1300 (defun python-nav--forward-sexp (&optional dir)
1301 "Move to forward sexp.
1302 With positive Optional argument DIR direction move forward, else
1304 (setq dir (or dir 1))
1306 (let* ((forward-p (if (> dir 0)
1307 (and (setq dir 1) t)
1308 (and (setq dir -1) nil)))
1309 (re-search-fn (if forward-p
1311 're-search-backward))
1312 (context-type (python-syntax-context-type)))
1314 ((eq context-type 'string)
1315 ;; Inside of a string, get out of it.
1316 (while (and (funcall re-search-fn "[\"']" nil t)
1317 (python-syntax-context 'string))))
1318 ((eq context-type 'comment)
1319 ;; Inside of a comment, just move forward.
1320 (python-util-forward-comment dir))
1321 ((or (eq context-type 'paren)
1322 (and forward-p (looking-at (python-rx open-paren)))
1323 (and (not forward-p)
1324 (eq (syntax-class (syntax-after (1- (point))))
1325 (car (string-to-syntax ")")))))
1326 ;; Inside a paren or looking at it, lisp knows what to do.
1327 (python-nav-lisp-forward-sexp-safe dir))
1329 ;; This part handles the lispy feel of
1330 ;; `python-nav-forward-sexp'. Knowing everything about the
1331 ;; current context and the context of the next sexp tries to
1332 ;; follow the lisp sexp motion commands in a symmetric manner.
1335 ((python-info-beginning-of-block-p) 'block-start)
1336 ((python-info-end-of-block-p) 'block-end)
1337 ((python-info-beginning-of-statement-p) 'statement-start)
1338 ((python-info-end-of-statement-p) 'statement-end)))
1341 (python-nav-lisp-forward-sexp-safe dir)
1345 (goto-char next-sexp-pos)
1347 ((python-info-beginning-of-block-p) 'block-start)
1348 ((python-info-end-of-block-p) 'block-end)
1349 ((python-info-beginning-of-statement-p) 'statement-start)
1350 ((python-info-end-of-statement-p) 'statement-end)
1351 ((python-info-statement-starts-block-p) 'starts-block)
1352 ((python-info-statement-ends-block-p) 'ends-block)))))
1354 (cond ((and (not (eobp))
1355 (python-info-current-line-empty-p))
1356 (python-util-forward-comment dir)
1357 (python-nav--forward-sexp dir))
1358 ((eq context 'block-start)
1359 (python-nav-end-of-block))
1360 ((eq context 'statement-start)
1361 (python-nav-end-of-statement))
1362 ((and (memq context '(statement-end block-end))
1363 (eq next-sexp-context 'ends-block))
1364 (goto-char next-sexp-pos)
1365 (python-nav-end-of-block))
1366 ((and (memq context '(statement-end block-end))
1367 (eq next-sexp-context 'starts-block))
1368 (goto-char next-sexp-pos)
1369 (python-nav-end-of-block))
1370 ((memq context '(statement-end block-end))
1371 (goto-char next-sexp-pos)
1372 (python-nav-end-of-statement))
1373 (t (goto-char next-sexp-pos)))
1374 (cond ((and (not (bobp))
1375 (python-info-current-line-empty-p))
1376 (python-util-forward-comment dir)
1377 (python-nav--forward-sexp dir))
1378 ((eq context 'block-end)
1379 (python-nav-beginning-of-block))
1380 ((eq context 'statement-end)
1381 (python-nav-beginning-of-statement))
1382 ((and (memq context '(statement-start block-start))
1383 (eq next-sexp-context 'starts-block))
1384 (goto-char next-sexp-pos)
1385 (python-nav-beginning-of-block))
1386 ((and (memq context '(statement-start block-start))
1387 (eq next-sexp-context 'ends-block))
1388 (goto-char next-sexp-pos)
1389 (python-nav-beginning-of-block))
1390 ((memq context '(statement-start block-start))
1391 (goto-char next-sexp-pos)
1392 (python-nav-beginning-of-statement))
1393 (t (goto-char next-sexp-pos))))))))))
1395 (defun python-nav--backward-sexp ()
1396 "Move to backward sexp."
1397 (python-nav--forward-sexp -1))
1399 (defun python-nav-forward-sexp (&optional arg)
1400 "Move forward across one block of code.
1401 With ARG, do it that many times. Negative arg -N means
1402 move backward N times."
1404 (or arg (setq arg 1))
1406 (python-nav--forward-sexp)
1407 (setq arg (1- arg)))
1409 (python-nav--backward-sexp)
1410 (setq arg (1+ arg))))
1413 ;;; Shell integration
1415 (defcustom python-shell-buffer-name "Python"
1416 "Default buffer name for Python interpreter."
1421 (defcustom python-shell-interpreter "python"
1422 "Default Python interpreter for shell."
1426 (defcustom python-shell-internal-buffer-name "Python Internal"
1427 "Default buffer name for the Internal Python interpreter."
1432 (defcustom python-shell-interpreter-args "-i"
1433 "Default arguments for the Python interpreter."
1437 (defcustom python-shell-prompt-regexp ">>> "
1438 "Regular Expression matching top\-level input prompt of python shell.
1439 It should not contain a caret (^) at the beginning."
1444 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1445 "Regular Expression matching block input prompt of python shell.
1446 It should not contain a caret (^) at the beginning."
1451 (defcustom python-shell-prompt-output-regexp ""
1452 "Regular Expression matching output prompt of python shell.
1453 It should not contain a caret (^) at the beginning."
1458 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1459 "Regular Expression matching pdb input prompt of python shell.
1460 It should not contain a caret (^) at the beginning."
1465 (defcustom python-shell-enable-font-lock t
1466 "Should syntax highlighting be enabled in the python shell buffer?
1467 Restart the python shell after changing this variable for it to take effect."
1472 (defcustom python-shell-process-environment nil
1473 "List of environment variables for Python shell.
1474 This variable follows the same rules as `process-environment'
1475 since it merges with it before the process creation routines are
1476 called. When this variable is nil, the Python shell is run with
1477 the default `process-environment'."
1478 :type '(repeat string)
1482 (defcustom python-shell-extra-pythonpaths nil
1483 "List of extra pythonpaths for Python shell.
1484 The values of this variable are added to the existing value of
1485 PYTHONPATH in the `process-environment' variable."
1486 :type '(repeat string)
1490 (defcustom python-shell-exec-path nil
1491 "List of path to search for binaries.
1492 This variable follows the same rules as `exec-path' since it
1493 merges with it before the process creation routines are called.
1494 When this variable is nil, the Python shell is run with the
1495 default `exec-path'."
1496 :type '(repeat string)
1500 (defcustom python-shell-virtualenv-path nil
1501 "Path to virtualenv root.
1502 This variable, when set to a string, makes the values stored in
1503 `python-shell-process-environment' and `python-shell-exec-path'
1504 to be modified properly so shells are started with the specified
1510 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1511 python-ffap-setup-code
1512 python-eldoc-setup-code)
1513 "List of code run by `python-shell-send-setup-codes'."
1514 :type '(repeat symbol)
1518 (defcustom python-shell-compilation-regexp-alist
1519 `((,(rx line-start (1+ (any " \t")) "File \""
1520 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1521 "\", line " (group (1+ digit)))
1523 (,(rx " in file " (group (1+ not-newline)) " on line "
1526 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1527 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1529 "`compilation-error-regexp-alist' for inferior Python."
1530 :type '(alist string)
1533 (defun python-shell-get-process-name (dedicated)
1534 "Calculate the appropriate process name for inferior Python process.
1535 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1536 returns a string with the form
1537 `python-shell-buffer-name'[variable `buffer-file-name'] else
1538 returns the value of `python-shell-buffer-name'."
1542 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1543 (format "%s" python-shell-buffer-name))))
1546 (defun python-shell-internal-get-process-name ()
1547 "Calculate the appropriate process name for Internal Python process.
1548 The name is calculated from `python-shell-global-buffer-name' and
1549 a hash of all relevant global shell settings in order to ensure
1550 uniqueness for different types of configurations."
1552 python-shell-internal-buffer-name
1555 (python-shell-parse-command)
1556 python-shell-prompt-regexp
1557 python-shell-prompt-block-regexp
1558 python-shell-prompt-output-regexp
1559 (mapconcat #'symbol-value python-shell-setup-codes "")
1560 (mapconcat #'identity python-shell-process-environment "")
1561 (mapconcat #'identity python-shell-extra-pythonpaths "")
1562 (mapconcat #'identity python-shell-exec-path "")
1563 (or python-shell-virtualenv-path "")
1564 (mapconcat #'identity python-shell-exec-path "")))))
1566 (defun python-shell-parse-command ()
1567 "Calculate the string used to execute the inferior Python process."
1568 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1570 (defun python-shell-calculate-process-environment ()
1571 "Calculate process environment given `python-shell-virtualenv-path'."
1572 (let ((process-environment (append
1573 python-shell-process-environment
1574 process-environment nil))
1575 (virtualenv (if python-shell-virtualenv-path
1576 (directory-file-name python-shell-virtualenv-path)
1578 (when python-shell-extra-pythonpaths
1579 (setenv "PYTHONPATH"
1581 (mapconcat 'identity
1582 python-shell-extra-pythonpaths
1585 (or (getenv "PYTHONPATH") ""))))
1586 (if (not virtualenv)
1588 (setenv "PYTHONHOME" nil)
1589 (setenv "PATH" (format "%s/bin%s%s"
1590 virtualenv path-separator
1591 (or (getenv "PATH") "")))
1592 (setenv "VIRTUAL_ENV" virtualenv))
1593 process-environment))
1595 (defun python-shell-calculate-exec-path ()
1596 "Calculate exec path given `python-shell-virtualenv-path'."
1597 (let ((path (append python-shell-exec-path
1599 (if (not python-shell-virtualenv-path)
1601 (cons (format "%s/bin"
1602 (directory-file-name python-shell-virtualenv-path))
1605 (defun python-comint-output-filter-function (output)
1606 "Hook run after content is put into comint buffer.
1607 OUTPUT is a string with the contents of the buffer."
1608 (ansi-color-filter-apply output))
1610 (defvar python-shell--parent-buffer nil)
1612 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1613 "Major mode for Python inferior process.
1614 Runs a Python interpreter as a subprocess of Emacs, with Python
1615 I/O through an Emacs buffer. Variables
1616 `python-shell-interpreter' and `python-shell-interpreter-args'
1617 controls which Python interpreter is run. Variables
1618 `python-shell-prompt-regexp',
1619 `python-shell-prompt-output-regexp',
1620 `python-shell-prompt-block-regexp',
1621 `python-shell-enable-font-lock',
1622 `python-shell-completion-setup-code',
1623 `python-shell-completion-string-code',
1624 `python-shell-completion-module-string-code',
1625 `python-eldoc-setup-code', `python-eldoc-string-code',
1626 `python-ffap-setup-code' and `python-ffap-string-code' can
1627 customize this mode for different Python interpreters.
1629 You can also add additional setup code to be run at
1630 initialization of the interpreter via `python-shell-setup-codes'
1633 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1634 (and python-shell--parent-buffer
1635 (python-util-clone-local-variables python-shell--parent-buffer))
1636 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1637 python-shell-prompt-regexp
1638 python-shell-prompt-block-regexp
1639 python-shell-prompt-pdb-regexp))
1640 (set-syntax-table python-mode-syntax-table)
1641 (setq mode-line-process '(":%s"))
1642 (make-local-variable 'comint-output-filter-functions)
1643 (add-hook 'comint-output-filter-functions
1644 'python-comint-output-filter-function)
1645 (add-hook 'comint-output-filter-functions
1646 'python-pdbtrack-comint-output-filter-function)
1647 (set (make-local-variable 'compilation-error-regexp-alist)
1648 python-shell-compilation-regexp-alist)
1649 (define-key inferior-python-mode-map [remap complete-symbol]
1650 'completion-at-point)
1651 (add-hook 'completion-at-point-functions
1652 'python-shell-completion-complete-at-point nil 'local)
1653 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1654 'python-shell-completion-complete-at-point)
1655 (define-key inferior-python-mode-map "\t"
1656 'python-shell-completion-complete-or-indent)
1657 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1658 (make-local-variable 'python-pdbtrack-tracked-buffer)
1659 (make-local-variable 'python-shell-internal-last-output)
1660 (when python-shell-enable-font-lock
1661 (set (make-local-variable 'font-lock-defaults)
1662 '(python-font-lock-keywords nil nil nil nil))
1663 (set (make-local-variable 'syntax-propertize-function)
1664 python-syntax-propertize-function))
1665 (compilation-shell-minor-mode 1))
1667 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
1668 "Create a python shell comint buffer.
1669 CMD is the python command to be executed and PROC-NAME is the
1670 process name the comint buffer will get. After the comint buffer
1671 is created the `inferior-python-mode' is activated. When
1672 optional argument POP is non-nil the buffer is shown. When
1673 optional argument INTERNAL is non-nil this process is run on a
1674 buffer with a name that starts with a space, following the Emacs
1675 convention for temporary/internal buffers, and also makes sure
1676 the user is not queried for confirmation when the process is
1679 (let* ((proc-buffer-name
1680 (format (if (not internal) "*%s*" " *%s*") proc-name))
1681 (process-environment (python-shell-calculate-process-environment))
1682 (exec-path (python-shell-calculate-exec-path)))
1683 (when (not (comint-check-proc proc-buffer-name))
1684 (let* ((cmdlist (split-string-and-unquote cmd))
1685 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1686 (car cmdlist) nil (cdr cmdlist)))
1687 (python-shell--parent-buffer (current-buffer))
1688 (process (get-buffer-process buffer)))
1689 (with-current-buffer buffer
1690 (inferior-python-mode))
1691 (accept-process-output process)
1692 (and pop (pop-to-buffer buffer t))
1693 (and internal (set-process-query-on-exit-flag process nil))))
1697 (defun run-python (cmd &optional dedicated show)
1698 "Run an inferior Python process.
1699 Input and output via buffer named after
1700 `python-shell-buffer-name'. If there is a process already
1701 running in that buffer, just switch to it.
1703 With argument, allows you to define CMD so you can edit the
1704 command used to call the interpreter and define DEDICATED, so a
1705 dedicated process for the current buffer is open. When numeric
1706 prefix arg is other than 0 or 4 do not SHOW.
1708 Runs the hook `inferior-python-mode-hook' (after the
1709 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1710 process buffer for a list of commands.)"
1712 (if current-prefix-arg
1714 (read-string "Run Python: " (python-shell-parse-command))
1715 (y-or-n-p "Make dedicated process? ")
1716 (= (prefix-numeric-value current-prefix-arg) 4))
1717 (list (python-shell-parse-command) nil t)))
1718 (python-shell-make-comint
1719 cmd (python-shell-get-process-name dedicated) show)
1722 (defun run-python-internal ()
1723 "Run an inferior Internal Python process.
1724 Input and output via buffer named after
1725 `python-shell-internal-buffer-name' and what
1726 `python-shell-internal-get-process-name' returns.
1728 This new kind of shell is intended to be used for generic
1729 communication related to defined configurations, the main
1730 difference with global or dedicated shells is that these ones are
1731 attached to a configuration, not a buffer. This means that can
1732 be used for example to retrieve the sys.path and other stuff,
1733 without messing with user shells. Note that
1734 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1735 are set to nil for these shells, so setup codes are not sent at
1737 (let ((python-shell-enable-font-lock nil)
1738 (inferior-python-mode-hook nil))
1740 (python-shell-make-comint
1741 (python-shell-parse-command)
1742 (python-shell-internal-get-process-name) nil t))))
1744 (defun python-shell-get-process ()
1745 "Get inferior Python process for current buffer and return it."
1746 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1747 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1748 (global-proc-name (python-shell-get-process-name nil))
1749 (global-proc-buffer-name (format "*%s*" global-proc-name))
1750 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1751 (global-running (comint-check-proc global-proc-buffer-name)))
1752 ;; Always prefer dedicated
1753 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1754 (and global-running global-proc-buffer-name)))))
1756 (defun python-shell-get-or-create-process ()
1757 "Get or create an inferior Python process for current buffer and return it."
1758 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1759 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1760 (global-proc-name (python-shell-get-process-name nil))
1761 (global-proc-buffer-name (format "*%s*" global-proc-name))
1762 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1763 (global-running (comint-check-proc global-proc-buffer-name))
1764 (current-prefix-arg 16))
1765 (when (and (not dedicated-running) (not global-running))
1766 (if (call-interactively 'run-python)
1767 (setq dedicated-running t)
1768 (setq global-running t)))
1769 ;; Always prefer dedicated
1770 (get-buffer-process (if dedicated-running
1771 dedicated-proc-buffer-name
1772 global-proc-buffer-name))))
1774 (defvar python-shell-internal-buffer nil
1775 "Current internal shell buffer for the current buffer.
1776 This is really not necessary at all for the code to work but it's
1777 there for compatibility with CEDET.")
1779 (defvar python-shell-internal-last-output nil
1780 "Last output captured by the internal shell.
1781 This is really not necessary at all for the code to work but it's
1782 there for compatibility with CEDET.")
1784 (defun python-shell-internal-get-or-create-process ()
1785 "Get or create an inferior Internal Python process."
1786 (let* ((proc-name (python-shell-internal-get-process-name))
1787 (proc-buffer-name (format " *%s*" proc-name)))
1788 (when (not (process-live-p proc-name))
1789 (run-python-internal)
1790 (setq python-shell-internal-buffer proc-buffer-name)
1791 ;; XXX: Why is this `sit-for' needed?
1792 ;; `python-shell-make-comint' calls `accept-process-output'
1793 ;; already but it is not helping to get proper output on
1794 ;; 'gnu/linux when the internal shell process is not running and
1795 ;; a call to `python-shell-internal-send-string' is issued.
1797 (get-buffer-process proc-buffer-name)))
1799 (define-obsolete-function-alias
1800 'python-proc 'python-shell-internal-get-or-create-process "24.3")
1802 (define-obsolete-variable-alias
1803 'python-buffer 'python-shell-internal-buffer "24.3")
1805 (define-obsolete-variable-alias
1806 'python-preoutput-result 'python-shell-internal-last-output "24.3")
1808 (defun python-shell-send-string (string &optional process msg)
1809 "Send STRING to inferior Python PROCESS.
1810 When MSG is non-nil messages the first line of STRING."
1811 (interactive "sPython command: ")
1812 (let ((process (or process (python-shell-get-or-create-process)))
1813 (lines (split-string string "\n" t)))
1814 (and msg (message "Sent: %s..." (nth 0 lines)))
1815 (if (> (length lines) 1)
1816 (let* ((temporary-file-directory
1817 (if (file-remote-p default-directory)
1818 (concat (file-remote-p default-directory) "/tmp")
1819 temporary-file-directory))
1820 (temp-file-name (make-temp-file "py"))
1821 (file-name (or (buffer-file-name) temp-file-name)))
1822 (with-temp-file temp-file-name
1824 (delete-trailing-whitespace))
1825 (python-shell-send-file file-name process temp-file-name))
1826 (comint-send-string process string)
1827 (when (or (not (string-match "\n$" string))
1828 (string-match "\n[ \t].*\n?$" string))
1829 (comint-send-string process "\n")))))
1831 (defvar python-shell-output-filter-in-progress nil)
1832 (defvar python-shell-output-filter-buffer nil)
1834 (defun python-shell-output-filter (string)
1835 "Filter used in `python-shell-send-string-no-output' to grab output.
1836 STRING is the output received to this point from the process.
1837 This filter saves received output from the process in
1838 `python-shell-output-filter-buffer' and stops receiving it after
1839 detecting a prompt at the end of the buffer."
1841 string (ansi-color-filter-apply string)
1842 python-shell-output-filter-buffer
1843 (concat python-shell-output-filter-buffer string))
1845 (format "\n\\(?:%s\\|%s\\|%s\\)$"
1846 python-shell-prompt-regexp
1847 python-shell-prompt-block-regexp
1848 python-shell-prompt-pdb-regexp)
1849 python-shell-output-filter-buffer)
1850 ;; Output ends when `python-shell-output-filter-buffer' contains
1851 ;; the prompt attached at the end of it.
1852 (setq python-shell-output-filter-in-progress nil
1853 python-shell-output-filter-buffer
1854 (substring python-shell-output-filter-buffer
1855 0 (match-beginning 0)))
1856 (when (and (> (length python-shell-prompt-output-regexp) 0)
1857 (string-match (concat "^" python-shell-prompt-output-regexp)
1858 python-shell-output-filter-buffer))
1859 ;; Some shells, like iPython might append a prompt before the
1860 ;; output, clean that.
1861 (setq python-shell-output-filter-buffer
1862 (substring python-shell-output-filter-buffer (match-end 0)))))
1865 (defun python-shell-send-string-no-output (string &optional process msg)
1866 "Send STRING to PROCESS and inhibit output.
1867 When MSG is non-nil messages the first line of STRING. Return
1869 (let ((process (or process (python-shell-get-or-create-process)))
1870 (comint-preoutput-filter-functions
1871 '(python-shell-output-filter))
1872 (python-shell-output-filter-in-progress t)
1876 (python-shell-send-string string process msg)
1877 (while python-shell-output-filter-in-progress
1878 ;; `python-shell-output-filter' takes care of setting
1879 ;; `python-shell-output-filter-in-progress' to NIL after it
1880 ;; detects end of output.
1881 (accept-process-output process))
1883 python-shell-output-filter-buffer
1884 (setq python-shell-output-filter-buffer nil)))
1885 (with-current-buffer (process-buffer process)
1886 (comint-interrupt-subjob)))))
1888 (defun python-shell-internal-send-string (string)
1889 "Send STRING to the Internal Python interpreter.
1890 Returns the output. See `python-shell-send-string-no-output'."
1891 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1892 ;; updated to support this new mode.
1893 (setq python-shell-internal-last-output
1894 (python-shell-send-string-no-output
1895 ;; Makes this function compatible with the old
1896 ;; python-send-receive. (At least for CEDET).
1897 (replace-regexp-in-string "_emacs_out +" "" string)
1898 (python-shell-internal-get-or-create-process) nil)))
1900 (define-obsolete-function-alias
1901 'python-send-receive 'python-shell-internal-send-string "24.3")
1903 (define-obsolete-function-alias
1904 'python-send-string 'python-shell-internal-send-string "24.3")
1906 (defun python-shell-send-region (start end)
1907 "Send the region delimited by START and END to inferior Python process."
1909 (python-shell-send-string (buffer-substring start end) nil t))
1911 (defun python-shell-send-buffer (&optional arg)
1912 "Send the entire buffer to inferior Python process.
1913 With prefix ARG allow execution of code inside blocks delimited
1914 by \"if __name__== '__main__':\""
1918 (let ((str (buffer-substring (point-min) (point-max))))
1921 (setq str (replace-regexp-in-string
1922 (python-rx if-name-main)
1923 "if __name__ == '__main__ ':" str)))
1924 (python-shell-send-string str))))
1926 (defun python-shell-send-defun (arg)
1927 "Send the current defun to inferior Python process.
1928 When argument ARG is non-nil do not include decorators."
1931 (python-shell-send-region
1934 (while (and (or (python-beginning-of-defun-function)
1935 (beginning-of-line 1))
1936 (> (current-indentation) 0)))
1938 (while (and (forward-line -1)
1939 (looking-at (python-rx decorator))))
1943 (or (python-end-of-defun-function)
1947 (defun python-shell-send-file (file-name &optional process temp-file-name)
1948 "Send FILE-NAME to inferior Python PROCESS.
1949 If TEMP-FILE-NAME is passed then that file is used for processing
1950 instead, while internally the shell will continue to use
1952 (interactive "fFile to send: ")
1953 (let* ((process (or process (python-shell-get-or-create-process)))
1954 (temp-file-name (when temp-file-name
1956 (or (file-remote-p temp-file-name 'localname)
1958 (file-name (or (when file-name
1960 (or (file-remote-p file-name 'localname)
1963 (when (not file-name)
1964 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1965 (python-shell-send-string
1967 (concat "__pyfile = open('''%s''');"
1968 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1970 (or temp-file-name file-name) file-name)
1973 (defun python-shell-switch-to-shell ()
1974 "Switch to inferior Python process buffer."
1976 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1978 (defun python-shell-send-setup-code ()
1979 "Send all setup code for shell.
1980 This function takes the list of setup code to send from the
1981 `python-shell-setup-codes' list."
1982 (let ((process (get-buffer-process (current-buffer))))
1983 (dolist (code python-shell-setup-codes)
1985 (message "Sent %s" code)
1986 (python-shell-send-string
1987 (symbol-value code) process)))))
1989 (add-hook 'inferior-python-mode-hook
1990 #'python-shell-send-setup-code)
1993 ;;; Shell completion
1995 (defcustom python-shell-completion-setup-code
1999 def __COMPLETER_all_completions(text): []
2002 readline.set_completer(rlcompleter.Completer().complete)
2003 def __COMPLETER_all_completions(text):
2009 res = readline.get_completer()(text, i)
2012 completions.append(res)
2016 "Code used to setup completion in inferior Python processes."
2020 (defcustom python-shell-completion-string-code
2021 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2022 "Python code used to get a string of completions separated by semicolons."
2026 (defcustom python-shell-completion-module-string-code ""
2027 "Python code used to get completions separated by semicolons for imports.
2029 For IPython v0.11, add the following line to
2030 `python-shell-completion-setup-code':
2032 from IPython.core.completerlib import module_completion
2034 and use the following as the value of this variable:
2036 ';'.join(module_completion('''%s'''))\n"
2040 (defcustom python-shell-completion-pdb-string-code
2041 "';'.join(globals().keys() + locals().keys())"
2042 "Python code used to get completions separated by semicolons for [i]pdb."
2046 (defun python-shell-completion-get-completions (process line input)
2047 "Do completion at point for PROCESS.
2048 LINE is used to detect the context on how to complete given
2051 ;; Get the last prompt for the inferior process
2052 ;; buffer. This is used for the completion code selection
2054 (with-current-buffer (process-buffer process)
2055 (buffer-substring-no-properties
2056 (overlay-start comint-last-prompt-overlay)
2057 (overlay-end comint-last-prompt-overlay))))
2059 ;; Check whether a prompt matches a pdb string, an import
2060 ;; statement or just the standard prompt and use the
2061 ;; correct python-shell-completion-*-code string
2062 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2064 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2067 (length python-shell-completion-module-string-code) 0)
2069 (concat "^" python-shell-prompt-regexp) prompt)
2070 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2073 (concat "^" python-shell-prompt-regexp) prompt)
2077 (case completion-context
2078 (pdb python-shell-completion-pdb-string-code)
2079 (import python-shell-completion-module-string-code)
2080 (default python-shell-completion-string-code)
2083 (if (eq completion-context 'import)
2084 (replace-regexp-in-string "^[ \t]+" "" line)
2086 (and completion-code
2087 (> (length input) 0)
2088 (with-current-buffer (process-buffer process)
2089 (let ((completions (python-shell-send-string-no-output
2090 (format completion-code input) process)))
2091 (and (> (length completions) 2)
2092 (split-string completions
2093 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2095 (defun python-shell-completion-complete-at-point (&optional process)
2096 "Perform completion at point in inferior Python.
2097 Optional argument PROCESS forces completions to be retrieved
2098 using that one instead of current buffer's process."
2099 (setq process (or process (get-buffer-process (current-buffer))))
2102 (with-syntax-table python-dotty-syntax-table
2103 (let* ((paren-depth (car (syntax-ppss)))
2104 (syntax-string "w_")
2105 (syntax-list (string-to-syntax syntax-string)))
2106 ;; Stop scanning for the beginning of the completion
2107 ;; subject after the char before point matches a
2110 (car (syntax-after (1- (point)))) syntax-list)
2111 (skip-syntax-backward syntax-string)
2112 (when (or (equal (char-before) ?\))
2113 (equal (char-before) ?\"))
2116 ;; honor initial paren depth
2117 (> (car (syntax-ppss)) paren-depth)
2118 (python-syntax-context 'string))
2123 (completion-table-dynamic
2125 #'python-shell-completion-get-completions
2126 process (buffer-substring-no-properties
2127 (line-beginning-position) end))))))
2129 (defun python-shell-completion-complete-or-indent ()
2130 "Complete or indent depending on the context.
2131 If content before pointer is all whitespace indent. If not try
2134 (if (string-match "^[[:space:]]*$"
2135 (buffer-substring (comint-line-beginning-position)
2137 (indent-for-tab-command)
2138 (completion-at-point)))
2141 ;;; PDB Track integration
2143 (defcustom python-pdbtrack-activate t
2144 "Non-nil makes python shell enable pdbtracking."
2149 (defcustom python-pdbtrack-stacktrace-info-regexp
2150 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2151 "Regular Expression matching stacktrace information.
2152 Used to extract the current line and module being inspected."
2157 (defvar python-pdbtrack-tracked-buffer nil
2158 "Variable containing the value of the current tracked buffer.
2159 Never set this variable directly, use
2160 `python-pdbtrack-set-tracked-buffer' instead.")
2162 (defvar python-pdbtrack-buffers-to-kill nil
2163 "List of buffers to be deleted after tracking finishes.")
2165 (defun python-pdbtrack-set-tracked-buffer (file-name)
2166 "Set the buffer for FILE-NAME as the tracked buffer.
2167 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2168 Returns the tracked buffer."
2169 (let ((file-buffer (get-file-buffer file-name)))
2171 (setq python-pdbtrack-tracked-buffer file-buffer)
2172 (setq file-buffer (find-file-noselect file-name))
2173 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2174 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2177 (defun python-pdbtrack-comint-output-filter-function (output)
2178 "Move overlay arrow to current pdb line in tracked buffer.
2179 Argument OUTPUT is a string with the output from the comint process."
2180 (when (and python-pdbtrack-activate (not (string= output "")))
2181 (let* ((full-output (ansi-color-filter-apply
2182 (buffer-substring comint-last-input-end (point-max))))
2186 (insert full-output)
2187 (goto-char (point-min))
2188 ;; OK, this sucked but now it became a cool hack. The
2189 ;; stacktrace information normally is on the first line
2190 ;; but in some cases (like when doing a step-in) it is
2192 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
2195 (looking-at python-pdbtrack-stacktrace-info-regexp)))
2196 (setq line-number (string-to-number
2197 (match-string-no-properties 2)))
2198 (match-string-no-properties 1)))))
2199 (if (and file-name line-number)
2200 (let* ((tracked-buffer
2201 (python-pdbtrack-set-tracked-buffer file-name))
2202 (shell-buffer (current-buffer))
2203 (tracked-buffer-window (get-buffer-window tracked-buffer))
2204 (tracked-buffer-line-pos))
2205 (with-current-buffer tracked-buffer
2206 (set (make-local-variable 'overlay-arrow-string) "=>")
2207 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2208 (setq tracked-buffer-line-pos (progn
2209 (goto-char (point-min))
2210 (forward-line (1- line-number))
2212 (when tracked-buffer-window
2214 tracked-buffer-window tracked-buffer-line-pos))
2215 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2216 (pop-to-buffer tracked-buffer)
2217 (switch-to-buffer-other-window shell-buffer))
2218 (when python-pdbtrack-tracked-buffer
2219 (with-current-buffer python-pdbtrack-tracked-buffer
2220 (set-marker overlay-arrow-position nil))
2221 (mapc #'(lambda (buffer)
2222 (ignore-errors (kill-buffer buffer)))
2223 python-pdbtrack-buffers-to-kill)
2224 (setq python-pdbtrack-tracked-buffer nil
2225 python-pdbtrack-buffers-to-kill nil)))))
2229 ;;; Symbol completion
2231 (defun python-completion-complete-at-point ()
2232 "Complete current symbol at point.
2233 For this to work the best as possible you should call
2234 `python-shell-send-buffer' from time to time so context in
2235 inferior python process is updated properly."
2236 (let ((process (python-shell-get-process)))
2238 (error "Completion needs an inferior Python process running")
2239 (python-shell-completion-complete-at-point process))))
2241 (add-to-list 'debug-ignored-errors
2242 "^Completion needs an inferior Python process running.")
2247 (defcustom python-fill-comment-function 'python-fill-comment
2248 "Function to fill comments.
2249 This is the function used by `python-fill-paragraph-function' to
2254 (defcustom python-fill-string-function 'python-fill-string
2255 "Function to fill strings.
2256 This is the function used by `python-fill-paragraph-function' to
2261 (defcustom python-fill-decorator-function 'python-fill-decorator
2262 "Function to fill decorators.
2263 This is the function used by `python-fill-paragraph-function' to
2268 (defcustom python-fill-paren-function 'python-fill-paren
2269 "Function to fill parens.
2270 This is the function used by `python-fill-paragraph-function' to
2275 (defcustom python-fill-docstring-style 'pep-257
2276 "Style used to fill docstrings.
2277 This affects `python-fill-string' behavior with regards to
2278 triple quotes positioning.
2280 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2281 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2282 position and will treat docstrings a normal string, any other
2283 value may result in one of the following docstring styles:
2288 Process foo, return bar.
2292 Process foo, return bar.
2294 If processing fails throw ProcessingError.
2299 \"\"\"Process foo, return bar.\"\"\"
2302 Process foo, return bar.
2304 If processing fails throw ProcessingError.
2310 \"\"\"Process foo, return bar.\"\"\"
2312 \"\"\"Process foo, return bar.
2314 If processing fails throw ProcessingError.
2320 \"\"\"Process foo, return bar.\"\"\"
2322 \"\"\"Process foo, return bar.
2324 If processing fails throw ProcessingError.
2329 \"\"\"Process foo, return bar.\"\"\"
2332 Process foo, return bar.
2334 If processing fails throw ProcessingError.
2337 (const :tag "Don't format docstrings" nil)
2338 (const :tag "Django's coding standards style." django)
2339 (const :tag "One newline and start and Two at end style." onetwo)
2340 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2341 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2342 (const :tag "Symmetric style." symmetric))
2345 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2347 (defun python-fill-paragraph-function (&optional justify)
2348 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2349 If any of the current line is in or at the end of a multi-line string,
2350 fill the string or the paragraph of it that point is in, preserving
2351 the string's indentation.
2352 Optional argument JUSTIFY defines if the paragraph should be justified."
2357 ((python-syntax-context 'comment)
2358 (funcall python-fill-comment-function justify))
2359 ;; Strings/Docstrings
2360 ((save-excursion (or (python-syntax-context 'string)
2361 (equal (string-to-syntax "|")
2362 (syntax-after (point)))))
2363 (funcall python-fill-string-function justify))
2365 ((equal (char-after (save-excursion
2366 (back-to-indentation)
2368 (funcall python-fill-decorator-function justify))
2370 ((or (python-syntax-context 'paren)
2371 (looking-at (python-rx open-paren))
2373 (skip-syntax-forward "^(" (line-end-position))
2374 (looking-at (python-rx open-paren))))
2375 (funcall python-fill-paren-function justify))
2378 (defun python-fill-comment (&optional justify)
2379 "Comment fill function for `python-fill-paragraph-function'.
2380 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2381 (fill-comment-paragraph justify))
2383 (defun python-fill-string (&optional justify)
2384 "String fill function for `python-fill-paragraph-function'.
2385 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2386 (let* ((marker (point-marker))
2388 (let ((m (make-marker)))
2389 (setf (marker-position m)
2390 (or (python-syntax-context 'string)
2391 (and (equal (string-to-syntax "|")
2392 (syntax-after (point)))
2394 (num-quotes (python-syntax-count-quotes
2395 (char-after str-start-pos) str-start-pos))
2398 (goto-char (+ str-start-pos num-quotes))
2399 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2400 (goto-char (point-max)))
2403 ;; Docstring styles may vary for oneliners and multi-liners.
2404 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2406 (case python-fill-docstring-style
2407 ;; delimiters-style is a cons cell with the form
2408 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2409 ;; is NIL means to not add any newlines for start or end
2410 ;; of docstring. See `python-fill-docstring-style' for a
2411 ;; graphic idea of each style.
2413 (onetwo (and multi-line-p (cons 1 2)))
2414 (pep-257 (and multi-line-p (cons nil 2)))
2415 (pep-257-nn (and multi-line-p (cons nil 1)))
2416 (symmetric (and multi-line-p (cons 1 1)))))
2417 (docstring-p (save-excursion
2418 ;; Consider docstrings those strings which
2419 ;; start on a line by themselves.
2420 (python-nav-beginning-of-statement)
2421 (and (= (point) str-start-pos))))
2422 (fill-paragraph-function))
2424 (narrow-to-region str-start-pos str-end-pos)
2425 (fill-paragraph justify))
2427 (when (and docstring-p python-fill-docstring-style)
2428 ;; Add the number of newlines indicated by the selected style
2429 ;; at the start of the docstring.
2430 (goto-char (+ str-start-pos num-quotes))
2431 (delete-region (point) (progn
2432 (skip-syntax-forward "> ")
2434 (and (car delimiters-style)
2435 (or (newline (car delimiters-style)) t)
2436 ;; Indent only if a newline is added.
2437 (indent-according-to-mode))
2438 ;; Add the number of newlines indicated by the selected style
2439 ;; at the end of the docstring.
2440 (goto-char (if (not (= str-end-pos (point-max)))
2441 (- str-end-pos num-quotes)
2443 (delete-region (point) (progn
2444 (skip-syntax-backward "> ")
2446 (and (cdr delimiters-style)
2447 ;; Add newlines only if string ends.
2448 (not (= str-end-pos (point-max)))
2449 (or (newline (cdr delimiters-style)) t)
2450 ;; Again indent only if a newline is added.
2451 (indent-according-to-mode))))) t)
2453 (defun python-fill-decorator (&optional justify)
2454 "Decorator fill function for `python-fill-paragraph-function'.
2455 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2458 (defun python-fill-paren (&optional justify)
2459 "Paren fill function for `python-fill-paragraph-function'.
2460 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2462 (narrow-to-region (progn
2463 (while (python-syntax-context 'paren)
2464 (goto-char (1- (point-marker))))
2466 (line-beginning-position))
2468 (when (not (python-syntax-context 'paren))
2470 (when (not (python-syntax-context 'paren))
2471 (skip-syntax-backward "^)")))
2472 (while (python-syntax-context 'paren)
2473 (goto-char (1+ (point-marker))))
2475 (let ((paragraph-start "\f\\|[ \t]*$")
2476 (paragraph-separate ",")
2477 (fill-paragraph-function))
2478 (goto-char (point-min))
2479 (fill-paragraph justify))
2482 (python-indent-line)
2483 (goto-char (line-end-position)))) t)
2488 (defcustom python-skeleton-autoinsert nil
2489 "Non-nil means template skeletons will be automagically inserted.
2490 This happens when pressing \"if<SPACE>\", for example, to prompt for
2496 (define-obsolete-variable-alias
2497 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2499 (defvar python-skeleton-available '()
2500 "Internal list of available skeletons.")
2502 (define-abbrev-table 'python-mode-abbrev-table ()
2503 "Abbrev table for Python mode."
2505 ;; Allow / inside abbrevs.
2506 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2507 ;; Only expand in code.
2508 :enable-function (lambda ()
2510 (not (python-syntax-comment-or-string-p))
2511 python-skeleton-autoinsert)))
2513 (defmacro python-skeleton-define (name doc &rest skel)
2514 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2515 The skeleton will be bound to python-skeleton-NAME and will
2516 be added to `python-mode-abbrev-table'."
2517 (declare (indent 2))
2518 (let* ((name (symbol-name name))
2519 (function-name (intern (concat "python-skeleton-" name))))
2521 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
2523 (setq python-skeleton-available
2524 (cons ',function-name python-skeleton-available))
2525 (define-skeleton ,function-name
2527 (format "Insert %s statement." name))
2530 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2531 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2532 The skeleton will be bound to python-skeleton-NAME."
2533 (declare (indent 2))
2534 (let* ((name (symbol-name name))
2535 (function-name (intern (concat "python-skeleton--" name)))
2537 "Add '%s' clause? " name)))
2540 `(< ,(format "%s:" name) \n \n
2542 `(define-skeleton ,function-name
2544 (format "Auxiliary skeleton for %s statement." name))
2546 (unless (y-or-n-p ,msg)
2550 (python-define-auxiliary-skeleton else nil)
2552 (python-define-auxiliary-skeleton except nil)
2554 (python-define-auxiliary-skeleton finally nil)
2556 (python-skeleton-define if nil
2560 ("other condition, %s: "
2564 '(python-skeleton--else) | ^)
2566 (python-skeleton-define while nil
2570 '(python-skeleton--else) | ^)
2572 (python-skeleton-define for nil
2576 '(python-skeleton--else) | ^)
2578 (python-skeleton-define try nil
2584 "except " str ":" \n
2587 '(python-skeleton--except)
2588 '(python-skeleton--else)
2589 '(python-skeleton--finally) | ^)
2591 (python-skeleton-define def nil
2593 "def " str " (" ("Parameter, %s: "
2594 (unless (equal ?\( (char-before)) ", ")
2596 "\"\"\"" - "\"\"\"" \n
2599 (python-skeleton-define class nil
2601 "class " str " (" ("Inheritance, %s: "
2602 (unless (equal ?\( (char-before)) ", ")
2606 "\"\"\"" - "\"\"\"" \n
2609 (defun python-skeleton-add-menu-items ()
2610 "Add menu items to Python->Skeletons menu."
2611 (let ((skeletons (sort python-skeleton-available 'string<))
2613 (dolist (skeleton skeletons)
2615 nil '("Python" "Skeletons")
2617 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2622 (defcustom python-ffap-setup-code
2623 "def __FFAP_get_module_path(module):
2626 path = __import__(module).__file__
2627 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2632 "Python code to get a module path."
2636 (defcustom python-ffap-string-code
2637 "__FFAP_get_module_path('''%s''')\n"
2638 "Python code used to get a string with the path of a module."
2642 (defun python-ffap-module-path (module)
2643 "Function for `ffap-alist' to return path for MODULE."
2645 (and (eq major-mode 'inferior-python-mode)
2646 (get-buffer-process (current-buffer)))
2647 (python-shell-get-process))))
2651 (python-shell-send-string-no-output
2652 (format python-ffap-string-code module) process)))
2654 (substring-no-properties module-file 1 -1))))))
2656 (eval-after-load "ffap"
2658 (push '(python-mode . python-ffap-module-path) ffap-alist)
2659 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2664 (defcustom python-check-command
2666 "Command used to check a Python file."
2670 (defcustom python-check-buffer-name
2671 "*Python check: %s*"
2672 "Buffer name used for check commands."
2676 (defvar python-check-custom-command nil
2679 (defun python-check (command)
2680 "Check a Python file (default current buffer's file).
2681 Runs COMMAND, a shell command, as if by `compile'. See
2682 `python-check-command' for the default."
2684 (list (read-string "Check command: "
2685 (or python-check-custom-command
2686 (concat python-check-command " "
2687 (shell-quote-argument
2689 (let ((name (buffer-file-name)))
2691 (file-name-nondirectory name)))
2693 (setq python-check-custom-command command)
2694 (save-some-buffers (not compilation-ask-about-save) nil)
2695 (let ((process-environment (python-shell-calculate-process-environment))
2696 (exec-path (python-shell-calculate-exec-path)))
2697 (compilation-start command nil
2699 (format python-check-buffer-name command)))))
2704 (defcustom python-eldoc-setup-code
2705 "def __PYDOC_get_help(obj):
2708 if hasattr(obj, 'startswith'):
2709 obj = eval(obj, globals())
2710 doc = inspect.getdoc(obj)
2711 if not doc and callable(obj):
2713 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2714 target = obj.__init__
2720 args = inspect.formatargspec(
2721 *inspect.getargspec(target)
2724 doc = '{objtype} {name}{args}'.format(
2725 objtype=objtype, name=name, args=args
2728 doc = doc.splitlines()[0]
2735 "Python code to setup documentation retrieval."
2739 (defcustom python-eldoc-string-code
2740 "__PYDOC_get_help('''%s''')\n"
2741 "Python code used to get a string with the documentation of an object."
2745 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2746 "Internal implementation to get documentation at point.
2747 If not FORCE-INPUT is passed then what
2748 `python-info-current-symbol' returns will be used. If not
2749 FORCE-PROCESS is passed what `python-shell-get-process' returns
2751 (let ((process (or force-process (python-shell-get-process))))
2753 (error "Eldoc needs an inferior Python process running")
2754 (let ((input (or force-input
2755 (python-info-current-symbol t))))
2757 (python-shell-send-string-no-output
2758 (format python-eldoc-string-code input)
2761 (defun python-eldoc-function ()
2762 "`eldoc-documentation-function' for Python.
2763 For this to work the best as possible you should call
2764 `python-shell-send-buffer' from time to time so context in
2765 inferior python process is updated properly."
2766 (python-eldoc--get-doc-at-point))
2768 (defun python-eldoc-at-point (symbol)
2769 "Get help on SYMBOL using `help'.
2770 Interactively, prompt for symbol."
2772 (let ((symbol (python-info-current-symbol t))
2773 (enable-recursive-minibuffers t))
2774 (list (read-string (if symbol
2775 (format "Describe symbol (default %s): " symbol)
2776 "Describe symbol: ")
2778 (message (python-eldoc--get-doc-at-point symbol)))
2780 (add-to-list 'debug-ignored-errors
2781 "^Eldoc needs an inferior Python process running.")
2786 (defun python-info-current-defun (&optional include-type)
2787 "Return name of surrounding function with Python compatible dotty syntax.
2788 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2789 This function is compatible to be used as
2790 `add-log-current-defun-function' since it returns nil if point is
2791 not inside a defun."
2793 (starting-indentation)
2799 (setq starting-point (point-marker))
2800 (setq starting-indentation (save-excursion
2801 (python-nav-beginning-of-statement)
2802 (current-indentation)))
2804 (while (python-beginning-of-defun-function 1)
2805 (when (or (< (current-indentation) starting-indentation)
2810 (python-end-of-defun-function)
2812 (setq first-run nil)
2813 (setq starting-indentation (current-indentation))
2814 (looking-at python-nav-beginning-of-defun-regexp)
2816 (if (not include-type)
2817 (match-string-no-properties 1)
2818 (mapconcat 'identity
2820 (match-string-no-properties 0)) " "))
2823 (mapconcat (lambda (string) string) names "."))))
2825 (defun python-info-current-symbol (&optional replace-self)
2826 "Return current symbol using dotty syntax.
2827 With optional argument REPLACE-SELF convert \"self\" to current
2830 (and (not (python-syntax-comment-or-string-p))
2831 (with-syntax-table python-dotty-syntax-table
2832 (let ((sym (symbol-at-point)))
2834 (substring-no-properties (symbol-name sym))))))))
2836 (if (not replace-self)
2838 (let ((current-defun (python-info-current-defun)))
2839 (if (not current-defun)
2841 (replace-regexp-in-string
2842 (python-rx line-start word-start "self" word-end ?.)
2844 (mapconcat 'identity
2845 (butlast (split-string current-defun "\\."))
2849 (defun python-info-statement-starts-block-p ()
2850 "Return non-nil if current statement opens a block."
2852 (python-nav-beginning-of-statement)
2853 (looking-at (python-rx block-start))))
2855 (defun python-info-statement-ends-block-p ()
2856 "Return non-nil if point is at end of block."
2857 (let ((end-of-block-pos (save-excursion
2858 (python-nav-end-of-block)))
2859 (end-of-statement-pos (save-excursion
2860 (python-nav-end-of-statement))))
2861 (and end-of-block-pos end-of-statement-pos
2862 (= end-of-block-pos end-of-statement-pos))))
2864 (defun python-info-beginning-of-statement-p ()
2865 "Return non-nil if point is at beginning of statement."
2866 (= (point) (save-excursion
2867 (python-nav-beginning-of-statement)
2870 (defun python-info-end-of-statement-p ()
2871 "Return non-nil if point is at end of statement."
2872 (= (point) (save-excursion
2873 (python-nav-end-of-statement)
2876 (defun python-info-beginning-of-block-p ()
2877 "Return non-nil if point is at beginning of block."
2878 (and (python-info-beginning-of-statement-p)
2879 (python-info-statement-starts-block-p)))
2881 (defun python-info-end-of-block-p ()
2882 "Return non-nil if point is at end of block."
2883 (and (python-info-end-of-statement-p)
2884 (python-info-statement-ends-block-p)))
2886 (defun python-info-closing-block ()
2887 "Return the point of the block the current line closes."
2888 (let ((closing-word (save-excursion
2889 (back-to-indentation)
2891 (indentation (current-indentation)))
2892 (when (member closing-word python-indent-dedenters)
2895 (while (and (> (current-indentation) indentation)
2897 (not (back-to-indentation))
2899 (back-to-indentation)
2901 ((not (equal indentation (current-indentation))) nil)
2902 ((string= closing-word "elif")
2903 (when (member (current-word) '("if" "elif"))
2905 ((string= closing-word "else")
2906 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2908 ((string= closing-word "except")
2909 (when (member (current-word) '("try"))
2911 ((string= closing-word "finally")
2912 (when (member (current-word) '("except" "else"))
2913 (point-marker))))))))
2915 (defun python-info-closing-block-message (&optional closing-block-point)
2916 "Message the contents of the block the current line closes.
2917 With optional argument CLOSING-BLOCK-POINT use that instead of
2918 recalculating it calling `python-info-closing-block'."
2919 (let ((point (or closing-block-point (python-info-closing-block))))
2923 (message "Closes %s" (save-excursion
2925 (back-to-indentation)
2927 (point) (line-end-position))))))))
2929 (defun python-info-line-ends-backslash-p (&optional line-number)
2930 "Return non-nil if current line ends with backslash.
2931 With optional argument LINE-NUMBER, check that line instead."
2936 (goto-char line-number))
2937 (while (and (not (eobp))
2938 (goto-char (line-end-position))
2939 (python-syntax-context 'paren)
2940 (not (equal (char-before (point)) ?\\)))
2942 (when (equal (char-before) ?\\)
2945 (defun python-info-beginning-of-backslash (&optional line-number)
2946 "Return the point where the backslashed line start.
2947 Optional argument LINE-NUMBER forces the line number to check against."
2952 (goto-char line-number))
2953 (when (python-info-line-ends-backslash-p)
2954 (while (save-excursion
2955 (goto-char (line-beginning-position))
2956 (python-syntax-context 'paren))
2958 (back-to-indentation)
2961 (defun python-info-continuation-line-p ()
2962 "Check if current line is continuation of another.
2963 When current line is continuation of another return the point
2964 where the continued line ends."
2968 (let* ((context-type (progn
2969 (back-to-indentation)
2970 (python-syntax-context-type)))
2971 (line-start (line-number-at-pos))
2972 (context-start (when context-type
2973 (python-syntax-context context-type))))
2974 (cond ((equal context-type 'paren)
2975 ;; Lines inside a paren are always a continuation line
2976 ;; (except the first one).
2977 (python-util-forward-comment -1)
2979 ((member context-type '(string comment))
2980 ;; move forward an roll again
2981 (goto-char context-start)
2982 (python-util-forward-comment)
2983 (python-info-continuation-line-p))
2985 ;; Not within a paren, string or comment, the only way
2986 ;; we are dealing with a continuation line is that
2987 ;; previous line contains a backslash, and this can
2988 ;; only be the previous line from current
2989 (back-to-indentation)
2990 (python-util-forward-comment -1)
2991 (when (and (equal (1- line-start) (line-number-at-pos))
2992 (python-info-line-ends-backslash-p))
2993 (point-marker))))))))
2995 (defun python-info-block-continuation-line-p ()
2996 "Return non-nil if current line is a continuation of a block."
2998 (when (python-info-continuation-line-p)
3000 (back-to-indentation)
3001 (when (looking-at (python-rx block-start))
3004 (defun python-info-assignment-continuation-line-p ()
3005 "Check if current line is a continuation of an assignment.
3006 When current line is continuation of another with an assignment
3007 return the point of the first non-blank character after the
3010 (when (python-info-continuation-line-p)
3012 (back-to-indentation)
3013 (when (and (not (looking-at (python-rx block-start)))
3014 (and (re-search-forward (python-rx not-simple-operator
3016 not-simple-operator)
3017 (line-end-position) t)
3018 (not (python-syntax-context-type))))
3019 (skip-syntax-forward "\s")
3022 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3023 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3024 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3026 (beginning-of-line 1)
3027 (looking-at python-nav-beginning-of-defun-regexp))))
3029 (defun python-info-current-line-comment-p ()
3030 "Check if current line is a comment line."
3031 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
3033 (defun python-info-current-line-empty-p ()
3034 "Check if current line is empty, ignoring whitespace."
3036 (beginning-of-line 1)
3038 (python-rx line-start (* whitespace)
3039 (group (* not-newline))
3040 (* whitespace) line-end))
3041 (string-equal "" (match-string-no-properties 1))))
3044 ;;; Utility functions
3046 (defun python-util-position (item seq)
3047 "Find the first occurrence of ITEM in SEQ.
3048 Return the index of the matching item, or nil if not found."
3049 (let ((member-result (member item seq)))
3051 (- (length seq) (length member-result)))))
3053 ;; Stolen from org-mode
3054 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3055 "Clone local variables from FROM-BUFFER.
3056 Optional argument REGEXP selects variables to clone and defaults
3060 (and (symbolp (car pair))
3061 (string-match (or regexp "^python-")
3062 (symbol-name (car pair)))
3063 (set (make-local-variable (car pair))
3065 (buffer-local-variables from-buffer)))
3067 (defun python-util-forward-comment (&optional direction)
3068 "Python mode specific version of `forward-comment'.
3069 Optional argument DIRECTION defines the direction to move to."
3070 (let ((comment-start (python-syntax-context 'comment))
3071 (factor (if (< (or direction 0) 0)
3075 (goto-char comment-start))
3076 (forward-comment factor)))
3080 (define-derived-mode python-mode prog-mode "Python"
3081 "Major mode for editing Python files.
3084 Entry to this mode calls the value of `python-mode-hook'
3085 if that value is non-nil."
3086 (set (make-local-variable 'tab-width) 8)
3087 (set (make-local-variable 'indent-tabs-mode) nil)
3089 (set (make-local-variable 'comment-start) "# ")
3090 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3092 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3093 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3095 (set (make-local-variable 'forward-sexp-function)
3096 'python-nav-forward-sexp)
3098 (set (make-local-variable 'font-lock-defaults)
3099 '(python-font-lock-keywords nil nil nil nil))
3101 (set (make-local-variable 'syntax-propertize-function)
3102 python-syntax-propertize-function)
3104 (set (make-local-variable 'indent-line-function)
3105 #'python-indent-line-function)
3106 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3108 (set (make-local-variable 'paragraph-start) "\\s-*$")
3109 (set (make-local-variable 'fill-paragraph-function)
3110 'python-fill-paragraph-function)
3112 (set (make-local-variable 'beginning-of-defun-function)
3113 #'python-beginning-of-defun-function)
3114 (set (make-local-variable 'end-of-defun-function)
3115 #'python-end-of-defun-function)
3117 (add-hook 'completion-at-point-functions
3118 'python-completion-complete-at-point nil 'local)
3120 (add-hook 'post-self-insert-hook
3121 'python-indent-post-self-insert-function nil 'local)
3123 (set (make-local-variable 'imenu-extract-index-name-function)
3124 #'python-info-current-defun)
3126 (set (make-local-variable 'add-log-current-defun-function)
3127 #'python-info-current-defun)
3129 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3131 (set (make-local-variable 'skeleton-further-elements)
3133 (< '(backward-delete-char-untabify (min python-indent-offset
3135 (^ '(- (1+ (current-indentation))))))
3137 (set (make-local-variable 'eldoc-documentation-function)
3138 #'python-eldoc-function)
3140 (add-to-list 'hs-special-modes-alist
3141 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3143 (python-end-of-defun-function)) nil))
3145 (set (make-local-variable 'mode-require-final-newline) t)
3147 (set (make-local-variable 'outline-regexp)
3148 (python-rx (* space) block-start))
3149 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3150 (set (make-local-variable 'outline-level)
3152 "`outline-level' function for Python mode."
3153 (1+ (/ (current-indentation) python-indent-offset))))
3155 (python-skeleton-add-menu-items)
3157 (make-local-variable 'python-shell-internal-buffer)
3159 (when python-indent-guess-indent-offset
3160 (python-indent-guess-indent-offset)))
3167 ;; indent-tabs-mode: nil
3170 ;;; python.el ends here