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