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