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