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
)
207 (eval-when-compile (require 'cl-lib
))
209 ;; Avoid compiler warnings
210 (defvar view-return-to-alist
)
211 (defvar compilation-error-regexp-alist
)
212 (defvar outline-heading-end-regexp
)
214 (autoload 'comint-mode
"comint")
217 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
219 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
222 "Python Language's flying circus support for Emacs."
225 :link
'(emacs-commentary-link "python"))
230 (defvar python-mode-map
231 (let ((map (make-sparse-keymap)))
233 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
234 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
235 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
236 (define-key map
"\C-c\C-j" 'imenu
)
238 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
239 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
240 (define-key map
"\C-c<" 'python-indent-shift-left
)
241 (define-key map
"\C-c>" 'python-indent-shift-right
)
242 (define-key map
":" 'python-indent-electric-colon
)
244 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
245 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
246 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
247 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
248 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
249 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
251 (define-key map
"\C-c\C-p" 'run-python
)
252 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
253 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
254 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
255 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
256 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
257 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
258 ;; Some util commands
259 (define-key map
"\C-c\C-v" 'python-check
)
260 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
262 (substitute-key-definition 'complete-symbol
'completion-at-point
264 (easy-menu-define python-menu map
"Python Mode menu"
266 :help
"Python-specific Features"
267 ["Shift region left" python-indent-shift-left
:active mark-active
268 :help
"Shift region left by a single indentation step"]
269 ["Shift region right" python-indent-shift-right
:active mark-active
270 :help
"Shift region right by a single indentation step"]
272 ["Start of def/class" beginning-of-defun
273 :help
"Go to start of outermost definition around point"]
274 ["End of def/class" end-of-defun
275 :help
"Go to end of definition around point"]
276 ["Mark def/class" mark-defun
277 :help
"Mark outermost definition around point"]
278 ["Jump to def/class" imenu
279 :help
"Jump to a class or function definition"]
283 ["Start interpreter" run-python
284 :help
"Run inferior Python process in a separate buffer"]
285 ["Switch to shell" python-shell-switch-to-shell
286 :help
"Switch to running inferior Python process"]
287 ["Eval string" python-shell-send-string
288 :help
"Eval string in inferior Python session"]
289 ["Eval buffer" python-shell-send-buffer
290 :help
"Eval buffer in inferior Python session"]
291 ["Eval region" python-shell-send-region
292 :help
"Eval region in inferior Python session"]
293 ["Eval defun" python-shell-send-defun
294 :help
"Eval defun in inferior Python session"]
295 ["Eval file" python-shell-send-file
296 :help
"Eval file in inferior Python session"]
297 ["Debugger" pdb
:help
"Run pdb under GUD"]
299 ["Check file" python-check
300 :help
"Check file for errors"]
301 ["Help on symbol" python-eldoc-at-point
302 :help
"Get help on symbol at point"]
303 ["Complete symbol" completion-at-point
304 :help
"Complete symbol before point"]))
306 "Keymap for `python-mode'.")
309 ;;; Python specialized rx
312 (defconst python-rx-constituents
313 `((block-start .
,(rx symbol-start
314 (or "def" "class" "if" "elif" "else" "try"
315 "except" "finally" "for" "while" "with")
317 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
319 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
320 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
321 (+ space
) "==" (+ space
)
322 (any ?
' ?
\") "__main__" (any ?
' ?
\")
324 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
325 (open-paren .
,(rx (or "{" "[" "(")))
326 (close-paren .
,(rx (or "}" "]" ")")))
327 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
328 ;; FIXME: rx should support (not simple-operator).
329 (not-simple-operator .
,(rx
331 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
332 ;; FIXME: Use regexp-opt.
333 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
334 "=" "%" "**" "//" "<<" ">>" "<=" "!="
335 "==" ">=" "is" "not")))
336 ;; FIXME: Use regexp-opt.
337 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
338 ">>=" "<<=" "&=" "^=" "|=")))
339 (string-delimiter .
,(rx (and
340 ;; Match even number of backslashes.
341 (or (not (any ?
\\ ?
\' ?
\")) point
342 ;; Quotes might be preceded by a escaped quote.
343 (and (or (not (any ?
\\)) point
) ?
\\
344 (* ?
\\ ?
\\) (any ?
\' ?
\")))
346 ;; Match single or triple quotes of any kind.
347 (group (or "\"" "\"\"\"" "'" "'''"))))))
348 "Additional Python specific sexps for `python-rx'")
350 (defmacro python-rx
(&rest regexps
)
351 "Python mode specialized rx macro.
352 This variant of `rx' supports common python named REGEXPS."
353 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
354 (cond ((null regexps
)
357 (rx-to-string `(and ,@regexps
) t
))
359 (rx-to-string (car regexps
) t
))))))
362 ;;; Font-lock and syntax
364 (defun python-syntax-context (type &optional syntax-ppss
)
365 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
366 TYPE can be `comment', `string' or `paren'. It returns the start
367 character address of the specified TYPE."
368 (declare (compiler-macro
372 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
373 (and (nth 4 ppss
) (nth 8 ppss
))))
375 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
376 (and (nth 3 ppss
) (nth 8 ppss
))))
378 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
380 (let ((ppss (or syntax-ppss
(syntax-ppss))))
382 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
383 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
384 (`paren
(nth 1 ppss
))
387 (defun python-syntax-context-type (&optional syntax-ppss
)
388 "Return the context type using SYNTAX-PPSS.
389 The type returned can be `comment', `string' or `paren'."
390 (let ((ppss (or syntax-ppss
(syntax-ppss))))
392 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
393 ((nth 1 ppss
) 'paren
))))
395 (defsubst python-syntax-comment-or-string-p
()
396 "Return non-nil if point is inside 'comment or 'string."
397 (nth 8 (syntax-ppss)))
399 (define-obsolete-function-alias
400 'python-info-ppss-context
#'python-syntax-context
"24.3")
402 (define-obsolete-function-alias
403 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
405 (define-obsolete-function-alias
406 'python-info-ppss-comment-or-string-p
407 #'python-syntax-comment-or-string-p
"24.3")
409 (defvar python-font-lock-keywords
413 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
414 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
415 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
420 ;; False, None, and True are listed as keywords on the Python 3
421 ;; documentation, but since they also qualify as constants they are
422 ;; fontified like that in order to keep font-lock consistent between
429 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
430 (1 font-lock-function-name-face
))
432 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
433 (1 font-lock-type-face
))
437 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
438 ;; copyright, license, credits, quit and exit are added by the site
439 ;; module and they are not intended to be used in programs
440 "copyright" "credits" "exit" "license" "quit")
441 symbol-end
) . font-lock-constant-face
)
443 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
444 (0+ "." (1+ (or word ?_
)))))
445 (1 font-lock-type-face
))
446 ;; Builtin Exceptions
449 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
450 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
451 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
452 "ImportError" "ImportWarning" "IndexError" "KeyError"
453 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
454 "NotImplementedError" "OSError" "OverflowError"
455 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
456 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
457 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
458 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
459 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
460 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
464 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
466 symbol-end
) . font-lock-type-face
)
470 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
471 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
472 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
473 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
474 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
475 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
476 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
477 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
480 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
481 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
484 "ascii" "bytearray" "bytes" "exec"
486 "__all__" "__doc__" "__name__" "__package__")
487 symbol-end
) . font-lock-builtin-face
)
489 ;; support for a = b = c = 5
491 (let ((re (python-rx (group (+ (any word ?. ?_
)))
492 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
493 assignment-operator
)))
494 (when (re-search-forward re limit t
)
495 (while (and (python-syntax-context 'paren
)
496 (re-search-forward re limit t
)))
497 (if (not (or (python-syntax-context 'paren
)
498 (equal (char-after (point-marker)) ?
=)))
500 (set-match-data nil
)))))
501 (1 font-lock-variable-name-face nil nil
))
502 ;; support for a, b, c = (1, 2, 3)
504 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
505 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
506 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
507 assignment-operator
)))
508 (when (and (re-search-forward re limit t
)
509 (goto-char (nth 3 (match-data))))
510 (while (and (python-syntax-context 'paren
)
511 (re-search-forward re limit t
))
512 (goto-char (nth 3 (match-data))))
513 (if (not (python-syntax-context 'paren
))
515 (set-match-data nil
)))))
516 (1 font-lock-variable-name-face nil nil
))))
518 (defconst python-syntax-propertize-function
519 (syntax-propertize-rules
520 ((python-rx string-delimiter
)
521 (0 (ignore (python-syntax-stringify))))))
523 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
524 "Count number of quotes around point (max is 3).
525 QUOTE-CHAR is the quote char to count. Optional argument POINT is
526 the point where scan starts (defaults to current point) and LIMIT
527 is used to limit the scan."
530 (or (not limit
) (< (+ point i
) limit
))
531 (eq (char-after (+ point i
)) quote-char
))
535 (defun python-syntax-stringify ()
536 "Put `syntax-table' property correctly on single/triple quotes."
537 (let* ((num-quotes (length (match-string-no-properties 1)))
539 (backward-char num-quotes
)
541 (forward-char num-quotes
)))
542 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
543 (quote-starting-pos (- (point) num-quotes
))
544 (quote-ending-pos (point))
547 (python-syntax-count-quotes
548 (char-before) string-start quote-starting-pos
))))
549 (cond ((and string-start
(= num-closing-quotes
0))
550 ;; This set of quotes doesn't match the string starting
554 ;; This set of quotes delimit the start of a string.
555 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
556 'syntax-table
(string-to-syntax "|")))
557 ((= num-quotes num-closing-quotes
)
558 ;; This set of quotes delimit the end of a string.
559 (put-text-property (1- quote-ending-pos
) quote-ending-pos
560 'syntax-table
(string-to-syntax "|")))
561 ((> num-quotes num-closing-quotes
)
562 ;; This may only happen whenever a triple quote is closing
563 ;; a single quoted string. Add string delimiter syntax to
565 (put-text-property quote-starting-pos quote-ending-pos
566 'syntax-table
(string-to-syntax "|"))))))
568 (defvar python-mode-syntax-table
569 (let ((table (make-syntax-table)))
570 ;; Give punctuation syntax to ASCII that normally has symbol
571 ;; syntax or has word syntax and isn't a letter.
572 (let ((symbol (string-to-syntax "_"))
573 (sst (standard-syntax-table)))
576 (if (equal symbol
(aref sst i
))
577 (modify-syntax-entry i
"." table
)))))
578 (modify-syntax-entry ?$
"." table
)
579 (modify-syntax-entry ?%
"." table
)
581 (modify-syntax-entry ?
# "<" table
)
582 (modify-syntax-entry ?
\n ">" table
)
583 (modify-syntax-entry ?
' "\"" table
)
584 (modify-syntax-entry ?
` "$" table
)
586 "Syntax table for Python files.")
588 (defvar python-dotty-syntax-table
589 (let ((table (make-syntax-table python-mode-syntax-table
)))
590 (modify-syntax-entry ?.
"w" table
)
591 (modify-syntax-entry ?_
"w" table
)
593 "Dotty syntax table for Python files.
594 It makes underscores and dots word constituent chars.")
599 (defcustom python-indent-offset
4
600 "Default indentation offset for Python."
605 (defcustom python-indent-guess-indent-offset t
606 "Non-nil tells Python mode to guess `python-indent-offset' value."
611 (define-obsolete-variable-alias
612 'python-indent
'python-indent-offset
"24.3")
614 (define-obsolete-variable-alias
615 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
617 (defvar python-indent-current-level
0
618 "Current indentation level `python-indent-line-function' is using.")
620 (defvar python-indent-levels
'(0)
621 "Levels of indentation available for `python-indent-line-function'.")
623 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
624 "List of words that should be dedented.
625 These make `python-indent-calculate-indentation' subtract the value of
626 `python-indent-offset'.")
628 (defun python-indent-guess-indent-offset ()
629 "Guess and set `python-indent-offset' for the current buffer."
634 (goto-char (point-min))
636 (while (and (not block-end
)
638 (python-rx line-start block-start
) nil t
))
640 (not (python-syntax-context-type))
642 (goto-char (line-end-position))
643 (python-util-forward-comment -
1)
644 (if (equal (char-before) ?
:)
647 (when (python-info-block-continuation-line-p)
648 (while (and (python-info-continuation-line-p)
651 (python-util-forward-comment -
1)
652 (when (equal (char-before) ?
:)
654 (setq block-end
(point-marker))))
657 (goto-char block-end
)
658 (python-util-forward-comment)
659 (current-indentation))))
661 (set (make-local-variable 'python-indent-offset
) indentation
)
662 (message "Can't guess python-indent-offset, using defaults: %s"
663 python-indent-offset
)))))))
665 (defun python-indent-context ()
666 "Get information on indentation context.
667 Context information is returned with a cons with the form:
670 Where status can be any of the following symbols:
671 * inside-paren: If point in between (), {} or []
672 * inside-string: If point is inside a string
673 * after-backslash: Previous line ends in a backslash
674 * after-beginning-of-block: Point is after beginning of block
675 * after-line: Point is after normal line
676 * no-indent: Point is at beginning of buffer or other special case
677 START is the buffer position where the sexp starts."
680 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
684 ;; Beginning of buffer
686 (goto-char (line-beginning-position))
690 ((setq start
(python-syntax-context 'string ppss
))
693 ((setq start
(python-syntax-context 'paren ppss
))
696 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
697 (python-syntax-context 'comment ppss
)))
698 (let ((line-beg-pos (line-beginning-position)))
699 (when (python-info-line-ends-backslash-p
701 (- line-beg-pos
2)))))
703 ;; After beginning of block
704 ((setq start
(save-excursion
706 (back-to-indentation)
707 (python-util-forward-comment -
1)
708 (equal (char-before) ?
:))
709 ;; Move to the first block start that's not in within
710 ;; a string, comment or paren and that's not a
711 ;; continuation line.
712 (while (and (re-search-backward
713 (python-rx block-start
) nil t
)
715 (python-syntax-context-type)
716 (python-info-continuation-line-p))))
717 (when (looking-at (python-rx block-start
))
719 'after-beginning-of-block
)
721 ((setq start
(save-excursion
722 (back-to-indentation)
723 (skip-chars-backward (rx (or whitespace ?
\n)))
724 (python-nav-beginning-of-statement)
731 (defun python-indent-calculate-indentation ()
732 "Calculate correct indentation offset for the current line."
733 (let* ((indentation-context (python-indent-context))
734 (context-status (car indentation-context
))
735 (context-start (cdr indentation-context
)))
739 (pcase context-status
741 ;; When point is after beginning of block just add one level
742 ;; of indentation relative to the context-start
743 (`after-beginning-of-block
744 (goto-char context-start
)
745 (+ (current-indentation) python-indent-offset
))
746 ;; When after a simple line just use previous line
747 ;; indentation, in the case current line starts with a
748 ;; `python-indent-dedenters' de-indent one level.
752 (goto-char context-start
)
753 (current-indentation))
755 (back-to-indentation)
756 (looking-at (regexp-opt python-indent-dedenters
)))
759 ;; When inside of a string, do nothing. just use the current
760 ;; indentation. XXX: perhaps it would be a good idea to
761 ;; invoke standard text indentation here
763 (goto-char context-start
)
764 (current-indentation))
765 ;; After backslash we have several possibilities.
768 ;; Check if current line is a dot continuation. For this
769 ;; the current line must start with a dot and previous
770 ;; line must contain a dot too.
772 (back-to-indentation)
773 (when (looking-at "\\.")
774 ;; If after moving one line back point is inside a paren it
775 ;; needs to move back until it's not anymore
779 (python-syntax-context 'paren
))))
780 (goto-char (line-end-position))
781 (while (and (re-search-backward
782 "\\." (line-beginning-position) t
)
783 (python-syntax-context-type)))
784 (if (and (looking-at "\\.")
785 (not (python-syntax-context-type)))
786 ;; The indentation is the same column of the
787 ;; first matching dot that's not inside a
788 ;; comment, a string or a paren
790 ;; No dot found on previous line, just add another
791 ;; indentation level.
792 (+ (current-indentation) python-indent-offset
)))))
793 ;; Check if prev line is a block continuation
794 ((let ((block-continuation-start
795 (python-info-block-continuation-line-p)))
796 (when block-continuation-start
797 ;; If block-continuation-start is set jump to that
798 ;; marker and use first column after the block start
799 ;; as indentation value.
800 (goto-char block-continuation-start
)
802 (python-rx block-start
(* space
))
803 (line-end-position) t
)
805 ;; Check if current line is an assignment continuation
806 ((let ((assignment-continuation-start
807 (python-info-assignment-continuation-line-p)))
808 (when assignment-continuation-start
809 ;; If assignment-continuation is set jump to that
810 ;; marker and use first column after the assignment
811 ;; operator as indentation value.
812 (goto-char assignment-continuation-start
)
816 (goto-char (python-info-beginning-of-backslash))
821 (or (python-info-beginning-of-backslash) (point)))
822 (python-info-line-ends-backslash-p)))
823 ;; The two previous lines ended in a backslash so we must
824 ;; respect previous line indentation.
825 (current-indentation)
826 ;; What happens here is that we are dealing with the second
827 ;; line of a backslash continuation, in that case we just going
828 ;; to add one indentation level.
829 (+ (current-indentation) python-indent-offset
)))))
830 ;; When inside a paren there's a need to handle nesting
834 ;; If current line closes the outermost open paren use the
835 ;; current indentation of the context-start line.
837 (skip-syntax-forward "\s" (line-end-position))
838 (when (and (looking-at (regexp-opt '(")" "]" "}")))
841 (not (python-syntax-context 'paren
))))
842 (goto-char context-start
)
843 (current-indentation))))
844 ;; If open paren is contained on a line by itself add another
845 ;; indentation level, else look for the first word after the
846 ;; opening paren and use it's column position as indentation
848 ((let* ((content-starts-in-newline)
851 (if (setq content-starts-in-newline
853 (goto-char context-start
)
857 (line-beginning-position)
859 (python-util-forward-comment))
861 (+ (current-indentation) python-indent-offset
)
865 ;; If current line closes a nested open paren de-indent one
868 (back-to-indentation)
869 (looking-at (regexp-opt '(")" "]" "}"))))
870 (- indent python-indent-offset
))
871 ;; If the line of the opening paren that wraps the current
872 ;; line starts a block add another level of indentation to
873 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
875 (when (and content-starts-in-newline
877 (goto-char context-start
)
878 (back-to-indentation)
879 (looking-at (python-rx block-start
))))
880 (+ indent python-indent-offset
))))
883 (defun python-indent-calculate-levels ()
884 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
885 (let* ((indentation (python-indent-calculate-indentation))
886 (remainder (% indentation python-indent-offset
))
887 (steps (/ (- indentation remainder
) python-indent-offset
)))
888 (setq python-indent-levels
(list 0))
889 (dotimes (step steps
)
890 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
891 (when (not (eq 0 remainder
))
892 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
893 (setq python-indent-levels
(nreverse python-indent-levels
))
894 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
896 (defun python-indent-toggle-levels ()
897 "Toggle `python-indent-current-level' over `python-indent-levels'."
898 (setq python-indent-current-level
(1- python-indent-current-level
))
899 (when (< python-indent-current-level
0)
900 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
902 (defun python-indent-line (&optional force-toggle
)
903 "Internal implementation of `python-indent-line-function'.
904 Uses the offset calculated in
905 `python-indent-calculate-indentation' and available levels
906 indicated by the variable `python-indent-levels' to set the
909 When the variable `last-command' is equal to
910 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
911 levels indicated in the variable `python-indent-levels' by
912 setting the current level in the variable
913 `python-indent-current-level'.
915 When the variable `last-command' is not equal to
916 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
917 possible indentation levels and saves it in the variable
918 `python-indent-levels'. Afterwards it sets the variable
919 `python-indent-current-level' correctly so offset is equal
920 to (`nth' `python-indent-current-level' `python-indent-levels')"
922 (and (or (and (eq this-command
'indent-for-tab-command
)
923 (eq last-command this-command
))
925 (not (equal python-indent-levels
'(0)))
926 (or (python-indent-toggle-levels) t
))
927 (python-indent-calculate-levels))
928 (let* ((starting-pos (point-marker))
929 (indent-ending-position
930 (+ (line-beginning-position) (current-indentation)))
931 (follow-indentation-p
933 (and (<= (line-beginning-position) starting-pos
)
934 (>= indent-ending-position starting-pos
))))
935 (next-indent (nth python-indent-current-level python-indent-levels
)))
936 (unless (= next-indent
(current-indentation))
938 (delete-horizontal-space)
939 (indent-to next-indent
)
940 (goto-char starting-pos
))
941 (and follow-indentation-p
(back-to-indentation)))
942 (python-info-closing-block-message))
944 (defun python-indent-line-function ()
945 "`indent-line-function' for Python mode.
946 See `python-indent-line' for details."
947 (python-indent-line))
949 (defun python-indent-dedent-line ()
950 "De-indent current line."
952 (when (and (not (python-syntax-comment-or-string-p))
953 (<= (point-marker) (save-excursion
954 (back-to-indentation)
956 (> (current-column) 0))
957 (python-indent-line t
)
960 (defun python-indent-dedent-line-backspace (arg)
961 "De-indent current line.
962 Argument ARG is passed to `backward-delete-char-untabify' when
963 point is not in between the indentation."
965 (when (not (python-indent-dedent-line))
966 (backward-delete-char-untabify arg
)))
967 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
969 (defun python-indent-region (start end
)
970 "Indent a python region automagically.
972 Called from a program, START and END specify the region to indent."
973 (let ((deactivate-mark nil
))
976 (setq end
(point-marker))
978 (or (bolp) (forward-line 1))
979 (while (< (point) end
)
980 (or (and (bolp) (eolp))
983 (back-to-indentation)
984 (setq word
(current-word))
987 ;; Don't mess with strings, unless it's the
988 ;; enclosing set of quotes.
989 (or (not (python-syntax-context 'string
))
993 (current-indentation)
994 (python-syntax-count-quotes (char-after) (point))))
995 (string-to-syntax "|"))))
997 (delete-horizontal-space)
998 (indent-to (python-indent-calculate-indentation)))))
1000 (move-marker end nil
))))
1002 (defun python-indent-shift-left (start end
&optional count
)
1003 "Shift lines contained in region START END by COUNT columns to the left.
1004 COUNT defaults to `python-indent-offset'. If region isn't
1005 active, the current line is shifted. The shifted region includes
1006 the lines in which START and END lie. An error is signaled if
1007 any lines in the region are indented less than COUNT columns."
1010 (list (region-beginning) (region-end) current-prefix-arg
)
1011 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1013 (setq count
(prefix-numeric-value count
))
1014 (setq count python-indent-offset
))
1016 (let ((deactivate-mark nil
))
1019 (while (< (point) end
)
1020 (if (and (< (current-indentation) count
)
1021 (not (looking-at "[ \t]*$")))
1022 (error "Can't shift all lines enough"))
1024 (indent-rigidly start end
(- count
))))))
1026 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1028 (defun python-indent-shift-right (start end
&optional count
)
1029 "Shift lines contained in region START END by COUNT columns to the left.
1030 COUNT defaults to `python-indent-offset'. If region isn't
1031 active, the current line is shifted. The shifted region includes
1032 the lines in which START and END lie."
1035 (list (region-beginning) (region-end) current-prefix-arg
)
1036 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1037 (let ((deactivate-mark nil
))
1039 (setq count
(prefix-numeric-value count
))
1040 (setq count python-indent-offset
))
1041 (indent-rigidly start end count
)))
1043 (defun python-indent-electric-colon (arg)
1044 "Insert a colon and maybe de-indent the current line.
1045 With numeric ARG, just insert that many colons. With
1046 \\[universal-argument], just insert a single colon."
1048 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1049 (when (and (not arg
)
1051 (not (equal ?
: (char-after (- (point-marker) 2))))
1052 (not (python-syntax-comment-or-string-p)))
1053 (let ((indentation (current-indentation))
1054 (calculated-indentation (python-indent-calculate-indentation)))
1055 (python-info-closing-block-message)
1056 (when (> indentation calculated-indentation
)
1058 (indent-line-to calculated-indentation
)
1059 (when (not (python-info-closing-block-message))
1060 (indent-line-to indentation
)))))))
1061 (put 'python-indent-electric-colon
'delete-selection t
)
1063 (defun python-indent-post-self-insert-function ()
1064 "Adjust closing paren line indentation after a char is added.
1065 This function is intended to be added to the
1066 `post-self-insert-hook.' If a line renders a paren alone, after
1067 adding a char before it, the line will be re-indented
1068 automatically if needed."
1069 (when (and (eq (char-before) last-command-event
)
1071 (memq (char-after) '(?\
) ?\
] ?\
})))
1073 (goto-char (line-beginning-position))
1074 ;; If after going to the beginning of line the point
1075 ;; is still inside a paren it's ok to do the trick
1076 (when (python-syntax-context 'paren
)
1077 (let ((indentation (python-indent-calculate-indentation)))
1078 (when (< (current-indentation) indentation
)
1079 (indent-line-to indentation
)))))))
1084 (defvar python-nav-beginning-of-defun-regexp
1085 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1086 "Regexp matching class or function definition.
1087 The name of the defun should be grouped so it can be retrieved
1088 via `match-string'.")
1090 (defun python-nav--beginning-of-defun (&optional arg
)
1091 "Internal implementation of `python-nav-beginning-of-defun'.
1092 With positive ARG search backwards, else search forwards."
1093 (when (or (null arg
) (= arg
0)) (setq arg
1))
1094 (let* ((re-search-fn (if (> arg
0)
1095 #'re-search-backward
1096 #'re-search-forward
))
1097 (line-beg-pos (line-beginning-position))
1098 (line-content-start (+ line-beg-pos
(current-indentation)))
1099 (pos (point-marker))
1104 (not (python-info-looking-at-beginning-of-defun))
1105 (python-nav-backward-block)))
1106 (or (and (python-info-looking-at-beginning-of-defun)
1107 (+ (current-indentation) python-indent-offset
))
1111 (when (and (< arg
0)
1112 (python-info-looking-at-beginning-of-defun))
1114 (while (and (funcall re-search-fn
1115 python-nav-beginning-of-defun-regexp nil t
)
1116 (or (python-syntax-context-type)
1117 ;; Handle nested defuns when moving
1118 ;; backwards by checking indentation.
1120 (not (= (current-indentation) 0))
1121 (>= (current-indentation) beg-indentation
)))))
1122 (and (python-info-looking-at-beginning-of-defun)
1123 (or (not (= (line-number-at-pos pos
)
1124 (line-number-at-pos)))
1125 (and (>= (point) line-beg-pos
)
1126 (<= (point) line-content-start
)
1127 (> pos line-content-start
)))))))
1129 (or (beginning-of-line 1) t
)
1130 (and (goto-char pos
) nil
))))
1132 (defun python-nav-beginning-of-defun (&optional arg
)
1133 "Move point to `beginning-of-defun'.
1134 With positive ARG search backwards else search forward. When ARG
1135 is nil or 0 defaults to 1. When searching backwards nested
1136 defuns are handled with care depending on current point
1137 position. Return non-nil if point is moved to
1138 `beginning-of-defun'."
1139 (when (or (null arg
) (= arg
0)) (setq arg
1))
1141 (cond ((and (eq this-command
'mark-defun
)
1142 (python-info-looking-at-beginning-of-defun)))
1144 (dotimes (i (if (> arg
0) arg
(- arg
)))
1145 (when (and (python-nav--beginning-of-defun arg)
1150 (defun python-nav-end-of-defun ()
1151 "Move point to the end of def or class.
1152 Returns nil if point is not in a def or class."
1154 (let ((beg-defun-indent)
1156 (when (or (python-info-looking-at-beginning-of-defun)
1157 (python-nav-beginning-of-defun 1)
1158 (python-nav-beginning-of-defun -1))
1159 (setq beg-defun-indent
(current-indentation))
1161 (python-nav-end-of-statement)
1162 (python-util-forward-comment 1)
1163 (and (> (current-indentation) beg-defun-indent
)
1165 (python-util-forward-comment -
1)
1167 ;; Ensure point moves forward.
1168 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1170 (defun python-nav-beginning-of-statement ()
1171 "Move to start of current statement."
1173 (while (and (or (back-to-indentation) t
)
1178 (python-info-line-ends-backslash-p))
1179 (python-syntax-context 'string
)
1180 (python-syntax-context 'paren
))
1181 (forward-line -
1))))
1184 (defun python-nav-end-of-statement ()
1185 "Move to end of current statement."
1187 (while (and (goto-char (line-end-position))
1190 (python-info-line-ends-backslash-p)
1191 (python-syntax-context 'string
)
1192 (python-syntax-context 'paren
))
1196 (defun python-nav-backward-statement (&optional arg
)
1197 "Move backward to previous statement.
1198 With ARG, repeat. See `python-nav-forward-statement'."
1200 (or arg
(setq arg
1))
1201 (python-nav-forward-statement (- arg
)))
1203 (defun python-nav-forward-statement (&optional arg
)
1204 "Move forward to next statement.
1205 With ARG, repeat. With negative argument, move ARG times
1206 backward to previous statement."
1208 (or arg
(setq arg
1))
1210 (python-nav-end-of-statement)
1211 (python-util-forward-comment)
1212 (python-nav-beginning-of-statement)
1213 (setq arg
(1- arg
)))
1215 (python-nav-beginning-of-statement)
1216 (python-util-forward-comment -
1)
1217 (python-nav-beginning-of-statement)
1218 (setq arg
(1+ arg
))))
1220 (defun python-nav-beginning-of-block ()
1221 "Move to start of current block."
1223 (let ((starting-pos (point))
1224 (block-regexp (python-rx
1225 line-start
(* whitespace
) block-start
)))
1227 (python-nav-beginning-of-statement)
1228 (looking-at (python-rx block-start
)))
1230 ;; Go to first line beginning a statement
1231 (while (and (not (bobp))
1232 (or (and (python-nav-beginning-of-statement) nil
)
1233 (python-info-current-line-comment-p)
1234 (python-info-current-line-empty-p)))
1236 (let ((block-matching-indent
1237 (- (current-indentation) python-indent-offset
)))
1239 (and (python-nav-backward-block)
1240 (> (current-indentation) block-matching-indent
)))
1241 (if (and (looking-at (python-rx block-start
))
1242 (= (current-indentation) block-matching-indent
))
1244 (and (goto-char starting-pos
) nil
))))))
1246 (defun python-nav-end-of-block ()
1247 "Move to end of current block."
1249 (when (python-nav-beginning-of-block)
1250 (let ((block-indentation (current-indentation)))
1251 (python-nav-end-of-statement)
1252 (while (and (forward-line 1)
1254 (or (and (> (current-indentation) block-indentation
)
1255 (or (python-nav-end-of-statement) t
))
1256 (python-info-current-line-comment-p)
1257 (python-info-current-line-empty-p))))
1258 (python-util-forward-comment -
1)
1261 (defun python-nav-backward-block (&optional arg
)
1262 "Move backward to previous block of code.
1263 With ARG, repeat. See `python-nav-forward-block'."
1265 (or arg
(setq arg
1))
1266 (python-nav-forward-block (- arg
)))
1268 (defun python-nav-forward-block (&optional arg
)
1269 "Move forward to next block of code.
1270 With ARG, repeat. With negative argument, move ARG times
1271 backward to previous block."
1273 (or arg
(setq arg
1))
1274 (let ((block-start-regexp
1275 (python-rx line-start
(* whitespace
) block-start
))
1276 (starting-pos (point)))
1278 (python-nav-end-of-statement)
1280 (re-search-forward block-start-regexp nil t
)
1281 (python-syntax-context-type)))
1282 (setq arg
(1- arg
)))
1284 (python-nav-beginning-of-statement)
1286 (re-search-backward block-start-regexp nil t
)
1287 (python-syntax-context-type)))
1288 (setq arg
(1+ arg
)))
1289 (python-nav-beginning-of-statement)
1290 (if (not (looking-at (python-rx block-start
)))
1291 (and (goto-char starting-pos
) nil
)
1292 (and (not (= (point) starting-pos
)) (point-marker)))))
1294 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1295 "Safe version of standard `forward-sexp'.
1296 When ARG > 0 move forward, else if ARG is < 0."
1297 (or arg
(setq arg
1))
1298 (let ((forward-sexp-function nil
)
1300 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1302 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1306 (while (and (funcall search-fn paren-regexp nil t
)
1307 (python-syntax-context 'paren
)))))))
1309 (defun python-nav--forward-sexp (&optional dir
)
1310 "Move to forward sexp.
1311 With positive Optional argument DIR direction move forward, else
1313 (setq dir
(or dir
1))
1315 (let* ((forward-p (if (> dir
0)
1316 (and (setq dir
1) t
)
1317 (and (setq dir -
1) nil
)))
1318 (re-search-fn (if forward-p
1320 're-search-backward
))
1321 (context-type (python-syntax-context-type)))
1323 ((eq context-type
'string
)
1324 ;; Inside of a string, get out of it.
1325 (while (and (funcall re-search-fn
"[\"']" nil t
)
1326 (python-syntax-context 'string
))))
1327 ((eq context-type
'comment
)
1328 ;; Inside of a comment, just move forward.
1329 (python-util-forward-comment dir
))
1330 ((or (eq context-type
'paren
)
1331 (and forward-p
(looking-at (python-rx open-paren
)))
1332 (and (not forward-p
)
1333 (eq (syntax-class (syntax-after (1- (point))))
1334 (car (string-to-syntax ")")))))
1335 ;; Inside a paren or looking at it, lisp knows what to do.
1336 (python-nav-lisp-forward-sexp-safe dir
))
1338 ;; This part handles the lispy feel of
1339 ;; `python-nav-forward-sexp'. Knowing everything about the
1340 ;; current context and the context of the next sexp tries to
1341 ;; follow the lisp sexp motion commands in a symmetric manner.
1344 ((python-info-beginning-of-block-p) 'block-start
)
1345 ((python-info-end-of-block-p) 'block-end
)
1346 ((python-info-beginning-of-statement-p) 'statement-start
)
1347 ((python-info-end-of-statement-p) 'statement-end
)))
1350 (python-nav-lisp-forward-sexp-safe dir
)
1354 (goto-char next-sexp-pos
)
1356 ((python-info-beginning-of-block-p) 'block-start
)
1357 ((python-info-end-of-block-p) 'block-end
)
1358 ((python-info-beginning-of-statement-p) 'statement-start
)
1359 ((python-info-end-of-statement-p) 'statement-end
)
1360 ((python-info-statement-starts-block-p) 'starts-block
)
1361 ((python-info-statement-ends-block-p) 'ends-block
)))))
1363 (cond ((and (not (eobp))
1364 (python-info-current-line-empty-p))
1365 (python-util-forward-comment dir
)
1366 (python-nav--forward-sexp dir
))
1367 ((eq context
'block-start
)
1368 (python-nav-end-of-block))
1369 ((eq context
'statement-start
)
1370 (python-nav-end-of-statement))
1371 ((and (memq context
'(statement-end block-end
))
1372 (eq next-sexp-context
'ends-block
))
1373 (goto-char next-sexp-pos
)
1374 (python-nav-end-of-block))
1375 ((and (memq context
'(statement-end block-end
))
1376 (eq next-sexp-context
'starts-block
))
1377 (goto-char next-sexp-pos
)
1378 (python-nav-end-of-block))
1379 ((memq context
'(statement-end block-end
))
1380 (goto-char next-sexp-pos
)
1381 (python-nav-end-of-statement))
1382 (t (goto-char next-sexp-pos
)))
1383 (cond ((and (not (bobp))
1384 (python-info-current-line-empty-p))
1385 (python-util-forward-comment dir
)
1386 (python-nav--forward-sexp dir
))
1387 ((eq context
'block-end
)
1388 (python-nav-beginning-of-block))
1389 ((eq context
'statement-end
)
1390 (python-nav-beginning-of-statement))
1391 ((and (memq context
'(statement-start block-start
))
1392 (eq next-sexp-context
'starts-block
))
1393 (goto-char next-sexp-pos
)
1394 (python-nav-beginning-of-block))
1395 ((and (memq context
'(statement-start block-start
))
1396 (eq next-sexp-context
'ends-block
))
1397 (goto-char next-sexp-pos
)
1398 (python-nav-beginning-of-block))
1399 ((memq context
'(statement-start block-start
))
1400 (goto-char next-sexp-pos
)
1401 (python-nav-beginning-of-statement))
1402 (t (goto-char next-sexp-pos
))))))))))
1404 (defun python-nav--backward-sexp ()
1405 "Move to backward sexp."
1406 (python-nav--forward-sexp -
1))
1408 (defun python-nav-forward-sexp (&optional arg
)
1409 "Move forward across one block of code.
1410 With ARG, do it that many times. Negative arg -N means
1411 move backward N times."
1413 (or arg
(setq arg
1))
1415 (python-nav--forward-sexp)
1416 (setq arg
(1- arg
)))
1418 (python-nav--backward-sexp)
1419 (setq arg
(1+ arg
))))
1421 (defun python-nav--up-list (&optional dir
)
1422 "Internal implementation of `python-nav-up-list'.
1423 DIR is always 1 or -1 and comes sanitized from
1424 `python-nav-up-list' calls."
1425 (let ((context (python-syntax-context-type))
1426 (forward-p (> dir
0)))
1428 ((memq context
'(string comment
)))
1429 ((eq context
'paren
)
1430 (let ((forward-sexp-function))
1432 ((and forward-p
(python-info-end-of-block-p))
1433 (let ((parent-end-pos
1435 (let ((indentation (and
1436 (python-nav-beginning-of-block)
1437 (current-indentation))))
1438 (while (and indentation
1440 (>= (current-indentation) indentation
)
1441 (python-nav-backward-block)))
1442 (python-nav-end-of-block)))))
1443 (and (> (or parent-end-pos
(point)) (point))
1444 (goto-char parent-end-pos
))))
1445 (forward-p (python-nav-end-of-block))
1446 ((and (not forward-p
)
1447 (> (current-indentation) 0)
1448 (python-info-beginning-of-block-p))
1449 (let ((prev-block-pos
1451 (let ((indentation (current-indentation)))
1452 (while (and (python-nav-backward-block)
1453 (>= (current-indentation) indentation
))))
1455 (and (> (point) prev-block-pos
)
1456 (goto-char prev-block-pos
))))
1457 ((not forward-p
) (python-nav-beginning-of-block)))))
1459 (defun python-nav-up-list (&optional arg
)
1460 "Move forward out of one level of parentheses (or blocks).
1461 With ARG, do this that many times.
1462 A negative argument means move backward but still to a less deep spot.
1463 This command assumes point is not in a string or comment."
1465 (or arg
(setq arg
1))
1467 (python-nav--up-list 1)
1468 (setq arg
(1- arg
)))
1470 (python-nav--up-list -
1)
1471 (setq arg
(1+ arg
))))
1473 (defun python-nav-backward-up-list (&optional arg
)
1474 "Move backward out of one level of parentheses (or blocks).
1475 With ARG, do this that many times.
1476 A negative argument means move backward but still to a less deep spot.
1477 This command assumes point is not in a string or comment."
1479 (or arg
(setq arg
1))
1480 (python-nav-up-list (- arg
)))
1483 ;;; Shell integration
1485 (defcustom python-shell-buffer-name
"Python"
1486 "Default buffer name for Python interpreter."
1491 (defcustom python-shell-interpreter
"python"
1492 "Default Python interpreter for shell."
1496 (defcustom python-shell-internal-buffer-name
"Python Internal"
1497 "Default buffer name for the Internal Python interpreter."
1502 (defcustom python-shell-interpreter-args
"-i"
1503 "Default arguments for the Python interpreter."
1507 (defcustom python-shell-prompt-regexp
">>> "
1508 "Regular Expression matching top\-level input prompt of python shell.
1509 It should not contain a caret (^) at the beginning."
1514 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1515 "Regular Expression matching block input prompt of python shell.
1516 It should not contain a caret (^) at the beginning."
1521 (defcustom python-shell-prompt-output-regexp
""
1522 "Regular Expression matching output prompt of python shell.
1523 It should not contain a caret (^) at the beginning."
1528 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1529 "Regular Expression matching pdb input prompt of python shell.
1530 It should not contain a caret (^) at the beginning."
1535 (defcustom python-shell-enable-font-lock t
1536 "Should syntax highlighting be enabled in the python shell buffer?
1537 Restart the python shell after changing this variable for it to take effect."
1542 (defcustom python-shell-process-environment nil
1543 "List of environment variables for Python shell.
1544 This variable follows the same rules as `process-environment'
1545 since it merges with it before the process creation routines are
1546 called. When this variable is nil, the Python shell is run with
1547 the default `process-environment'."
1548 :type
'(repeat string
)
1552 (defcustom python-shell-extra-pythonpaths nil
1553 "List of extra pythonpaths for Python shell.
1554 The values of this variable are added to the existing value of
1555 PYTHONPATH in the `process-environment' variable."
1556 :type
'(repeat string
)
1560 (defcustom python-shell-exec-path nil
1561 "List of path to search for binaries.
1562 This variable follows the same rules as `exec-path' since it
1563 merges with it before the process creation routines are called.
1564 When this variable is nil, the Python shell is run with the
1565 default `exec-path'."
1566 :type
'(repeat string
)
1570 (defcustom python-shell-virtualenv-path nil
1571 "Path to virtualenv root.
1572 This variable, when set to a string, makes the values stored in
1573 `python-shell-process-environment' and `python-shell-exec-path'
1574 to be modified properly so shells are started with the specified
1580 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1581 python-ffap-setup-code
1582 python-eldoc-setup-code
)
1583 "List of code run by `python-shell-send-setup-codes'."
1584 :type
'(repeat symbol
)
1588 (defcustom python-shell-compilation-regexp-alist
1589 `((,(rx line-start
(1+ (any " \t")) "File \""
1590 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1591 "\", line " (group (1+ digit
)))
1593 (,(rx " in file " (group (1+ not-newline
)) " on line "
1596 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1597 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1599 "`compilation-error-regexp-alist' for inferior Python."
1600 :type
'(alist string
)
1603 (defun python-shell-get-process-name (dedicated)
1604 "Calculate the appropriate process name for inferior Python process.
1605 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1606 returns a string with the form
1607 `python-shell-buffer-name'[variable `buffer-file-name'] else
1608 returns the value of `python-shell-buffer-name'."
1612 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1613 (format "%s" python-shell-buffer-name
))))
1616 (defun python-shell-internal-get-process-name ()
1617 "Calculate the appropriate process name for Internal Python process.
1618 The name is calculated from `python-shell-global-buffer-name' and
1619 a hash of all relevant global shell settings in order to ensure
1620 uniqueness for different types of configurations."
1622 python-shell-internal-buffer-name
1625 (python-shell-parse-command)
1626 python-shell-prompt-regexp
1627 python-shell-prompt-block-regexp
1628 python-shell-prompt-output-regexp
1629 (mapconcat #'symbol-value python-shell-setup-codes
"")
1630 (mapconcat #'identity python-shell-process-environment
"")
1631 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1632 (mapconcat #'identity python-shell-exec-path
"")
1633 (or python-shell-virtualenv-path
"")
1634 (mapconcat #'identity python-shell-exec-path
"")))))
1636 (defun python-shell-parse-command ()
1637 "Calculate the string used to execute the inferior Python process."
1638 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1640 (defun python-shell-calculate-process-environment ()
1641 "Calculate process environment given `python-shell-virtualenv-path'."
1642 (let ((process-environment (append
1643 python-shell-process-environment
1644 process-environment nil
))
1645 (virtualenv (if python-shell-virtualenv-path
1646 (directory-file-name python-shell-virtualenv-path
)
1648 (when python-shell-extra-pythonpaths
1649 (setenv "PYTHONPATH"
1651 (mapconcat 'identity
1652 python-shell-extra-pythonpaths
1655 (or (getenv "PYTHONPATH") ""))))
1656 (if (not virtualenv
)
1658 (setenv "PYTHONHOME" nil
)
1659 (setenv "PATH" (format "%s/bin%s%s"
1660 virtualenv path-separator
1661 (or (getenv "PATH") "")))
1662 (setenv "VIRTUAL_ENV" virtualenv
))
1663 process-environment
))
1665 (defun python-shell-calculate-exec-path ()
1666 "Calculate exec path given `python-shell-virtualenv-path'."
1667 (let ((path (append python-shell-exec-path
1669 (if (not python-shell-virtualenv-path
)
1671 (cons (format "%s/bin"
1672 (directory-file-name python-shell-virtualenv-path
))
1675 (defun python-comint-output-filter-function (output)
1676 "Hook run after content is put into comint buffer.
1677 OUTPUT is a string with the contents of the buffer."
1678 (ansi-color-filter-apply output
))
1680 (defvar python-shell--parent-buffer nil
)
1682 (defvar python-shell-output-syntax-table
1683 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1684 (modify-syntax-entry ?
\' "." table
)
1685 (modify-syntax-entry ?
\" "." table
)
1686 (modify-syntax-entry ?\
( "." table
)
1687 (modify-syntax-entry ?\
[ "." table
)
1688 (modify-syntax-entry ?\
{ "." table
)
1689 (modify-syntax-entry ?\
) "." table
)
1690 (modify-syntax-entry ?\
] "." table
)
1691 (modify-syntax-entry ?\
} "." table
)
1693 "Syntax table for shell output.
1694 It makes parens and quotes be treated as punctuation chars.")
1696 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1697 "Major mode for Python inferior process.
1698 Runs a Python interpreter as a subprocess of Emacs, with Python
1699 I/O through an Emacs buffer. Variables
1700 `python-shell-interpreter' and `python-shell-interpreter-args'
1701 controls which Python interpreter is run. Variables
1702 `python-shell-prompt-regexp',
1703 `python-shell-prompt-output-regexp',
1704 `python-shell-prompt-block-regexp',
1705 `python-shell-enable-font-lock',
1706 `python-shell-completion-setup-code',
1707 `python-shell-completion-string-code',
1708 `python-shell-completion-module-string-code',
1709 `python-eldoc-setup-code', `python-eldoc-string-code',
1710 `python-ffap-setup-code' and `python-ffap-string-code' can
1711 customize this mode for different Python interpreters.
1713 You can also add additional setup code to be run at
1714 initialization of the interpreter via `python-shell-setup-codes'
1717 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1718 (and python-shell--parent-buffer
1719 (python-util-clone-local-variables python-shell--parent-buffer
))
1720 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1721 python-shell-prompt-regexp
1722 python-shell-prompt-block-regexp
1723 python-shell-prompt-pdb-regexp
))
1724 (setq mode-line-process
'(":%s"))
1725 (make-local-variable 'comint-output-filter-functions
)
1726 (add-hook 'comint-output-filter-functions
1727 'python-comint-output-filter-function
)
1728 (add-hook 'comint-output-filter-functions
1729 'python-pdbtrack-comint-output-filter-function
)
1730 (set (make-local-variable 'compilation-error-regexp-alist
)
1731 python-shell-compilation-regexp-alist
)
1732 (define-key inferior-python-mode-map
[remap complete-symbol
]
1733 'completion-at-point
)
1734 (add-hook 'completion-at-point-functions
1735 'python-shell-completion-complete-at-point nil
'local
)
1736 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1737 'python-shell-completion-complete-at-point
)
1738 (define-key inferior-python-mode-map
"\t"
1739 'python-shell-completion-complete-or-indent
)
1740 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1741 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1742 (make-local-variable 'python-shell-internal-last-output
)
1743 (when python-shell-enable-font-lock
1744 (set-syntax-table python-mode-syntax-table
)
1745 (set (make-local-variable 'font-lock-defaults
)
1746 '(python-font-lock-keywords nil nil nil nil
))
1747 (set (make-local-variable 'syntax-propertize-function
)
1749 ;; XXX: Unfortunately eval is needed here to make use of the
1750 ;; dynamic value of `comint-prompt-regexp'.
1751 `(syntax-propertize-rules
1752 (,comint-prompt-regexp
1755 comint-last-input-start end
'syntax-table
1756 python-shell-output-syntax-table
)
1757 ;; XXX: This might look weird, but it is the easiest
1758 ;; way to ensure font lock gets cleaned up before the
1759 ;; current prompt, which is needed for unclosed
1760 ;; strings to not mess up with current input.
1761 (font-lock-unfontify-region comint-last-input-start end
))))
1762 (,(python-rx string-delimiter
)
1764 (and (not (eq (get-text-property start
'field
) 'output
))
1765 (python-syntax-stringify)))))))))
1766 (compilation-shell-minor-mode 1))
1768 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1769 "Create a python shell comint buffer.
1770 CMD is the python command to be executed and PROC-NAME is the
1771 process name the comint buffer will get. After the comint buffer
1772 is created the `inferior-python-mode' is activated. When
1773 optional argument POP is non-nil the buffer is shown. When
1774 optional argument INTERNAL is non-nil this process is run on a
1775 buffer with a name that starts with a space, following the Emacs
1776 convention for temporary/internal buffers, and also makes sure
1777 the user is not queried for confirmation when the process is
1780 (let* ((proc-buffer-name
1781 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1782 (process-environment (python-shell-calculate-process-environment))
1783 (exec-path (python-shell-calculate-exec-path)))
1784 (when (not (comint-check-proc proc-buffer-name
))
1785 (let* ((cmdlist (split-string-and-unquote cmd
))
1786 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1787 (car cmdlist
) nil
(cdr cmdlist
)))
1788 (python-shell--parent-buffer (current-buffer))
1789 (process (get-buffer-process buffer
)))
1790 (with-current-buffer buffer
1791 (inferior-python-mode))
1792 (accept-process-output process
)
1793 (and pop
(pop-to-buffer buffer t
))
1794 (and internal
(set-process-query-on-exit-flag process nil
))))
1798 (defun run-python (cmd &optional dedicated show
)
1799 "Run an inferior Python process.
1800 Input and output via buffer named after
1801 `python-shell-buffer-name'. If there is a process already
1802 running in that buffer, just switch to it.
1804 With argument, allows you to define CMD so you can edit the
1805 command used to call the interpreter and define DEDICATED, so a
1806 dedicated process for the current buffer is open. When numeric
1807 prefix arg is other than 0 or 4 do not SHOW.
1809 Runs the hook `inferior-python-mode-hook' (after the
1810 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1811 process buffer for a list of commands.)"
1813 (if current-prefix-arg
1815 (read-string "Run Python: " (python-shell-parse-command))
1816 (y-or-n-p "Make dedicated process? ")
1817 (= (prefix-numeric-value current-prefix-arg
) 4))
1818 (list (python-shell-parse-command) nil t
)))
1819 (python-shell-make-comint
1820 cmd
(python-shell-get-process-name dedicated
) show
)
1823 (defun run-python-internal ()
1824 "Run an inferior Internal Python process.
1825 Input and output via buffer named after
1826 `python-shell-internal-buffer-name' and what
1827 `python-shell-internal-get-process-name' returns.
1829 This new kind of shell is intended to be used for generic
1830 communication related to defined configurations, the main
1831 difference with global or dedicated shells is that these ones are
1832 attached to a configuration, not a buffer. This means that can
1833 be used for example to retrieve the sys.path and other stuff,
1834 without messing with user shells. Note that
1835 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1836 are set to nil for these shells, so setup codes are not sent at
1838 (let ((python-shell-enable-font-lock nil
)
1839 (inferior-python-mode-hook nil
))
1841 (python-shell-make-comint
1842 (python-shell-parse-command)
1843 (python-shell-internal-get-process-name) nil t
))))
1845 (defun python-shell-get-process ()
1846 "Get inferior Python process for current buffer and return it."
1847 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1848 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1849 (global-proc-name (python-shell-get-process-name nil
))
1850 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1851 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1852 (global-running (comint-check-proc global-proc-buffer-name
)))
1853 ;; Always prefer dedicated
1854 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1855 (and global-running global-proc-buffer-name
)))))
1857 (defun python-shell-get-or-create-process ()
1858 "Get or create an inferior Python process for current buffer and return it."
1859 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1860 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1861 (global-proc-name (python-shell-get-process-name nil
))
1862 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1863 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1864 (global-running (comint-check-proc global-proc-buffer-name
))
1865 (current-prefix-arg 16))
1866 (when (and (not dedicated-running
) (not global-running
))
1867 (if (call-interactively 'run-python
)
1868 (setq dedicated-running t
)
1869 (setq global-running t
)))
1870 ;; Always prefer dedicated
1871 (get-buffer-process (if dedicated-running
1872 dedicated-proc-buffer-name
1873 global-proc-buffer-name
))))
1875 (defvar python-shell-internal-buffer nil
1876 "Current internal shell buffer for the current buffer.
1877 This is really not necessary at all for the code to work but it's
1878 there for compatibility with CEDET.")
1880 (defvar python-shell-internal-last-output nil
1881 "Last output captured by the internal shell.
1882 This is really not necessary at all for the code to work but it's
1883 there for compatibility with CEDET.")
1885 (defun python-shell-internal-get-or-create-process ()
1886 "Get or create an inferior Internal Python process."
1887 (let* ((proc-name (python-shell-internal-get-process-name))
1888 (proc-buffer-name (format " *%s*" proc-name
)))
1889 (when (not (process-live-p proc-name
))
1890 (run-python-internal)
1891 (setq python-shell-internal-buffer proc-buffer-name
)
1892 ;; XXX: Why is this `sit-for' needed?
1893 ;; `python-shell-make-comint' calls `accept-process-output'
1894 ;; already but it is not helping to get proper output on
1895 ;; 'gnu/linux when the internal shell process is not running and
1896 ;; a call to `python-shell-internal-send-string' is issued.
1898 (get-buffer-process proc-buffer-name
)))
1900 (define-obsolete-function-alias
1901 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1903 (define-obsolete-variable-alias
1904 'python-buffer
'python-shell-internal-buffer
"24.3")
1906 (define-obsolete-variable-alias
1907 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1909 (defun python-shell-send-string (string &optional process msg
)
1910 "Send STRING to inferior Python PROCESS.
1911 When MSG is non-nil messages the first line of STRING."
1912 (interactive "sPython command: ")
1913 (let ((process (or process
(python-shell-get-or-create-process)))
1914 (lines (split-string string
"\n" t
)))
1915 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1916 (if (> (length lines
) 1)
1917 (let* ((temporary-file-directory
1918 (if (file-remote-p default-directory
)
1919 (concat (file-remote-p default-directory
) "/tmp")
1920 temporary-file-directory
))
1921 (temp-file-name (make-temp-file "py"))
1922 (file-name (or (buffer-file-name) temp-file-name
)))
1923 (with-temp-file temp-file-name
1925 (delete-trailing-whitespace))
1926 (python-shell-send-file file-name process temp-file-name
))
1927 (comint-send-string process string
)
1928 (when (or (not (string-match "\n$" string
))
1929 (string-match "\n[ \t].*\n?$" string
))
1930 (comint-send-string process
"\n")))))
1932 (defvar python-shell-output-filter-in-progress nil
)
1933 (defvar python-shell-output-filter-buffer nil
)
1935 (defun python-shell-output-filter (string)
1936 "Filter used in `python-shell-send-string-no-output' to grab output.
1937 STRING is the output received to this point from the process.
1938 This filter saves received output from the process in
1939 `python-shell-output-filter-buffer' and stops receiving it after
1940 detecting a prompt at the end of the buffer."
1942 string
(ansi-color-filter-apply string
)
1943 python-shell-output-filter-buffer
1944 (concat python-shell-output-filter-buffer string
))
1946 ;; XXX: It seems on OSX an extra carriage return is attached
1947 ;; at the end of output, this handles that too.
1948 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1949 python-shell-prompt-regexp
1950 python-shell-prompt-block-regexp
1951 python-shell-prompt-pdb-regexp
)
1952 python-shell-output-filter-buffer
)
1953 ;; Output ends when `python-shell-output-filter-buffer' contains
1954 ;; the prompt attached at the end of it.
1955 (setq python-shell-output-filter-in-progress nil
1956 python-shell-output-filter-buffer
1957 (substring python-shell-output-filter-buffer
1958 0 (match-beginning 0)))
1959 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1960 (string-match (concat "^" python-shell-prompt-output-regexp
)
1961 python-shell-output-filter-buffer
))
1962 ;; Some shells, like iPython might append a prompt before the
1963 ;; output, clean that.
1964 (setq python-shell-output-filter-buffer
1965 (substring python-shell-output-filter-buffer
(match-end 0)))))
1968 (defun python-shell-send-string-no-output (string &optional process msg
)
1969 "Send STRING to PROCESS and inhibit output.
1970 When MSG is non-nil messages the first line of STRING. Return
1972 (let ((process (or process
(python-shell-get-or-create-process)))
1973 (comint-preoutput-filter-functions
1974 '(python-shell-output-filter))
1975 (python-shell-output-filter-in-progress t
)
1979 (python-shell-send-string string process msg
)
1980 (while python-shell-output-filter-in-progress
1981 ;; `python-shell-output-filter' takes care of setting
1982 ;; `python-shell-output-filter-in-progress' to NIL after it
1983 ;; detects end of output.
1984 (accept-process-output process
))
1986 python-shell-output-filter-buffer
1987 (setq python-shell-output-filter-buffer nil
)))
1988 (with-current-buffer (process-buffer process
)
1989 (comint-interrupt-subjob)))))
1991 (defun python-shell-internal-send-string (string)
1992 "Send STRING to the Internal Python interpreter.
1993 Returns the output. See `python-shell-send-string-no-output'."
1994 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1995 ;; updated to support this new mode.
1996 (setq python-shell-internal-last-output
1997 (python-shell-send-string-no-output
1998 ;; Makes this function compatible with the old
1999 ;; python-send-receive. (At least for CEDET).
2000 (replace-regexp-in-string "_emacs_out +" "" string
)
2001 (python-shell-internal-get-or-create-process) nil
)))
2003 (define-obsolete-function-alias
2004 'python-send-receive
'python-shell-internal-send-string
"24.3")
2006 (define-obsolete-function-alias
2007 'python-send-string
'python-shell-internal-send-string
"24.3")
2009 (defun python-shell-send-region (start end
)
2010 "Send the region delimited by START and END to inferior Python process."
2012 (python-shell-send-string (buffer-substring start end
) nil t
))
2014 (defun python-shell-send-buffer (&optional arg
)
2015 "Send the entire buffer to inferior Python process.
2016 With prefix ARG allow execution of code inside blocks delimited
2017 by \"if __name__== '__main__':\""
2021 (let ((str (buffer-substring (point-min) (point-max))))
2024 (setq str
(replace-regexp-in-string
2025 (python-rx if-name-main
)
2026 "if __name__ == '__main__ ':" str
)))
2027 (python-shell-send-string str
))))
2029 (defun python-shell-send-defun (arg)
2030 "Send the current defun to inferior Python process.
2031 When argument ARG is non-nil do not include decorators."
2034 (python-shell-send-region
2037 (while (and (or (python-nav-beginning-of-defun)
2038 (beginning-of-line 1))
2039 (> (current-indentation) 0)))
2041 (while (and (forward-line -
1)
2042 (looking-at (python-rx decorator
))))
2046 (or (python-nav-end-of-defun)
2050 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2051 "Send FILE-NAME to inferior Python PROCESS.
2052 If TEMP-FILE-NAME is passed then that file is used for processing
2053 instead, while internally the shell will continue to use
2055 (interactive "fFile to send: ")
2056 (let* ((process (or process
(python-shell-get-or-create-process)))
2057 (temp-file-name (when temp-file-name
2059 (or (file-remote-p temp-file-name
'localname
)
2061 (file-name (or (when file-name
2063 (or (file-remote-p file-name
'localname
)
2066 (when (not file-name
)
2067 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2068 (python-shell-send-string
2070 (concat "__pyfile = open('''%s''');"
2071 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2073 (or temp-file-name file-name
) file-name
)
2076 (defun python-shell-switch-to-shell ()
2077 "Switch to inferior Python process buffer."
2079 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2081 (defun python-shell-send-setup-code ()
2082 "Send all setup code for shell.
2083 This function takes the list of setup code to send from the
2084 `python-shell-setup-codes' list."
2085 (let ((process (get-buffer-process (current-buffer))))
2086 (dolist (code python-shell-setup-codes
)
2088 (message "Sent %s" code
)
2089 (python-shell-send-string
2090 (symbol-value code
) process
)))))
2092 (add-hook 'inferior-python-mode-hook
2093 #'python-shell-send-setup-code
)
2096 ;;; Shell completion
2098 (defcustom python-shell-completion-setup-code
2102 def __COMPLETER_all_completions(text): []
2105 readline.set_completer(rlcompleter.Completer().complete)
2106 def __COMPLETER_all_completions(text):
2112 res = readline.get_completer()(text, i)
2115 completions.append(res)
2119 "Code used to setup completion in inferior Python processes."
2123 (defcustom python-shell-completion-string-code
2124 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2125 "Python code used to get a string of completions separated by semicolons."
2129 (defcustom python-shell-completion-module-string-code
""
2130 "Python code used to get completions separated by semicolons for imports.
2132 For IPython v0.11, add the following line to
2133 `python-shell-completion-setup-code':
2135 from IPython.core.completerlib import module_completion
2137 and use the following as the value of this variable:
2139 ';'.join(module_completion('''%s'''))\n"
2143 (defcustom python-shell-completion-pdb-string-code
2144 "';'.join(globals().keys() + locals().keys())"
2145 "Python code used to get completions separated by semicolons for [i]pdb."
2149 (defun python-shell-completion-get-completions (process line input
)
2150 "Do completion at point for PROCESS.
2151 LINE is used to detect the context on how to complete given
2154 ;; Get the last prompt for the inferior process
2155 ;; buffer. This is used for the completion code selection
2157 (with-current-buffer (process-buffer process
)
2158 (buffer-substring-no-properties
2159 (overlay-start comint-last-prompt-overlay
)
2160 (overlay-end comint-last-prompt-overlay
))))
2162 ;; Check whether a prompt matches a pdb string, an import
2163 ;; statement or just the standard prompt and use the
2164 ;; correct python-shell-completion-*-code string
2165 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2167 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2170 (length python-shell-completion-module-string-code
) 0)
2172 (concat "^" python-shell-prompt-regexp
) prompt
)
2173 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2176 (concat "^" python-shell-prompt-regexp
) prompt
)
2180 (pcase completion-context
2181 (`pdb python-shell-completion-pdb-string-code
)
2182 (`import python-shell-completion-module-string-code
)
2183 (`default python-shell-completion-string-code
)
2186 (if (eq completion-context
'import
)
2187 (replace-regexp-in-string "^[ \t]+" "" line
)
2189 (and completion-code
2190 (> (length input
) 0)
2191 (with-current-buffer (process-buffer process
)
2192 (let ((completions (python-shell-send-string-no-output
2193 (format completion-code input
) process
)))
2194 (and (> (length completions
) 2)
2195 (split-string completions
2196 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2198 (defun python-shell-completion-complete-at-point (&optional process
)
2199 "Perform completion at point in inferior Python.
2200 Optional argument PROCESS forces completions to be retrieved
2201 using that one instead of current buffer's process."
2202 (setq process
(or process
(get-buffer-process (current-buffer))))
2205 (with-syntax-table python-dotty-syntax-table
2206 (let* ((paren-depth (car (syntax-ppss)))
2207 (syntax-string "w_")
2208 (syntax-list (string-to-syntax syntax-string
)))
2209 ;; Stop scanning for the beginning of the completion
2210 ;; subject after the char before point matches a
2213 (car (syntax-after (1- (point)))) syntax-list
)
2214 (skip-syntax-backward syntax-string
)
2215 (when (or (equal (char-before) ?\
))
2216 (equal (char-before) ?
\"))
2219 ;; honor initial paren depth
2220 (> (car (syntax-ppss)) paren-depth
)
2221 (python-syntax-context 'string
))
2226 (completion-table-dynamic
2228 #'python-shell-completion-get-completions
2229 process
(buffer-substring-no-properties
2230 (line-beginning-position) end
))))))
2232 (defun python-shell-completion-complete-or-indent ()
2233 "Complete or indent depending on the context.
2234 If content before pointer is all whitespace indent. If not try
2237 (if (string-match "^[[:space:]]*$"
2238 (buffer-substring (comint-line-beginning-position)
2240 (indent-for-tab-command)
2241 (completion-at-point)))
2244 ;;; PDB Track integration
2246 (defcustom python-pdbtrack-activate t
2247 "Non-nil makes python shell enable pdbtracking."
2252 (defcustom python-pdbtrack-stacktrace-info-regexp
2253 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2254 "Regular Expression matching stacktrace information.
2255 Used to extract the current line and module being inspected."
2260 (defvar python-pdbtrack-tracked-buffer nil
2261 "Variable containing the value of the current tracked buffer.
2262 Never set this variable directly, use
2263 `python-pdbtrack-set-tracked-buffer' instead.")
2265 (defvar python-pdbtrack-buffers-to-kill nil
2266 "List of buffers to be deleted after tracking finishes.")
2268 (defun python-pdbtrack-set-tracked-buffer (file-name)
2269 "Set the buffer for FILE-NAME as the tracked buffer.
2270 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2271 Returns the tracked buffer."
2272 (let ((file-buffer (get-file-buffer file-name
)))
2274 (setq python-pdbtrack-tracked-buffer file-buffer
)
2275 (setq file-buffer
(find-file-noselect file-name
))
2276 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2277 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2280 (defun python-pdbtrack-comint-output-filter-function (output)
2281 "Move overlay arrow to current pdb line in tracked buffer.
2282 Argument OUTPUT is a string with the output from the comint process."
2283 (when (and python-pdbtrack-activate
(not (string= output
"")))
2284 (let* ((full-output (ansi-color-filter-apply
2285 (buffer-substring comint-last-input-end
(point-max))))
2289 (insert full-output
)
2290 (goto-char (point-min))
2291 ;; OK, this sucked but now it became a cool hack. The
2292 ;; stacktrace information normally is on the first line
2293 ;; but in some cases (like when doing a step-in) it is
2295 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2298 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2299 (setq line-number
(string-to-number
2300 (match-string-no-properties 2)))
2301 (match-string-no-properties 1)))))
2302 (if (and file-name line-number
)
2303 (let* ((tracked-buffer
2304 (python-pdbtrack-set-tracked-buffer file-name
))
2305 (shell-buffer (current-buffer))
2306 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2307 (tracked-buffer-line-pos))
2308 (with-current-buffer tracked-buffer
2309 (set (make-local-variable 'overlay-arrow-string
) "=>")
2310 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2311 (setq tracked-buffer-line-pos
(progn
2312 (goto-char (point-min))
2313 (forward-line (1- line-number
))
2315 (when tracked-buffer-window
2317 tracked-buffer-window tracked-buffer-line-pos
))
2318 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2319 (pop-to-buffer tracked-buffer
)
2320 (switch-to-buffer-other-window shell-buffer
))
2321 (when python-pdbtrack-tracked-buffer
2322 (with-current-buffer python-pdbtrack-tracked-buffer
2323 (set-marker overlay-arrow-position nil
))
2324 (mapc #'(lambda (buffer)
2325 (ignore-errors (kill-buffer buffer
)))
2326 python-pdbtrack-buffers-to-kill
)
2327 (setq python-pdbtrack-tracked-buffer nil
2328 python-pdbtrack-buffers-to-kill nil
)))))
2332 ;;; Symbol completion
2334 (defun python-completion-complete-at-point ()
2335 "Complete current symbol at point.
2336 For this to work the best as possible you should call
2337 `python-shell-send-buffer' from time to time so context in
2338 inferior python process is updated properly."
2339 (let ((process (python-shell-get-process)))
2341 (error "Completion needs an inferior Python process running")
2342 (python-shell-completion-complete-at-point process
))))
2344 (add-to-list 'debug-ignored-errors
2345 "^Completion needs an inferior Python process running.")
2350 (defcustom python-fill-comment-function
'python-fill-comment
2351 "Function to fill comments.
2352 This is the function used by `python-fill-paragraph' to
2357 (defcustom python-fill-string-function
'python-fill-string
2358 "Function to fill strings.
2359 This is the function used by `python-fill-paragraph' to
2364 (defcustom python-fill-decorator-function
'python-fill-decorator
2365 "Function to fill decorators.
2366 This is the function used by `python-fill-paragraph' to
2371 (defcustom python-fill-paren-function
'python-fill-paren
2372 "Function to fill parens.
2373 This is the function used by `python-fill-paragraph' to
2378 (defcustom python-fill-docstring-style
'pep-257
2379 "Style used to fill docstrings.
2380 This affects `python-fill-string' behavior with regards to
2381 triple quotes positioning.
2383 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2384 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2385 position and will treat docstrings a normal string, any other
2386 value may result in one of the following docstring styles:
2391 Process foo, return bar.
2395 Process foo, return bar.
2397 If processing fails throw ProcessingError.
2402 \"\"\"Process foo, return bar.\"\"\"
2405 Process foo, return bar.
2407 If processing fails throw ProcessingError.
2413 \"\"\"Process foo, return bar.\"\"\"
2415 \"\"\"Process foo, return bar.
2417 If processing fails throw ProcessingError.
2423 \"\"\"Process foo, return bar.\"\"\"
2425 \"\"\"Process foo, return bar.
2427 If processing fails throw ProcessingError.
2432 \"\"\"Process foo, return bar.\"\"\"
2435 Process foo, return bar.
2437 If processing fails throw ProcessingError.
2440 (const :tag
"Don't format docstrings" nil
)
2441 (const :tag
"Django's coding standards style." django
)
2442 (const :tag
"One newline and start and Two at end style." onetwo
)
2443 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2444 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2445 (const :tag
"Symmetric style." symmetric
))
2448 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2450 (defun python-fill-paragraph (&optional justify
)
2451 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2452 If any of the current line is in or at the end of a multi-line string,
2453 fill the string or the paragraph of it that point is in, preserving
2454 the string's indentation.
2455 Optional argument JUSTIFY defines if the paragraph should be justified."
2460 ((python-syntax-context 'comment
)
2461 (funcall python-fill-comment-function justify
))
2462 ;; Strings/Docstrings
2463 ((save-excursion (or (python-syntax-context 'string
)
2464 (equal (string-to-syntax "|")
2465 (syntax-after (point)))))
2466 (funcall python-fill-string-function justify
))
2468 ((equal (char-after (save-excursion
2469 (python-nav-beginning-of-statement))) ?
@)
2470 (funcall python-fill-decorator-function justify
))
2472 ((or (python-syntax-context 'paren
)
2473 (looking-at (python-rx open-paren
))
2475 (skip-syntax-forward "^(" (line-end-position))
2476 (looking-at (python-rx open-paren
))))
2477 (funcall python-fill-paren-function justify
))
2480 (defun python-fill-comment (&optional justify
)
2481 "Comment fill function for `python-fill-paragraph'.
2482 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2483 (fill-comment-paragraph justify
))
2485 (defun python-fill-string (&optional justify
)
2486 "String fill function for `python-fill-paragraph'.
2487 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2488 (let* ((marker (point-marker))
2490 (let ((m (make-marker)))
2491 (setf (marker-position m
)
2492 (or (python-syntax-context 'string
)
2493 (and (equal (string-to-syntax "|")
2494 (syntax-after (point)))
2496 (num-quotes (python-syntax-count-quotes
2497 (char-after str-start-pos
) str-start-pos
))
2500 (goto-char (+ str-start-pos num-quotes
))
2501 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2502 (goto-char (point-max)))
2505 ;; Docstring styles may vary for oneliners and multi-liners.
2506 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2508 (pcase python-fill-docstring-style
2509 ;; delimiters-style is a cons cell with the form
2510 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2511 ;; is NIL means to not add any newlines for start or end
2512 ;; of docstring. See `python-fill-docstring-style' for a
2513 ;; graphic idea of each style.
2514 (`django
(cons 1 1))
2515 (`onetwo
(and multi-line-p
(cons 1 2)))
2516 (`pep-257
(and multi-line-p
(cons nil
2)))
2517 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
2518 (`symmetric
(and multi-line-p
(cons 1 1)))))
2519 (docstring-p (save-excursion
2520 ;; Consider docstrings those strings which
2521 ;; start on a line by themselves.
2522 (python-nav-beginning-of-statement)
2523 (and (= (point) str-start-pos
))))
2524 (fill-paragraph-function))
2526 (narrow-to-region str-start-pos str-end-pos
)
2527 (fill-paragraph justify
))
2529 (when (and docstring-p python-fill-docstring-style
)
2530 ;; Add the number of newlines indicated by the selected style
2531 ;; at the start of the docstring.
2532 (goto-char (+ str-start-pos num-quotes
))
2533 (delete-region (point) (progn
2534 (skip-syntax-forward "> ")
2536 (and (car delimiters-style
)
2537 (or (newline (car delimiters-style
)) t
)
2538 ;; Indent only if a newline is added.
2539 (indent-according-to-mode))
2540 ;; Add the number of newlines indicated by the selected style
2541 ;; at the end of the docstring.
2542 (goto-char (if (not (= str-end-pos
(point-max)))
2543 (- str-end-pos num-quotes
)
2545 (delete-region (point) (progn
2546 (skip-syntax-backward "> ")
2548 (and (cdr delimiters-style
)
2549 ;; Add newlines only if string ends.
2550 (not (= str-end-pos
(point-max)))
2551 (or (newline (cdr delimiters-style
)) t
)
2552 ;; Again indent only if a newline is added.
2553 (indent-according-to-mode))))) t
)
2555 (defun python-fill-decorator (&optional justify
)
2556 "Decorator fill function for `python-fill-paragraph'.
2557 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2560 (defun python-fill-paren (&optional justify
)
2561 "Paren fill function for `python-fill-paragraph'.
2562 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2564 (narrow-to-region (progn
2565 (while (python-syntax-context 'paren
)
2566 (goto-char (1- (point-marker))))
2568 (line-beginning-position))
2570 (when (not (python-syntax-context 'paren
))
2572 (when (not (python-syntax-context 'paren
))
2573 (skip-syntax-backward "^)")))
2574 (while (python-syntax-context 'paren
)
2575 (goto-char (1+ (point-marker))))
2577 (let ((paragraph-start "\f\\|[ \t]*$")
2578 (paragraph-separate ",")
2579 (fill-paragraph-function))
2580 (goto-char (point-min))
2581 (fill-paragraph justify
))
2584 (python-indent-line)
2585 (goto-char (line-end-position)))) t
)
2590 (defcustom python-skeleton-autoinsert nil
2591 "Non-nil means template skeletons will be automagically inserted.
2592 This happens when pressing \"if<SPACE>\", for example, to prompt for
2598 (define-obsolete-variable-alias
2599 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2601 (defvar python-skeleton-available
'()
2602 "Internal list of available skeletons.")
2604 (define-abbrev-table 'python-mode-abbrev-table
()
2605 "Abbrev table for Python mode."
2607 ;; Allow / inside abbrevs.
2608 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2609 ;; Only expand in code.
2610 :enable-function
(lambda ()
2612 (not (python-syntax-comment-or-string-p))
2613 python-skeleton-autoinsert
)))
2615 (defmacro python-skeleton-define
(name doc
&rest skel
)
2616 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2617 The skeleton will be bound to python-skeleton-NAME and will
2618 be added to `python-mode-abbrev-table'."
2619 (declare (indent 2))
2620 (let* ((name (symbol-name name
))
2621 (function-name (intern (concat "python-skeleton-" name
))))
2623 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2625 (setq python-skeleton-available
2626 (cons ',function-name python-skeleton-available
))
2627 (define-skeleton ,function-name
2629 (format "Insert %s statement." name
))
2632 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2633 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2634 The skeleton will be bound to python-skeleton-NAME."
2635 (declare (indent 2))
2636 (let* ((name (symbol-name name
))
2637 (function-name (intern (concat "python-skeleton--" name
)))
2639 "Add '%s' clause? " name
)))
2642 `(< ,(format "%s:" name
) \n \n
2644 `(define-skeleton ,function-name
2646 (format "Auxiliary skeleton for %s statement." name
))
2648 (unless (y-or-n-p ,msg
)
2652 (python-define-auxiliary-skeleton else nil
)
2654 (python-define-auxiliary-skeleton except nil
)
2656 (python-define-auxiliary-skeleton finally nil
)
2658 (python-skeleton-define if nil
2662 ("other condition, %s: "
2666 '(python-skeleton--else) | ^
)
2668 (python-skeleton-define while nil
2672 '(python-skeleton--else) | ^
)
2674 (python-skeleton-define for nil
2678 '(python-skeleton--else) | ^
)
2680 (python-skeleton-define try nil
2686 "except " str
":" \n
2689 '(python-skeleton--except)
2690 '(python-skeleton--else)
2691 '(python-skeleton--finally) | ^
)
2693 (python-skeleton-define def nil
2695 "def " str
"(" ("Parameter, %s: "
2696 (unless (equal ?\
( (char-before)) ", ")
2698 "\"\"\"" -
"\"\"\"" \n
2701 (python-skeleton-define class nil
2703 "class " str
"(" ("Inheritance, %s: "
2704 (unless (equal ?\
( (char-before)) ", ")
2708 "\"\"\"" -
"\"\"\"" \n
2711 (defun python-skeleton-add-menu-items ()
2712 "Add menu items to Python->Skeletons menu."
2713 (let ((skeletons (sort python-skeleton-available
'string
<))
2715 (dolist (skeleton skeletons
)
2717 nil
'("Python" "Skeletons")
2719 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
2724 (defcustom python-ffap-setup-code
2725 "def __FFAP_get_module_path(module):
2728 path = __import__(module).__file__
2729 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2734 "Python code to get a module path."
2738 (defcustom python-ffap-string-code
2739 "__FFAP_get_module_path('''%s''')\n"
2740 "Python code used to get a string with the path of a module."
2744 (defun python-ffap-module-path (module)
2745 "Function for `ffap-alist' to return path for MODULE."
2747 (and (eq major-mode
'inferior-python-mode
)
2748 (get-buffer-process (current-buffer)))
2749 (python-shell-get-process))))
2753 (python-shell-send-string-no-output
2754 (format python-ffap-string-code module
) process
)))
2756 (substring-no-properties module-file
1 -
1))))))
2758 (eval-after-load "ffap"
2760 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2761 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2766 (defcustom python-check-command
2768 "Command used to check a Python file."
2772 (defcustom python-check-buffer-name
2773 "*Python check: %s*"
2774 "Buffer name used for check commands."
2778 (defvar python-check-custom-command nil
2781 (defun python-check (command)
2782 "Check a Python file (default current buffer's file).
2783 Runs COMMAND, a shell command, as if by `compile'. See
2784 `python-check-command' for the default."
2786 (list (read-string "Check command: "
2787 (or python-check-custom-command
2788 (concat python-check-command
" "
2789 (shell-quote-argument
2791 (let ((name (buffer-file-name)))
2793 (file-name-nondirectory name
)))
2795 (setq python-check-custom-command command
)
2796 (save-some-buffers (not compilation-ask-about-save
) nil
)
2797 (let ((process-environment (python-shell-calculate-process-environment))
2798 (exec-path (python-shell-calculate-exec-path)))
2799 (compilation-start command nil
2801 (format python-check-buffer-name command
)))))
2806 (defcustom python-eldoc-setup-code
2807 "def __PYDOC_get_help(obj):
2810 if hasattr(obj, 'startswith'):
2811 obj = eval(obj, globals())
2812 doc = inspect.getdoc(obj)
2813 if not doc and callable(obj):
2815 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2816 target = obj.__init__
2822 args = inspect.formatargspec(
2823 *inspect.getargspec(target)
2826 doc = '{objtype} {name}{args}'.format(
2827 objtype=objtype, name=name, args=args
2830 doc = doc.splitlines()[0]
2837 "Python code to setup documentation retrieval."
2841 (defcustom python-eldoc-string-code
2842 "__PYDOC_get_help('''%s''')\n"
2843 "Python code used to get a string with the documentation of an object."
2847 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2848 "Internal implementation to get documentation at point.
2849 If not FORCE-INPUT is passed then what
2850 `python-info-current-symbol' returns will be used. If not
2851 FORCE-PROCESS is passed what `python-shell-get-process' returns
2853 (let ((process (or force-process
(python-shell-get-process))))
2855 (error "Eldoc needs an inferior Python process running")
2856 (let ((input (or force-input
2857 (python-info-current-symbol t
))))
2859 (python-shell-send-string-no-output
2860 (format python-eldoc-string-code input
)
2863 (defun python-eldoc-function ()
2864 "`eldoc-documentation-function' for Python.
2865 For this to work the best as possible you should call
2866 `python-shell-send-buffer' from time to time so context in
2867 inferior python process is updated properly."
2868 (python-eldoc--get-doc-at-point))
2870 (defun python-eldoc-at-point (symbol)
2871 "Get help on SYMBOL using `help'.
2872 Interactively, prompt for symbol."
2874 (let ((symbol (python-info-current-symbol t
))
2875 (enable-recursive-minibuffers t
))
2876 (list (read-string (if symbol
2877 (format "Describe symbol (default %s): " symbol
)
2878 "Describe symbol: ")
2880 (message (python-eldoc--get-doc-at-point symbol
)))
2882 (add-to-list 'debug-ignored-errors
2883 "^Eldoc needs an inferior Python process running.")
2888 (defun python-imenu-prev-index-position ()
2889 "Python mode's `imenu-prev-index-position-function'."
2891 (while (and (setq found
2892 (re-search-backward python-nav-beginning-of-defun-regexp nil t
))
2893 (not (python-info-looking-at-beginning-of-defun))))
2895 (python-info-looking-at-beginning-of-defun)
2896 (python-info-current-defun))))
2901 (defun python-info-current-defun (&optional include-type
)
2902 "Return name of surrounding function with Python compatible dotty syntax.
2903 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2904 This function is compatible to be used as
2905 `add-log-current-defun-function' since it returns nil if point is
2906 not inside a defun."
2912 (starting-indentation
2915 (python-nav-beginning-of-defun 1)
2916 ;; This extra number is just for checking code
2917 ;; against indentation to work well on first run.
2918 (+ (current-indentation) 4))))
2919 (starting-point (point)))
2920 ;; Check point is inside a defun.
2921 (when (and starting-indentation
2924 (python-nav-end-of-defun)
2927 (while (python-nav-beginning-of-defun 1)
2928 (when (< (current-indentation) starting-indentation
)
2929 (setq starting-indentation
(current-indentation))
2932 (if (not include-type
)
2933 (match-string-no-properties 1)
2934 (mapconcat 'identity
2936 (match-string-no-properties 0)) " "))
2938 (and (= (current-indentation) 0) (throw 'exit t
)))))
2940 (mapconcat (lambda (string) string
) names
"."))))))
2942 (defun python-info-current-symbol (&optional replace-self
)
2943 "Return current symbol using dotty syntax.
2944 With optional argument REPLACE-SELF convert \"self\" to current
2947 (and (not (python-syntax-comment-or-string-p))
2948 (with-syntax-table python-dotty-syntax-table
2949 (let ((sym (symbol-at-point)))
2951 (substring-no-properties (symbol-name sym
))))))))
2953 (if (not replace-self
)
2955 (let ((current-defun (python-info-current-defun)))
2956 (if (not current-defun
)
2958 (replace-regexp-in-string
2959 (python-rx line-start word-start
"self" word-end ?.
)
2961 (mapconcat 'identity
2962 (butlast (split-string current-defun
"\\."))
2966 (defun python-info-statement-starts-block-p ()
2967 "Return non-nil if current statement opens a block."
2969 (python-nav-beginning-of-statement)
2970 (looking-at (python-rx block-start
))))
2972 (defun python-info-statement-ends-block-p ()
2973 "Return non-nil if point is at end of block."
2974 (let ((end-of-block-pos (save-excursion
2975 (python-nav-end-of-block)))
2976 (end-of-statement-pos (save-excursion
2977 (python-nav-end-of-statement))))
2978 (and end-of-block-pos end-of-statement-pos
2979 (= end-of-block-pos end-of-statement-pos
))))
2981 (defun python-info-beginning-of-statement-p ()
2982 "Return non-nil if point is at beginning of statement."
2983 (= (point) (save-excursion
2984 (python-nav-beginning-of-statement)
2987 (defun python-info-end-of-statement-p ()
2988 "Return non-nil if point is at end of statement."
2989 (= (point) (save-excursion
2990 (python-nav-end-of-statement)
2993 (defun python-info-beginning-of-block-p ()
2994 "Return non-nil if point is at beginning of block."
2995 (and (python-info-beginning-of-statement-p)
2996 (python-info-statement-starts-block-p)))
2998 (defun python-info-end-of-block-p ()
2999 "Return non-nil if point is at end of block."
3000 (and (python-info-end-of-statement-p)
3001 (python-info-statement-ends-block-p)))
3003 (defun python-info-closing-block ()
3004 "Return the point of the block the current line closes."
3005 (let ((closing-word (save-excursion
3006 (back-to-indentation)
3008 (indentation (current-indentation)))
3009 (when (member closing-word python-indent-dedenters
)
3012 (while (and (> (current-indentation) indentation
)
3014 (not (back-to-indentation))
3016 (back-to-indentation)
3018 ((not (equal indentation
(current-indentation))) nil
)
3019 ((string= closing-word
"elif")
3020 (when (member (current-word) '("if" "elif"))
3022 ((string= closing-word
"else")
3023 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3025 ((string= closing-word
"except")
3026 (when (member (current-word) '("try"))
3028 ((string= closing-word
"finally")
3029 (when (member (current-word) '("except" "else"))
3030 (point-marker))))))))
3032 (defun python-info-closing-block-message (&optional closing-block-point
)
3033 "Message the contents of the block the current line closes.
3034 With optional argument CLOSING-BLOCK-POINT use that instead of
3035 recalculating it calling `python-info-closing-block'."
3036 (let ((point (or closing-block-point
(python-info-closing-block))))
3040 (message "Closes %s" (save-excursion
3042 (back-to-indentation)
3044 (point) (line-end-position))))))))
3046 (defun python-info-line-ends-backslash-p (&optional line-number
)
3047 "Return non-nil if current line ends with backslash.
3048 With optional argument LINE-NUMBER, check that line instead."
3053 (goto-char line-number
))
3054 (while (and (not (eobp))
3055 (goto-char (line-end-position))
3056 (python-syntax-context 'paren
)
3057 (not (equal (char-before (point)) ?
\\)))
3059 (when (equal (char-before) ?
\\)
3062 (defun python-info-beginning-of-backslash (&optional line-number
)
3063 "Return the point where the backslashed line start.
3064 Optional argument LINE-NUMBER forces the line number to check against."
3069 (goto-char line-number
))
3070 (when (python-info-line-ends-backslash-p)
3071 (while (save-excursion
3072 (goto-char (line-beginning-position))
3073 (python-syntax-context 'paren
))
3075 (back-to-indentation)
3078 (defun python-info-continuation-line-p ()
3079 "Check if current line is continuation of another.
3080 When current line is continuation of another return the point
3081 where the continued line ends."
3085 (let* ((context-type (progn
3086 (back-to-indentation)
3087 (python-syntax-context-type)))
3088 (line-start (line-number-at-pos))
3089 (context-start (when context-type
3090 (python-syntax-context context-type
))))
3091 (cond ((equal context-type
'paren
)
3092 ;; Lines inside a paren are always a continuation line
3093 ;; (except the first one).
3094 (python-util-forward-comment -
1)
3096 ((member context-type
'(string comment
))
3097 ;; move forward an roll again
3098 (goto-char context-start
)
3099 (python-util-forward-comment)
3100 (python-info-continuation-line-p))
3102 ;; Not within a paren, string or comment, the only way
3103 ;; we are dealing with a continuation line is that
3104 ;; previous line contains a backslash, and this can
3105 ;; only be the previous line from current
3106 (back-to-indentation)
3107 (python-util-forward-comment -
1)
3108 (when (and (equal (1- line-start
) (line-number-at-pos))
3109 (python-info-line-ends-backslash-p))
3110 (point-marker))))))))
3112 (defun python-info-block-continuation-line-p ()
3113 "Return non-nil if current line is a continuation of a block."
3115 (when (python-info-continuation-line-p)
3117 (back-to-indentation)
3118 (when (looking-at (python-rx block-start
))
3121 (defun python-info-assignment-continuation-line-p ()
3122 "Check if current line is a continuation of an assignment.
3123 When current line is continuation of another with an assignment
3124 return the point of the first non-blank character after the
3127 (when (python-info-continuation-line-p)
3129 (back-to-indentation)
3130 (when (and (not (looking-at (python-rx block-start
)))
3131 (and (re-search-forward (python-rx not-simple-operator
3133 not-simple-operator
)
3134 (line-end-position) t
)
3135 (not (python-syntax-context-type))))
3136 (skip-syntax-forward "\s")
3139 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3140 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3141 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3143 (beginning-of-line 1)
3144 (looking-at python-nav-beginning-of-defun-regexp
))))
3146 (defun python-info-current-line-comment-p ()
3147 "Check if current line is a comment line."
3148 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3150 (defun python-info-current-line-empty-p ()
3151 "Check if current line is empty, ignoring whitespace."
3153 (beginning-of-line 1)
3155 (python-rx line-start
(* whitespace
)
3156 (group (* not-newline
))
3157 (* whitespace
) line-end
))
3158 (string-equal "" (match-string-no-properties 1))))
3161 ;;; Utility functions
3163 (defun python-util-position (item seq
)
3164 "Find the first occurrence of ITEM in SEQ.
3165 Return the index of the matching item, or nil if not found."
3166 (let ((member-result (member item seq
)))
3168 (- (length seq
) (length member-result
)))))
3170 ;; Stolen from org-mode
3171 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3172 "Clone local variables from FROM-BUFFER.
3173 Optional argument REGEXP selects variables to clone and defaults
3177 (and (symbolp (car pair
))
3178 (string-match (or regexp
"^python-")
3179 (symbol-name (car pair
)))
3180 (set (make-local-variable (car pair
))
3182 (buffer-local-variables from-buffer
)))
3184 (defun python-util-forward-comment (&optional direction
)
3185 "Python mode specific version of `forward-comment'.
3186 Optional argument DIRECTION defines the direction to move to."
3187 (let ((comment-start (python-syntax-context 'comment
))
3188 (factor (if (< (or direction
0) 0)
3192 (goto-char comment-start
))
3193 (forward-comment factor
)))
3197 (define-derived-mode python-mode prog-mode
"Python"
3198 "Major mode for editing Python files.
3201 Entry to this mode calls the value of `python-mode-hook'
3202 if that value is non-nil."
3203 (set (make-local-variable 'tab-width
) 8)
3204 (set (make-local-variable 'indent-tabs-mode
) nil
)
3206 (set (make-local-variable 'comment-start
) "# ")
3207 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3209 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3210 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3212 (set (make-local-variable 'forward-sexp-function
)
3213 'python-nav-forward-sexp
)
3215 (set (make-local-variable 'font-lock-defaults
)
3216 '(python-font-lock-keywords nil nil nil nil
))
3218 (set (make-local-variable 'syntax-propertize-function
)
3219 python-syntax-propertize-function
)
3221 (set (make-local-variable 'indent-line-function
)
3222 #'python-indent-line-function
)
3223 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3225 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3226 (set (make-local-variable 'fill-paragraph-function
)
3227 'python-fill-paragraph
)
3229 (set (make-local-variable 'beginning-of-defun-function
)
3230 #'python-nav-beginning-of-defun
)
3231 (set (make-local-variable 'end-of-defun-function
)
3232 #'python-nav-end-of-defun
)
3234 (add-hook 'completion-at-point-functions
3235 'python-completion-complete-at-point nil
'local
)
3237 (add-hook 'post-self-insert-hook
3238 'python-indent-post-self-insert-function nil
'local
)
3240 (set (make-local-variable 'imenu-extract-index-name-function
)
3241 #'python-info-current-defun
)
3243 (set (make-local-variable 'imenu-prev-index-position-function
)
3244 #'python-imenu-prev-index-position
)
3246 (set (make-local-variable 'add-log-current-defun-function
)
3247 #'python-info-current-defun
)
3249 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3251 (set (make-local-variable 'skeleton-further-elements
)
3253 (< '(backward-delete-char-untabify (min python-indent-offset
3255 (^
'(- (1+ (current-indentation))))))
3257 (set (make-local-variable 'eldoc-documentation-function
)
3258 #'python-eldoc-function
)
3260 (add-to-list 'hs-special-modes-alist
3261 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3263 (python-nav-end-of-defun)) nil
))
3265 (set (make-local-variable 'mode-require-final-newline
) t
)
3267 (set (make-local-variable 'outline-regexp
)
3268 (python-rx (* space
) block-start
))
3269 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3270 (set (make-local-variable 'outline-level
)
3272 "`outline-level' function for Python mode."
3273 (1+ (/ (current-indentation) python-indent-offset
))))
3275 (python-skeleton-add-menu-items)
3277 (make-local-variable 'python-shell-internal-buffer
)
3279 (when python-indent-guess-indent-offset
3280 (python-indent-guess-indent-offset)))
3287 ;; indent-tabs-mode: nil
3290 ;;; python.el ends here