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