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