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