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