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