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