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