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