Un-indent after "pass" and "return" statements
[emacs.git] / lisp / progmodes / python.el
blob266d193cddae27f680129931e97ed4b27f12bb92
1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2013 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
7 ;; Version: 0.24.2
8 ;; Maintainer: FSF
9 ;; Created: Jul 2010
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/>.
27 ;;; Commentary:
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,
36 ;; Imenu.
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp' allows easy navigation
58 ;; between code blocks. If you prefer `cc-mode'-like `forward-sexp'
59 ;; movement, setting `forward-sexp-function' to nil is enough, You can
60 ;; 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
77 ;; iPython 0.11:
79 ;; (setq
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:
103 ;; (setq
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/
124 ;; virtualenv:
126 ;; (setq python-shell-process-environment
127 ;; (list
128 ;; (format "PATH=%s" (mapconcat
129 ;; 'identity
130 ;; (reverse
131 ;; (cons (getenv "PATH")
132 ;; '("/path/to/env/bin/")))
133 ;; ":"))
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 ;; dabbrev. If you have `dabbrev-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
170 ;; running.
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: This mode supports Imenu in its most basic form, letting it
181 ;; build the necessary alist via `imenu-default-create-index-function'
182 ;; by having set `imenu-extract-index-name-function' to
183 ;; `python-info-current-defun' and
184 ;; `imenu-prev-index-position-function' to
185 ;; `python-imenu-prev-index-position'.
187 ;; If you used python-mode.el you probably will miss auto-indentation
188 ;; when inserting newlines. To achieve the same behavior you have
189 ;; two options:
191 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
193 ;; 2) Add the following hook in your .emacs:
195 ;; (add-hook 'python-mode-hook
196 ;; #'(lambda ()
197 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
199 ;; I'd recommend the first one since you'll get the same behavior for
200 ;; all modes out-of-the-box.
202 ;;; Installation:
204 ;; Add this to your .emacs:
206 ;; (add-to-list 'load-path "/folder/containing/file")
207 ;; (require 'python)
209 ;;; TODO:
211 ;;; Code:
213 (require 'ansi-color)
214 (require 'comint)
216 (eval-when-compile
217 (require 'cl)
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")
225 ;;;###autoload
226 (add-to-list 'auto-mode-alist (cons (purecopy "\\.py\\'") 'python-mode))
227 ;;;###autoload
228 (add-to-list 'interpreter-mode-alist (cons (purecopy "python") 'python-mode))
230 (defgroup python nil
231 "Python Language's flying circus support for Emacs."
232 :group 'languages
233 :version "24.3"
234 :link '(emacs-commentary-link "python"))
237 ;;; Bindings
239 (defvar python-mode-map
240 (let ((map (make-sparse-keymap)))
241 ;; Movement
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)
246 ;; Indent specific
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)
251 (define-key map ":" 'python-indent-electric-colon)
252 ;; Skeletons
253 (define-key map "\C-c\C-tc" 'python-skeleton-class)
254 (define-key map "\C-c\C-td" 'python-skeleton-def)
255 (define-key map "\C-c\C-tf" 'python-skeleton-for)
256 (define-key map "\C-c\C-ti" 'python-skeleton-if)
257 (define-key map "\C-c\C-tt" 'python-skeleton-try)
258 (define-key map "\C-c\C-tw" 'python-skeleton-while)
259 ;; Shell interaction
260 (define-key map "\C-c\C-p" 'run-python)
261 (define-key map "\C-c\C-s" 'python-shell-send-string)
262 (define-key map "\C-c\C-r" 'python-shell-send-region)
263 (define-key map "\C-\M-x" 'python-shell-send-defun)
264 (define-key map "\C-c\C-c" 'python-shell-send-buffer)
265 (define-key map "\C-c\C-l" 'python-shell-send-file)
266 (define-key map "\C-c\C-z" 'python-shell-switch-to-shell)
267 ;; Some util commands
268 (define-key map "\C-c\C-v" 'python-check)
269 (define-key map "\C-c\C-f" 'python-eldoc-at-point)
270 ;; Utilities
271 (substitute-key-definition 'complete-symbol 'completion-at-point
272 map global-map)
273 (easy-menu-define python-menu map "Python Mode menu"
274 `("Python"
275 :help "Python-specific Features"
276 ["Shift region left" python-indent-shift-left :active mark-active
277 :help "Shift region left by a single indentation step"]
278 ["Shift region right" python-indent-shift-right :active mark-active
279 :help "Shift region right by a single indentation step"]
281 ["Start of def/class" beginning-of-defun
282 :help "Go to start of outermost definition around point"]
283 ["End of def/class" end-of-defun
284 :help "Go to end of definition around point"]
285 ["Mark def/class" mark-defun
286 :help "Mark outermost definition around point"]
287 ["Jump to def/class" imenu
288 :help "Jump to a class or function definition"]
289 "--"
290 ("Skeletons")
291 "---"
292 ["Start interpreter" run-python
293 :help "Run inferior Python process in a separate buffer"]
294 ["Switch to shell" python-shell-switch-to-shell
295 :help "Switch to running inferior Python process"]
296 ["Eval string" python-shell-send-string
297 :help "Eval string in inferior Python session"]
298 ["Eval buffer" python-shell-send-buffer
299 :help "Eval buffer in inferior Python session"]
300 ["Eval region" python-shell-send-region
301 :help "Eval region in inferior Python session"]
302 ["Eval defun" python-shell-send-defun
303 :help "Eval defun in inferior Python session"]
304 ["Eval file" python-shell-send-file
305 :help "Eval file in inferior Python session"]
306 ["Debugger" pdb :help "Run pdb under GUD"]
307 "----"
308 ["Check file" python-check
309 :help "Check file for errors"]
310 ["Help on symbol" python-eldoc-at-point
311 :help "Get help on symbol at point"]
312 ["Complete symbol" completion-at-point
313 :help "Complete symbol before point"]))
314 map)
315 "Keymap for `python-mode'.")
318 ;;; Python specialized rx
320 (eval-when-compile
321 (defconst python-rx-constituents
322 `((block-start . ,(rx symbol-start
323 (or "def" "class" "if" "elif" "else" "try"
324 "except" "finally" "for" "while" "with")
325 symbol-end))
326 (decorator . ,(rx line-start (* space) ?@ (any letter ?_)
327 (* (any word ?_))))
328 (defun . ,(rx symbol-start (or "def" "class") symbol-end))
329 (if-name-main . ,(rx line-start "if" (+ space) "__name__"
330 (+ space) "==" (+ space)
331 (any ?' ?\") "__main__" (any ?' ?\")
332 (* space) ?:))
333 (symbol-name . ,(rx (any letter ?_) (* (any word ?_))))
334 (open-paren . ,(rx (or "{" "[" "(")))
335 (close-paren . ,(rx (or "}" "]" ")")))
336 (simple-operator . ,(rx (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%)))
337 ;; FIXME: rx should support (not simple-operator).
338 (not-simple-operator . ,(rx
339 (not
340 (any ?+ ?- ?/ ?& ?^ ?~ ?| ?* ?< ?> ?= ?%))))
341 ;; FIXME: Use regexp-opt.
342 (operator . ,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
343 "=" "%" "**" "//" "<<" ">>" "<=" "!="
344 "==" ">=" "is" "not")))
345 ;; FIXME: Use regexp-opt.
346 (assignment-operator . ,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
347 ">>=" "<<=" "&=" "^=" "|=")))
348 (string-delimiter . ,(rx (and
349 ;; Match even number of backslashes.
350 (or (not (any ?\\ ?\' ?\")) point
351 ;; Quotes might be preceded by a escaped quote.
352 (and (or (not (any ?\\)) point) ?\\
353 (* ?\\ ?\\) (any ?\' ?\")))
354 (* ?\\ ?\\)
355 ;; Match single or triple quotes of any kind.
356 (group (or "\"" "\"\"\"" "'" "'''"))))))
357 "Additional Python specific sexps for `python-rx'")
359 (defmacro python-rx (&rest regexps)
360 "Python mode specialized rx macro.
361 This variant of `rx' supports common python named REGEXPS."
362 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
363 (cond ((null regexps)
364 (error "No regexp"))
365 ((cdr regexps)
366 (rx-to-string `(and ,@regexps) t))
368 (rx-to-string (car regexps) t))))))
371 ;;; Font-lock and syntax
373 (defun python-syntax-context (type &optional syntax-ppss)
374 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
375 TYPE can be `comment', `string' or `paren'. It returns the start
376 character address of the specified TYPE."
377 (let ((ppss (or syntax-ppss (syntax-ppss))))
378 (case type
379 (comment (and (nth 4 ppss) (nth 8 ppss)))
380 (string (and (not (nth 4 ppss)) (nth 8 ppss)))
381 (paren (nth 1 ppss))
382 (t nil))))
384 (defun python-syntax-context-type (&optional syntax-ppss)
385 "Return the context type using SYNTAX-PPSS.
386 The type returned can be `comment', `string' or `paren'."
387 (let ((ppss (or syntax-ppss (syntax-ppss))))
388 (cond
389 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
390 ((nth 1 ppss) 'paren))))
392 (defsubst python-syntax-comment-or-string-p ()
393 "Return non-nil if point is inside 'comment or 'string."
394 (nth 8 (syntax-ppss)))
396 (define-obsolete-function-alias
397 'python-info-ppss-context #'python-syntax-context "24.3")
399 (define-obsolete-function-alias
400 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
402 (define-obsolete-function-alias
403 'python-info-ppss-comment-or-string-p
404 #'python-syntax-comment-or-string-p "24.3")
406 (defvar python-font-lock-keywords
407 ;; Keywords
408 `(,(rx symbol-start
410 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
411 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
412 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
413 "try"
414 ;; Python 2:
415 "print" "exec"
416 ;; Python 3:
417 ;; False, None, and True are listed as keywords on the Python 3
418 ;; documentation, but since they also qualify as constants they are
419 ;; fontified like that in order to keep font-lock consistent between
420 ;; Python versions.
421 "nonlocal"
422 ;; Extra:
423 "self")
424 symbol-end)
425 ;; functions
426 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
427 (1 font-lock-function-name-face))
428 ;; classes
429 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
430 (1 font-lock-type-face))
431 ;; Constants
432 (,(rx symbol-start
434 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
435 ;; copyright, license, credits, quit and exit are added by the site
436 ;; module and they are not intended to be used in programs
437 "copyright" "credits" "exit" "license" "quit")
438 symbol-end) . font-lock-constant-face)
439 ;; Decorators.
440 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
441 (0+ "." (1+ (or word ?_)))))
442 (1 font-lock-type-face))
443 ;; Builtin Exceptions
444 (,(rx symbol-start
446 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
447 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
448 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
449 "ImportError" "ImportWarning" "IndexError" "KeyError"
450 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
451 "NotImplementedError" "OSError" "OverflowError"
452 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
453 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
454 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
455 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
456 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
457 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
458 ;; Python 2:
459 "StandardError"
460 ;; Python 3:
461 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
462 "TabError")
463 symbol-end) . font-lock-type-face)
464 ;; Builtins
465 (,(rx symbol-start
467 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
468 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
469 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
470 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
471 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
472 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
473 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
474 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
475 "__import__"
476 ;; Python 2:
477 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
478 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
479 "intern"
480 ;; Python 3:
481 "ascii" "bytearray" "bytes" "exec"
482 ;; Extra:
483 "__all__" "__doc__" "__name__" "__package__")
484 symbol-end) . font-lock-builtin-face)
485 ;; assignments
486 ;; support for a = b = c = 5
487 (,(lambda (limit)
488 (let ((re (python-rx (group (+ (any word ?. ?_)))
489 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
490 assignment-operator)))
491 (when (re-search-forward re limit t)
492 (while (and (python-syntax-context 'paren)
493 (re-search-forward re limit t)))
494 (if (and (not (python-syntax-context 'paren))
495 (not (equal (char-after (point-marker)) ?=)))
497 (set-match-data nil)))))
498 (1 font-lock-variable-name-face nil nil))
499 ;; support for a, b, c = (1, 2, 3)
500 (,(lambda (limit)
501 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
502 (* ?, (* space) (+ (any word ?. ?_)) (* space))
503 ?, (* space) (+ (any word ?. ?_)) (* space)
504 assignment-operator)))
505 (when (and (re-search-forward re limit t)
506 (goto-char (nth 3 (match-data))))
507 (while (and (python-syntax-context 'paren)
508 (re-search-forward re limit t))
509 (goto-char (nth 3 (match-data))))
510 (if (not (python-syntax-context 'paren))
512 (set-match-data nil)))))
513 (1 font-lock-variable-name-face nil nil))))
515 (defconst python-syntax-propertize-function
516 (syntax-propertize-rules
517 ((python-rx string-delimiter)
518 (0 (ignore (python-syntax-stringify))))))
520 (defsubst python-syntax-count-quotes (quote-char &optional point limit)
521 "Count number of quotes around point (max is 3).
522 QUOTE-CHAR is the quote char to count. Optional argument POINT is
523 the point where scan starts (defaults to current point) and LIMIT
524 is used to limit the scan."
525 (let ((i 0))
526 (while (and (< i 3)
527 (or (not limit) (< (+ point i) limit))
528 (eq (char-after (+ point i)) quote-char))
529 (incf i))
532 (defun python-syntax-stringify ()
533 "Put `syntax-table' property correctly on single/triple quotes."
534 (let* ((num-quotes (length (match-string-no-properties 1)))
535 (ppss (prog2
536 (backward-char num-quotes)
537 (syntax-ppss)
538 (forward-char num-quotes)))
539 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
540 (quote-starting-pos (- (point) num-quotes))
541 (quote-ending-pos (point))
542 (num-closing-quotes
543 (and string-start
544 (python-syntax-count-quotes
545 (char-before) string-start quote-starting-pos))))
546 (cond ((and string-start (= num-closing-quotes 0))
547 ;; This set of quotes doesn't match the string starting
548 ;; kind. Do nothing.
549 nil)
550 ((not string-start)
551 ;; This set of quotes delimit the start of a string.
552 (put-text-property quote-starting-pos (1+ quote-starting-pos)
553 'syntax-table (string-to-syntax "|")))
554 ((= num-quotes num-closing-quotes)
555 ;; This set of quotes delimit the end of a string.
556 (put-text-property (1- quote-ending-pos) quote-ending-pos
557 'syntax-table (string-to-syntax "|")))
558 ((> num-quotes num-closing-quotes)
559 ;; This may only happen whenever a triple quote is closing
560 ;; a single quoted string. Add string delimiter syntax to
561 ;; all three quotes.
562 (put-text-property quote-starting-pos quote-ending-pos
563 'syntax-table (string-to-syntax "|"))))))
565 (defvar python-mode-syntax-table
566 (let ((table (make-syntax-table)))
567 ;; Give punctuation syntax to ASCII that normally has symbol
568 ;; syntax or has word syntax and isn't a letter.
569 (let ((symbol (string-to-syntax "_"))
570 (sst (standard-syntax-table)))
571 (dotimes (i 128)
572 (unless (= i ?_)
573 (if (equal symbol (aref sst i))
574 (modify-syntax-entry i "." table)))))
575 (modify-syntax-entry ?$ "." table)
576 (modify-syntax-entry ?% "." table)
577 ;; exceptions
578 (modify-syntax-entry ?# "<" table)
579 (modify-syntax-entry ?\n ">" table)
580 (modify-syntax-entry ?' "\"" table)
581 (modify-syntax-entry ?` "$" table)
582 table)
583 "Syntax table for Python files.")
585 (defvar python-dotty-syntax-table
586 (let ((table (make-syntax-table python-mode-syntax-table)))
587 (modify-syntax-entry ?. "w" table)
588 (modify-syntax-entry ?_ "w" table)
589 table)
590 "Dotty syntax table for Python files.
591 It makes underscores and dots word constituent chars.")
594 ;;; Indentation
596 (defcustom python-indent-offset 4
597 "Default indentation offset for Python."
598 :group 'python
599 :type 'integer
600 :safe 'integerp)
602 (defcustom python-indent-guess-indent-offset t
603 "Non-nil tells Python mode to guess `python-indent-offset' value."
604 :type 'boolean
605 :group 'python
606 :safe 'booleanp)
608 (defcustom python-indent-trigger-commands
609 '(indent-for-tab-command yas-expand yas/expand)
610 "Commands that might trigger a `python-indent-line' call."
611 :type '(repeat symbol)
612 :group 'python)
614 (define-obsolete-variable-alias
615 'python-indent 'python-indent-offset "24.3")
617 (define-obsolete-variable-alias
618 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
620 (defvar python-indent-current-level 0
621 "Current indentation level `python-indent-line-function' is using.")
623 (defvar python-indent-levels '(0)
624 "Levels of indentation available for `python-indent-line-function'.")
626 (defvar python-indent-dedenters '("else" "elif" "except" "finally")
627 "List of words that should be dedented.
628 These make `python-indent-calculate-indentation' subtract the value of
629 `python-indent-offset'.")
631 (defvar python-indent-block-enders '("return" "pass")
632 "List of words that mark the end of a block.
633 These make `python-indent-calculate-indentation' subtract the
634 value of `python-indent-offset' when `python-indent-context' is
635 AFTER-LINE.")
637 (defun python-indent-guess-indent-offset ()
638 "Guess and set `python-indent-offset' for the current buffer."
639 (interactive)
640 (save-excursion
641 (save-restriction
642 (widen)
643 (goto-char (point-min))
644 (let ((block-end))
645 (while (and (not block-end)
646 (re-search-forward
647 (python-rx line-start block-start) nil t))
648 (when (and
649 (not (python-syntax-context-type))
650 (progn
651 (goto-char (line-end-position))
652 (python-util-forward-comment -1)
653 (if (equal (char-before) ?:)
655 (forward-line 1)
656 (when (python-info-block-continuation-line-p)
657 (while (and (python-info-continuation-line-p)
658 (not (eobp)))
659 (forward-line 1))
660 (python-util-forward-comment -1)
661 (when (equal (char-before) ?:)
662 t)))))
663 (setq block-end (point-marker))))
664 (let ((indentation
665 (when block-end
666 (goto-char block-end)
667 (python-util-forward-comment)
668 (current-indentation))))
669 (if indentation
670 (set (make-local-variable 'python-indent-offset) indentation)
671 (message "Can't guess python-indent-offset, using defaults: %s"
672 python-indent-offset)))))))
674 (defun python-indent-context ()
675 "Get information on indentation context.
676 Context information is returned with a cons with the form:
677 \(STATUS . START)
679 Where status can be any of the following symbols:
680 * inside-paren: If point in between (), {} or []
681 * inside-string: If point is inside a string
682 * after-backslash: Previous line ends in a backslash
683 * after-beginning-of-block: Point is after beginning of block
684 * after-line: Point is after normal line
685 * no-indent: Point is at beginning of buffer or other special case
686 START is the buffer position where the sexp starts."
687 (save-restriction
688 (widen)
689 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
690 (start))
691 (cons
692 (cond
693 ;; Beginning of buffer
694 ((save-excursion
695 (goto-char (line-beginning-position))
696 (bobp))
697 'no-indent)
698 ;; Inside string
699 ((setq start (python-syntax-context 'string ppss))
700 'inside-string)
701 ;; Inside a paren
702 ((setq start (python-syntax-context 'paren ppss))
703 'inside-paren)
704 ;; After backslash
705 ((setq start (when (not (or (python-syntax-context 'string ppss)
706 (python-syntax-context 'comment ppss)))
707 (let ((line-beg-pos (line-number-at-pos)))
708 (python-info-line-ends-backslash-p
709 (1- line-beg-pos)))))
710 'after-backslash)
711 ;; After beginning of block
712 ((setq start (save-excursion
713 (when (progn
714 (back-to-indentation)
715 (python-util-forward-comment -1)
716 (equal (char-before) ?:))
717 ;; Move to the first block start that's not in within
718 ;; a string, comment or paren and that's not a
719 ;; continuation line.
720 (while (and (re-search-backward
721 (python-rx block-start) nil t)
723 (python-syntax-context-type)
724 (python-info-continuation-line-p))))
725 (when (looking-at (python-rx block-start))
726 (point-marker)))))
727 'after-beginning-of-block)
728 ;; After normal line
729 ((setq start (save-excursion
730 (back-to-indentation)
731 (skip-chars-backward (rx (or whitespace ?\n)))
732 (python-nav-beginning-of-statement)
733 (point-marker)))
734 'after-line)
735 ;; Do not indent
736 (t 'no-indent))
737 start))))
739 (defun python-indent-calculate-indentation ()
740 "Calculate correct indentation offset for the current line."
741 (let* ((indentation-context (python-indent-context))
742 (context-status (car indentation-context))
743 (context-start (cdr indentation-context)))
744 (save-restriction
745 (widen)
746 (save-excursion
747 (case context-status
748 ('no-indent 0)
749 ;; When point is after beginning of block just add one level
750 ;; of indentation relative to the context-start
751 ('after-beginning-of-block
752 (goto-char context-start)
753 (+ (current-indentation) python-indent-offset))
754 ;; When after a simple line just use previous line
755 ;; indentation, in the case current line starts with a
756 ;; `python-indent-dedenters' de-indent one level.
757 ('after-line
759 (save-excursion
760 (goto-char context-start)
761 (current-indentation))
762 (if (or (save-excursion
763 (back-to-indentation)
764 (looking-at (regexp-opt python-indent-dedenters)))
765 (save-excursion
766 (python-util-forward-comment -1)
767 (python-nav-beginning-of-statement)
768 (member (current-word) python-indent-block-enders)))
769 python-indent-offset
770 0)))
771 ;; When inside of a string, do nothing. just use the current
772 ;; indentation. XXX: perhaps it would be a good idea to
773 ;; invoke standard text indentation here
774 ('inside-string
775 (goto-char context-start)
776 (current-indentation))
777 ;; After backslash we have several possibilities.
778 ('after-backslash
779 (cond
780 ;; Check if current line is a dot continuation. For this
781 ;; the current line must start with a dot and previous
782 ;; line must contain a dot too.
783 ((save-excursion
784 (back-to-indentation)
785 (when (looking-at "\\.")
786 ;; If after moving one line back point is inside a paren it
787 ;; needs to move back until it's not anymore
788 (while (prog2
789 (forward-line -1)
790 (and (not (bobp))
791 (python-syntax-context 'paren))))
792 (goto-char (line-end-position))
793 (while (and (re-search-backward
794 "\\." (line-beginning-position) t)
795 (python-syntax-context-type)))
796 (if (and (looking-at "\\.")
797 (not (python-syntax-context-type)))
798 ;; The indentation is the same column of the
799 ;; first matching dot that's not inside a
800 ;; comment, a string or a paren
801 (current-column)
802 ;; No dot found on previous line, just add another
803 ;; indentation level.
804 (+ (current-indentation) python-indent-offset)))))
805 ;; Check if prev line is a block continuation
806 ((let ((block-continuation-start
807 (python-info-block-continuation-line-p)))
808 (when block-continuation-start
809 ;; If block-continuation-start is set jump to that
810 ;; marker and use first column after the block start
811 ;; as indentation value.
812 (goto-char block-continuation-start)
813 (re-search-forward
814 (python-rx block-start (* space))
815 (line-end-position) t)
816 (current-column))))
817 ;; Check if current line is an assignment continuation
818 ((let ((assignment-continuation-start
819 (python-info-assignment-continuation-line-p)))
820 (when assignment-continuation-start
821 ;; If assignment-continuation is set jump to that
822 ;; marker and use first column after the assignment
823 ;; operator as indentation value.
824 (goto-char assignment-continuation-start)
825 (current-column))))
827 (forward-line -1)
828 (goto-char (python-info-beginning-of-backslash))
829 (if (save-excursion
830 (and
831 (forward-line -1)
832 (goto-char
833 (or (python-info-beginning-of-backslash) (point)))
834 (python-info-line-ends-backslash-p)))
835 ;; The two previous lines ended in a backslash so we must
836 ;; respect previous line indentation.
837 (current-indentation)
838 ;; What happens here is that we are dealing with the second
839 ;; line of a backslash continuation, in that case we just going
840 ;; to add one indentation level.
841 (+ (current-indentation) python-indent-offset)))))
842 ;; When inside a paren there's a need to handle nesting
843 ;; correctly
844 ('inside-paren
845 (cond
846 ;; If current line closes the outermost open paren use the
847 ;; current indentation of the context-start line.
848 ((save-excursion
849 (skip-syntax-forward "\s" (line-end-position))
850 (when (and (looking-at (regexp-opt '(")" "]" "}")))
851 (progn
852 (forward-char 1)
853 (not (python-syntax-context 'paren))))
854 (goto-char context-start)
855 (current-indentation))))
856 ;; If open paren is contained on a line by itself add another
857 ;; indentation level, else look for the first word after the
858 ;; opening paren and use it's column position as indentation
859 ;; level.
860 ((let* ((content-starts-in-newline)
861 (indent
862 (save-excursion
863 (if (setq content-starts-in-newline
864 (progn
865 (goto-char context-start)
866 (forward-char)
867 (save-restriction
868 (narrow-to-region
869 (line-beginning-position)
870 (line-end-position))
871 (python-util-forward-comment))
872 (looking-at "$")))
873 (+ (current-indentation) python-indent-offset)
874 (current-column)))))
875 ;; Adjustments
876 (cond
877 ;; If current line closes a nested open paren de-indent one
878 ;; level.
879 ((progn
880 (back-to-indentation)
881 (looking-at (regexp-opt '(")" "]" "}"))))
882 (- indent python-indent-offset))
883 ;; If the line of the opening paren that wraps the current
884 ;; line starts a block add another level of indentation to
885 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
886 ((save-excursion
887 (when (and content-starts-in-newline
888 (progn
889 (goto-char context-start)
890 (back-to-indentation)
891 (looking-at (python-rx block-start))))
892 (+ indent python-indent-offset))))
893 (t indent)))))))))))
895 (defun python-indent-calculate-levels ()
896 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
897 (let* ((indentation (python-indent-calculate-indentation))
898 (remainder (% indentation python-indent-offset))
899 (steps (/ (- indentation remainder) python-indent-offset)))
900 (setq python-indent-levels (list 0))
901 (dotimes (step steps)
902 (push (* python-indent-offset (1+ step)) python-indent-levels))
903 (when (not (eq 0 remainder))
904 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
905 (setq python-indent-levels (nreverse python-indent-levels))
906 (setq python-indent-current-level (1- (length python-indent-levels)))))
908 (defun python-indent-toggle-levels ()
909 "Toggle `python-indent-current-level' over `python-indent-levels'."
910 (setq python-indent-current-level (1- python-indent-current-level))
911 (when (< python-indent-current-level 0)
912 (setq python-indent-current-level (1- (length python-indent-levels)))))
914 (defun python-indent-line (&optional force-toggle)
915 "Internal implementation of `python-indent-line-function'.
916 Uses the offset calculated in
917 `python-indent-calculate-indentation' and available levels
918 indicated by the variable `python-indent-levels' to set the
919 current indentation.
921 When the variable `last-command' is equal to one of the symbols
922 inside `python-indent-trigger-commands' or FORCE-TOGGLE is
923 non-nil it cycles levels indicated in the variable
924 `python-indent-levels' by setting the current level in the
925 variable `python-indent-current-level'.
927 When the variable `last-command' is not equal to one of the
928 symbols inside `python-indent-trigger-commands' and FORCE-TOGGLE
929 is nil it calculates possible indentation levels and saves it in
930 the variable `python-indent-levels'. Afterwards it sets the
931 variable `python-indent-current-level' correctly so offset is
932 equal to (`nth' `python-indent-current-level'
933 `python-indent-levels')"
935 (and (or (and (memq this-command python-indent-trigger-commands)
936 (eq last-command this-command))
937 force-toggle)
938 (not (equal python-indent-levels '(0)))
939 (or (python-indent-toggle-levels) t))
940 (python-indent-calculate-levels))
941 (let* ((starting-pos (point-marker))
942 (indent-ending-position
943 (+ (line-beginning-position) (current-indentation)))
944 (follow-indentation-p
945 (or (bolp)
946 (and (<= (line-beginning-position) starting-pos)
947 (>= indent-ending-position starting-pos))))
948 (next-indent (nth python-indent-current-level python-indent-levels)))
949 (unless (= next-indent (current-indentation))
950 (beginning-of-line)
951 (delete-horizontal-space)
952 (indent-to next-indent)
953 (goto-char starting-pos))
954 (and follow-indentation-p (back-to-indentation)))
955 (python-info-closing-block-message))
957 (defun python-indent-line-function ()
958 "`indent-line-function' for Python mode.
959 See `python-indent-line' for details."
960 (python-indent-line))
962 (defun python-indent-dedent-line ()
963 "De-indent current line."
964 (interactive "*")
965 (when (and (not (python-syntax-comment-or-string-p))
966 (<= (point-marker) (save-excursion
967 (back-to-indentation)
968 (point-marker)))
969 (> (current-column) 0))
970 (python-indent-line t)
973 (defun python-indent-dedent-line-backspace (arg)
974 "De-indent current line.
975 Argument ARG is passed to `backward-delete-char-untabify' when
976 point is not in between the indentation."
977 (interactive "*p")
978 (when (not (python-indent-dedent-line))
979 (backward-delete-char-untabify arg)))
980 (put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
982 (defun python-indent-region (start end)
983 "Indent a python region automagically.
985 Called from a program, START and END specify the region to indent."
986 (let ((deactivate-mark nil))
987 (save-excursion
988 (goto-char end)
989 (setq end (point-marker))
990 (goto-char start)
991 (or (bolp) (forward-line 1))
992 (while (< (point) end)
993 (or (and (bolp) (eolp))
994 (let (word)
995 (forward-line -1)
996 (back-to-indentation)
997 (setq word (current-word))
998 (forward-line 1)
999 (when (and word
1000 ;; Don't mess with strings, unless it's the
1001 ;; enclosing set of quotes.
1002 (or (not (python-syntax-context 'string))
1004 (syntax-after
1005 (+ (1- (point))
1006 (current-indentation)
1007 (python-syntax-count-quotes (char-after) (point))))
1008 (string-to-syntax "|"))))
1009 (beginning-of-line)
1010 (delete-horizontal-space)
1011 (indent-to (python-indent-calculate-indentation)))))
1012 (forward-line 1))
1013 (move-marker end nil))))
1015 (defun python-indent-shift-left (start end &optional count)
1016 "Shift lines contained in region START END by COUNT columns to the left.
1017 COUNT defaults to `python-indent-offset'. If region isn't
1018 active, the current line is shifted. The shifted region includes
1019 the lines in which START and END lie. An error is signaled if
1020 any lines in the region are indented less than COUNT columns."
1021 (interactive
1022 (if mark-active
1023 (list (region-beginning) (region-end) current-prefix-arg)
1024 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1025 (if count
1026 (setq count (prefix-numeric-value count))
1027 (setq count python-indent-offset))
1028 (when (> count 0)
1029 (let ((deactivate-mark nil))
1030 (save-excursion
1031 (goto-char start)
1032 (while (< (point) end)
1033 (if (and (< (current-indentation) count)
1034 (not (looking-at "[ \t]*$")))
1035 (error "Can't shift all lines enough"))
1036 (forward-line))
1037 (indent-rigidly start end (- count))))))
1039 (add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1041 (defun python-indent-shift-right (start end &optional count)
1042 "Shift lines contained in region START END by COUNT columns to the left.
1043 COUNT defaults to `python-indent-offset'. If region isn't
1044 active, the current line is shifted. The shifted region includes
1045 the lines in which START and END lie."
1046 (interactive
1047 (if mark-active
1048 (list (region-beginning) (region-end) current-prefix-arg)
1049 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1050 (let ((deactivate-mark nil))
1051 (if count
1052 (setq count (prefix-numeric-value count))
1053 (setq count python-indent-offset))
1054 (indent-rigidly start end count)))
1056 (defun python-indent-electric-colon (arg)
1057 "Insert a colon and maybe de-indent the current line.
1058 With numeric ARG, just insert that many colons. With
1059 \\[universal-argument], just insert a single colon."
1060 (interactive "*P")
1061 (self-insert-command (if (not (integerp arg)) 1 arg))
1062 (when (and (not arg)
1063 (eolp)
1064 (not (equal ?: (char-after (- (point-marker) 2))))
1065 (not (python-syntax-comment-or-string-p)))
1066 (let ((indentation (current-indentation))
1067 (calculated-indentation (python-indent-calculate-indentation)))
1068 (python-info-closing-block-message)
1069 (when (> indentation calculated-indentation)
1070 (save-excursion
1071 (indent-line-to calculated-indentation)
1072 (when (not (python-info-closing-block-message))
1073 (indent-line-to indentation)))))))
1074 (put 'python-indent-electric-colon 'delete-selection t)
1076 (defun python-indent-post-self-insert-function ()
1077 "Adjust closing paren line indentation after a char is added.
1078 This function is intended to be added to the
1079 `post-self-insert-hook.' If a line renders a paren alone, after
1080 adding a char before it, the line will be re-indented
1081 automatically if needed."
1082 (when (and (eq (char-before) last-command-event)
1083 (not (bolp))
1084 (memq (char-after) '(?\) ?\] ?\})))
1085 (save-excursion
1086 (goto-char (line-beginning-position))
1087 ;; If after going to the beginning of line the point
1088 ;; is still inside a paren it's ok to do the trick
1089 (when (python-syntax-context 'paren)
1090 (let ((indentation (python-indent-calculate-indentation)))
1091 (when (< (current-indentation) indentation)
1092 (indent-line-to indentation)))))))
1095 ;;; Navigation
1097 (defvar python-nav-beginning-of-defun-regexp
1098 (python-rx line-start (* space) defun (+ space) (group symbol-name))
1099 "Regexp matching class or function definition.
1100 The name of the defun should be grouped so it can be retrieved
1101 via `match-string'.")
1103 (defun python-nav--beginning-of-defun (&optional arg)
1104 "Internal implementation of `python-nav-beginning-of-defun'.
1105 With positive ARG search backwards, else search forwards."
1106 (when (or (null arg) (= arg 0)) (setq arg 1))
1107 (let* ((re-search-fn (if (> arg 0)
1108 #'re-search-backward
1109 #'re-search-forward))
1110 (line-beg-pos (line-beginning-position))
1111 (line-content-start (+ line-beg-pos (current-indentation)))
1112 (pos (point-marker))
1113 (beg-indentation
1114 (and (> arg 0)
1115 (save-excursion
1116 (while (and
1117 (not (python-info-looking-at-beginning-of-defun))
1118 (python-nav-backward-block)))
1119 (or (and (python-info-looking-at-beginning-of-defun)
1120 (+ (current-indentation) python-indent-offset))
1121 0))))
1122 (found
1123 (progn
1124 (when (and (< arg 0)
1125 (python-info-looking-at-beginning-of-defun))
1126 (end-of-line 1))
1127 (while (and (funcall re-search-fn
1128 python-nav-beginning-of-defun-regexp nil t)
1129 (or (python-syntax-context-type)
1130 ;; Handle nested defuns when moving
1131 ;; backwards by checking indentation.
1132 (and (> arg 0)
1133 (not (= (current-indentation) 0))
1134 (>= (current-indentation) beg-indentation)))))
1135 (and (python-info-looking-at-beginning-of-defun)
1136 (or (not (= (line-number-at-pos pos)
1137 (line-number-at-pos)))
1138 (and (>= (point) line-beg-pos)
1139 (<= (point) line-content-start)
1140 (> pos line-content-start)))))))
1141 (if found
1142 (or (beginning-of-line 1) t)
1143 (and (goto-char pos) nil))))
1145 (defun python-nav-beginning-of-defun (&optional arg)
1146 "Move point to `beginning-of-defun'.
1147 With positive ARG search backwards else search forward. When ARG
1148 is nil or 0 defaults to 1. When searching backwards nested
1149 defuns are handled with care depending on current point
1150 position. Return non-nil if point is moved to
1151 `beginning-of-defun'."
1152 (when (or (null arg) (= arg 0)) (setq arg 1))
1153 (let ((found))
1154 (cond ((and (eq this-command 'mark-defun)
1155 (python-info-looking-at-beginning-of-defun)))
1157 (dotimes (i (if (> arg 0) arg (- arg)))
1158 (when (and (python-nav--beginning-of-defun arg)
1159 (not found))
1160 (setq found t)))))
1161 found))
1163 (defun python-nav-end-of-defun ()
1164 "Move point to the end of def or class.
1165 Returns nil if point is not in a def or class."
1166 (interactive)
1167 (let ((beg-defun-indent)
1168 (beg-pos (point)))
1169 (when (or (python-info-looking-at-beginning-of-defun)
1170 (python-nav-beginning-of-defun 1)
1171 (python-nav-beginning-of-defun -1))
1172 (setq beg-defun-indent (current-indentation))
1173 (while (progn
1174 (python-nav-end-of-statement)
1175 (python-util-forward-comment 1)
1176 (and (> (current-indentation) beg-defun-indent)
1177 (not (eobp)))))
1178 (python-util-forward-comment -1)
1179 (forward-line 1)
1180 ;; Ensure point moves forward.
1181 (and (> beg-pos (point)) (goto-char beg-pos)))))
1183 (defun python-nav-beginning-of-statement ()
1184 "Move to start of current statement."
1185 (interactive "^")
1186 (while (and (or (back-to-indentation) t)
1187 (not (bobp))
1188 (when (or
1189 (save-excursion
1190 (forward-line -1)
1191 (python-info-line-ends-backslash-p))
1192 (python-syntax-context 'string)
1193 (python-syntax-context 'paren))
1194 (forward-line -1))))
1195 (point-marker))
1197 (defun python-nav-end-of-statement (&optional noend)
1198 "Move to end of current statement.
1199 Optional argument NOEND is internal and makes the logic to not
1200 jump to the end of line when moving forward searching for the end
1201 of the statement."
1202 (interactive "^")
1203 (let (string-start bs-pos)
1204 (while (and (or noend (goto-char (line-end-position)))
1205 (not (eobp))
1206 (cond ((setq string-start (python-syntax-context 'string))
1207 (goto-char string-start)
1208 (if (python-syntax-context 'paren)
1209 ;; Ended up inside a paren, roll again.
1210 (python-nav-end-of-statement t)
1211 ;; This is not inside a paren, move to the
1212 ;; end of this string.
1213 (goto-char (+ (point)
1214 (python-syntax-count-quotes
1215 (char-after (point)) (point))))
1216 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
1217 (goto-char (point-max)))))
1218 ((python-syntax-context 'paren)
1219 ;; The statement won't end before we've escaped
1220 ;; at least one level of parenthesis.
1221 (condition-case err
1222 (goto-char (scan-lists (point) 1 -1))
1223 (scan-error (goto-char (nth 3 err)))))
1224 ((setq bs-pos (python-info-line-ends-backslash-p))
1225 (goto-char bs-pos)
1226 (forward-line 1))))))
1227 (point-marker))
1229 (defun python-nav-backward-statement (&optional arg)
1230 "Move backward to previous statement.
1231 With ARG, repeat. See `python-nav-forward-statement'."
1232 (interactive "^p")
1233 (or arg (setq arg 1))
1234 (python-nav-forward-statement (- arg)))
1236 (defun python-nav-forward-statement (&optional arg)
1237 "Move forward to next statement.
1238 With ARG, repeat. With negative argument, move ARG times
1239 backward to previous statement."
1240 (interactive "^p")
1241 (or arg (setq arg 1))
1242 (while (> arg 0)
1243 (python-nav-end-of-statement)
1244 (python-util-forward-comment)
1245 (python-nav-beginning-of-statement)
1246 (setq arg (1- arg)))
1247 (while (< arg 0)
1248 (python-nav-beginning-of-statement)
1249 (python-util-forward-comment -1)
1250 (python-nav-beginning-of-statement)
1251 (setq arg (1+ arg))))
1253 (defun python-nav-beginning-of-block ()
1254 "Move to start of current block."
1255 (interactive "^")
1256 (let ((starting-pos (point))
1257 (block-regexp (python-rx
1258 line-start (* whitespace) block-start)))
1259 (if (progn
1260 (python-nav-beginning-of-statement)
1261 (looking-at (python-rx block-start)))
1262 (point-marker)
1263 ;; Go to first line beginning a statement
1264 (while (and (not (bobp))
1265 (or (and (python-nav-beginning-of-statement) nil)
1266 (python-info-current-line-comment-p)
1267 (python-info-current-line-empty-p)))
1268 (forward-line -1))
1269 (let ((block-matching-indent
1270 (- (current-indentation) python-indent-offset)))
1271 (while
1272 (and (python-nav-backward-block)
1273 (> (current-indentation) block-matching-indent)))
1274 (if (and (looking-at (python-rx block-start))
1275 (= (current-indentation) block-matching-indent))
1276 (point-marker)
1277 (and (goto-char starting-pos) nil))))))
1279 (defun python-nav-end-of-block ()
1280 "Move to end of current block."
1281 (interactive "^")
1282 (when (python-nav-beginning-of-block)
1283 (let ((block-indentation (current-indentation)))
1284 (python-nav-end-of-statement)
1285 (while (and (forward-line 1)
1286 (not (eobp))
1287 (or (and (> (current-indentation) block-indentation)
1288 (or (python-nav-end-of-statement) t))
1289 (python-info-current-line-comment-p)
1290 (python-info-current-line-empty-p))))
1291 (python-util-forward-comment -1)
1292 (point-marker))))
1294 (defun python-nav-backward-block (&optional arg)
1295 "Move backward to previous block of code.
1296 With ARG, repeat. See `python-nav-forward-block'."
1297 (interactive "^p")
1298 (or arg (setq arg 1))
1299 (python-nav-forward-block (- arg)))
1301 (defun python-nav-forward-block (&optional arg)
1302 "Move forward to next block of code.
1303 With ARG, repeat. With negative argument, move ARG times
1304 backward to previous block."
1305 (interactive "^p")
1306 (or arg (setq arg 1))
1307 (let ((block-start-regexp
1308 (python-rx line-start (* whitespace) block-start))
1309 (starting-pos (point)))
1310 (while (> arg 0)
1311 (python-nav-end-of-statement)
1312 (while (and
1313 (re-search-forward block-start-regexp nil t)
1314 (python-syntax-context-type)))
1315 (setq arg (1- arg)))
1316 (while (< arg 0)
1317 (python-nav-beginning-of-statement)
1318 (while (and
1319 (re-search-backward block-start-regexp nil t)
1320 (python-syntax-context-type)))
1321 (setq arg (1+ arg)))
1322 (python-nav-beginning-of-statement)
1323 (if (not (looking-at (python-rx block-start)))
1324 (and (goto-char starting-pos) nil)
1325 (and (not (= (point) starting-pos)) (point-marker)))))
1327 (defun python-nav-lisp-forward-sexp-safe (&optional arg)
1328 "Safe version of standard `forward-sexp'.
1329 When ARG > 0 move forward, else if ARG is < 0."
1330 (or arg (setq arg 1))
1331 (let ((forward-sexp-function)
1332 (paren-regexp
1333 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1334 (search-fn
1335 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1336 (condition-case nil
1337 (forward-sexp arg)
1338 (error
1339 (while (and (funcall search-fn paren-regexp nil t)
1340 (python-syntax-context 'paren)))))))
1342 (defun python-nav--forward-sexp (&optional dir)
1343 "Move to forward sexp.
1344 With positive Optional argument DIR direction move forward, else
1345 backwards."
1346 (setq dir (or dir 1))
1347 (unless (= dir 0)
1348 (let* ((forward-p (if (> dir 0)
1349 (and (setq dir 1) t)
1350 (and (setq dir -1) nil)))
1351 (re-search-fn (if forward-p
1352 're-search-forward
1353 're-search-backward))
1354 (context-type (python-syntax-context-type)))
1355 (cond
1356 ((memq context-type '(string comment))
1357 ;; Inside of a string, get out of it.
1358 (let ((forward-sexp-function))
1359 (forward-sexp dir)))
1360 ((or (eq context-type 'paren)
1361 (and forward-p (looking-at (python-rx open-paren)))
1362 (and (not forward-p)
1363 (eq (syntax-class (syntax-after (1- (point))))
1364 (car (string-to-syntax ")")))))
1365 ;; Inside a paren or looking at it, lisp knows what to do.
1366 (python-nav-lisp-forward-sexp-safe dir))
1368 ;; This part handles the lispy feel of
1369 ;; `python-nav-forward-sexp'. Knowing everything about the
1370 ;; current context and the context of the next sexp tries to
1371 ;; follow the lisp sexp motion commands in a symmetric manner.
1372 (let* ((context
1373 (cond
1374 ((python-info-beginning-of-block-p) 'block-start)
1375 ((python-info-end-of-block-p) 'block-end)
1376 ((python-info-beginning-of-statement-p) 'statement-start)
1377 ((python-info-end-of-statement-p) 'statement-end)))
1378 (next-sexp-pos
1379 (save-excursion
1380 (python-nav-lisp-forward-sexp-safe dir)
1381 (point)))
1382 (next-sexp-context
1383 (save-excursion
1384 (goto-char next-sexp-pos)
1385 (cond
1386 ((python-info-beginning-of-block-p) 'block-start)
1387 ((python-info-end-of-block-p) 'block-end)
1388 ((python-info-beginning-of-statement-p) 'statement-start)
1389 ((python-info-end-of-statement-p) 'statement-end)
1390 ((python-info-statement-starts-block-p) 'starts-block)
1391 ((python-info-statement-ends-block-p) 'ends-block)))))
1392 (if forward-p
1393 (cond ((and (not (eobp))
1394 (python-info-current-line-empty-p))
1395 (python-util-forward-comment dir)
1396 (python-nav--forward-sexp dir))
1397 ((eq context 'block-start)
1398 (python-nav-end-of-block))
1399 ((eq context 'statement-start)
1400 (python-nav-end-of-statement))
1401 ((and (memq context '(statement-end block-end))
1402 (eq next-sexp-context 'ends-block))
1403 (goto-char next-sexp-pos)
1404 (python-nav-end-of-block))
1405 ((and (memq context '(statement-end block-end))
1406 (eq next-sexp-context 'starts-block))
1407 (goto-char next-sexp-pos)
1408 (python-nav-end-of-block))
1409 ((memq context '(statement-end block-end))
1410 (goto-char next-sexp-pos)
1411 (python-nav-end-of-statement))
1412 (t (goto-char next-sexp-pos)))
1413 (cond ((and (not (bobp))
1414 (python-info-current-line-empty-p))
1415 (python-util-forward-comment dir)
1416 (python-nav--forward-sexp dir))
1417 ((eq context 'block-end)
1418 (python-nav-beginning-of-block))
1419 ((eq context 'statement-end)
1420 (python-nav-beginning-of-statement))
1421 ((and (memq context '(statement-start block-start))
1422 (eq next-sexp-context 'starts-block))
1423 (goto-char next-sexp-pos)
1424 (python-nav-beginning-of-block))
1425 ((and (memq context '(statement-start block-start))
1426 (eq next-sexp-context 'ends-block))
1427 (goto-char next-sexp-pos)
1428 (python-nav-beginning-of-block))
1429 ((memq context '(statement-start block-start))
1430 (goto-char next-sexp-pos)
1431 (python-nav-beginning-of-statement))
1432 (t (goto-char next-sexp-pos))))))))))
1434 (defun python-nav--backward-sexp ()
1435 "Move to backward sexp."
1436 (python-nav--forward-sexp -1))
1438 (defun python-nav-forward-sexp (&optional arg)
1439 "Move forward across one block of code.
1440 With ARG, do it that many times. Negative arg -N means
1441 move backward N times."
1442 (interactive "^p")
1443 (or arg (setq arg 1))
1444 (while (> arg 0)
1445 (python-nav--forward-sexp)
1446 (setq arg (1- arg)))
1447 (while (< arg 0)
1448 (python-nav--backward-sexp)
1449 (setq arg (1+ arg))))
1451 (defun python-nav--up-list (&optional dir)
1452 "Internal implementation of `python-nav-up-list'.
1453 DIR is always 1 or -1 and comes sanitized from
1454 `python-nav-up-list' calls."
1455 (let ((context (python-syntax-context-type))
1456 (forward-p (> dir 0)))
1457 (cond
1458 ((memq context '(string comment)))
1459 ((eq context 'paren)
1460 (let ((forward-sexp-function))
1461 (up-list dir)))
1462 ((and forward-p (python-info-end-of-block-p))
1463 (let ((parent-end-pos
1464 (save-excursion
1465 (let ((indentation (and
1466 (python-nav-beginning-of-block)
1467 (current-indentation))))
1468 (while (and indentation
1469 (> indentation 0)
1470 (>= (current-indentation) indentation)
1471 (python-nav-backward-block)))
1472 (python-nav-end-of-block)))))
1473 (and (> (or parent-end-pos (point)) (point))
1474 (goto-char parent-end-pos))))
1475 (forward-p (python-nav-end-of-block))
1476 ((and (not forward-p)
1477 (> (current-indentation) 0)
1478 (python-info-beginning-of-block-p))
1479 (let ((prev-block-pos
1480 (save-excursion
1481 (let ((indentation (current-indentation)))
1482 (while (and (python-nav-backward-block)
1483 (>= (current-indentation) indentation))))
1484 (point))))
1485 (and (> (point) prev-block-pos)
1486 (goto-char prev-block-pos))))
1487 ((not forward-p) (python-nav-beginning-of-block)))))
1489 (defun python-nav-up-list (&optional arg)
1490 "Move forward out of one level of parentheses (or blocks).
1491 With ARG, do this that many times.
1492 A negative argument means move backward but still to a less deep spot.
1493 This command assumes point is not in a string or comment."
1494 (interactive "^p")
1495 (or arg (setq arg 1))
1496 (while (> arg 0)
1497 (python-nav--up-list 1)
1498 (setq arg (1- arg)))
1499 (while (< arg 0)
1500 (python-nav--up-list -1)
1501 (setq arg (1+ arg))))
1503 (defun python-nav-backward-up-list (&optional arg)
1504 "Move backward out of one level of parentheses (or blocks).
1505 With ARG, do this that many times.
1506 A negative argument means move backward but still to a less deep spot.
1507 This command assumes point is not in a string or comment."
1508 (interactive "^p")
1509 (or arg (setq arg 1))
1510 (python-nav-up-list (- arg)))
1513 ;;; Shell integration
1515 (defcustom python-shell-buffer-name "Python"
1516 "Default buffer name for Python interpreter."
1517 :type 'string
1518 :group 'python
1519 :safe 'stringp)
1521 (defcustom python-shell-interpreter "python"
1522 "Default Python interpreter for shell."
1523 :type 'string
1524 :group 'python)
1526 (defcustom python-shell-internal-buffer-name "Python Internal"
1527 "Default buffer name for the Internal Python interpreter."
1528 :type 'string
1529 :group 'python
1530 :safe 'stringp)
1532 (defcustom python-shell-interpreter-args "-i"
1533 "Default arguments for the Python interpreter."
1534 :type 'string
1535 :group 'python)
1537 (defcustom python-shell-prompt-regexp ">>> "
1538 "Regular Expression matching top\-level input prompt of python shell.
1539 It should not contain a caret (^) at the beginning."
1540 :type 'string
1541 :group 'python
1542 :safe 'stringp)
1544 (defcustom python-shell-prompt-block-regexp "[.][.][.] "
1545 "Regular Expression matching block input prompt of python shell.
1546 It should not contain a caret (^) at the beginning."
1547 :type 'string
1548 :group 'python
1549 :safe 'stringp)
1551 (defcustom python-shell-prompt-output-regexp ""
1552 "Regular Expression matching output prompt of python shell.
1553 It should not contain a caret (^) at the beginning."
1554 :type 'string
1555 :group 'python
1556 :safe 'stringp)
1558 (defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
1559 "Regular Expression matching pdb input prompt of python shell.
1560 It should not contain a caret (^) at the beginning."
1561 :type 'string
1562 :group 'python
1563 :safe 'stringp)
1565 (defcustom python-shell-enable-font-lock t
1566 "Should syntax highlighting be enabled in the python shell buffer?
1567 Restart the python shell after changing this variable for it to take effect."
1568 :type 'boolean
1569 :group 'python
1570 :safe 'booleanp)
1572 (defcustom python-shell-process-environment nil
1573 "List of environment variables for Python shell.
1574 This variable follows the same rules as `process-environment'
1575 since it merges with it before the process creation routines are
1576 called. When this variable is nil, the Python shell is run with
1577 the default `process-environment'."
1578 :type '(repeat string)
1579 :group 'python
1580 :safe 'listp)
1582 (defcustom python-shell-extra-pythonpaths nil
1583 "List of extra pythonpaths for Python shell.
1584 The values of this variable are added to the existing value of
1585 PYTHONPATH in the `process-environment' variable."
1586 :type '(repeat string)
1587 :group 'python
1588 :safe 'listp)
1590 (defcustom python-shell-exec-path nil
1591 "List of path to search for binaries.
1592 This variable follows the same rules as `exec-path' since it
1593 merges with it before the process creation routines are called.
1594 When this variable is nil, the Python shell is run with the
1595 default `exec-path'."
1596 :type '(repeat string)
1597 :group 'python
1598 :safe 'listp)
1600 (defcustom python-shell-virtualenv-path nil
1601 "Path to virtualenv root.
1602 This variable, when set to a string, makes the values stored in
1603 `python-shell-process-environment' and `python-shell-exec-path'
1604 to be modified properly so shells are started with the specified
1605 virtualenv."
1606 :type 'string
1607 :group 'python
1608 :safe 'stringp)
1610 (defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1611 python-ffap-setup-code
1612 python-eldoc-setup-code)
1613 "List of code run by `python-shell-send-setup-codes'."
1614 :type '(repeat symbol)
1615 :group 'python
1616 :safe 'listp)
1618 (defcustom python-shell-compilation-regexp-alist
1619 `((,(rx line-start (1+ (any " \t")) "File \""
1620 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1621 "\", line " (group (1+ digit)))
1622 1 2)
1623 (,(rx " in file " (group (1+ not-newline)) " on line "
1624 (group (1+ digit)))
1625 1 2)
1626 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1627 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1628 1 2))
1629 "`compilation-error-regexp-alist' for inferior Python."
1630 :type '(alist string)
1631 :group 'python)
1633 (defun python-shell-get-process-name (dedicated)
1634 "Calculate the appropriate process name for inferior Python process.
1635 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1636 returns a string with the form
1637 `python-shell-buffer-name'[variable `buffer-file-name'] else
1638 returns the value of `python-shell-buffer-name'."
1639 (let ((process-name
1640 (if (and dedicated
1641 buffer-file-name)
1642 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1643 (format "%s" python-shell-buffer-name))))
1644 process-name))
1646 (defun python-shell-internal-get-process-name ()
1647 "Calculate the appropriate process name for Internal Python process.
1648 The name is calculated from `python-shell-global-buffer-name' and
1649 a hash of all relevant global shell settings in order to ensure
1650 uniqueness for different types of configurations."
1651 (format "%s [%s]"
1652 python-shell-internal-buffer-name
1653 (md5
1654 (concat
1655 (python-shell-parse-command)
1656 python-shell-prompt-regexp
1657 python-shell-prompt-block-regexp
1658 python-shell-prompt-output-regexp
1659 (mapconcat #'symbol-value python-shell-setup-codes "")
1660 (mapconcat #'identity python-shell-process-environment "")
1661 (mapconcat #'identity python-shell-extra-pythonpaths "")
1662 (mapconcat #'identity python-shell-exec-path "")
1663 (or python-shell-virtualenv-path "")
1664 (mapconcat #'identity python-shell-exec-path "")))))
1666 (defun python-shell-parse-command ()
1667 "Calculate the string used to execute the inferior Python process."
1668 (let ((process-environment (python-shell-calculate-process-environment))
1669 (exec-path (python-shell-calculate-exec-path)))
1670 (format "%s %s"
1671 (executable-find python-shell-interpreter)
1672 python-shell-interpreter-args)))
1674 (defun python-shell-calculate-process-environment ()
1675 "Calculate process environment given `python-shell-virtualenv-path'."
1676 (let ((process-environment (append
1677 python-shell-process-environment
1678 process-environment nil))
1679 (virtualenv (if python-shell-virtualenv-path
1680 (directory-file-name python-shell-virtualenv-path)
1681 nil)))
1682 (when python-shell-extra-pythonpaths
1683 (setenv "PYTHONPATH"
1684 (format "%s%s%s"
1685 (mapconcat 'identity
1686 python-shell-extra-pythonpaths
1687 path-separator)
1688 path-separator
1689 (or (getenv "PYTHONPATH") ""))))
1690 (if (not virtualenv)
1691 process-environment
1692 (setenv "PYTHONHOME" nil)
1693 (setenv "PATH" (format "%s/bin%s%s"
1694 virtualenv path-separator
1695 (or (getenv "PATH") "")))
1696 (setenv "VIRTUAL_ENV" virtualenv))
1697 process-environment))
1699 (defun python-shell-calculate-exec-path ()
1700 "Calculate exec path given `python-shell-virtualenv-path'."
1701 (let ((path (append python-shell-exec-path
1702 exec-path nil)))
1703 (if (not python-shell-virtualenv-path)
1704 path
1705 (cons (format "%s/bin"
1706 (directory-file-name python-shell-virtualenv-path))
1707 path))))
1709 (defun python-comint-output-filter-function (output)
1710 "Hook run after content is put into comint buffer.
1711 OUTPUT is a string with the contents of the buffer."
1712 (ansi-color-filter-apply output))
1714 (defvar python-shell--parent-buffer nil)
1716 (defvar python-shell-output-syntax-table
1717 (let ((table (make-syntax-table python-dotty-syntax-table)))
1718 (modify-syntax-entry ?\' "." table)
1719 (modify-syntax-entry ?\" "." table)
1720 (modify-syntax-entry ?\( "." table)
1721 (modify-syntax-entry ?\[ "." table)
1722 (modify-syntax-entry ?\{ "." table)
1723 (modify-syntax-entry ?\) "." table)
1724 (modify-syntax-entry ?\] "." table)
1725 (modify-syntax-entry ?\} "." table)
1726 table)
1727 "Syntax table for shell output.
1728 It makes parens and quotes be treated as punctuation chars.")
1730 (define-derived-mode inferior-python-mode comint-mode "Inferior Python"
1731 "Major mode for Python inferior process.
1732 Runs a Python interpreter as a subprocess of Emacs, with Python
1733 I/O through an Emacs buffer. Variables
1734 `python-shell-interpreter' and `python-shell-interpreter-args'
1735 controls which Python interpreter is run. Variables
1736 `python-shell-prompt-regexp',
1737 `python-shell-prompt-output-regexp',
1738 `python-shell-prompt-block-regexp',
1739 `python-shell-enable-font-lock',
1740 `python-shell-completion-setup-code',
1741 `python-shell-completion-string-code',
1742 `python-shell-completion-module-string-code',
1743 `python-eldoc-setup-code', `python-eldoc-string-code',
1744 `python-ffap-setup-code' and `python-ffap-string-code' can
1745 customize this mode for different Python interpreters.
1747 You can also add additional setup code to be run at
1748 initialization of the interpreter via `python-shell-setup-codes'
1749 variable.
1751 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1752 (and python-shell--parent-buffer
1753 (python-util-clone-local-variables python-shell--parent-buffer))
1754 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1755 python-shell-prompt-regexp
1756 python-shell-prompt-block-regexp
1757 python-shell-prompt-pdb-regexp))
1758 (setq mode-line-process '(":%s"))
1759 (make-local-variable 'comint-output-filter-functions)
1760 (add-hook 'comint-output-filter-functions
1761 'python-comint-output-filter-function)
1762 (add-hook 'comint-output-filter-functions
1763 'python-pdbtrack-comint-output-filter-function)
1764 (set (make-local-variable 'compilation-error-regexp-alist)
1765 python-shell-compilation-regexp-alist)
1766 (define-key inferior-python-mode-map [remap complete-symbol]
1767 'completion-at-point)
1768 (add-hook 'completion-at-point-functions
1769 'python-shell-completion-complete-at-point nil 'local)
1770 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1771 'python-shell-completion-complete-at-point)
1772 (define-key inferior-python-mode-map "\t"
1773 'python-shell-completion-complete-or-indent)
1774 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1775 (make-local-variable 'python-pdbtrack-tracked-buffer)
1776 (make-local-variable 'python-shell-internal-last-output)
1777 (when python-shell-enable-font-lock
1778 (set-syntax-table python-mode-syntax-table)
1779 (set (make-local-variable 'font-lock-defaults)
1780 '(python-font-lock-keywords nil nil nil nil))
1781 (set (make-local-variable 'syntax-propertize-function)
1782 (eval
1783 ;; XXX: Unfortunately eval is needed here to make use of the
1784 ;; dynamic value of `comint-prompt-regexp'.
1785 `(syntax-propertize-rules
1786 (,comint-prompt-regexp
1787 (0 (ignore
1788 (put-text-property
1789 comint-last-input-start end 'syntax-table
1790 python-shell-output-syntax-table)
1791 ;; XXX: This might look weird, but it is the easiest
1792 ;; way to ensure font lock gets cleaned up before the
1793 ;; current prompt, which is needed for unclosed
1794 ;; strings to not mess up with current input.
1795 (font-lock-unfontify-region comint-last-input-start end))))
1796 (,(python-rx string-delimiter)
1797 (0 (ignore
1798 (and (not (eq (get-text-property start 'field) 'output))
1799 (python-syntax-stringify)))))))))
1800 (compilation-shell-minor-mode 1))
1802 (defun python-shell-make-comint (cmd proc-name &optional pop internal)
1803 "Create a python shell comint buffer.
1804 CMD is the python command to be executed and PROC-NAME is the
1805 process name the comint buffer will get. After the comint buffer
1806 is created the `inferior-python-mode' is activated. When
1807 optional argument POP is non-nil the buffer is shown. When
1808 optional argument INTERNAL is non-nil this process is run on a
1809 buffer with a name that starts with a space, following the Emacs
1810 convention for temporary/internal buffers, and also makes sure
1811 the user is not queried for confirmation when the process is
1812 killed."
1813 (save-excursion
1814 (let* ((proc-buffer-name
1815 (format (if (not internal) "*%s*" " *%s*") proc-name))
1816 (process-environment (python-shell-calculate-process-environment))
1817 (exec-path (python-shell-calculate-exec-path)))
1818 (when (not (comint-check-proc proc-buffer-name))
1819 (let* ((cmdlist (split-string-and-unquote cmd))
1820 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1821 (car cmdlist) nil (cdr cmdlist)))
1822 (python-shell--parent-buffer (current-buffer))
1823 (process (get-buffer-process buffer)))
1824 (with-current-buffer buffer
1825 (inferior-python-mode))
1826 (accept-process-output process)
1827 (and pop (pop-to-buffer buffer t))
1828 (and internal (set-process-query-on-exit-flag process nil))))
1829 proc-buffer-name)))
1831 ;;;###autoload
1832 (defun run-python (cmd &optional dedicated show)
1833 "Run an inferior Python process.
1834 Input and output via buffer named after
1835 `python-shell-buffer-name'. If there is a process already
1836 running in that buffer, just switch to it.
1838 With argument, allows you to define CMD so you can edit the
1839 command used to call the interpreter and define DEDICATED, so a
1840 dedicated process for the current buffer is open. When numeric
1841 prefix arg is other than 0 or 4 do not SHOW.
1843 Runs the hook `inferior-python-mode-hook' (after the
1844 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1845 process buffer for a list of commands.)"
1846 (interactive
1847 (if current-prefix-arg
1848 (list
1849 (read-string "Run Python: " (python-shell-parse-command))
1850 (y-or-n-p "Make dedicated process? ")
1851 (= (prefix-numeric-value current-prefix-arg) 4))
1852 (list (python-shell-parse-command) nil t)))
1853 (python-shell-make-comint
1854 cmd (python-shell-get-process-name dedicated) show)
1855 dedicated)
1857 (defun run-python-internal ()
1858 "Run an inferior Internal Python process.
1859 Input and output via buffer named after
1860 `python-shell-internal-buffer-name' and what
1861 `python-shell-internal-get-process-name' returns.
1863 This new kind of shell is intended to be used for generic
1864 communication related to defined configurations, the main
1865 difference with global or dedicated shells is that these ones are
1866 attached to a configuration, not a buffer. This means that can
1867 be used for example to retrieve the sys.path and other stuff,
1868 without messing with user shells. Note that
1869 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1870 are set to nil for these shells, so setup codes are not sent at
1871 startup."
1872 (let ((python-shell-enable-font-lock nil)
1873 (inferior-python-mode-hook nil))
1874 (get-buffer-process
1875 (python-shell-make-comint
1876 (python-shell-parse-command)
1877 (python-shell-internal-get-process-name) nil t))))
1879 (defun python-shell-get-process ()
1880 "Get inferior Python process for current buffer and return it."
1881 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1882 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1883 (global-proc-name (python-shell-get-process-name nil))
1884 (global-proc-buffer-name (format "*%s*" global-proc-name))
1885 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1886 (global-running (comint-check-proc global-proc-buffer-name)))
1887 ;; Always prefer dedicated
1888 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1889 (and global-running global-proc-buffer-name)))))
1891 (defun python-shell-get-or-create-process ()
1892 "Get or create an inferior Python process for current buffer and return it."
1893 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1894 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1895 (global-proc-name (python-shell-get-process-name nil))
1896 (global-proc-buffer-name (format "*%s*" global-proc-name))
1897 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1898 (global-running (comint-check-proc global-proc-buffer-name))
1899 (current-prefix-arg 16))
1900 (when (and (not dedicated-running) (not global-running))
1901 (if (call-interactively 'run-python)
1902 (setq dedicated-running t)
1903 (setq global-running t)))
1904 ;; Always prefer dedicated
1905 (get-buffer-process (if dedicated-running
1906 dedicated-proc-buffer-name
1907 global-proc-buffer-name))))
1909 (defvar python-shell-internal-buffer nil
1910 "Current internal shell buffer for the current buffer.
1911 This is really not necessary at all for the code to work but it's
1912 there for compatibility with CEDET.")
1914 (defvar python-shell-internal-last-output nil
1915 "Last output captured by the internal shell.
1916 This is really not necessary at all for the code to work but it's
1917 there for compatibility with CEDET.")
1919 (defun python-shell-internal-get-or-create-process ()
1920 "Get or create an inferior Internal Python process."
1921 (let* ((proc-name (python-shell-internal-get-process-name))
1922 (proc-buffer-name (format " *%s*" proc-name)))
1923 (when (not (process-live-p proc-name))
1924 (run-python-internal)
1925 (setq python-shell-internal-buffer proc-buffer-name)
1926 ;; XXX: Why is this `sit-for' needed?
1927 ;; `python-shell-make-comint' calls `accept-process-output'
1928 ;; already but it is not helping to get proper output on
1929 ;; 'gnu/linux when the internal shell process is not running and
1930 ;; a call to `python-shell-internal-send-string' is issued.
1931 (sit-for 0.1 t))
1932 (get-buffer-process proc-buffer-name)))
1934 (define-obsolete-function-alias
1935 'python-proc 'python-shell-internal-get-or-create-process "24.3")
1937 (define-obsolete-variable-alias
1938 'python-buffer 'python-shell-internal-buffer "24.3")
1940 (define-obsolete-variable-alias
1941 'python-preoutput-result 'python-shell-internal-last-output "24.3")
1943 (defun python-shell-send-string (string &optional process msg)
1944 "Send STRING to inferior Python PROCESS.
1945 When MSG is non-nil messages the first line of STRING."
1946 (interactive "sPython command: ")
1947 (let ((process (or process (python-shell-get-or-create-process)))
1948 (lines (split-string string "\n" t)))
1949 (and msg (message "Sent: %s..." (nth 0 lines)))
1950 (if (> (length lines) 1)
1951 (let* ((temporary-file-directory
1952 (if (file-remote-p default-directory)
1953 (concat (file-remote-p default-directory) "/tmp")
1954 temporary-file-directory))
1955 (temp-file-name (make-temp-file "py"))
1956 (file-name (or (buffer-file-name) temp-file-name)))
1957 (with-temp-file temp-file-name
1958 (insert string)
1959 (delete-trailing-whitespace))
1960 (python-shell-send-file file-name process temp-file-name))
1961 (comint-send-string process string)
1962 (when (or (not (string-match "\n$" string))
1963 (string-match "\n[ \t].*\n?$" string))
1964 (comint-send-string process "\n")))))
1966 (defvar python-shell-output-filter-in-progress nil)
1967 (defvar python-shell-output-filter-buffer nil)
1969 (defun python-shell-output-filter (string)
1970 "Filter used in `python-shell-send-string-no-output' to grab output.
1971 STRING is the output received to this point from the process.
1972 This filter saves received output from the process in
1973 `python-shell-output-filter-buffer' and stops receiving it after
1974 detecting a prompt at the end of the buffer."
1975 (setq
1976 string (ansi-color-filter-apply string)
1977 python-shell-output-filter-buffer
1978 (concat python-shell-output-filter-buffer string))
1979 (when (string-match
1980 ;; XXX: It seems on OSX an extra carriage return is attached
1981 ;; at the end of output, this handles that too.
1982 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1983 python-shell-prompt-regexp
1984 python-shell-prompt-block-regexp
1985 python-shell-prompt-pdb-regexp)
1986 python-shell-output-filter-buffer)
1987 ;; Output ends when `python-shell-output-filter-buffer' contains
1988 ;; the prompt attached at the end of it.
1989 (setq python-shell-output-filter-in-progress nil
1990 python-shell-output-filter-buffer
1991 (substring python-shell-output-filter-buffer
1992 0 (match-beginning 0)))
1993 (when (and (> (length python-shell-prompt-output-regexp) 0)
1994 (string-match (concat "^" python-shell-prompt-output-regexp)
1995 python-shell-output-filter-buffer))
1996 ;; Some shells, like iPython might append a prompt before the
1997 ;; output, clean that.
1998 (setq python-shell-output-filter-buffer
1999 (substring python-shell-output-filter-buffer (match-end 0)))))
2002 (defun python-shell-send-string-no-output (string &optional process msg)
2003 "Send STRING to PROCESS and inhibit output.
2004 When MSG is non-nil messages the first line of STRING. Return
2005 the output."
2006 (let ((process (or process (python-shell-get-or-create-process)))
2007 (comint-preoutput-filter-functions
2008 '(python-shell-output-filter))
2009 (python-shell-output-filter-in-progress t)
2010 (inhibit-quit t))
2012 (with-local-quit
2013 (python-shell-send-string string process msg)
2014 (while python-shell-output-filter-in-progress
2015 ;; `python-shell-output-filter' takes care of setting
2016 ;; `python-shell-output-filter-in-progress' to NIL after it
2017 ;; detects end of output.
2018 (accept-process-output process))
2019 (prog1
2020 python-shell-output-filter-buffer
2021 (setq python-shell-output-filter-buffer nil)))
2022 (with-current-buffer (process-buffer process)
2023 (comint-interrupt-subjob)))))
2025 (defun python-shell-internal-send-string (string)
2026 "Send STRING to the Internal Python interpreter.
2027 Returns the output. See `python-shell-send-string-no-output'."
2028 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
2029 ;; updated to support this new mode.
2030 (setq python-shell-internal-last-output
2031 (python-shell-send-string-no-output
2032 ;; Makes this function compatible with the old
2033 ;; python-send-receive. (At least for CEDET).
2034 (replace-regexp-in-string "_emacs_out +" "" string)
2035 (python-shell-internal-get-or-create-process) nil)))
2037 (define-obsolete-function-alias
2038 'python-send-receive 'python-shell-internal-send-string "24.3")
2040 (define-obsolete-function-alias
2041 'python-send-string 'python-shell-internal-send-string "24.3")
2043 (defun python-shell-send-region (start end)
2044 "Send the region delimited by START and END to inferior Python process."
2045 (interactive "r")
2046 (python-shell-send-string
2047 (concat
2048 (let ((line-num (line-number-at-pos start)))
2049 ;; When sending a region, add blank lines for non sent code so
2050 ;; backtraces remain correct.
2051 (make-string (1- line-num) ?\n))
2052 (buffer-substring start end))
2053 nil t))
2055 (defun python-shell-send-buffer (&optional arg)
2056 "Send the entire buffer to inferior Python process.
2057 With prefix ARG allow execution of code inside blocks delimited
2058 by \"if __name__== '__main__':\""
2059 (interactive "P")
2060 (save-restriction
2061 (widen)
2062 (let ((str (buffer-substring (point-min) (point-max))))
2063 (and
2064 (not arg)
2065 (setq str (replace-regexp-in-string
2066 (python-rx if-name-main)
2067 "if __name__ == '__main__ ':" str)))
2068 (python-shell-send-string str))))
2070 (defun python-shell-send-defun (arg)
2071 "Send the current defun to inferior Python process.
2072 When argument ARG is non-nil do not include decorators."
2073 (interactive "P")
2074 (save-excursion
2075 (python-shell-send-region
2076 (progn
2077 (end-of-line 1)
2078 (while (and (or (python-nav-beginning-of-defun)
2079 (beginning-of-line 1))
2080 (> (current-indentation) 0)))
2081 (when (not arg)
2082 (while (and (forward-line -1)
2083 (looking-at (python-rx decorator))))
2084 (forward-line 1))
2085 (point-marker))
2086 (progn
2087 (or (python-nav-end-of-defun)
2088 (end-of-line 1))
2089 (point-marker)))))
2091 (defun python-shell-send-file (file-name &optional process temp-file-name)
2092 "Send FILE-NAME to inferior Python PROCESS.
2093 If TEMP-FILE-NAME is passed then that file is used for processing
2094 instead, while internally the shell will continue to use
2095 FILE-NAME."
2096 (interactive "fFile to send: ")
2097 (let* ((process (or process (python-shell-get-or-create-process)))
2098 (temp-file-name (when temp-file-name
2099 (expand-file-name
2100 (or (file-remote-p temp-file-name 'localname)
2101 temp-file-name))))
2102 (file-name (or (when file-name
2103 (expand-file-name
2104 (or (file-remote-p file-name 'localname)
2105 file-name)))
2106 temp-file-name)))
2107 (when (not file-name)
2108 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2109 (python-shell-send-string
2110 (format
2111 (concat "__pyfile = open('''%s''');"
2112 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2113 "__pyfile.close()")
2114 (or temp-file-name file-name) file-name)
2115 process)))
2117 (defun python-shell-switch-to-shell ()
2118 "Switch to inferior Python process buffer."
2119 (interactive)
2120 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
2122 (defun python-shell-send-setup-code ()
2123 "Send all setup code for shell.
2124 This function takes the list of setup code to send from the
2125 `python-shell-setup-codes' list."
2126 (let ((process (get-buffer-process (current-buffer))))
2127 (dolist (code python-shell-setup-codes)
2128 (when code
2129 (message "Sent %s" code)
2130 (python-shell-send-string
2131 (symbol-value code) process)))))
2133 (add-hook 'inferior-python-mode-hook
2134 #'python-shell-send-setup-code)
2137 ;;; Shell completion
2139 (defcustom python-shell-completion-setup-code
2140 "try:
2141 import readline
2142 except ImportError:
2143 def __COMPLETER_all_completions(text): []
2144 else:
2145 import rlcompleter
2146 readline.set_completer(rlcompleter.Completer().complete)
2147 def __COMPLETER_all_completions(text):
2148 import sys
2149 completions = []
2150 try:
2151 i = 0
2152 while True:
2153 res = readline.get_completer()(text, i)
2154 if not res: break
2155 i += 1
2156 completions.append(res)
2157 except NameError:
2158 pass
2159 return completions"
2160 "Code used to setup completion in inferior Python processes."
2161 :type 'string
2162 :group 'python)
2164 (defcustom python-shell-completion-string-code
2165 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2166 "Python code used to get a string of completions separated by semicolons."
2167 :type 'string
2168 :group 'python)
2170 (defcustom python-shell-completion-module-string-code ""
2171 "Python code used to get completions separated by semicolons for imports.
2173 For IPython v0.11, add the following line to
2174 `python-shell-completion-setup-code':
2176 from IPython.core.completerlib import module_completion
2178 and use the following as the value of this variable:
2180 ';'.join(module_completion('''%s'''))\n"
2181 :type 'string
2182 :group 'python)
2184 (defcustom python-shell-completion-pdb-string-code
2185 "';'.join(globals().keys() + locals().keys())"
2186 "Python code used to get completions separated by semicolons for [i]pdb."
2187 :type 'string
2188 :group 'python)
2190 (defun python-shell-completion-get-completions (process line input)
2191 "Do completion at point for PROCESS.
2192 LINE is used to detect the context on how to complete given
2193 INPUT."
2194 (let* ((prompt
2195 ;; Get the last prompt for the inferior process
2196 ;; buffer. This is used for the completion code selection
2197 ;; heuristic.
2198 (with-current-buffer (process-buffer process)
2199 (buffer-substring-no-properties
2200 (overlay-start comint-last-prompt-overlay)
2201 (overlay-end comint-last-prompt-overlay))))
2202 (completion-context
2203 ;; Check whether a prompt matches a pdb string, an import
2204 ;; statement or just the standard prompt and use the
2205 ;; correct python-shell-completion-*-code string
2206 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
2207 (string-match
2208 (concat "^" python-shell-prompt-pdb-regexp) prompt))
2209 'pdb)
2210 ((and (>
2211 (length python-shell-completion-module-string-code) 0)
2212 (string-match
2213 (concat "^" python-shell-prompt-regexp) prompt)
2214 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line))
2215 'import)
2216 ((string-match
2217 (concat "^" python-shell-prompt-regexp) prompt)
2218 'default)
2219 (t nil)))
2220 (completion-code
2221 (case completion-context
2222 (pdb python-shell-completion-pdb-string-code)
2223 (import python-shell-completion-module-string-code)
2224 (default python-shell-completion-string-code)
2225 (t nil)))
2226 (input
2227 (if (eq completion-context 'import)
2228 (replace-regexp-in-string "^[ \t]+" "" line)
2229 input)))
2230 (and completion-code
2231 (> (length input) 0)
2232 (with-current-buffer (process-buffer process)
2233 (let ((completions (python-shell-send-string-no-output
2234 (format completion-code input) process)))
2235 (and (> (length completions) 2)
2236 (split-string completions
2237 "^'\\|^\"\\|;\\|'$\\|\"$" t)))))))
2239 (defun python-shell-completion-complete-at-point (&optional process)
2240 "Perform completion at point in inferior Python.
2241 Optional argument PROCESS forces completions to be retrieved
2242 using that one instead of current buffer's process."
2243 (setq process (or process (get-buffer-process (current-buffer))))
2244 (let* ((start
2245 (save-excursion
2246 (with-syntax-table python-dotty-syntax-table
2247 (let* ((paren-depth (car (syntax-ppss)))
2248 (syntax-string "w_")
2249 (syntax-list (string-to-syntax syntax-string)))
2250 ;; Stop scanning for the beginning of the completion
2251 ;; subject after the char before point matches a
2252 ;; delimiter
2253 (while (member
2254 (car (syntax-after (1- (point)))) syntax-list)
2255 (skip-syntax-backward syntax-string)
2256 (when (or (equal (char-before) ?\))
2257 (equal (char-before) ?\"))
2258 (forward-char -1))
2259 (while (or
2260 ;; honor initial paren depth
2261 (> (car (syntax-ppss)) paren-depth)
2262 (python-syntax-context 'string))
2263 (forward-char -1)))
2264 (point)))))
2265 (end (point)))
2266 (list start end
2267 (completion-table-dynamic
2268 (apply-partially
2269 #'python-shell-completion-get-completions
2270 process (buffer-substring-no-properties
2271 (line-beginning-position) end))))))
2273 (defun python-shell-completion-complete-or-indent ()
2274 "Complete or indent depending on the context.
2275 If content before pointer is all whitespace indent. If not try
2276 to complete."
2277 (interactive)
2278 (if (string-match "^[[:space:]]*$"
2279 (buffer-substring (comint-line-beginning-position)
2280 (point-marker)))
2281 (indent-for-tab-command)
2282 (completion-at-point)))
2285 ;;; PDB Track integration
2287 (defcustom python-pdbtrack-activate t
2288 "Non-nil makes python shell enable pdbtracking."
2289 :type 'boolean
2290 :group 'python
2291 :safe 'booleanp)
2293 (defcustom python-pdbtrack-stacktrace-info-regexp
2294 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2295 "Regular Expression matching stacktrace information.
2296 Used to extract the current line and module being inspected."
2297 :type 'string
2298 :group 'python
2299 :safe 'stringp)
2301 (defvar python-pdbtrack-tracked-buffer nil
2302 "Variable containing the value of the current tracked buffer.
2303 Never set this variable directly, use
2304 `python-pdbtrack-set-tracked-buffer' instead.")
2306 (defvar python-pdbtrack-buffers-to-kill nil
2307 "List of buffers to be deleted after tracking finishes.")
2309 (defun python-pdbtrack-set-tracked-buffer (file-name)
2310 "Set the buffer for FILE-NAME as the tracked buffer.
2311 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2312 Returns the tracked buffer."
2313 (let ((file-buffer (get-file-buffer file-name)))
2314 (if file-buffer
2315 (setq python-pdbtrack-tracked-buffer file-buffer)
2316 (setq file-buffer (find-file-noselect file-name))
2317 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
2318 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
2319 file-buffer))
2321 (defun python-pdbtrack-comint-output-filter-function (output)
2322 "Move overlay arrow to current pdb line in tracked buffer.
2323 Argument OUTPUT is a string with the output from the comint process."
2324 (when (and python-pdbtrack-activate (not (string= output "")))
2325 (let* ((full-output (ansi-color-filter-apply
2326 (buffer-substring comint-last-input-end (point-max))))
2327 (line-number)
2328 (file-name
2329 (with-temp-buffer
2330 (insert full-output)
2331 ;; When the debugger encounters a pdb.set_trace()
2332 ;; command, it prints a single stack frame. Sometimes
2333 ;; it prints a bit of extra information about the
2334 ;; arguments of the present function. When ipdb
2335 ;; encounters an exception, it prints the _entire_ stack
2336 ;; trace. To handle all of these cases, we want to find
2337 ;; the _last_ stack frame printed in the most recent
2338 ;; batch of output, then jump to the corrsponding
2339 ;; file/line number.
2340 (goto-char (point-max))
2341 (when (re-search-backward python-pdbtrack-stacktrace-info-regexp nil t)
2342 (setq line-number (string-to-number
2343 (match-string-no-properties 2)))
2344 (match-string-no-properties 1)))))
2345 (if (and file-name line-number)
2346 (let* ((tracked-buffer
2347 (python-pdbtrack-set-tracked-buffer file-name))
2348 (shell-buffer (current-buffer))
2349 (tracked-buffer-window (get-buffer-window tracked-buffer))
2350 (tracked-buffer-line-pos))
2351 (with-current-buffer tracked-buffer
2352 (set (make-local-variable 'overlay-arrow-string) "=>")
2353 (set (make-local-variable 'overlay-arrow-position) (make-marker))
2354 (setq tracked-buffer-line-pos (progn
2355 (goto-char (point-min))
2356 (forward-line (1- line-number))
2357 (point-marker)))
2358 (when tracked-buffer-window
2359 (set-window-point
2360 tracked-buffer-window tracked-buffer-line-pos))
2361 (set-marker overlay-arrow-position tracked-buffer-line-pos))
2362 (pop-to-buffer tracked-buffer)
2363 (switch-to-buffer-other-window shell-buffer))
2364 (when python-pdbtrack-tracked-buffer
2365 (with-current-buffer python-pdbtrack-tracked-buffer
2366 (set-marker overlay-arrow-position nil))
2367 (mapc #'(lambda (buffer)
2368 (ignore-errors (kill-buffer buffer)))
2369 python-pdbtrack-buffers-to-kill)
2370 (setq python-pdbtrack-tracked-buffer nil
2371 python-pdbtrack-buffers-to-kill nil)))))
2372 output)
2375 ;;; Symbol completion
2377 (defun python-completion-complete-at-point ()
2378 "Complete current symbol at point.
2379 For this to work the best as possible you should call
2380 `python-shell-send-buffer' from time to time so context in
2381 inferior python process is updated properly."
2382 (let ((process (python-shell-get-process)))
2383 (if (not process)
2384 (error "Completion needs an inferior Python process running")
2385 (python-shell-completion-complete-at-point process))))
2387 (add-to-list 'debug-ignored-errors
2388 "^Completion needs an inferior Python process running.")
2391 ;;; Fill paragraph
2393 (defcustom python-fill-comment-function 'python-fill-comment
2394 "Function to fill comments.
2395 This is the function used by `python-fill-paragraph' to
2396 fill comments."
2397 :type 'symbol
2398 :group 'python)
2400 (defcustom python-fill-string-function 'python-fill-string
2401 "Function to fill strings.
2402 This is the function used by `python-fill-paragraph' to
2403 fill strings."
2404 :type 'symbol
2405 :group 'python)
2407 (defcustom python-fill-decorator-function 'python-fill-decorator
2408 "Function to fill decorators.
2409 This is the function used by `python-fill-paragraph' to
2410 fill decorators."
2411 :type 'symbol
2412 :group 'python)
2414 (defcustom python-fill-paren-function 'python-fill-paren
2415 "Function to fill parens.
2416 This is the function used by `python-fill-paragraph' to
2417 fill parens."
2418 :type 'symbol
2419 :group 'python)
2421 (defcustom python-fill-docstring-style 'pep-257
2422 "Style used to fill docstrings.
2423 This affects `python-fill-string' behavior with regards to
2424 triple quotes positioning.
2426 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2427 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2428 position and will treat docstrings a normal string, any other
2429 value may result in one of the following docstring styles:
2431 DJANGO:
2433 \"\"\"
2434 Process foo, return bar.
2435 \"\"\"
2437 \"\"\"
2438 Process foo, return bar.
2440 If processing fails throw ProcessingError.
2441 \"\"\"
2443 ONETWO:
2445 \"\"\"Process foo, return bar.\"\"\"
2447 \"\"\"
2448 Process foo, return bar.
2450 If processing fails throw ProcessingError.
2452 \"\"\"
2454 PEP-257:
2456 \"\"\"Process foo, return bar.\"\"\"
2458 \"\"\"Process foo, return bar.
2460 If processing fails throw ProcessingError.
2462 \"\"\"
2464 PEP-257-NN:
2466 \"\"\"Process foo, return bar.\"\"\"
2468 \"\"\"Process foo, return bar.
2470 If processing fails throw ProcessingError.
2471 \"\"\"
2473 SYMMETRIC:
2475 \"\"\"Process foo, return bar.\"\"\"
2477 \"\"\"
2478 Process foo, return bar.
2480 If processing fails throw ProcessingError.
2481 \"\"\""
2482 :type '(choice
2483 (const :tag "Don't format docstrings" nil)
2484 (const :tag "Django's coding standards style." django)
2485 (const :tag "One newline and start and Two at end style." onetwo)
2486 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2487 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2488 (const :tag "Symmetric style." symmetric))
2489 :group 'python
2490 :safe (lambda (val)
2491 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
2493 (defun python-fill-paragraph (&optional justify)
2494 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2495 If any of the current line is in or at the end of a multi-line string,
2496 fill the string or the paragraph of it that point is in, preserving
2497 the string's indentation.
2498 Optional argument JUSTIFY defines if the paragraph should be justified."
2499 (interactive "P")
2500 (save-excursion
2501 (cond
2502 ;; Comments
2503 ((python-syntax-context 'comment)
2504 (funcall python-fill-comment-function justify))
2505 ;; Strings/Docstrings
2506 ((save-excursion (or (python-syntax-context 'string)
2507 (equal (string-to-syntax "|")
2508 (syntax-after (point)))))
2509 (funcall python-fill-string-function justify))
2510 ;; Decorators
2511 ((equal (char-after (save-excursion
2512 (python-nav-beginning-of-statement))) ?@)
2513 (funcall python-fill-decorator-function justify))
2514 ;; Parens
2515 ((or (python-syntax-context 'paren)
2516 (looking-at (python-rx open-paren))
2517 (save-excursion
2518 (skip-syntax-forward "^(" (line-end-position))
2519 (looking-at (python-rx open-paren))))
2520 (funcall python-fill-paren-function justify))
2521 (t t))))
2523 (defun python-fill-comment (&optional justify)
2524 "Comment fill function for `python-fill-paragraph'.
2525 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2526 (fill-comment-paragraph justify))
2528 (defun python-fill-string (&optional justify)
2529 "String fill function for `python-fill-paragraph'.
2530 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2531 (let* ((marker (point-marker))
2532 (str-start-pos
2533 (let ((m (make-marker)))
2534 (setf (marker-position m)
2535 (or (python-syntax-context 'string)
2536 (and (equal (string-to-syntax "|")
2537 (syntax-after (point)))
2538 (point)))) m))
2539 (num-quotes (python-syntax-count-quotes
2540 (char-after str-start-pos) str-start-pos))
2541 (str-end-pos
2542 (save-excursion
2543 (goto-char (+ str-start-pos num-quotes))
2544 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2545 (goto-char (point-max)))
2546 (point-marker)))
2547 (multi-line-p
2548 ;; Docstring styles may vary for oneliners and multi-liners.
2549 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2550 (delimiters-style
2551 (case python-fill-docstring-style
2552 ;; delimiters-style is a cons cell with the form
2553 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2554 ;; is NIL means to not add any newlines for start or end
2555 ;; of docstring. See `python-fill-docstring-style' for a
2556 ;; graphic idea of each style.
2557 (django (cons 1 1))
2558 (onetwo (and multi-line-p (cons 1 2)))
2559 (pep-257 (and multi-line-p (cons nil 2)))
2560 (pep-257-nn (and multi-line-p (cons nil 1)))
2561 (symmetric (and multi-line-p (cons 1 1)))))
2562 (docstring-p (save-excursion
2563 ;; Consider docstrings those strings which
2564 ;; start on a line by themselves.
2565 (python-nav-beginning-of-statement)
2566 (and (= (point) str-start-pos))))
2567 (fill-paragraph-function))
2568 (save-restriction
2569 (narrow-to-region str-start-pos str-end-pos)
2570 (fill-paragraph justify))
2571 (save-excursion
2572 (when (and docstring-p python-fill-docstring-style)
2573 ;; Add the number of newlines indicated by the selected style
2574 ;; at the start of the docstring.
2575 (goto-char (+ str-start-pos num-quotes))
2576 (delete-region (point) (progn
2577 (skip-syntax-forward "> ")
2578 (point)))
2579 (and (car delimiters-style)
2580 (or (newline (car delimiters-style)) t)
2581 ;; Indent only if a newline is added.
2582 (indent-according-to-mode))
2583 ;; Add the number of newlines indicated by the selected style
2584 ;; at the end of the docstring.
2585 (goto-char (if (not (= str-end-pos (point-max)))
2586 (- str-end-pos num-quotes)
2587 str-end-pos))
2588 (delete-region (point) (progn
2589 (skip-syntax-backward "> ")
2590 (point)))
2591 (and (cdr delimiters-style)
2592 ;; Add newlines only if string ends.
2593 (not (= str-end-pos (point-max)))
2594 (or (newline (cdr delimiters-style)) t)
2595 ;; Again indent only if a newline is added.
2596 (indent-according-to-mode))))) t)
2598 (defun python-fill-decorator (&optional justify)
2599 "Decorator fill function for `python-fill-paragraph'.
2600 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2603 (defun python-fill-paren (&optional justify)
2604 "Paren fill function for `python-fill-paragraph'.
2605 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2606 (save-restriction
2607 (narrow-to-region (progn
2608 (while (python-syntax-context 'paren)
2609 (goto-char (1- (point-marker))))
2610 (point-marker)
2611 (line-beginning-position))
2612 (progn
2613 (when (not (python-syntax-context 'paren))
2614 (end-of-line)
2615 (when (not (python-syntax-context 'paren))
2616 (skip-syntax-backward "^)")))
2617 (while (python-syntax-context 'paren)
2618 (goto-char (1+ (point-marker))))
2619 (point-marker)))
2620 (let ((paragraph-start "\f\\|[ \t]*$")
2621 (paragraph-separate ",")
2622 (fill-paragraph-function))
2623 (goto-char (point-min))
2624 (fill-paragraph justify))
2625 (while (not (eobp))
2626 (forward-line 1)
2627 (python-indent-line)
2628 (goto-char (line-end-position)))) t)
2631 ;;; Skeletons
2633 (defcustom python-skeleton-autoinsert nil
2634 "Non-nil means template skeletons will be automagically inserted.
2635 This happens when pressing \"if<SPACE>\", for example, to prompt for
2636 the if condition."
2637 :type 'boolean
2638 :group 'python
2639 :safe 'booleanp)
2641 (define-obsolete-variable-alias
2642 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
2644 (defvar python-skeleton-available '()
2645 "Internal list of available skeletons.")
2647 (define-abbrev-table 'python-mode-abbrev-table ()
2648 "Abbrev table for Python mode."
2649 :case-fixed t
2650 ;; Allow / inside abbrevs.
2651 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2652 ;; Only expand in code.
2653 :enable-function (lambda ()
2654 (and
2655 (not (python-syntax-comment-or-string-p))
2656 python-skeleton-autoinsert)))
2658 (defmacro python-skeleton-define (name doc &rest skel)
2659 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2660 The skeleton will be bound to python-skeleton-NAME and will
2661 be added to `python-mode-abbrev-table'."
2662 (declare (indent 2))
2663 (let* ((name (symbol-name name))
2664 (function-name (intern (concat "python-skeleton-" name))))
2665 `(progn
2666 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
2667 :system t)
2668 (setq python-skeleton-available
2669 (cons ',function-name python-skeleton-available))
2670 (define-skeleton ,function-name
2671 ,(or doc
2672 (format "Insert %s statement." name))
2673 ,@skel))))
2675 (defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2676 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2677 The skeleton will be bound to python-skeleton-NAME."
2678 (declare (indent 2))
2679 (let* ((name (symbol-name name))
2680 (function-name (intern (concat "python-skeleton--" name)))
2681 (msg (format
2682 "Add '%s' clause? " name)))
2683 (when (not skel)
2684 (setq skel
2685 `(< ,(format "%s:" name) \n \n
2686 > _ \n)))
2687 `(define-skeleton ,function-name
2688 ,(or doc
2689 (format "Auxiliary skeleton for %s statement." name))
2691 (unless (y-or-n-p ,msg)
2692 (signal 'quit t))
2693 ,@skel)))
2695 (python-define-auxiliary-skeleton else nil)
2697 (python-define-auxiliary-skeleton except nil)
2699 (python-define-auxiliary-skeleton finally nil)
2701 (python-skeleton-define if nil
2702 "Condition: "
2703 "if " str ":" \n
2704 _ \n
2705 ("other condition, %s: "
2707 "elif " str ":" \n
2708 > _ \n nil)
2709 '(python-skeleton--else) | ^)
2711 (python-skeleton-define while nil
2712 "Condition: "
2713 "while " str ":" \n
2714 > _ \n
2715 '(python-skeleton--else) | ^)
2717 (python-skeleton-define for nil
2718 "Iteration spec: "
2719 "for " str ":" \n
2720 > _ \n
2721 '(python-skeleton--else) | ^)
2723 (python-skeleton-define try nil
2725 "try:" \n
2726 > _ \n
2727 ("Exception, %s: "
2729 "except " str ":" \n
2730 > _ \n nil)
2731 resume:
2732 '(python-skeleton--except)
2733 '(python-skeleton--else)
2734 '(python-skeleton--finally) | ^)
2736 (python-skeleton-define def nil
2737 "Function name: "
2738 "def " str "(" ("Parameter, %s: "
2739 (unless (equal ?\( (char-before)) ", ")
2740 str) "):" \n
2741 "\"\"\"" - "\"\"\"" \n
2742 > _ \n)
2744 (python-skeleton-define class nil
2745 "Class name: "
2746 "class " str "(" ("Inheritance, %s: "
2747 (unless (equal ?\( (char-before)) ", ")
2748 str)
2749 & ")" | -2
2750 ":" \n
2751 "\"\"\"" - "\"\"\"" \n
2752 > _ \n)
2754 (defun python-skeleton-add-menu-items ()
2755 "Add menu items to Python->Skeletons menu."
2756 (let ((skeletons (sort python-skeleton-available 'string<))
2757 (items))
2758 (dolist (skeleton skeletons)
2759 (easy-menu-add-item
2760 nil '("Python" "Skeletons")
2761 `[,(format
2762 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2763 ,skeleton t]))))
2765 ;;; FFAP
2767 (defcustom python-ffap-setup-code
2768 "def __FFAP_get_module_path(module):
2769 try:
2770 import os
2771 path = __import__(module).__file__
2772 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2773 path = path[:-1]
2774 return path
2775 except:
2776 return ''"
2777 "Python code to get a module path."
2778 :type 'string
2779 :group 'python)
2781 (defcustom python-ffap-string-code
2782 "__FFAP_get_module_path('''%s''')\n"
2783 "Python code used to get a string with the path of a module."
2784 :type 'string
2785 :group 'python)
2787 (defun python-ffap-module-path (module)
2788 "Function for `ffap-alist' to return path for MODULE."
2789 (let ((process (or
2790 (and (eq major-mode 'inferior-python-mode)
2791 (get-buffer-process (current-buffer)))
2792 (python-shell-get-process))))
2793 (if (not process)
2795 (let ((module-file
2796 (python-shell-send-string-no-output
2797 (format python-ffap-string-code module) process)))
2798 (when module-file
2799 (substring-no-properties module-file 1 -1))))))
2801 (eval-after-load "ffap"
2802 '(progn
2803 (push '(python-mode . python-ffap-module-path) ffap-alist)
2804 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2807 ;;; Code check
2809 (defcustom python-check-command
2810 "pyflakes"
2811 "Command used to check a Python file."
2812 :type 'string
2813 :group 'python)
2815 (defcustom python-check-buffer-name
2816 "*Python check: %s*"
2817 "Buffer name used for check commands."
2818 :type 'string
2819 :group 'python)
2821 (defvar python-check-custom-command nil
2822 "Internal use.")
2824 (defun python-check (command)
2825 "Check a Python file (default current buffer's file).
2826 Runs COMMAND, a shell command, as if by `compile'. See
2827 `python-check-command' for the default."
2828 (interactive
2829 (list (read-string "Check command: "
2830 (or python-check-custom-command
2831 (concat python-check-command " "
2832 (shell-quote-argument
2834 (let ((name (buffer-file-name)))
2835 (and name
2836 (file-name-nondirectory name)))
2837 "")))))))
2838 (setq python-check-custom-command command)
2839 (save-some-buffers (not compilation-ask-about-save) nil)
2840 (let ((process-environment (python-shell-calculate-process-environment))
2841 (exec-path (python-shell-calculate-exec-path)))
2842 (compilation-start command nil
2843 (lambda (mode-name)
2844 (format python-check-buffer-name command)))))
2847 ;;; Eldoc
2849 (defcustom python-eldoc-setup-code
2850 "def __PYDOC_get_help(obj):
2851 try:
2852 import inspect
2853 if hasattr(obj, 'startswith'):
2854 obj = eval(obj, globals())
2855 doc = inspect.getdoc(obj)
2856 if not doc and callable(obj):
2857 target = None
2858 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2859 target = obj.__init__
2860 objtype = 'class'
2861 else:
2862 target = obj
2863 objtype = 'def'
2864 if target:
2865 args = inspect.formatargspec(
2866 *inspect.getargspec(target)
2868 name = obj.__name__
2869 doc = '{objtype} {name}{args}'.format(
2870 objtype=objtype, name=name, args=args
2872 else:
2873 doc = doc.splitlines()[0]
2874 except:
2875 doc = ''
2876 try:
2877 exec('print doc')
2878 except SyntaxError:
2879 print(doc)"
2880 "Python code to setup documentation retrieval."
2881 :type 'string
2882 :group 'python)
2884 (defcustom python-eldoc-string-code
2885 "__PYDOC_get_help('''%s''')\n"
2886 "Python code used to get a string with the documentation of an object."
2887 :type 'string
2888 :group 'python)
2890 (defun python-eldoc--get-doc-at-point (&optional force-input force-process)
2891 "Internal implementation to get documentation at point.
2892 If not FORCE-INPUT is passed then what
2893 `python-info-current-symbol' returns will be used. If not
2894 FORCE-PROCESS is passed what `python-shell-get-process' returns
2895 is used."
2896 (let ((process (or force-process (python-shell-get-process))))
2897 (if (not process)
2898 (error "Eldoc needs an inferior Python process running")
2899 (let ((input (or force-input
2900 (python-info-current-symbol t))))
2901 (and input
2902 (python-shell-send-string-no-output
2903 (format python-eldoc-string-code input)
2904 process))))))
2906 (defun python-eldoc-function ()
2907 "`eldoc-documentation-function' for Python.
2908 For this to work the best as possible you should call
2909 `python-shell-send-buffer' from time to time so context in
2910 inferior python process is updated properly."
2911 (python-eldoc--get-doc-at-point))
2913 (defun python-eldoc-at-point (symbol)
2914 "Get help on SYMBOL using `help'.
2915 Interactively, prompt for symbol."
2916 (interactive
2917 (let ((symbol (python-info-current-symbol t))
2918 (enable-recursive-minibuffers t))
2919 (list (read-string (if symbol
2920 (format "Describe symbol (default %s): " symbol)
2921 "Describe symbol: ")
2922 nil nil symbol))))
2923 (message (python-eldoc--get-doc-at-point symbol)))
2925 (add-to-list 'debug-ignored-errors
2926 "^Eldoc needs an inferior Python process running.")
2929 ;;; Imenu
2931 (defun python-imenu-prev-index-position ()
2932 "Python mode's `imenu-prev-index-position-function'."
2933 (let ((found))
2934 (while (and (setq found
2935 (re-search-backward python-nav-beginning-of-defun-regexp nil t))
2936 (not (python-info-looking-at-beginning-of-defun))))
2937 (and found
2938 (python-info-looking-at-beginning-of-defun)
2939 (python-info-current-defun))))
2942 ;;; Misc helpers
2944 (defun python-info-current-defun (&optional include-type)
2945 "Return name of surrounding function with Python compatible dotty syntax.
2946 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2947 This function is compatible to be used as
2948 `add-log-current-defun-function' since it returns nil if point is
2949 not inside a defun."
2950 (save-restriction
2951 (widen)
2952 (save-excursion
2953 (end-of-line 1)
2954 (let ((names)
2955 (starting-indentation (current-indentation))
2956 (starting-pos (point))
2957 (first-run t)
2958 (last-indent)
2959 (type))
2960 (catch 'exit
2961 (while (python-nav-beginning-of-defun 1)
2962 (when (save-match-data
2963 (and
2964 (or (not last-indent)
2965 (< (current-indentation) last-indent))
2967 (and first-run
2968 (save-excursion
2969 ;; If this is the first run, we may add
2970 ;; the current defun at point.
2971 (setq first-run nil)
2972 (goto-char starting-pos)
2973 (python-nav-beginning-of-statement)
2974 (beginning-of-line 1)
2975 (looking-at-p
2976 python-nav-beginning-of-defun-regexp)))
2977 (< starting-pos
2978 (save-excursion
2979 (let ((min-indent
2980 (+ (current-indentation)
2981 python-indent-offset)))
2982 (if (< starting-indentation min-indent)
2983 ;; If the starting indentation is not
2984 ;; within the min defun indent make the
2985 ;; check fail.
2986 starting-pos
2987 ;; Else go to the end of defun and add
2988 ;; up the current indentation to the
2989 ;; ending position.
2990 (python-nav-end-of-defun)
2991 (+ (point)
2992 (if (>= (current-indentation) min-indent)
2993 (1+ (current-indentation))
2994 0)))))))))
2995 (save-match-data (setq last-indent (current-indentation)))
2996 (if (or (not include-type) type)
2997 (setq names (cons (match-string-no-properties 1) names))
2998 (let ((match (split-string (match-string-no-properties 0))))
2999 (setq type (car match))
3000 (setq names (cons (cadr match) names)))))
3001 ;; Stop searching ASAP.
3002 (and (= (current-indentation) 0) (throw 'exit t))))
3003 (and names
3004 (concat (and type (format "%s " type))
3005 (mapconcat 'identity names ".")))))))
3007 (defun python-info-current-symbol (&optional replace-self)
3008 "Return current symbol using dotty syntax.
3009 With optional argument REPLACE-SELF convert \"self\" to current
3010 parent defun name."
3011 (let ((name
3012 (and (not (python-syntax-comment-or-string-p))
3013 (with-syntax-table python-dotty-syntax-table
3014 (let ((sym (symbol-at-point)))
3015 (and sym
3016 (substring-no-properties (symbol-name sym))))))))
3017 (when name
3018 (if (not replace-self)
3019 name
3020 (let ((current-defun (python-info-current-defun)))
3021 (if (not current-defun)
3022 name
3023 (replace-regexp-in-string
3024 (python-rx line-start word-start "self" word-end ?.)
3025 (concat
3026 (mapconcat 'identity
3027 (butlast (split-string current-defun "\\."))
3028 ".") ".")
3029 name)))))))
3031 (defun python-info-statement-starts-block-p ()
3032 "Return non-nil if current statement opens a block."
3033 (save-excursion
3034 (python-nav-beginning-of-statement)
3035 (looking-at (python-rx block-start))))
3037 (defun python-info-statement-ends-block-p ()
3038 "Return non-nil if point is at end of block."
3039 (let ((end-of-block-pos (save-excursion
3040 (python-nav-end-of-block)))
3041 (end-of-statement-pos (save-excursion
3042 (python-nav-end-of-statement))))
3043 (and end-of-block-pos end-of-statement-pos
3044 (= end-of-block-pos end-of-statement-pos))))
3046 (defun python-info-beginning-of-statement-p ()
3047 "Return non-nil if point is at beginning of statement."
3048 (= (point) (save-excursion
3049 (python-nav-beginning-of-statement)
3050 (point))))
3052 (defun python-info-end-of-statement-p ()
3053 "Return non-nil if point is at end of statement."
3054 (= (point) (save-excursion
3055 (python-nav-end-of-statement)
3056 (point))))
3058 (defun python-info-beginning-of-block-p ()
3059 "Return non-nil if point is at beginning of block."
3060 (and (python-info-beginning-of-statement-p)
3061 (python-info-statement-starts-block-p)))
3063 (defun python-info-end-of-block-p ()
3064 "Return non-nil if point is at end of block."
3065 (and (python-info-end-of-statement-p)
3066 (python-info-statement-ends-block-p)))
3068 (defun python-info-closing-block ()
3069 "Return the point of the block the current line closes."
3070 (let ((closing-word (save-excursion
3071 (back-to-indentation)
3072 (current-word)))
3073 (indentation (current-indentation)))
3074 (when (member closing-word python-indent-dedenters)
3075 (save-excursion
3076 (forward-line -1)
3077 (while (and (> (current-indentation) indentation)
3078 (not (bobp))
3079 (not (back-to-indentation))
3080 (forward-line -1)))
3081 (back-to-indentation)
3082 (cond
3083 ((not (equal indentation (current-indentation))) nil)
3084 ((string= closing-word "elif")
3085 (when (member (current-word) '("if" "elif"))
3086 (point-marker)))
3087 ((string= closing-word "else")
3088 (when (member (current-word) '("if" "elif" "except" "for" "while"))
3089 (point-marker)))
3090 ((string= closing-word "except")
3091 (when (member (current-word) '("try"))
3092 (point-marker)))
3093 ((string= closing-word "finally")
3094 (when (member (current-word) '("except" "else"))
3095 (point-marker))))))))
3097 (defun python-info-closing-block-message (&optional closing-block-point)
3098 "Message the contents of the block the current line closes.
3099 With optional argument CLOSING-BLOCK-POINT use that instead of
3100 recalculating it calling `python-info-closing-block'."
3101 (let ((point (or closing-block-point (python-info-closing-block))))
3102 (when point
3103 (save-restriction
3104 (widen)
3105 (message "Closes %s" (save-excursion
3106 (goto-char point)
3107 (back-to-indentation)
3108 (buffer-substring
3109 (point) (line-end-position))))))))
3111 (defun python-info-line-ends-backslash-p (&optional line-number)
3112 "Return non-nil if current line ends with backslash.
3113 With optional argument LINE-NUMBER, check that line instead."
3114 (save-excursion
3115 (save-restriction
3116 (widen)
3117 (when line-number
3118 (python-util-goto-line line-number))
3119 (while (and (not (eobp))
3120 (goto-char (line-end-position))
3121 (python-syntax-context 'paren)
3122 (not (equal (char-before (point)) ?\\)))
3123 (forward-line 1))
3124 (when (equal (char-before) ?\\)
3125 (point-marker)))))
3127 (defun python-info-beginning-of-backslash (&optional line-number)
3128 "Return the point where the backslashed line start.
3129 Optional argument LINE-NUMBER forces the line number to check against."
3130 (save-excursion
3131 (save-restriction
3132 (widen)
3133 (when line-number
3134 (python-util-goto-line line-number))
3135 (when (python-info-line-ends-backslash-p)
3136 (while (save-excursion
3137 (goto-char (line-beginning-position))
3138 (python-syntax-context 'paren))
3139 (forward-line -1))
3140 (back-to-indentation)
3141 (point-marker)))))
3143 (defun python-info-continuation-line-p ()
3144 "Check if current line is continuation of another.
3145 When current line is continuation of another return the point
3146 where the continued line ends."
3147 (save-excursion
3148 (save-restriction
3149 (widen)
3150 (let* ((context-type (progn
3151 (back-to-indentation)
3152 (python-syntax-context-type)))
3153 (line-start (line-number-at-pos))
3154 (context-start (when context-type
3155 (python-syntax-context context-type))))
3156 (cond ((equal context-type 'paren)
3157 ;; Lines inside a paren are always a continuation line
3158 ;; (except the first one).
3159 (python-util-forward-comment -1)
3160 (point-marker))
3161 ((member context-type '(string comment))
3162 ;; move forward an roll again
3163 (goto-char context-start)
3164 (python-util-forward-comment)
3165 (python-info-continuation-line-p))
3167 ;; Not within a paren, string or comment, the only way
3168 ;; we are dealing with a continuation line is that
3169 ;; previous line contains a backslash, and this can
3170 ;; only be the previous line from current
3171 (back-to-indentation)
3172 (python-util-forward-comment -1)
3173 (when (and (equal (1- line-start) (line-number-at-pos))
3174 (python-info-line-ends-backslash-p))
3175 (point-marker))))))))
3177 (defun python-info-block-continuation-line-p ()
3178 "Return non-nil if current line is a continuation of a block."
3179 (save-excursion
3180 (when (python-info-continuation-line-p)
3181 (forward-line -1)
3182 (back-to-indentation)
3183 (when (looking-at (python-rx block-start))
3184 (point-marker)))))
3186 (defun python-info-assignment-continuation-line-p ()
3187 "Check if current line is a continuation of an assignment.
3188 When current line is continuation of another with an assignment
3189 return the point of the first non-blank character after the
3190 operator."
3191 (save-excursion
3192 (when (python-info-continuation-line-p)
3193 (forward-line -1)
3194 (back-to-indentation)
3195 (when (and (not (looking-at (python-rx block-start)))
3196 (and (re-search-forward (python-rx not-simple-operator
3197 assignment-operator
3198 not-simple-operator)
3199 (line-end-position) t)
3200 (not (python-syntax-context-type))))
3201 (skip-syntax-forward "\s")
3202 (point-marker)))))
3204 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
3205 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3206 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
3207 (save-excursion
3208 (beginning-of-line 1)
3209 (looking-at python-nav-beginning-of-defun-regexp))))
3211 (defun python-info-current-line-comment-p ()
3212 "Check if current line is a comment line."
3213 (char-equal
3214 (or (char-after (+ (line-beginning-position) (current-indentation))) ?_)
3215 ?#))
3217 (defun python-info-current-line-empty-p ()
3218 "Check if current line is empty, ignoring whitespace."
3219 (save-excursion
3220 (beginning-of-line 1)
3221 (looking-at
3222 (python-rx line-start (* whitespace)
3223 (group (* not-newline))
3224 (* whitespace) line-end))
3225 (string-equal "" (match-string-no-properties 1))))
3228 ;;; Utility functions
3230 (defun python-util-goto-line (line-number)
3231 "Move point to LINE-NUMBER."
3232 (goto-char (point-min))
3233 (forward-line (1- line-number)))
3235 ;; Stolen from org-mode
3236 (defun python-util-clone-local-variables (from-buffer &optional regexp)
3237 "Clone local variables from FROM-BUFFER.
3238 Optional argument REGEXP selects variables to clone and defaults
3239 to \"^python-\"."
3240 (mapc
3241 (lambda (pair)
3242 (and (symbolp (car pair))
3243 (string-match (or regexp "^python-")
3244 (symbol-name (car pair)))
3245 (set (make-local-variable (car pair))
3246 (cdr pair))))
3247 (buffer-local-variables from-buffer)))
3249 (defun python-util-forward-comment (&optional direction)
3250 "Python mode specific version of `forward-comment'.
3251 Optional argument DIRECTION defines the direction to move to."
3252 (let ((comment-start (python-syntax-context 'comment))
3253 (factor (if (< (or direction 0) 0)
3254 -99999
3255 99999)))
3256 (when comment-start
3257 (goto-char comment-start))
3258 (forward-comment factor)))
3261 ;;;###autoload
3262 (define-derived-mode python-mode prog-mode "Python"
3263 "Major mode for editing Python files.
3265 \\{python-mode-map}
3266 Entry to this mode calls the value of `python-mode-hook'
3267 if that value is non-nil."
3268 (set (make-local-variable 'tab-width) 8)
3269 (set (make-local-variable 'indent-tabs-mode) nil)
3271 (set (make-local-variable 'comment-start) "# ")
3272 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3274 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3275 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3277 (set (make-local-variable 'forward-sexp-function)
3278 'python-nav-forward-sexp)
3280 (set (make-local-variable 'font-lock-defaults)
3281 '(python-font-lock-keywords nil nil nil nil))
3283 (set (make-local-variable 'syntax-propertize-function)
3284 python-syntax-propertize-function)
3286 (set (make-local-variable 'indent-line-function)
3287 #'python-indent-line-function)
3288 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3290 (set (make-local-variable 'paragraph-start) "\\s-*$")
3291 (set (make-local-variable 'fill-paragraph-function)
3292 'python-fill-paragraph)
3294 (set (make-local-variable 'beginning-of-defun-function)
3295 #'python-nav-beginning-of-defun)
3296 (set (make-local-variable 'end-of-defun-function)
3297 #'python-nav-end-of-defun)
3299 (add-hook 'completion-at-point-functions
3300 'python-completion-complete-at-point nil 'local)
3302 (add-hook 'post-self-insert-hook
3303 'python-indent-post-self-insert-function nil 'local)
3305 (set (make-local-variable 'imenu-extract-index-name-function)
3306 #'python-info-current-defun)
3308 (set (make-local-variable 'imenu-prev-index-position-function)
3309 #'python-imenu-prev-index-position)
3311 (set (make-local-variable 'add-log-current-defun-function)
3312 #'python-info-current-defun)
3314 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3316 (set (make-local-variable 'skeleton-further-elements)
3317 '((abbrev-mode nil)
3318 (< '(backward-delete-char-untabify (min python-indent-offset
3319 (current-column))))
3320 (^ '(- (1+ (current-indentation))))))
3322 (set (make-local-variable 'eldoc-documentation-function)
3323 #'python-eldoc-function)
3325 (add-to-list 'hs-special-modes-alist
3326 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
3327 ,(lambda (arg)
3328 (python-nav-end-of-defun)) nil))
3330 (set (make-local-variable 'mode-require-final-newline) t)
3332 (set (make-local-variable 'outline-regexp)
3333 (python-rx (* space) block-start))
3334 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3335 (set (make-local-variable 'outline-level)
3336 #'(lambda ()
3337 "`outline-level' function for Python mode."
3338 (1+ (/ (current-indentation) python-indent-offset))))
3340 (python-skeleton-add-menu-items)
3342 (make-local-variable 'python-shell-internal-buffer)
3344 (when python-indent-guess-indent-offset
3345 (python-indent-guess-indent-offset)))
3348 (provide 'python)
3350 ;; Local Variables:
3351 ;; coding: utf-8
3352 ;; indent-tabs-mode: nil
3353 ;; End:
3355 ;;; python.el ends here