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