1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2013 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. As an alternative you can use the defined
159 ;; skeleton commands: `python-skeleton-class', `python-skeleton-def'
160 ;; `python-skeleton-for', `python-skeleton-if', `python-skeleton-try'
161 ;; and `python-skeleton-while'.
163 ;; FFAP: You can find the filename for a given module when using ffap
164 ;; out of the box. This feature needs an inferior python shell
167 ;; Code check: Check the current file for errors with `python-check'
168 ;; using the program defined in `python-check-command'.
170 ;; Eldoc: returns documentation for object at point by using the
171 ;; inferior python subprocess to inspect its documentation. As you
172 ;; might guessed you should run `python-shell-send-buffer' from time
173 ;; to time to get better results too.
175 ;; Imenu: This mode supports Imenu in its most basic form, letting it
176 ;; build the necessary alist via `imenu-default-create-index-function'
177 ;; by having set `imenu-extract-index-name-function' to
178 ;; `python-info-current-defun' and
179 ;; `imenu-prev-index-position-function' to
180 ;; `python-imenu-prev-index-position'.
182 ;; If you used python-mode.el you probably will miss auto-indentation
183 ;; when inserting newlines. To achieve the same behavior you have
186 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
188 ;; 2) Add the following hook in your .emacs:
190 ;; (add-hook 'python-mode-hook
192 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
194 ;; I'd recommend the first one since you'll get the same behavior for
195 ;; all modes out-of-the-box.
199 ;; Add this to your .emacs:
201 ;; (add-to-list 'load-path "/folder/containing/file")
208 (require 'ansi-color
)
213 ;; Avoid compiler warnings
214 (defvar view-return-to-alist
)
215 (defvar compilation-error-regexp-alist
)
216 (defvar outline-heading-end-regexp
))
218 (autoload 'comint-mode
"comint")
221 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
223 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
226 "Python Language's flying circus support for Emacs."
229 :link
'(emacs-commentary-link "python"))
234 (defvar python-mode-map
235 (let ((map (make-sparse-keymap)))
237 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
238 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
239 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
240 (define-key map
"\C-c\C-j" 'imenu
)
242 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
243 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
244 (define-key map
"\C-c<" 'python-indent-shift-left
)
245 (define-key map
"\C-c>" 'python-indent-shift-right
)
246 (define-key map
":" 'python-indent-electric-colon
)
248 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
249 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
250 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
251 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
252 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
253 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
255 (define-key map
"\C-c\C-p" 'run-python
)
256 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
257 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
258 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
259 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
260 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
261 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
262 ;; Some util commands
263 (define-key map
"\C-c\C-v" 'python-check
)
264 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
266 (substitute-key-definition 'complete-symbol
'completion-at-point
268 (easy-menu-define python-menu map
"Python Mode menu"
270 :help
"Python-specific Features"
271 ["Shift region left" python-indent-shift-left
:active mark-active
272 :help
"Shift region left by a single indentation step"]
273 ["Shift region right" python-indent-shift-right
:active mark-active
274 :help
"Shift region right by a single indentation step"]
276 ["Start of def/class" beginning-of-defun
277 :help
"Go to start of outermost definition around point"]
278 ["End of def/class" end-of-defun
279 :help
"Go to end of definition around point"]
280 ["Mark def/class" mark-defun
281 :help
"Mark outermost definition around point"]
282 ["Jump to def/class" imenu
283 :help
"Jump to a class or function definition"]
287 ["Start interpreter" run-python
288 :help
"Run inferior Python process in a separate buffer"]
289 ["Switch to shell" python-shell-switch-to-shell
290 :help
"Switch to running inferior Python process"]
291 ["Eval string" python-shell-send-string
292 :help
"Eval string in inferior Python session"]
293 ["Eval buffer" python-shell-send-buffer
294 :help
"Eval buffer in inferior Python session"]
295 ["Eval region" python-shell-send-region
296 :help
"Eval region in inferior Python session"]
297 ["Eval defun" python-shell-send-defun
298 :help
"Eval defun in inferior Python session"]
299 ["Eval file" python-shell-send-file
300 :help
"Eval file in inferior Python session"]
301 ["Debugger" pdb
:help
"Run pdb under GUD"]
303 ["Check file" python-check
304 :help
"Check file for errors"]
305 ["Help on symbol" python-eldoc-at-point
306 :help
"Get help on symbol at point"]
307 ["Complete symbol" completion-at-point
308 :help
"Complete symbol before point"]))
310 "Keymap for `python-mode'.")
313 ;;; Python specialized rx
316 (defconst python-rx-constituents
317 `((block-start .
,(rx symbol-start
318 (or "def" "class" "if" "elif" "else" "try"
319 "except" "finally" "for" "while" "with")
321 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
323 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
324 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
325 (+ space
) "==" (+ space
)
326 (any ?
' ?
\") "__main__" (any ?
' ?
\")
328 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
329 (open-paren .
,(rx (or "{" "[" "(")))
330 (close-paren .
,(rx (or "}" "]" ")")))
331 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
332 ;; FIXME: rx should support (not simple-operator).
333 (not-simple-operator .
,(rx
335 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
336 ;; FIXME: Use regexp-opt.
337 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
338 "=" "%" "**" "//" "<<" ">>" "<=" "!="
339 "==" ">=" "is" "not")))
340 ;; FIXME: Use regexp-opt.
341 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
342 ">>=" "<<=" "&=" "^=" "|=")))
343 (string-delimiter .
,(rx (and
344 ;; Match even number of backslashes.
345 (or (not (any ?
\\ ?
\' ?
\")) point
346 ;; Quotes might be preceded by a escaped quote.
347 (and (or (not (any ?
\\)) point
) ?
\\
348 (* ?
\\ ?
\\) (any ?
\' ?
\")))
350 ;; Match single or triple quotes of any kind.
351 (group (or "\"" "\"\"\"" "'" "'''"))))))
352 "Additional Python specific sexps for `python-rx'")
354 (defmacro python-rx
(&rest regexps
)
355 "Python mode specialized rx macro.
356 This variant of `rx' supports common python named REGEXPS."
357 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
358 (cond ((null regexps
)
361 (rx-to-string `(and ,@regexps
) t
))
363 (rx-to-string (car regexps
) t
))))))
366 ;;; Font-lock and syntax
368 (defun python-syntax-context (type &optional syntax-ppss
)
369 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
370 TYPE can be `comment', `string' or `paren'. It returns the start
371 character address of the specified TYPE."
372 (let ((ppss (or syntax-ppss
(syntax-ppss))))
374 (comment (and (nth 4 ppss
) (nth 8 ppss
)))
375 (string (and (not (nth 4 ppss
)) (nth 8 ppss
)))
379 (defun python-syntax-context-type (&optional syntax-ppss
)
380 "Return the context type using SYNTAX-PPSS.
381 The type returned can be `comment', `string' or `paren'."
382 (let ((ppss (or syntax-ppss
(syntax-ppss))))
384 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
385 ((nth 1 ppss
) 'paren
))))
387 (defsubst python-syntax-comment-or-string-p
()
388 "Return non-nil if point is inside 'comment or 'string."
389 (nth 8 (syntax-ppss)))
391 (define-obsolete-function-alias
392 'python-info-ppss-context
#'python-syntax-context
"24.3")
394 (define-obsolete-function-alias
395 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
397 (define-obsolete-function-alias
398 'python-info-ppss-comment-or-string-p
399 #'python-syntax-comment-or-string-p
"24.3")
401 (defvar python-font-lock-keywords
405 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
406 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
407 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
412 ;; False, None, and True are listed as keywords on the Python 3
413 ;; documentation, but since they also qualify as constants they are
414 ;; fontified like that in order to keep font-lock consistent between
421 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
422 (1 font-lock-function-name-face
))
424 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
425 (1 font-lock-type-face
))
429 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
430 ;; copyright, license, credits, quit and exit are added by the site
431 ;; module and they are not intended to be used in programs
432 "copyright" "credits" "exit" "license" "quit")
433 symbol-end
) . font-lock-constant-face
)
435 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
436 (0+ "." (1+ (or word ?_
)))))
437 (1 font-lock-type-face
))
438 ;; Builtin Exceptions
441 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
442 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
443 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
444 "ImportError" "ImportWarning" "IndexError" "KeyError"
445 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
446 "NotImplementedError" "OSError" "OverflowError"
447 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
448 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
449 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
450 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
451 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
452 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
456 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
458 symbol-end
) . font-lock-type-face
)
462 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
463 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
464 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
465 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
466 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
467 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
468 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
469 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
472 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
473 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
476 "ascii" "bytearray" "bytes" "exec"
478 "__all__" "__doc__" "__name__" "__package__")
479 symbol-end
) . font-lock-builtin-face
)
481 ;; support for a = b = c = 5
483 (let ((re (python-rx (group (+ (any word ?. ?_
)))
484 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
485 assignment-operator
)))
486 (when (re-search-forward re limit t
)
487 (while (and (python-syntax-context 'paren
)
488 (re-search-forward re limit t
)))
489 (if (and (not (python-syntax-context 'paren
))
490 (not (equal (char-after (point-marker)) ?
=)))
492 (set-match-data nil
)))))
493 (1 font-lock-variable-name-face nil nil
))
494 ;; support for a, b, c = (1, 2, 3)
496 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
497 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
498 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
499 assignment-operator
)))
500 (when (and (re-search-forward re limit t
)
501 (goto-char (nth 3 (match-data))))
502 (while (and (python-syntax-context 'paren
)
503 (re-search-forward re limit t
))
504 (goto-char (nth 3 (match-data))))
505 (if (not (python-syntax-context 'paren
))
507 (set-match-data nil
)))))
508 (1 font-lock-variable-name-face nil nil
))))
510 (defconst python-syntax-propertize-function
511 (syntax-propertize-rules
512 ((python-rx string-delimiter
)
513 (0 (ignore (python-syntax-stringify))))))
515 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
516 "Count number of quotes around point (max is 3).
517 QUOTE-CHAR is the quote char to count. Optional argument POINT is
518 the point where scan starts (defaults to current point) and LIMIT
519 is used to limit the scan."
522 (or (not limit
) (< (+ point i
) limit
))
523 (eq (char-after (+ point i
)) quote-char
))
527 (defun python-syntax-stringify ()
528 "Put `syntax-table' property correctly on single/triple quotes."
529 (let* ((num-quotes (length (match-string-no-properties 1)))
531 (backward-char num-quotes
)
533 (forward-char num-quotes
)))
534 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
535 (quote-starting-pos (- (point) num-quotes
))
536 (quote-ending-pos (point))
539 (python-syntax-count-quotes
540 (char-before) string-start quote-starting-pos
))))
541 (cond ((and string-start
(= num-closing-quotes
0))
542 ;; This set of quotes doesn't match the string starting
546 ;; This set of quotes delimit the start of a string.
547 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
548 'syntax-table
(string-to-syntax "|")))
549 ((= num-quotes num-closing-quotes
)
550 ;; This set of quotes delimit the end of a string.
551 (put-text-property (1- quote-ending-pos
) quote-ending-pos
552 'syntax-table
(string-to-syntax "|")))
553 ((> num-quotes num-closing-quotes
)
554 ;; This may only happen whenever a triple quote is closing
555 ;; a single quoted string. Add string delimiter syntax to
557 (put-text-property quote-starting-pos quote-ending-pos
558 'syntax-table
(string-to-syntax "|"))))))
560 (defvar python-mode-syntax-table
561 (let ((table (make-syntax-table)))
562 ;; Give punctuation syntax to ASCII that normally has symbol
563 ;; syntax or has word syntax and isn't a letter.
564 (let ((symbol (string-to-syntax "_"))
565 (sst (standard-syntax-table)))
568 (if (equal symbol
(aref sst i
))
569 (modify-syntax-entry i
"." table
)))))
570 (modify-syntax-entry ?$
"." table
)
571 (modify-syntax-entry ?%
"." table
)
573 (modify-syntax-entry ?
# "<" table
)
574 (modify-syntax-entry ?
\n ">" table
)
575 (modify-syntax-entry ?
' "\"" table
)
576 (modify-syntax-entry ?
` "$" table
)
578 "Syntax table for Python files.")
580 (defvar python-dotty-syntax-table
581 (let ((table (make-syntax-table python-mode-syntax-table
)))
582 (modify-syntax-entry ?.
"w" table
)
583 (modify-syntax-entry ?_
"w" table
)
585 "Dotty syntax table for Python files.
586 It makes underscores and dots word constituent chars.")
591 (defcustom python-indent-offset
4
592 "Default indentation offset for Python."
597 (defcustom python-indent-guess-indent-offset t
598 "Non-nil tells Python mode to guess `python-indent-offset' value."
603 (defcustom python-indent-trigger-commands
604 '(indent-for-tab-command yas-expand yas
/expand
)
605 "Commands that might trigger a `python-indent-line' call."
606 :type
'(repeat symbol
)
609 (define-obsolete-variable-alias
610 'python-indent
'python-indent-offset
"24.3")
612 (define-obsolete-variable-alias
613 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
615 (defvar python-indent-current-level
0
616 "Current indentation level `python-indent-line-function' is using.")
618 (defvar python-indent-levels
'(0)
619 "Levels of indentation available for `python-indent-line-function'.")
621 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
622 "List of words that should be dedented.
623 These make `python-indent-calculate-indentation' subtract the value of
624 `python-indent-offset'.")
626 (defun python-indent-guess-indent-offset ()
627 "Guess and set `python-indent-offset' for the current buffer."
632 (goto-char (point-min))
634 (while (and (not block-end
)
636 (python-rx line-start block-start
) nil t
))
638 (not (python-syntax-context-type))
640 (goto-char (line-end-position))
641 (python-util-forward-comment -
1)
642 (if (equal (char-before) ?
:)
645 (when (python-info-block-continuation-line-p)
646 (while (and (python-info-continuation-line-p)
649 (python-util-forward-comment -
1)
650 (when (equal (char-before) ?
:)
652 (setq block-end
(point-marker))))
655 (goto-char block-end
)
656 (python-util-forward-comment)
657 (current-indentation))))
659 (set (make-local-variable 'python-indent-offset
) indentation
)
660 (message "Can't guess python-indent-offset, using defaults: %s"
661 python-indent-offset
)))))))
663 (defun python-indent-context ()
664 "Get information on indentation context.
665 Context information is returned with a cons with the form:
668 Where status can be any of the following symbols:
669 * inside-paren: If point in between (), {} or []
670 * inside-string: If point is inside a string
671 * after-backslash: Previous line ends in a backslash
672 * after-beginning-of-block: Point is after beginning of block
673 * after-line: Point is after normal line
674 * no-indent: Point is at beginning of buffer or other special case
675 START is the buffer position where the sexp starts."
678 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
682 ;; Beginning of buffer
684 (goto-char (line-beginning-position))
688 ((setq start
(python-syntax-context 'string ppss
))
691 ((setq start
(python-syntax-context 'paren ppss
))
694 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
695 (python-syntax-context 'comment ppss
)))
696 (let ((line-beg-pos (line-beginning-position)))
697 (when (python-info-line-ends-backslash-p
699 (- line-beg-pos
2)))))
701 ;; After beginning of block
702 ((setq start
(save-excursion
704 (back-to-indentation)
705 (python-util-forward-comment -
1)
706 (equal (char-before) ?
:))
707 ;; Move to the first block start that's not in within
708 ;; a string, comment or paren and that's not a
709 ;; continuation line.
710 (while (and (re-search-backward
711 (python-rx block-start
) nil t
)
713 (python-syntax-context-type)
714 (python-info-continuation-line-p))))
715 (when (looking-at (python-rx block-start
))
717 'after-beginning-of-block
)
719 ((setq start
(save-excursion
720 (back-to-indentation)
721 (skip-chars-backward (rx (or whitespace ?
\n)))
722 (python-nav-beginning-of-statement)
729 (defun python-indent-calculate-indentation ()
730 "Calculate correct indentation offset for the current line."
731 (let* ((indentation-context (python-indent-context))
732 (context-status (car indentation-context
))
733 (context-start (cdr indentation-context
)))
739 ;; When point is after beginning of block just add one level
740 ;; of indentation relative to the context-start
741 ('after-beginning-of-block
742 (goto-char context-start
)
743 (+ (current-indentation) python-indent-offset
))
744 ;; When after a simple line just use previous line
745 ;; indentation, in the case current line starts with a
746 ;; `python-indent-dedenters' de-indent one level.
750 (goto-char context-start
)
751 (current-indentation))
753 (back-to-indentation)
754 (looking-at (regexp-opt python-indent-dedenters
)))
757 ;; When inside of a string, do nothing. just use the current
758 ;; indentation. XXX: perhaps it would be a good idea to
759 ;; invoke standard text indentation here
761 (goto-char context-start
)
762 (current-indentation))
763 ;; After backslash we have several possibilities.
766 ;; Check if current line is a dot continuation. For this
767 ;; the current line must start with a dot and previous
768 ;; line must contain a dot too.
770 (back-to-indentation)
771 (when (looking-at "\\.")
772 ;; If after moving one line back point is inside a paren it
773 ;; needs to move back until it's not anymore
777 (python-syntax-context 'paren
))))
778 (goto-char (line-end-position))
779 (while (and (re-search-backward
780 "\\." (line-beginning-position) t
)
781 (python-syntax-context-type)))
782 (if (and (looking-at "\\.")
783 (not (python-syntax-context-type)))
784 ;; The indentation is the same column of the
785 ;; first matching dot that's not inside a
786 ;; comment, a string or a paren
788 ;; No dot found on previous line, just add another
789 ;; indentation level.
790 (+ (current-indentation) python-indent-offset
)))))
791 ;; Check if prev line is a block continuation
792 ((let ((block-continuation-start
793 (python-info-block-continuation-line-p)))
794 (when block-continuation-start
795 ;; If block-continuation-start is set jump to that
796 ;; marker and use first column after the block start
797 ;; as indentation value.
798 (goto-char block-continuation-start
)
800 (python-rx block-start
(* space
))
801 (line-end-position) t
)
803 ;; Check if current line is an assignment continuation
804 ((let ((assignment-continuation-start
805 (python-info-assignment-continuation-line-p)))
806 (when assignment-continuation-start
807 ;; If assignment-continuation is set jump to that
808 ;; marker and use first column after the assignment
809 ;; operator as indentation value.
810 (goto-char assignment-continuation-start
)
814 (goto-char (python-info-beginning-of-backslash))
819 (or (python-info-beginning-of-backslash) (point)))
820 (python-info-line-ends-backslash-p)))
821 ;; The two previous lines ended in a backslash so we must
822 ;; respect previous line indentation.
823 (current-indentation)
824 ;; What happens here is that we are dealing with the second
825 ;; line of a backslash continuation, in that case we just going
826 ;; to add one indentation level.
827 (+ (current-indentation) python-indent-offset
)))))
828 ;; When inside a paren there's a need to handle nesting
832 ;; If current line closes the outermost open paren use the
833 ;; current indentation of the context-start line.
835 (skip-syntax-forward "\s" (line-end-position))
836 (when (and (looking-at (regexp-opt '(")" "]" "}")))
839 (not (python-syntax-context 'paren
))))
840 (goto-char context-start
)
841 (current-indentation))))
842 ;; If open paren is contained on a line by itself add another
843 ;; indentation level, else look for the first word after the
844 ;; opening paren and use it's column position as indentation
846 ((let* ((content-starts-in-newline)
849 (if (setq content-starts-in-newline
851 (goto-char context-start
)
855 (line-beginning-position)
857 (python-util-forward-comment))
859 (+ (current-indentation) python-indent-offset
)
863 ;; If current line closes a nested open paren de-indent one
866 (back-to-indentation)
867 (looking-at (regexp-opt '(")" "]" "}"))))
868 (- indent python-indent-offset
))
869 ;; If the line of the opening paren that wraps the current
870 ;; line starts a block add another level of indentation to
871 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
873 (when (and content-starts-in-newline
875 (goto-char context-start
)
876 (back-to-indentation)
877 (looking-at (python-rx block-start
))))
878 (+ indent python-indent-offset
))))
881 (defun python-indent-calculate-levels ()
882 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
883 (let* ((indentation (python-indent-calculate-indentation))
884 (remainder (% indentation python-indent-offset
))
885 (steps (/ (- indentation remainder
) python-indent-offset
)))
886 (setq python-indent-levels
(list 0))
887 (dotimes (step steps
)
888 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
889 (when (not (eq 0 remainder
))
890 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
891 (setq python-indent-levels
(nreverse python-indent-levels
))
892 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
894 (defun python-indent-toggle-levels ()
895 "Toggle `python-indent-current-level' over `python-indent-levels'."
896 (setq python-indent-current-level
(1- python-indent-current-level
))
897 (when (< python-indent-current-level
0)
898 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
900 (defun python-indent-line (&optional force-toggle
)
901 "Internal implementation of `python-indent-line-function'.
902 Uses the offset calculated in
903 `python-indent-calculate-indentation' and available levels
904 indicated by the variable `python-indent-levels' to set the
907 When the variable `last-command' is equal to one of the symbols
908 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
909 non-nil it cycles levels indicated in the variable
910 `python-indent-levels' by setting the current level in the
911 variable `python-indent-current-level'.
913 When the variable `last-command' is not equal to one of the
914 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
915 is nil it calculates possible indentation levels and saves it in
916 the variable `python-indent-levels'. Afterwards it sets the
917 variable `python-indent-current-level' correctly so offset is
918 equal to (`nth' `python-indent-current-level'
919 `python-indent-levels')"
921 (and (or (and (memq this-command python-indent-trigger-commands
)
922 (eq last-command this-command
))
924 (not (equal python-indent-levels
'(0)))
925 (or (python-indent-toggle-levels) t
))
926 (python-indent-calculate-levels))
927 (let* ((starting-pos (point-marker))
928 (indent-ending-position
929 (+ (line-beginning-position) (current-indentation)))
930 (follow-indentation-p
932 (and (<= (line-beginning-position) starting-pos
)
933 (>= indent-ending-position starting-pos
))))
934 (next-indent (nth python-indent-current-level python-indent-levels
)))
935 (unless (= next-indent
(current-indentation))
937 (delete-horizontal-space)
938 (indent-to next-indent
)
939 (goto-char starting-pos
))
940 (and follow-indentation-p
(back-to-indentation)))
941 (python-info-closing-block-message))
943 (defun python-indent-line-function ()
944 "`indent-line-function' for Python mode.
945 See `python-indent-line' for details."
946 (python-indent-line))
948 (defun python-indent-dedent-line ()
949 "De-indent current line."
951 (when (and (not (python-syntax-comment-or-string-p))
952 (<= (point-marker) (save-excursion
953 (back-to-indentation)
955 (> (current-column) 0))
956 (python-indent-line t
)
959 (defun python-indent-dedent-line-backspace (arg)
960 "De-indent current line.
961 Argument ARG is passed to `backward-delete-char-untabify' when
962 point is not in between the indentation."
964 (when (not (python-indent-dedent-line))
965 (backward-delete-char-untabify arg
)))
966 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
968 (defun python-indent-region (start end
)
969 "Indent a python region automagically.
971 Called from a program, START and END specify the region to indent."
972 (let ((deactivate-mark nil
))
975 (setq end
(point-marker))
977 (or (bolp) (forward-line 1))
978 (while (< (point) end
)
979 (or (and (bolp) (eolp))
982 (back-to-indentation)
983 (setq word
(current-word))
986 ;; Don't mess with strings, unless it's the
987 ;; enclosing set of quotes.
988 (or (not (python-syntax-context 'string
))
992 (current-indentation)
993 (python-syntax-count-quotes (char-after) (point))))
994 (string-to-syntax "|"))))
996 (delete-horizontal-space)
997 (indent-to (python-indent-calculate-indentation)))))
999 (move-marker end nil
))))
1001 (defun python-indent-shift-left (start end
&optional count
)
1002 "Shift lines contained in region START END by COUNT columns to the left.
1003 COUNT defaults to `python-indent-offset'. If region isn't
1004 active, the current line is shifted. The shifted region includes
1005 the lines in which START and END lie. An error is signaled if
1006 any lines in the region are indented less than COUNT columns."
1009 (list (region-beginning) (region-end) current-prefix-arg
)
1010 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1012 (setq count
(prefix-numeric-value count
))
1013 (setq count python-indent-offset
))
1015 (let ((deactivate-mark nil
))
1018 (while (< (point) end
)
1019 (if (and (< (current-indentation) count
)
1020 (not (looking-at "[ \t]*$")))
1021 (error "Can't shift all lines enough"))
1023 (indent-rigidly start end
(- count
))))))
1025 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1027 (defun python-indent-shift-right (start end
&optional count
)
1028 "Shift lines contained in region START END by COUNT columns to the left.
1029 COUNT defaults to `python-indent-offset'. If region isn't
1030 active, the current line is shifted. The shifted region includes
1031 the lines in which START and END lie."
1034 (list (region-beginning) (region-end) current-prefix-arg
)
1035 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1036 (let ((deactivate-mark nil
))
1038 (setq count
(prefix-numeric-value count
))
1039 (setq count python-indent-offset
))
1040 (indent-rigidly start end count
)))
1042 (defun python-indent-electric-colon (arg)
1043 "Insert a colon and maybe de-indent the current line.
1044 With numeric ARG, just insert that many colons. With
1045 \\[universal-argument], just insert a single colon."
1047 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1048 (when (and (not arg
)
1050 (not (equal ?
: (char-after (- (point-marker) 2))))
1051 (not (python-syntax-comment-or-string-p)))
1052 (let ((indentation (current-indentation))
1053 (calculated-indentation (python-indent-calculate-indentation)))
1054 (python-info-closing-block-message)
1055 (when (> indentation calculated-indentation
)
1057 (indent-line-to calculated-indentation
)
1058 (when (not (python-info-closing-block-message))
1059 (indent-line-to indentation
)))))))
1060 (put 'python-indent-electric-colon
'delete-selection t
)
1062 (defun python-indent-post-self-insert-function ()
1063 "Adjust closing paren line indentation after a char is added.
1064 This function is intended to be added to the
1065 `post-self-insert-hook.' If a line renders a paren alone, after
1066 adding a char before it, the line will be re-indented
1067 automatically if needed."
1068 (when (and (eq (char-before) last-command-event
)
1070 (memq (char-after) '(?\
) ?\
] ?\
})))
1072 (goto-char (line-beginning-position))
1073 ;; If after going to the beginning of line the point
1074 ;; is still inside a paren it's ok to do the trick
1075 (when (python-syntax-context 'paren
)
1076 (let ((indentation (python-indent-calculate-indentation)))
1077 (when (< (current-indentation) indentation
)
1078 (indent-line-to indentation
)))))))
1083 (defvar python-nav-beginning-of-defun-regexp
1084 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1085 "Regexp matching class or function definition.
1086 The name of the defun should be grouped so it can be retrieved
1087 via `match-string'.")
1089 (defun python-nav--beginning-of-defun (&optional arg
)
1090 "Internal implementation of `python-nav-beginning-of-defun'.
1091 With positive ARG search backwards, else search forwards."
1092 (when (or (null arg
) (= arg
0)) (setq arg
1))
1093 (let* ((re-search-fn (if (> arg
0)
1094 #'re-search-backward
1095 #'re-search-forward
))
1096 (line-beg-pos (line-beginning-position))
1097 (line-content-start (+ line-beg-pos
(current-indentation)))
1098 (pos (point-marker))
1103 (not (python-info-looking-at-beginning-of-defun))
1104 (python-nav-backward-block)))
1105 (or (and (python-info-looking-at-beginning-of-defun)
1106 (+ (current-indentation) python-indent-offset
))
1110 (when (and (< arg
0)
1111 (python-info-looking-at-beginning-of-defun))
1113 (while (and (funcall re-search-fn
1114 python-nav-beginning-of-defun-regexp nil t
)
1115 (or (python-syntax-context-type)
1116 ;; Handle nested defuns when moving
1117 ;; backwards by checking indentation.
1119 (not (= (current-indentation) 0))
1120 (>= (current-indentation) beg-indentation
)))))
1121 (and (python-info-looking-at-beginning-of-defun)
1122 (or (not (= (line-number-at-pos pos
)
1123 (line-number-at-pos)))
1124 (and (>= (point) line-beg-pos
)
1125 (<= (point) line-content-start
)
1126 (> pos line-content-start
)))))))
1128 (or (beginning-of-line 1) t
)
1129 (and (goto-char pos
) nil
))))
1131 (defun python-nav-beginning-of-defun (&optional arg
)
1132 "Move point to `beginning-of-defun'.
1133 With positive ARG search backwards else search forward. When ARG
1134 is nil or 0 defaults to 1. When searching backwards nested
1135 defuns are handled with care depending on current point
1136 position. Return non-nil if point is moved to
1137 `beginning-of-defun'."
1138 (when (or (null arg
) (= arg
0)) (setq arg
1))
1140 (cond ((and (eq this-command
'mark-defun
)
1141 (python-info-looking-at-beginning-of-defun)))
1143 (dotimes (i (if (> arg
0) arg
(- arg
)))
1144 (when (and (python-nav--beginning-of-defun arg)
1149 (defun python-nav-end-of-defun ()
1150 "Move point to the end of def or class.
1151 Returns nil if point is not in a def or class."
1153 (let ((beg-defun-indent)
1155 (when (or (python-info-looking-at-beginning-of-defun)
1156 (python-nav-beginning-of-defun 1)
1157 (python-nav-beginning-of-defun -1))
1158 (setq beg-defun-indent
(current-indentation))
1160 (python-nav-end-of-statement)
1161 (python-util-forward-comment 1)
1162 (and (> (current-indentation) beg-defun-indent
)
1164 (python-util-forward-comment -
1)
1166 ;; Ensure point moves forward.
1167 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1169 (defun python-nav-beginning-of-statement ()
1170 "Move to start of current statement."
1172 (while (and (or (back-to-indentation) t
)
1177 (python-info-line-ends-backslash-p))
1178 (python-syntax-context 'string
)
1179 (python-syntax-context 'paren
))
1180 (forward-line -
1))))
1183 (defun python-nav-end-of-statement (&optional noend
)
1184 "Move to end of current statement.
1185 Optional argument NOEND is internal and makes the logic to not
1186 jump to the end of line when moving forward searching for the end
1189 (let (string-start bs-pos
)
1190 (while (and (or noend
(goto-char (line-end-position)))
1192 (cond ((setq string-start
(python-syntax-context 'string
))
1193 (goto-char string-start
)
1194 (if (python-syntax-context 'paren
)
1195 ;; Ended up inside a paren, roll again.
1196 (python-nav-end-of-statement t
)
1197 ;; This is not inside a paren, move to the
1198 ;; end of this string.
1199 (goto-char (+ (point)
1200 (python-syntax-count-quotes
1201 (char-after (point)) (point))))
1202 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1203 (goto-char (point-max)))))
1204 ((python-syntax-context 'paren
)
1205 ;; The statement won't end before we've escaped
1206 ;; at least one level of parenthesis.
1208 (goto-char (scan-lists (point) 1 -
1))
1209 (scan-error (goto-char (nth 3 err
)))))
1210 ((setq bs-pos
(python-info-line-ends-backslash-p))
1212 (forward-line 1))))))
1215 (defun python-nav-backward-statement (&optional arg
)
1216 "Move backward to previous statement.
1217 With ARG, repeat. See `python-nav-forward-statement'."
1219 (or arg
(setq arg
1))
1220 (python-nav-forward-statement (- arg
)))
1222 (defun python-nav-forward-statement (&optional arg
)
1223 "Move forward to next statement.
1224 With ARG, repeat. With negative argument, move ARG times
1225 backward to previous statement."
1227 (or arg
(setq arg
1))
1229 (python-nav-end-of-statement)
1230 (python-util-forward-comment)
1231 (python-nav-beginning-of-statement)
1232 (setq arg
(1- arg
)))
1234 (python-nav-beginning-of-statement)
1235 (python-util-forward-comment -
1)
1236 (python-nav-beginning-of-statement)
1237 (setq arg
(1+ arg
))))
1239 (defun python-nav-beginning-of-block ()
1240 "Move to start of current block."
1242 (let ((starting-pos (point))
1243 (block-regexp (python-rx
1244 line-start
(* whitespace
) block-start
)))
1246 (python-nav-beginning-of-statement)
1247 (looking-at (python-rx block-start
)))
1249 ;; Go to first line beginning a statement
1250 (while (and (not (bobp))
1251 (or (and (python-nav-beginning-of-statement) nil
)
1252 (python-info-current-line-comment-p)
1253 (python-info-current-line-empty-p)))
1255 (let ((block-matching-indent
1256 (- (current-indentation) python-indent-offset
)))
1258 (and (python-nav-backward-block)
1259 (> (current-indentation) block-matching-indent
)))
1260 (if (and (looking-at (python-rx block-start
))
1261 (= (current-indentation) block-matching-indent
))
1263 (and (goto-char starting-pos
) nil
))))))
1265 (defun python-nav-end-of-block ()
1266 "Move to end of current block."
1268 (when (python-nav-beginning-of-block)
1269 (let ((block-indentation (current-indentation)))
1270 (python-nav-end-of-statement)
1271 (while (and (forward-line 1)
1273 (or (and (> (current-indentation) block-indentation
)
1274 (or (python-nav-end-of-statement) t
))
1275 (python-info-current-line-comment-p)
1276 (python-info-current-line-empty-p))))
1277 (python-util-forward-comment -
1)
1280 (defun python-nav-backward-block (&optional arg
)
1281 "Move backward to previous block of code.
1282 With ARG, repeat. See `python-nav-forward-block'."
1284 (or arg
(setq arg
1))
1285 (python-nav-forward-block (- arg
)))
1287 (defun python-nav-forward-block (&optional arg
)
1288 "Move forward to next block of code.
1289 With ARG, repeat. With negative argument, move ARG times
1290 backward to previous block."
1292 (or arg
(setq arg
1))
1293 (let ((block-start-regexp
1294 (python-rx line-start
(* whitespace
) block-start
))
1295 (starting-pos (point)))
1297 (python-nav-end-of-statement)
1299 (re-search-forward block-start-regexp nil t
)
1300 (python-syntax-context-type)))
1301 (setq arg
(1- arg
)))
1303 (python-nav-beginning-of-statement)
1305 (re-search-backward block-start-regexp nil t
)
1306 (python-syntax-context-type)))
1307 (setq arg
(1+ arg
)))
1308 (python-nav-beginning-of-statement)
1309 (if (not (looking-at (python-rx block-start
)))
1310 (and (goto-char starting-pos
) nil
)
1311 (and (not (= (point) starting-pos
)) (point-marker)))))
1313 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1314 "Safe version of standard `forward-sexp'.
1315 When ARG > 0 move forward, else if ARG is < 0."
1316 (or arg
(setq arg
1))
1317 (let ((forward-sexp-function)
1319 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1321 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1325 (while (and (funcall search-fn paren-regexp nil t
)
1326 (python-syntax-context 'paren
)))))))
1328 (defun python-nav--forward-sexp (&optional dir
)
1329 "Move to forward sexp.
1330 With positive Optional argument DIR direction move forward, else
1332 (setq dir
(or dir
1))
1334 (let* ((forward-p (if (> dir
0)
1335 (and (setq dir
1) t
)
1336 (and (setq dir -
1) nil
)))
1337 (re-search-fn (if forward-p
1339 're-search-backward
))
1340 (context-type (python-syntax-context-type)))
1342 ((eq context-type
'string
)
1343 ;; Inside of a string, get out of it.
1344 (while (and (funcall re-search-fn
"[\"']" nil t
)
1345 (python-syntax-context 'string
))))
1346 ((eq context-type
'comment
)
1347 ;; Inside of a comment, just move forward.
1348 (python-util-forward-comment dir
))
1349 ((or (eq context-type
'paren
)
1350 (and forward-p
(looking-at (python-rx open-paren
)))
1351 (and (not forward-p
)
1352 (eq (syntax-class (syntax-after (1- (point))))
1353 (car (string-to-syntax ")")))))
1354 ;; Inside a paren or looking at it, lisp knows what to do.
1355 (python-nav-lisp-forward-sexp-safe dir
))
1357 ;; This part handles the lispy feel of
1358 ;; `python-nav-forward-sexp'. Knowing everything about the
1359 ;; current context and the context of the next sexp tries to
1360 ;; follow the lisp sexp motion commands in a symmetric manner.
1363 ((python-info-beginning-of-block-p) 'block-start
)
1364 ((python-info-end-of-block-p) 'block-end
)
1365 ((python-info-beginning-of-statement-p) 'statement-start
)
1366 ((python-info-end-of-statement-p) 'statement-end
)))
1369 (python-nav-lisp-forward-sexp-safe dir
)
1373 (goto-char next-sexp-pos
)
1375 ((python-info-beginning-of-block-p) 'block-start
)
1376 ((python-info-end-of-block-p) 'block-end
)
1377 ((python-info-beginning-of-statement-p) 'statement-start
)
1378 ((python-info-end-of-statement-p) 'statement-end
)
1379 ((python-info-statement-starts-block-p) 'starts-block
)
1380 ((python-info-statement-ends-block-p) 'ends-block
)))))
1382 (cond ((and (not (eobp))
1383 (python-info-current-line-empty-p))
1384 (python-util-forward-comment dir
)
1385 (python-nav--forward-sexp dir
))
1386 ((eq context
'block-start
)
1387 (python-nav-end-of-block))
1388 ((eq context
'statement-start
)
1389 (python-nav-end-of-statement))
1390 ((and (memq context
'(statement-end block-end
))
1391 (eq next-sexp-context
'ends-block
))
1392 (goto-char next-sexp-pos
)
1393 (python-nav-end-of-block))
1394 ((and (memq context
'(statement-end block-end
))
1395 (eq next-sexp-context
'starts-block
))
1396 (goto-char next-sexp-pos
)
1397 (python-nav-end-of-block))
1398 ((memq context
'(statement-end block-end
))
1399 (goto-char next-sexp-pos
)
1400 (python-nav-end-of-statement))
1401 (t (goto-char next-sexp-pos
)))
1402 (cond ((and (not (bobp))
1403 (python-info-current-line-empty-p))
1404 (python-util-forward-comment dir
)
1405 (python-nav--forward-sexp dir
))
1406 ((eq context
'block-end
)
1407 (python-nav-beginning-of-block))
1408 ((eq context
'statement-end
)
1409 (python-nav-beginning-of-statement))
1410 ((and (memq context
'(statement-start block-start
))
1411 (eq next-sexp-context
'starts-block
))
1412 (goto-char next-sexp-pos
)
1413 (python-nav-beginning-of-block))
1414 ((and (memq context
'(statement-start block-start
))
1415 (eq next-sexp-context
'ends-block
))
1416 (goto-char next-sexp-pos
)
1417 (python-nav-beginning-of-block))
1418 ((memq context
'(statement-start block-start
))
1419 (goto-char next-sexp-pos
)
1420 (python-nav-beginning-of-statement))
1421 (t (goto-char next-sexp-pos
))))))))))
1423 (defun python-nav--backward-sexp ()
1424 "Move to backward sexp."
1425 (python-nav--forward-sexp -
1))
1427 (defun python-nav-forward-sexp (&optional arg
)
1428 "Move forward across one block of code.
1429 With ARG, do it that many times. Negative arg -N means
1430 move backward N times."
1432 (or arg
(setq arg
1))
1434 (python-nav--forward-sexp)
1435 (setq arg
(1- arg
)))
1437 (python-nav--backward-sexp)
1438 (setq arg
(1+ arg
))))
1440 (defun python-nav--up-list (&optional dir
)
1441 "Internal implementation of `python-nav-up-list'.
1442 DIR is always 1 or -1 and comes sanitized from
1443 `python-nav-up-list' calls."
1444 (let ((context (python-syntax-context-type))
1445 (forward-p (> dir
0)))
1447 ((memq context
'(string comment
)))
1448 ((eq context
'paren
)
1449 (let ((forward-sexp-function))
1451 ((and forward-p
(python-info-end-of-block-p))
1452 (let ((parent-end-pos
1454 (let ((indentation (and
1455 (python-nav-beginning-of-block)
1456 (current-indentation))))
1457 (while (and indentation
1459 (>= (current-indentation) indentation
)
1460 (python-nav-backward-block)))
1461 (python-nav-end-of-block)))))
1462 (and (> (or parent-end-pos
(point)) (point))
1463 (goto-char parent-end-pos
))))
1464 (forward-p (python-nav-end-of-block))
1465 ((and (not forward-p
)
1466 (> (current-indentation) 0)
1467 (python-info-beginning-of-block-p))
1468 (let ((prev-block-pos
1470 (let ((indentation (current-indentation)))
1471 (while (and (python-nav-backward-block)
1472 (>= (current-indentation) indentation
))))
1474 (and (> (point) prev-block-pos
)
1475 (goto-char prev-block-pos
))))
1476 ((not forward-p
) (python-nav-beginning-of-block)))))
1478 (defun python-nav-up-list (&optional arg
)
1479 "Move forward out of one level of parentheses (or blocks).
1480 With ARG, do this that many times.
1481 A negative argument means move backward but still to a less deep spot.
1482 This command assumes point is not in a string or comment."
1484 (or arg
(setq arg
1))
1486 (python-nav--up-list 1)
1487 (setq arg
(1- arg
)))
1489 (python-nav--up-list -
1)
1490 (setq arg
(1+ arg
))))
1492 (defun python-nav-backward-up-list (&optional arg
)
1493 "Move backward out of one level of parentheses (or blocks).
1494 With ARG, do this that many times.
1495 A negative argument means move backward but still to a less deep spot.
1496 This command assumes point is not in a string or comment."
1498 (or arg
(setq arg
1))
1499 (python-nav-up-list (- arg
)))
1502 ;;; Shell integration
1504 (defcustom python-shell-buffer-name
"Python"
1505 "Default buffer name for Python interpreter."
1510 (defcustom python-shell-interpreter
"python"
1511 "Default Python interpreter for shell."
1515 (defcustom python-shell-internal-buffer-name
"Python Internal"
1516 "Default buffer name for the Internal Python interpreter."
1521 (defcustom python-shell-interpreter-args
"-i"
1522 "Default arguments for the Python interpreter."
1526 (defcustom python-shell-prompt-regexp
">>> "
1527 "Regular Expression matching top\-level input prompt of python shell.
1528 It should not contain a caret (^) at the beginning."
1533 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1534 "Regular Expression matching block input prompt of python shell.
1535 It should not contain a caret (^) at the beginning."
1540 (defcustom python-shell-prompt-output-regexp
""
1541 "Regular Expression matching output prompt of python shell.
1542 It should not contain a caret (^) at the beginning."
1547 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1548 "Regular Expression matching pdb input prompt of python shell.
1549 It should not contain a caret (^) at the beginning."
1554 (defcustom python-shell-enable-font-lock t
1555 "Should syntax highlighting be enabled in the python shell buffer?
1556 Restart the python shell after changing this variable for it to take effect."
1561 (defcustom python-shell-process-environment nil
1562 "List of environment variables for Python shell.
1563 This variable follows the same rules as `process-environment'
1564 since it merges with it before the process creation routines are
1565 called. When this variable is nil, the Python shell is run with
1566 the default `process-environment'."
1567 :type
'(repeat string
)
1571 (defcustom python-shell-extra-pythonpaths nil
1572 "List of extra pythonpaths for Python shell.
1573 The values of this variable are added to the existing value of
1574 PYTHONPATH in the `process-environment' variable."
1575 :type
'(repeat string
)
1579 (defcustom python-shell-exec-path nil
1580 "List of path to search for binaries.
1581 This variable follows the same rules as `exec-path' since it
1582 merges with it before the process creation routines are called.
1583 When this variable is nil, the Python shell is run with the
1584 default `exec-path'."
1585 :type
'(repeat string
)
1589 (defcustom python-shell-virtualenv-path nil
1590 "Path to virtualenv root.
1591 This variable, when set to a string, makes the values stored in
1592 `python-shell-process-environment' and `python-shell-exec-path'
1593 to be modified properly so shells are started with the specified
1599 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1600 python-ffap-setup-code
1601 python-eldoc-setup-code
)
1602 "List of code run by `python-shell-send-setup-codes'."
1603 :type
'(repeat symbol
)
1607 (defcustom python-shell-compilation-regexp-alist
1608 `((,(rx line-start
(1+ (any " \t")) "File \""
1609 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1610 "\", line " (group (1+ digit
)))
1612 (,(rx " in file " (group (1+ not-newline
)) " on line "
1615 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1616 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1618 "`compilation-error-regexp-alist' for inferior Python."
1619 :type
'(alist string
)
1622 (defun python-shell-get-process-name (dedicated)
1623 "Calculate the appropriate process name for inferior Python process.
1624 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1625 returns a string with the form
1626 `python-shell-buffer-name'[variable `buffer-file-name'] else
1627 returns the value of `python-shell-buffer-name'."
1631 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1632 (format "%s" python-shell-buffer-name
))))
1635 (defun python-shell-internal-get-process-name ()
1636 "Calculate the appropriate process name for Internal Python process.
1637 The name is calculated from `python-shell-global-buffer-name' and
1638 a hash of all relevant global shell settings in order to ensure
1639 uniqueness for different types of configurations."
1641 python-shell-internal-buffer-name
1644 (python-shell-parse-command)
1645 python-shell-prompt-regexp
1646 python-shell-prompt-block-regexp
1647 python-shell-prompt-output-regexp
1648 (mapconcat #'symbol-value python-shell-setup-codes
"")
1649 (mapconcat #'identity python-shell-process-environment
"")
1650 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1651 (mapconcat #'identity python-shell-exec-path
"")
1652 (or python-shell-virtualenv-path
"")
1653 (mapconcat #'identity python-shell-exec-path
"")))))
1655 (defun python-shell-parse-command ()
1656 "Calculate the string used to execute the inferior Python process."
1657 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1659 (defun python-shell-calculate-process-environment ()
1660 "Calculate process environment given `python-shell-virtualenv-path'."
1661 (let ((process-environment (append
1662 python-shell-process-environment
1663 process-environment nil
))
1664 (virtualenv (if python-shell-virtualenv-path
1665 (directory-file-name python-shell-virtualenv-path
)
1667 (when python-shell-extra-pythonpaths
1668 (setenv "PYTHONPATH"
1670 (mapconcat 'identity
1671 python-shell-extra-pythonpaths
1674 (or (getenv "PYTHONPATH") ""))))
1675 (if (not virtualenv
)
1677 (setenv "PYTHONHOME" nil
)
1678 (setenv "PATH" (format "%s/bin%s%s"
1679 virtualenv path-separator
1680 (or (getenv "PATH") "")))
1681 (setenv "VIRTUAL_ENV" virtualenv
))
1682 process-environment
))
1684 (defun python-shell-calculate-exec-path ()
1685 "Calculate exec path given `python-shell-virtualenv-path'."
1686 (let ((path (append python-shell-exec-path
1688 (if (not python-shell-virtualenv-path
)
1690 (cons (format "%s/bin"
1691 (directory-file-name python-shell-virtualenv-path
))
1694 (defun python-comint-output-filter-function (output)
1695 "Hook run after content is put into comint buffer.
1696 OUTPUT is a string with the contents of the buffer."
1697 (ansi-color-filter-apply output
))
1699 (defvar python-shell--parent-buffer nil
)
1701 (defvar python-shell-output-syntax-table
1702 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1703 (modify-syntax-entry ?
\' "." table
)
1704 (modify-syntax-entry ?
\" "." table
)
1705 (modify-syntax-entry ?\
( "." table
)
1706 (modify-syntax-entry ?\
[ "." table
)
1707 (modify-syntax-entry ?\
{ "." table
)
1708 (modify-syntax-entry ?\
) "." table
)
1709 (modify-syntax-entry ?\
] "." table
)
1710 (modify-syntax-entry ?\
} "." table
)
1712 "Syntax table for shell output.
1713 It makes parens and quotes be treated as punctuation chars.")
1715 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1716 "Major mode for Python inferior process.
1717 Runs a Python interpreter as a subprocess of Emacs, with Python
1718 I/O through an Emacs buffer. Variables
1719 `python-shell-interpreter' and `python-shell-interpreter-args'
1720 controls which Python interpreter is run. Variables
1721 `python-shell-prompt-regexp',
1722 `python-shell-prompt-output-regexp',
1723 `python-shell-prompt-block-regexp',
1724 `python-shell-enable-font-lock',
1725 `python-shell-completion-setup-code',
1726 `python-shell-completion-string-code',
1727 `python-shell-completion-module-string-code',
1728 `python-eldoc-setup-code', `python-eldoc-string-code',
1729 `python-ffap-setup-code' and `python-ffap-string-code' can
1730 customize this mode for different Python interpreters.
1732 You can also add additional setup code to be run at
1733 initialization of the interpreter via `python-shell-setup-codes'
1736 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1737 (and python-shell--parent-buffer
1738 (python-util-clone-local-variables python-shell--parent-buffer
))
1739 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1740 python-shell-prompt-regexp
1741 python-shell-prompt-block-regexp
1742 python-shell-prompt-pdb-regexp
))
1743 (setq mode-line-process
'(":%s"))
1744 (make-local-variable 'comint-output-filter-functions
)
1745 (add-hook 'comint-output-filter-functions
1746 'python-comint-output-filter-function
)
1747 (add-hook 'comint-output-filter-functions
1748 'python-pdbtrack-comint-output-filter-function
)
1749 (set (make-local-variable 'compilation-error-regexp-alist
)
1750 python-shell-compilation-regexp-alist
)
1751 (define-key inferior-python-mode-map
[remap complete-symbol
]
1752 'completion-at-point
)
1753 (add-hook 'completion-at-point-functions
1754 'python-shell-completion-complete-at-point nil
'local
)
1755 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1756 'python-shell-completion-complete-at-point
)
1757 (define-key inferior-python-mode-map
"\t"
1758 'python-shell-completion-complete-or-indent
)
1759 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1760 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1761 (make-local-variable 'python-shell-internal-last-output
)
1762 (when python-shell-enable-font-lock
1763 (set-syntax-table python-mode-syntax-table
)
1764 (set (make-local-variable 'font-lock-defaults
)
1765 '(python-font-lock-keywords nil nil nil nil
))
1766 (set (make-local-variable 'syntax-propertize-function
)
1768 ;; XXX: Unfortunately eval is needed here to make use of the
1769 ;; dynamic value of `comint-prompt-regexp'.
1770 `(syntax-propertize-rules
1771 (,comint-prompt-regexp
1774 comint-last-input-start end
'syntax-table
1775 python-shell-output-syntax-table
)
1776 ;; XXX: This might look weird, but it is the easiest
1777 ;; way to ensure font lock gets cleaned up before the
1778 ;; current prompt, which is needed for unclosed
1779 ;; strings to not mess up with current input.
1780 (font-lock-unfontify-region comint-last-input-start end
))))
1781 (,(python-rx string-delimiter
)
1783 (and (not (eq (get-text-property start
'field
) 'output
))
1784 (python-syntax-stringify)))))))))
1785 (compilation-shell-minor-mode 1))
1787 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1788 "Create a python shell comint buffer.
1789 CMD is the python command to be executed and PROC-NAME is the
1790 process name the comint buffer will get. After the comint buffer
1791 is created the `inferior-python-mode' is activated. When
1792 optional argument POP is non-nil the buffer is shown. When
1793 optional argument INTERNAL is non-nil this process is run on a
1794 buffer with a name that starts with a space, following the Emacs
1795 convention for temporary/internal buffers, and also makes sure
1796 the user is not queried for confirmation when the process is
1799 (let* ((proc-buffer-name
1800 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1801 (process-environment (python-shell-calculate-process-environment))
1802 (exec-path (python-shell-calculate-exec-path)))
1803 (when (not (comint-check-proc proc-buffer-name
))
1804 (let* ((cmdlist (split-string-and-unquote cmd
))
1805 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1806 (car cmdlist
) nil
(cdr cmdlist
)))
1807 (python-shell--parent-buffer (current-buffer))
1808 (process (get-buffer-process buffer
)))
1809 (with-current-buffer buffer
1810 (inferior-python-mode))
1811 (accept-process-output process
)
1812 (and pop
(pop-to-buffer buffer t
))
1813 (and internal
(set-process-query-on-exit-flag process nil
))))
1817 (defun run-python (cmd &optional dedicated show
)
1818 "Run an inferior Python process.
1819 Input and output via buffer named after
1820 `python-shell-buffer-name'. If there is a process already
1821 running in that buffer, just switch to it.
1823 With argument, allows you to define CMD so you can edit the
1824 command used to call the interpreter and define DEDICATED, so a
1825 dedicated process for the current buffer is open. When numeric
1826 prefix arg is other than 0 or 4 do not SHOW.
1828 Runs the hook `inferior-python-mode-hook' (after the
1829 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1830 process buffer for a list of commands.)"
1832 (if current-prefix-arg
1834 (read-string "Run Python: " (python-shell-parse-command))
1835 (y-or-n-p "Make dedicated process? ")
1836 (= (prefix-numeric-value current-prefix-arg
) 4))
1837 (list (python-shell-parse-command) nil t
)))
1838 (python-shell-make-comint
1839 cmd
(python-shell-get-process-name dedicated
) show
)
1842 (defun run-python-internal ()
1843 "Run an inferior Internal Python process.
1844 Input and output via buffer named after
1845 `python-shell-internal-buffer-name' and what
1846 `python-shell-internal-get-process-name' returns.
1848 This new kind of shell is intended to be used for generic
1849 communication related to defined configurations, the main
1850 difference with global or dedicated shells is that these ones are
1851 attached to a configuration, not a buffer. This means that can
1852 be used for example to retrieve the sys.path and other stuff,
1853 without messing with user shells. Note that
1854 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1855 are set to nil for these shells, so setup codes are not sent at
1857 (let ((python-shell-enable-font-lock nil
)
1858 (inferior-python-mode-hook nil
))
1860 (python-shell-make-comint
1861 (python-shell-parse-command)
1862 (python-shell-internal-get-process-name) nil t
))))
1864 (defun python-shell-get-process ()
1865 "Get inferior Python process for current buffer and return it."
1866 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1867 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1868 (global-proc-name (python-shell-get-process-name nil
))
1869 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1870 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1871 (global-running (comint-check-proc global-proc-buffer-name
)))
1872 ;; Always prefer dedicated
1873 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1874 (and global-running global-proc-buffer-name
)))))
1876 (defun python-shell-get-or-create-process ()
1877 "Get or create an inferior Python process for current buffer and return it."
1878 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1879 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1880 (global-proc-name (python-shell-get-process-name nil
))
1881 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1882 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1883 (global-running (comint-check-proc global-proc-buffer-name
))
1884 (current-prefix-arg 16))
1885 (when (and (not dedicated-running
) (not global-running
))
1886 (if (call-interactively 'run-python
)
1887 (setq dedicated-running t
)
1888 (setq global-running t
)))
1889 ;; Always prefer dedicated
1890 (get-buffer-process (if dedicated-running
1891 dedicated-proc-buffer-name
1892 global-proc-buffer-name
))))
1894 (defvar python-shell-internal-buffer nil
1895 "Current internal shell buffer for the current buffer.
1896 This is really not necessary at all for the code to work but it's
1897 there for compatibility with CEDET.")
1899 (defvar python-shell-internal-last-output nil
1900 "Last output captured by the internal shell.
1901 This is really not necessary at all for the code to work but it's
1902 there for compatibility with CEDET.")
1904 (defun python-shell-internal-get-or-create-process ()
1905 "Get or create an inferior Internal Python process."
1906 (let* ((proc-name (python-shell-internal-get-process-name))
1907 (proc-buffer-name (format " *%s*" proc-name
)))
1908 (when (not (process-live-p proc-name
))
1909 (run-python-internal)
1910 (setq python-shell-internal-buffer proc-buffer-name
)
1911 ;; XXX: Why is this `sit-for' needed?
1912 ;; `python-shell-make-comint' calls `accept-process-output'
1913 ;; already but it is not helping to get proper output on
1914 ;; 'gnu/linux when the internal shell process is not running and
1915 ;; a call to `python-shell-internal-send-string' is issued.
1917 (get-buffer-process proc-buffer-name
)))
1919 (define-obsolete-function-alias
1920 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1922 (define-obsolete-variable-alias
1923 'python-buffer
'python-shell-internal-buffer
"24.3")
1925 (define-obsolete-variable-alias
1926 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1928 (defun python-shell-send-string (string &optional process msg
)
1929 "Send STRING to inferior Python PROCESS.
1930 When MSG is non-nil messages the first line of STRING."
1931 (interactive "sPython command: ")
1932 (let ((process (or process
(python-shell-get-or-create-process)))
1933 (lines (split-string string
"\n" t
)))
1934 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1935 (if (> (length lines
) 1)
1936 (let* ((temporary-file-directory
1937 (if (file-remote-p default-directory
)
1938 (concat (file-remote-p default-directory
) "/tmp")
1939 temporary-file-directory
))
1940 (temp-file-name (make-temp-file "py"))
1941 (file-name (or (buffer-file-name) temp-file-name
)))
1942 (with-temp-file temp-file-name
1944 (delete-trailing-whitespace))
1945 (python-shell-send-file file-name process temp-file-name
))
1946 (comint-send-string process string
)
1947 (when (or (not (string-match "\n$" string
))
1948 (string-match "\n[ \t].*\n?$" string
))
1949 (comint-send-string process
"\n")))))
1951 (defvar python-shell-output-filter-in-progress nil
)
1952 (defvar python-shell-output-filter-buffer nil
)
1954 (defun python-shell-output-filter (string)
1955 "Filter used in `python-shell-send-string-no-output' to grab output.
1956 STRING is the output received to this point from the process.
1957 This filter saves received output from the process in
1958 `python-shell-output-filter-buffer' and stops receiving it after
1959 detecting a prompt at the end of the buffer."
1961 string
(ansi-color-filter-apply string
)
1962 python-shell-output-filter-buffer
1963 (concat python-shell-output-filter-buffer string
))
1965 ;; XXX: It seems on OSX an extra carriage return is attached
1966 ;; at the end of output, this handles that too.
1967 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1968 python-shell-prompt-regexp
1969 python-shell-prompt-block-regexp
1970 python-shell-prompt-pdb-regexp
)
1971 python-shell-output-filter-buffer
)
1972 ;; Output ends when `python-shell-output-filter-buffer' contains
1973 ;; the prompt attached at the end of it.
1974 (setq python-shell-output-filter-in-progress nil
1975 python-shell-output-filter-buffer
1976 (substring python-shell-output-filter-buffer
1977 0 (match-beginning 0)))
1978 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1979 (string-match (concat "^" python-shell-prompt-output-regexp
)
1980 python-shell-output-filter-buffer
))
1981 ;; Some shells, like iPython might append a prompt before the
1982 ;; output, clean that.
1983 (setq python-shell-output-filter-buffer
1984 (substring python-shell-output-filter-buffer
(match-end 0)))))
1987 (defun python-shell-send-string-no-output (string &optional process msg
)
1988 "Send STRING to PROCESS and inhibit output.
1989 When MSG is non-nil messages the first line of STRING. Return
1991 (let ((process (or process
(python-shell-get-or-create-process)))
1992 (comint-preoutput-filter-functions
1993 '(python-shell-output-filter))
1994 (python-shell-output-filter-in-progress t
)
1998 (python-shell-send-string string process msg
)
1999 (while python-shell-output-filter-in-progress
2000 ;; `python-shell-output-filter' takes care of setting
2001 ;; `python-shell-output-filter-in-progress' to NIL after it
2002 ;; detects end of output.
2003 (accept-process-output process
))
2005 python-shell-output-filter-buffer
2006 (setq python-shell-output-filter-buffer nil
)))
2007 (with-current-buffer (process-buffer process
)
2008 (comint-interrupt-subjob)))))
2010 (defun python-shell-internal-send-string (string)
2011 "Send STRING to the Internal Python interpreter.
2012 Returns the output. See `python-shell-send-string-no-output'."
2013 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2014 ;; updated to support this new mode.
2015 (setq python-shell-internal-last-output
2016 (python-shell-send-string-no-output
2017 ;; Makes this function compatible with the old
2018 ;; python-send-receive. (At least for CEDET).
2019 (replace-regexp-in-string "_emacs_out +" "" string
)
2020 (python-shell-internal-get-or-create-process) nil
)))
2022 (define-obsolete-function-alias
2023 'python-send-receive
'python-shell-internal-send-string
"24.3")
2025 (define-obsolete-function-alias
2026 'python-send-string
'python-shell-internal-send-string
"24.3")
2028 (defun python-shell-send-region (start end
)
2029 "Send the region delimited by START and END to inferior Python process."
2031 (python-shell-send-string
2033 (let ((line-num (line-number-at-pos start
)))
2034 ;; When sending a region, add blank lines for non sent code so
2035 ;; backtraces remain correct.
2036 (make-string (1- line-num
) ?
\n))
2037 (buffer-substring start end
))
2040 (defun python-shell-send-buffer (&optional arg
)
2041 "Send the entire buffer to inferior Python process.
2042 With prefix ARG allow execution of code inside blocks delimited
2043 by \"if __name__== '__main__':\""
2047 (let ((str (buffer-substring (point-min) (point-max))))
2050 (setq str
(replace-regexp-in-string
2051 (python-rx if-name-main
)
2052 "if __name__ == '__main__ ':" str
)))
2053 (python-shell-send-string str
))))
2055 (defun python-shell-send-defun (arg)
2056 "Send the current defun to inferior Python process.
2057 When argument ARG is non-nil do not include decorators."
2060 (python-shell-send-region
2063 (while (and (or (python-nav-beginning-of-defun)
2064 (beginning-of-line 1))
2065 (> (current-indentation) 0)))
2067 (while (and (forward-line -
1)
2068 (looking-at (python-rx decorator
))))
2072 (or (python-nav-end-of-defun)
2076 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2077 "Send FILE-NAME to inferior Python PROCESS.
2078 If TEMP-FILE-NAME is passed then that file is used for processing
2079 instead, while internally the shell will continue to use
2081 (interactive "fFile to send: ")
2082 (let* ((process (or process
(python-shell-get-or-create-process)))
2083 (temp-file-name (when temp-file-name
2085 (or (file-remote-p temp-file-name
'localname
)
2087 (file-name (or (when file-name
2089 (or (file-remote-p file-name
'localname
)
2092 (when (not file-name
)
2093 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2094 (python-shell-send-string
2096 (concat "__pyfile = open('''%s''');"
2097 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2099 (or temp-file-name file-name
) file-name
)
2102 (defun python-shell-switch-to-shell ()
2103 "Switch to inferior Python process buffer."
2105 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2107 (defun python-shell-send-setup-code ()
2108 "Send all setup code for shell.
2109 This function takes the list of setup code to send from the
2110 `python-shell-setup-codes' list."
2111 (let ((process (get-buffer-process (current-buffer))))
2112 (dolist (code python-shell-setup-codes
)
2114 (message "Sent %s" code
)
2115 (python-shell-send-string
2116 (symbol-value code
) process
)))))
2118 (add-hook 'inferior-python-mode-hook
2119 #'python-shell-send-setup-code
)
2122 ;;; Shell completion
2124 (defcustom python-shell-completion-setup-code
2128 def __COMPLETER_all_completions(text): []
2131 readline.set_completer(rlcompleter.Completer().complete)
2132 def __COMPLETER_all_completions(text):
2138 res = readline.get_completer()(text, i)
2141 completions.append(res)
2145 "Code used to setup completion in inferior Python processes."
2149 (defcustom python-shell-completion-string-code
2150 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2151 "Python code used to get a string of completions separated by semicolons."
2155 (defcustom python-shell-completion-module-string-code
""
2156 "Python code used to get completions separated by semicolons for imports.
2158 For IPython v0.11, add the following line to
2159 `python-shell-completion-setup-code':
2161 from IPython.core.completerlib import module_completion
2163 and use the following as the value of this variable:
2165 ';'.join(module_completion('''%s'''))\n"
2169 (defcustom python-shell-completion-pdb-string-code
2170 "';'.join(globals().keys() + locals().keys())"
2171 "Python code used to get completions separated by semicolons for [i]pdb."
2175 (defun python-shell-completion-get-completions (process line input
)
2176 "Do completion at point for PROCESS.
2177 LINE is used to detect the context on how to complete given
2180 ;; Get the last prompt for the inferior process
2181 ;; buffer. This is used for the completion code selection
2183 (with-current-buffer (process-buffer process
)
2184 (buffer-substring-no-properties
2185 (overlay-start comint-last-prompt-overlay
)
2186 (overlay-end comint-last-prompt-overlay
))))
2188 ;; Check whether a prompt matches a pdb string, an import
2189 ;; statement or just the standard prompt and use the
2190 ;; correct python-shell-completion-*-code string
2191 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2193 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2196 (length python-shell-completion-module-string-code
) 0)
2198 (concat "^" python-shell-prompt-regexp
) prompt
)
2199 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2202 (concat "^" python-shell-prompt-regexp
) prompt
)
2206 (case completion-context
2207 (pdb python-shell-completion-pdb-string-code
)
2208 (import python-shell-completion-module-string-code
)
2209 (default python-shell-completion-string-code
)
2212 (if (eq completion-context
'import
)
2213 (replace-regexp-in-string "^[ \t]+" "" line
)
2215 (and completion-code
2216 (> (length input
) 0)
2217 (with-current-buffer (process-buffer process
)
2218 (let ((completions (python-shell-send-string-no-output
2219 (format completion-code input
) process
)))
2220 (and (> (length completions
) 2)
2221 (split-string completions
2222 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2224 (defun python-shell-completion-complete-at-point (&optional process
)
2225 "Perform completion at point in inferior Python.
2226 Optional argument PROCESS forces completions to be retrieved
2227 using that one instead of current buffer's process."
2228 (setq process
(or process
(get-buffer-process (current-buffer))))
2231 (with-syntax-table python-dotty-syntax-table
2232 (let* ((paren-depth (car (syntax-ppss)))
2233 (syntax-string "w_")
2234 (syntax-list (string-to-syntax syntax-string
)))
2235 ;; Stop scanning for the beginning of the completion
2236 ;; subject after the char before point matches a
2239 (car (syntax-after (1- (point)))) syntax-list
)
2240 (skip-syntax-backward syntax-string
)
2241 (when (or (equal (char-before) ?\
))
2242 (equal (char-before) ?
\"))
2245 ;; honor initial paren depth
2246 (> (car (syntax-ppss)) paren-depth
)
2247 (python-syntax-context 'string
))
2252 (completion-table-dynamic
2254 #'python-shell-completion-get-completions
2255 process
(buffer-substring-no-properties
2256 (line-beginning-position) end
))))))
2258 (defun python-shell-completion-complete-or-indent ()
2259 "Complete or indent depending on the context.
2260 If content before pointer is all whitespace indent. If not try
2263 (if (string-match "^[[:space:]]*$"
2264 (buffer-substring (comint-line-beginning-position)
2266 (indent-for-tab-command)
2267 (completion-at-point)))
2270 ;;; PDB Track integration
2272 (defcustom python-pdbtrack-activate t
2273 "Non-nil makes python shell enable pdbtracking."
2278 (defcustom python-pdbtrack-stacktrace-info-regexp
2279 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2280 "Regular Expression matching stacktrace information.
2281 Used to extract the current line and module being inspected."
2286 (defvar python-pdbtrack-tracked-buffer nil
2287 "Variable containing the value of the current tracked buffer.
2288 Never set this variable directly, use
2289 `python-pdbtrack-set-tracked-buffer' instead.")
2291 (defvar python-pdbtrack-buffers-to-kill nil
2292 "List of buffers to be deleted after tracking finishes.")
2294 (defun python-pdbtrack-set-tracked-buffer (file-name)
2295 "Set the buffer for FILE-NAME as the tracked buffer.
2296 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2297 Returns the tracked buffer."
2298 (let ((file-buffer (get-file-buffer file-name
)))
2300 (setq python-pdbtrack-tracked-buffer file-buffer
)
2301 (setq file-buffer
(find-file-noselect file-name
))
2302 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2303 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2306 (defun python-pdbtrack-comint-output-filter-function (output)
2307 "Move overlay arrow to current pdb line in tracked buffer.
2308 Argument OUTPUT is a string with the output from the comint process."
2309 (when (and python-pdbtrack-activate
(not (string= output
"")))
2310 (let* ((full-output (ansi-color-filter-apply
2311 (buffer-substring comint-last-input-end
(point-max))))
2315 (insert full-output
)
2316 (goto-char (point-min))
2317 ;; OK, this sucked but now it became a cool hack. The
2318 ;; stacktrace information normally is on the first line
2319 ;; but in some cases (like when doing a step-in) it is
2321 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2324 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2325 (setq line-number
(string-to-number
2326 (match-string-no-properties 2)))
2327 (match-string-no-properties 1)))))
2328 (if (and file-name line-number
)
2329 (let* ((tracked-buffer
2330 (python-pdbtrack-set-tracked-buffer file-name
))
2331 (shell-buffer (current-buffer))
2332 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2333 (tracked-buffer-line-pos))
2334 (with-current-buffer tracked-buffer
2335 (set (make-local-variable 'overlay-arrow-string
) "=>")
2336 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2337 (setq tracked-buffer-line-pos
(progn
2338 (goto-char (point-min))
2339 (forward-line (1- line-number
))
2341 (when tracked-buffer-window
2343 tracked-buffer-window tracked-buffer-line-pos
))
2344 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2345 (pop-to-buffer tracked-buffer
)
2346 (switch-to-buffer-other-window shell-buffer
))
2347 (when python-pdbtrack-tracked-buffer
2348 (with-current-buffer python-pdbtrack-tracked-buffer
2349 (set-marker overlay-arrow-position nil
))
2350 (mapc #'(lambda (buffer)
2351 (ignore-errors (kill-buffer buffer
)))
2352 python-pdbtrack-buffers-to-kill
)
2353 (setq python-pdbtrack-tracked-buffer nil
2354 python-pdbtrack-buffers-to-kill nil
)))))
2358 ;;; Symbol completion
2360 (defun python-completion-complete-at-point ()
2361 "Complete current symbol at point.
2362 For this to work the best as possible you should call
2363 `python-shell-send-buffer' from time to time so context in
2364 inferior python process is updated properly."
2365 (let ((process (python-shell-get-process)))
2367 (error "Completion needs an inferior Python process running")
2368 (python-shell-completion-complete-at-point process
))))
2370 (add-to-list 'debug-ignored-errors
2371 "^Completion needs an inferior Python process running.")
2376 (defcustom python-fill-comment-function
'python-fill-comment
2377 "Function to fill comments.
2378 This is the function used by `python-fill-paragraph' to
2383 (defcustom python-fill-string-function
'python-fill-string
2384 "Function to fill strings.
2385 This is the function used by `python-fill-paragraph' to
2390 (defcustom python-fill-decorator-function
'python-fill-decorator
2391 "Function to fill decorators.
2392 This is the function used by `python-fill-paragraph' to
2397 (defcustom python-fill-paren-function
'python-fill-paren
2398 "Function to fill parens.
2399 This is the function used by `python-fill-paragraph' to
2404 (defcustom python-fill-docstring-style
'pep-257
2405 "Style used to fill docstrings.
2406 This affects `python-fill-string' behavior with regards to
2407 triple quotes positioning.
2409 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2410 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2411 position and will treat docstrings a normal string, any other
2412 value may result in one of the following docstring styles:
2417 Process foo, return bar.
2421 Process foo, return bar.
2423 If processing fails throw ProcessingError.
2428 \"\"\"Process foo, return bar.\"\"\"
2431 Process foo, return bar.
2433 If processing fails throw ProcessingError.
2439 \"\"\"Process foo, return bar.\"\"\"
2441 \"\"\"Process foo, return bar.
2443 If processing fails throw ProcessingError.
2449 \"\"\"Process foo, return bar.\"\"\"
2451 \"\"\"Process foo, return bar.
2453 If processing fails throw ProcessingError.
2458 \"\"\"Process foo, return bar.\"\"\"
2461 Process foo, return bar.
2463 If processing fails throw ProcessingError.
2466 (const :tag
"Don't format docstrings" nil
)
2467 (const :tag
"Django's coding standards style." django
)
2468 (const :tag
"One newline and start and Two at end style." onetwo
)
2469 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2470 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2471 (const :tag
"Symmetric style." symmetric
))
2474 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2476 (defun python-fill-paragraph (&optional justify
)
2477 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2478 If any of the current line is in or at the end of a multi-line string,
2479 fill the string or the paragraph of it that point is in, preserving
2480 the string's indentation.
2481 Optional argument JUSTIFY defines if the paragraph should be justified."
2486 ((python-syntax-context 'comment
)
2487 (funcall python-fill-comment-function justify
))
2488 ;; Strings/Docstrings
2489 ((save-excursion (or (python-syntax-context 'string
)
2490 (equal (string-to-syntax "|")
2491 (syntax-after (point)))))
2492 (funcall python-fill-string-function justify
))
2494 ((equal (char-after (save-excursion
2495 (python-nav-beginning-of-statement))) ?
@)
2496 (funcall python-fill-decorator-function justify
))
2498 ((or (python-syntax-context 'paren
)
2499 (looking-at (python-rx open-paren
))
2501 (skip-syntax-forward "^(" (line-end-position))
2502 (looking-at (python-rx open-paren
))))
2503 (funcall python-fill-paren-function justify
))
2506 (defun python-fill-comment (&optional justify
)
2507 "Comment fill function for `python-fill-paragraph'.
2508 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2509 (fill-comment-paragraph justify
))
2511 (defun python-fill-string (&optional justify
)
2512 "String fill function for `python-fill-paragraph'.
2513 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2514 (let* ((marker (point-marker))
2516 (let ((m (make-marker)))
2517 (setf (marker-position m
)
2518 (or (python-syntax-context 'string
)
2519 (and (equal (string-to-syntax "|")
2520 (syntax-after (point)))
2522 (num-quotes (python-syntax-count-quotes
2523 (char-after str-start-pos
) str-start-pos
))
2526 (goto-char (+ str-start-pos num-quotes
))
2527 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2528 (goto-char (point-max)))
2531 ;; Docstring styles may vary for oneliners and multi-liners.
2532 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2534 (case python-fill-docstring-style
2535 ;; delimiters-style is a cons cell with the form
2536 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2537 ;; is NIL means to not add any newlines for start or end
2538 ;; of docstring. See `python-fill-docstring-style' for a
2539 ;; graphic idea of each style.
2541 (onetwo (and multi-line-p
(cons 1 2)))
2542 (pep-257 (and multi-line-p
(cons nil
2)))
2543 (pep-257-nn (and multi-line-p
(cons nil
1)))
2544 (symmetric (and multi-line-p
(cons 1 1)))))
2545 (docstring-p (save-excursion
2546 ;; Consider docstrings those strings which
2547 ;; start on a line by themselves.
2548 (python-nav-beginning-of-statement)
2549 (and (= (point) str-start-pos
))))
2550 (fill-paragraph-function))
2552 (narrow-to-region str-start-pos str-end-pos
)
2553 (fill-paragraph justify
))
2555 (when (and docstring-p python-fill-docstring-style
)
2556 ;; Add the number of newlines indicated by the selected style
2557 ;; at the start of the docstring.
2558 (goto-char (+ str-start-pos num-quotes
))
2559 (delete-region (point) (progn
2560 (skip-syntax-forward "> ")
2562 (and (car delimiters-style
)
2563 (or (newline (car delimiters-style
)) t
)
2564 ;; Indent only if a newline is added.
2565 (indent-according-to-mode))
2566 ;; Add the number of newlines indicated by the selected style
2567 ;; at the end of the docstring.
2568 (goto-char (if (not (= str-end-pos
(point-max)))
2569 (- str-end-pos num-quotes
)
2571 (delete-region (point) (progn
2572 (skip-syntax-backward "> ")
2574 (and (cdr delimiters-style
)
2575 ;; Add newlines only if string ends.
2576 (not (= str-end-pos
(point-max)))
2577 (or (newline (cdr delimiters-style
)) t
)
2578 ;; Again indent only if a newline is added.
2579 (indent-according-to-mode))))) t
)
2581 (defun python-fill-decorator (&optional justify
)
2582 "Decorator fill function for `python-fill-paragraph'.
2583 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2586 (defun python-fill-paren (&optional justify
)
2587 "Paren fill function for `python-fill-paragraph'.
2588 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2590 (narrow-to-region (progn
2591 (while (python-syntax-context 'paren
)
2592 (goto-char (1- (point-marker))))
2594 (line-beginning-position))
2596 (when (not (python-syntax-context 'paren
))
2598 (when (not (python-syntax-context 'paren
))
2599 (skip-syntax-backward "^)")))
2600 (while (python-syntax-context 'paren
)
2601 (goto-char (1+ (point-marker))))
2603 (let ((paragraph-start "\f\\|[ \t]*$")
2604 (paragraph-separate ",")
2605 (fill-paragraph-function))
2606 (goto-char (point-min))
2607 (fill-paragraph justify
))
2610 (python-indent-line)
2611 (goto-char (line-end-position)))) t
)
2616 (defcustom python-skeleton-autoinsert nil
2617 "Non-nil means template skeletons will be automagically inserted.
2618 This happens when pressing \"if<SPACE>\", for example, to prompt for
2624 (define-obsolete-variable-alias
2625 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2627 (defvar python-skeleton-available
'()
2628 "Internal list of available skeletons.")
2630 (define-abbrev-table 'python-mode-abbrev-table
()
2631 "Abbrev table for Python mode."
2633 ;; Allow / inside abbrevs.
2634 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2635 ;; Only expand in code.
2636 :enable-function
(lambda ()
2638 (not (python-syntax-comment-or-string-p))
2639 python-skeleton-autoinsert
)))
2641 (defmacro python-skeleton-define
(name doc
&rest skel
)
2642 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2643 The skeleton will be bound to python-skeleton-NAME and will
2644 be added to `python-mode-abbrev-table'."
2645 (declare (indent 2))
2646 (let* ((name (symbol-name name
))
2647 (function-name (intern (concat "python-skeleton-" name
))))
2649 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2651 (setq python-skeleton-available
2652 (cons ',function-name python-skeleton-available
))
2653 (define-skeleton ,function-name
2655 (format "Insert %s statement." name
))
2658 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2659 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2660 The skeleton will be bound to python-skeleton-NAME."
2661 (declare (indent 2))
2662 (let* ((name (symbol-name name
))
2663 (function-name (intern (concat "python-skeleton--" name
)))
2665 "Add '%s' clause? " name
)))
2668 `(< ,(format "%s:" name
) \n \n
2670 `(define-skeleton ,function-name
2672 (format "Auxiliary skeleton for %s statement." name
))
2674 (unless (y-or-n-p ,msg
)
2678 (python-define-auxiliary-skeleton else nil
)
2680 (python-define-auxiliary-skeleton except nil
)
2682 (python-define-auxiliary-skeleton finally nil
)
2684 (python-skeleton-define if nil
2688 ("other condition, %s: "
2692 '(python-skeleton--else) | ^
)
2694 (python-skeleton-define while nil
2698 '(python-skeleton--else) | ^
)
2700 (python-skeleton-define for nil
2704 '(python-skeleton--else) | ^
)
2706 (python-skeleton-define try nil
2712 "except " str
":" \n
2715 '(python-skeleton--except)
2716 '(python-skeleton--else)
2717 '(python-skeleton--finally) | ^
)
2719 (python-skeleton-define def nil
2721 "def " str
"(" ("Parameter, %s: "
2722 (unless (equal ?\
( (char-before)) ", ")
2724 "\"\"\"" -
"\"\"\"" \n
2727 (python-skeleton-define class nil
2729 "class " str
"(" ("Inheritance, %s: "
2730 (unless (equal ?\
( (char-before)) ", ")
2734 "\"\"\"" -
"\"\"\"" \n
2737 (defun python-skeleton-add-menu-items ()
2738 "Add menu items to Python->Skeletons menu."
2739 (let ((skeletons (sort python-skeleton-available
'string
<))
2741 (dolist (skeleton skeletons
)
2743 nil
'("Python" "Skeletons")
2745 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2750 (defcustom python-ffap-setup-code
2751 "def __FFAP_get_module_path(module):
2754 path = __import__(module).__file__
2755 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2760 "Python code to get a module path."
2764 (defcustom python-ffap-string-code
2765 "__FFAP_get_module_path('''%s''')\n"
2766 "Python code used to get a string with the path of a module."
2770 (defun python-ffap-module-path (module)
2771 "Function for `ffap-alist' to return path for MODULE."
2773 (and (eq major-mode
'inferior-python-mode
)
2774 (get-buffer-process (current-buffer)))
2775 (python-shell-get-process))))
2779 (python-shell-send-string-no-output
2780 (format python-ffap-string-code module
) process
)))
2782 (substring-no-properties module-file
1 -
1))))))
2784 (eval-after-load "ffap"
2786 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2787 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2792 (defcustom python-check-command
2794 "Command used to check a Python file."
2798 (defcustom python-check-buffer-name
2799 "*Python check: %s*"
2800 "Buffer name used for check commands."
2804 (defvar python-check-custom-command nil
2807 (defun python-check (command)
2808 "Check a Python file (default current buffer's file).
2809 Runs COMMAND, a shell command, as if by `compile'. See
2810 `python-check-command' for the default."
2812 (list (read-string "Check command: "
2813 (or python-check-custom-command
2814 (concat python-check-command
" "
2815 (shell-quote-argument
2817 (let ((name (buffer-file-name)))
2819 (file-name-nondirectory name
)))
2821 (setq python-check-custom-command command
)
2822 (save-some-buffers (not compilation-ask-about-save
) nil
)
2823 (let ((process-environment (python-shell-calculate-process-environment))
2824 (exec-path (python-shell-calculate-exec-path)))
2825 (compilation-start command nil
2827 (format python-check-buffer-name command
)))))
2832 (defcustom python-eldoc-setup-code
2833 "def __PYDOC_get_help(obj):
2836 if hasattr(obj, 'startswith'):
2837 obj = eval(obj, globals())
2838 doc = inspect.getdoc(obj)
2839 if not doc and callable(obj):
2841 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2842 target = obj.__init__
2848 args = inspect.formatargspec(
2849 *inspect.getargspec(target)
2852 doc = '{objtype} {name}{args}'.format(
2853 objtype=objtype, name=name, args=args
2856 doc = doc.splitlines()[0]
2863 "Python code to setup documentation retrieval."
2867 (defcustom python-eldoc-string-code
2868 "__PYDOC_get_help('''%s''')\n"
2869 "Python code used to get a string with the documentation of an object."
2873 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2874 "Internal implementation to get documentation at point.
2875 If not FORCE-INPUT is passed then what
2876 `python-info-current-symbol' returns will be used. If not
2877 FORCE-PROCESS is passed what `python-shell-get-process' returns
2879 (let ((process (or force-process
(python-shell-get-process))))
2881 (error "Eldoc needs an inferior Python process running")
2882 (let ((input (or force-input
2883 (python-info-current-symbol t
))))
2885 (python-shell-send-string-no-output
2886 (format python-eldoc-string-code input
)
2889 (defun python-eldoc-function ()
2890 "`eldoc-documentation-function' for Python.
2891 For this to work the best as possible you should call
2892 `python-shell-send-buffer' from time to time so context in
2893 inferior python process is updated properly."
2894 (python-eldoc--get-doc-at-point))
2896 (defun python-eldoc-at-point (symbol)
2897 "Get help on SYMBOL using `help'.
2898 Interactively, prompt for symbol."
2900 (let ((symbol (python-info-current-symbol t
))
2901 (enable-recursive-minibuffers t
))
2902 (list (read-string (if symbol
2903 (format "Describe symbol (default %s): " symbol
)
2904 "Describe symbol: ")
2906 (message (python-eldoc--get-doc-at-point symbol
)))
2908 (add-to-list 'debug-ignored-errors
2909 "^Eldoc needs an inferior Python process running.")
2914 (defun python-imenu-prev-index-position ()
2915 "Python mode's `imenu-prev-index-position-function'."
2917 (while (and (setq found
2918 (re-search-backward python-nav-beginning-of-defun-regexp nil t
))
2919 (not (python-info-looking-at-beginning-of-defun))))
2921 (python-info-looking-at-beginning-of-defun)
2922 (python-info-current-defun))))
2927 (defun python-info-current-defun (&optional include-type
)
2928 "Return name of surrounding function with Python compatible dotty syntax.
2929 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2930 This function is compatible to be used as
2931 `add-log-current-defun-function' since it returns nil if point is
2932 not inside a defun."
2938 (starting-indentation
2941 (python-nav-beginning-of-defun 1)
2942 ;; This extra number is just for checking code
2943 ;; against indentation to work well on first run.
2944 (+ (current-indentation) 4))))
2945 (starting-point (point)))
2946 ;; Check point is inside a defun.
2947 (when (and starting-indentation
2950 (python-nav-end-of-defun)
2953 (while (python-nav-beginning-of-defun 1)
2954 (when (< (current-indentation) starting-indentation
)
2955 (setq starting-indentation
(current-indentation))
2958 (if (not include-type
)
2959 (match-string-no-properties 1)
2960 (mapconcat 'identity
2962 (match-string-no-properties 0)) " "))
2964 (and (= (current-indentation) 0) (throw 'exit t
)))))
2966 (mapconcat (lambda (string) string
) names
"."))))))
2968 (defun python-info-current-symbol (&optional replace-self
)
2969 "Return current symbol using dotty syntax.
2970 With optional argument REPLACE-SELF convert \"self\" to current
2973 (and (not (python-syntax-comment-or-string-p))
2974 (with-syntax-table python-dotty-syntax-table
2975 (let ((sym (symbol-at-point)))
2977 (substring-no-properties (symbol-name sym
))))))))
2979 (if (not replace-self
)
2981 (let ((current-defun (python-info-current-defun)))
2982 (if (not current-defun
)
2984 (replace-regexp-in-string
2985 (python-rx line-start word-start
"self" word-end ?.
)
2987 (mapconcat 'identity
2988 (butlast (split-string current-defun
"\\."))
2992 (defun python-info-statement-starts-block-p ()
2993 "Return non-nil if current statement opens a block."
2995 (python-nav-beginning-of-statement)
2996 (looking-at (python-rx block-start
))))
2998 (defun python-info-statement-ends-block-p ()
2999 "Return non-nil if point is at end of block."
3000 (let ((end-of-block-pos (save-excursion
3001 (python-nav-end-of-block)))
3002 (end-of-statement-pos (save-excursion
3003 (python-nav-end-of-statement))))
3004 (and end-of-block-pos end-of-statement-pos
3005 (= end-of-block-pos end-of-statement-pos
))))
3007 (defun python-info-beginning-of-statement-p ()
3008 "Return non-nil if point is at beginning of statement."
3009 (= (point) (save-excursion
3010 (python-nav-beginning-of-statement)
3013 (defun python-info-end-of-statement-p ()
3014 "Return non-nil if point is at end of statement."
3015 (= (point) (save-excursion
3016 (python-nav-end-of-statement)
3019 (defun python-info-beginning-of-block-p ()
3020 "Return non-nil if point is at beginning of block."
3021 (and (python-info-beginning-of-statement-p)
3022 (python-info-statement-starts-block-p)))
3024 (defun python-info-end-of-block-p ()
3025 "Return non-nil if point is at end of block."
3026 (and (python-info-end-of-statement-p)
3027 (python-info-statement-ends-block-p)))
3029 (defun python-info-closing-block ()
3030 "Return the point of the block the current line closes."
3031 (let ((closing-word (save-excursion
3032 (back-to-indentation)
3034 (indentation (current-indentation)))
3035 (when (member closing-word python-indent-dedenters
)
3038 (while (and (> (current-indentation) indentation
)
3040 (not (back-to-indentation))
3042 (back-to-indentation)
3044 ((not (equal indentation
(current-indentation))) nil
)
3045 ((string= closing-word
"elif")
3046 (when (member (current-word) '("if" "elif"))
3048 ((string= closing-word
"else")
3049 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3051 ((string= closing-word
"except")
3052 (when (member (current-word) '("try"))
3054 ((string= closing-word
"finally")
3055 (when (member (current-word) '("except" "else"))
3056 (point-marker))))))))
3058 (defun python-info-closing-block-message (&optional closing-block-point
)
3059 "Message the contents of the block the current line closes.
3060 With optional argument CLOSING-BLOCK-POINT use that instead of
3061 recalculating it calling `python-info-closing-block'."
3062 (let ((point (or closing-block-point
(python-info-closing-block))))
3066 (message "Closes %s" (save-excursion
3068 (back-to-indentation)
3070 (point) (line-end-position))))))))
3072 (defun python-info-line-ends-backslash-p (&optional line-number
)
3073 "Return non-nil if current line ends with backslash.
3074 With optional argument LINE-NUMBER, check that line instead."
3079 (goto-char line-number
))
3080 (while (and (not (eobp))
3081 (goto-char (line-end-position))
3082 (python-syntax-context 'paren
)
3083 (not (equal (char-before (point)) ?
\\)))
3085 (when (equal (char-before) ?
\\)
3088 (defun python-info-beginning-of-backslash (&optional line-number
)
3089 "Return the point where the backslashed line start.
3090 Optional argument LINE-NUMBER forces the line number to check against."
3095 (goto-char line-number
))
3096 (when (python-info-line-ends-backslash-p)
3097 (while (save-excursion
3098 (goto-char (line-beginning-position))
3099 (python-syntax-context 'paren
))
3101 (back-to-indentation)
3104 (defun python-info-continuation-line-p ()
3105 "Check if current line is continuation of another.
3106 When current line is continuation of another return the point
3107 where the continued line ends."
3111 (let* ((context-type (progn
3112 (back-to-indentation)
3113 (python-syntax-context-type)))
3114 (line-start (line-number-at-pos))
3115 (context-start (when context-type
3116 (python-syntax-context context-type
))))
3117 (cond ((equal context-type
'paren
)
3118 ;; Lines inside a paren are always a continuation line
3119 ;; (except the first one).
3120 (python-util-forward-comment -
1)
3122 ((member context-type
'(string comment
))
3123 ;; move forward an roll again
3124 (goto-char context-start
)
3125 (python-util-forward-comment)
3126 (python-info-continuation-line-p))
3128 ;; Not within a paren, string or comment, the only way
3129 ;; we are dealing with a continuation line is that
3130 ;; previous line contains a backslash, and this can
3131 ;; only be the previous line from current
3132 (back-to-indentation)
3133 (python-util-forward-comment -
1)
3134 (when (and (equal (1- line-start
) (line-number-at-pos))
3135 (python-info-line-ends-backslash-p))
3136 (point-marker))))))))
3138 (defun python-info-block-continuation-line-p ()
3139 "Return non-nil if current line is a continuation of a block."
3141 (when (python-info-continuation-line-p)
3143 (back-to-indentation)
3144 (when (looking-at (python-rx block-start
))
3147 (defun python-info-assignment-continuation-line-p ()
3148 "Check if current line is a continuation of an assignment.
3149 When current line is continuation of another with an assignment
3150 return the point of the first non-blank character after the
3153 (when (python-info-continuation-line-p)
3155 (back-to-indentation)
3156 (when (and (not (looking-at (python-rx block-start
)))
3157 (and (re-search-forward (python-rx not-simple-operator
3159 not-simple-operator
)
3160 (line-end-position) t
)
3161 (not (python-syntax-context-type))))
3162 (skip-syntax-forward "\s")
3165 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3166 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3167 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3169 (beginning-of-line 1)
3170 (looking-at python-nav-beginning-of-defun-regexp
))))
3172 (defun python-info-current-line-comment-p ()
3173 "Check if current line is a comment line."
3174 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3176 (defun python-info-current-line-empty-p ()
3177 "Check if current line is empty, ignoring whitespace."
3179 (beginning-of-line 1)
3181 (python-rx line-start
(* whitespace
)
3182 (group (* not-newline
))
3183 (* whitespace
) line-end
))
3184 (string-equal "" (match-string-no-properties 1))))
3187 ;;; Utility functions
3189 (defun python-util-position (item seq
)
3190 "Find the first occurrence of ITEM in SEQ.
3191 Return the index of the matching item, or nil if not found."
3192 (let ((member-result (member item seq
)))
3194 (- (length seq
) (length member-result
)))))
3196 ;; Stolen from org-mode
3197 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3198 "Clone local variables from FROM-BUFFER.
3199 Optional argument REGEXP selects variables to clone and defaults
3203 (and (symbolp (car pair
))
3204 (string-match (or regexp
"^python-")
3205 (symbol-name (car pair
)))
3206 (set (make-local-variable (car pair
))
3208 (buffer-local-variables from-buffer
)))
3210 (defun python-util-forward-comment (&optional direction
)
3211 "Python mode specific version of `forward-comment'.
3212 Optional argument DIRECTION defines the direction to move to."
3213 (let ((comment-start (python-syntax-context 'comment
))
3214 (factor (if (< (or direction
0) 0)
3218 (goto-char comment-start
))
3219 (forward-comment factor
)))
3223 (define-derived-mode python-mode prog-mode
"Python"
3224 "Major mode for editing Python files.
3227 Entry to this mode calls the value of `python-mode-hook'
3228 if that value is non-nil."
3229 (set (make-local-variable 'tab-width
) 8)
3230 (set (make-local-variable 'indent-tabs-mode
) nil
)
3232 (set (make-local-variable 'comment-start
) "# ")
3233 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3235 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3236 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3238 (set (make-local-variable 'forward-sexp-function
)
3239 'python-nav-forward-sexp
)
3241 (set (make-local-variable 'font-lock-defaults
)
3242 '(python-font-lock-keywords nil nil nil nil
))
3244 (set (make-local-variable 'syntax-propertize-function
)
3245 python-syntax-propertize-function
)
3247 (set (make-local-variable 'indent-line-function
)
3248 #'python-indent-line-function
)
3249 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3251 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3252 (set (make-local-variable 'fill-paragraph-function
)
3253 'python-fill-paragraph
)
3255 (set (make-local-variable 'beginning-of-defun-function
)
3256 #'python-nav-beginning-of-defun
)
3257 (set (make-local-variable 'end-of-defun-function
)
3258 #'python-nav-end-of-defun
)
3260 (add-hook 'completion-at-point-functions
3261 'python-completion-complete-at-point nil
'local
)
3263 (add-hook 'post-self-insert-hook
3264 'python-indent-post-self-insert-function nil
'local
)
3266 (set (make-local-variable 'imenu-extract-index-name-function
)
3267 #'python-info-current-defun
)
3269 (set (make-local-variable 'imenu-prev-index-position-function
)
3270 #'python-imenu-prev-index-position
)
3272 (set (make-local-variable 'add-log-current-defun-function
)
3273 #'python-info-current-defun
)
3275 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3277 (set (make-local-variable 'skeleton-further-elements
)
3279 (< '(backward-delete-char-untabify (min python-indent-offset
3281 (^
'(- (1+ (current-indentation))))))
3283 (set (make-local-variable 'eldoc-documentation-function
)
3284 #'python-eldoc-function
)
3286 (add-to-list 'hs-special-modes-alist
3287 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3289 (python-nav-end-of-defun)) nil
))
3291 (set (make-local-variable 'mode-require-final-newline
) t
)
3293 (set (make-local-variable 'outline-regexp
)
3294 (python-rx (* space
) block-start
))
3295 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3296 (set (make-local-variable 'outline-level
)
3298 "`outline-level' function for Python mode."
3299 (1+ (/ (current-indentation) python-indent-offset
))))
3301 (python-skeleton-add-menu-items)
3303 (make-local-variable 'python-shell-internal-buffer
)
3305 (when python-indent-guess-indent-offset
3306 (python-indent-guess-indent-offset)))
3313 ;; indent-tabs-mode: nil
3316 ;;; python.el ends here