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