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