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