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