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