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' and
176 ;; `imenu-prev-index-position-function' to
177 ;; `python-imenu-prev-index-position'.
179 ;; If you used python-mode.el you probably will miss auto-indentation
180 ;; when inserting newlines. To achieve the same behavior you have
183 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
185 ;; 2) Add the following hook in your .emacs:
187 ;; (add-hook 'python-mode-hook
189 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
191 ;; I'd recommend the first one since you'll get the same behavior for
192 ;; all modes out-of-the-box.
196 ;; Add this to your .emacs:
198 ;; (add-to-list 'load-path "/folder/containing/file")
205 (require 'ansi-color
)
210 ;; Avoid compiler warnings
211 (defvar view-return-to-alist
)
212 (defvar compilation-error-regexp-alist
)
213 (defvar outline-heading-end-regexp
))
215 (autoload 'comint-mode
"comint")
218 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
220 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
223 "Python Language's flying circus support for Emacs."
226 :link
'(emacs-commentary-link "python"))
231 (defvar python-mode-map
232 (let ((map (make-sparse-keymap)))
234 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
235 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
236 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
237 (define-key map
"\C-c\C-j" 'imenu
)
239 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
240 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
241 (define-key map
"\C-c<" 'python-indent-shift-left
)
242 (define-key map
"\C-c>" 'python-indent-shift-right
)
243 (define-key map
":" 'python-indent-electric-colon
)
245 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
246 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
247 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
248 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
249 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
250 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
252 (define-key map
"\C-c\C-p" 'run-python
)
253 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
254 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
255 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
256 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
257 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
258 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
259 ;; Some util commands
260 (define-key map
"\C-c\C-v" 'python-check
)
261 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
263 (substitute-key-definition 'complete-symbol
'completion-at-point
265 (easy-menu-define python-menu map
"Python Mode menu"
267 :help
"Python-specific Features"
268 ["Shift region left" python-indent-shift-left
:active mark-active
269 :help
"Shift region left by a single indentation step"]
270 ["Shift region right" python-indent-shift-right
:active mark-active
271 :help
"Shift region right by a single indentation step"]
273 ["Start of def/class" beginning-of-defun
274 :help
"Go to start of outermost definition around point"]
275 ["End of def/class" end-of-defun
276 :help
"Go to end of definition around point"]
277 ["Mark def/class" mark-defun
278 :help
"Mark outermost definition around point"]
279 ["Jump to def/class" imenu
280 :help
"Jump to a class or function definition"]
284 ["Start interpreter" run-python
285 :help
"Run inferior Python process in a separate buffer"]
286 ["Switch to shell" python-shell-switch-to-shell
287 :help
"Switch to running inferior Python process"]
288 ["Eval string" python-shell-send-string
289 :help
"Eval string in inferior Python session"]
290 ["Eval buffer" python-shell-send-buffer
291 :help
"Eval buffer in inferior Python session"]
292 ["Eval region" python-shell-send-region
293 :help
"Eval region in inferior Python session"]
294 ["Eval defun" python-shell-send-defun
295 :help
"Eval defun in inferior Python session"]
296 ["Eval file" python-shell-send-file
297 :help
"Eval file in inferior Python session"]
298 ["Debugger" pdb
:help
"Run pdb under GUD"]
300 ["Check file" python-check
301 :help
"Check file for errors"]
302 ["Help on symbol" python-eldoc-at-point
303 :help
"Get help on symbol at point"]
304 ["Complete symbol" completion-at-point
305 :help
"Complete symbol before point"]))
307 "Keymap for `python-mode'.")
310 ;;; Python specialized rx
313 (defconst python-rx-constituents
314 `((block-start .
,(rx symbol-start
315 (or "def" "class" "if" "elif" "else" "try"
316 "except" "finally" "for" "while" "with")
318 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
320 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
321 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
322 (+ space
) "==" (+ space
)
323 (any ?
' ?
\") "__main__" (any ?
' ?
\")
325 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
326 (open-paren .
,(rx (or "{" "[" "(")))
327 (close-paren .
,(rx (or "}" "]" ")")))
328 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
329 ;; FIXME: rx should support (not simple-operator).
330 (not-simple-operator .
,(rx
332 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
333 ;; FIXME: Use regexp-opt.
334 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
335 "=" "%" "**" "//" "<<" ">>" "<=" "!="
336 "==" ">=" "is" "not")))
337 ;; FIXME: Use regexp-opt.
338 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
339 ">>=" "<<=" "&=" "^=" "|=")))
340 (string-delimiter .
,(rx (and
341 ;; Match even number of backslashes.
342 (or (not (any ?
\\ ?
\' ?
\")) point
343 ;; Quotes might be preceded by a escaped quote.
344 (and (or (not (any ?
\\)) point
) ?
\\
345 (* ?
\\ ?
\\) (any ?
\' ?
\")))
347 ;; Match single or triple quotes of any kind.
348 (group (or "\"" "\"\"\"" "'" "'''"))))))
349 "Additional Python specific sexps for `python-rx'")
351 (defmacro python-rx
(&rest regexps
)
352 "Python mode specialized rx macro.
353 This variant of `rx' supports common python named REGEXPS."
354 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
355 (cond ((null regexps
)
358 (rx-to-string `(and ,@regexps
) t
))
360 (rx-to-string (car regexps
) t
))))))
363 ;;; Font-lock and syntax
365 (defun python-syntax-context (type &optional syntax-ppss
)
366 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
367 TYPE can be `comment', `string' or `paren'. It returns the start
368 character address of the specified TYPE."
369 (let ((ppss (or syntax-ppss
(syntax-ppss))))
371 (comment (and (nth 4 ppss
) (nth 8 ppss
)))
372 (string (and (not (nth 4 ppss
)) (nth 8 ppss
)))
376 (defun python-syntax-context-type (&optional syntax-ppss
)
377 "Return the context type using SYNTAX-PPSS.
378 The type returned can be `comment', `string' or `paren'."
379 (let ((ppss (or syntax-ppss
(syntax-ppss))))
381 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
382 ((nth 1 ppss
) 'paren
))))
384 (defsubst python-syntax-comment-or-string-p
()
385 "Return non-nil if point is inside 'comment or 'string."
386 (nth 8 (syntax-ppss)))
388 (define-obsolete-function-alias
389 'python-info-ppss-context
#'python-syntax-context
"24.3")
391 (define-obsolete-function-alias
392 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
394 (define-obsolete-function-alias
395 'python-info-ppss-comment-or-string-p
396 #'python-syntax-comment-or-string-p
"24.3")
398 (defvar python-font-lock-keywords
402 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
403 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
404 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
409 ;; False, None, and True are listed as keywords on the Python 3
410 ;; documentation, but since they also qualify as constants they are
411 ;; fontified like that in order to keep font-lock consistent between
418 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
419 (1 font-lock-function-name-face
))
421 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
422 (1 font-lock-type-face
))
426 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
427 ;; copyright, license, credits, quit and exit are added by the site
428 ;; module and they are not intended to be used in programs
429 "copyright" "credits" "exit" "license" "quit")
430 symbol-end
) . font-lock-constant-face
)
432 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
433 (0+ "." (1+ (or word ?_
)))))
434 (1 font-lock-type-face
))
435 ;; Builtin Exceptions
438 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
439 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
440 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
441 "ImportError" "ImportWarning" "IndexError" "KeyError"
442 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
443 "NotImplementedError" "OSError" "OverflowError"
444 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
445 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
446 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
447 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
448 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
449 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
453 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
455 symbol-end
) . font-lock-type-face
)
459 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
460 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
461 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
462 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
463 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
464 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
465 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
466 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
469 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
470 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
473 "ascii" "bytearray" "bytes" "exec"
475 "__all__" "__doc__" "__name__" "__package__")
476 symbol-end
) . font-lock-builtin-face
)
478 ;; support for a = b = c = 5
480 (let ((re (python-rx (group (+ (any word ?. ?_
)))
481 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
482 assignment-operator
)))
483 (when (re-search-forward re limit t
)
484 (while (and (python-syntax-context 'paren
)
485 (re-search-forward re limit t
)))
486 (if (and (not (python-syntax-context 'paren
))
487 (not (equal (char-after (point-marker)) ?
=)))
489 (set-match-data nil
)))))
490 (1 font-lock-variable-name-face nil nil
))
491 ;; support for a, b, c = (1, 2, 3)
493 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
494 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
495 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
496 assignment-operator
)))
497 (when (and (re-search-forward re limit t
)
498 (goto-char (nth 3 (match-data))))
499 (while (and (python-syntax-context 'paren
)
500 (re-search-forward re limit t
))
501 (goto-char (nth 3 (match-data))))
502 (if (not (python-syntax-context 'paren
))
504 (set-match-data nil
)))))
505 (1 font-lock-variable-name-face nil nil
))))
507 (defconst python-syntax-propertize-function
508 (syntax-propertize-rules
509 ((python-rx string-delimiter
)
510 (0 (ignore (python-syntax-stringify))))))
512 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
513 "Count number of quotes around point (max is 3).
514 QUOTE-CHAR is the quote char to count. Optional argument POINT is
515 the point where scan starts (defaults to current point) and LIMIT
516 is used to limit the scan."
519 (or (not limit
) (< (+ point i
) limit
))
520 (eq (char-after (+ point i
)) quote-char
))
524 (defun python-syntax-stringify ()
525 "Put `syntax-table' property correctly on single/triple quotes."
526 (let* ((num-quotes (length (match-string-no-properties 1)))
528 (backward-char num-quotes
)
530 (forward-char num-quotes
)))
531 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
532 (quote-starting-pos (- (point) num-quotes
))
533 (quote-ending-pos (point))
536 (python-syntax-count-quotes
537 (char-before) string-start quote-starting-pos
))))
538 (cond ((and string-start
(= num-closing-quotes
0))
539 ;; This set of quotes doesn't match the string starting
543 ;; This set of quotes delimit the start of a string.
544 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
545 'syntax-table
(string-to-syntax "|")))
546 ((= num-quotes num-closing-quotes
)
547 ;; This set of quotes delimit the end of a string.
548 (put-text-property (1- quote-ending-pos
) quote-ending-pos
549 'syntax-table
(string-to-syntax "|")))
550 ((> num-quotes num-closing-quotes
)
551 ;; This may only happen whenever a triple quote is closing
552 ;; a single quoted string. Add string delimiter syntax to
554 (put-text-property quote-starting-pos quote-ending-pos
555 'syntax-table
(string-to-syntax "|"))))))
557 (defvar python-mode-syntax-table
558 (let ((table (make-syntax-table)))
559 ;; Give punctuation syntax to ASCII that normally has symbol
560 ;; syntax or has word syntax and isn't a letter.
561 (let ((symbol (string-to-syntax "_"))
562 (sst (standard-syntax-table)))
565 (if (equal symbol
(aref sst i
))
566 (modify-syntax-entry i
"." table
)))))
567 (modify-syntax-entry ?$
"." table
)
568 (modify-syntax-entry ?%
"." table
)
570 (modify-syntax-entry ?
# "<" table
)
571 (modify-syntax-entry ?
\n ">" table
)
572 (modify-syntax-entry ?
' "\"" table
)
573 (modify-syntax-entry ?
` "$" table
)
575 "Syntax table for Python files.")
577 (defvar python-dotty-syntax-table
578 (let ((table (make-syntax-table python-mode-syntax-table
)))
579 (modify-syntax-entry ?.
"w" table
)
580 (modify-syntax-entry ?_
"w" table
)
582 "Dotty syntax table for Python files.
583 It makes underscores and dots word constituent chars.")
588 (defcustom python-indent-offset
4
589 "Default indentation offset for Python."
594 (defcustom python-indent-guess-indent-offset t
595 "Non-nil tells Python mode to guess `python-indent-offset' value."
600 (define-obsolete-variable-alias
601 'python-indent
'python-indent-offset
"24.3")
603 (define-obsolete-variable-alias
604 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
606 (defvar python-indent-current-level
0
607 "Current indentation level `python-indent-line-function' is using.")
609 (defvar python-indent-levels
'(0)
610 "Levels of indentation available for `python-indent-line-function'.")
612 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
613 "List of words that should be dedented.
614 These make `python-indent-calculate-indentation' subtract the value of
615 `python-indent-offset'.")
617 (defun python-indent-guess-indent-offset ()
618 "Guess and set `python-indent-offset' for the current buffer."
623 (goto-char (point-min))
625 (while (and (not block-end
)
627 (python-rx line-start block-start
) nil t
))
629 (not (python-syntax-context-type))
631 (goto-char (line-end-position))
632 (python-util-forward-comment -
1)
633 (if (equal (char-before) ?
:)
636 (when (python-info-block-continuation-line-p)
637 (while (and (python-info-continuation-line-p)
640 (python-util-forward-comment -
1)
641 (when (equal (char-before) ?
:)
643 (setq block-end
(point-marker))))
646 (goto-char block-end
)
647 (python-util-forward-comment)
648 (current-indentation))))
650 (set (make-local-variable 'python-indent-offset
) indentation
)
651 (message "Can't guess python-indent-offset, using defaults: %s"
652 python-indent-offset
)))))))
654 (defun python-indent-context ()
655 "Get information on indentation context.
656 Context information is returned with a cons with the form:
659 Where status can be any of the following symbols:
660 * inside-paren: If point in between (), {} or []
661 * inside-string: If point is inside a string
662 * after-backslash: Previous line ends in a backslash
663 * after-beginning-of-block: Point is after beginning of block
664 * after-line: Point is after normal line
665 * no-indent: Point is at beginning of buffer or other special case
666 START is the buffer position where the sexp starts."
669 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
673 ;; Beginning of buffer
675 (goto-char (line-beginning-position))
679 ((setq start
(python-syntax-context 'string ppss
))
682 ((setq start
(python-syntax-context 'paren ppss
))
685 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
686 (python-syntax-context 'comment ppss
)))
687 (let ((line-beg-pos (line-beginning-position)))
688 (when (python-info-line-ends-backslash-p
690 (- line-beg-pos
2)))))
692 ;; After beginning of block
693 ((setq start
(save-excursion
695 (back-to-indentation)
696 (python-util-forward-comment -
1)
697 (equal (char-before) ?
:))
698 ;; Move to the first block start that's not in within
699 ;; a string, comment or paren and that's not a
700 ;; continuation line.
701 (while (and (re-search-backward
702 (python-rx block-start
) nil t
)
704 (python-syntax-context-type)
705 (python-info-continuation-line-p))))
706 (when (looking-at (python-rx block-start
))
708 'after-beginning-of-block
)
710 ((setq start
(save-excursion
711 (back-to-indentation)
712 (skip-chars-backward (rx (or whitespace ?
\n)))
713 (python-nav-beginning-of-statement)
720 (defun python-indent-calculate-indentation ()
721 "Calculate correct indentation offset for the current line."
722 (let* ((indentation-context (python-indent-context))
723 (context-status (car indentation-context
))
724 (context-start (cdr indentation-context
)))
730 ;; When point is after beginning of block just add one level
731 ;; of indentation relative to the context-start
732 ('after-beginning-of-block
733 (goto-char context-start
)
734 (+ (current-indentation) python-indent-offset
))
735 ;; When after a simple line just use previous line
736 ;; indentation, in the case current line starts with a
737 ;; `python-indent-dedenters' de-indent one level.
741 (goto-char context-start
)
742 (current-indentation))
744 (back-to-indentation)
745 (looking-at (regexp-opt python-indent-dedenters
)))
748 ;; When inside of a string, do nothing. just use the current
749 ;; indentation. XXX: perhaps it would be a good idea to
750 ;; invoke standard text indentation here
752 (goto-char context-start
)
753 (current-indentation))
754 ;; After backslash we have several possibilities.
757 ;; Check if current line is a dot continuation. For this
758 ;; the current line must start with a dot and previous
759 ;; line must contain a dot too.
761 (back-to-indentation)
762 (when (looking-at "\\.")
763 ;; If after moving one line back point is inside a paren it
764 ;; needs to move back until it's not anymore
768 (python-syntax-context 'paren
))))
769 (goto-char (line-end-position))
770 (while (and (re-search-backward
771 "\\." (line-beginning-position) t
)
772 (python-syntax-context-type)))
773 (if (and (looking-at "\\.")
774 (not (python-syntax-context-type)))
775 ;; The indentation is the same column of the
776 ;; first matching dot that's not inside a
777 ;; comment, a string or a paren
779 ;; No dot found on previous line, just add another
780 ;; indentation level.
781 (+ (current-indentation) python-indent-offset
)))))
782 ;; Check if prev line is a block continuation
783 ((let ((block-continuation-start
784 (python-info-block-continuation-line-p)))
785 (when block-continuation-start
786 ;; If block-continuation-start is set jump to that
787 ;; marker and use first column after the block start
788 ;; as indentation value.
789 (goto-char block-continuation-start
)
791 (python-rx block-start
(* space
))
792 (line-end-position) t
)
794 ;; Check if current line is an assignment continuation
795 ((let ((assignment-continuation-start
796 (python-info-assignment-continuation-line-p)))
797 (when assignment-continuation-start
798 ;; If assignment-continuation is set jump to that
799 ;; marker and use first column after the assignment
800 ;; operator as indentation value.
801 (goto-char assignment-continuation-start
)
805 (goto-char (python-info-beginning-of-backslash))
810 (or (python-info-beginning-of-backslash) (point)))
811 (python-info-line-ends-backslash-p)))
812 ;; The two previous lines ended in a backslash so we must
813 ;; respect previous line indentation.
814 (current-indentation)
815 ;; What happens here is that we are dealing with the second
816 ;; line of a backslash continuation, in that case we just going
817 ;; to add one indentation level.
818 (+ (current-indentation) python-indent-offset
)))))
819 ;; When inside a paren there's a need to handle nesting
823 ;; If current line closes the outermost open paren use the
824 ;; current indentation of the context-start line.
826 (skip-syntax-forward "\s" (line-end-position))
827 (when (and (looking-at (regexp-opt '(")" "]" "}")))
830 (not (python-syntax-context 'paren
))))
831 (goto-char context-start
)
832 (current-indentation))))
833 ;; If open paren is contained on a line by itself add another
834 ;; indentation level, else look for the first word after the
835 ;; opening paren and use it's column position as indentation
837 ((let* ((content-starts-in-newline)
840 (if (setq content-starts-in-newline
842 (goto-char context-start
)
846 (line-beginning-position)
848 (python-util-forward-comment))
850 (+ (current-indentation) python-indent-offset
)
854 ;; If current line closes a nested open paren de-indent one
857 (back-to-indentation)
858 (looking-at (regexp-opt '(")" "]" "}"))))
859 (- indent python-indent-offset
))
860 ;; If the line of the opening paren that wraps the current
861 ;; line starts a block add another level of indentation to
862 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
864 (when (and content-starts-in-newline
866 (goto-char context-start
)
867 (back-to-indentation)
868 (looking-at (python-rx block-start
))))
869 (+ indent python-indent-offset
))))
872 (defun python-indent-calculate-levels ()
873 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
874 (let* ((indentation (python-indent-calculate-indentation))
875 (remainder (% indentation python-indent-offset
))
876 (steps (/ (- indentation remainder
) python-indent-offset
)))
877 (setq python-indent-levels
(list 0))
878 (dotimes (step steps
)
879 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
880 (when (not (eq 0 remainder
))
881 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
882 (setq python-indent-levels
(nreverse python-indent-levels
))
883 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
885 (defun python-indent-toggle-levels ()
886 "Toggle `python-indent-current-level' over `python-indent-levels'."
887 (setq python-indent-current-level
(1- python-indent-current-level
))
888 (when (< python-indent-current-level
0)
889 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
891 (defun python-indent-line (&optional force-toggle
)
892 "Internal implementation of `python-indent-line-function'.
893 Uses the offset calculated in
894 `python-indent-calculate-indentation' and available levels
895 indicated by the variable `python-indent-levels' to set the
898 When the variable `last-command' is equal to
899 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
900 levels indicated in the variable `python-indent-levels' by
901 setting the current level in the variable
902 `python-indent-current-level'.
904 When the variable `last-command' is not equal to
905 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
906 possible indentation levels and saves it in the variable
907 `python-indent-levels'. Afterwards it sets the variable
908 `python-indent-current-level' correctly so offset is equal
909 to (`nth' `python-indent-current-level' `python-indent-levels')"
911 (and (or (and (eq this-command
'indent-for-tab-command
)
912 (eq last-command this-command
))
914 (not (equal python-indent-levels
'(0)))
915 (or (python-indent-toggle-levels) t
))
916 (python-indent-calculate-levels))
917 (let* ((starting-pos (point-marker))
918 (indent-ending-position
919 (+ (line-beginning-position) (current-indentation)))
920 (follow-indentation-p
922 (and (<= (line-beginning-position) starting-pos
)
923 (>= indent-ending-position starting-pos
))))
924 (next-indent (nth python-indent-current-level python-indent-levels
)))
925 (unless (= next-indent
(current-indentation))
927 (delete-horizontal-space)
928 (indent-to next-indent
)
929 (goto-char starting-pos
))
930 (and follow-indentation-p
(back-to-indentation)))
931 (python-info-closing-block-message))
933 (defun python-indent-line-function ()
934 "`indent-line-function' for Python mode.
935 See `python-indent-line' for details."
936 (python-indent-line))
938 (defun python-indent-dedent-line ()
939 "De-indent current line."
941 (when (and (not (python-syntax-comment-or-string-p))
942 (<= (point-marker) (save-excursion
943 (back-to-indentation)
945 (> (current-column) 0))
946 (python-indent-line t
)
949 (defun python-indent-dedent-line-backspace (arg)
950 "De-indent current line.
951 Argument ARG is passed to `backward-delete-char-untabify' when
952 point is not in between the indentation."
954 (when (not (python-indent-dedent-line))
955 (backward-delete-char-untabify arg
)))
956 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
958 (defun python-indent-region (start end
)
959 "Indent a python region automagically.
961 Called from a program, START and END specify the region to indent."
962 (let ((deactivate-mark nil
))
965 (setq end
(point-marker))
967 (or (bolp) (forward-line 1))
968 (while (< (point) end
)
969 (or (and (bolp) (eolp))
972 (back-to-indentation)
973 (setq word
(current-word))
976 ;; Don't mess with strings, unless it's the
977 ;; enclosing set of quotes.
978 (or (not (python-syntax-context 'string
))
982 (current-indentation)
983 (python-syntax-count-quotes (char-after) (point))))
984 (string-to-syntax "|"))))
986 (delete-horizontal-space)
987 (indent-to (python-indent-calculate-indentation)))))
989 (move-marker end nil
))))
991 (defun python-indent-shift-left (start end
&optional count
)
992 "Shift lines contained in region START END by COUNT columns to the left.
993 COUNT defaults to `python-indent-offset'. If region isn't
994 active, the current line is shifted. The shifted region includes
995 the lines in which START and END lie. An error is signaled if
996 any lines in the region are indented less than COUNT columns."
999 (list (region-beginning) (region-end) current-prefix-arg
)
1000 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1002 (setq count
(prefix-numeric-value count
))
1003 (setq count python-indent-offset
))
1005 (let ((deactivate-mark nil
))
1008 (while (< (point) end
)
1009 (if (and (< (current-indentation) count
)
1010 (not (looking-at "[ \t]*$")))
1011 (error "Can't shift all lines enough"))
1013 (indent-rigidly start end
(- count
))))))
1015 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1017 (defun python-indent-shift-right (start end
&optional count
)
1018 "Shift lines contained in region START END by COUNT columns to the left.
1019 COUNT defaults to `python-indent-offset'. If region isn't
1020 active, the current line is shifted. The shifted region includes
1021 the lines in which START and END lie."
1024 (list (region-beginning) (region-end) current-prefix-arg
)
1025 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1026 (let ((deactivate-mark nil
))
1028 (setq count
(prefix-numeric-value count
))
1029 (setq count python-indent-offset
))
1030 (indent-rigidly start end count
)))
1032 (defun python-indent-electric-colon (arg)
1033 "Insert a colon and maybe de-indent the current line.
1034 With numeric ARG, just insert that many colons. With
1035 \\[universal-argument], just insert a single colon."
1037 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1038 (when (and (not arg
)
1040 (not (equal ?
: (char-after (- (point-marker) 2))))
1041 (not (python-syntax-comment-or-string-p)))
1042 (let ((indentation (current-indentation))
1043 (calculated-indentation (python-indent-calculate-indentation)))
1044 (python-info-closing-block-message)
1045 (when (> indentation calculated-indentation
)
1047 (indent-line-to calculated-indentation
)
1048 (when (not (python-info-closing-block-message))
1049 (indent-line-to indentation
)))))))
1050 (put 'python-indent-electric-colon
'delete-selection t
)
1052 (defun python-indent-post-self-insert-function ()
1053 "Adjust closing paren line indentation after a char is added.
1054 This function is intended to be added to the
1055 `post-self-insert-hook.' If a line renders a paren alone, after
1056 adding a char before it, the line will be re-indented
1057 automatically if needed."
1058 (when (and (eq (char-before) last-command-event
)
1060 (memq (char-after) '(?\
) ?\
] ?\
})))
1062 (goto-char (line-beginning-position))
1063 ;; If after going to the beginning of line the point
1064 ;; is still inside a paren it's ok to do the trick
1065 (when (python-syntax-context 'paren
)
1066 (let ((indentation (python-indent-calculate-indentation)))
1067 (when (< (current-indentation) indentation
)
1068 (indent-line-to indentation
)))))))
1073 (defvar python-nav-beginning-of-defun-regexp
1074 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1075 "Regexp matching class or function definition.
1076 The name of the defun should be grouped so it can be retrieved
1077 via `match-string'.")
1079 (defun python-nav--beginning-of-defun (&optional arg
)
1080 "Internal implementation of `python-nav-beginning-of-defun'.
1081 With positive ARG search backwards, else search forwards."
1082 (when (or (null arg
) (= arg
0)) (setq arg
1))
1083 (let* ((re-search-fn (if (> arg
0)
1084 #'re-search-backward
1085 #'re-search-forward
))
1086 (line-beg-pos (line-beginning-position))
1087 (line-content-start (+ line-beg-pos
(current-indentation)))
1088 (pos (point-marker))
1093 (not (python-info-looking-at-beginning-of-defun))
1094 (python-nav-backward-block)))
1095 (or (and (python-info-looking-at-beginning-of-defun)
1096 (+ (current-indentation) python-indent-offset
))
1100 (when (and (< arg
0)
1101 (python-info-looking-at-beginning-of-defun))
1103 (while (and (funcall re-search-fn
1104 python-nav-beginning-of-defun-regexp nil t
)
1105 (or (python-syntax-context-type)
1106 ;; Handle nested defuns when moving
1107 ;; backwards by checking indentation.
1109 (not (= (current-indentation) 0))
1110 (>= (current-indentation) beg-indentation
)))))
1111 (and (python-info-looking-at-beginning-of-defun)
1112 (or (not (= (line-number-at-pos pos
)
1113 (line-number-at-pos)))
1114 (and (>= (point) line-beg-pos
)
1115 (<= (point) line-content-start
)
1116 (> pos line-content-start
)))))))
1118 (or (beginning-of-line 1) t
)
1119 (and (goto-char pos
) nil
))))
1121 (defun python-nav-beginning-of-defun (&optional arg
)
1122 "Move point to `beginning-of-defun'.
1123 With positive ARG search backwards else search forward. When ARG
1124 is nil or 0 defaults to 1. When searching backwards nested
1125 defuns are handled with care depending on current point
1126 position. Return non-nil if point is moved to
1127 `beginning-of-defun'."
1128 (when (or (null arg
) (= arg
0)) (setq arg
1))
1130 (cond ((and (eq this-command
'mark-defun
)
1131 (python-info-looking-at-beginning-of-defun)))
1133 (dotimes (i (if (> arg
0) arg
(- arg
)))
1134 (when (and (python-nav--beginning-of-defun arg)
1139 (defun python-nav-end-of-defun ()
1140 "Move point to the end of def or class.
1141 Returns nil if point is not in a def or class."
1143 (let ((beg-defun-indent)
1145 (when (or (python-info-looking-at-beginning-of-defun)
1146 (python-nav-beginning-of-defun 1)
1147 (python-nav-beginning-of-defun -1))
1148 (setq beg-defun-indent
(current-indentation))
1150 (python-nav-end-of-statement)
1151 (python-util-forward-comment 1)
1152 (and (> (current-indentation) beg-defun-indent
)
1154 (python-util-forward-comment -
1)
1156 ;; Ensure point moves forward.
1157 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1159 (defun python-nav-beginning-of-statement ()
1160 "Move to start of current statement."
1162 (while (and (or (back-to-indentation) t
)
1167 (python-info-line-ends-backslash-p))
1168 (python-syntax-context 'string
)
1169 (python-syntax-context 'paren
))
1170 (forward-line -
1))))
1173 (defun python-nav-end-of-statement ()
1174 "Move to end of current statement."
1176 (while (and (goto-char (line-end-position))
1179 (python-info-line-ends-backslash-p)
1180 (python-syntax-context 'string
)
1181 (python-syntax-context 'paren
))
1185 (defun python-nav-backward-statement (&optional arg
)
1186 "Move backward to previous statement.
1187 With ARG, repeat. See `python-nav-forward-statement'."
1189 (or arg
(setq arg
1))
1190 (python-nav-forward-statement (- arg
)))
1192 (defun python-nav-forward-statement (&optional arg
)
1193 "Move forward to next statement.
1194 With ARG, repeat. With negative argument, move ARG times
1195 backward to previous statement."
1197 (or arg
(setq arg
1))
1199 (python-nav-end-of-statement)
1200 (python-util-forward-comment)
1201 (python-nav-beginning-of-statement)
1202 (setq arg
(1- arg
)))
1204 (python-nav-beginning-of-statement)
1205 (python-util-forward-comment -
1)
1206 (python-nav-beginning-of-statement)
1207 (setq arg
(1+ arg
))))
1209 (defun python-nav-beginning-of-block ()
1210 "Move to start of current block."
1212 (let ((starting-pos (point))
1213 (block-regexp (python-rx
1214 line-start
(* whitespace
) block-start
)))
1216 (python-nav-beginning-of-statement)
1217 (looking-at (python-rx block-start
)))
1219 ;; Go to first line beginning a statement
1220 (while (and (not (bobp))
1221 (or (and (python-nav-beginning-of-statement) nil
)
1222 (python-info-current-line-comment-p)
1223 (python-info-current-line-empty-p)))
1225 (let ((block-matching-indent
1226 (- (current-indentation) python-indent-offset
)))
1228 (and (python-nav-backward-block)
1229 (> (current-indentation) block-matching-indent
)))
1230 (if (and (looking-at (python-rx block-start
))
1231 (= (current-indentation) block-matching-indent
))
1233 (and (goto-char starting-pos
) nil
))))))
1235 (defun python-nav-end-of-block ()
1236 "Move to end of current block."
1238 (when (python-nav-beginning-of-block)
1239 (let ((block-indentation (current-indentation)))
1240 (python-nav-end-of-statement)
1241 (while (and (forward-line 1)
1243 (or (and (> (current-indentation) block-indentation
)
1244 (or (python-nav-end-of-statement) t
))
1245 (python-info-current-line-comment-p)
1246 (python-info-current-line-empty-p))))
1247 (python-util-forward-comment -
1)
1250 (defun python-nav-backward-block (&optional arg
)
1251 "Move backward to previous block of code.
1252 With ARG, repeat. See `python-nav-forward-block'."
1254 (or arg
(setq arg
1))
1255 (python-nav-forward-block (- arg
)))
1257 (defun python-nav-forward-block (&optional arg
)
1258 "Move forward to next block of code.
1259 With ARG, repeat. With negative argument, move ARG times
1260 backward to previous block."
1262 (or arg
(setq arg
1))
1263 (let ((block-start-regexp
1264 (python-rx line-start
(* whitespace
) block-start
))
1265 (starting-pos (point)))
1267 (python-nav-end-of-statement)
1269 (re-search-forward block-start-regexp nil t
)
1270 (python-syntax-context-type)))
1271 (setq arg
(1- arg
)))
1273 (python-nav-beginning-of-statement)
1275 (re-search-backward block-start-regexp nil t
)
1276 (python-syntax-context-type)))
1277 (setq arg
(1+ arg
)))
1278 (python-nav-beginning-of-statement)
1279 (if (not (looking-at (python-rx block-start
)))
1280 (and (goto-char starting-pos
) nil
)
1281 (and (not (= (point) starting-pos
)) (point-marker)))))
1283 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1284 "Safe version of standard `forward-sexp'.
1285 When ARG > 0 move forward, else if ARG is < 0."
1286 (or arg
(setq arg
1))
1287 (let ((forward-sexp-function nil
)
1289 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1291 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1295 (while (and (funcall search-fn paren-regexp nil t
)
1296 (python-syntax-context 'paren
)))))))
1298 (defun python-nav--forward-sexp (&optional dir
)
1299 "Move to forward sexp.
1300 With positive Optional argument DIR direction move forward, else
1302 (setq dir
(or dir
1))
1304 (let* ((forward-p (if (> dir
0)
1305 (and (setq dir
1) t
)
1306 (and (setq dir -
1) nil
)))
1307 (re-search-fn (if forward-p
1309 're-search-backward
))
1310 (context-type (python-syntax-context-type)))
1312 ((eq context-type
'string
)
1313 ;; Inside of a string, get out of it.
1314 (while (and (funcall re-search-fn
"[\"']" nil t
)
1315 (python-syntax-context 'string
))))
1316 ((eq context-type
'comment
)
1317 ;; Inside of a comment, just move forward.
1318 (python-util-forward-comment dir
))
1319 ((or (eq context-type
'paren
)
1320 (and forward-p
(looking-at (python-rx open-paren
)))
1321 (and (not forward-p
)
1322 (eq (syntax-class (syntax-after (1- (point))))
1323 (car (string-to-syntax ")")))))
1324 ;; Inside a paren or looking at it, lisp knows what to do.
1325 (python-nav-lisp-forward-sexp-safe dir
))
1327 ;; This part handles the lispy feel of
1328 ;; `python-nav-forward-sexp'. Knowing everything about the
1329 ;; current context and the context of the next sexp tries to
1330 ;; follow the lisp sexp motion commands in a symmetric manner.
1333 ((python-info-beginning-of-block-p) 'block-start
)
1334 ((python-info-end-of-block-p) 'block-end
)
1335 ((python-info-beginning-of-statement-p) 'statement-start
)
1336 ((python-info-end-of-statement-p) 'statement-end
)))
1339 (python-nav-lisp-forward-sexp-safe dir
)
1343 (goto-char next-sexp-pos
)
1345 ((python-info-beginning-of-block-p) 'block-start
)
1346 ((python-info-end-of-block-p) 'block-end
)
1347 ((python-info-beginning-of-statement-p) 'statement-start
)
1348 ((python-info-end-of-statement-p) 'statement-end
)
1349 ((python-info-statement-starts-block-p) 'starts-block
)
1350 ((python-info-statement-ends-block-p) 'ends-block
)))))
1352 (cond ((and (not (eobp))
1353 (python-info-current-line-empty-p))
1354 (python-util-forward-comment dir
)
1355 (python-nav--forward-sexp dir
))
1356 ((eq context
'block-start
)
1357 (python-nav-end-of-block))
1358 ((eq context
'statement-start
)
1359 (python-nav-end-of-statement))
1360 ((and (memq context
'(statement-end block-end
))
1361 (eq next-sexp-context
'ends-block
))
1362 (goto-char next-sexp-pos
)
1363 (python-nav-end-of-block))
1364 ((and (memq context
'(statement-end block-end
))
1365 (eq next-sexp-context
'starts-block
))
1366 (goto-char next-sexp-pos
)
1367 (python-nav-end-of-block))
1368 ((memq context
'(statement-end block-end
))
1369 (goto-char next-sexp-pos
)
1370 (python-nav-end-of-statement))
1371 (t (goto-char next-sexp-pos
)))
1372 (cond ((and (not (bobp))
1373 (python-info-current-line-empty-p))
1374 (python-util-forward-comment dir
)
1375 (python-nav--forward-sexp dir
))
1376 ((eq context
'block-end
)
1377 (python-nav-beginning-of-block))
1378 ((eq context
'statement-end
)
1379 (python-nav-beginning-of-statement))
1380 ((and (memq context
'(statement-start block-start
))
1381 (eq next-sexp-context
'starts-block
))
1382 (goto-char next-sexp-pos
)
1383 (python-nav-beginning-of-block))
1384 ((and (memq context
'(statement-start block-start
))
1385 (eq next-sexp-context
'ends-block
))
1386 (goto-char next-sexp-pos
)
1387 (python-nav-beginning-of-block))
1388 ((memq context
'(statement-start block-start
))
1389 (goto-char next-sexp-pos
)
1390 (python-nav-beginning-of-statement))
1391 (t (goto-char next-sexp-pos
))))))))))
1393 (defun python-nav--backward-sexp ()
1394 "Move to backward sexp."
1395 (python-nav--forward-sexp -
1))
1397 (defun python-nav-forward-sexp (&optional arg
)
1398 "Move forward across one block of code.
1399 With ARG, do it that many times. Negative arg -N means
1400 move backward N times."
1402 (or arg
(setq arg
1))
1404 (python-nav--forward-sexp)
1405 (setq arg
(1- arg
)))
1407 (python-nav--backward-sexp)
1408 (setq arg
(1+ arg
))))
1410 (defun python-nav--up-list (&optional dir
)
1411 "Internal implementation of `python-nav-up-list'.
1412 DIR is always 1 or -1 and comes sanitized from
1413 `python-nav-up-list' calls."
1414 (let ((context (python-syntax-context-type))
1415 (forward-p (> dir
0)))
1417 ((memq context
'(string comment
)))
1418 ((eq context
'paren
)
1419 (let ((forward-sexp-function))
1421 ((and forward-p
(python-info-end-of-block-p))
1422 (let ((parent-end-pos
1424 (let ((indentation (and
1425 (python-nav-beginning-of-block)
1426 (current-indentation))))
1427 (while (and indentation
1429 (>= (current-indentation) indentation
)
1430 (python-nav-backward-block)))
1431 (python-nav-end-of-block)))))
1432 (and (> (or parent-end-pos
(point)) (point))
1433 (goto-char parent-end-pos
))))
1434 (forward-p (python-nav-end-of-block))
1435 ((and (not forward-p
)
1436 (> (current-indentation) 0)
1437 (python-info-beginning-of-block-p))
1438 (let ((prev-block-pos
1440 (let ((indentation (current-indentation)))
1441 (while (and (python-nav-backward-block)
1442 (>= (current-indentation) indentation
))))
1444 (and (> (point) prev-block-pos
)
1445 (goto-char prev-block-pos
))))
1446 ((not forward-p
) (python-nav-beginning-of-block)))))
1448 (defun python-nav-up-list (&optional arg
)
1449 "Move forward out of one level of parentheses (or blocks).
1450 With ARG, do this that many times.
1451 A negative argument means move backward but still to a less deep spot.
1452 This command assumes point is not in a string or comment."
1454 (or arg
(setq arg
1))
1456 (python-nav--up-list 1)
1457 (setq arg
(1- arg
)))
1459 (python-nav--up-list -
1)
1460 (setq arg
(1+ arg
))))
1462 (defun python-nav-backward-up-list (&optional arg
)
1463 "Move backward out of one level of parentheses (or blocks).
1464 With ARG, do this that many times.
1465 A negative argument means move backward but still to a less deep spot.
1466 This command assumes point is not in a string or comment."
1468 (or arg
(setq arg
1))
1469 (python-nav-up-list (- arg
)))
1472 ;;; Shell integration
1474 (defcustom python-shell-buffer-name
"Python"
1475 "Default buffer name for Python interpreter."
1480 (defcustom python-shell-interpreter
"python"
1481 "Default Python interpreter for shell."
1485 (defcustom python-shell-internal-buffer-name
"Python Internal"
1486 "Default buffer name for the Internal Python interpreter."
1491 (defcustom python-shell-interpreter-args
"-i"
1492 "Default arguments for the Python interpreter."
1496 (defcustom python-shell-prompt-regexp
">>> "
1497 "Regular Expression matching top\-level input prompt of python shell.
1498 It should not contain a caret (^) at the beginning."
1503 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1504 "Regular Expression matching block input prompt of python shell.
1505 It should not contain a caret (^) at the beginning."
1510 (defcustom python-shell-prompt-output-regexp
""
1511 "Regular Expression matching output prompt of python shell.
1512 It should not contain a caret (^) at the beginning."
1517 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1518 "Regular Expression matching pdb input prompt of python shell.
1519 It should not contain a caret (^) at the beginning."
1524 (defcustom python-shell-enable-font-lock t
1525 "Should syntax highlighting be enabled in the python shell buffer?
1526 Restart the python shell after changing this variable for it to take effect."
1531 (defcustom python-shell-process-environment nil
1532 "List of environment variables for Python shell.
1533 This variable follows the same rules as `process-environment'
1534 since it merges with it before the process creation routines are
1535 called. When this variable is nil, the Python shell is run with
1536 the default `process-environment'."
1537 :type
'(repeat string
)
1541 (defcustom python-shell-extra-pythonpaths nil
1542 "List of extra pythonpaths for Python shell.
1543 The values of this variable are added to the existing value of
1544 PYTHONPATH in the `process-environment' variable."
1545 :type
'(repeat string
)
1549 (defcustom python-shell-exec-path nil
1550 "List of path to search for binaries.
1551 This variable follows the same rules as `exec-path' since it
1552 merges with it before the process creation routines are called.
1553 When this variable is nil, the Python shell is run with the
1554 default `exec-path'."
1555 :type
'(repeat string
)
1559 (defcustom python-shell-virtualenv-path nil
1560 "Path to virtualenv root.
1561 This variable, when set to a string, makes the values stored in
1562 `python-shell-process-environment' and `python-shell-exec-path'
1563 to be modified properly so shells are started with the specified
1569 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1570 python-ffap-setup-code
1571 python-eldoc-setup-code
)
1572 "List of code run by `python-shell-send-setup-codes'."
1573 :type
'(repeat symbol
)
1577 (defcustom python-shell-compilation-regexp-alist
1578 `((,(rx line-start
(1+ (any " \t")) "File \""
1579 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1580 "\", line " (group (1+ digit
)))
1582 (,(rx " in file " (group (1+ not-newline
)) " on line "
1585 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1586 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1588 "`compilation-error-regexp-alist' for inferior Python."
1589 :type
'(alist string
)
1592 (defun python-shell-get-process-name (dedicated)
1593 "Calculate the appropriate process name for inferior Python process.
1594 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1595 returns a string with the form
1596 `python-shell-buffer-name'[variable `buffer-file-name'] else
1597 returns the value of `python-shell-buffer-name'."
1601 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1602 (format "%s" python-shell-buffer-name
))))
1605 (defun python-shell-internal-get-process-name ()
1606 "Calculate the appropriate process name for Internal Python process.
1607 The name is calculated from `python-shell-global-buffer-name' and
1608 a hash of all relevant global shell settings in order to ensure
1609 uniqueness for different types of configurations."
1611 python-shell-internal-buffer-name
1614 (python-shell-parse-command)
1615 python-shell-prompt-regexp
1616 python-shell-prompt-block-regexp
1617 python-shell-prompt-output-regexp
1618 (mapconcat #'symbol-value python-shell-setup-codes
"")
1619 (mapconcat #'identity python-shell-process-environment
"")
1620 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1621 (mapconcat #'identity python-shell-exec-path
"")
1622 (or python-shell-virtualenv-path
"")
1623 (mapconcat #'identity python-shell-exec-path
"")))))
1625 (defun python-shell-parse-command ()
1626 "Calculate the string used to execute the inferior Python process."
1627 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1629 (defun python-shell-calculate-process-environment ()
1630 "Calculate process environment given `python-shell-virtualenv-path'."
1631 (let ((process-environment (append
1632 python-shell-process-environment
1633 process-environment nil
))
1634 (virtualenv (if python-shell-virtualenv-path
1635 (directory-file-name python-shell-virtualenv-path
)
1637 (when python-shell-extra-pythonpaths
1638 (setenv "PYTHONPATH"
1640 (mapconcat 'identity
1641 python-shell-extra-pythonpaths
1644 (or (getenv "PYTHONPATH") ""))))
1645 (if (not virtualenv
)
1647 (setenv "PYTHONHOME" nil
)
1648 (setenv "PATH" (format "%s/bin%s%s"
1649 virtualenv path-separator
1650 (or (getenv "PATH") "")))
1651 (setenv "VIRTUAL_ENV" virtualenv
))
1652 process-environment
))
1654 (defun python-shell-calculate-exec-path ()
1655 "Calculate exec path given `python-shell-virtualenv-path'."
1656 (let ((path (append python-shell-exec-path
1658 (if (not python-shell-virtualenv-path
)
1660 (cons (format "%s/bin"
1661 (directory-file-name python-shell-virtualenv-path
))
1664 (defun python-comint-output-filter-function (output)
1665 "Hook run after content is put into comint buffer.
1666 OUTPUT is a string with the contents of the buffer."
1667 (ansi-color-filter-apply output
))
1669 (defvar python-shell--parent-buffer nil
)
1671 (defvar python-shell-output-syntax-table
1672 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1673 (modify-syntax-entry ?
\' "." table
)
1674 (modify-syntax-entry ?
\" "." table
)
1675 (modify-syntax-entry ?\
( "." table
)
1676 (modify-syntax-entry ?\
[ "." table
)
1677 (modify-syntax-entry ?\
{ "." table
)
1678 (modify-syntax-entry ?\
) "." table
)
1679 (modify-syntax-entry ?\
] "." table
)
1680 (modify-syntax-entry ?\
} "." table
)
1682 "Syntax table for shell output.
1683 It makes parens and quotes be treated as punctuation chars.")
1685 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1686 "Major mode for Python inferior process.
1687 Runs a Python interpreter as a subprocess of Emacs, with Python
1688 I/O through an Emacs buffer. Variables
1689 `python-shell-interpreter' and `python-shell-interpreter-args'
1690 controls which Python interpreter is run. Variables
1691 `python-shell-prompt-regexp',
1692 `python-shell-prompt-output-regexp',
1693 `python-shell-prompt-block-regexp',
1694 `python-shell-enable-font-lock',
1695 `python-shell-completion-setup-code',
1696 `python-shell-completion-string-code',
1697 `python-shell-completion-module-string-code',
1698 `python-eldoc-setup-code', `python-eldoc-string-code',
1699 `python-ffap-setup-code' and `python-ffap-string-code' can
1700 customize this mode for different Python interpreters.
1702 You can also add additional setup code to be run at
1703 initialization of the interpreter via `python-shell-setup-codes'
1706 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1707 (and python-shell--parent-buffer
1708 (python-util-clone-local-variables python-shell--parent-buffer
))
1709 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1710 python-shell-prompt-regexp
1711 python-shell-prompt-block-regexp
1712 python-shell-prompt-pdb-regexp
))
1713 (setq mode-line-process
'(":%s"))
1714 (make-local-variable 'comint-output-filter-functions
)
1715 (add-hook 'comint-output-filter-functions
1716 'python-comint-output-filter-function
)
1717 (add-hook 'comint-output-filter-functions
1718 'python-pdbtrack-comint-output-filter-function
)
1719 (set (make-local-variable 'compilation-error-regexp-alist
)
1720 python-shell-compilation-regexp-alist
)
1721 (define-key inferior-python-mode-map
[remap complete-symbol
]
1722 'completion-at-point
)
1723 (add-hook 'completion-at-point-functions
1724 'python-shell-completion-complete-at-point nil
'local
)
1725 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1726 'python-shell-completion-complete-at-point
)
1727 (define-key inferior-python-mode-map
"\t"
1728 'python-shell-completion-complete-or-indent
)
1729 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1730 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1731 (make-local-variable 'python-shell-internal-last-output
)
1732 (when python-shell-enable-font-lock
1733 (set-syntax-table python-mode-syntax-table
)
1734 (set (make-local-variable 'font-lock-defaults
)
1735 '(python-font-lock-keywords nil nil nil nil
))
1736 (set (make-local-variable 'syntax-propertize-function
)
1738 ;; XXX: Unfortunately eval is needed here to make use of the
1739 ;; dynamic value of `comint-prompt-regexp'.
1740 `(syntax-propertize-rules
1741 (,comint-prompt-regexp
1744 comint-last-input-start end
'syntax-table
1745 python-shell-output-syntax-table
)
1746 ;; XXX: This might look weird, but it is the easiest
1747 ;; way to ensure font lock gets cleaned up before the
1748 ;; current prompt, which is needed for unclosed
1749 ;; strings to not mess up with current input.
1750 (font-lock-unfontify-region comint-last-input-start end
))))
1751 (,(python-rx string-delimiter
)
1753 (and (not (eq (get-text-property start
'field
) 'output
))
1754 (python-syntax-stringify)))))))))
1755 (compilation-shell-minor-mode 1))
1757 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1758 "Create a python shell comint buffer.
1759 CMD is the python command to be executed and PROC-NAME is the
1760 process name the comint buffer will get. After the comint buffer
1761 is created the `inferior-python-mode' is activated. When
1762 optional argument POP is non-nil the buffer is shown. When
1763 optional argument INTERNAL is non-nil this process is run on a
1764 buffer with a name that starts with a space, following the Emacs
1765 convention for temporary/internal buffers, and also makes sure
1766 the user is not queried for confirmation when the process is
1769 (let* ((proc-buffer-name
1770 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1771 (process-environment (python-shell-calculate-process-environment))
1772 (exec-path (python-shell-calculate-exec-path)))
1773 (when (not (comint-check-proc proc-buffer-name
))
1774 (let* ((cmdlist (split-string-and-unquote cmd
))
1775 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1776 (car cmdlist
) nil
(cdr cmdlist
)))
1777 (python-shell--parent-buffer (current-buffer))
1778 (process (get-buffer-process buffer
)))
1779 (with-current-buffer buffer
1780 (inferior-python-mode))
1781 (accept-process-output process
)
1782 (and pop
(pop-to-buffer buffer t
))
1783 (and internal
(set-process-query-on-exit-flag process nil
))))
1787 (defun run-python (cmd &optional dedicated show
)
1788 "Run an inferior Python process.
1789 Input and output via buffer named after
1790 `python-shell-buffer-name'. If there is a process already
1791 running in that buffer, just switch to it.
1793 With argument, allows you to define CMD so you can edit the
1794 command used to call the interpreter and define DEDICATED, so a
1795 dedicated process for the current buffer is open. When numeric
1796 prefix arg is other than 0 or 4 do not SHOW.
1798 Runs the hook `inferior-python-mode-hook' (after the
1799 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1800 process buffer for a list of commands.)"
1802 (if current-prefix-arg
1804 (read-string "Run Python: " (python-shell-parse-command))
1805 (y-or-n-p "Make dedicated process? ")
1806 (= (prefix-numeric-value current-prefix-arg
) 4))
1807 (list (python-shell-parse-command) nil t
)))
1808 (python-shell-make-comint
1809 cmd
(python-shell-get-process-name dedicated
) show
)
1812 (defun run-python-internal ()
1813 "Run an inferior Internal Python process.
1814 Input and output via buffer named after
1815 `python-shell-internal-buffer-name' and what
1816 `python-shell-internal-get-process-name' returns.
1818 This new kind of shell is intended to be used for generic
1819 communication related to defined configurations, the main
1820 difference with global or dedicated shells is that these ones are
1821 attached to a configuration, not a buffer. This means that can
1822 be used for example to retrieve the sys.path and other stuff,
1823 without messing with user shells. Note that
1824 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1825 are set to nil for these shells, so setup codes are not sent at
1827 (let ((python-shell-enable-font-lock nil
)
1828 (inferior-python-mode-hook nil
))
1830 (python-shell-make-comint
1831 (python-shell-parse-command)
1832 (python-shell-internal-get-process-name) nil t
))))
1834 (defun python-shell-get-process ()
1835 "Get inferior Python process for current buffer and return it."
1836 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1837 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1838 (global-proc-name (python-shell-get-process-name nil
))
1839 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1840 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1841 (global-running (comint-check-proc global-proc-buffer-name
)))
1842 ;; Always prefer dedicated
1843 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1844 (and global-running global-proc-buffer-name
)))))
1846 (defun python-shell-get-or-create-process ()
1847 "Get or create an inferior Python process for current buffer and return it."
1848 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1849 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1850 (global-proc-name (python-shell-get-process-name nil
))
1851 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1852 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1853 (global-running (comint-check-proc global-proc-buffer-name
))
1854 (current-prefix-arg 16))
1855 (when (and (not dedicated-running
) (not global-running
))
1856 (if (call-interactively 'run-python
)
1857 (setq dedicated-running t
)
1858 (setq global-running t
)))
1859 ;; Always prefer dedicated
1860 (get-buffer-process (if dedicated-running
1861 dedicated-proc-buffer-name
1862 global-proc-buffer-name
))))
1864 (defvar python-shell-internal-buffer nil
1865 "Current internal shell buffer for the current buffer.
1866 This is really not necessary at all for the code to work but it's
1867 there for compatibility with CEDET.")
1869 (defvar python-shell-internal-last-output nil
1870 "Last output captured by the internal shell.
1871 This is really not necessary at all for the code to work but it's
1872 there for compatibility with CEDET.")
1874 (defun python-shell-internal-get-or-create-process ()
1875 "Get or create an inferior Internal Python process."
1876 (let* ((proc-name (python-shell-internal-get-process-name))
1877 (proc-buffer-name (format " *%s*" proc-name
)))
1878 (when (not (process-live-p proc-name
))
1879 (run-python-internal)
1880 (setq python-shell-internal-buffer proc-buffer-name
)
1881 ;; XXX: Why is this `sit-for' needed?
1882 ;; `python-shell-make-comint' calls `accept-process-output'
1883 ;; already but it is not helping to get proper output on
1884 ;; 'gnu/linux when the internal shell process is not running and
1885 ;; a call to `python-shell-internal-send-string' is issued.
1887 (get-buffer-process proc-buffer-name
)))
1889 (define-obsolete-function-alias
1890 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1892 (define-obsolete-variable-alias
1893 'python-buffer
'python-shell-internal-buffer
"24.3")
1895 (define-obsolete-variable-alias
1896 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1898 (defun python-shell-send-string (string &optional process msg
)
1899 "Send STRING to inferior Python PROCESS.
1900 When MSG is non-nil messages the first line of STRING."
1901 (interactive "sPython command: ")
1902 (let ((process (or process
(python-shell-get-or-create-process)))
1903 (lines (split-string string
"\n" t
)))
1904 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1905 (if (> (length lines
) 1)
1906 (let* ((temporary-file-directory
1907 (if (file-remote-p default-directory
)
1908 (concat (file-remote-p default-directory
) "/tmp")
1909 temporary-file-directory
))
1910 (temp-file-name (make-temp-file "py"))
1911 (file-name (or (buffer-file-name) temp-file-name
)))
1912 (with-temp-file temp-file-name
1914 (delete-trailing-whitespace))
1915 (python-shell-send-file file-name process temp-file-name
))
1916 (comint-send-string process string
)
1917 (when (or (not (string-match "\n$" string
))
1918 (string-match "\n[ \t].*\n?$" string
))
1919 (comint-send-string process
"\n")))))
1921 (defvar python-shell-output-filter-in-progress nil
)
1922 (defvar python-shell-output-filter-buffer nil
)
1924 (defun python-shell-output-filter (string)
1925 "Filter used in `python-shell-send-string-no-output' to grab output.
1926 STRING is the output received to this point from the process.
1927 This filter saves received output from the process in
1928 `python-shell-output-filter-buffer' and stops receiving it after
1929 detecting a prompt at the end of the buffer."
1931 string
(ansi-color-filter-apply string
)
1932 python-shell-output-filter-buffer
1933 (concat python-shell-output-filter-buffer string
))
1935 ;; XXX: It seems on OSX an extra carriage return is attached
1936 ;; at the end of output, this handles that too.
1937 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1938 python-shell-prompt-regexp
1939 python-shell-prompt-block-regexp
1940 python-shell-prompt-pdb-regexp
)
1941 python-shell-output-filter-buffer
)
1942 ;; Output ends when `python-shell-output-filter-buffer' contains
1943 ;; the prompt attached at the end of it.
1944 (setq python-shell-output-filter-in-progress nil
1945 python-shell-output-filter-buffer
1946 (substring python-shell-output-filter-buffer
1947 0 (match-beginning 0)))
1948 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1949 (string-match (concat "^" python-shell-prompt-output-regexp
)
1950 python-shell-output-filter-buffer
))
1951 ;; Some shells, like iPython might append a prompt before the
1952 ;; output, clean that.
1953 (setq python-shell-output-filter-buffer
1954 (substring python-shell-output-filter-buffer
(match-end 0)))))
1957 (defun python-shell-send-string-no-output (string &optional process msg
)
1958 "Send STRING to PROCESS and inhibit output.
1959 When MSG is non-nil messages the first line of STRING. Return
1961 (let ((process (or process
(python-shell-get-or-create-process)))
1962 (comint-preoutput-filter-functions
1963 '(python-shell-output-filter))
1964 (python-shell-output-filter-in-progress t
)
1968 (python-shell-send-string string process msg
)
1969 (while python-shell-output-filter-in-progress
1970 ;; `python-shell-output-filter' takes care of setting
1971 ;; `python-shell-output-filter-in-progress' to NIL after it
1972 ;; detects end of output.
1973 (accept-process-output process
))
1975 python-shell-output-filter-buffer
1976 (setq python-shell-output-filter-buffer nil
)))
1977 (with-current-buffer (process-buffer process
)
1978 (comint-interrupt-subjob)))))
1980 (defun python-shell-internal-send-string (string)
1981 "Send STRING to the Internal Python interpreter.
1982 Returns the output. See `python-shell-send-string-no-output'."
1983 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1984 ;; updated to support this new mode.
1985 (setq python-shell-internal-last-output
1986 (python-shell-send-string-no-output
1987 ;; Makes this function compatible with the old
1988 ;; python-send-receive. (At least for CEDET).
1989 (replace-regexp-in-string "_emacs_out +" "" string
)
1990 (python-shell-internal-get-or-create-process) nil
)))
1992 (define-obsolete-function-alias
1993 'python-send-receive
'python-shell-internal-send-string
"24.3")
1995 (define-obsolete-function-alias
1996 'python-send-string
'python-shell-internal-send-string
"24.3")
1998 (defun python-shell-send-region (start end
)
1999 "Send the region delimited by START and END to inferior Python process."
2001 (python-shell-send-string (buffer-substring start end
) nil t
))
2003 (defun python-shell-send-buffer (&optional arg
)
2004 "Send the entire buffer to inferior Python process.
2005 With prefix ARG allow execution of code inside blocks delimited
2006 by \"if __name__== '__main__':\""
2010 (let ((str (buffer-substring (point-min) (point-max))))
2013 (setq str
(replace-regexp-in-string
2014 (python-rx if-name-main
)
2015 "if __name__ == '__main__ ':" str
)))
2016 (python-shell-send-string str
))))
2018 (defun python-shell-send-defun (arg)
2019 "Send the current defun to inferior Python process.
2020 When argument ARG is non-nil do not include decorators."
2023 (python-shell-send-region
2026 (while (and (or (python-nav-beginning-of-defun)
2027 (beginning-of-line 1))
2028 (> (current-indentation) 0)))
2030 (while (and (forward-line -
1)
2031 (looking-at (python-rx decorator
))))
2035 (or (python-nav-end-of-defun)
2039 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2040 "Send FILE-NAME to inferior Python PROCESS.
2041 If TEMP-FILE-NAME is passed then that file is used for processing
2042 instead, while internally the shell will continue to use
2044 (interactive "fFile to send: ")
2045 (let* ((process (or process
(python-shell-get-or-create-process)))
2046 (temp-file-name (when temp-file-name
2048 (or (file-remote-p temp-file-name
'localname
)
2050 (file-name (or (when file-name
2052 (or (file-remote-p file-name
'localname
)
2055 (when (not file-name
)
2056 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2057 (python-shell-send-string
2059 (concat "__pyfile = open('''%s''');"
2060 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2062 (or temp-file-name file-name
) file-name
)
2065 (defun python-shell-switch-to-shell ()
2066 "Switch to inferior Python process buffer."
2068 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2070 (defun python-shell-send-setup-code ()
2071 "Send all setup code for shell.
2072 This function takes the list of setup code to send from the
2073 `python-shell-setup-codes' list."
2074 (let ((process (get-buffer-process (current-buffer))))
2075 (dolist (code python-shell-setup-codes
)
2077 (message "Sent %s" code
)
2078 (python-shell-send-string
2079 (symbol-value code
) process
)))))
2081 (add-hook 'inferior-python-mode-hook
2082 #'python-shell-send-setup-code
)
2085 ;;; Shell completion
2087 (defcustom python-shell-completion-setup-code
2091 def __COMPLETER_all_completions(text): []
2094 readline.set_completer(rlcompleter.Completer().complete)
2095 def __COMPLETER_all_completions(text):
2101 res = readline.get_completer()(text, i)
2104 completions.append(res)
2108 "Code used to setup completion in inferior Python processes."
2112 (defcustom python-shell-completion-string-code
2113 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2114 "Python code used to get a string of completions separated by semicolons."
2118 (defcustom python-shell-completion-module-string-code
""
2119 "Python code used to get completions separated by semicolons for imports.
2121 For IPython v0.11, add the following line to
2122 `python-shell-completion-setup-code':
2124 from IPython.core.completerlib import module_completion
2126 and use the following as the value of this variable:
2128 ';'.join(module_completion('''%s'''))\n"
2132 (defcustom python-shell-completion-pdb-string-code
2133 "';'.join(globals().keys() + locals().keys())"
2134 "Python code used to get completions separated by semicolons for [i]pdb."
2138 (defun python-shell-completion-get-completions (process line input
)
2139 "Do completion at point for PROCESS.
2140 LINE is used to detect the context on how to complete given
2143 ;; Get the last prompt for the inferior process
2144 ;; buffer. This is used for the completion code selection
2146 (with-current-buffer (process-buffer process
)
2147 (buffer-substring-no-properties
2148 (overlay-start comint-last-prompt-overlay
)
2149 (overlay-end comint-last-prompt-overlay
))))
2151 ;; Check whether a prompt matches a pdb string, an import
2152 ;; statement or just the standard prompt and use the
2153 ;; correct python-shell-completion-*-code string
2154 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2156 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2159 (length python-shell-completion-module-string-code
) 0)
2161 (concat "^" python-shell-prompt-regexp
) prompt
)
2162 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2165 (concat "^" python-shell-prompt-regexp
) prompt
)
2169 (case completion-context
2170 (pdb python-shell-completion-pdb-string-code
)
2171 (import python-shell-completion-module-string-code
)
2172 (default python-shell-completion-string-code
)
2175 (if (eq completion-context
'import
)
2176 (replace-regexp-in-string "^[ \t]+" "" line
)
2178 (and completion-code
2179 (> (length input
) 0)
2180 (with-current-buffer (process-buffer process
)
2181 (let ((completions (python-shell-send-string-no-output
2182 (format completion-code input
) process
)))
2183 (and (> (length completions
) 2)
2184 (split-string completions
2185 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2187 (defun python-shell-completion-complete-at-point (&optional process
)
2188 "Perform completion at point in inferior Python.
2189 Optional argument PROCESS forces completions to be retrieved
2190 using that one instead of current buffer's process."
2191 (setq process
(or process
(get-buffer-process (current-buffer))))
2194 (with-syntax-table python-dotty-syntax-table
2195 (let* ((paren-depth (car (syntax-ppss)))
2196 (syntax-string "w_")
2197 (syntax-list (string-to-syntax syntax-string
)))
2198 ;; Stop scanning for the beginning of the completion
2199 ;; subject after the char before point matches a
2202 (car (syntax-after (1- (point)))) syntax-list
)
2203 (skip-syntax-backward syntax-string
)
2204 (when (or (equal (char-before) ?\
))
2205 (equal (char-before) ?
\"))
2208 ;; honor initial paren depth
2209 (> (car (syntax-ppss)) paren-depth
)
2210 (python-syntax-context 'string
))
2215 (completion-table-dynamic
2217 #'python-shell-completion-get-completions
2218 process
(buffer-substring-no-properties
2219 (line-beginning-position) end
))))))
2221 (defun python-shell-completion-complete-or-indent ()
2222 "Complete or indent depending on the context.
2223 If content before pointer is all whitespace indent. If not try
2226 (if (string-match "^[[:space:]]*$"
2227 (buffer-substring (comint-line-beginning-position)
2229 (indent-for-tab-command)
2230 (completion-at-point)))
2233 ;;; PDB Track integration
2235 (defcustom python-pdbtrack-activate t
2236 "Non-nil makes python shell enable pdbtracking."
2241 (defcustom python-pdbtrack-stacktrace-info-regexp
2242 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2243 "Regular Expression matching stacktrace information.
2244 Used to extract the current line and module being inspected."
2249 (defvar python-pdbtrack-tracked-buffer nil
2250 "Variable containing the value of the current tracked buffer.
2251 Never set this variable directly, use
2252 `python-pdbtrack-set-tracked-buffer' instead.")
2254 (defvar python-pdbtrack-buffers-to-kill nil
2255 "List of buffers to be deleted after tracking finishes.")
2257 (defun python-pdbtrack-set-tracked-buffer (file-name)
2258 "Set the buffer for FILE-NAME as the tracked buffer.
2259 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2260 Returns the tracked buffer."
2261 (let ((file-buffer (get-file-buffer file-name
)))
2263 (setq python-pdbtrack-tracked-buffer file-buffer
)
2264 (setq file-buffer
(find-file-noselect file-name
))
2265 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2266 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2269 (defun python-pdbtrack-comint-output-filter-function (output)
2270 "Move overlay arrow to current pdb line in tracked buffer.
2271 Argument OUTPUT is a string with the output from the comint process."
2272 (when (and python-pdbtrack-activate
(not (string= output
"")))
2273 (let* ((full-output (ansi-color-filter-apply
2274 (buffer-substring comint-last-input-end
(point-max))))
2278 (insert full-output
)
2279 (goto-char (point-min))
2280 ;; OK, this sucked but now it became a cool hack. The
2281 ;; stacktrace information normally is on the first line
2282 ;; but in some cases (like when doing a step-in) it is
2284 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2287 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2288 (setq line-number
(string-to-number
2289 (match-string-no-properties 2)))
2290 (match-string-no-properties 1)))))
2291 (if (and file-name line-number
)
2292 (let* ((tracked-buffer
2293 (python-pdbtrack-set-tracked-buffer file-name
))
2294 (shell-buffer (current-buffer))
2295 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2296 (tracked-buffer-line-pos))
2297 (with-current-buffer tracked-buffer
2298 (set (make-local-variable 'overlay-arrow-string
) "=>")
2299 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2300 (setq tracked-buffer-line-pos
(progn
2301 (goto-char (point-min))
2302 (forward-line (1- line-number
))
2304 (when tracked-buffer-window
2306 tracked-buffer-window tracked-buffer-line-pos
))
2307 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2308 (pop-to-buffer tracked-buffer
)
2309 (switch-to-buffer-other-window shell-buffer
))
2310 (when python-pdbtrack-tracked-buffer
2311 (with-current-buffer python-pdbtrack-tracked-buffer
2312 (set-marker overlay-arrow-position nil
))
2313 (mapc #'(lambda (buffer)
2314 (ignore-errors (kill-buffer buffer
)))
2315 python-pdbtrack-buffers-to-kill
)
2316 (setq python-pdbtrack-tracked-buffer nil
2317 python-pdbtrack-buffers-to-kill nil
)))))
2321 ;;; Symbol completion
2323 (defun python-completion-complete-at-point ()
2324 "Complete current symbol at point.
2325 For this to work the best as possible you should call
2326 `python-shell-send-buffer' from time to time so context in
2327 inferior python process is updated properly."
2328 (let ((process (python-shell-get-process)))
2330 (error "Completion needs an inferior Python process running")
2331 (python-shell-completion-complete-at-point process
))))
2333 (add-to-list 'debug-ignored-errors
2334 "^Completion needs an inferior Python process running.")
2339 (defcustom python-fill-comment-function
'python-fill-comment
2340 "Function to fill comments.
2341 This is the function used by `python-fill-paragraph' to
2346 (defcustom python-fill-string-function
'python-fill-string
2347 "Function to fill strings.
2348 This is the function used by `python-fill-paragraph' to
2353 (defcustom python-fill-decorator-function
'python-fill-decorator
2354 "Function to fill decorators.
2355 This is the function used by `python-fill-paragraph' to
2360 (defcustom python-fill-paren-function
'python-fill-paren
2361 "Function to fill parens.
2362 This is the function used by `python-fill-paragraph' to
2367 (defcustom python-fill-docstring-style
'pep-257
2368 "Style used to fill docstrings.
2369 This affects `python-fill-string' behavior with regards to
2370 triple quotes positioning.
2372 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2373 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2374 position and will treat docstrings a normal string, any other
2375 value may result in one of the following docstring styles:
2380 Process foo, return bar.
2384 Process foo, return bar.
2386 If processing fails throw ProcessingError.
2391 \"\"\"Process foo, return bar.\"\"\"
2394 Process foo, return bar.
2396 If processing fails throw ProcessingError.
2402 \"\"\"Process foo, return bar.\"\"\"
2404 \"\"\"Process foo, return bar.
2406 If processing fails throw ProcessingError.
2412 \"\"\"Process foo, return bar.\"\"\"
2414 \"\"\"Process foo, return bar.
2416 If processing fails throw ProcessingError.
2421 \"\"\"Process foo, return bar.\"\"\"
2424 Process foo, return bar.
2426 If processing fails throw ProcessingError.
2429 (const :tag
"Don't format docstrings" nil
)
2430 (const :tag
"Django's coding standards style." django
)
2431 (const :tag
"One newline and start and Two at end style." onetwo
)
2432 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2433 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2434 (const :tag
"Symmetric style." symmetric
))
2437 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2439 (defun python-fill-paragraph (&optional justify
)
2440 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2441 If any of the current line is in or at the end of a multi-line string,
2442 fill the string or the paragraph of it that point is in, preserving
2443 the string's indentation.
2444 Optional argument JUSTIFY defines if the paragraph should be justified."
2449 ((python-syntax-context 'comment
)
2450 (funcall python-fill-comment-function justify
))
2451 ;; Strings/Docstrings
2452 ((save-excursion (or (python-syntax-context 'string
)
2453 (equal (string-to-syntax "|")
2454 (syntax-after (point)))))
2455 (funcall python-fill-string-function justify
))
2457 ((equal (char-after (save-excursion
2458 (python-nav-beginning-of-statement))) ?
@)
2459 (funcall python-fill-decorator-function justify
))
2461 ((or (python-syntax-context 'paren
)
2462 (looking-at (python-rx open-paren
))
2464 (skip-syntax-forward "^(" (line-end-position))
2465 (looking-at (python-rx open-paren
))))
2466 (funcall python-fill-paren-function justify
))
2469 (defun python-fill-comment (&optional justify
)
2470 "Comment fill function for `python-fill-paragraph'.
2471 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2472 (fill-comment-paragraph justify
))
2474 (defun python-fill-string (&optional justify
)
2475 "String fill function for `python-fill-paragraph'.
2476 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2477 (let* ((marker (point-marker))
2479 (let ((m (make-marker)))
2480 (setf (marker-position m
)
2481 (or (python-syntax-context 'string
)
2482 (and (equal (string-to-syntax "|")
2483 (syntax-after (point)))
2485 (num-quotes (python-syntax-count-quotes
2486 (char-after str-start-pos
) str-start-pos
))
2489 (goto-char (+ str-start-pos num-quotes
))
2490 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2491 (goto-char (point-max)))
2494 ;; Docstring styles may vary for oneliners and multi-liners.
2495 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2497 (case python-fill-docstring-style
2498 ;; delimiters-style is a cons cell with the form
2499 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2500 ;; is NIL means to not add any newlines for start or end
2501 ;; of docstring. See `python-fill-docstring-style' for a
2502 ;; graphic idea of each style.
2504 (onetwo (and multi-line-p
(cons 1 2)))
2505 (pep-257 (and multi-line-p
(cons nil
2)))
2506 (pep-257-nn (and multi-line-p
(cons nil
1)))
2507 (symmetric (and multi-line-p
(cons 1 1)))))
2508 (docstring-p (save-excursion
2509 ;; Consider docstrings those strings which
2510 ;; start on a line by themselves.
2511 (python-nav-beginning-of-statement)
2512 (and (= (point) str-start-pos
))))
2513 (fill-paragraph-function))
2515 (narrow-to-region str-start-pos str-end-pos
)
2516 (fill-paragraph justify
))
2518 (when (and docstring-p python-fill-docstring-style
)
2519 ;; Add the number of newlines indicated by the selected style
2520 ;; at the start of the docstring.
2521 (goto-char (+ str-start-pos num-quotes
))
2522 (delete-region (point) (progn
2523 (skip-syntax-forward "> ")
2525 (and (car delimiters-style
)
2526 (or (newline (car delimiters-style
)) t
)
2527 ;; Indent only if a newline is added.
2528 (indent-according-to-mode))
2529 ;; Add the number of newlines indicated by the selected style
2530 ;; at the end of the docstring.
2531 (goto-char (if (not (= str-end-pos
(point-max)))
2532 (- str-end-pos num-quotes
)
2534 (delete-region (point) (progn
2535 (skip-syntax-backward "> ")
2537 (and (cdr delimiters-style
)
2538 ;; Add newlines only if string ends.
2539 (not (= str-end-pos
(point-max)))
2540 (or (newline (cdr delimiters-style
)) t
)
2541 ;; Again indent only if a newline is added.
2542 (indent-according-to-mode))))) t
)
2544 (defun python-fill-decorator (&optional justify
)
2545 "Decorator fill function for `python-fill-paragraph'.
2546 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2549 (defun python-fill-paren (&optional justify
)
2550 "Paren fill function for `python-fill-paragraph'.
2551 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2553 (narrow-to-region (progn
2554 (while (python-syntax-context 'paren
)
2555 (goto-char (1- (point-marker))))
2557 (line-beginning-position))
2559 (when (not (python-syntax-context 'paren
))
2561 (when (not (python-syntax-context 'paren
))
2562 (skip-syntax-backward "^)")))
2563 (while (python-syntax-context 'paren
)
2564 (goto-char (1+ (point-marker))))
2566 (let ((paragraph-start "\f\\|[ \t]*$")
2567 (paragraph-separate ",")
2568 (fill-paragraph-function))
2569 (goto-char (point-min))
2570 (fill-paragraph justify
))
2573 (python-indent-line)
2574 (goto-char (line-end-position)))) t
)
2579 (defcustom python-skeleton-autoinsert nil
2580 "Non-nil means template skeletons will be automagically inserted.
2581 This happens when pressing \"if<SPACE>\", for example, to prompt for
2587 (define-obsolete-variable-alias
2588 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2590 (defvar python-skeleton-available
'()
2591 "Internal list of available skeletons.")
2593 (define-abbrev-table 'python-mode-abbrev-table
()
2594 "Abbrev table for Python mode."
2596 ;; Allow / inside abbrevs.
2597 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2598 ;; Only expand in code.
2599 :enable-function
(lambda ()
2601 (not (python-syntax-comment-or-string-p))
2602 python-skeleton-autoinsert
)))
2604 (defmacro python-skeleton-define
(name doc
&rest skel
)
2605 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2606 The skeleton will be bound to python-skeleton-NAME and will
2607 be added to `python-mode-abbrev-table'."
2608 (declare (indent 2))
2609 (let* ((name (symbol-name name
))
2610 (function-name (intern (concat "python-skeleton-" name
))))
2612 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2614 (setq python-skeleton-available
2615 (cons ',function-name python-skeleton-available
))
2616 (define-skeleton ,function-name
2618 (format "Insert %s statement." name
))
2621 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2622 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2623 The skeleton will be bound to python-skeleton-NAME."
2624 (declare (indent 2))
2625 (let* ((name (symbol-name name
))
2626 (function-name (intern (concat "python-skeleton--" name
)))
2628 "Add '%s' clause? " name
)))
2631 `(< ,(format "%s:" name
) \n \n
2633 `(define-skeleton ,function-name
2635 (format "Auxiliary skeleton for %s statement." name
))
2637 (unless (y-or-n-p ,msg
)
2641 (python-define-auxiliary-skeleton else nil
)
2643 (python-define-auxiliary-skeleton except nil
)
2645 (python-define-auxiliary-skeleton finally nil
)
2647 (python-skeleton-define if nil
2651 ("other condition, %s: "
2655 '(python-skeleton--else) | ^
)
2657 (python-skeleton-define while nil
2661 '(python-skeleton--else) | ^
)
2663 (python-skeleton-define for nil
2667 '(python-skeleton--else) | ^
)
2669 (python-skeleton-define try nil
2675 "except " str
":" \n
2678 '(python-skeleton--except)
2679 '(python-skeleton--else)
2680 '(python-skeleton--finally) | ^
)
2682 (python-skeleton-define def nil
2684 "def " str
"(" ("Parameter, %s: "
2685 (unless (equal ?\
( (char-before)) ", ")
2687 "\"\"\"" -
"\"\"\"" \n
2690 (python-skeleton-define class nil
2692 "class " str
"(" ("Inheritance, %s: "
2693 (unless (equal ?\
( (char-before)) ", ")
2697 "\"\"\"" -
"\"\"\"" \n
2700 (defun python-skeleton-add-menu-items ()
2701 "Add menu items to Python->Skeletons menu."
2702 (let ((skeletons (sort python-skeleton-available
'string
<))
2704 (dolist (skeleton skeletons
)
2706 nil
'("Python" "Skeletons")
2708 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2713 (defcustom python-ffap-setup-code
2714 "def __FFAP_get_module_path(module):
2717 path = __import__(module).__file__
2718 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2723 "Python code to get a module path."
2727 (defcustom python-ffap-string-code
2728 "__FFAP_get_module_path('''%s''')\n"
2729 "Python code used to get a string with the path of a module."
2733 (defun python-ffap-module-path (module)
2734 "Function for `ffap-alist' to return path for MODULE."
2736 (and (eq major-mode
'inferior-python-mode
)
2737 (get-buffer-process (current-buffer)))
2738 (python-shell-get-process))))
2742 (python-shell-send-string-no-output
2743 (format python-ffap-string-code module
) process
)))
2745 (substring-no-properties module-file
1 -
1))))))
2747 (eval-after-load "ffap"
2749 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2750 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2755 (defcustom python-check-command
2757 "Command used to check a Python file."
2761 (defcustom python-check-buffer-name
2762 "*Python check: %s*"
2763 "Buffer name used for check commands."
2767 (defvar python-check-custom-command nil
2770 (defun python-check (command)
2771 "Check a Python file (default current buffer's file).
2772 Runs COMMAND, a shell command, as if by `compile'. See
2773 `python-check-command' for the default."
2775 (list (read-string "Check command: "
2776 (or python-check-custom-command
2777 (concat python-check-command
" "
2778 (shell-quote-argument
2780 (let ((name (buffer-file-name)))
2782 (file-name-nondirectory name
)))
2784 (setq python-check-custom-command command
)
2785 (save-some-buffers (not compilation-ask-about-save
) nil
)
2786 (let ((process-environment (python-shell-calculate-process-environment))
2787 (exec-path (python-shell-calculate-exec-path)))
2788 (compilation-start command nil
2790 (format python-check-buffer-name command
)))))
2795 (defcustom python-eldoc-setup-code
2796 "def __PYDOC_get_help(obj):
2799 if hasattr(obj, 'startswith'):
2800 obj = eval(obj, globals())
2801 doc = inspect.getdoc(obj)
2802 if not doc and callable(obj):
2804 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2805 target = obj.__init__
2811 args = inspect.formatargspec(
2812 *inspect.getargspec(target)
2815 doc = '{objtype} {name}{args}'.format(
2816 objtype=objtype, name=name, args=args
2819 doc = doc.splitlines()[0]
2826 "Python code to setup documentation retrieval."
2830 (defcustom python-eldoc-string-code
2831 "__PYDOC_get_help('''%s''')\n"
2832 "Python code used to get a string with the documentation of an object."
2836 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2837 "Internal implementation to get documentation at point.
2838 If not FORCE-INPUT is passed then what
2839 `python-info-current-symbol' returns will be used. If not
2840 FORCE-PROCESS is passed what `python-shell-get-process' returns
2842 (let ((process (or force-process
(python-shell-get-process))))
2844 (error "Eldoc needs an inferior Python process running")
2845 (let ((input (or force-input
2846 (python-info-current-symbol t
))))
2848 (python-shell-send-string-no-output
2849 (format python-eldoc-string-code input
)
2852 (defun python-eldoc-function ()
2853 "`eldoc-documentation-function' for Python.
2854 For this to work the best as possible you should call
2855 `python-shell-send-buffer' from time to time so context in
2856 inferior python process is updated properly."
2857 (python-eldoc--get-doc-at-point))
2859 (defun python-eldoc-at-point (symbol)
2860 "Get help on SYMBOL using `help'.
2861 Interactively, prompt for symbol."
2863 (let ((symbol (python-info-current-symbol t
))
2864 (enable-recursive-minibuffers t
))
2865 (list (read-string (if symbol
2866 (format "Describe symbol (default %s): " symbol
)
2867 "Describe symbol: ")
2869 (message (python-eldoc--get-doc-at-point symbol
)))
2871 (add-to-list 'debug-ignored-errors
2872 "^Eldoc needs an inferior Python process running.")
2877 (defun python-imenu-prev-index-position ()
2878 "Python mode's `imenu-prev-index-position-function'."
2880 (while (and (setq found
2881 (re-search-backward python-nav-beginning-of-defun-regexp nil t
))
2882 (not (python-info-looking-at-beginning-of-defun))))
2884 (python-info-looking-at-beginning-of-defun)
2885 (python-info-current-defun))))
2890 (defun python-info-current-defun (&optional include-type
)
2891 "Return name of surrounding function with Python compatible dotty syntax.
2892 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2893 This function is compatible to be used as
2894 `add-log-current-defun-function' since it returns nil if point is
2895 not inside a defun."
2901 (starting-indentation
2904 (python-nav-beginning-of-defun 1)
2905 ;; This extra number is just for checking code
2906 ;; against indentation to work well on first run.
2907 (+ (current-indentation) 4))))
2908 (starting-point (point)))
2909 ;; Check point is inside a defun.
2910 (when (and starting-indentation
2913 (python-nav-end-of-defun)
2916 (while (python-nav-beginning-of-defun 1)
2917 (when (< (current-indentation) starting-indentation
)
2918 (setq starting-indentation
(current-indentation))
2921 (if (not include-type
)
2922 (match-string-no-properties 1)
2923 (mapconcat 'identity
2925 (match-string-no-properties 0)) " "))
2927 (and (= (current-indentation) 0) (throw 'exit t
)))))
2929 (mapconcat (lambda (string) string
) names
"."))))))
2931 (defun python-info-current-symbol (&optional replace-self
)
2932 "Return current symbol using dotty syntax.
2933 With optional argument REPLACE-SELF convert \"self\" to current
2936 (and (not (python-syntax-comment-or-string-p))
2937 (with-syntax-table python-dotty-syntax-table
2938 (let ((sym (symbol-at-point)))
2940 (substring-no-properties (symbol-name sym
))))))))
2942 (if (not replace-self
)
2944 (let ((current-defun (python-info-current-defun)))
2945 (if (not current-defun
)
2947 (replace-regexp-in-string
2948 (python-rx line-start word-start
"self" word-end ?.
)
2950 (mapconcat 'identity
2951 (butlast (split-string current-defun
"\\."))
2955 (defun python-info-statement-starts-block-p ()
2956 "Return non-nil if current statement opens a block."
2958 (python-nav-beginning-of-statement)
2959 (looking-at (python-rx block-start
))))
2961 (defun python-info-statement-ends-block-p ()
2962 "Return non-nil if point is at end of block."
2963 (let ((end-of-block-pos (save-excursion
2964 (python-nav-end-of-block)))
2965 (end-of-statement-pos (save-excursion
2966 (python-nav-end-of-statement))))
2967 (and end-of-block-pos end-of-statement-pos
2968 (= end-of-block-pos end-of-statement-pos
))))
2970 (defun python-info-beginning-of-statement-p ()
2971 "Return non-nil if point is at beginning of statement."
2972 (= (point) (save-excursion
2973 (python-nav-beginning-of-statement)
2976 (defun python-info-end-of-statement-p ()
2977 "Return non-nil if point is at end of statement."
2978 (= (point) (save-excursion
2979 (python-nav-end-of-statement)
2982 (defun python-info-beginning-of-block-p ()
2983 "Return non-nil if point is at beginning of block."
2984 (and (python-info-beginning-of-statement-p)
2985 (python-info-statement-starts-block-p)))
2987 (defun python-info-end-of-block-p ()
2988 "Return non-nil if point is at end of block."
2989 (and (python-info-end-of-statement-p)
2990 (python-info-statement-ends-block-p)))
2992 (defun python-info-closing-block ()
2993 "Return the point of the block the current line closes."
2994 (let ((closing-word (save-excursion
2995 (back-to-indentation)
2997 (indentation (current-indentation)))
2998 (when (member closing-word python-indent-dedenters
)
3001 (while (and (> (current-indentation) indentation
)
3003 (not (back-to-indentation))
3005 (back-to-indentation)
3007 ((not (equal indentation
(current-indentation))) nil
)
3008 ((string= closing-word
"elif")
3009 (when (member (current-word) '("if" "elif"))
3011 ((string= closing-word
"else")
3012 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3014 ((string= closing-word
"except")
3015 (when (member (current-word) '("try"))
3017 ((string= closing-word
"finally")
3018 (when (member (current-word) '("except" "else"))
3019 (point-marker))))))))
3021 (defun python-info-closing-block-message (&optional closing-block-point
)
3022 "Message the contents of the block the current line closes.
3023 With optional argument CLOSING-BLOCK-POINT use that instead of
3024 recalculating it calling `python-info-closing-block'."
3025 (let ((point (or closing-block-point
(python-info-closing-block))))
3029 (message "Closes %s" (save-excursion
3031 (back-to-indentation)
3033 (point) (line-end-position))))))))
3035 (defun python-info-line-ends-backslash-p (&optional line-number
)
3036 "Return non-nil if current line ends with backslash.
3037 With optional argument LINE-NUMBER, check that line instead."
3042 (goto-char line-number
))
3043 (while (and (not (eobp))
3044 (goto-char (line-end-position))
3045 (python-syntax-context 'paren
)
3046 (not (equal (char-before (point)) ?
\\)))
3048 (when (equal (char-before) ?
\\)
3051 (defun python-info-beginning-of-backslash (&optional line-number
)
3052 "Return the point where the backslashed line start.
3053 Optional argument LINE-NUMBER forces the line number to check against."
3058 (goto-char line-number
))
3059 (when (python-info-line-ends-backslash-p)
3060 (while (save-excursion
3061 (goto-char (line-beginning-position))
3062 (python-syntax-context 'paren
))
3064 (back-to-indentation)
3067 (defun python-info-continuation-line-p ()
3068 "Check if current line is continuation of another.
3069 When current line is continuation of another return the point
3070 where the continued line ends."
3074 (let* ((context-type (progn
3075 (back-to-indentation)
3076 (python-syntax-context-type)))
3077 (line-start (line-number-at-pos))
3078 (context-start (when context-type
3079 (python-syntax-context context-type
))))
3080 (cond ((equal context-type
'paren
)
3081 ;; Lines inside a paren are always a continuation line
3082 ;; (except the first one).
3083 (python-util-forward-comment -
1)
3085 ((member context-type
'(string comment
))
3086 ;; move forward an roll again
3087 (goto-char context-start
)
3088 (python-util-forward-comment)
3089 (python-info-continuation-line-p))
3091 ;; Not within a paren, string or comment, the only way
3092 ;; we are dealing with a continuation line is that
3093 ;; previous line contains a backslash, and this can
3094 ;; only be the previous line from current
3095 (back-to-indentation)
3096 (python-util-forward-comment -
1)
3097 (when (and (equal (1- line-start
) (line-number-at-pos))
3098 (python-info-line-ends-backslash-p))
3099 (point-marker))))))))
3101 (defun python-info-block-continuation-line-p ()
3102 "Return non-nil if current line is a continuation of a block."
3104 (when (python-info-continuation-line-p)
3106 (back-to-indentation)
3107 (when (looking-at (python-rx block-start
))
3110 (defun python-info-assignment-continuation-line-p ()
3111 "Check if current line is a continuation of an assignment.
3112 When current line is continuation of another with an assignment
3113 return the point of the first non-blank character after the
3116 (when (python-info-continuation-line-p)
3118 (back-to-indentation)
3119 (when (and (not (looking-at (python-rx block-start
)))
3120 (and (re-search-forward (python-rx not-simple-operator
3122 not-simple-operator
)
3123 (line-end-position) t
)
3124 (not (python-syntax-context-type))))
3125 (skip-syntax-forward "\s")
3128 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3129 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3130 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3132 (beginning-of-line 1)
3133 (looking-at python-nav-beginning-of-defun-regexp
))))
3135 (defun python-info-current-line-comment-p ()
3136 "Check if current line is a comment line."
3137 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3139 (defun python-info-current-line-empty-p ()
3140 "Check if current line is empty, ignoring whitespace."
3142 (beginning-of-line 1)
3144 (python-rx line-start
(* whitespace
)
3145 (group (* not-newline
))
3146 (* whitespace
) line-end
))
3147 (string-equal "" (match-string-no-properties 1))))
3150 ;;; Utility functions
3152 (defun python-util-position (item seq
)
3153 "Find the first occurrence of ITEM in SEQ.
3154 Return the index of the matching item, or nil if not found."
3155 (let ((member-result (member item seq
)))
3157 (- (length seq
) (length member-result
)))))
3159 ;; Stolen from org-mode
3160 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3161 "Clone local variables from FROM-BUFFER.
3162 Optional argument REGEXP selects variables to clone and defaults
3166 (and (symbolp (car pair
))
3167 (string-match (or regexp
"^python-")
3168 (symbol-name (car pair
)))
3169 (set (make-local-variable (car pair
))
3171 (buffer-local-variables from-buffer
)))
3173 (defun python-util-forward-comment (&optional direction
)
3174 "Python mode specific version of `forward-comment'.
3175 Optional argument DIRECTION defines the direction to move to."
3176 (let ((comment-start (python-syntax-context 'comment
))
3177 (factor (if (< (or direction
0) 0)
3181 (goto-char comment-start
))
3182 (forward-comment factor
)))
3186 (define-derived-mode python-mode prog-mode
"Python"
3187 "Major mode for editing Python files.
3190 Entry to this mode calls the value of `python-mode-hook'
3191 if that value is non-nil."
3192 (set (make-local-variable 'tab-width
) 8)
3193 (set (make-local-variable 'indent-tabs-mode
) nil
)
3195 (set (make-local-variable 'comment-start
) "# ")
3196 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3198 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3199 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3201 (set (make-local-variable 'forward-sexp-function
)
3202 'python-nav-forward-sexp
)
3204 (set (make-local-variable 'font-lock-defaults
)
3205 '(python-font-lock-keywords nil nil nil nil
))
3207 (set (make-local-variable 'syntax-propertize-function
)
3208 python-syntax-propertize-function
)
3210 (set (make-local-variable 'indent-line-function
)
3211 #'python-indent-line-function
)
3212 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3214 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3215 (set (make-local-variable 'fill-paragraph-function
)
3216 'python-fill-paragraph
)
3218 (set (make-local-variable 'beginning-of-defun-function
)
3219 #'python-nav-beginning-of-defun
)
3220 (set (make-local-variable 'end-of-defun-function
)
3221 #'python-nav-end-of-defun
)
3223 (add-hook 'completion-at-point-functions
3224 'python-completion-complete-at-point nil
'local
)
3226 (add-hook 'post-self-insert-hook
3227 'python-indent-post-self-insert-function nil
'local
)
3229 (set (make-local-variable 'imenu-extract-index-name-function
)
3230 #'python-info-current-defun
)
3232 (set (make-local-variable 'imenu-prev-index-position-function
)
3233 #'python-imenu-prev-index-position
)
3235 (set (make-local-variable 'add-log-current-defun-function
)
3236 #'python-info-current-defun
)
3238 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3240 (set (make-local-variable 'skeleton-further-elements
)
3242 (< '(backward-delete-char-untabify (min python-indent-offset
3244 (^
'(- (1+ (current-indentation))))))
3246 (set (make-local-variable 'eldoc-documentation-function
)
3247 #'python-eldoc-function
)
3249 (add-to-list 'hs-special-modes-alist
3250 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3252 (python-nav-end-of-defun)) nil
))
3254 (set (make-local-variable 'mode-require-final-newline
) t
)
3256 (set (make-local-variable 'outline-regexp
)
3257 (python-rx (* space
) block-start
))
3258 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3259 (set (make-local-variable 'outline-level
)
3261 "`outline-level' function for Python mode."
3262 (1+ (/ (current-indentation) python-indent-offset
))))
3264 (python-skeleton-add-menu-items)
3266 (make-local-variable 'python-shell-internal-buffer
)
3268 (when python-indent-guess-indent-offset
3269 (python-indent-guess-indent-offset)))
3276 ;; indent-tabs-mode: nil
3279 ;;; python.el ends here