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