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 (let ((process-environment (python-shell-calculate-process-environment))
1658 (exec-path (python-shell-calculate-exec-path)))
1660 (executable-find python-shell-interpreter
)
1661 python-shell-interpreter-args
)))
1663 (defun python-shell-calculate-process-environment ()
1664 "Calculate process environment given `python-shell-virtualenv-path'."
1665 (let ((process-environment (append
1666 python-shell-process-environment
1667 process-environment nil
))
1668 (virtualenv (if python-shell-virtualenv-path
1669 (directory-file-name python-shell-virtualenv-path
)
1671 (when python-shell-extra-pythonpaths
1672 (setenv "PYTHONPATH"
1674 (mapconcat 'identity
1675 python-shell-extra-pythonpaths
1678 (or (getenv "PYTHONPATH") ""))))
1679 (if (not virtualenv
)
1681 (setenv "PYTHONHOME" nil
)
1682 (setenv "PATH" (format "%s/bin%s%s"
1683 virtualenv path-separator
1684 (or (getenv "PATH") "")))
1685 (setenv "VIRTUAL_ENV" virtualenv
))
1686 process-environment
))
1688 (defun python-shell-calculate-exec-path ()
1689 "Calculate exec path given `python-shell-virtualenv-path'."
1690 (let ((path (append python-shell-exec-path
1692 (if (not python-shell-virtualenv-path
)
1694 (cons (format "%s/bin"
1695 (directory-file-name python-shell-virtualenv-path
))
1698 (defun python-comint-output-filter-function (output)
1699 "Hook run after content is put into comint buffer.
1700 OUTPUT is a string with the contents of the buffer."
1701 (ansi-color-filter-apply output
))
1703 (defvar python-shell--parent-buffer nil
)
1705 (defvar python-shell-output-syntax-table
1706 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1707 (modify-syntax-entry ?
\' "." table
)
1708 (modify-syntax-entry ?
\" "." table
)
1709 (modify-syntax-entry ?\
( "." table
)
1710 (modify-syntax-entry ?\
[ "." table
)
1711 (modify-syntax-entry ?\
{ "." table
)
1712 (modify-syntax-entry ?\
) "." table
)
1713 (modify-syntax-entry ?\
] "." table
)
1714 (modify-syntax-entry ?\
} "." table
)
1716 "Syntax table for shell output.
1717 It makes parens and quotes be treated as punctuation chars.")
1719 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1720 "Major mode for Python inferior process.
1721 Runs a Python interpreter as a subprocess of Emacs, with Python
1722 I/O through an Emacs buffer. Variables
1723 `python-shell-interpreter' and `python-shell-interpreter-args'
1724 controls which Python interpreter is run. Variables
1725 `python-shell-prompt-regexp',
1726 `python-shell-prompt-output-regexp',
1727 `python-shell-prompt-block-regexp',
1728 `python-shell-enable-font-lock',
1729 `python-shell-completion-setup-code',
1730 `python-shell-completion-string-code',
1731 `python-shell-completion-module-string-code',
1732 `python-eldoc-setup-code', `python-eldoc-string-code',
1733 `python-ffap-setup-code' and `python-ffap-string-code' can
1734 customize this mode for different Python interpreters.
1736 You can also add additional setup code to be run at
1737 initialization of the interpreter via `python-shell-setup-codes'
1740 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1741 (and python-shell--parent-buffer
1742 (python-util-clone-local-variables python-shell--parent-buffer
))
1743 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1744 python-shell-prompt-regexp
1745 python-shell-prompt-block-regexp
1746 python-shell-prompt-pdb-regexp
))
1747 (setq mode-line-process
'(":%s"))
1748 (make-local-variable 'comint-output-filter-functions
)
1749 (add-hook 'comint-output-filter-functions
1750 'python-comint-output-filter-function
)
1751 (add-hook 'comint-output-filter-functions
1752 'python-pdbtrack-comint-output-filter-function
)
1753 (set (make-local-variable 'compilation-error-regexp-alist
)
1754 python-shell-compilation-regexp-alist
)
1755 (define-key inferior-python-mode-map
[remap complete-symbol
]
1756 'completion-at-point
)
1757 (add-hook 'completion-at-point-functions
1758 'python-shell-completion-complete-at-point nil
'local
)
1759 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1760 'python-shell-completion-complete-at-point
)
1761 (define-key inferior-python-mode-map
"\t"
1762 'python-shell-completion-complete-or-indent
)
1763 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1764 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1765 (make-local-variable 'python-shell-internal-last-output
)
1766 (when python-shell-enable-font-lock
1767 (set-syntax-table python-mode-syntax-table
)
1768 (set (make-local-variable 'font-lock-defaults
)
1769 '(python-font-lock-keywords nil nil nil nil
))
1770 (set (make-local-variable 'syntax-propertize-function
)
1772 ;; XXX: Unfortunately eval is needed here to make use of the
1773 ;; dynamic value of `comint-prompt-regexp'.
1774 `(syntax-propertize-rules
1775 (,comint-prompt-regexp
1778 comint-last-input-start end
'syntax-table
1779 python-shell-output-syntax-table
)
1780 ;; XXX: This might look weird, but it is the easiest
1781 ;; way to ensure font lock gets cleaned up before the
1782 ;; current prompt, which is needed for unclosed
1783 ;; strings to not mess up with current input.
1784 (font-lock-unfontify-region comint-last-input-start end
))))
1785 (,(python-rx string-delimiter
)
1787 (and (not (eq (get-text-property start
'field
) 'output
))
1788 (python-syntax-stringify)))))))))
1789 (compilation-shell-minor-mode 1))
1791 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1792 "Create a python shell comint buffer.
1793 CMD is the python command to be executed and PROC-NAME is the
1794 process name the comint buffer will get. After the comint buffer
1795 is created the `inferior-python-mode' is activated. When
1796 optional argument POP is non-nil the buffer is shown. When
1797 optional argument INTERNAL is non-nil this process is run on a
1798 buffer with a name that starts with a space, following the Emacs
1799 convention for temporary/internal buffers, and also makes sure
1800 the user is not queried for confirmation when the process is
1803 (let* ((proc-buffer-name
1804 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1805 (process-environment (python-shell-calculate-process-environment))
1806 (exec-path (python-shell-calculate-exec-path)))
1807 (when (not (comint-check-proc proc-buffer-name
))
1808 (let* ((cmdlist (split-string-and-unquote cmd
))
1809 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1810 (car cmdlist
) nil
(cdr cmdlist
)))
1811 (python-shell--parent-buffer (current-buffer))
1812 (process (get-buffer-process buffer
)))
1813 (with-current-buffer buffer
1814 (inferior-python-mode))
1815 (accept-process-output process
)
1816 (and pop
(pop-to-buffer buffer t
))
1817 (and internal
(set-process-query-on-exit-flag process nil
))))
1821 (defun run-python (cmd &optional dedicated show
)
1822 "Run an inferior Python process.
1823 Input and output via buffer named after
1824 `python-shell-buffer-name'. If there is a process already
1825 running in that buffer, just switch to it.
1827 With argument, allows you to define CMD so you can edit the
1828 command used to call the interpreter and define DEDICATED, so a
1829 dedicated process for the current buffer is open. When numeric
1830 prefix arg is other than 0 or 4 do not SHOW.
1832 Runs the hook `inferior-python-mode-hook' (after the
1833 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1834 process buffer for a list of commands.)"
1836 (if current-prefix-arg
1838 (read-string "Run Python: " (python-shell-parse-command))
1839 (y-or-n-p "Make dedicated process? ")
1840 (= (prefix-numeric-value current-prefix-arg
) 4))
1841 (list (python-shell-parse-command) nil t
)))
1842 (python-shell-make-comint
1843 cmd
(python-shell-get-process-name dedicated
) show
)
1846 (defun run-python-internal ()
1847 "Run an inferior Internal Python process.
1848 Input and output via buffer named after
1849 `python-shell-internal-buffer-name' and what
1850 `python-shell-internal-get-process-name' returns.
1852 This new kind of shell is intended to be used for generic
1853 communication related to defined configurations, the main
1854 difference with global or dedicated shells is that these ones are
1855 attached to a configuration, not a buffer. This means that can
1856 be used for example to retrieve the sys.path and other stuff,
1857 without messing with user shells. Note that
1858 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1859 are set to nil for these shells, so setup codes are not sent at
1861 (let ((python-shell-enable-font-lock nil
)
1862 (inferior-python-mode-hook nil
))
1864 (python-shell-make-comint
1865 (python-shell-parse-command)
1866 (python-shell-internal-get-process-name) nil t
))))
1868 (defun python-shell-get-process ()
1869 "Get inferior Python process for current buffer and return it."
1870 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1871 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1872 (global-proc-name (python-shell-get-process-name nil
))
1873 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1874 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1875 (global-running (comint-check-proc global-proc-buffer-name
)))
1876 ;; Always prefer dedicated
1877 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1878 (and global-running global-proc-buffer-name
)))))
1880 (defun python-shell-get-or-create-process ()
1881 "Get or create an inferior Python process for current buffer and return it."
1882 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1883 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1884 (global-proc-name (python-shell-get-process-name nil
))
1885 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1886 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1887 (global-running (comint-check-proc global-proc-buffer-name
))
1888 (current-prefix-arg 16))
1889 (when (and (not dedicated-running
) (not global-running
))
1890 (if (call-interactively 'run-python
)
1891 (setq dedicated-running t
)
1892 (setq global-running t
)))
1893 ;; Always prefer dedicated
1894 (get-buffer-process (if dedicated-running
1895 dedicated-proc-buffer-name
1896 global-proc-buffer-name
))))
1898 (defvar python-shell-internal-buffer nil
1899 "Current internal shell buffer for the current buffer.
1900 This is really not necessary at all for the code to work but it's
1901 there for compatibility with CEDET.")
1903 (defvar python-shell-internal-last-output nil
1904 "Last output captured by the internal shell.
1905 This is really not necessary at all for the code to work but it's
1906 there for compatibility with CEDET.")
1908 (defun python-shell-internal-get-or-create-process ()
1909 "Get or create an inferior Internal Python process."
1910 (let* ((proc-name (python-shell-internal-get-process-name))
1911 (proc-buffer-name (format " *%s*" proc-name
)))
1912 (when (not (process-live-p proc-name
))
1913 (run-python-internal)
1914 (setq python-shell-internal-buffer proc-buffer-name
)
1915 ;; XXX: Why is this `sit-for' needed?
1916 ;; `python-shell-make-comint' calls `accept-process-output'
1917 ;; already but it is not helping to get proper output on
1918 ;; 'gnu/linux when the internal shell process is not running and
1919 ;; a call to `python-shell-internal-send-string' is issued.
1921 (get-buffer-process proc-buffer-name
)))
1923 (define-obsolete-function-alias
1924 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1926 (define-obsolete-variable-alias
1927 'python-buffer
'python-shell-internal-buffer
"24.3")
1929 (define-obsolete-variable-alias
1930 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1932 (defun python-shell-send-string (string &optional process msg
)
1933 "Send STRING to inferior Python PROCESS.
1934 When MSG is non-nil messages the first line of STRING."
1935 (interactive "sPython command: ")
1936 (let ((process (or process
(python-shell-get-or-create-process)))
1937 (lines (split-string string
"\n" t
)))
1938 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1939 (if (> (length lines
) 1)
1940 (let* ((temporary-file-directory
1941 (if (file-remote-p default-directory
)
1942 (concat (file-remote-p default-directory
) "/tmp")
1943 temporary-file-directory
))
1944 (temp-file-name (make-temp-file "py"))
1945 (file-name (or (buffer-file-name) temp-file-name
)))
1946 (with-temp-file temp-file-name
1948 (delete-trailing-whitespace))
1949 (python-shell-send-file file-name process temp-file-name
))
1950 (comint-send-string process string
)
1951 (when (or (not (string-match "\n$" string
))
1952 (string-match "\n[ \t].*\n?$" string
))
1953 (comint-send-string process
"\n")))))
1955 (defvar python-shell-output-filter-in-progress nil
)
1956 (defvar python-shell-output-filter-buffer nil
)
1958 (defun python-shell-output-filter (string)
1959 "Filter used in `python-shell-send-string-no-output' to grab output.
1960 STRING is the output received to this point from the process.
1961 This filter saves received output from the process in
1962 `python-shell-output-filter-buffer' and stops receiving it after
1963 detecting a prompt at the end of the buffer."
1965 string
(ansi-color-filter-apply string
)
1966 python-shell-output-filter-buffer
1967 (concat python-shell-output-filter-buffer string
))
1969 ;; XXX: It seems on OSX an extra carriage return is attached
1970 ;; at the end of output, this handles that too.
1971 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1972 python-shell-prompt-regexp
1973 python-shell-prompt-block-regexp
1974 python-shell-prompt-pdb-regexp
)
1975 python-shell-output-filter-buffer
)
1976 ;; Output ends when `python-shell-output-filter-buffer' contains
1977 ;; the prompt attached at the end of it.
1978 (setq python-shell-output-filter-in-progress nil
1979 python-shell-output-filter-buffer
1980 (substring python-shell-output-filter-buffer
1981 0 (match-beginning 0)))
1982 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1983 (string-match (concat "^" python-shell-prompt-output-regexp
)
1984 python-shell-output-filter-buffer
))
1985 ;; Some shells, like iPython might append a prompt before the
1986 ;; output, clean that.
1987 (setq python-shell-output-filter-buffer
1988 (substring python-shell-output-filter-buffer
(match-end 0)))))
1991 (defun python-shell-send-string-no-output (string &optional process msg
)
1992 "Send STRING to PROCESS and inhibit output.
1993 When MSG is non-nil messages the first line of STRING. Return
1995 (let ((process (or process
(python-shell-get-or-create-process)))
1996 (comint-preoutput-filter-functions
1997 '(python-shell-output-filter))
1998 (python-shell-output-filter-in-progress t
)
2002 (python-shell-send-string string process msg
)
2003 (while python-shell-output-filter-in-progress
2004 ;; `python-shell-output-filter' takes care of setting
2005 ;; `python-shell-output-filter-in-progress' to NIL after it
2006 ;; detects end of output.
2007 (accept-process-output process
))
2009 python-shell-output-filter-buffer
2010 (setq python-shell-output-filter-buffer nil
)))
2011 (with-current-buffer (process-buffer process
)
2012 (comint-interrupt-subjob)))))
2014 (defun python-shell-internal-send-string (string)
2015 "Send STRING to the Internal Python interpreter.
2016 Returns the output. See `python-shell-send-string-no-output'."
2017 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2018 ;; updated to support this new mode.
2019 (setq python-shell-internal-last-output
2020 (python-shell-send-string-no-output
2021 ;; Makes this function compatible with the old
2022 ;; python-send-receive. (At least for CEDET).
2023 (replace-regexp-in-string "_emacs_out +" "" string
)
2024 (python-shell-internal-get-or-create-process) nil
)))
2026 (define-obsolete-function-alias
2027 'python-send-receive
'python-shell-internal-send-string
"24.3")
2029 (define-obsolete-function-alias
2030 'python-send-string
'python-shell-internal-send-string
"24.3")
2032 (defun python-shell-send-region (start end
)
2033 "Send the region delimited by START and END to inferior Python process."
2035 (python-shell-send-string
2037 (let ((line-num (line-number-at-pos start
)))
2038 ;; When sending a region, add blank lines for non sent code so
2039 ;; backtraces remain correct.
2040 (make-string (1- line-num
) ?
\n))
2041 (buffer-substring start end
))
2044 (defun python-shell-send-buffer (&optional arg
)
2045 "Send the entire buffer to inferior Python process.
2046 With prefix ARG allow execution of code inside blocks delimited
2047 by \"if __name__== '__main__':\""
2051 (let ((str (buffer-substring (point-min) (point-max))))
2054 (setq str
(replace-regexp-in-string
2055 (python-rx if-name-main
)
2056 "if __name__ == '__main__ ':" str
)))
2057 (python-shell-send-string str
))))
2059 (defun python-shell-send-defun (arg)
2060 "Send the current defun to inferior Python process.
2061 When argument ARG is non-nil do not include decorators."
2064 (python-shell-send-region
2067 (while (and (or (python-nav-beginning-of-defun)
2068 (beginning-of-line 1))
2069 (> (current-indentation) 0)))
2071 (while (and (forward-line -
1)
2072 (looking-at (python-rx decorator
))))
2076 (or (python-nav-end-of-defun)
2080 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2081 "Send FILE-NAME to inferior Python PROCESS.
2082 If TEMP-FILE-NAME is passed then that file is used for processing
2083 instead, while internally the shell will continue to use
2085 (interactive "fFile to send: ")
2086 (let* ((process (or process
(python-shell-get-or-create-process)))
2087 (temp-file-name (when temp-file-name
2089 (or (file-remote-p temp-file-name
'localname
)
2091 (file-name (or (when file-name
2093 (or (file-remote-p file-name
'localname
)
2096 (when (not file-name
)
2097 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2098 (python-shell-send-string
2100 (concat "__pyfile = open('''%s''');"
2101 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2103 (or temp-file-name file-name
) file-name
)
2106 (defun python-shell-switch-to-shell ()
2107 "Switch to inferior Python process buffer."
2109 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2111 (defun python-shell-send-setup-code ()
2112 "Send all setup code for shell.
2113 This function takes the list of setup code to send from the
2114 `python-shell-setup-codes' list."
2115 (let ((process (get-buffer-process (current-buffer))))
2116 (dolist (code python-shell-setup-codes
)
2118 (message "Sent %s" code
)
2119 (python-shell-send-string
2120 (symbol-value code
) process
)))))
2122 (add-hook 'inferior-python-mode-hook
2123 #'python-shell-send-setup-code
)
2126 ;;; Shell completion
2128 (defcustom python-shell-completion-setup-code
2132 def __COMPLETER_all_completions(text): []
2135 readline.set_completer(rlcompleter.Completer().complete)
2136 def __COMPLETER_all_completions(text):
2142 res = readline.get_completer()(text, i)
2145 completions.append(res)
2149 "Code used to setup completion in inferior Python processes."
2153 (defcustom python-shell-completion-string-code
2154 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2155 "Python code used to get a string of completions separated by semicolons."
2159 (defcustom python-shell-completion-module-string-code
""
2160 "Python code used to get completions separated by semicolons for imports.
2162 For IPython v0.11, add the following line to
2163 `python-shell-completion-setup-code':
2165 from IPython.core.completerlib import module_completion
2167 and use the following as the value of this variable:
2169 ';'.join(module_completion('''%s'''))\n"
2173 (defcustom python-shell-completion-pdb-string-code
2174 "';'.join(globals().keys() + locals().keys())"
2175 "Python code used to get completions separated by semicolons for [i]pdb."
2179 (defun python-shell-completion-get-completions (process line input
)
2180 "Do completion at point for PROCESS.
2181 LINE is used to detect the context on how to complete given
2184 ;; Get the last prompt for the inferior process
2185 ;; buffer. This is used for the completion code selection
2187 (with-current-buffer (process-buffer process
)
2188 (buffer-substring-no-properties
2189 (overlay-start comint-last-prompt-overlay
)
2190 (overlay-end comint-last-prompt-overlay
))))
2192 ;; Check whether a prompt matches a pdb string, an import
2193 ;; statement or just the standard prompt and use the
2194 ;; correct python-shell-completion-*-code string
2195 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2197 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2200 (length python-shell-completion-module-string-code
) 0)
2202 (concat "^" python-shell-prompt-regexp
) prompt
)
2203 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2206 (concat "^" python-shell-prompt-regexp
) prompt
)
2210 (case completion-context
2211 (pdb python-shell-completion-pdb-string-code
)
2212 (import python-shell-completion-module-string-code
)
2213 (default python-shell-completion-string-code
)
2216 (if (eq completion-context
'import
)
2217 (replace-regexp-in-string "^[ \t]+" "" line
)
2219 (and completion-code
2220 (> (length input
) 0)
2221 (with-current-buffer (process-buffer process
)
2222 (let ((completions (python-shell-send-string-no-output
2223 (format completion-code input
) process
)))
2224 (and (> (length completions
) 2)
2225 (split-string completions
2226 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2228 (defun python-shell-completion-complete-at-point (&optional process
)
2229 "Perform completion at point in inferior Python.
2230 Optional argument PROCESS forces completions to be retrieved
2231 using that one instead of current buffer's process."
2232 (setq process
(or process
(get-buffer-process (current-buffer))))
2235 (with-syntax-table python-dotty-syntax-table
2236 (let* ((paren-depth (car (syntax-ppss)))
2237 (syntax-string "w_")
2238 (syntax-list (string-to-syntax syntax-string
)))
2239 ;; Stop scanning for the beginning of the completion
2240 ;; subject after the char before point matches a
2243 (car (syntax-after (1- (point)))) syntax-list
)
2244 (skip-syntax-backward syntax-string
)
2245 (when (or (equal (char-before) ?\
))
2246 (equal (char-before) ?
\"))
2249 ;; honor initial paren depth
2250 (> (car (syntax-ppss)) paren-depth
)
2251 (python-syntax-context 'string
))
2256 (completion-table-dynamic
2258 #'python-shell-completion-get-completions
2259 process
(buffer-substring-no-properties
2260 (line-beginning-position) end
))))))
2262 (defun python-shell-completion-complete-or-indent ()
2263 "Complete or indent depending on the context.
2264 If content before pointer is all whitespace indent. If not try
2267 (if (string-match "^[[:space:]]*$"
2268 (buffer-substring (comint-line-beginning-position)
2270 (indent-for-tab-command)
2271 (completion-at-point)))
2274 ;;; PDB Track integration
2276 (defcustom python-pdbtrack-activate t
2277 "Non-nil makes python shell enable pdbtracking."
2282 (defcustom python-pdbtrack-stacktrace-info-regexp
2283 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2284 "Regular Expression matching stacktrace information.
2285 Used to extract the current line and module being inspected."
2290 (defvar python-pdbtrack-tracked-buffer nil
2291 "Variable containing the value of the current tracked buffer.
2292 Never set this variable directly, use
2293 `python-pdbtrack-set-tracked-buffer' instead.")
2295 (defvar python-pdbtrack-buffers-to-kill nil
2296 "List of buffers to be deleted after tracking finishes.")
2298 (defun python-pdbtrack-set-tracked-buffer (file-name)
2299 "Set the buffer for FILE-NAME as the tracked buffer.
2300 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2301 Returns the tracked buffer."
2302 (let ((file-buffer (get-file-buffer file-name
)))
2304 (setq python-pdbtrack-tracked-buffer file-buffer
)
2305 (setq file-buffer
(find-file-noselect file-name
))
2306 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2307 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2310 (defun python-pdbtrack-comint-output-filter-function (output)
2311 "Move overlay arrow to current pdb line in tracked buffer.
2312 Argument OUTPUT is a string with the output from the comint process."
2313 (when (and python-pdbtrack-activate
(not (string= output
"")))
2314 (let* ((full-output (ansi-color-filter-apply
2315 (buffer-substring comint-last-input-end
(point-max))))
2319 (insert full-output
)
2320 ;; When the debugger encounters a pdb.set_trace()
2321 ;; command, it prints a single stack frame. Sometimes
2322 ;; it prints a bit of extra information about the
2323 ;; arguments of the present function. When ipdb
2324 ;; encounters an exception, it prints the _entire_ stack
2325 ;; trace. To handle all of these cases, we want to find
2326 ;; the _last_ stack frame printed in the most recent
2327 ;; batch of output, then jump to the corrsponding
2328 ;; file/line number.
2329 (goto-char (point-max))
2330 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
2331 (setq line-number
(string-to-number
2332 (match-string-no-properties 2)))
2333 (match-string-no-properties 1)))))
2334 (if (and file-name line-number
)
2335 (let* ((tracked-buffer
2336 (python-pdbtrack-set-tracked-buffer file-name
))
2337 (shell-buffer (current-buffer))
2338 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2339 (tracked-buffer-line-pos))
2340 (with-current-buffer tracked-buffer
2341 (set (make-local-variable 'overlay-arrow-string
) "=>")
2342 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2343 (setq tracked-buffer-line-pos
(progn
2344 (goto-char (point-min))
2345 (forward-line (1- line-number
))
2347 (when tracked-buffer-window
2349 tracked-buffer-window tracked-buffer-line-pos
))
2350 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2351 (pop-to-buffer tracked-buffer
)
2352 (switch-to-buffer-other-window shell-buffer
))
2353 (when python-pdbtrack-tracked-buffer
2354 (with-current-buffer python-pdbtrack-tracked-buffer
2355 (set-marker overlay-arrow-position nil
))
2356 (mapc #'(lambda (buffer)
2357 (ignore-errors (kill-buffer buffer
)))
2358 python-pdbtrack-buffers-to-kill
)
2359 (setq python-pdbtrack-tracked-buffer nil
2360 python-pdbtrack-buffers-to-kill nil
)))))
2364 ;;; Symbol completion
2366 (defun python-completion-complete-at-point ()
2367 "Complete current symbol at point.
2368 For this to work the best as possible you should call
2369 `python-shell-send-buffer' from time to time so context in
2370 inferior python process is updated properly."
2371 (let ((process (python-shell-get-process)))
2373 (error "Completion needs an inferior Python process running")
2374 (python-shell-completion-complete-at-point process
))))
2376 (add-to-list 'debug-ignored-errors
2377 "^Completion needs an inferior Python process running.")
2382 (defcustom python-fill-comment-function
'python-fill-comment
2383 "Function to fill comments.
2384 This is the function used by `python-fill-paragraph' to
2389 (defcustom python-fill-string-function
'python-fill-string
2390 "Function to fill strings.
2391 This is the function used by `python-fill-paragraph' to
2396 (defcustom python-fill-decorator-function
'python-fill-decorator
2397 "Function to fill decorators.
2398 This is the function used by `python-fill-paragraph' to
2403 (defcustom python-fill-paren-function
'python-fill-paren
2404 "Function to fill parens.
2405 This is the function used by `python-fill-paragraph' to
2410 (defcustom python-fill-docstring-style
'pep-257
2411 "Style used to fill docstrings.
2412 This affects `python-fill-string' behavior with regards to
2413 triple quotes positioning.
2415 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2416 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2417 position and will treat docstrings a normal string, any other
2418 value may result in one of the following docstring styles:
2423 Process foo, return bar.
2427 Process foo, return bar.
2429 If processing fails throw ProcessingError.
2434 \"\"\"Process foo, return bar.\"\"\"
2437 Process foo, return bar.
2439 If processing fails throw ProcessingError.
2445 \"\"\"Process foo, return bar.\"\"\"
2447 \"\"\"Process foo, return bar.
2449 If processing fails throw ProcessingError.
2455 \"\"\"Process foo, return bar.\"\"\"
2457 \"\"\"Process foo, return bar.
2459 If processing fails throw ProcessingError.
2464 \"\"\"Process foo, return bar.\"\"\"
2467 Process foo, return bar.
2469 If processing fails throw ProcessingError.
2472 (const :tag
"Don't format docstrings" nil
)
2473 (const :tag
"Django's coding standards style." django
)
2474 (const :tag
"One newline and start and Two at end style." onetwo
)
2475 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2476 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2477 (const :tag
"Symmetric style." symmetric
))
2480 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2482 (defun python-fill-paragraph (&optional justify
)
2483 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2484 If any of the current line is in or at the end of a multi-line string,
2485 fill the string or the paragraph of it that point is in, preserving
2486 the string's indentation.
2487 Optional argument JUSTIFY defines if the paragraph should be justified."
2492 ((python-syntax-context 'comment
)
2493 (funcall python-fill-comment-function justify
))
2494 ;; Strings/Docstrings
2495 ((save-excursion (or (python-syntax-context 'string
)
2496 (equal (string-to-syntax "|")
2497 (syntax-after (point)))))
2498 (funcall python-fill-string-function justify
))
2500 ((equal (char-after (save-excursion
2501 (python-nav-beginning-of-statement))) ?
@)
2502 (funcall python-fill-decorator-function justify
))
2504 ((or (python-syntax-context 'paren
)
2505 (looking-at (python-rx open-paren
))
2507 (skip-syntax-forward "^(" (line-end-position))
2508 (looking-at (python-rx open-paren
))))
2509 (funcall python-fill-paren-function justify
))
2512 (defun python-fill-comment (&optional justify
)
2513 "Comment fill function for `python-fill-paragraph'.
2514 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2515 (fill-comment-paragraph justify
))
2517 (defun python-fill-string (&optional justify
)
2518 "String fill function for `python-fill-paragraph'.
2519 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2520 (let* ((marker (point-marker))
2522 (let ((m (make-marker)))
2523 (setf (marker-position m
)
2524 (or (python-syntax-context 'string
)
2525 (and (equal (string-to-syntax "|")
2526 (syntax-after (point)))
2528 (num-quotes (python-syntax-count-quotes
2529 (char-after str-start-pos
) str-start-pos
))
2532 (goto-char (+ str-start-pos num-quotes
))
2533 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2534 (goto-char (point-max)))
2537 ;; Docstring styles may vary for oneliners and multi-liners.
2538 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2540 (case python-fill-docstring-style
2541 ;; delimiters-style is a cons cell with the form
2542 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2543 ;; is NIL means to not add any newlines for start or end
2544 ;; of docstring. See `python-fill-docstring-style' for a
2545 ;; graphic idea of each style.
2547 (onetwo (and multi-line-p
(cons 1 2)))
2548 (pep-257 (and multi-line-p
(cons nil
2)))
2549 (pep-257-nn (and multi-line-p
(cons nil
1)))
2550 (symmetric (and multi-line-p
(cons 1 1)))))
2551 (docstring-p (save-excursion
2552 ;; Consider docstrings those strings which
2553 ;; start on a line by themselves.
2554 (python-nav-beginning-of-statement)
2555 (and (= (point) str-start-pos
))))
2556 (fill-paragraph-function))
2558 (narrow-to-region str-start-pos str-end-pos
)
2559 (fill-paragraph justify
))
2561 (when (and docstring-p python-fill-docstring-style
)
2562 ;; Add the number of newlines indicated by the selected style
2563 ;; at the start of the docstring.
2564 (goto-char (+ str-start-pos num-quotes
))
2565 (delete-region (point) (progn
2566 (skip-syntax-forward "> ")
2568 (and (car delimiters-style
)
2569 (or (newline (car delimiters-style
)) t
)
2570 ;; Indent only if a newline is added.
2571 (indent-according-to-mode))
2572 ;; Add the number of newlines indicated by the selected style
2573 ;; at the end of the docstring.
2574 (goto-char (if (not (= str-end-pos
(point-max)))
2575 (- str-end-pos num-quotes
)
2577 (delete-region (point) (progn
2578 (skip-syntax-backward "> ")
2580 (and (cdr delimiters-style
)
2581 ;; Add newlines only if string ends.
2582 (not (= str-end-pos
(point-max)))
2583 (or (newline (cdr delimiters-style
)) t
)
2584 ;; Again indent only if a newline is added.
2585 (indent-according-to-mode))))) t
)
2587 (defun python-fill-decorator (&optional justify
)
2588 "Decorator fill function for `python-fill-paragraph'.
2589 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2592 (defun python-fill-paren (&optional justify
)
2593 "Paren fill function for `python-fill-paragraph'.
2594 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2596 (narrow-to-region (progn
2597 (while (python-syntax-context 'paren
)
2598 (goto-char (1- (point-marker))))
2600 (line-beginning-position))
2602 (when (not (python-syntax-context 'paren
))
2604 (when (not (python-syntax-context 'paren
))
2605 (skip-syntax-backward "^)")))
2606 (while (python-syntax-context 'paren
)
2607 (goto-char (1+ (point-marker))))
2609 (let ((paragraph-start "\f\\|[ \t]*$")
2610 (paragraph-separate ",")
2611 (fill-paragraph-function))
2612 (goto-char (point-min))
2613 (fill-paragraph justify
))
2616 (python-indent-line)
2617 (goto-char (line-end-position)))) t
)
2622 (defcustom python-skeleton-autoinsert nil
2623 "Non-nil means template skeletons will be automagically inserted.
2624 This happens when pressing \"if<SPACE>\", for example, to prompt for
2630 (define-obsolete-variable-alias
2631 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2633 (defvar python-skeleton-available
'()
2634 "Internal list of available skeletons.")
2636 (define-abbrev-table 'python-mode-abbrev-table
()
2637 "Abbrev table for Python mode."
2639 ;; Allow / inside abbrevs.
2640 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2641 ;; Only expand in code.
2642 :enable-function
(lambda ()
2644 (not (python-syntax-comment-or-string-p))
2645 python-skeleton-autoinsert
)))
2647 (defmacro python-skeleton-define
(name doc
&rest skel
)
2648 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2649 The skeleton will be bound to python-skeleton-NAME and will
2650 be added to `python-mode-abbrev-table'."
2651 (declare (indent 2))
2652 (let* ((name (symbol-name name
))
2653 (function-name (intern (concat "python-skeleton-" name
))))
2655 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2657 (setq python-skeleton-available
2658 (cons ',function-name python-skeleton-available
))
2659 (define-skeleton ,function-name
2661 (format "Insert %s statement." name
))
2664 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2665 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2666 The skeleton will be bound to python-skeleton-NAME."
2667 (declare (indent 2))
2668 (let* ((name (symbol-name name
))
2669 (function-name (intern (concat "python-skeleton--" name
)))
2671 "Add '%s' clause? " name
)))
2674 `(< ,(format "%s:" name
) \n \n
2676 `(define-skeleton ,function-name
2678 (format "Auxiliary skeleton for %s statement." name
))
2680 (unless (y-or-n-p ,msg
)
2684 (python-define-auxiliary-skeleton else nil
)
2686 (python-define-auxiliary-skeleton except nil
)
2688 (python-define-auxiliary-skeleton finally nil
)
2690 (python-skeleton-define if nil
2694 ("other condition, %s: "
2698 '(python-skeleton--else) | ^
)
2700 (python-skeleton-define while nil
2704 '(python-skeleton--else) | ^
)
2706 (python-skeleton-define for nil
2710 '(python-skeleton--else) | ^
)
2712 (python-skeleton-define try nil
2718 "except " str
":" \n
2721 '(python-skeleton--except)
2722 '(python-skeleton--else)
2723 '(python-skeleton--finally) | ^
)
2725 (python-skeleton-define def nil
2727 "def " str
"(" ("Parameter, %s: "
2728 (unless (equal ?\
( (char-before)) ", ")
2730 "\"\"\"" -
"\"\"\"" \n
2733 (python-skeleton-define class nil
2735 "class " str
"(" ("Inheritance, %s: "
2736 (unless (equal ?\
( (char-before)) ", ")
2740 "\"\"\"" -
"\"\"\"" \n
2743 (defun python-skeleton-add-menu-items ()
2744 "Add menu items to Python->Skeletons menu."
2745 (let ((skeletons (sort python-skeleton-available
'string
<))
2747 (dolist (skeleton skeletons
)
2749 nil
'("Python" "Skeletons")
2751 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2756 (defcustom python-ffap-setup-code
2757 "def __FFAP_get_module_path(module):
2760 path = __import__(module).__file__
2761 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2766 "Python code to get a module path."
2770 (defcustom python-ffap-string-code
2771 "__FFAP_get_module_path('''%s''')\n"
2772 "Python code used to get a string with the path of a module."
2776 (defun python-ffap-module-path (module)
2777 "Function for `ffap-alist' to return path for MODULE."
2779 (and (eq major-mode
'inferior-python-mode
)
2780 (get-buffer-process (current-buffer)))
2781 (python-shell-get-process))))
2785 (python-shell-send-string-no-output
2786 (format python-ffap-string-code module
) process
)))
2788 (substring-no-properties module-file
1 -
1))))))
2790 (eval-after-load "ffap"
2792 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2793 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2798 (defcustom python-check-command
2800 "Command used to check a Python file."
2804 (defcustom python-check-buffer-name
2805 "*Python check: %s*"
2806 "Buffer name used for check commands."
2810 (defvar python-check-custom-command nil
2813 (defun python-check (command)
2814 "Check a Python file (default current buffer's file).
2815 Runs COMMAND, a shell command, as if by `compile'. See
2816 `python-check-command' for the default."
2818 (list (read-string "Check command: "
2819 (or python-check-custom-command
2820 (concat python-check-command
" "
2821 (shell-quote-argument
2823 (let ((name (buffer-file-name)))
2825 (file-name-nondirectory name
)))
2827 (setq python-check-custom-command command
)
2828 (save-some-buffers (not compilation-ask-about-save
) nil
)
2829 (let ((process-environment (python-shell-calculate-process-environment))
2830 (exec-path (python-shell-calculate-exec-path)))
2831 (compilation-start command nil
2833 (format python-check-buffer-name command
)))))
2838 (defcustom python-eldoc-setup-code
2839 "def __PYDOC_get_help(obj):
2842 if hasattr(obj, 'startswith'):
2843 obj = eval(obj, globals())
2844 doc = inspect.getdoc(obj)
2845 if not doc and callable(obj):
2847 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2848 target = obj.__init__
2854 args = inspect.formatargspec(
2855 *inspect.getargspec(target)
2858 doc = '{objtype} {name}{args}'.format(
2859 objtype=objtype, name=name, args=args
2862 doc = doc.splitlines()[0]
2869 "Python code to setup documentation retrieval."
2873 (defcustom python-eldoc-string-code
2874 "__PYDOC_get_help('''%s''')\n"
2875 "Python code used to get a string with the documentation of an object."
2879 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2880 "Internal implementation to get documentation at point.
2881 If not FORCE-INPUT is passed then what
2882 `python-info-current-symbol' returns will be used. If not
2883 FORCE-PROCESS is passed what `python-shell-get-process' returns
2885 (let ((process (or force-process
(python-shell-get-process))))
2887 (error "Eldoc needs an inferior Python process running")
2888 (let ((input (or force-input
2889 (python-info-current-symbol t
))))
2891 (python-shell-send-string-no-output
2892 (format python-eldoc-string-code input
)
2895 (defun python-eldoc-function ()
2896 "`eldoc-documentation-function' for Python.
2897 For this to work the best as possible you should call
2898 `python-shell-send-buffer' from time to time so context in
2899 inferior python process is updated properly."
2900 (python-eldoc--get-doc-at-point))
2902 (defun python-eldoc-at-point (symbol)
2903 "Get help on SYMBOL using `help'.
2904 Interactively, prompt for symbol."
2906 (let ((symbol (python-info-current-symbol t
))
2907 (enable-recursive-minibuffers t
))
2908 (list (read-string (if symbol
2909 (format "Describe symbol (default %s): " symbol
)
2910 "Describe symbol: ")
2912 (message (python-eldoc--get-doc-at-point symbol
)))
2914 (add-to-list 'debug-ignored-errors
2915 "^Eldoc needs an inferior Python process running.")
2920 (defun python-imenu-prev-index-position ()
2921 "Python mode's `imenu-prev-index-position-function'."
2923 (while (and (setq found
2924 (re-search-backward python-nav-beginning-of-defun-regexp nil t
))
2925 (not (python-info-looking-at-beginning-of-defun))))
2927 (python-info-looking-at-beginning-of-defun)
2928 (python-info-current-defun))))
2933 (defun python-info-current-defun (&optional include-type
)
2934 "Return name of surrounding function with Python compatible dotty syntax.
2935 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2936 This function is compatible to be used as
2937 `add-log-current-defun-function' since it returns nil if point is
2938 not inside a defun."
2944 (starting-indentation (current-indentation))
2945 (starting-pos (point))
2950 (while (python-nav-beginning-of-defun 1)
2952 (or (not last-indent
)
2953 (< (current-indentation) last-indent
))
2957 ;; If this is the first run, we may add
2958 ;; the current defun at point.
2959 (setq first-run nil
)
2960 (goto-char starting-pos
)
2961 (python-nav-beginning-of-statement)
2962 (beginning-of-line 1)
2964 python-nav-beginning-of-defun-regexp
)))
2968 (+ (current-indentation)
2969 python-indent-offset
)))
2970 (if (< starting-indentation min-indent
)
2971 ;; If the starting indentation is not
2972 ;; within the min defun indent make the
2975 ;; Else go to the end of defun and add
2976 ;; up the current indentation to the
2978 (python-nav-end-of-defun)
2980 (if (>= (current-indentation) min-indent
)
2981 (1+ (current-indentation))
2983 (setq last-indent
(current-indentation))
2984 (if (or (not include-type
) type
)
2985 (setq names
(cons (match-string-no-properties 1) names
))
2986 (let ((match (split-string (match-string-no-properties 0))))
2987 (setq type
(car match
))
2988 (setq names
(cons (cadr match
) names
)))))
2989 ;; Stop searching ASAP.
2990 (and (= (current-indentation) 0) (throw 'exit t
))))
2992 (concat (and type
(format "%s " type
))
2993 (mapconcat 'identity names
".")))))))
2995 (defun python-info-current-symbol (&optional replace-self
)
2996 "Return current symbol using dotty syntax.
2997 With optional argument REPLACE-SELF convert \"self\" to current
3000 (and (not (python-syntax-comment-or-string-p))
3001 (with-syntax-table python-dotty-syntax-table
3002 (let ((sym (symbol-at-point)))
3004 (substring-no-properties (symbol-name sym
))))))))
3006 (if (not replace-self
)
3008 (let ((current-defun (python-info-current-defun)))
3009 (if (not current-defun
)
3011 (replace-regexp-in-string
3012 (python-rx line-start word-start
"self" word-end ?.
)
3014 (mapconcat 'identity
3015 (butlast (split-string current-defun
"\\."))
3019 (defun python-info-statement-starts-block-p ()
3020 "Return non-nil if current statement opens a block."
3022 (python-nav-beginning-of-statement)
3023 (looking-at (python-rx block-start
))))
3025 (defun python-info-statement-ends-block-p ()
3026 "Return non-nil if point is at end of block."
3027 (let ((end-of-block-pos (save-excursion
3028 (python-nav-end-of-block)))
3029 (end-of-statement-pos (save-excursion
3030 (python-nav-end-of-statement))))
3031 (and end-of-block-pos end-of-statement-pos
3032 (= end-of-block-pos end-of-statement-pos
))))
3034 (defun python-info-beginning-of-statement-p ()
3035 "Return non-nil if point is at beginning of statement."
3036 (= (point) (save-excursion
3037 (python-nav-beginning-of-statement)
3040 (defun python-info-end-of-statement-p ()
3041 "Return non-nil if point is at end of statement."
3042 (= (point) (save-excursion
3043 (python-nav-end-of-statement)
3046 (defun python-info-beginning-of-block-p ()
3047 "Return non-nil if point is at beginning of block."
3048 (and (python-info-beginning-of-statement-p)
3049 (python-info-statement-starts-block-p)))
3051 (defun python-info-end-of-block-p ()
3052 "Return non-nil if point is at end of block."
3053 (and (python-info-end-of-statement-p)
3054 (python-info-statement-ends-block-p)))
3056 (defun python-info-closing-block ()
3057 "Return the point of the block the current line closes."
3058 (let ((closing-word (save-excursion
3059 (back-to-indentation)
3061 (indentation (current-indentation)))
3062 (when (member closing-word python-indent-dedenters
)
3065 (while (and (> (current-indentation) indentation
)
3067 (not (back-to-indentation))
3069 (back-to-indentation)
3071 ((not (equal indentation
(current-indentation))) nil
)
3072 ((string= closing-word
"elif")
3073 (when (member (current-word) '("if" "elif"))
3075 ((string= closing-word
"else")
3076 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3078 ((string= closing-word
"except")
3079 (when (member (current-word) '("try"))
3081 ((string= closing-word
"finally")
3082 (when (member (current-word) '("except" "else"))
3083 (point-marker))))))))
3085 (defun python-info-closing-block-message (&optional closing-block-point
)
3086 "Message the contents of the block the current line closes.
3087 With optional argument CLOSING-BLOCK-POINT use that instead of
3088 recalculating it calling `python-info-closing-block'."
3089 (let ((point (or closing-block-point
(python-info-closing-block))))
3093 (message "Closes %s" (save-excursion
3095 (back-to-indentation)
3097 (point) (line-end-position))))))))
3099 (defun python-info-line-ends-backslash-p (&optional line-number
)
3100 "Return non-nil if current line ends with backslash.
3101 With optional argument LINE-NUMBER, check that line instead."
3106 (goto-char line-number
))
3107 (while (and (not (eobp))
3108 (goto-char (line-end-position))
3109 (python-syntax-context 'paren
)
3110 (not (equal (char-before (point)) ?
\\)))
3112 (when (equal (char-before) ?
\\)
3115 (defun python-info-beginning-of-backslash (&optional line-number
)
3116 "Return the point where the backslashed line start.
3117 Optional argument LINE-NUMBER forces the line number to check against."
3122 (goto-char line-number
))
3123 (when (python-info-line-ends-backslash-p)
3124 (while (save-excursion
3125 (goto-char (line-beginning-position))
3126 (python-syntax-context 'paren
))
3128 (back-to-indentation)
3131 (defun python-info-continuation-line-p ()
3132 "Check if current line is continuation of another.
3133 When current line is continuation of another return the point
3134 where the continued line ends."
3138 (let* ((context-type (progn
3139 (back-to-indentation)
3140 (python-syntax-context-type)))
3141 (line-start (line-number-at-pos))
3142 (context-start (when context-type
3143 (python-syntax-context context-type
))))
3144 (cond ((equal context-type
'paren
)
3145 ;; Lines inside a paren are always a continuation line
3146 ;; (except the first one).
3147 (python-util-forward-comment -
1)
3149 ((member context-type
'(string comment
))
3150 ;; move forward an roll again
3151 (goto-char context-start
)
3152 (python-util-forward-comment)
3153 (python-info-continuation-line-p))
3155 ;; Not within a paren, string or comment, the only way
3156 ;; we are dealing with a continuation line is that
3157 ;; previous line contains a backslash, and this can
3158 ;; only be the previous line from current
3159 (back-to-indentation)
3160 (python-util-forward-comment -
1)
3161 (when (and (equal (1- line-start
) (line-number-at-pos))
3162 (python-info-line-ends-backslash-p))
3163 (point-marker))))))))
3165 (defun python-info-block-continuation-line-p ()
3166 "Return non-nil if current line is a continuation of a block."
3168 (when (python-info-continuation-line-p)
3170 (back-to-indentation)
3171 (when (looking-at (python-rx block-start
))
3174 (defun python-info-assignment-continuation-line-p ()
3175 "Check if current line is a continuation of an assignment.
3176 When current line is continuation of another with an assignment
3177 return the point of the first non-blank character after the
3180 (when (python-info-continuation-line-p)
3182 (back-to-indentation)
3183 (when (and (not (looking-at (python-rx block-start
)))
3184 (and (re-search-forward (python-rx not-simple-operator
3186 not-simple-operator
)
3187 (line-end-position) t
)
3188 (not (python-syntax-context-type))))
3189 (skip-syntax-forward "\s")
3192 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3193 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3194 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3196 (beginning-of-line 1)
3197 (looking-at python-nav-beginning-of-defun-regexp
))))
3199 (defun python-info-current-line-comment-p ()
3200 "Check if current line is a comment line."
3201 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3203 (defun python-info-current-line-empty-p ()
3204 "Check if current line is empty, ignoring whitespace."
3206 (beginning-of-line 1)
3208 (python-rx line-start
(* whitespace
)
3209 (group (* not-newline
))
3210 (* whitespace
) line-end
))
3211 (string-equal "" (match-string-no-properties 1))))
3214 ;;; Utility functions
3216 (defun python-util-position (item seq
)
3217 "Find the first occurrence of ITEM in SEQ.
3218 Return the index of the matching item, or nil if not found."
3219 (let ((member-result (member item seq
)))
3221 (- (length seq
) (length member-result
)))))
3223 ;; Stolen from org-mode
3224 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3225 "Clone local variables from FROM-BUFFER.
3226 Optional argument REGEXP selects variables to clone and defaults
3230 (and (symbolp (car pair
))
3231 (string-match (or regexp
"^python-")
3232 (symbol-name (car pair
)))
3233 (set (make-local-variable (car pair
))
3235 (buffer-local-variables from-buffer
)))
3237 (defun python-util-forward-comment (&optional direction
)
3238 "Python mode specific version of `forward-comment'.
3239 Optional argument DIRECTION defines the direction to move to."
3240 (let ((comment-start (python-syntax-context 'comment
))
3241 (factor (if (< (or direction
0) 0)
3245 (goto-char comment-start
))
3246 (forward-comment factor
)))
3250 (define-derived-mode python-mode prog-mode
"Python"
3251 "Major mode for editing Python files.
3254 Entry to this mode calls the value of `python-mode-hook'
3255 if that value is non-nil."
3256 (set (make-local-variable 'tab-width
) 8)
3257 (set (make-local-variable 'indent-tabs-mode
) nil
)
3259 (set (make-local-variable 'comment-start
) "# ")
3260 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3262 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3263 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3265 (set (make-local-variable 'forward-sexp-function
)
3266 'python-nav-forward-sexp
)
3268 (set (make-local-variable 'font-lock-defaults
)
3269 '(python-font-lock-keywords nil nil nil nil
))
3271 (set (make-local-variable 'syntax-propertize-function
)
3272 python-syntax-propertize-function
)
3274 (set (make-local-variable 'indent-line-function
)
3275 #'python-indent-line-function
)
3276 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3278 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3279 (set (make-local-variable 'fill-paragraph-function
)
3280 'python-fill-paragraph
)
3282 (set (make-local-variable 'beginning-of-defun-function
)
3283 #'python-nav-beginning-of-defun
)
3284 (set (make-local-variable 'end-of-defun-function
)
3285 #'python-nav-end-of-defun
)
3287 (add-hook 'completion-at-point-functions
3288 'python-completion-complete-at-point nil
'local
)
3290 (add-hook 'post-self-insert-hook
3291 'python-indent-post-self-insert-function nil
'local
)
3293 (set (make-local-variable 'imenu-extract-index-name-function
)
3294 #'python-info-current-defun
)
3296 (set (make-local-variable 'imenu-prev-index-position-function
)
3297 #'python-imenu-prev-index-position
)
3299 (set (make-local-variable 'add-log-current-defun-function
)
3300 #'python-info-current-defun
)
3302 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3304 (set (make-local-variable 'skeleton-further-elements
)
3306 (< '(backward-delete-char-untabify (min python-indent-offset
3308 (^
'(- (1+ (current-indentation))))))
3310 (set (make-local-variable 'eldoc-documentation-function
)
3311 #'python-eldoc-function
)
3313 (add-to-list 'hs-special-modes-alist
3314 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3316 (python-nav-end-of-defun)) nil
))
3318 (set (make-local-variable 'mode-require-final-newline
) t
)
3320 (set (make-local-variable 'outline-regexp
)
3321 (python-rx (* space
) block-start
))
3322 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3323 (set (make-local-variable 'outline-level
)
3325 "`outline-level' function for Python mode."
3326 (1+ (/ (current-indentation) python-indent-offset
))))
3328 (python-skeleton-add-menu-items)
3330 (make-local-variable 'python-shell-internal-buffer
)
3332 (when python-indent-guess-indent-offset
3333 (python-indent-guess-indent-offset)))
3340 ;; indent-tabs-mode: nil
3343 ;;; python.el ends here