1 ;;; python.el --- Python's flying circus support for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 2003-2014 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
8 ;; Maintainer: emacs-devel@gnu.org
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 electric-indent-mode
44 ;; is supported such that when inserting a colon the current line is
45 ;; 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', `python-nav-end-of-block' and
56 ;; `python-nav-if-name-main' are included but no bound to any key. At
57 ;; last but not least the specialized `python-nav-forward-sexp' allows
58 ;; easy navigation between code blocks. If you prefer `cc-mode'-like
59 ;; `forward-sexp' movement, setting `forward-sexp-function' to nil is
60 ;; enough, You can do that using the `python-mode-hook':
62 ;; (add-hook 'python-mode-hook
63 ;; (lambda () (setq forward-sexp-function nil)))
65 ;; Shell interaction: is provided and allows you to execute easily any
66 ;; block of code of your current buffer in an inferior Python process.
68 ;; Shell completion: hitting tab will try to complete the current
69 ;; word. Shell completion is implemented in a manner that if you
70 ;; change the `python-shell-interpreter' to any other (for example
71 ;; IPython) it should be easy to integrate another way to calculate
72 ;; completions. You just need to specify your custom
73 ;; `python-shell-completion-setup-code' and
74 ;; `python-shell-completion-string-code'.
76 ;; Here is a complete example of the settings you would use for
80 ;; python-shell-interpreter "ipython"
81 ;; python-shell-interpreter-args ""
82 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
83 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
84 ;; python-shell-completion-setup-code
85 ;; "from IPython.core.completerlib import module_completion"
86 ;; python-shell-completion-module-string-code
87 ;; "';'.join(module_completion('''%s'''))\n"
88 ;; python-shell-completion-string-code
89 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
91 ;; For iPython 0.10 everything would be the same except for
92 ;; `python-shell-completion-string-code' and
93 ;; `python-shell-completion-module-string-code':
95 ;; (setq python-shell-completion-string-code
96 ;; "';'.join(__IP.complete('''%s'''))\n"
97 ;; python-shell-completion-module-string-code "")
99 ;; Unfortunately running iPython on Windows needs some more tweaking.
100 ;; The way you must set `python-shell-interpreter' and
101 ;; `python-shell-interpreter-args' is as follows:
104 ;; python-shell-interpreter "C:\\Python27\\python.exe"
105 ;; python-shell-interpreter-args
106 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
108 ;; That will spawn the iPython process correctly (Of course you need
109 ;; to modify the paths according to your system).
111 ;; Please note that the default completion system depends on the
112 ;; readline module, so if you are using some Operating System that
113 ;; bundles Python without it (like Windows) just install the
114 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
115 ;; you should be good to go.
117 ;; Shell virtualenv support: The shell also contains support for
118 ;; virtualenvs and other special environment modifications thanks to
119 ;; `python-shell-process-environment' and `python-shell-exec-path'.
120 ;; These two variables allows you to modify execution paths and
121 ;; environment variables to make easy for you to setup virtualenv rules
122 ;; or behavior modifications when running shells. Here is an example
123 ;; of how to make shell processes to be run using the /path/to/env/
126 ;; (setq python-shell-process-environment
128 ;; (format "PATH=%s" (mapconcat
131 ;; (cons (getenv "PATH")
132 ;; '("/path/to/env/bin/")))
134 ;; "VIRTUAL_ENV=/path/to/env/"))
135 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
137 ;; Since the above is cumbersome and can be programmatically
138 ;; calculated, the variable `python-shell-virtualenv-path' is
139 ;; provided. When this variable is set with the path of the
140 ;; virtualenv to use, `process-environment' and `exec-path' get proper
141 ;; values in order to run shells inside the specified virtualenv. So
142 ;; the following will achieve the same as the previous example:
144 ;; (setq python-shell-virtualenv-path "/path/to/env/")
146 ;; Also the `python-shell-extra-pythonpaths' variable have been
147 ;; introduced as simple way of adding paths to the PYTHONPATH without
148 ;; affecting existing values.
150 ;; Pdb tracking: when you execute a block of code that contains some
151 ;; call to pdb (or ipdb) it will prompt the block of code and will
152 ;; follow the execution of pdb marking the current line with an arrow.
154 ;; Symbol completion: you can complete the symbol at point. It uses
155 ;; the shell completion in background so you should run
156 ;; `python-shell-send-buffer' from time to time to get better results.
158 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
159 ;; def, for, if, try and while. These skeletons are integrated with
160 ;; abbrev. If you have `abbrev-mode' activated and
161 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
162 ;; the name of any of those defined and hit SPC, they will be
163 ;; automatically expanded. As an alternative you can use the defined
164 ;; skeleton commands: `python-skeleton-class', `python-skeleton-def'
165 ;; `python-skeleton-for', `python-skeleton-if', `python-skeleton-try'
166 ;; and `python-skeleton-while'.
168 ;; FFAP: You can find the filename for a given module when using ffap
169 ;; out of the box. This feature needs an inferior python shell
172 ;; Code check: Check the current file for errors with `python-check'
173 ;; using the program defined in `python-check-command'.
175 ;; Eldoc: returns documentation for object at point by using the
176 ;; inferior python subprocess to inspect its documentation. As you
177 ;; might guessed you should run `python-shell-send-buffer' from time
178 ;; to time to get better results too.
180 ;; Imenu: There are two index building functions to be used as
181 ;; `imenu-create-index-function': `python-imenu-create-index' (the
182 ;; default one, builds the alist in form of a tree) and
183 ;; `python-imenu-create-flat-index'. See also
184 ;; `python-imenu-format-item-label-function',
185 ;; `python-imenu-format-parent-item-label-function',
186 ;; `python-imenu-format-parent-item-jump-label-function' variables for
187 ;; changing the way labels are formatted in the tree version.
189 ;; If you used python-mode.el you probably will miss auto-indentation
190 ;; when inserting newlines. To achieve the same behavior you have
193 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
195 ;; 2) Add the following hook in your .emacs:
197 ;; (add-hook 'python-mode-hook
199 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
201 ;; I'd recommend the first one since you'll get the same behavior for
202 ;; all modes out-of-the-box.
206 ;; Add this to your .emacs:
208 ;; (add-to-list 'load-path "/folder/containing/file")
215 (require 'ansi-color
)
218 ;; Avoid compiler warnings
219 (defvar view-return-to-alist
)
220 (defvar compilation-error-regexp-alist
)
221 (defvar outline-heading-end-regexp
)
223 (autoload 'comint-mode
"comint")
226 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
228 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python[0-9.]*") 'python-mode
))
231 "Python Language's flying circus support for Emacs."
234 :link
'(emacs-commentary-link "python"))
239 (defvar python-mode-map
240 (let ((map (make-sparse-keymap)))
242 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
243 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
244 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
245 (define-key map
"\C-c\C-j" 'imenu
)
247 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
248 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
249 (define-key map
"\C-c<" 'python-indent-shift-left
)
250 (define-key map
"\C-c>" 'python-indent-shift-right
)
252 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
253 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
254 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
255 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
256 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
257 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
259 (define-key map
"\C-c\C-p" 'run-python
)
260 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
261 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
262 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
263 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
264 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
265 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
266 ;; Some util commands
267 (define-key map
"\C-c\C-v" 'python-check
)
268 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
270 (substitute-key-definition 'complete-symbol
'completion-at-point
272 (easy-menu-define python-menu map
"Python Mode menu"
274 :help
"Python-specific Features"
275 ["Shift region left" python-indent-shift-left
:active mark-active
276 :help
"Shift region left by a single indentation step"]
277 ["Shift region right" python-indent-shift-right
:active mark-active
278 :help
"Shift region right by a single indentation step"]
280 ["Start of def/class" beginning-of-defun
281 :help
"Go to start of outermost definition around point"]
282 ["End of def/class" end-of-defun
283 :help
"Go to end of definition around point"]
284 ["Mark def/class" mark-defun
285 :help
"Mark outermost definition around point"]
286 ["Jump to def/class" imenu
287 :help
"Jump to a class or function definition"]
291 ["Start interpreter" run-python
292 :help
"Run inferior Python process in a separate buffer"]
293 ["Switch to shell" python-shell-switch-to-shell
294 :help
"Switch to running inferior Python process"]
295 ["Eval string" python-shell-send-string
296 :help
"Eval string in inferior Python session"]
297 ["Eval buffer" python-shell-send-buffer
298 :help
"Eval buffer in inferior Python session"]
299 ["Eval region" python-shell-send-region
300 :help
"Eval region in inferior Python session"]
301 ["Eval defun" python-shell-send-defun
302 :help
"Eval defun in inferior Python session"]
303 ["Eval file" python-shell-send-file
304 :help
"Eval file in inferior Python session"]
305 ["Debugger" pdb
:help
"Run pdb under GUD"]
307 ["Check file" python-check
308 :help
"Check file for errors"]
309 ["Help on symbol" python-eldoc-at-point
310 :help
"Get help on symbol at point"]
311 ["Complete symbol" completion-at-point
312 :help
"Complete symbol before point"]))
314 "Keymap for `python-mode'.")
317 ;;; Python specialized rx
320 (defconst python-rx-constituents
321 `((block-start .
,(rx symbol-start
322 (or "def" "class" "if" "elif" "else" "try"
323 "except" "finally" "for" "while" "with")
325 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
327 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
328 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
329 (+ space
) "==" (+ space
)
330 (any ?
' ?
\") "__main__" (any ?
' ?
\")
332 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
333 (open-paren .
,(rx (or "{" "[" "(")))
334 (close-paren .
,(rx (or "}" "]" ")")))
335 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
336 ;; FIXME: rx should support (not simple-operator).
337 (not-simple-operator .
,(rx
339 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
340 ;; FIXME: Use regexp-opt.
341 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
342 "=" "%" "**" "//" "<<" ">>" "<=" "!="
343 "==" ">=" "is" "not")))
344 ;; FIXME: Use regexp-opt.
345 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
346 ">>=" "<<=" "&=" "^=" "|=")))
347 (string-delimiter .
,(rx (and
348 ;; Match even number of backslashes.
349 (or (not (any ?
\\ ?
\' ?
\")) point
350 ;; Quotes might be preceded by a escaped quote.
351 (and (or (not (any ?
\\)) point
) ?
\\
352 (* ?
\\ ?
\\) (any ?
\' ?
\")))
354 ;; Match single or triple quotes of any kind.
355 (group (or "\"" "\"\"\"" "'" "'''"))))))
356 "Additional Python specific sexps for `python-rx'")
358 (defmacro python-rx
(&rest regexps
)
359 "Python mode specialized rx macro.
360 This variant of `rx' supports common Python named REGEXPS."
361 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
362 (cond ((null regexps
)
365 (rx-to-string `(and ,@regexps
) t
))
367 (rx-to-string (car regexps
) t
))))))
370 ;;; Font-lock and syntax
373 (defun python-syntax--context-compiler-macro (form type
&optional syntax-ppss
)
376 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
377 (and (nth 4 ppss
) (nth 8 ppss
))))
379 `(let ((ppss (or ,syntax-ppss
(syntax-ppss))))
380 (and (nth 3 ppss
) (nth 8 ppss
))))
382 `(nth 1 (or ,syntax-ppss
(syntax-ppss))))
385 (defun python-syntax-context (type &optional syntax-ppss
)
386 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
387 TYPE can be `comment', `string' or `paren'. It returns the start
388 character address of the specified TYPE."
389 (declare (compiler-macro python-syntax--context-compiler-macro
))
390 (let ((ppss (or syntax-ppss
(syntax-ppss))))
392 (`comment
(and (nth 4 ppss
) (nth 8 ppss
)))
393 (`string
(and (nth 3 ppss
) (nth 8 ppss
)))
394 (`paren
(nth 1 ppss
))
397 (defun python-syntax-context-type (&optional syntax-ppss
)
398 "Return the context type using SYNTAX-PPSS.
399 The type returned can be `comment', `string' or `paren'."
400 (let ((ppss (or syntax-ppss
(syntax-ppss))))
402 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
403 ((nth 1 ppss
) 'paren
))))
405 (defsubst python-syntax-comment-or-string-p
()
406 "Return non-nil if point is inside 'comment or 'string."
407 (nth 8 (syntax-ppss)))
409 (define-obsolete-function-alias
410 'python-info-ppss-context
#'python-syntax-context
"24.3")
412 (define-obsolete-function-alias
413 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
415 (define-obsolete-function-alias
416 'python-info-ppss-comment-or-string-p
417 #'python-syntax-comment-or-string-p
"24.3")
419 (defvar python-font-lock-keywords
423 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
424 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
425 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
430 ;; False, None, and True are listed as keywords on the Python 3
431 ;; documentation, but since they also qualify as constants they are
432 ;; fontified like that in order to keep font-lock consistent between
439 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
440 (1 font-lock-function-name-face
))
442 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
443 (1 font-lock-type-face
))
447 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
448 ;; copyright, license, credits, quit and exit are added by the site
449 ;; module and they are not intended to be used in programs
450 "copyright" "credits" "exit" "license" "quit")
451 symbol-end
) . font-lock-constant-face
)
453 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
454 (0+ "." (1+ (or word ?_
)))))
455 (1 font-lock-type-face
))
456 ;; Builtin Exceptions
459 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
460 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
461 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
462 "ImportError" "ImportWarning" "IndexError" "KeyError"
463 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
464 "NotImplementedError" "OSError" "OverflowError"
465 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
466 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
467 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
468 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
469 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
470 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
474 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
476 symbol-end
) . font-lock-type-face
)
480 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
481 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
482 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
483 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
484 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
485 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
486 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
487 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
490 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
491 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
494 "ascii" "bytearray" "bytes" "exec"
496 "__all__" "__doc__" "__name__" "__package__")
497 symbol-end
) . font-lock-builtin-face
)
499 ;; support for a = b = c = 5
501 (let ((re (python-rx (group (+ (any word ?. ?_
)))
502 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
503 assignment-operator
))
505 (while (and (setq res
(re-search-forward re limit t
))
506 (or (python-syntax-context 'paren
)
507 (equal (char-after (point-marker)) ?
=))))
509 (1 font-lock-variable-name-face nil nil
))
510 ;; support for a, b, c = (1, 2, 3)
512 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
513 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
514 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
515 assignment-operator
))
517 (while (and (setq res
(re-search-forward re limit t
))
518 (goto-char (match-end 1))
519 (python-syntax-context 'paren
)))
521 (1 font-lock-variable-name-face nil nil
))))
523 (defconst python-syntax-propertize-function
524 (syntax-propertize-rules
525 ((python-rx string-delimiter
)
526 (0 (ignore (python-syntax-stringify))))))
528 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
529 "Count number of quotes around point (max is 3).
530 QUOTE-CHAR is the quote char to count. Optional argument POINT is
531 the point where scan starts (defaults to current point), and LIMIT
532 is used to limit the scan."
535 (or (not limit
) (< (+ point i
) limit
))
536 (eq (char-after (+ point i
)) quote-char
))
540 (defun python-syntax-stringify ()
541 "Put `syntax-table' property correctly on single/triple quotes."
542 (let* ((num-quotes (length (match-string-no-properties 1)))
544 (backward-char num-quotes
)
546 (forward-char num-quotes
)))
547 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
548 (quote-starting-pos (- (point) num-quotes
))
549 (quote-ending-pos (point))
552 (python-syntax-count-quotes
553 (char-before) string-start quote-starting-pos
))))
554 (cond ((and string-start
(= num-closing-quotes
0))
555 ;; This set of quotes doesn't match the string starting
559 ;; This set of quotes delimit the start of a string.
560 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
561 'syntax-table
(string-to-syntax "|")))
562 ((= num-quotes num-closing-quotes
)
563 ;; This set of quotes delimit the end of a string.
564 (put-text-property (1- quote-ending-pos
) quote-ending-pos
565 'syntax-table
(string-to-syntax "|")))
566 ((> num-quotes num-closing-quotes
)
567 ;; This may only happen whenever a triple quote is closing
568 ;; a single quoted string. Add string delimiter syntax to
570 (put-text-property quote-starting-pos quote-ending-pos
571 'syntax-table
(string-to-syntax "|"))))))
573 (defvar python-mode-syntax-table
574 (let ((table (make-syntax-table)))
575 ;; Give punctuation syntax to ASCII that normally has symbol
576 ;; syntax or has word syntax and isn't a letter.
577 (let ((symbol (string-to-syntax "_"))
578 (sst (standard-syntax-table)))
581 (if (equal symbol
(aref sst i
))
582 (modify-syntax-entry i
"." table
)))))
583 (modify-syntax-entry ?$
"." table
)
584 (modify-syntax-entry ?%
"." table
)
586 (modify-syntax-entry ?
# "<" table
)
587 (modify-syntax-entry ?
\n ">" table
)
588 (modify-syntax-entry ?
' "\"" table
)
589 (modify-syntax-entry ?
` "$" table
)
591 "Syntax table for Python files.")
593 (defvar python-dotty-syntax-table
594 (let ((table (make-syntax-table python-mode-syntax-table
)))
595 (modify-syntax-entry ?.
"w" table
)
596 (modify-syntax-entry ?_
"w" table
)
598 "Dotty syntax table for Python files.
599 It makes underscores and dots word constituent chars.")
604 (defcustom python-indent-offset
4
605 "Default indentation offset for Python."
610 (defcustom python-indent-guess-indent-offset t
611 "Non-nil tells Python mode to guess `python-indent-offset' value."
616 (defcustom python-indent-trigger-commands
617 '(indent-for-tab-command yas-expand yas
/expand
)
618 "Commands that might trigger a `python-indent-line' call."
619 :type
'(repeat symbol
)
622 (define-obsolete-variable-alias
623 'python-indent
'python-indent-offset
"24.3")
625 (define-obsolete-variable-alias
626 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
628 (defvar python-indent-current-level
0
629 "Current indentation level `python-indent-line-function' is using.")
631 (defvar python-indent-levels
'(0)
632 "Levels of indentation available for `python-indent-line-function'.")
634 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
635 "List of words that should be dedented.
636 These make `python-indent-calculate-indentation' subtract the value of
637 `python-indent-offset'.")
639 (defvar python-indent-block-enders
640 '("break" "continue" "pass" "raise" "return")
641 "List of words that mark the end of a block.
642 These make `python-indent-calculate-indentation' subtract the
643 value of `python-indent-offset' when `python-indent-context' is
646 (defun python-indent-guess-indent-offset ()
647 "Guess and set `python-indent-offset' for the current buffer."
652 (goto-char (point-min))
654 (while (and (not block-end
)
656 (python-rx line-start block-start
) nil t
))
658 (not (python-syntax-context-type))
660 (goto-char (line-end-position))
661 (python-util-forward-comment -
1)
662 (if (equal (char-before) ?
:)
665 (when (python-info-block-continuation-line-p)
666 (while (and (python-info-continuation-line-p)
669 (python-util-forward-comment -
1)
670 (when (equal (char-before) ?
:)
672 (setq block-end
(point-marker))))
675 (goto-char block-end
)
676 (python-util-forward-comment)
677 (current-indentation))))
678 (if (and indentation
(not (zerop indentation
)))
679 (set (make-local-variable 'python-indent-offset
) indentation
)
680 (message "Can't guess python-indent-offset, using defaults: %s"
681 python-indent-offset
)))))))
683 (defun python-indent-context ()
684 "Get information on indentation context.
685 Context information is returned with a cons with the form:
688 Where status can be any of the following symbols:
690 * after-comment: When current line might continue a comment block
691 * inside-paren: If point in between (), {} or []
692 * inside-string: If point is inside a string
693 * after-backslash: Previous line ends in a backslash
694 * after-beginning-of-block: Point is after beginning of block
695 * after-line: Point is after normal line
696 * no-indent: Point is at beginning of buffer or other special case
697 START is the buffer position where the sexp starts."
700 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
704 ;; Beginning of buffer
706 (goto-char (line-beginning-position))
709 ;; Comment continuation
713 (python-info-current-line-comment-p)
714 (python-info-current-line-empty-p))
717 (python-info-current-line-comment-p)))
721 ((setq start
(python-syntax-context 'string ppss
))
724 ((setq start
(python-syntax-context 'paren ppss
))
727 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
728 (python-syntax-context 'comment ppss
)))
729 (let ((line-beg-pos (line-number-at-pos)))
730 (python-info-line-ends-backslash-p
731 (1- line-beg-pos
)))))
733 ;; After beginning of block
734 ((setq start
(save-excursion
736 (back-to-indentation)
737 (python-util-forward-comment -
1)
738 (equal (char-before) ?
:))
739 ;; Move to the first block start that's not in within
740 ;; a string, comment or paren and that's not a
741 ;; continuation line.
742 (while (and (re-search-backward
743 (python-rx block-start
) nil t
)
745 (python-syntax-context-type)
746 (python-info-continuation-line-p))))
747 (when (looking-at (python-rx block-start
))
749 'after-beginning-of-block
)
751 ((setq start
(save-excursion
752 (back-to-indentation)
753 (skip-chars-backward (rx (or whitespace ?
\n)))
754 (python-nav-beginning-of-statement)
761 (defun python-indent-calculate-indentation ()
762 "Calculate correct indentation offset for the current line."
763 (let* ((indentation-context (python-indent-context))
764 (context-status (car indentation-context
))
765 (context-start (cdr indentation-context
)))
769 (pcase context-status
772 (goto-char context-start
)
773 (current-indentation))
774 ;; When point is after beginning of block just add one level
775 ;; of indentation relative to the context-start
776 (`after-beginning-of-block
777 (goto-char context-start
)
778 (+ (current-indentation) python-indent-offset
))
779 ;; When after a simple line just use previous line
780 ;; indentation, in the case current line starts with a
781 ;; `python-indent-dedenters' de-indent one level.
783 (let* ((pair (save-excursion
784 (goto-char context-start
)
786 (current-indentation)
787 (python-info-beginning-of-block-p))))
788 (context-indentation (car pair
))
789 (after-block-start-p (cdr pair
))
791 (if (or (save-excursion
792 (back-to-indentation)
794 ;; De-indent only when dedenters are not
795 ;; next to a block start. This allows
796 ;; one-liner constructs such as:
797 ;; if condition: print "yay"
799 (not after-block-start-p
)
800 (looking-at (regexp-opt python-indent-dedenters
))))
802 (python-util-forward-comment -
1)
803 (python-nav-beginning-of-statement)
804 (looking-at (regexp-opt python-indent-block-enders
))))
807 (- context-indentation adjustment
)))
808 ;; When inside of a string, do nothing. just use the current
809 ;; indentation. XXX: perhaps it would be a good idea to
810 ;; invoke standard text indentation here
812 (goto-char context-start
)
813 (current-indentation))
814 ;; After backslash we have several possibilities.
817 ;; Check if current line is a dot continuation. For this
818 ;; the current line must start with a dot and previous
819 ;; line must contain a dot too.
821 (back-to-indentation)
822 (when (looking-at "\\.")
823 ;; If after moving one line back point is inside a paren it
824 ;; needs to move back until it's not anymore
828 (python-syntax-context 'paren
))))
829 (goto-char (line-end-position))
830 (while (and (re-search-backward
831 "\\." (line-beginning-position) t
)
832 (python-syntax-context-type)))
833 (if (and (looking-at "\\.")
834 (not (python-syntax-context-type)))
835 ;; The indentation is the same column of the
836 ;; first matching dot that's not inside a
837 ;; comment, a string or a paren
839 ;; No dot found on previous line, just add another
840 ;; indentation level.
841 (+ (current-indentation) python-indent-offset
)))))
842 ;; Check if prev line is a block continuation
843 ((let ((block-continuation-start
844 (python-info-block-continuation-line-p)))
845 (when block-continuation-start
846 ;; If block-continuation-start is set jump to that
847 ;; marker and use first column after the block start
848 ;; as indentation value.
849 (goto-char block-continuation-start
)
851 (python-rx block-start
(* space
))
852 (line-end-position) t
)
854 ;; Check if current line is an assignment continuation
855 ((let ((assignment-continuation-start
856 (python-info-assignment-continuation-line-p)))
857 (when assignment-continuation-start
858 ;; If assignment-continuation is set jump to that
859 ;; marker and use first column after the assignment
860 ;; operator as indentation value.
861 (goto-char assignment-continuation-start
)
865 (goto-char (python-info-beginning-of-backslash))
870 (or (python-info-beginning-of-backslash) (point)))
871 (python-info-line-ends-backslash-p)))
872 ;; The two previous lines ended in a backslash so we must
873 ;; respect previous line indentation.
874 (current-indentation)
875 ;; What happens here is that we are dealing with the second
876 ;; line of a backslash continuation, in that case we just going
877 ;; to add one indentation level.
878 (+ (current-indentation) python-indent-offset
)))))
879 ;; When inside a paren there's a need to handle nesting
883 ;; If current line closes the outermost open paren use the
884 ;; current indentation of the context-start line.
886 (skip-syntax-forward "\s" (line-end-position))
887 (when (and (looking-at (regexp-opt '(")" "]" "}")))
890 (not (python-syntax-context 'paren
))))
891 (goto-char context-start
)
892 (current-indentation))))
893 ;; If open paren is contained on a line by itself add another
894 ;; indentation level, else look for the first word after the
895 ;; opening paren and use it's column position as indentation
897 ((let* ((content-starts-in-newline)
900 (if (setq content-starts-in-newline
902 (goto-char context-start
)
906 (line-beginning-position)
908 (python-util-forward-comment))
910 (+ (current-indentation) python-indent-offset
)
914 ;; If current line closes a nested open paren de-indent one
917 (back-to-indentation)
918 (looking-at (regexp-opt '(")" "]" "}"))))
919 (- indent python-indent-offset
))
920 ;; If the line of the opening paren that wraps the current
921 ;; line starts a block add another level of indentation to
922 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
924 (when (and content-starts-in-newline
926 (goto-char context-start
)
927 (back-to-indentation)
928 (looking-at (python-rx block-start
))))
929 (+ indent python-indent-offset
))))
932 (defun python-indent-calculate-levels ()
933 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
934 (let* ((indentation (python-indent-calculate-indentation))
935 (remainder (% indentation python-indent-offset
))
936 (steps (/ (- indentation remainder
) python-indent-offset
)))
937 (setq python-indent-levels
(list 0))
938 (dotimes (step steps
)
939 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
940 (when (not (eq 0 remainder
))
941 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
942 (setq python-indent-levels
(nreverse python-indent-levels
))
943 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
945 (defun python-indent-toggle-levels ()
946 "Toggle `python-indent-current-level' over `python-indent-levels'."
947 (setq python-indent-current-level
(1- python-indent-current-level
))
948 (when (< python-indent-current-level
0)
949 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
951 (defun python-indent-line (&optional force-toggle
)
952 "Internal implementation of `python-indent-line-function'.
953 Uses the offset calculated in
954 `python-indent-calculate-indentation' and available levels
955 indicated by the variable `python-indent-levels' to set the
958 When the variable `last-command' is equal to one of the symbols
959 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
960 non-nil it cycles levels indicated in the variable
961 `python-indent-levels' by setting the current level in the
962 variable `python-indent-current-level'.
964 When the variable `last-command' is not equal to one of the
965 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
966 is nil it calculates possible indentation levels and saves them
967 in the variable `python-indent-levels'. Afterwards it sets the
968 variable `python-indent-current-level' correctly so offset is
970 (nth python-indent-current-level python-indent-levels)"
972 (and (or (and (memq this-command python-indent-trigger-commands
)
973 (eq last-command this-command
))
975 (not (equal python-indent-levels
'(0)))
976 (or (python-indent-toggle-levels) t
))
977 (python-indent-calculate-levels))
978 (let* ((starting-pos (point-marker))
979 (indent-ending-position
980 (+ (line-beginning-position) (current-indentation)))
981 (follow-indentation-p
983 (and (<= (line-beginning-position) starting-pos
)
984 (>= indent-ending-position starting-pos
))))
985 (next-indent (nth python-indent-current-level python-indent-levels
)))
986 (unless (= next-indent
(current-indentation))
988 (delete-horizontal-space)
989 (indent-to next-indent
)
990 (goto-char starting-pos
))
991 (and follow-indentation-p
(back-to-indentation)))
992 (python-info-closing-block-message))
994 (defun python-indent-line-function ()
995 "`indent-line-function' for Python mode.
996 See `python-indent-line' for details."
997 (python-indent-line))
999 (defun python-indent-dedent-line ()
1000 "De-indent current line."
1002 (when (and (not (python-syntax-comment-or-string-p))
1003 (<= (point-marker) (save-excursion
1004 (back-to-indentation)
1006 (> (current-column) 0))
1007 (python-indent-line t
)
1010 (defun python-indent-dedent-line-backspace (arg)
1011 "De-indent current line.
1012 Argument ARG is passed to `backward-delete-char-untabify' when
1013 point is not in between the indentation."
1015 (when (not (python-indent-dedent-line))
1016 (backward-delete-char-untabify arg
)))
1017 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
1019 (defun python-indent-region (start end
)
1020 "Indent a Python region automagically.
1022 Called from a program, START and END specify the region to indent."
1023 (let ((deactivate-mark nil
))
1026 (setq end
(point-marker))
1028 (or (bolp) (forward-line 1))
1029 (while (< (point) end
)
1030 (or (and (bolp) (eolp))
1033 (back-to-indentation)
1034 (setq word
(current-word))
1037 ;; Don't mess with strings, unless it's the
1038 ;; enclosing set of quotes.
1039 (or (not (python-syntax-context 'string
))
1043 (current-indentation)
1044 (python-syntax-count-quotes (char-after) (point))))
1045 (string-to-syntax "|"))))
1047 (delete-horizontal-space)
1048 (indent-to (python-indent-calculate-indentation)))))
1050 (move-marker end nil
))))
1052 (defun python-indent-shift-left (start end
&optional count
)
1053 "Shift lines contained in region START END by COUNT columns to the left.
1054 COUNT defaults to `python-indent-offset'. If region isn't
1055 active, the current line is shifted. The shifted region includes
1056 the lines in which START and END lie. An error is signaled if
1057 any lines in the region are indented less than COUNT columns."
1060 (list (region-beginning) (region-end) current-prefix-arg
)
1061 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1063 (setq count
(prefix-numeric-value count
))
1064 (setq count python-indent-offset
))
1066 (let ((deactivate-mark nil
))
1069 (while (< (point) end
)
1070 (if (and (< (current-indentation) count
)
1071 (not (looking-at "[ \t]*$")))
1072 (error "Can't shift all lines enough"))
1074 (indent-rigidly start end
(- count
))))))
1076 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1078 (defun python-indent-shift-right (start end
&optional count
)
1079 "Shift lines contained in region START END by COUNT columns to the right.
1080 COUNT defaults to `python-indent-offset'. If region isn't
1081 active, the current line is shifted. The shifted region includes
1082 the lines in which START and END lie."
1085 (list (region-beginning) (region-end) current-prefix-arg
)
1086 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1087 (let ((deactivate-mark nil
))
1088 (setq count
(if count
(prefix-numeric-value count
)
1089 python-indent-offset
))
1090 (indent-rigidly start end count
)))
1092 (defun python-indent-post-self-insert-function ()
1093 "Adjust indentation after insertion of some characters.
1094 This function is intended to be added to `post-self-insert-hook.'
1095 If a line renders a paren alone, after adding a char before it,
1096 the line will be re-indented automatically if needed."
1097 (when (and electric-indent-mode
1098 (eq (char-before) last-command-event
))
1101 (memq (char-after) '(?\
) ?\
] ?\
})))
1103 (goto-char (line-beginning-position))
1104 ;; If after going to the beginning of line the point
1105 ;; is still inside a paren it's ok to do the trick
1106 (when (python-syntax-context 'paren
)
1107 (let ((indentation (python-indent-calculate-indentation)))
1108 (when (< (current-indentation) indentation
)
1109 (indent-line-to indentation
))))))
1110 ((and (eq ?
: last-command-event
)
1111 (memq ?
: electric-indent-chars
)
1112 (not current-prefix-arg
)
1114 (not (equal ?
: (char-before (1- (point)))))
1115 (not (python-syntax-comment-or-string-p)))
1116 (let ((indentation (current-indentation))
1117 (calculated-indentation (python-indent-calculate-indentation)))
1118 (python-info-closing-block-message)
1119 (when (> indentation calculated-indentation
)
1121 (indent-line-to calculated-indentation
)
1122 (when (not (python-info-closing-block-message))
1123 (indent-line-to indentation
)))))))))
1128 (defvar python-nav-beginning-of-defun-regexp
1129 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1130 "Regexp matching class or function definition.
1131 The name of the defun should be grouped so it can be retrieved
1132 via `match-string'.")
1134 (defun python-nav--beginning-of-defun (&optional arg
)
1135 "Internal implementation of `python-nav-beginning-of-defun'.
1136 With positive ARG search backwards, else search forwards."
1137 (when (or (null arg
) (= arg
0)) (setq arg
1))
1138 (let* ((re-search-fn (if (> arg
0)
1139 #'re-search-backward
1140 #'re-search-forward
))
1141 (line-beg-pos (line-beginning-position))
1142 (line-content-start (+ line-beg-pos
(current-indentation)))
1143 (pos (point-marker))
1148 (not (python-info-looking-at-beginning-of-defun))
1149 (python-nav-backward-block)))
1150 (or (and (python-info-looking-at-beginning-of-defun)
1151 (+ (current-indentation) python-indent-offset
))
1155 (when (and (< arg
0)
1156 (python-info-looking-at-beginning-of-defun))
1158 (while (and (funcall re-search-fn
1159 python-nav-beginning-of-defun-regexp nil t
)
1160 (or (python-syntax-context-type)
1161 ;; Handle nested defuns when moving
1162 ;; backwards by checking indentation.
1164 (not (= (current-indentation) 0))
1165 (>= (current-indentation) beg-indentation
)))))
1166 (and (python-info-looking-at-beginning-of-defun)
1167 (or (not (= (line-number-at-pos pos
)
1168 (line-number-at-pos)))
1169 (and (>= (point) line-beg-pos
)
1170 (<= (point) line-content-start
)
1171 (> pos line-content-start
)))))))
1173 (or (beginning-of-line 1) t
)
1174 (and (goto-char pos
) nil
))))
1176 (defun python-nav-beginning-of-defun (&optional arg
)
1177 "Move point to `beginning-of-defun'.
1178 With positive ARG search backwards else search forward.
1179 ARG nil or 0 defaults to 1. When searching backwards,
1180 nested defuns are handled with care depending on current
1181 point position. Return non-nil if point is moved to
1182 `beginning-of-defun'."
1183 (when (or (null arg
) (= arg
0)) (setq arg
1))
1185 (while (and (not (= arg
0))
1186 (let ((keep-searching-p
1187 (python-nav--beginning-of-defun arg)))
1188 (when (and keep-searching-p
(null found
))
1191 (setq arg
(if (> arg
0) (1- arg
) (1+ arg
))))
1194 (defun python-nav-end-of-defun ()
1195 "Move point to the end of def or class.
1196 Returns nil if point is not in a def or class."
1198 (let ((beg-defun-indent)
1200 (when (or (python-info-looking-at-beginning-of-defun)
1201 (python-nav-beginning-of-defun 1)
1202 (python-nav-beginning-of-defun -1))
1203 (setq beg-defun-indent
(current-indentation))
1205 (python-nav-end-of-statement)
1206 (python-util-forward-comment 1)
1207 (and (> (current-indentation) beg-defun-indent
)
1209 (python-util-forward-comment -
1)
1211 ;; Ensure point moves forward.
1212 (and (> beg-pos
(point)) (goto-char beg-pos
)))))
1214 (defun python-nav--syntactically (fn poscompfn
&optional contextfn
)
1215 "Move point using FN avoiding places with specific context.
1216 FN must take no arguments. POSCOMPFN is a two arguments function
1217 used to compare current and previous point after it is moved
1218 using FN, this is normally a less-than or greater-than
1219 comparison. Optional argument CONTEXTFN defaults to
1220 `python-syntax-context-type' and is used for checking current
1221 point context, it must return a non-nil value if this point must
1223 (let ((contextfn (or contextfn
'python-syntax-context-type
))
1224 (start-pos (point-marker))
1229 (and (funcall fn
) (point-marker)))
1230 (context (funcall contextfn
)))
1231 (cond ((and (not context
) newpos
1232 (or (and (not prev-pos
) newpos
)
1233 (and prev-pos newpos
1234 (funcall poscompfn newpos prev-pos
))))
1235 (throw 'found
(point-marker)))
1236 ((and newpos context
)
1237 (setq prev-pos
(point)))
1238 (t (when (not newpos
) (goto-char start-pos
))
1239 (throw 'found nil
))))))))
1241 (defun python-nav--forward-defun (arg)
1242 "Internal implementation of python-nav-{backward,forward}-defun.
1243 Uses ARG to define which function to call, and how many times
1246 (while (and (> arg
0)
1248 (python-nav--syntactically
1251 python-nav-beginning-of-defun-regexp nil t
))
1253 (setq arg
(1- arg
)))
1254 (while (and (< arg
0)
1256 (python-nav--syntactically
1259 python-nav-beginning-of-defun-regexp nil t
))
1261 (setq arg
(1+ arg
)))
1264 (defun python-nav-backward-defun (&optional arg
)
1265 "Navigate to closer defun backward ARG times.
1266 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1267 nested definitions."
1269 (python-nav--forward-defun (- (or arg
1))))
1271 (defun python-nav-forward-defun (&optional arg
)
1272 "Navigate to closer defun forward ARG times.
1273 Unlikely `python-nav-beginning-of-defun' this doesn't care about
1274 nested definitions."
1276 (python-nav--forward-defun (or arg
1)))
1278 (defun python-nav-beginning-of-statement ()
1279 "Move to start of current statement."
1281 (back-to-indentation)
1282 (let* ((ppss (syntax-ppss))
1285 (python-syntax-context 'paren ppss
)
1286 (python-syntax-context 'string ppss
))))
1289 (goto-char context-point
)
1290 (python-nav-beginning-of-statement))
1293 (python-info-line-ends-backslash-p))
1295 (python-nav-beginning-of-statement))))
1298 (defun python-nav-end-of-statement (&optional noend
)
1299 "Move to end of current statement.
1300 Optional argument NOEND is internal and makes the logic to not
1301 jump to the end of line when moving forward searching for the end
1304 (let (string-start bs-pos
)
1305 (while (and (or noend
(goto-char (line-end-position)))
1307 (cond ((setq string-start
(python-syntax-context 'string
))
1308 (goto-char string-start
)
1309 (if (python-syntax-context 'paren
)
1310 ;; Ended up inside a paren, roll again.
1311 (python-nav-end-of-statement t
)
1312 ;; This is not inside a paren, move to the
1313 ;; end of this string.
1314 (goto-char (+ (point)
1315 (python-syntax-count-quotes
1316 (char-after (point)) (point))))
1317 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
1318 (goto-char (point-max)))))
1319 ((python-syntax-context 'paren
)
1320 ;; The statement won't end before we've escaped
1321 ;; at least one level of parenthesis.
1323 (goto-char (scan-lists (point) 1 -
1))
1324 (scan-error (goto-char (nth 3 err
)))))
1325 ((setq bs-pos
(python-info-line-ends-backslash-p))
1327 (forward-line 1))))))
1330 (defun python-nav-backward-statement (&optional arg
)
1331 "Move backward to previous statement.
1332 With ARG, repeat. See `python-nav-forward-statement'."
1334 (or arg
(setq arg
1))
1335 (python-nav-forward-statement (- arg
)))
1337 (defun python-nav-forward-statement (&optional arg
)
1338 "Move forward to next statement.
1339 With ARG, repeat. With negative argument, move ARG times
1340 backward to previous statement."
1342 (or arg
(setq arg
1))
1344 (python-nav-end-of-statement)
1345 (python-util-forward-comment)
1346 (python-nav-beginning-of-statement)
1347 (setq arg
(1- arg
)))
1349 (python-nav-beginning-of-statement)
1350 (python-util-forward-comment -
1)
1351 (python-nav-beginning-of-statement)
1352 (setq arg
(1+ arg
))))
1354 (defun python-nav-beginning-of-block ()
1355 "Move to start of current block."
1357 (let ((starting-pos (point)))
1359 (python-nav-beginning-of-statement)
1360 (looking-at (python-rx block-start
)))
1362 ;; Go to first line beginning a statement
1363 (while (and (not (bobp))
1364 (or (and (python-nav-beginning-of-statement) nil
)
1365 (python-info-current-line-comment-p)
1366 (python-info-current-line-empty-p)))
1368 (let ((block-matching-indent
1369 (- (current-indentation) python-indent-offset
)))
1371 (and (python-nav-backward-block)
1372 (> (current-indentation) block-matching-indent
)))
1373 (if (and (looking-at (python-rx block-start
))
1374 (= (current-indentation) block-matching-indent
))
1376 (and (goto-char starting-pos
) nil
))))))
1378 (defun python-nav-end-of-block ()
1379 "Move to end of current block."
1381 (when (python-nav-beginning-of-block)
1382 (let ((block-indentation (current-indentation)))
1383 (python-nav-end-of-statement)
1384 (while (and (forward-line 1)
1386 (or (and (> (current-indentation) block-indentation
)
1387 (or (python-nav-end-of-statement) t
))
1388 (python-info-current-line-comment-p)
1389 (python-info-current-line-empty-p))))
1390 (python-util-forward-comment -
1)
1393 (defun python-nav-backward-block (&optional arg
)
1394 "Move backward to previous block of code.
1395 With ARG, repeat. See `python-nav-forward-block'."
1397 (or arg
(setq arg
1))
1398 (python-nav-forward-block (- arg
)))
1400 (defun python-nav-forward-block (&optional arg
)
1401 "Move forward to next block of code.
1402 With ARG, repeat. With negative argument, move ARG times
1403 backward to previous block."
1405 (or arg
(setq arg
1))
1406 (let ((block-start-regexp
1407 (python-rx line-start
(* whitespace
) block-start
))
1408 (starting-pos (point)))
1410 (python-nav-end-of-statement)
1412 (re-search-forward block-start-regexp nil t
)
1413 (python-syntax-context-type)))
1414 (setq arg
(1- arg
)))
1416 (python-nav-beginning-of-statement)
1418 (re-search-backward block-start-regexp nil t
)
1419 (python-syntax-context-type)))
1420 (setq arg
(1+ arg
)))
1421 (python-nav-beginning-of-statement)
1422 (if (not (looking-at (python-rx block-start
)))
1423 (and (goto-char starting-pos
) nil
)
1424 (and (not (= (point) starting-pos
)) (point-marker)))))
1426 (defun python-nav--lisp-forward-sexp (&optional arg
)
1427 "Standard version `forward-sexp'.
1428 It ignores completely the value of `forward-sexp-function' by
1429 setting it to nil before calling `forward-sexp'. With positive
1430 ARG move forward only one sexp, else move backwards."
1431 (let ((forward-sexp-function)
1432 (arg (if (or (not arg
) (> arg
0)) 1 -
1)))
1433 (forward-sexp arg
)))
1435 (defun python-nav--lisp-forward-sexp-safe (&optional arg
)
1436 "Safe version of standard `forward-sexp'.
1437 When at end of sexp (i.e. looking at a opening/closing paren)
1438 skips it instead of throwing an error. With positive ARG move
1439 forward only one sexp, else move backwards."
1440 (let* ((arg (if (or (not arg
) (> arg
0)) 1 -
1))
1442 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1444 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1446 (python-nav--lisp-forward-sexp arg
)
1448 (while (and (funcall search-fn paren-regexp nil t
)
1449 (python-syntax-context 'paren
)))))))
1451 (defun python-nav--forward-sexp (&optional dir safe
)
1452 "Move to forward sexp.
1453 With positive optional argument DIR direction move forward, else
1454 backwards. When optional argument SAFE is non-nil do not throw
1455 errors when at end of sexp, skip it instead."
1456 (setq dir
(or dir
1))
1458 (let* ((forward-p (if (> dir
0)
1459 (and (setq dir
1) t
)
1460 (and (setq dir -
1) nil
)))
1461 (context-type (python-syntax-context-type)))
1463 ((memq context-type
'(string comment
))
1464 ;; Inside of a string, get out of it.
1465 (let ((forward-sexp-function))
1466 (forward-sexp dir
)))
1467 ((or (eq context-type
'paren
)
1468 (and forward-p
(looking-at (python-rx open-paren
)))
1469 (and (not forward-p
)
1470 (eq (syntax-class (syntax-after (1- (point))))
1471 (car (string-to-syntax ")")))))
1472 ;; Inside a paren or looking at it, lisp knows what to do.
1474 (python-nav--lisp-forward-sexp-safe dir
)
1475 (python-nav--lisp-forward-sexp dir
)))
1477 ;; This part handles the lispy feel of
1478 ;; `python-nav-forward-sexp'. Knowing everything about the
1479 ;; current context and the context of the next sexp tries to
1480 ;; follow the lisp sexp motion commands in a symmetric manner.
1483 ((python-info-beginning-of-block-p) 'block-start
)
1484 ((python-info-end-of-block-p) 'block-end
)
1485 ((python-info-beginning-of-statement-p) 'statement-start
)
1486 ((python-info-end-of-statement-p) 'statement-end
)))
1490 (python-nav--lisp-forward-sexp-safe dir
)
1491 (python-nav--lisp-forward-sexp dir
))
1495 (goto-char next-sexp-pos
)
1497 ((python-info-beginning-of-block-p) 'block-start
)
1498 ((python-info-end-of-block-p) 'block-end
)
1499 ((python-info-beginning-of-statement-p) 'statement-start
)
1500 ((python-info-end-of-statement-p) 'statement-end
)
1501 ((python-info-statement-starts-block-p) 'starts-block
)
1502 ((python-info-statement-ends-block-p) 'ends-block
)))))
1504 (cond ((and (not (eobp))
1505 (python-info-current-line-empty-p))
1506 (python-util-forward-comment dir
)
1507 (python-nav--forward-sexp dir
))
1508 ((eq context
'block-start
)
1509 (python-nav-end-of-block))
1510 ((eq context
'statement-start
)
1511 (python-nav-end-of-statement))
1512 ((and (memq context
'(statement-end block-end
))
1513 (eq next-sexp-context
'ends-block
))
1514 (goto-char next-sexp-pos
)
1515 (python-nav-end-of-block))
1516 ((and (memq context
'(statement-end block-end
))
1517 (eq next-sexp-context
'starts-block
))
1518 (goto-char next-sexp-pos
)
1519 (python-nav-end-of-block))
1520 ((memq context
'(statement-end block-end
))
1521 (goto-char next-sexp-pos
)
1522 (python-nav-end-of-statement))
1523 (t (goto-char next-sexp-pos
)))
1524 (cond ((and (not (bobp))
1525 (python-info-current-line-empty-p))
1526 (python-util-forward-comment dir
)
1527 (python-nav--forward-sexp dir
))
1528 ((eq context
'block-end
)
1529 (python-nav-beginning-of-block))
1530 ((eq context
'statement-end
)
1531 (python-nav-beginning-of-statement))
1532 ((and (memq context
'(statement-start block-start
))
1533 (eq next-sexp-context
'starts-block
))
1534 (goto-char next-sexp-pos
)
1535 (python-nav-beginning-of-block))
1536 ((and (memq context
'(statement-start block-start
))
1537 (eq next-sexp-context
'ends-block
))
1538 (goto-char next-sexp-pos
)
1539 (python-nav-beginning-of-block))
1540 ((memq context
'(statement-start block-start
))
1541 (goto-char next-sexp-pos
)
1542 (python-nav-beginning-of-statement))
1543 (t (goto-char next-sexp-pos
))))))))))
1545 (defun python-nav-forward-sexp (&optional arg
)
1546 "Move forward across expressions.
1547 With ARG, do it that many times. Negative arg -N means move
1550 (or arg
(setq arg
1))
1552 (python-nav--forward-sexp 1)
1553 (setq arg
(1- arg
)))
1555 (python-nav--forward-sexp -
1)
1556 (setq arg
(1+ arg
))))
1558 (defun python-nav-backward-sexp (&optional arg
)
1559 "Move backward across expressions.
1560 With ARG, do it that many times. Negative arg -N means move
1563 (or arg
(setq arg
1))
1564 (python-nav-forward-sexp (- arg
)))
1566 (defun python-nav-forward-sexp-safe (&optional arg
)
1567 "Move forward safely across expressions.
1568 With ARG, do it that many times. Negative arg -N means move
1571 (or arg
(setq arg
1))
1573 (python-nav--forward-sexp 1 t
)
1574 (setq arg
(1- arg
)))
1576 (python-nav--forward-sexp -
1 t
)
1577 (setq arg
(1+ arg
))))
1579 (defun python-nav-backward-sexp-safe (&optional arg
)
1580 "Move backward safely across expressions.
1581 With ARG, do it that many times. Negative arg -N means move
1584 (or arg
(setq arg
1))
1585 (python-nav-forward-sexp-safe (- arg
)))
1587 (defun python-nav--up-list (&optional dir
)
1588 "Internal implementation of `python-nav-up-list'.
1589 DIR is always 1 or -1 and comes sanitized from
1590 `python-nav-up-list' calls."
1591 (let ((context (python-syntax-context-type))
1592 (forward-p (> dir
0)))
1594 ((memq context
'(string comment
)))
1595 ((eq context
'paren
)
1596 (let ((forward-sexp-function))
1598 ((and forward-p
(python-info-end-of-block-p))
1599 (let ((parent-end-pos
1601 (let ((indentation (and
1602 (python-nav-beginning-of-block)
1603 (current-indentation))))
1604 (while (and indentation
1606 (>= (current-indentation) indentation
)
1607 (python-nav-backward-block)))
1608 (python-nav-end-of-block)))))
1609 (and (> (or parent-end-pos
(point)) (point))
1610 (goto-char parent-end-pos
))))
1611 (forward-p (python-nav-end-of-block))
1612 ((and (not forward-p
)
1613 (> (current-indentation) 0)
1614 (python-info-beginning-of-block-p))
1615 (let ((prev-block-pos
1617 (let ((indentation (current-indentation)))
1618 (while (and (python-nav-backward-block)
1619 (>= (current-indentation) indentation
))))
1621 (and (> (point) prev-block-pos
)
1622 (goto-char prev-block-pos
))))
1623 ((not forward-p
) (python-nav-beginning-of-block)))))
1625 (defun python-nav-up-list (&optional arg
)
1626 "Move forward out of one level of parentheses (or blocks).
1627 With ARG, do this that many times.
1628 A negative argument means move backward but still to a less deep spot.
1629 This command assumes point is not in a string or comment."
1631 (or arg
(setq arg
1))
1633 (python-nav--up-list 1)
1634 (setq arg
(1- arg
)))
1636 (python-nav--up-list -
1)
1637 (setq arg
(1+ arg
))))
1639 (defun python-nav-backward-up-list (&optional arg
)
1640 "Move backward out of one level of parentheses (or blocks).
1641 With ARG, do this that many times.
1642 A negative argument means move forward but still to a less deep spot.
1643 This command assumes point is not in a string or comment."
1645 (or arg
(setq arg
1))
1646 (python-nav-up-list (- arg
)))
1648 (defun python-nav-if-name-main ()
1649 "Move point at the beginning the __main__ block.
1650 When \"if __name__ == '__main__':\" is found returns its
1651 position, else returns nil."
1653 (let ((point (point))
1654 (found (catch 'found
1655 (goto-char (point-min))
1656 (while (re-search-forward
1657 (python-rx line-start
1659 "__name__" (+ space
)
1661 (group-n 1 (or ?
\" ?
\'))
1662 "__main__" (backref 1) (* space
) ":")
1664 (when (not (python-syntax-context-type))
1666 (throw 'found t
))))))
1669 (ignore (goto-char point
)))))
1672 ;;; Shell integration
1674 (defcustom python-shell-buffer-name
"Python"
1675 "Default buffer name for Python interpreter."
1680 (defcustom python-shell-interpreter
"python"
1681 "Default Python interpreter for shell."
1685 (defcustom python-shell-internal-buffer-name
"Python Internal"
1686 "Default buffer name for the Internal Python interpreter."
1691 (defcustom python-shell-interpreter-args
"-i"
1692 "Default arguments for the Python interpreter."
1696 (defcustom python-shell-prompt-regexp
">>> "
1697 "Regular expression matching top-level input prompt of Python shell.
1698 It should not contain a caret (^) at the beginning."
1703 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1704 "Regular expression matching block input prompt of Python shell.
1705 It should not contain a caret (^) at the beginning."
1710 (defcustom python-shell-prompt-output-regexp
""
1711 "Regular expression matching output prompt of Python shell.
1712 It should not contain a caret (^) at the beginning."
1717 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1718 "Regular expression matching pdb input prompt of Python shell.
1719 It should not contain a caret (^) at the beginning."
1724 (defcustom python-shell-enable-font-lock t
1725 "Should syntax highlighting be enabled in the Python shell buffer?
1726 Restart the Python shell after changing this variable for it to take effect."
1731 (defcustom python-shell-process-environment nil
1732 "List of environment variables for Python shell.
1733 This variable follows the same rules as `process-environment'
1734 since it merges with it before the process creation routines are
1735 called. When this variable is nil, the Python shell is run with
1736 the default `process-environment'."
1737 :type
'(repeat string
)
1741 (defcustom python-shell-extra-pythonpaths nil
1742 "List of extra pythonpaths for Python shell.
1743 The values of this variable are added to the existing value of
1744 PYTHONPATH in the `process-environment' variable."
1745 :type
'(repeat string
)
1749 (defcustom python-shell-exec-path nil
1750 "List of path to search for binaries.
1751 This variable follows the same rules as `exec-path' since it
1752 merges with it before the process creation routines are called.
1753 When this variable is nil, the Python shell is run with the
1754 default `exec-path'."
1755 :type
'(repeat string
)
1759 (defcustom python-shell-virtualenv-path nil
1760 "Path to virtualenv root.
1761 This variable, when set to a string, makes the values stored in
1762 `python-shell-process-environment' and `python-shell-exec-path'
1763 to be modified properly so shells are started with the specified
1765 :type
'(choice (const nil
) string
)
1769 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1770 python-ffap-setup-code
1771 python-eldoc-setup-code
)
1772 "List of code run by `python-shell-send-setup-codes'."
1773 :type
'(repeat symbol
)
1777 (defcustom python-shell-compilation-regexp-alist
1778 `((,(rx line-start
(1+ (any " \t")) "File \""
1779 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1780 "\", line " (group (1+ digit
)))
1782 (,(rx " in file " (group (1+ not-newline
)) " on line "
1785 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1786 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1788 "`compilation-error-regexp-alist' for inferior Python."
1789 :type
'(alist string
)
1792 (defun python-shell-get-process-name (dedicated)
1793 "Calculate the appropriate process name for inferior Python process.
1794 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1795 returns a string with the form
1796 `python-shell-buffer-name'[variable `buffer-file-name'] else
1797 returns the value of `python-shell-buffer-name'."
1801 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1802 (format "%s" python-shell-buffer-name
))))
1805 (defun python-shell-internal-get-process-name ()
1806 "Calculate the appropriate process name for Internal Python process.
1807 The name is calculated from `python-shell-global-buffer-name' and
1808 a hash of all relevant global shell settings in order to ensure
1809 uniqueness for different types of configurations."
1811 python-shell-internal-buffer-name
1814 (python-shell-parse-command)
1815 python-shell-prompt-regexp
1816 python-shell-prompt-block-regexp
1817 python-shell-prompt-output-regexp
1818 (mapconcat #'symbol-value python-shell-setup-codes
"")
1819 (mapconcat #'identity python-shell-process-environment
"")
1820 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1821 (mapconcat #'identity python-shell-exec-path
"")
1822 (or python-shell-virtualenv-path
"")
1823 (mapconcat #'identity python-shell-exec-path
"")))))
1825 (defun python-shell-parse-command ()
1826 "Calculate the string used to execute the inferior Python process."
1827 (let ((process-environment (python-shell-calculate-process-environment))
1828 (exec-path (python-shell-calculate-exec-path)))
1830 (executable-find python-shell-interpreter
)
1831 python-shell-interpreter-args
)))
1833 (defun python-shell-calculate-process-environment ()
1834 "Calculate process environment given `python-shell-virtualenv-path'."
1835 (let ((process-environment (append
1836 python-shell-process-environment
1837 process-environment nil
))
1838 (virtualenv (if python-shell-virtualenv-path
1839 (directory-file-name python-shell-virtualenv-path
)
1841 (when python-shell-extra-pythonpaths
1842 (setenv "PYTHONPATH"
1844 (mapconcat 'identity
1845 python-shell-extra-pythonpaths
1848 (or (getenv "PYTHONPATH") ""))))
1849 (if (not virtualenv
)
1851 (setenv "PYTHONHOME" nil
)
1852 (setenv "PATH" (format "%s/bin%s%s"
1853 virtualenv path-separator
1854 (or (getenv "PATH") "")))
1855 (setenv "VIRTUAL_ENV" virtualenv
))
1856 process-environment
))
1858 (defun python-shell-calculate-exec-path ()
1859 "Calculate exec path given `python-shell-virtualenv-path'."
1860 (let ((path (append python-shell-exec-path
1862 (if (not python-shell-virtualenv-path
)
1864 (cons (format "%s/bin"
1865 (directory-file-name python-shell-virtualenv-path
))
1868 (defun python-comint-output-filter-function (output)
1869 "Hook run after content is put into comint buffer.
1870 OUTPUT is a string with the contents of the buffer."
1871 (ansi-color-filter-apply output
))
1873 (defvar python-shell--parent-buffer nil
)
1875 (defvar python-shell-output-syntax-table
1876 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1877 (modify-syntax-entry ?
\' "." table
)
1878 (modify-syntax-entry ?
\" "." table
)
1879 (modify-syntax-entry ?\
( "." table
)
1880 (modify-syntax-entry ?\
[ "." table
)
1881 (modify-syntax-entry ?\
{ "." table
)
1882 (modify-syntax-entry ?\
) "." table
)
1883 (modify-syntax-entry ?\
] "." table
)
1884 (modify-syntax-entry ?\
} "." table
)
1886 "Syntax table for shell output.
1887 It makes parens and quotes be treated as punctuation chars.")
1889 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1890 "Major mode for Python inferior process.
1891 Runs a Python interpreter as a subprocess of Emacs, with Python
1892 I/O through an Emacs buffer. Variables `python-shell-interpreter'
1893 and `python-shell-interpreter-args' control which Python
1894 interpreter is run. Variables
1895 `python-shell-prompt-regexp',
1896 `python-shell-prompt-output-regexp',
1897 `python-shell-prompt-block-regexp',
1898 `python-shell-enable-font-lock',
1899 `python-shell-completion-setup-code',
1900 `python-shell-completion-string-code',
1901 `python-shell-completion-module-string-code',
1902 `python-eldoc-setup-code', `python-eldoc-string-code',
1903 `python-ffap-setup-code' and `python-ffap-string-code' can
1904 customize this mode for different Python interpreters.
1906 You can also add additional setup code to be run at
1907 initialization of the interpreter via `python-shell-setup-codes'
1910 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1911 (and python-shell--parent-buffer
1912 (python-util-clone-local-variables python-shell--parent-buffer
))
1913 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1914 python-shell-prompt-regexp
1915 python-shell-prompt-block-regexp
1916 python-shell-prompt-pdb-regexp
))
1917 (setq mode-line-process
'(":%s"))
1918 (make-local-variable 'comint-output-filter-functions
)
1919 (add-hook 'comint-output-filter-functions
1920 'python-comint-output-filter-function
)
1921 (add-hook 'comint-output-filter-functions
1922 'python-pdbtrack-comint-output-filter-function
)
1923 (set (make-local-variable 'compilation-error-regexp-alist
)
1924 python-shell-compilation-regexp-alist
)
1925 (define-key inferior-python-mode-map
[remap complete-symbol
]
1926 'completion-at-point
)
1927 (add-hook 'completion-at-point-functions
1928 'python-shell-completion-complete-at-point nil
'local
)
1929 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1930 'python-shell-completion-complete-at-point
)
1931 (define-key inferior-python-mode-map
"\t"
1932 'python-shell-completion-complete-or-indent
)
1933 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1934 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1935 (make-local-variable 'python-shell-internal-last-output
)
1936 (when python-shell-enable-font-lock
1937 (set-syntax-table python-mode-syntax-table
)
1938 (set (make-local-variable 'font-lock-defaults
)
1939 '(python-font-lock-keywords nil nil nil nil
))
1940 (set (make-local-variable 'syntax-propertize-function
)
1942 ;; XXX: Unfortunately eval is needed here to make use of the
1943 ;; dynamic value of `comint-prompt-regexp'.
1944 `(syntax-propertize-rules
1945 (,comint-prompt-regexp
1948 comint-last-input-start end
'syntax-table
1949 python-shell-output-syntax-table
)
1950 ;; XXX: This might look weird, but it is the easiest
1951 ;; way to ensure font lock gets cleaned up before the
1952 ;; current prompt, which is needed for unclosed
1953 ;; strings to not mess up with current input.
1954 (font-lock-unfontify-region comint-last-input-start end
))))
1955 (,(python-rx string-delimiter
)
1957 (and (not (eq (get-text-property start
'field
) 'output
))
1958 (python-syntax-stringify)))))))))
1959 (compilation-shell-minor-mode 1))
1961 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1962 "Create a Python shell comint buffer.
1963 CMD is the Python command to be executed and PROC-NAME is the
1964 process name the comint buffer will get. After the comint buffer
1965 is created the `inferior-python-mode' is activated. When
1966 optional argument POP is non-nil the buffer is shown. When
1967 optional argument INTERNAL is non-nil this process is run on a
1968 buffer with a name that starts with a space, following the Emacs
1969 convention for temporary/internal buffers, and also makes sure
1970 the user is not queried for confirmation when the process is
1973 (let* ((proc-buffer-name
1974 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1975 (process-environment (python-shell-calculate-process-environment))
1976 (exec-path (python-shell-calculate-exec-path)))
1977 (when (not (comint-check-proc proc-buffer-name
))
1978 (let* ((cmdlist (split-string-and-unquote cmd
))
1979 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1980 (car cmdlist
) nil
(cdr cmdlist
)))
1981 (python-shell--parent-buffer (current-buffer))
1982 (process (get-buffer-process buffer
)))
1983 (with-current-buffer buffer
1984 (inferior-python-mode))
1985 (accept-process-output process
)
1986 (and pop
(pop-to-buffer buffer t
))
1987 (and internal
(set-process-query-on-exit-flag process nil
))))
1991 (defun run-python (cmd &optional dedicated show
)
1992 "Run an inferior Python process.
1993 Input and output via buffer named after
1994 `python-shell-buffer-name'. If there is a process already
1995 running in that buffer, just switch to it.
1997 With argument, allows you to define CMD so you can edit the
1998 command used to call the interpreter and define DEDICATED, so a
1999 dedicated process for the current buffer is open. When numeric
2000 prefix arg is other than 0 or 4 do not SHOW.
2002 Runs the hook `inferior-python-mode-hook' after
2003 `comint-mode-hook' is run. (Type \\[describe-mode] in the
2004 process buffer for a list of commands.)"
2006 (if current-prefix-arg
2008 (read-string "Run Python: " (python-shell-parse-command))
2009 (y-or-n-p "Make dedicated process? ")
2010 (= (prefix-numeric-value current-prefix-arg
) 4))
2011 (list (python-shell-parse-command) nil t
)))
2012 (python-shell-make-comint
2013 cmd
(python-shell-get-process-name dedicated
) show
)
2016 (defun run-python-internal ()
2017 "Run an inferior Internal Python process.
2018 Input and output via buffer named after
2019 `python-shell-internal-buffer-name' and what
2020 `python-shell-internal-get-process-name' returns.
2022 This new kind of shell is intended to be used for generic
2023 communication related to defined configurations; the main
2024 difference with global or dedicated shells is that these ones are
2025 attached to a configuration, not a buffer. This means that can
2026 be used for example to retrieve the sys.path and other stuff,
2027 without messing with user shells. Note that
2028 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
2029 are set to nil for these shells, so setup codes are not sent at
2031 (let ((python-shell-enable-font-lock nil
)
2032 (inferior-python-mode-hook nil
))
2034 (python-shell-make-comint
2035 (python-shell-parse-command)
2036 (python-shell-internal-get-process-name) nil t
))))
2038 (defun python-shell-get-buffer ()
2039 "Return inferior Python buffer for current buffer."
2040 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2041 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2042 (global-proc-name (python-shell-get-process-name nil
))
2043 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2044 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2045 (global-running (comint-check-proc global-proc-buffer-name
)))
2046 ;; Always prefer dedicated
2047 (or (and dedicated-running dedicated-proc-buffer-name
)
2048 (and global-running global-proc-buffer-name
))))
2050 (defun python-shell-get-process ()
2051 "Return inferior Python process for current buffer."
2052 (get-buffer-process (python-shell-get-buffer)))
2054 (defun python-shell-get-or-create-process ()
2055 "Get or create an inferior Python process for current buffer and return it."
2056 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
2057 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
2058 (global-proc-name (python-shell-get-process-name nil
))
2059 (global-proc-buffer-name (format "*%s*" global-proc-name
))
2060 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
2061 (global-running (comint-check-proc global-proc-buffer-name
))
2062 (current-prefix-arg 16))
2063 (when (and (not dedicated-running
) (not global-running
))
2064 (if (call-interactively 'run-python
)
2065 (setq dedicated-running t
)
2066 (setq global-running t
)))
2067 ;; Always prefer dedicated
2068 (get-buffer-process (if dedicated-running
2069 dedicated-proc-buffer-name
2070 global-proc-buffer-name
))))
2072 (defvar python-shell-internal-buffer nil
2073 "Current internal shell buffer for the current buffer.
2074 This is really not necessary at all for the code to work but it's
2075 there for compatibility with CEDET.")
2077 (defvar python-shell-internal-last-output nil
2078 "Last output captured by the internal shell.
2079 This is really not necessary at all for the code to work but it's
2080 there for compatibility with CEDET.")
2082 (defun python-shell-internal-get-or-create-process ()
2083 "Get or create an inferior Internal Python process."
2084 (let* ((proc-name (python-shell-internal-get-process-name))
2085 (proc-buffer-name (format " *%s*" proc-name
)))
2086 (when (not (process-live-p proc-name
))
2087 (run-python-internal)
2088 (setq python-shell-internal-buffer proc-buffer-name
)
2089 ;; XXX: Why is this `sit-for' needed?
2090 ;; `python-shell-make-comint' calls `accept-process-output'
2091 ;; already but it is not helping to get proper output on
2092 ;; 'gnu/linux when the internal shell process is not running and
2093 ;; a call to `python-shell-internal-send-string' is issued.
2095 (get-buffer-process proc-buffer-name
)))
2097 (define-obsolete-function-alias
2098 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
2100 (define-obsolete-variable-alias
2101 'python-buffer
'python-shell-internal-buffer
"24.3")
2103 (define-obsolete-variable-alias
2104 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
2106 (defun python-shell--save-temp-file (string)
2107 (let* ((temporary-file-directory
2108 (if (file-remote-p default-directory
)
2109 (concat (file-remote-p default-directory
) "/tmp")
2110 temporary-file-directory
))
2111 (temp-file-name (make-temp-file "py"))
2112 (coding-system-for-write 'utf-8
))
2113 (with-temp-file temp-file-name
2114 (insert "# -*- coding: utf-8 -*-\n") ;Not needed for Python-3.
2116 (delete-trailing-whitespace))
2119 (defun python-shell-send-string (string &optional process
)
2120 "Send STRING to inferior Python PROCESS."
2121 (interactive "sPython command: ")
2122 (let ((process (or process
(python-shell-get-or-create-process))))
2123 (if (string-match ".\n+." string
) ;Multiline.
2124 (let* ((temp-file-name (python-shell--save-temp-file string
)))
2125 (python-shell-send-file temp-file-name process temp-file-name t
))
2126 (comint-send-string process string
)
2127 (when (or (not (string-match "\n\\'" string
))
2128 (string-match "\n[ \t].*\n?\\'" string
))
2129 (comint-send-string process
"\n")))))
2131 (defvar python-shell-output-filter-in-progress nil
)
2132 (defvar python-shell-output-filter-buffer nil
)
2134 (defun python-shell-output-filter (string)
2135 "Filter used in `python-shell-send-string-no-output' to grab output.
2136 STRING is the output received to this point from the process.
2137 This filter saves received output from the process in
2138 `python-shell-output-filter-buffer' and stops receiving it after
2139 detecting a prompt at the end of the buffer."
2141 string
(ansi-color-filter-apply string
)
2142 python-shell-output-filter-buffer
2143 (concat python-shell-output-filter-buffer string
))
2145 ;; XXX: It seems on OSX an extra carriage return is attached
2146 ;; at the end of output, this handles that too.
2147 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
2148 python-shell-prompt-regexp
2149 python-shell-prompt-block-regexp
2150 python-shell-prompt-pdb-regexp
)
2151 python-shell-output-filter-buffer
)
2152 ;; Output ends when `python-shell-output-filter-buffer' contains
2153 ;; the prompt attached at the end of it.
2154 (setq python-shell-output-filter-in-progress nil
2155 python-shell-output-filter-buffer
2156 (substring python-shell-output-filter-buffer
2157 0 (match-beginning 0)))
2158 (when (and (> (length python-shell-prompt-output-regexp
) 0)
2159 (string-match (concat "^" python-shell-prompt-output-regexp
)
2160 python-shell-output-filter-buffer
))
2161 ;; Some shells, like iPython might append a prompt before the
2162 ;; output, clean that.
2163 (setq python-shell-output-filter-buffer
2164 (substring python-shell-output-filter-buffer
(match-end 0)))))
2167 (defun python-shell-send-string-no-output (string &optional process
)
2168 "Send STRING to PROCESS and inhibit output.
2170 (let ((process (or process
(python-shell-get-or-create-process)))
2171 (comint-preoutput-filter-functions
2172 '(python-shell-output-filter))
2173 (python-shell-output-filter-in-progress t
)
2177 (python-shell-send-string string process
)
2178 (while python-shell-output-filter-in-progress
2179 ;; `python-shell-output-filter' takes care of setting
2180 ;; `python-shell-output-filter-in-progress' to NIL after it
2181 ;; detects end of output.
2182 (accept-process-output process
))
2184 python-shell-output-filter-buffer
2185 (setq python-shell-output-filter-buffer nil
)))
2186 (with-current-buffer (process-buffer process
)
2187 (comint-interrupt-subjob)))))
2189 (defun python-shell-internal-send-string (string)
2190 "Send STRING to the Internal Python interpreter.
2191 Returns the output. See `python-shell-send-string-no-output'."
2192 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2193 ;; updated to support this new mode.
2194 (setq python-shell-internal-last-output
2195 (python-shell-send-string-no-output
2196 ;; Makes this function compatible with the old
2197 ;; python-send-receive. (At least for CEDET).
2198 (replace-regexp-in-string "_emacs_out +" "" string
)
2199 (python-shell-internal-get-or-create-process))))
2201 (define-obsolete-function-alias
2202 'python-send-receive
'python-shell-internal-send-string
"24.3")
2204 (define-obsolete-function-alias
2205 'python-send-string
'python-shell-internal-send-string
"24.3")
2207 (defvar python--use-fake-loc nil
2208 "If non-nil, use `compilation-fake-loc' to trace errors back to the buffer.
2209 If nil, regions of text are prepended by the corresponding number of empty
2210 lines and Python is told to output error messages referring to the whole
2213 (defun python-shell-buffer-substring (start end
&optional nomain
)
2214 "Send buffer substring from START to END formatted for shell.
2215 This is a wrapper over `buffer-substring' that takes care of
2216 different transformations for the code sent to be evaluated in
2218 1. When optional argument NOMAIN is non-nil everything under an
2219 \"if __name__ == '__main__'\" block will be removed.
2220 2. When a subregion of the buffer is sent, it takes care of
2221 appending extra empty lines so tracebacks are correct.
2222 3. Wraps indented regions under an \"if True:\" block so the
2223 interpreter evaluates them correctly."
2224 (let ((substring (buffer-substring-no-properties start end
))
2225 (fillstr (unless python--use-fake-loc
2226 (make-string (1- (line-number-at-pos start
)) ?
\n)))
2227 (toplevel-block-p (save-excursion
2229 (or (zerop (line-number-at-pos start
))
2231 (python-util-forward-comment 1)
2232 (zerop (current-indentation)))))))
2235 (if fillstr
(insert fillstr
))
2237 (goto-char (point-min))
2238 (unless python--use-fake-loc
2239 ;; python-shell--save-temp-file adds an extra coding line, which would
2240 ;; throw off the line-counts, so let's try to compensate here.
2241 (if (looking-at "[ \t]*[#\n]")
2242 (delete-region (point) (line-beginning-position 2))))
2243 (when (not toplevel-block-p
)
2245 (delete-region (point) (line-end-position)))
2247 (let* ((if-name-main-start-end
2250 (when (python-nav-if-name-main)
2252 (progn (python-nav-forward-sexp-safe)
2254 ;; Oh destructuring bind, how I miss you.
2255 (if-name-main-start (car if-name-main-start-end
))
2256 (if-name-main-end (cdr if-name-main-start-end
)))
2257 (when if-name-main-start-end
2258 (goto-char if-name-main-start
)
2259 (delete-region if-name-main-start if-name-main-end
)
2262 (- (line-number-at-pos if-name-main-end
)
2263 (line-number-at-pos if-name-main-start
)) ?
\n)))))
2264 (buffer-substring-no-properties (point-min) (point-max)))))
2266 (declare-function compilation-fake-loc
"compile"
2267 (marker file
&optional line col
))
2269 (defun python-shell-send-region (start end
&optional nomain
)
2270 "Send the region delimited by START and END to inferior Python process."
2272 (let* ((python--use-fake-loc
2273 (or python--use-fake-loc
(not buffer-file-name
)))
2274 (string (python-shell-buffer-substring start end nomain
))
2275 (process (python-shell-get-or-create-process))
2276 (_ (string-match "\\`\n*\\(.*\\)" string
)))
2277 (message "Sent: %s..." (match-string 1 string
))
2278 (let* ((temp-file-name (python-shell--save-temp-file string
))
2279 (file-name (or (buffer-file-name) temp-file-name
)))
2280 (python-shell-send-file file-name process temp-file-name t
)
2281 (unless python--use-fake-loc
2282 (with-current-buffer (process-buffer process
)
2283 (compilation-fake-loc (copy-marker start
) temp-file-name
2284 2)) ;; Not 1, because of the added coding line.
2287 (defun python-shell-send-buffer (&optional arg
)
2288 "Send the entire buffer to inferior Python process.
2289 With prefix ARG allow execution of code inside blocks delimited
2290 by \"if __name__== '__main__':\"."
2294 (python-shell-send-region (point-min) (point-max) (not arg
))))
2296 (defun python-shell-send-defun (arg)
2297 "Send the current defun to inferior Python process.
2298 When argument ARG is non-nil do not include decorators."
2301 (python-shell-send-region
2304 (while (and (or (python-nav-beginning-of-defun)
2305 (beginning-of-line 1))
2306 (> (current-indentation) 0)))
2308 (while (and (forward-line -
1)
2309 (looking-at (python-rx decorator
))))
2313 (or (python-nav-end-of-defun)
2317 (defun python-shell-send-file (file-name &optional process temp-file-name
2319 "Send FILE-NAME to inferior Python PROCESS.
2320 If TEMP-FILE-NAME is passed then that file is used for processing
2321 instead, while internally the shell will continue to use FILE-NAME.
2322 If DELETE is non-nil, delete the file afterwards."
2323 (interactive "fFile to send: ")
2324 (let* ((process (or process
(python-shell-get-or-create-process)))
2325 (temp-file-name (when temp-file-name
2327 (or (file-remote-p temp-file-name
'localname
)
2329 (file-name (or (when file-name
2331 (or (file-remote-p file-name
'localname
)
2334 (when (not file-name
)
2335 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2336 (python-shell-send-string
2338 (concat "__pyfile = open('''%s''');"
2339 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2340 "__pyfile.close()%s")
2341 (or temp-file-name file-name
) file-name
2342 (if delete
(format "; import os; os.remove('''%s''')"
2343 (or temp-file-name file-name
))
2347 (defun python-shell-switch-to-shell ()
2348 "Switch to inferior Python process buffer."
2350 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2352 (defun python-shell-send-setup-code ()
2353 "Send all setup code for shell.
2354 This function takes the list of setup code to send from the
2355 `python-shell-setup-codes' list."
2356 (let ((process (get-buffer-process (current-buffer))))
2357 (dolist (code python-shell-setup-codes
)
2359 (message "Sent %s" code
)
2360 (python-shell-send-string
2361 (symbol-value code
) process
)))))
2363 (add-hook 'inferior-python-mode-hook
2364 #'python-shell-send-setup-code
)
2367 ;;; Shell completion
2369 (defcustom python-shell-completion-setup-code
2373 def __COMPLETER_all_completions(text): []
2376 readline.set_completer(rlcompleter.Completer().complete)
2377 def __COMPLETER_all_completions(text):
2383 res = readline.get_completer()(text, i)
2386 completions.append(res)
2390 "Code used to setup completion in inferior Python processes."
2394 (defcustom python-shell-completion-string-code
2395 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2396 "Python code used to get a string of completions separated by semicolons."
2400 (defcustom python-shell-completion-module-string-code
""
2401 "Python code used to get completions separated by semicolons for imports.
2403 For IPython v0.11, add the following line to
2404 `python-shell-completion-setup-code':
2406 from IPython.core.completerlib import module_completion
2408 and use the following as the value of this variable:
2410 ';'.join(module_completion('''%s'''))\n"
2414 (defcustom python-shell-completion-pdb-string-code
2415 "';'.join(globals().keys() + locals().keys())"
2416 "Python code used to get completions separated by semicolons for [i]pdb."
2420 (defun python-shell-completion-get-completions (process line input
)
2421 "Do completion at point for PROCESS.
2422 LINE is used to detect the context on how to complete given INPUT."
2424 ;; Get last prompt of the inferior process buffer (this
2425 ;; intentionally avoids using `comint-last-prompt' because
2426 ;; of incompatibilities with Emacs 24.x).
2427 (with-current-buffer (process-buffer process
)
2429 (buffer-substring-no-properties
2430 (- (point) (length line
))
2432 (re-search-backward "^")
2433 (python-util-forward-comment)
2436 ;; Check whether a prompt matches a pdb string, an import
2437 ;; statement or just the standard prompt and use the
2438 ;; correct python-shell-completion-*-code string
2439 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2441 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2444 (length python-shell-completion-module-string-code
) 0)
2446 (concat "^" python-shell-prompt-regexp
) prompt
)
2447 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2450 (concat "^" python-shell-prompt-regexp
) prompt
)
2454 (pcase completion-context
2455 (`pdb python-shell-completion-pdb-string-code
)
2456 (`import python-shell-completion-module-string-code
)
2457 (`default python-shell-completion-string-code
)
2460 (if (eq completion-context
'import
)
2461 (replace-regexp-in-string "^[ \t]+" "" line
)
2463 (and completion-code
2464 (> (length input
) 0)
2465 (with-current-buffer (process-buffer process
)
2466 (let ((completions (python-shell-send-string-no-output
2467 (format completion-code input
) process
)))
2468 (and (> (length completions
) 2)
2469 (split-string completions
2470 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2472 (defun python-shell-completion-complete-at-point (&optional process
)
2473 "Perform completion at point in inferior Python.
2474 Optional argument PROCESS forces completions to be retrieved
2475 using that one instead of current buffer's process."
2476 (setq process
(or process
(get-buffer-process (current-buffer))))
2479 (with-syntax-table python-dotty-syntax-table
2480 (let* ((paren-depth (car (syntax-ppss)))
2481 (syntax-string "w_")
2482 (syntax-list (string-to-syntax syntax-string
)))
2483 ;; Stop scanning for the beginning of the completion
2484 ;; subject after the char before point matches a
2487 (car (syntax-after (1- (point)))) syntax-list
)
2488 (skip-syntax-backward syntax-string
)
2489 (when (or (equal (char-before) ?\
))
2490 (equal (char-before) ?
\"))
2493 ;; honor initial paren depth
2494 (> (car (syntax-ppss)) paren-depth
)
2495 (python-syntax-context 'string
))
2500 (completion-table-dynamic
2502 #'python-shell-completion-get-completions
2503 process
(buffer-substring-no-properties
2504 (line-beginning-position) end
))))))
2506 (defun python-shell-completion-complete-or-indent ()
2507 "Complete or indent depending on the context.
2508 If content before pointer is all whitespace, indent.
2509 If not try to complete."
2511 (if (string-match "^[[:space:]]*$"
2512 (buffer-substring (comint-line-beginning-position)
2514 (indent-for-tab-command)
2515 (completion-at-point)))
2518 ;;; PDB Track integration
2520 (defcustom python-pdbtrack-activate t
2521 "Non-nil makes Python shell enable pdbtracking."
2526 (defcustom python-pdbtrack-stacktrace-info-regexp
2527 "> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2528 "Regular expression matching stacktrace information.
2529 Used to extract the current line and module being inspected."
2534 (defvar python-pdbtrack-tracked-buffer nil
2535 "Variable containing the value of the current tracked buffer.
2536 Never set this variable directly, use
2537 `python-pdbtrack-set-tracked-buffer' instead.")
2539 (defvar python-pdbtrack-buffers-to-kill nil
2540 "List of buffers to be deleted after tracking finishes.")
2542 (defun python-pdbtrack-set-tracked-buffer (file-name)
2543 "Set the buffer for FILE-NAME as the tracked buffer.
2544 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2545 Returns the tracked buffer."
2546 (let ((file-buffer (get-file-buffer
2547 (concat (file-remote-p default-directory
)
2550 (setq python-pdbtrack-tracked-buffer file-buffer
)
2551 (setq file-buffer
(find-file-noselect file-name
))
2552 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2553 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2556 (defun python-pdbtrack-comint-output-filter-function (output)
2557 "Move overlay arrow to current pdb line in tracked buffer.
2558 Argument OUTPUT is a string with the output from the comint process."
2559 (when (and python-pdbtrack-activate
(not (string= output
"")))
2560 (let* ((full-output (ansi-color-filter-apply
2561 (buffer-substring comint-last-input-end
(point-max))))
2565 (insert full-output
)
2566 ;; When the debugger encounters a pdb.set_trace()
2567 ;; command, it prints a single stack frame. Sometimes
2568 ;; it prints a bit of extra information about the
2569 ;; arguments of the present function. When ipdb
2570 ;; encounters an exception, it prints the _entire_ stack
2571 ;; trace. To handle all of these cases, we want to find
2572 ;; the _last_ stack frame printed in the most recent
2573 ;; batch of output, then jump to the corresponding
2574 ;; file/line number.
2575 (goto-char (point-max))
2576 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t
)
2577 (setq line-number
(string-to-number
2578 (match-string-no-properties 2)))
2579 (match-string-no-properties 1)))))
2580 (if (and file-name line-number
)
2581 (let* ((tracked-buffer
2582 (python-pdbtrack-set-tracked-buffer file-name
))
2583 (shell-buffer (current-buffer))
2584 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2585 (tracked-buffer-line-pos))
2586 (with-current-buffer tracked-buffer
2587 (set (make-local-variable 'overlay-arrow-string
) "=>")
2588 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2589 (setq tracked-buffer-line-pos
(progn
2590 (goto-char (point-min))
2591 (forward-line (1- line-number
))
2593 (when tracked-buffer-window
2595 tracked-buffer-window tracked-buffer-line-pos
))
2596 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2597 (pop-to-buffer tracked-buffer
)
2598 (switch-to-buffer-other-window shell-buffer
))
2599 (when python-pdbtrack-tracked-buffer
2600 (with-current-buffer python-pdbtrack-tracked-buffer
2601 (set-marker overlay-arrow-position nil
))
2602 (mapc #'(lambda (buffer)
2603 (ignore-errors (kill-buffer buffer
)))
2604 python-pdbtrack-buffers-to-kill
)
2605 (setq python-pdbtrack-tracked-buffer nil
2606 python-pdbtrack-buffers-to-kill nil
)))))
2610 ;;; Symbol completion
2612 (defun python-completion-complete-at-point ()
2613 "Complete current symbol at point.
2614 For this to work as best as possible you should call
2615 `python-shell-send-buffer' from time to time so context in
2616 inferior Python process is updated properly."
2617 (let ((process (python-shell-get-process)))
2619 (error "Completion needs an inferior Python process running")
2620 (python-shell-completion-complete-at-point process
))))
2622 (add-to-list 'debug-ignored-errors
2623 "^Completion needs an inferior Python process running.")
2628 (defcustom python-fill-comment-function
'python-fill-comment
2629 "Function to fill comments.
2630 This is the function used by `python-fill-paragraph' to
2635 (defcustom python-fill-string-function
'python-fill-string
2636 "Function to fill strings.
2637 This is the function used by `python-fill-paragraph' to
2642 (defcustom python-fill-decorator-function
'python-fill-decorator
2643 "Function to fill decorators.
2644 This is the function used by `python-fill-paragraph' to
2649 (defcustom python-fill-paren-function
'python-fill-paren
2650 "Function to fill parens.
2651 This is the function used by `python-fill-paragraph' to
2656 (defcustom python-fill-docstring-style
'pep-257
2657 "Style used to fill docstrings.
2658 This affects `python-fill-string' behavior with regards to
2659 triple quotes positioning.
2661 Possible values are `django', `onetwo', `pep-257', `pep-257-nn',
2662 `symmetric', and nil. A value of nil won't care about quotes
2663 position and will treat docstrings a normal string, any other
2664 value may result in one of the following docstring styles:
2669 Process foo, return bar.
2673 Process foo, return bar.
2675 If processing fails throw ProcessingError.
2680 \"\"\"Process foo, return bar.\"\"\"
2683 Process foo, return bar.
2685 If processing fails throw ProcessingError.
2691 \"\"\"Process foo, return bar.\"\"\"
2693 \"\"\"Process foo, return bar.
2695 If processing fails throw ProcessingError.
2701 \"\"\"Process foo, return bar.\"\"\"
2703 \"\"\"Process foo, return bar.
2705 If processing fails throw ProcessingError.
2710 \"\"\"Process foo, return bar.\"\"\"
2713 Process foo, return bar.
2715 If processing fails throw ProcessingError.
2718 (const :tag
"Don't format docstrings" nil
)
2719 (const :tag
"Django's coding standards style." django
)
2720 (const :tag
"One newline and start and Two at end style." onetwo
)
2721 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2722 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2723 (const :tag
"Symmetric style." symmetric
))
2726 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2728 (defun python-fill-paragraph (&optional justify
)
2729 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2730 If any of the current line is in or at the end of a multi-line string,
2731 fill the string or the paragraph of it that point is in, preserving
2732 the string's indentation.
2733 Optional argument JUSTIFY defines if the paragraph should be justified."
2738 ((python-syntax-context 'comment
)
2739 (funcall python-fill-comment-function justify
))
2740 ;; Strings/Docstrings
2741 ((save-excursion (or (python-syntax-context 'string
)
2742 (equal (string-to-syntax "|")
2743 (syntax-after (point)))))
2744 (funcall python-fill-string-function justify
))
2746 ((equal (char-after (save-excursion
2747 (python-nav-beginning-of-statement))) ?
@)
2748 (funcall python-fill-decorator-function justify
))
2750 ((or (python-syntax-context 'paren
)
2751 (looking-at (python-rx open-paren
))
2753 (skip-syntax-forward "^(" (line-end-position))
2754 (looking-at (python-rx open-paren
))))
2755 (funcall python-fill-paren-function justify
))
2758 (defun python-fill-comment (&optional justify
)
2759 "Comment fill function for `python-fill-paragraph'.
2760 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2761 (fill-comment-paragraph justify
))
2763 (defun python-fill-string (&optional justify
)
2764 "String fill function for `python-fill-paragraph'.
2765 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2766 (let* ((str-start-pos
2769 (or (python-syntax-context 'string
)
2770 (and (equal (string-to-syntax "|")
2771 (syntax-after (point)))
2773 (num-quotes (python-syntax-count-quotes
2774 (char-after str-start-pos
) str-start-pos
))
2777 (goto-char (+ str-start-pos num-quotes
))
2778 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2779 (goto-char (point-max)))
2782 ;; Docstring styles may vary for oneliners and multi-liners.
2783 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2785 (pcase python-fill-docstring-style
2786 ;; delimiters-style is a cons cell with the form
2787 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2788 ;; is NIL means to not add any newlines for start or end
2789 ;; of docstring. See `python-fill-docstring-style' for a
2790 ;; graphic idea of each style.
2791 (`django
(cons 1 1))
2792 (`onetwo
(and multi-line-p
(cons 1 2)))
2793 (`pep-257
(and multi-line-p
(cons nil
2)))
2794 (`pep-257-nn
(and multi-line-p
(cons nil
1)))
2795 (`symmetric
(and multi-line-p
(cons 1 1)))))
2796 (docstring-p (save-excursion
2797 ;; Consider docstrings those strings which
2798 ;; start on a line by themselves.
2799 (python-nav-beginning-of-statement)
2800 (and (= (point) str-start-pos
))))
2801 (fill-paragraph-function))
2803 (narrow-to-region str-start-pos str-end-pos
)
2804 (fill-paragraph justify
))
2806 (when (and docstring-p python-fill-docstring-style
)
2807 ;; Add the number of newlines indicated by the selected style
2808 ;; at the start of the docstring.
2809 (goto-char (+ str-start-pos num-quotes
))
2810 (delete-region (point) (progn
2811 (skip-syntax-forward "> ")
2813 (and (car delimiters-style
)
2814 (or (newline (car delimiters-style
)) t
)
2815 ;; Indent only if a newline is added.
2816 (indent-according-to-mode))
2817 ;; Add the number of newlines indicated by the selected style
2818 ;; at the end of the docstring.
2819 (goto-char (if (not (= str-end-pos
(point-max)))
2820 (- str-end-pos num-quotes
)
2822 (delete-region (point) (progn
2823 (skip-syntax-backward "> ")
2825 (and (cdr delimiters-style
)
2826 ;; Add newlines only if string ends.
2827 (not (= str-end-pos
(point-max)))
2828 (or (newline (cdr delimiters-style
)) t
)
2829 ;; Again indent only if a newline is added.
2830 (indent-according-to-mode))))) t
)
2832 (defun python-fill-decorator (&optional _justify
)
2833 "Decorator fill function for `python-fill-paragraph'.
2834 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2837 (defun python-fill-paren (&optional justify
)
2838 "Paren fill function for `python-fill-paragraph'.
2839 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2841 (narrow-to-region (progn
2842 (while (python-syntax-context 'paren
)
2843 (goto-char (1- (point-marker))))
2845 (line-beginning-position))
2847 (when (not (python-syntax-context 'paren
))
2849 (when (not (python-syntax-context 'paren
))
2850 (skip-syntax-backward "^)")))
2851 (while (python-syntax-context 'paren
)
2852 (goto-char (1+ (point-marker))))
2854 (let ((paragraph-start "\f\\|[ \t]*$")
2855 (paragraph-separate ",")
2856 (fill-paragraph-function))
2857 (goto-char (point-min))
2858 (fill-paragraph justify
))
2861 (python-indent-line)
2862 (goto-char (line-end-position)))) t
)
2867 (defcustom python-skeleton-autoinsert nil
2868 "Non-nil means template skeletons will be automagically inserted.
2869 This happens when pressing \"if<SPACE>\", for example, to prompt for
2875 (define-obsolete-variable-alias
2876 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2878 (defvar python-skeleton-available
'()
2879 "Internal list of available skeletons.")
2881 (define-abbrev-table 'python-mode-skeleton-abbrev-table
()
2882 "Abbrev table for Python mode skeletons."
2884 ;; Allow / inside abbrevs.
2885 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2886 ;; Only expand in code.
2887 :enable-function
(lambda ()
2889 (not (python-syntax-comment-or-string-p))
2890 python-skeleton-autoinsert
)))
2892 (defmacro python-skeleton-define
(name doc
&rest skel
)
2893 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2894 The skeleton will be bound to python-skeleton-NAME and will
2895 be added to `python-mode-skeleton-abbrev-table'."
2896 (declare (indent 2))
2897 (let* ((name (symbol-name name
))
2898 (function-name (intern (concat "python-skeleton-" name
))))
2900 (define-abbrev python-mode-skeleton-abbrev-table
2901 ,name
"" ',function-name
:system t
)
2902 (setq python-skeleton-available
2903 (cons ',function-name python-skeleton-available
))
2904 (define-skeleton ,function-name
2906 (format "Insert %s statement." name
))
2909 (define-abbrev-table 'python-mode-abbrev-table
()
2910 "Abbrev table for Python mode."
2911 :parents
(list python-mode-skeleton-abbrev-table
))
2913 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2914 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2915 The skeleton will be bound to python-skeleton-NAME."
2916 (declare (indent 2))
2917 (let* ((name (symbol-name name
))
2918 (function-name (intern (concat "python-skeleton--" name
)))
2920 "Add '%s' clause? " name
)))
2923 `(< ,(format "%s:" name
) \n \n
2925 `(define-skeleton ,function-name
2927 (format "Auxiliary skeleton for %s statement." name
))
2929 (unless (y-or-n-p ,msg
)
2933 (python-define-auxiliary-skeleton else nil
)
2935 (python-define-auxiliary-skeleton except nil
)
2937 (python-define-auxiliary-skeleton finally nil
)
2939 (python-skeleton-define if nil
2943 ("other condition, %s: "
2947 '(python-skeleton--else) | ^
)
2949 (python-skeleton-define while nil
2953 '(python-skeleton--else) | ^
)
2955 (python-skeleton-define for nil
2959 '(python-skeleton--else) | ^
)
2961 (python-skeleton-define try nil
2967 "except " str
":" \n
2970 '(python-skeleton--except)
2971 '(python-skeleton--else)
2972 '(python-skeleton--finally) | ^
)
2974 (python-skeleton-define def nil
2976 "def " str
"(" ("Parameter, %s: "
2977 (unless (equal ?\
( (char-before)) ", ")
2979 "\"\"\"" -
"\"\"\"" \n
2982 (python-skeleton-define class nil
2984 "class " str
"(" ("Inheritance, %s: "
2985 (unless (equal ?\
( (char-before)) ", ")
2989 "\"\"\"" -
"\"\"\"" \n
2992 (defun python-skeleton-add-menu-items ()
2993 "Add menu items to Python->Skeletons menu."
2994 (let ((skeletons (sort python-skeleton-available
'string
<)))
2995 (dolist (skeleton skeletons
)
2997 nil
'("Python" "Skeletons")
2999 "Insert %s" (nth 2 (split-string (symbol-name skeleton
) "-")))
3004 (defcustom python-ffap-setup-code
3005 "def __FFAP_get_module_path(module):
3008 path = __import__(module).__file__
3009 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
3014 "Python code to get a module path."
3018 (defcustom python-ffap-string-code
3019 "__FFAP_get_module_path('''%s''')\n"
3020 "Python code used to get a string with the path of a module."
3024 (defun python-ffap-module-path (module)
3025 "Function for `ffap-alist' to return path for MODULE."
3027 (and (eq major-mode
'inferior-python-mode
)
3028 (get-buffer-process (current-buffer)))
3029 (python-shell-get-process))))
3033 (python-shell-send-string-no-output
3034 (format python-ffap-string-code module
) process
)))
3036 (substring-no-properties module-file
1 -
1))))))
3040 (eval-after-load "ffap"
3042 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
3043 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
3048 (defcustom python-check-command
3050 "Command used to check a Python file."
3054 (defcustom python-check-buffer-name
3055 "*Python check: %s*"
3056 "Buffer name used for check commands."
3060 (defvar python-check-custom-command nil
3063 (defun python-check (command)
3064 "Check a Python file (default current buffer's file).
3065 Runs COMMAND, a shell command, as if by `compile'.
3066 See `python-check-command' for the default."
3068 (list (read-string "Check command: "
3069 (or python-check-custom-command
3070 (concat python-check-command
" "
3071 (shell-quote-argument
3073 (let ((name (buffer-file-name)))
3075 (file-name-nondirectory name
)))
3077 (setq python-check-custom-command command
)
3078 (save-some-buffers (not compilation-ask-about-save
) nil
)
3079 (let ((process-environment (python-shell-calculate-process-environment))
3080 (exec-path (python-shell-calculate-exec-path)))
3081 (compilation-start command nil
3083 (format python-check-buffer-name command
)))))
3088 (defcustom python-eldoc-setup-code
3089 "def __PYDOC_get_help(obj):
3092 if hasattr(obj, 'startswith'):
3093 obj = eval(obj, globals())
3094 doc = inspect.getdoc(obj)
3095 if not doc and callable(obj):
3097 if inspect.isclass(obj) and hasattr(obj, '__init__'):
3098 target = obj.__init__
3104 args = inspect.formatargspec(
3105 *inspect.getargspec(target)
3108 doc = '{objtype} {name}{args}'.format(
3109 objtype=objtype, name=name, args=args
3112 doc = doc.splitlines()[0]
3119 "Python code to setup documentation retrieval."
3123 (defcustom python-eldoc-string-code
3124 "__PYDOC_get_help('''%s''')\n"
3125 "Python code used to get a string with the documentation of an object."
3129 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
3130 "Internal implementation to get documentation at point.
3131 If not FORCE-INPUT is passed then what `python-info-current-symbol'
3132 returns will be used. If not FORCE-PROCESS is passed what
3133 `python-shell-get-process' returns is used."
3134 (let ((process (or force-process
(python-shell-get-process))))
3136 (error "Eldoc needs an inferior Python process running")
3137 (let ((input (or force-input
3138 (python-info-current-symbol t
))))
3140 (python-shell-send-string-no-output
3141 (format python-eldoc-string-code input
)
3144 (defun python-eldoc-function ()
3145 "`eldoc-documentation-function' for Python.
3146 For this to work as best as possible you should call
3147 `python-shell-send-buffer' from time to time so context in
3148 inferior Python process is updated properly."
3149 (python-eldoc--get-doc-at-point))
3151 (defun python-eldoc-at-point (symbol)
3152 "Get help on SYMBOL using `help'.
3153 Interactively, prompt for symbol."
3155 (let ((symbol (python-info-current-symbol t
))
3156 (enable-recursive-minibuffers t
))
3157 (list (read-string (if symbol
3158 (format "Describe symbol (default %s): " symbol
)
3159 "Describe symbol: ")
3161 (message (python-eldoc--get-doc-at-point symbol
)))
3163 (add-to-list 'debug-ignored-errors
3164 "^Eldoc needs an inferior Python process running.")
3169 (defvar python-imenu-format-item-label-function
3170 'python-imenu-format-item-label
3171 "Imenu function used to format an item label.
3172 It must be a function with two arguments: TYPE and NAME.")
3174 (defvar python-imenu-format-parent-item-label-function
3175 'python-imenu-format-parent-item-label
3176 "Imenu function used to format a parent item label.
3177 It must be a function with two arguments: TYPE and NAME.")
3179 (defvar python-imenu-format-parent-item-jump-label-function
3180 'python-imenu-format-parent-item-jump-label
3181 "Imenu function used to format a parent jump item label.
3182 It must be a function with two arguments: TYPE and NAME.")
3184 (defun python-imenu-format-item-label (type name
)
3185 "Return Imenu label for single node using TYPE and NAME."
3186 (format "%s (%s)" name type
))
3188 (defun python-imenu-format-parent-item-label (type name
)
3189 "Return Imenu label for parent node using TYPE and NAME."
3190 (format "%s..." (python-imenu-format-item-label type name
)))
3192 (defun python-imenu-format-parent-item-jump-label (type _name
)
3193 "Return Imenu label for parent node jump using TYPE and NAME."
3194 (if (string= type
"class")
3195 "*class definition*"
3196 "*function definition*"))
3198 (defun python-imenu--put-parent (type name pos tree
)
3199 "Add the parent with TYPE, NAME and POS to TREE."
3201 (funcall python-imenu-format-item-label-function type name
))
3203 (funcall python-imenu-format-parent-item-jump-label-function type name
)))
3206 (cons label
(cons (cons jump-label pos
) tree
)))))
3208 (defun python-imenu--build-tree (&optional min-indent prev-indent tree
)
3209 "Recursively build the tree of nested definitions of a node.
3210 Arguments MIN-INDENT, PREV-INDENT and TREE are internal and should
3211 not be passed explicitly unless you know what you are doing."
3212 (setq min-indent
(or min-indent
0)
3213 prev-indent
(or prev-indent python-indent-offset
))
3214 (let* ((pos (python-nav-backward-defun))
3216 (name (when (and pos
(looking-at python-nav-beginning-of-defun-regexp
))
3217 (let ((split (split-string (match-string-no-properties 0))))
3218 (setq type
(car split
))
3221 (funcall python-imenu-format-item-label-function type name
)))
3222 (indent (current-indentation))
3223 (children-indent-limit (+ python-indent-offset min-indent
)))
3225 ;; Nothing found, probably near to bobp.
3227 ((<= indent min-indent
)
3228 ;; The current indentation points that this is a parent
3229 ;; node, add it to the tree and stop recursing.
3230 (python-imenu--put-parent type name pos tree
))
3232 (python-imenu--build-tree
3235 (if (<= indent children-indent-limit
)
3236 ;; This lies within the children indent offset range,
3237 ;; so it's a normal child of its parent (i.e., not
3238 ;; a child of a child).
3239 (cons (cons label pos
) tree
)
3240 ;; Oh no, a child of a child?! Fear not, we
3241 ;; know how to roll. We recursively parse these by
3242 ;; swapping prev-indent and min-indent plus adding this
3243 ;; newly found item to a fresh subtree. This works, I
3246 (python-imenu--build-tree
3247 prev-indent indent
(list (cons label pos
)))
3250 (defun python-imenu-create-index ()
3251 "Return tree Imenu alist for the current Python buffer.
3252 Change `python-imenu-format-item-label-function',
3253 `python-imenu-format-parent-item-label-function',
3254 `python-imenu-format-parent-item-jump-label-function' to
3255 customize how labels are formatted."
3256 (goto-char (point-max))
3259 (while (setq tree
(python-imenu--build-tree))
3260 (setq index
(cons tree index
)))
3263 (defun python-imenu-create-flat-index (&optional alist prefix
)
3264 "Return flat outline of the current Python buffer for Imenu.
3265 Optional argument ALIST is the tree to be flattened; when nil
3266 `python-imenu-build-index' is used with
3267 `python-imenu-format-parent-item-jump-label-function'
3268 `python-imenu-format-parent-item-label-function'
3269 `python-imenu-format-item-label-function' set to
3270 (lambda (type name) name)
3271 Optional argument PREFIX is used in recursive calls and should
3272 not be passed explicitly.
3279 (\"decorator\" . 173)
3282 (\"wrapped_f\" . 393))))
3288 (\"decorator\" . 173)
3289 (\"decorator.wrap\" . 353)
3290 (\"decorator.wrapped_f\" . 393))"
3291 ;; Inspired by imenu--flatten-index-alist removed in revno 21853.
3296 (let ((name (if prefix
3297 (concat prefix
"." (car item
))
3300 (cond ((or (numberp pos
) (markerp pos
))
3301 (list (cons name pos
)))
3304 (cons name
(cdar pos
))
3305 (python-imenu-create-flat-index (cddr item
) name
))))))
3307 (let* ((fn (lambda (_type name
) name
))
3308 (python-imenu-format-item-label-function fn
)
3309 (python-imenu-format-parent-item-label-function fn
)
3310 (python-imenu-format-parent-item-jump-label-function fn
))
3311 (python-imenu-create-index))))))
3316 (defun python-info-current-defun (&optional include-type
)
3317 "Return name of surrounding function with Python compatible dotty syntax.
3318 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
3319 This function can be used as the value of `add-log-current-defun-function'
3320 since it returns nil if point is not inside a defun."
3326 (starting-indentation (current-indentation))
3327 (starting-pos (point))
3332 (while (python-nav-beginning-of-defun 1)
3333 (when (save-match-data
3335 (or (not last-indent
)
3336 (< (current-indentation) last-indent
))
3340 ;; If this is the first run, we may add
3341 ;; the current defun at point.
3342 (setq first-run nil
)
3343 (goto-char starting-pos
)
3344 (python-nav-beginning-of-statement)
3345 (beginning-of-line 1)
3347 python-nav-beginning-of-defun-regexp
)))
3351 (+ (current-indentation)
3352 python-indent-offset
)))
3353 (if (< starting-indentation min-indent
)
3354 ;; If the starting indentation is not
3355 ;; within the min defun indent make the
3358 ;; Else go to the end of defun and add
3359 ;; up the current indentation to the
3361 (python-nav-end-of-defun)
3363 (if (>= (current-indentation) min-indent
)
3364 (1+ (current-indentation))
3366 (save-match-data (setq last-indent
(current-indentation)))
3367 (if (or (not include-type
) type
)
3368 (setq names
(cons (match-string-no-properties 1) names
))
3369 (let ((match (split-string (match-string-no-properties 0))))
3370 (setq type
(car match
))
3371 (setq names
(cons (cadr match
) names
)))))
3372 ;; Stop searching ASAP.
3373 (and (= (current-indentation) 0) (throw 'exit t
))))
3375 (concat (and type
(format "%s " type
))
3376 (mapconcat 'identity names
".")))))))
3378 (defun python-info-current-symbol (&optional replace-self
)
3379 "Return current symbol using dotty syntax.
3380 With optional argument REPLACE-SELF convert \"self\" to current
3383 (and (not (python-syntax-comment-or-string-p))
3384 (with-syntax-table python-dotty-syntax-table
3385 (let ((sym (symbol-at-point)))
3387 (substring-no-properties (symbol-name sym
))))))))
3389 (if (not replace-self
)
3391 (let ((current-defun (python-info-current-defun)))
3392 (if (not current-defun
)
3394 (replace-regexp-in-string
3395 (python-rx line-start word-start
"self" word-end ?.
)
3397 (mapconcat 'identity
3398 (butlast (split-string current-defun
"\\."))
3402 (defun python-info-statement-starts-block-p ()
3403 "Return non-nil if current statement opens a block."
3405 (python-nav-beginning-of-statement)
3406 (looking-at (python-rx block-start
))))
3408 (defun python-info-statement-ends-block-p ()
3409 "Return non-nil if point is at end of block."
3410 (let ((end-of-block-pos (save-excursion
3411 (python-nav-end-of-block)))
3412 (end-of-statement-pos (save-excursion
3413 (python-nav-end-of-statement))))
3414 (and end-of-block-pos end-of-statement-pos
3415 (= end-of-block-pos end-of-statement-pos
))))
3417 (defun python-info-beginning-of-statement-p ()
3418 "Return non-nil if point is at beginning of statement."
3419 (= (point) (save-excursion
3420 (python-nav-beginning-of-statement)
3423 (defun python-info-end-of-statement-p ()
3424 "Return non-nil if point is at end of statement."
3425 (= (point) (save-excursion
3426 (python-nav-end-of-statement)
3429 (defun python-info-beginning-of-block-p ()
3430 "Return non-nil if point is at beginning of block."
3431 (and (python-info-beginning-of-statement-p)
3432 (python-info-statement-starts-block-p)))
3434 (defun python-info-end-of-block-p ()
3435 "Return non-nil if point is at end of block."
3436 (and (python-info-end-of-statement-p)
3437 (python-info-statement-ends-block-p)))
3439 (defun python-info-closing-block ()
3440 "Return the point of the block the current line closes."
3441 (let ((closing-word (save-excursion
3442 (back-to-indentation)
3444 (indentation (current-indentation)))
3445 (when (member closing-word python-indent-dedenters
)
3448 (while (and (> (current-indentation) indentation
)
3450 (not (back-to-indentation))
3452 (back-to-indentation)
3454 ((not (equal indentation
(current-indentation))) nil
)
3455 ((string= closing-word
"elif")
3456 (when (member (current-word) '("if" "elif"))
3458 ((string= closing-word
"else")
3459 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3461 ((string= closing-word
"except")
3462 (when (member (current-word) '("try"))
3464 ((string= closing-word
"finally")
3465 (when (member (current-word) '("except" "else"))
3466 (point-marker))))))))
3468 (defun python-info-closing-block-message (&optional closing-block-point
)
3469 "Message the contents of the block the current line closes.
3470 With optional argument CLOSING-BLOCK-POINT use that instead of
3471 recalculating it calling `python-info-closing-block'."
3472 (let ((point (or closing-block-point
(python-info-closing-block))))
3476 (message "Closes %s" (save-excursion
3478 (back-to-indentation)
3480 (point) (line-end-position))))))))
3482 (defun python-info-line-ends-backslash-p (&optional line-number
)
3483 "Return non-nil if current line ends with backslash.
3484 With optional argument LINE-NUMBER, check that line instead."
3489 (python-util-goto-line line-number
))
3490 (while (and (not (eobp))
3491 (goto-char (line-end-position))
3492 (python-syntax-context 'paren
)
3493 (not (equal (char-before (point)) ?
\\)))
3495 (when (equal (char-before) ?
\\)
3498 (defun python-info-beginning-of-backslash (&optional line-number
)
3499 "Return the point where the backslashed line start.
3500 Optional argument LINE-NUMBER forces the line number to check against."
3505 (python-util-goto-line line-number
))
3506 (when (python-info-line-ends-backslash-p)
3507 (while (save-excursion
3508 (goto-char (line-beginning-position))
3509 (python-syntax-context 'paren
))
3511 (back-to-indentation)
3514 (defun python-info-continuation-line-p ()
3515 "Check if current line is continuation of another.
3516 When current line is continuation of another return the point
3517 where the continued line ends."
3521 (let* ((context-type (progn
3522 (back-to-indentation)
3523 (python-syntax-context-type)))
3524 (line-start (line-number-at-pos))
3525 (context-start (when context-type
3526 (python-syntax-context context-type
))))
3527 (cond ((equal context-type
'paren
)
3528 ;; Lines inside a paren are always a continuation line
3529 ;; (except the first one).
3530 (python-util-forward-comment -
1)
3532 ((member context-type
'(string comment
))
3533 ;; move forward an roll again
3534 (goto-char context-start
)
3535 (python-util-forward-comment)
3536 (python-info-continuation-line-p))
3538 ;; Not within a paren, string or comment, the only way
3539 ;; we are dealing with a continuation line is that
3540 ;; previous line contains a backslash, and this can
3541 ;; only be the previous line from current
3542 (back-to-indentation)
3543 (python-util-forward-comment -
1)
3544 (when (and (equal (1- line-start
) (line-number-at-pos))
3545 (python-info-line-ends-backslash-p))
3546 (point-marker))))))))
3548 (defun python-info-block-continuation-line-p ()
3549 "Return non-nil if current line is a continuation of a block."
3551 (when (python-info-continuation-line-p)
3553 (back-to-indentation)
3554 (when (looking-at (python-rx block-start
))
3557 (defun python-info-assignment-continuation-line-p ()
3558 "Check if current line is a continuation of an assignment.
3559 When current line is continuation of another with an assignment
3560 return the point of the first non-blank character after the
3563 (when (python-info-continuation-line-p)
3565 (back-to-indentation)
3566 (when (and (not (looking-at (python-rx block-start
)))
3567 (and (re-search-forward (python-rx not-simple-operator
3569 not-simple-operator
)
3570 (line-end-position) t
)
3571 (not (python-syntax-context-type))))
3572 (skip-syntax-forward "\s")
3575 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3576 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3577 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3579 (beginning-of-line 1)
3580 (looking-at python-nav-beginning-of-defun-regexp
))))
3582 (defun python-info-current-line-comment-p ()
3583 "Return non-nil if current line is a comment line."
3585 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_
)
3588 (defun python-info-current-line-empty-p ()
3589 "Return non-nil if current line is empty, ignoring whitespace."
3591 (beginning-of-line 1)
3593 (python-rx line-start
(* whitespace
)
3594 (group (* not-newline
))
3595 (* whitespace
) line-end
))
3596 (string-equal "" (match-string-no-properties 1))))
3599 ;;; Utility functions
3601 (defun python-util-goto-line (line-number)
3602 "Move point to LINE-NUMBER."
3603 (goto-char (point-min))
3604 (forward-line (1- line-number
)))
3606 ;; Stolen from org-mode
3607 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3608 "Clone local variables from FROM-BUFFER.
3609 Optional argument REGEXP selects variables to clone and defaults
3613 (and (symbolp (car pair
))
3614 (string-match (or regexp
"^python-")
3615 (symbol-name (car pair
)))
3616 (set (make-local-variable (car pair
))
3618 (buffer-local-variables from-buffer
)))
3620 (defun python-util-forward-comment (&optional direction
)
3621 "Python mode specific version of `forward-comment'.
3622 Optional argument DIRECTION defines the direction to move to."
3623 (let ((comment-start (python-syntax-context 'comment
))
3624 (factor (if (< (or direction
0) 0)
3628 (goto-char comment-start
))
3629 (forward-comment factor
)))
3631 (defun python-util-popn (lst n
)
3632 "Return LST first N elements.
3633 N should be an integer, when negative its opposite is used.
3634 When N is bigger than the length of LST, the list is
3636 (let* ((n (min (abs n
)))
3642 (setq acc
(cons (car lst
) acc
)
3648 (defun python-electric-pair-string-delimiter ()
3649 (when (and electric-pair-mode
3650 (memq last-command-event
'(?
\" ?
\'))
3652 (while (eq (char-before (- (point) count
)) last-command-event
)
3655 (eq (char-after) last-command-event
))
3656 (save-excursion (insert (make-string 2 last-command-event
)))))
3658 (defvar electric-indent-inhibit
)
3661 (define-derived-mode python-mode prog-mode
"Python"
3662 "Major mode for editing Python files.
3664 \\{python-mode-map}"
3665 (set (make-local-variable 'tab-width
) 8)
3666 (set (make-local-variable 'indent-tabs-mode
) nil
)
3668 (set (make-local-variable 'comment-start
) "# ")
3669 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3671 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3672 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3674 (set (make-local-variable 'forward-sexp-function
)
3675 'python-nav-forward-sexp
)
3677 (set (make-local-variable 'font-lock-defaults
)
3678 '(python-font-lock-keywords nil nil nil nil
))
3680 (set (make-local-variable 'syntax-propertize-function
)
3681 python-syntax-propertize-function
)
3683 (set (make-local-variable 'indent-line-function
)
3684 #'python-indent-line-function
)
3685 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3686 ;; Because indentation is not redundant, we cannot safely reindent code.
3687 (setq-local electric-indent-inhibit t
)
3688 (setq-local electric-indent-chars
(cons ?
: electric-indent-chars
))
3690 ;; Add """ ... """ pairing to electric-pair-mode.
3691 (add-hook 'post-self-insert-hook
3692 #'python-electric-pair-string-delimiter
'append t
)
3694 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3695 (set (make-local-variable 'fill-paragraph-function
)
3696 #'python-fill-paragraph
)
3698 (set (make-local-variable 'beginning-of-defun-function
)
3699 #'python-nav-beginning-of-defun
)
3700 (set (make-local-variable 'end-of-defun-function
)
3701 #'python-nav-end-of-defun
)
3703 (add-hook 'completion-at-point-functions
3704 #'python-completion-complete-at-point nil
'local
)
3706 (add-hook 'post-self-insert-hook
3707 #'python-indent-post-self-insert-function
'append
'local
)
3709 (set (make-local-variable 'imenu-create-index-function
)
3710 #'python-imenu-create-index
)
3712 (set (make-local-variable 'add-log-current-defun-function
)
3713 #'python-info-current-defun
)
3715 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3717 (set (make-local-variable 'skeleton-further-elements
)
3719 (< '(backward-delete-char-untabify (min python-indent-offset
3721 (^
'(- (1+ (current-indentation))))))
3723 (set (make-local-variable 'eldoc-documentation-function
)
3724 #'python-eldoc-function
)
3726 (add-to-list 'hs-special-modes-alist
3727 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3729 (python-nav-end-of-defun)) nil
))
3731 (set (make-local-variable 'mode-require-final-newline
) t
)
3733 (set (make-local-variable 'outline-regexp
)
3734 (python-rx (* space
) block-start
))
3735 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3736 (set (make-local-variable 'outline-level
)
3738 "`outline-level' function for Python mode."
3739 (1+ (/ (current-indentation) python-indent-offset
))))
3741 (python-skeleton-add-menu-items)
3743 (make-local-variable 'python-shell-internal-buffer
)
3745 (when python-indent-guess-indent-offset
3746 (python-indent-guess-indent-offset)))
3753 ;; indent-tabs-mode: nil
3756 ;;; python.el ends here