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