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