Fix shell handling of unbalanced quotes and parens in output.
[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 "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
a5b773c4
FEG
340 ">>=" "<<=" "&=" "^=" "|=")))
341 (string-delimiter . ,(rx (and
342 ;; Match even number of backslashes.
343 (or (not (any ?\\ ?\' ?\")) point
344 ;; Quotes might be preceded by a escaped quote.
345 (and (or (not (any ?\\)) point) ?\\
346 (* ?\\ ?\\) (any ?\' ?\")))
347 (* ?\\ ?\\)
348 ;; Match single or triple quotes of any kind.
349 (group (or "\"" "\"\"\"" "'" "'''"))))))
350 "Additional Python specific sexps for `python-rx'")
351
352 (defmacro python-rx (&rest regexps)
353 "Python mode specialized rx macro.
6cad4c6e 354This variant of `rx' supports common python named REGEXPS."
a5b773c4
FEG
355 (let ((rx-constituents (append python-rx-constituents rx-constituents)))
356 (cond ((null regexps)
357 (error "No regexp"))
358 ((cdr regexps)
359 (rx-to-string `(and ,@regexps) t))
360 (t
361 (rx-to-string (car regexps) t))))))
45c138ac
FEG
362
363\f
364;;; Font-lock and syntax
2d79ec42
FEG
365
366(defun python-syntax-context (type &optional syntax-ppss)
367 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
368TYPE can be `comment', `string' or `paren'. It returns the start
369character address of the specified TYPE."
370 (let ((ppss (or syntax-ppss (syntax-ppss))))
371 (case type
372 (comment (and (nth 4 ppss) (nth 8 ppss)))
373 (string (and (not (nth 4 ppss)) (nth 8 ppss)))
374 (paren (nth 1 ppss))
375 (t nil))))
376
377(defun python-syntax-context-type (&optional syntax-ppss)
378 "Return the context type using SYNTAX-PPSS.
379The type returned can be `comment', `string' or `paren'."
380 (let ((ppss (or syntax-ppss (syntax-ppss))))
381 (cond
382 ((nth 8 ppss) (if (nth 4 ppss) 'comment 'string))
383 ((nth 1 ppss) 'paren))))
384
385(defsubst python-syntax-comment-or-string-p ()
386 "Return non-nil if point is inside 'comment or 'string."
387 (nth 8 (syntax-ppss)))
388
389(define-obsolete-function-alias
2a1e2476 390 'python-info-ppss-context #'python-syntax-context "24.3")
2d79ec42
FEG
391
392(define-obsolete-function-alias
2a1e2476 393 'python-info-ppss-context-type #'python-syntax-context-type "24.3")
2d79ec42
FEG
394
395(define-obsolete-function-alias
396 'python-info-ppss-comment-or-string-p
2a1e2476 397 #'python-syntax-comment-or-string-p "24.3")
2d79ec42 398
45c138ac
FEG
399(defvar python-font-lock-keywords
400 ;; Keywords
401 `(,(rx symbol-start
27d7f16f
FEG
402 (or
403 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
404 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
405 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
406 "try"
407 ;; Python 2:
408 "print" "exec"
409 ;; Python 3:
410 ;; False, None, and True are listed as keywords on the Python 3
411 ;; documentation, but since they also qualify as constants they are
412 ;; fontified like that in order to keep font-lock consistent between
413 ;; Python versions.
479a14cc
FEG
414 "nonlocal"
415 ;; Extra:
416 "self")
45c138ac
FEG
417 symbol-end)
418 ;; functions
419 (,(rx symbol-start "def" (1+ space) (group (1+ (or word ?_))))
420 (1 font-lock-function-name-face))
421 ;; classes
422 (,(rx symbol-start "class" (1+ space) (group (1+ (or word ?_))))
423 (1 font-lock-type-face))
424 ;; Constants
c61d750e 425 (,(rx symbol-start
27d7f16f
FEG
426 (or
427 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
428 ;; copyright, license, credits, quit and exit are added by the site
429 ;; module and they are not intended to be used in programs
430 "copyright" "credits" "exit" "license" "quit")
c61d750e 431 symbol-end) . font-lock-constant-face)
45c138ac
FEG
432 ;; Decorators.
433 (,(rx line-start (* (any " \t")) (group "@" (1+ (or word ?_))
434 (0+ "." (1+ (or word ?_)))))
435 (1 font-lock-type-face))
436 ;; Builtin Exceptions
437 (,(rx symbol-start
27d7f16f
FEG
438 (or
439 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
440 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
441 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
442 "ImportError" "ImportWarning" "IndexError" "KeyError"
443 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
444 "NotImplementedError" "OSError" "OverflowError"
445 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
446 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
447 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
448 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
449 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
450 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
451 ;; Python 2:
452 "StandardError"
453 ;; Python 3:
454 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
455 "TabError")
45c138ac
FEG
456 symbol-end) . font-lock-type-face)
457 ;; Builtins
9438f1ef 458 (,(rx symbol-start
27d7f16f
FEG
459 (or
460 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
461 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
462 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
463 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
464 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
465 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
466 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
467 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
468 "__import__"
469 ;; Python 2:
470 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
471 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
472 "intern"
473 ;; Python 3:
474 "ascii" "bytearray" "bytes" "exec"
475 ;; Extra:
476 "__all__" "__doc__" "__name__" "__package__")
9438f1ef 477 symbol-end) . font-lock-builtin-face)
48d1354e 478 ;; assignments
45c138ac
FEG
479 ;; support for a = b = c = 5
480 (,(lambda (limit)
d8e594db
FEG
481 (let ((re (python-rx (group (+ (any word ?. ?_)))
482 (? ?\[ (+ (not (any ?\]))) ?\]) (* space)
45c138ac
FEG
483 assignment-operator)))
484 (when (re-search-forward re limit t)
2d79ec42 485 (while (and (python-syntax-context 'paren)
45c138ac 486 (re-search-forward re limit t)))
2d79ec42 487 (if (and (not (python-syntax-context 'paren))
534e2438 488 (not (equal (char-after (point-marker)) ?=)))
45c138ac
FEG
489 t
490 (set-match-data nil)))))
491 (1 font-lock-variable-name-face nil nil))
492 ;; support for a, b, c = (1, 2, 3)
493 (,(lambda (limit)
494 (let ((re (python-rx (group (+ (any word ?. ?_))) (* space)
495 (* ?, (* space) (+ (any word ?. ?_)) (* space))
496 ?, (* space) (+ (any word ?. ?_)) (* space)
497 assignment-operator)))
498 (when (and (re-search-forward re limit t)
499 (goto-char (nth 3 (match-data))))
2d79ec42 500 (while (and (python-syntax-context 'paren)
45c138ac
FEG
501 (re-search-forward re limit t))
502 (goto-char (nth 3 (match-data))))
2d79ec42 503 (if (not (python-syntax-context 'paren))
45c138ac
FEG
504 t
505 (set-match-data nil)))))
506 (1 font-lock-variable-name-face nil nil))))
507
aeadd9a4 508(defconst python-syntax-propertize-function
aeadd9a4 509 (syntax-propertize-rules
a5b773c4 510 ((python-rx string-delimiter)
5727eadf 511 (0 (ignore (python-syntax-stringify))))))
8fb8b88f
FEG
512
513(defsubst python-syntax-count-quotes (quote-char &optional point limit)
514 "Count number of quotes around point (max is 3).
515QUOTE-CHAR is the quote char to count. Optional argument POINT is
516the point where scan starts (defaults to current point) and LIMIT
517is used to limit the scan."
518 (let ((i 0))
519 (while (and (< i 3)
520 (or (not limit) (< (+ point i) limit))
521 (eq (char-after (+ point i)) quote-char))
522 (incf i))
523 i))
524
525(defun python-syntax-stringify ()
526 "Put `syntax-table' property correctly on single/triple quotes."
a1a9f411 527 (let* ((num-quotes (length (match-string-no-properties 1)))
8fb8b88f
FEG
528 (ppss (prog2
529 (backward-char num-quotes)
530 (syntax-ppss)
531 (forward-char num-quotes)))
532 (string-start (and (not (nth 4 ppss)) (nth 8 ppss)))
533 (quote-starting-pos (- (point) num-quotes))
534 (quote-ending-pos (point))
535 (num-closing-quotes
536 (and string-start
537 (python-syntax-count-quotes
538 (char-before) string-start quote-starting-pos))))
539 (cond ((and string-start (= num-closing-quotes 0))
540 ;; This set of quotes doesn't match the string starting
541 ;; kind. Do nothing.
542 nil)
543 ((not string-start)
544 ;; This set of quotes delimit the start of a string.
545 (put-text-property quote-starting-pos (1+ quote-starting-pos)
546 'syntax-table (string-to-syntax "|")))
547 ((= num-quotes num-closing-quotes)
548 ;; This set of quotes delimit the end of a string.
549 (put-text-property (1- quote-ending-pos) quote-ending-pos
550 'syntax-table (string-to-syntax "|")))
551 ((> num-quotes num-closing-quotes)
552 ;; This may only happen whenever a triple quote is closing
553 ;; a single quoted string. Add string delimiter syntax to
554 ;; all three quotes.
555 (put-text-property quote-starting-pos quote-ending-pos
556 'syntax-table (string-to-syntax "|"))))))
45c138ac
FEG
557
558(defvar python-mode-syntax-table
559 (let ((table (make-syntax-table)))
560 ;; Give punctuation syntax to ASCII that normally has symbol
561 ;; syntax or has word syntax and isn't a letter.
562 (let ((symbol (string-to-syntax "_"))
6cad4c6e 563 (sst (standard-syntax-table)))
45c138ac 564 (dotimes (i 128)
6cad4c6e
FEG
565 (unless (= i ?_)
566 (if (equal symbol (aref sst i))
567 (modify-syntax-entry i "." table)))))
45c138ac
FEG
568 (modify-syntax-entry ?$ "." table)
569 (modify-syntax-entry ?% "." table)
570 ;; exceptions
571 (modify-syntax-entry ?# "<" table)
572 (modify-syntax-entry ?\n ">" table)
573 (modify-syntax-entry ?' "\"" table)
574 (modify-syntax-entry ?` "$" table)
575 table)
576 "Syntax table for Python files.")
577
578(defvar python-dotty-syntax-table
579 (let ((table (make-syntax-table python-mode-syntax-table)))
580 (modify-syntax-entry ?. "w" table)
581 (modify-syntax-entry ?_ "w" table)
582 table)
583 "Dotty syntax table for Python files.
584It makes underscores and dots word constituent chars.")
585
586\f
587;;; Indentation
588
589(defcustom python-indent-offset 4
590 "Default indentation offset for Python."
591 :group 'python
592 :type 'integer
593 :safe 'integerp)
594
595(defcustom python-indent-guess-indent-offset t
596 "Non-nil tells Python mode to guess `python-indent-offset' value."
597 :type 'boolean
0f55249e
FEG
598 :group 'python
599 :safe 'booleanp)
45c138ac 600
9ddf3c74 601(define-obsolete-variable-alias
2a1e2476 602 'python-indent 'python-indent-offset "24.3")
9ddf3c74
FEG
603
604(define-obsolete-variable-alias
2a1e2476 605 'python-guess-indent 'python-indent-guess-indent-offset "24.3")
9ddf3c74 606
45c138ac
FEG
607(defvar python-indent-current-level 0
608 "Current indentation level `python-indent-line-function' is using.")
609
610(defvar python-indent-levels '(0)
611 "Levels of indentation available for `python-indent-line-function'.")
612
613(defvar python-indent-dedenters '("else" "elif" "except" "finally")
614 "List of words that should be dedented.
615These make `python-indent-calculate-indentation' subtract the value of
616`python-indent-offset'.")
617
618(defun python-indent-guess-indent-offset ()
954aa7bd 619 "Guess and set `python-indent-offset' for the current buffer."
9ddf3c74 620 (interactive)
6cad4c6e
FEG
621 (save-excursion
622 (save-restriction
623 (widen)
624 (goto-char (point-min))
625 (let ((block-end))
626 (while (and (not block-end)
627 (re-search-forward
628 (python-rx line-start block-start) nil t))
629 (when (and
2d79ec42 630 (not (python-syntax-context-type))
6cad4c6e
FEG
631 (progn
632 (goto-char (line-end-position))
633 (python-util-forward-comment -1)
634 (if (equal (char-before) ?:)
635 t
636 (forward-line 1)
637 (when (python-info-block-continuation-line-p)
638 (while (and (python-info-continuation-line-p)
639 (not (eobp)))
640 (forward-line 1))
641 (python-util-forward-comment -1)
642 (when (equal (char-before) ?:)
643 t)))))
644 (setq block-end (point-marker))))
645 (let ((indentation
646 (when block-end
647 (goto-char block-end)
648 (python-util-forward-comment)
649 (current-indentation))))
650 (if indentation
651 (setq python-indent-offset indentation)
652 (message "Can't guess python-indent-offset, using defaults: %s"
653 python-indent-offset)))))))
45c138ac 654
e2d8d479
FEG
655(defun python-indent-context ()
656 "Get information on indentation context.
657Context information is returned with a cons with the form:
658 \(STATUS . START)
45c138ac
FEG
659
660Where status can be any of the following symbols:
45c138ac
FEG
661 * inside-paren: If point in between (), {} or []
662 * inside-string: If point is inside a string
663 * after-backslash: Previous line ends in a backslash
664 * after-beginning-of-block: Point is after beginning of block
665 * after-line: Point is after normal line
666 * no-indent: Point is at beginning of buffer or other special case
45c138ac
FEG
667START is the buffer position where the sexp starts."
668 (save-restriction
669 (widen)
670 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
671 (start))
672 (cons
673 (cond
69bab1de 674 ;; Beginning of buffer
19b122e4
FEG
675 ((save-excursion
676 (goto-char (line-beginning-position))
677 (bobp))
69bab1de 678 'no-indent)
45c138ac 679 ;; Inside string
2d79ec42 680 ((setq start (python-syntax-context 'string ppss))
45c138ac 681 'inside-string)
be0d5bae
FEG
682 ;; Inside a paren
683 ((setq start (python-syntax-context 'paren ppss))
684 'inside-paren)
45c138ac 685 ;; After backslash
2d79ec42
FEG
686 ((setq start (when (not (or (python-syntax-context 'string ppss)
687 (python-syntax-context 'comment ppss)))
45c138ac 688 (let ((line-beg-pos (line-beginning-position)))
6cad4c6e
FEG
689 (when (python-info-line-ends-backslash-p
690 (1- line-beg-pos))
45c138ac
FEG
691 (- line-beg-pos 2)))))
692 'after-backslash)
693 ;; After beginning of block
694 ((setq start (save-excursion
0674d3fa
FEG
695 (when (progn
696 (back-to-indentation)
697 (python-util-forward-comment -1)
698 (equal (char-before) ?:))
699 ;; Move to the first block start that's not in within
700 ;; a string, comment or paren and that's not a
701 ;; continuation line.
702 (while (and (re-search-backward
703 (python-rx block-start) nil t)
704 (or
2d79ec42 705 (python-syntax-context-type)
0674d3fa
FEG
706 (python-info-continuation-line-p))))
707 (when (looking-at (python-rx block-start))
45c138ac
FEG
708 (point-marker)))))
709 'after-beginning-of-block)
710 ;; After normal line
711 ((setq start (save-excursion
257b0017 712 (back-to-indentation)
be0d5bae 713 (skip-chars-backward (rx (or whitespace ?\n)))
bcdc27d7 714 (python-nav-beginning-of-statement)
45c138ac
FEG
715 (point-marker)))
716 'after-line)
717 ;; Do not indent
718 (t 'no-indent))
719 start))))
720
721(defun python-indent-calculate-indentation ()
722 "Calculate correct indentation offset for the current line."
723 (let* ((indentation-context (python-indent-context))
724 (context-status (car indentation-context))
725 (context-start (cdr indentation-context)))
726 (save-restriction
727 (widen)
728 (save-excursion
729 (case context-status
730 ('no-indent 0)
0674d3fa
FEG
731 ;; When point is after beginning of block just add one level
732 ;; of indentation relative to the context-start
45c138ac
FEG
733 ('after-beginning-of-block
734 (goto-char context-start)
735 (+ (current-indentation) python-indent-offset))
0674d3fa
FEG
736 ;; When after a simple line just use previous line
737 ;; indentation, in the case current line starts with a
738 ;; `python-indent-dedenters' de-indent one level.
45c138ac
FEG
739 ('after-line
740 (-
741 (save-excursion
742 (goto-char context-start)
743 (current-indentation))
744 (if (progn
745 (back-to-indentation)
746 (looking-at (regexp-opt python-indent-dedenters)))
747 python-indent-offset
748 0)))
0674d3fa
FEG
749 ;; When inside of a string, do nothing. just use the current
750 ;; indentation. XXX: perhaps it would be a good idea to
751 ;; invoke standard text indentation here
45c138ac
FEG
752 ('inside-string
753 (goto-char context-start)
754 (current-indentation))
48d1354e 755 ;; After backslash we have several possibilities.
45c138ac 756 ('after-backslash
0674d3fa
FEG
757 (cond
758 ;; Check if current line is a dot continuation. For this
759 ;; the current line must start with a dot and previous
760 ;; line must contain a dot too.
761 ((save-excursion
762 (back-to-indentation)
763 (when (looking-at "\\.")
dc4f2e53
FEG
764 ;; If after moving one line back point is inside a paren it
765 ;; needs to move back until it's not anymore
766 (while (prog2
767 (forward-line -1)
768 (and (not (bobp))
2d79ec42 769 (python-syntax-context 'paren))))
0674d3fa 770 (goto-char (line-end-position))
6cad4c6e
FEG
771 (while (and (re-search-backward
772 "\\." (line-beginning-position) t)
2d79ec42 773 (python-syntax-context-type)))
0674d3fa 774 (if (and (looking-at "\\.")
2d79ec42 775 (not (python-syntax-context-type)))
0674d3fa
FEG
776 ;; The indentation is the same column of the
777 ;; first matching dot that's not inside a
778 ;; comment, a string or a paren
779 (current-column)
780 ;; No dot found on previous line, just add another
781 ;; indentation level.
782 (+ (current-indentation) python-indent-offset)))))
783 ;; Check if prev line is a block continuation
784 ((let ((block-continuation-start
785 (python-info-block-continuation-line-p)))
786 (when block-continuation-start
787 ;; If block-continuation-start is set jump to that
788 ;; marker and use first column after the block start
789 ;; as indentation value.
790 (goto-char block-continuation-start)
791 (re-search-forward
792 (python-rx block-start (* space))
793 (line-end-position) t)
794 (current-column))))
795 ;; Check if current line is an assignment continuation
796 ((let ((assignment-continuation-start
797 (python-info-assignment-continuation-line-p)))
798 (when assignment-continuation-start
799 ;; If assignment-continuation is set jump to that
800 ;; marker and use first column after the assignment
801 ;; operator as indentation value.
802 (goto-char assignment-continuation-start)
803 (current-column))))
804 (t
805 (forward-line -1)
48d1354e 806 (goto-char (python-info-beginning-of-backslash))
0674d3fa
FEG
807 (if (save-excursion
808 (and
0674d3fa 809 (forward-line -1)
dc4f2e53 810 (goto-char
48d1354e 811 (or (python-info-beginning-of-backslash) (point)))
0674d3fa
FEG
812 (python-info-line-ends-backslash-p)))
813 ;; The two previous lines ended in a backslash so we must
814 ;; respect previous line indentation.
815 (current-indentation)
816 ;; What happens here is that we are dealing with the second
817 ;; line of a backslash continuation, in that case we just going
818 ;; to add one indentation level.
819 (+ (current-indentation) python-indent-offset)))))
820 ;; When inside a paren there's a need to handle nesting
821 ;; correctly
45c138ac 822 ('inside-paren
0674d3fa 823 (cond
48d1354e 824 ;; If current line closes the outermost open paren use the
0674d3fa
FEG
825 ;; current indentation of the context-start line.
826 ((save-excursion
827 (skip-syntax-forward "\s" (line-end-position))
828 (when (and (looking-at (regexp-opt '(")" "]" "}")))
829 (progn
830 (forward-char 1)
2d79ec42 831 (not (python-syntax-context 'paren))))
0674d3fa
FEG
832 (goto-char context-start)
833 (current-indentation))))
834 ;; If open paren is contained on a line by itself add another
835 ;; indentation level, else look for the first word after the
836 ;; opening paren and use it's column position as indentation
837 ;; level.
838 ((let* ((content-starts-in-newline)
839 (indent
840 (save-excursion
841 (if (setq content-starts-in-newline
842 (progn
843 (goto-char context-start)
844 (forward-char)
845 (save-restriction
846 (narrow-to-region
847 (line-beginning-position)
848 (line-end-position))
849 (python-util-forward-comment))
850 (looking-at "$")))
851 (+ (current-indentation) python-indent-offset)
852 (current-column)))))
853 ;; Adjustments
854 (cond
855 ;; If current line closes a nested open paren de-indent one
856 ;; level.
857 ((progn
17d13b85 858 (back-to-indentation)
0674d3fa
FEG
859 (looking-at (regexp-opt '(")" "]" "}"))))
860 (- indent python-indent-offset))
861 ;; If the line of the opening paren that wraps the current
862 ;; line starts a block add another level of indentation to
863 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
864 ((save-excursion
865 (when (and content-starts-in-newline
866 (progn
867 (goto-char context-start)
868 (back-to-indentation)
869 (looking-at (python-rx block-start))))
870 (+ indent python-indent-offset))))
871 (t indent)))))))))))
45c138ac
FEG
872
873(defun python-indent-calculate-levels ()
874 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
875 (let* ((indentation (python-indent-calculate-indentation))
876 (remainder (% indentation python-indent-offset))
877 (steps (/ (- indentation remainder) python-indent-offset)))
65e4f764 878 (setq python-indent-levels (list 0))
45c138ac 879 (dotimes (step steps)
65e4f764 880 (push (* python-indent-offset (1+ step)) python-indent-levels))
45c138ac 881 (when (not (eq 0 remainder))
65e4f764 882 (push (+ (* python-indent-offset steps) remainder) python-indent-levels))
45c138ac
FEG
883 (setq python-indent-levels (nreverse python-indent-levels))
884 (setq python-indent-current-level (1- (length python-indent-levels)))))
885
886(defun python-indent-toggle-levels ()
887 "Toggle `python-indent-current-level' over `python-indent-levels'."
888 (setq python-indent-current-level (1- python-indent-current-level))
889 (when (< python-indent-current-level 0)
890 (setq python-indent-current-level (1- (length python-indent-levels)))))
891
892(defun python-indent-line (&optional force-toggle)
893 "Internal implementation of `python-indent-line-function'.
45c138ac
FEG
894Uses the offset calculated in
895`python-indent-calculate-indentation' and available levels
e2d8d479
FEG
896indicated by the variable `python-indent-levels' to set the
897current indentation.
45c138ac
FEG
898
899When the variable `last-command' is equal to
e2d8d479
FEG
900`indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
901levels indicated in the variable `python-indent-levels' by
902setting the current level in the variable
903`python-indent-current-level'.
45c138ac
FEG
904
905When the variable `last-command' is not equal to
e2d8d479
FEG
906`indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
907possible indentation levels and saves it in the variable
908`python-indent-levels'. Afterwards it sets the variable
909`python-indent-current-level' correctly so offset is equal
910to (`nth' `python-indent-current-level' `python-indent-levels')"
095bb823
FEG
911 (or
912 (and (or (and (eq this-command 'indent-for-tab-command)
913 (eq last-command this-command))
914 force-toggle)
915 (not (equal python-indent-levels '(0)))
916 (or (python-indent-toggle-levels) t))
917 (python-indent-calculate-levels))
918 (let* ((starting-pos (point-marker))
919 (indent-ending-position
920 (+ (line-beginning-position) (current-indentation)))
921 (follow-indentation-p
922 (or (bolp)
923 (and (<= (line-beginning-position) starting-pos)
924 (>= indent-ending-position starting-pos))))
925 (next-indent (nth python-indent-current-level python-indent-levels)))
926 (unless (= next-indent (current-indentation))
927 (beginning-of-line)
928 (delete-horizontal-space)
929 (indent-to next-indent)
930 (goto-char starting-pos))
931 (and follow-indentation-p (back-to-indentation)))
cd7ab092 932 (python-info-closing-block-message))
45c138ac
FEG
933
934(defun python-indent-line-function ()
935 "`indent-line-function' for Python mode.
e2d8d479 936See `python-indent-line' for details."
45c138ac
FEG
937 (python-indent-line))
938
939(defun python-indent-dedent-line ()
e2d8d479 940 "De-indent current line."
45c138ac 941 (interactive "*")
2d79ec42 942 (when (and (not (python-syntax-comment-or-string-p))
45c138ac
FEG
943 (<= (point-marker) (save-excursion
944 (back-to-indentation)
945 (point-marker)))
946 (> (current-column) 0))
947 (python-indent-line t)
948 t))
949
950(defun python-indent-dedent-line-backspace (arg)
e2d8d479 951 "De-indent current line.
45c138ac 952Argument ARG is passed to `backward-delete-char-untabify' when
e2d8d479 953point is not in between the indentation."
45c138ac
FEG
954 (interactive "*p")
955 (when (not (python-indent-dedent-line))
956 (backward-delete-char-untabify arg)))
183f9296 957(put 'python-indent-dedent-line-backspace 'delete-selection 'supersede)
45c138ac
FEG
958
959(defun python-indent-region (start end)
960 "Indent a python region automagically.
961
962Called from a program, START and END specify the region to indent."
cb42456f
FEG
963 (let ((deactivate-mark nil))
964 (save-excursion
965 (goto-char end)
966 (setq end (point-marker))
967 (goto-char start)
968 (or (bolp) (forward-line 1))
969 (while (< (point) end)
970 (or (and (bolp) (eolp))
971 (let (word)
972 (forward-line -1)
973 (back-to-indentation)
974 (setq word (current-word))
975 (forward-line 1)
be0d5bae
FEG
976 (when (and word
977 ;; Don't mess with strings, unless it's the
978 ;; enclosing set of quotes.
979 (or (not (python-syntax-context 'string))
980 (eq
981 (syntax-after
982 (+ (1- (point))
983 (current-indentation)
984 (python-syntax-count-quotes (char-after) (point))))
985 (string-to-syntax "|"))))
cb42456f
FEG
986 (beginning-of-line)
987 (delete-horizontal-space)
988 (indent-to (python-indent-calculate-indentation)))))
989 (forward-line 1))
990 (move-marker end nil))))
45c138ac
FEG
991
992(defun python-indent-shift-left (start end &optional count)
993 "Shift lines contained in region START END by COUNT columns to the left.
e2d8d479
FEG
994COUNT defaults to `python-indent-offset'. If region isn't
995active, the current line is shifted. The shifted region includes
996the lines in which START and END lie. An error is signaled if
997any lines in the region are indented less than COUNT columns."
45c138ac
FEG
998 (interactive
999 (if mark-active
1000 (list (region-beginning) (region-end) current-prefix-arg)
1001 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
1002 (if count
1003 (setq count (prefix-numeric-value count))
1004 (setq count python-indent-offset))
1005 (when (> count 0)
cb42456f
FEG
1006 (let ((deactivate-mark nil))
1007 (save-excursion
1008 (goto-char start)
1009 (while (< (point) end)
1010 (if (and (< (current-indentation) count)
1011 (not (looking-at "[ \t]*$")))
1012 (error "Can't shift all lines enough"))
1013 (forward-line))
1014 (indent-rigidly start end (- count))))))
45c138ac
FEG
1015
1016(add-to-list 'debug-ignored-errors "^Can't shift all lines enough")
1017
1018(defun python-indent-shift-right (start end &optional count)
1019 "Shift lines contained in region START END by COUNT columns to the left.
e2d8d479
FEG
1020COUNT defaults to `python-indent-offset'. If region isn't
1021active, the current line is shifted. The shifted region includes
1022the lines in which START and END lie."
45c138ac
FEG
1023 (interactive
1024 (if mark-active
1025 (list (region-beginning) (region-end) current-prefix-arg)
1026 (list (line-beginning-position) (line-end-position) current-prefix-arg)))
cb42456f
FEG
1027 (let ((deactivate-mark nil))
1028 (if count
1029 (setq count (prefix-numeric-value count))
1030 (setq count python-indent-offset))
1031 (indent-rigidly start end count)))
45c138ac 1032
ffdb56c3 1033(defun python-indent-electric-colon (arg)
e2d8d479
FEG
1034 "Insert a colon and maybe de-indent the current line.
1035With numeric ARG, just insert that many colons. With
1036\\[universal-argument], just insert a single colon."
ffdb56c3
FEG
1037 (interactive "*P")
1038 (self-insert-command (if (not (integerp arg)) 1 arg))
c43cd8b1
FEG
1039 (when (and (not arg)
1040 (eolp)
1041 (not (equal ?: (char-after (- (point-marker) 2))))
2d79ec42 1042 (not (python-syntax-comment-or-string-p)))
c43cd8b1
FEG
1043 (let ((indentation (current-indentation))
1044 (calculated-indentation (python-indent-calculate-indentation)))
cd7ab092 1045 (python-info-closing-block-message)
c43cd8b1
FEG
1046 (when (> indentation calculated-indentation)
1047 (save-excursion
1048 (indent-line-to calculated-indentation)
cd7ab092 1049 (when (not (python-info-closing-block-message))
c43cd8b1 1050 (indent-line-to indentation)))))))
ffdb56c3
FEG
1051(put 'python-indent-electric-colon 'delete-selection t)
1052
5eae76ae
FEG
1053(defun python-indent-post-self-insert-function ()
1054 "Adjust closing paren line indentation after a char is added.
1055This function is intended to be added to the
1056`post-self-insert-hook.' If a line renders a paren alone, after
1057adding a char before it, the line will be re-indented
1058automatically if needed."
1059 (when (and (eq (char-before) last-command-event)
5eae76ae
FEG
1060 (not (bolp))
1061 (memq (char-after) '(?\) ?\] ?\})))
cd05d2a6
FEG
1062 (save-excursion
1063 (goto-char (line-beginning-position))
1064 ;; If after going to the beginning of line the point
1065 ;; is still inside a paren it's ok to do the trick
2d79ec42 1066 (when (python-syntax-context 'paren)
cd05d2a6
FEG
1067 (let ((indentation (python-indent-calculate-indentation)))
1068 (when (< (current-indentation) indentation)
1069 (indent-line-to indentation)))))))
5eae76ae 1070
45c138ac
FEG
1071\f
1072;;; Navigation
1073
0567effb 1074(defvar python-nav-beginning-of-defun-regexp
af5c1beb 1075 (python-rx line-start (* space) defun (+ space) (group symbol-name))
fc6c545e 1076 "Regexp matching class or function definition.
fc2dc7df
FEG
1077The name of the defun should be grouped so it can be retrieved
1078via `match-string'.")
45c138ac 1079
8c6f9e60 1080(defun python-nav-beginning-of-defun (&optional arg)
053a6c72 1081 "Move point to `beginning-of-defun'.
8c6f9e60
FEG
1082With positive ARG move search backwards. With negative do the
1083same but forward. When ARG is nil or 0 defaults to 1. This is
1084the main part of `python-beginning-of-defun-function'. Return
1085non-nil if point is moved to `beginning-of-defun'."
1086 (when (or (null arg) (= arg 0)) (setq arg 1))
1087 (let* ((re-search-fn (if (> arg 0)
1088 #'re-search-backward
1089 #'re-search-forward))
1090 (line-beg-pos (line-beginning-position))
1091 (line-content-start (+ line-beg-pos (current-indentation)))
1092 (pos (point-marker))
1093 (found
1094 (progn
1095 (when (and (< arg 0)
1096 (python-info-looking-at-beginning-of-defun))
1097 (end-of-line 1))
1098 (while (and (funcall re-search-fn
1099 python-nav-beginning-of-defun-regexp nil t)
2d79ec42 1100 (python-syntax-context-type)))
8c6f9e60
FEG
1101 (and (python-info-looking-at-beginning-of-defun)
1102 (or (not (= (line-number-at-pos pos)
1103 (line-number-at-pos)))
1104 (and (>= (point) line-beg-pos)
1105 (<= (point) line-content-start)
1106 (> pos line-content-start)))))))
1107 (if found
1108 (or (beginning-of-line 1) t)
1109 (and (goto-char pos) nil))))
1110
1111(defun python-beginning-of-defun-function (&optional arg)
0567effb 1112 "Move point to the beginning of def or class.
8c6f9e60
FEG
1113With positive ARG move that number of functions backwards. With
1114negative do the same but forward. When ARG is nil or 0 defaults
1115to 1. Return non-nil if point is moved to `beginning-of-defun'."
0567effb 1116 (when (or (null arg) (= arg 0)) (setq arg 1))
8c6f9e60
FEG
1117 (let ((found))
1118 (cond ((and (eq this-command 'mark-defun)
1119 (python-info-looking-at-beginning-of-defun)))
1120 (t
1121 (dotimes (i (if (> arg 0) arg (- arg)))
1122 (when (and (python-nav-beginning-of-defun arg)
1123 (not found))
1124 (setq found t)))))
1125 found))
45c138ac
FEG
1126
1127(defun python-end-of-defun-function ()
1128 "Move point to the end of def or class.
1129Returns nil if point is not in a def or class."
0567effb 1130 (interactive)
8c6f9e60
FEG
1131 (let ((beg-defun-indent))
1132 (when (or (python-info-looking-at-beginning-of-defun)
1133 (python-beginning-of-defun-function 1)
1134 (python-beginning-of-defun-function -1))
1135 (setq beg-defun-indent (current-indentation))
1136 (forward-line 1)
1137 ;; Go as forward as possible
1138 (while (and (or
1139 (python-nav-beginning-of-defun -1)
1140 (and (goto-char (point-max)) nil))
1141 (> (current-indentation) beg-defun-indent)))
1142 (beginning-of-line 1)
1143 ;; Go as backwards as possible
1144 (while (and (forward-line -1)
1145 (not (bobp))
1146 (or (not (current-word))
1147 (equal (char-after (+ (point) (current-indentation))) ?#)
1148 (<= (current-indentation) beg-defun-indent)
1149 (looking-at (python-rx decorator))
2d79ec42 1150 (python-syntax-context-type))))
8c6f9e60
FEG
1151 (forward-line 1)
1152 ;; If point falls inside a paren or string context the point is
1153 ;; forwarded at the end of it (or end of buffer if its not closed)
2d79ec42 1154 (let ((context-type (python-syntax-context-type)))
8c6f9e60
FEG
1155 (when (memq context-type '(paren string))
1156 ;; Slow but safe.
1157 (while (and (not (eobp))
2d79ec42 1158 (python-syntax-context-type))
8c6f9e60 1159 (forward-line 1)))))))
45c138ac 1160
bcdc27d7 1161(defun python-nav-beginning-of-statement ()
032d23ab 1162 "Move to start of current statement."
3697b531 1163 (interactive "^")
032d23ab 1164 (while (and (or (back-to-indentation) t)
3697b531
FEG
1165 (not (bobp))
1166 (when (or
1167 (save-excursion
1168 (forward-line -1)
1169 (python-info-line-ends-backslash-p))
2d79ec42
FEG
1170 (python-syntax-context 'string)
1171 (python-syntax-context 'paren))
8dbce54c
FEG
1172 (forward-line -1))))
1173 (point-marker))
3697b531 1174
bcdc27d7 1175(defun python-nav-end-of-statement ()
032d23ab 1176 "Move to end of current statement."
3697b531
FEG
1177 (interactive "^")
1178 (while (and (goto-char (line-end-position))
1179 (not (eobp))
1180 (when (or
1181 (python-info-line-ends-backslash-p)
2d79ec42
FEG
1182 (python-syntax-context 'string)
1183 (python-syntax-context 'paren))
8dbce54c
FEG
1184 (forward-line 1))))
1185 (point-marker))
3697b531 1186
032d23ab
FEG
1187(defun python-nav-backward-statement (&optional arg)
1188 "Move backward to previous statement.
1189With ARG, repeat. See `python-nav-forward-statement'."
9fff1858
FEG
1190 (interactive "^p")
1191 (or arg (setq arg 1))
032d23ab 1192 (python-nav-forward-statement (- arg)))
9fff1858 1193
032d23ab
FEG
1194(defun python-nav-forward-statement (&optional arg)
1195 "Move forward to next statement.
1196With ARG, repeat. With negative argument, move ARG times
1197backward to previous statement."
9fff1858
FEG
1198 (interactive "^p")
1199 (or arg (setq arg 1))
1200 (while (> arg 0)
bcdc27d7 1201 (python-nav-end-of-statement)
0674d3fa 1202 (python-util-forward-comment)
bcdc27d7 1203 (python-nav-beginning-of-statement)
9fff1858
FEG
1204 (setq arg (1- arg)))
1205 (while (< arg 0)
bcdc27d7 1206 (python-nav-beginning-of-statement)
0674d3fa 1207 (python-util-forward-comment -1)
bcdc27d7 1208 (python-nav-beginning-of-statement)
032d23ab
FEG
1209 (setq arg (1+ arg))))
1210
bcdc27d7 1211(defun python-nav-beginning-of-block ()
032d23ab
FEG
1212 "Move to start of current block."
1213 (interactive "^")
1214 (let ((starting-pos (point))
1215 (block-regexp (python-rx
1216 line-start (* whitespace) block-start)))
1217 (if (progn
bcdc27d7 1218 (python-nav-beginning-of-statement)
032d23ab
FEG
1219 (looking-at (python-rx block-start)))
1220 (point-marker)
1221 ;; Go to first line beginning a statement
1222 (while (and (not (bobp))
bcdc27d7 1223 (or (and (python-nav-beginning-of-statement) nil)
032d23ab
FEG
1224 (python-info-current-line-comment-p)
1225 (python-info-current-line-empty-p)))
1226 (forward-line -1))
1227 (let ((block-matching-indent
1228 (- (current-indentation) python-indent-offset)))
1229 (while
1230 (and (python-nav-backward-block)
1231 (> (current-indentation) block-matching-indent)))
1232 (if (and (looking-at (python-rx block-start))
1233 (= (current-indentation) block-matching-indent))
1234 (point-marker)
1235 (and (goto-char starting-pos) nil))))))
1236
bcdc27d7 1237(defun python-nav-end-of-block ()
032d23ab
FEG
1238 "Move to end of current block."
1239 (interactive "^")
bcdc27d7 1240 (when (python-nav-beginning-of-block)
032d23ab 1241 (let ((block-indentation (current-indentation)))
bcdc27d7 1242 (python-nav-end-of-statement)
032d23ab
FEG
1243 (while (and (forward-line 1)
1244 (not (eobp))
1245 (or (and (> (current-indentation) block-indentation)
bcdc27d7 1246 (or (python-nav-end-of-statement) t))
032d23ab
FEG
1247 (python-info-current-line-comment-p)
1248 (python-info-current-line-empty-p))))
1249 (python-util-forward-comment -1)
1250 (point-marker))))
1251
1252(defun python-nav-backward-block (&optional arg)
1253 "Move backward to previous block of code.
1254With ARG, repeat. See `python-nav-forward-block'."
1255 (interactive "^p")
1256 (or arg (setq arg 1))
1257 (python-nav-forward-block (- arg)))
1258
1259(defun python-nav-forward-block (&optional arg)
1260 "Move forward to next block of code.
1261With ARG, repeat. With negative argument, move ARG times
1262backward to previous block."
1263 (interactive "^p")
1264 (or arg (setq arg 1))
1265 (let ((block-start-regexp
1266 (python-rx line-start (* whitespace) block-start))
1267 (starting-pos (point)))
1268 (while (> arg 0)
bcdc27d7 1269 (python-nav-end-of-statement)
032d23ab
FEG
1270 (while (and
1271 (re-search-forward block-start-regexp nil t)
2d79ec42 1272 (python-syntax-context-type)))
032d23ab
FEG
1273 (setq arg (1- arg)))
1274 (while (< arg 0)
bcdc27d7 1275 (python-nav-beginning-of-statement)
032d23ab
FEG
1276 (while (and
1277 (re-search-backward block-start-regexp nil t)
2d79ec42 1278 (python-syntax-context-type)))
032d23ab 1279 (setq arg (1+ arg)))
bcdc27d7 1280 (python-nav-beginning-of-statement)
032d23ab
FEG
1281 (if (not (looking-at (python-rx block-start)))
1282 (and (goto-char starting-pos) nil)
1283 (and (not (= (point) starting-pos)) (point-marker)))))
1284
489af14f
FEG
1285(defun python-nav-lisp-forward-sexp-safe (&optional arg)
1286 "Safe version of standard `forward-sexp'.
1287When ARG > 0 move forward, else if ARG is < 0."
1288 (or arg (setq arg 1))
1289 (let ((forward-sexp-function nil)
1290 (paren-regexp
1291 (if (> arg 0) (python-rx close-paren) (python-rx open-paren)))
1292 (search-fn
1293 (if (> arg 0) #'re-search-forward #'re-search-backward)))
1294 (condition-case nil
1295 (forward-sexp arg)
1296 (error
1297 (while (and (funcall search-fn paren-regexp nil t)
1298 (python-syntax-context 'paren)))))))
1299
8dbce54c
FEG
1300(defun python-nav--forward-sexp (&optional dir)
1301 "Move to forward sexp.
1302With positive Optional argument DIR direction move forward, else
1303backwards."
1304 (setq dir (or dir 1))
1305 (unless (= dir 0)
1306 (let* ((forward-p (if (> dir 0)
1307 (and (setq dir 1) t)
1308 (and (setq dir -1) nil)))
1309 (re-search-fn (if forward-p
1310 're-search-forward
1311 're-search-backward))
1312 (context-type (python-syntax-context-type)))
1313 (cond
1314 ((eq context-type 'string)
1315 ;; Inside of a string, get out of it.
1316 (while (and (funcall re-search-fn "[\"']" nil t)
1317 (python-syntax-context 'string))))
1318 ((eq context-type 'comment)
1319 ;; Inside of a comment, just move forward.
1320 (python-util-forward-comment dir))
1321 ((or (eq context-type 'paren)
1322 (and forward-p (looking-at (python-rx open-paren)))
1323 (and (not forward-p)
1324 (eq (syntax-class (syntax-after (1- (point))))
1325 (car (string-to-syntax ")")))))
1326 ;; Inside a paren or looking at it, lisp knows what to do.
1327 (python-nav-lisp-forward-sexp-safe dir))
1328 (t
1329 ;; This part handles the lispy feel of
1330 ;; `python-nav-forward-sexp'. Knowing everything about the
1331 ;; current context and the context of the next sexp tries to
1332 ;; follow the lisp sexp motion commands in a symmetric manner.
1333 (let* ((context
1334 (cond
1335 ((python-info-beginning-of-block-p) 'block-start)
1336 ((python-info-end-of-block-p) 'block-end)
1337 ((python-info-beginning-of-statement-p) 'statement-start)
1338 ((python-info-end-of-statement-p) 'statement-end)))
1339 (next-sexp-pos
1340 (save-excursion
1341 (python-nav-lisp-forward-sexp-safe dir)
1342 (point)))
1343 (next-sexp-context
1344 (save-excursion
1345 (goto-char next-sexp-pos)
1346 (cond
1347 ((python-info-beginning-of-block-p) 'block-start)
1348 ((python-info-end-of-block-p) 'block-end)
1349 ((python-info-beginning-of-statement-p) 'statement-start)
1350 ((python-info-end-of-statement-p) 'statement-end)
1351 ((python-info-statement-starts-block-p) 'starts-block)
1352 ((python-info-statement-ends-block-p) 'ends-block)))))
1353 (if forward-p
1354 (cond ((and (not (eobp))
1355 (python-info-current-line-empty-p))
1356 (python-util-forward-comment dir)
1357 (python-nav--forward-sexp dir))
1358 ((eq context 'block-start)
1359 (python-nav-end-of-block))
1360 ((eq context 'statement-start)
1361 (python-nav-end-of-statement))
1362 ((and (memq context '(statement-end block-end))
1363 (eq next-sexp-context 'ends-block))
1364 (goto-char next-sexp-pos)
1365 (python-nav-end-of-block))
1366 ((and (memq context '(statement-end block-end))
1367 (eq next-sexp-context 'starts-block))
1368 (goto-char next-sexp-pos)
1369 (python-nav-end-of-block))
1370 ((memq context '(statement-end block-end))
1371 (goto-char next-sexp-pos)
1372 (python-nav-end-of-statement))
1373 (t (goto-char next-sexp-pos)))
1374 (cond ((and (not (bobp))
1375 (python-info-current-line-empty-p))
1376 (python-util-forward-comment dir)
1377 (python-nav--forward-sexp dir))
1378 ((eq context 'block-end)
1379 (python-nav-beginning-of-block))
1380 ((eq context 'statement-end)
1381 (python-nav-beginning-of-statement))
1382 ((and (memq context '(statement-start block-start))
1383 (eq next-sexp-context 'starts-block))
1384 (goto-char next-sexp-pos)
1385 (python-nav-beginning-of-block))
1386 ((and (memq context '(statement-start block-start))
1387 (eq next-sexp-context 'ends-block))
1388 (goto-char next-sexp-pos)
1389 (python-nav-beginning-of-block))
1390 ((memq context '(statement-start block-start))
1391 (goto-char next-sexp-pos)
1392 (python-nav-beginning-of-statement))
1393 (t (goto-char next-sexp-pos))))))))))
489af14f
FEG
1394
1395(defun python-nav--backward-sexp ()
1396 "Move to backward sexp."
8dbce54c 1397 (python-nav--forward-sexp -1))
489af14f
FEG
1398
1399(defun python-nav-forward-sexp (&optional arg)
032d23ab
FEG
1400 "Move forward across one block of code.
1401With ARG, do it that many times. Negative arg -N means
1402move backward N times."
1403 (interactive "^p")
1404 (or arg (setq arg 1))
1405 (while (> arg 0)
489af14f
FEG
1406 (python-nav--forward-sexp)
1407 (setq arg (1- arg)))
032d23ab 1408 (while (< arg 0)
489af14f 1409 (python-nav--backward-sexp)
9fff1858
FEG
1410 (setq arg (1+ arg))))
1411
45c138ac
FEG
1412\f
1413;;; Shell integration
1414
0f55249e
FEG
1415(defcustom python-shell-buffer-name "Python"
1416 "Default buffer name for Python interpreter."
1417 :type 'string
1418 :group 'python
1419 :safe 'stringp)
45c138ac
FEG
1420
1421(defcustom python-shell-interpreter "python"
1422 "Default Python interpreter for shell."
45c138ac 1423 :type 'string
c4b155cb 1424 :group 'python)
45c138ac 1425
0f55249e
FEG
1426(defcustom python-shell-internal-buffer-name "Python Internal"
1427 "Default buffer name for the Internal Python interpreter."
1428 :type 'string
1429 :group 'python
1430 :safe 'stringp)
1fe1b5aa 1431
45c138ac
FEG
1432(defcustom python-shell-interpreter-args "-i"
1433 "Default arguments for the Python interpreter."
45c138ac 1434 :type 'string
c4b155cb 1435 :group 'python)
45c138ac
FEG
1436
1437(defcustom python-shell-prompt-regexp ">>> "
e2d8d479
FEG
1438 "Regular Expression matching top\-level input prompt of python shell.
1439It should not contain a caret (^) at the beginning."
45c138ac
FEG
1440 :type 'string
1441 :group 'python
1442 :safe 'stringp)
1443
1444(defcustom python-shell-prompt-block-regexp "[.][.][.] "
e2d8d479
FEG
1445 "Regular Expression matching block input prompt of python shell.
1446It should not contain a caret (^) at the beginning."
45c138ac
FEG
1447 :type 'string
1448 :group 'python
1449 :safe 'stringp)
1450
0f55249e 1451(defcustom python-shell-prompt-output-regexp ""
e2d8d479
FEG
1452 "Regular Expression matching output prompt of python shell.
1453It should not contain a caret (^) at the beginning."
62feb915
FEG
1454 :type 'string
1455 :group 'python
1456 :safe 'stringp)
1457
45c138ac 1458(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
e2d8d479
FEG
1459 "Regular Expression matching pdb input prompt of python shell.
1460It should not contain a caret (^) at the beginning."
45c138ac
FEG
1461 :type 'string
1462 :group 'python
1463 :safe 'stringp)
1464
a7a6d8ff 1465(defcustom python-shell-enable-font-lock t
b4b661d8
DD
1466 "Should syntax highlighting be enabled in the python shell buffer?
1467Restart the python shell after changing this variable for it to take effect."
1468 :type 'boolean
1469 :group 'python
1470 :safe 'booleanp)
1471
66bbb27f 1472(defcustom python-shell-process-environment nil
307bd2e8
FEG
1473 "List of environment variables for Python shell.
1474This variable follows the same rules as `process-environment'
66bbb27f
FEG
1475since it merges with it before the process creation routines are
1476called. When this variable is nil, the Python shell is run with
307bd2e8 1477the default `process-environment'."
66bbb27f
FEG
1478 :type '(repeat string)
1479 :group 'python
1480 :safe 'listp)
1481
929036b4
FEG
1482(defcustom python-shell-extra-pythonpaths nil
1483 "List of extra pythonpaths for Python shell.
1484The values of this variable are added to the existing value of
1485PYTHONPATH in the `process-environment' variable."
1486 :type '(repeat string)
1487 :group 'python
1488 :safe 'listp)
1489
66bbb27f
FEG
1490(defcustom python-shell-exec-path nil
1491 "List of path to search for binaries.
1492This variable follows the same rules as `exec-path' since it
1493merges with it before the process creation routines are called.
1494When this variable is nil, the Python shell is run with the
1495default `exec-path'."
1496 :type '(repeat string)
1497 :group 'python
1498 :safe 'listp)
1499
64348c32
FEG
1500(defcustom python-shell-virtualenv-path nil
1501 "Path to virtualenv root.
1502This variable, when set to a string, makes the values stored in
1503`python-shell-process-environment' and `python-shell-exec-path'
1504to be modified properly so shells are started with the specified
1505virtualenv."
1506 :type 'string
1507 :group 'python
1508 :safe 'stringp)
1509
c0428ba0
FEG
1510(defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1511 python-ffap-setup-code
1512 python-eldoc-setup-code)
279c9272 1513 "List of code run by `python-shell-send-setup-codes'."
c0428ba0
FEG
1514 :type '(repeat symbol)
1515 :group 'python
1516 :safe 'listp)
1517
45c138ac
FEG
1518(defcustom python-shell-compilation-regexp-alist
1519 `((,(rx line-start (1+ (any " \t")) "File \""
6cad4c6e
FEG
1520 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1521 "\", line " (group (1+ digit)))
45c138ac
FEG
1522 1 2)
1523 (,(rx " in file " (group (1+ not-newline)) " on line "
6cad4c6e 1524 (group (1+ digit)))
45c138ac
FEG
1525 1 2)
1526 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
6cad4c6e 1527 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
45c138ac
FEG
1528 1 2))
1529 "`compilation-error-regexp-alist' for inferior Python."
1530 :type '(alist string)
1531 :group 'python)
1532
1533(defun python-shell-get-process-name (dedicated)
e37a4551 1534 "Calculate the appropriate process name for inferior Python process.
45c138ac
FEG
1535If DEDICATED is t and the variable `buffer-file-name' is non-nil
1536returns a string with the form
1537`python-shell-buffer-name'[variable `buffer-file-name'] else
1530c98e 1538returns the value of `python-shell-buffer-name'."
45c138ac
FEG
1539 (let ((process-name
1540 (if (and dedicated
1541 buffer-file-name)
1542 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1543 (format "%s" python-shell-buffer-name))))
45c138ac
FEG
1544 process-name))
1545
1fe1b5aa 1546(defun python-shell-internal-get-process-name ()
e37a4551 1547 "Calculate the appropriate process name for Internal Python process.
1fe1b5aa
FEG
1548The name is calculated from `python-shell-global-buffer-name' and
1549a hash of all relevant global shell settings in order to ensure
1550uniqueness for different types of configurations."
1551 (format "%s [%s]"
1552 python-shell-internal-buffer-name
1553 (md5
1554 (concat
1555 (python-shell-parse-command)
279c9272
FEG
1556 python-shell-prompt-regexp
1557 python-shell-prompt-block-regexp
1558 python-shell-prompt-output-regexp
1fe1b5aa 1559 (mapconcat #'symbol-value python-shell-setup-codes "")
2bdce388
FEG
1560 (mapconcat #'identity python-shell-process-environment "")
1561 (mapconcat #'identity python-shell-extra-pythonpaths "")
1562 (mapconcat #'identity python-shell-exec-path "")
64348c32 1563 (or python-shell-virtualenv-path "")
2bdce388 1564 (mapconcat #'identity python-shell-exec-path "")))))
1fe1b5aa 1565
45c138ac 1566(defun python-shell-parse-command ()
e2d8d479 1567 "Calculate the string used to execute the inferior Python process."
45c138ac
FEG
1568 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1569
307bd2e8
FEG
1570(defun python-shell-calculate-process-environment ()
1571 "Calculate process environment given `python-shell-virtualenv-path'."
40417cb3
FEG
1572 (let ((process-environment (append
1573 python-shell-process-environment
1574 process-environment nil))
64348c32
FEG
1575 (virtualenv (if python-shell-virtualenv-path
1576 (directory-file-name python-shell-virtualenv-path)
1577 nil)))
929036b4
FEG
1578 (when python-shell-extra-pythonpaths
1579 (setenv "PYTHONPATH"
1580 (format "%s%s%s"
1581 (mapconcat 'identity
1582 python-shell-extra-pythonpaths
1583 path-separator)
1584 path-separator
1585 (or (getenv "PYTHONPATH") ""))))
64348c32 1586 (if (not virtualenv)
40417cb3
FEG
1587 process-environment
1588 (setenv "PYTHONHOME" nil)
1589 (setenv "PATH" (format "%s/bin%s%s"
929036b4
FEG
1590 virtualenv path-separator
1591 (or (getenv "PATH") "")))
40417cb3
FEG
1592 (setenv "VIRTUAL_ENV" virtualenv))
1593 process-environment))
64348c32
FEG
1594
1595(defun python-shell-calculate-exec-path ()
1596 "Calculate exec path given `python-shell-virtualenv-path'."
40417cb3
FEG
1597 (let ((path (append python-shell-exec-path
1598 exec-path nil)))
64348c32
FEG
1599 (if (not python-shell-virtualenv-path)
1600 path
1601 (cons (format "%s/bin"
1602 (directory-file-name python-shell-virtualenv-path))
1603 path))))
1604
45c138ac
FEG
1605(defun python-comint-output-filter-function (output)
1606 "Hook run after content is put into comint buffer.
1607OUTPUT is a string with the contents of the buffer."
1608 (ansi-color-filter-apply output))
1609
f27c99dc
FEG
1610(defvar python-shell--parent-buffer nil)
1611
a5b773c4
FEG
1612(defvar python-shell-output-syntax-table
1613 (let ((table (make-syntax-table python-dotty-syntax-table)))
1614 (modify-syntax-entry ?\' "." table)
1615 (modify-syntax-entry ?\" "." table)
1616 (modify-syntax-entry ?\( "." table)
1617 (modify-syntax-entry ?\[ "." table)
1618 (modify-syntax-entry ?\{ "." table)
1619 (modify-syntax-entry ?\) "." table)
1620 (modify-syntax-entry ?\] "." table)
1621 (modify-syntax-entry ?\} "." table)
1622 table)
1623 "Syntax table for shell output.
1624It makes parens and quotes be treated as punctuation chars.")
1625
45c138ac 1626(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
62feb915 1627 "Major mode for Python inferior process.
e2d8d479
FEG
1628Runs a Python interpreter as a subprocess of Emacs, with Python
1629I/O through an Emacs buffer. Variables
1630`python-shell-interpreter' and `python-shell-interpreter-args'
1631controls which Python interpreter is run. Variables
1632`python-shell-prompt-regexp',
1633`python-shell-prompt-output-regexp',
1634`python-shell-prompt-block-regexp',
a7a6d8ff 1635`python-shell-enable-font-lock',
e2d8d479 1636`python-shell-completion-setup-code',
9399498e 1637`python-shell-completion-string-code',
f6b59cd1 1638`python-shell-completion-module-string-code',
9399498e
FEG
1639`python-eldoc-setup-code', `python-eldoc-string-code',
1640`python-ffap-setup-code' and `python-ffap-string-code' can
1641customize this mode for different Python interpreters.
e2d8d479
FEG
1642
1643You can also add additional setup code to be run at
1644initialization of the interpreter via `python-shell-setup-codes'
1645variable.
1646
1647\(Type \\[describe-mode] in the process buffer for a list of commands.)"
f27c99dc
FEG
1648 (and python-shell--parent-buffer
1649 (python-util-clone-local-variables python-shell--parent-buffer))
1650 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1651 python-shell-prompt-regexp
1652 python-shell-prompt-block-regexp
1653 python-shell-prompt-pdb-regexp))
45c138ac 1654 (setq mode-line-process '(":%s"))
45c138ac
FEG
1655 (make-local-variable 'comint-output-filter-functions)
1656 (add-hook 'comint-output-filter-functions
1657 'python-comint-output-filter-function)
1658 (add-hook 'comint-output-filter-functions
1659 'python-pdbtrack-comint-output-filter-function)
1660 (set (make-local-variable 'compilation-error-regexp-alist)
1661 python-shell-compilation-regexp-alist)
ed0eb594
FEG
1662 (define-key inferior-python-mode-map [remap complete-symbol]
1663 'completion-at-point)
1664 (add-hook 'completion-at-point-functions
1665 'python-shell-completion-complete-at-point nil 'local)
62feb915
FEG
1666 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1667 'python-shell-completion-complete-at-point)
aa81af71 1668 (define-key inferior-python-mode-map "\t"
62feb915 1669 'python-shell-completion-complete-or-indent)
e0cc4efa
FEG
1670 (make-local-variable 'python-pdbtrack-buffers-to-kill)
1671 (make-local-variable 'python-pdbtrack-tracked-buffer)
1672 (make-local-variable 'python-shell-internal-last-output)
a7a6d8ff 1673 (when python-shell-enable-font-lock
a5b773c4 1674 (set-syntax-table python-mode-syntax-table)
aeadd9a4
FEG
1675 (set (make-local-variable 'font-lock-defaults)
1676 '(python-font-lock-keywords nil nil nil nil))
1677 (set (make-local-variable 'syntax-propertize-function)
a5b773c4
FEG
1678 (syntax-propertize-rules
1679 (comint-prompt-regexp
1680 (0 (ignore
1681 (put-text-property
1682 comint-last-input-start end 'syntax-table
1683 python-shell-output-syntax-table)
1684 (font-lock-unfontify-region comint-last-input-start end))))
1685 ((python-rx string-delimiter)
1686 (0 (ignore
1687 (and (not (eq (get-text-property start 'field) 'output))
1688 (python-syntax-stringify))))))))
45c138ac
FEG
1689 (compilation-shell-minor-mode 1))
1690
ba7b0154 1691(defun python-shell-make-comint (cmd proc-name &optional pop internal)
77afb61a 1692 "Create a python shell comint buffer.
96eeb83a 1693CMD is the python command to be executed and PROC-NAME is the
77afb61a 1694process name the comint buffer will get. After the comint buffer
ba7b0154
FEG
1695is created the `inferior-python-mode' is activated. When
1696optional argument POP is non-nil the buffer is shown. When
1697optional argument INTERNAL is non-nil this process is run on a
1698buffer with a name that starts with a space, following the Emacs
1699convention for temporary/internal buffers, and also makes sure
1700the user is not queried for confirmation when the process is
1701killed."
77afb61a 1702 (save-excursion
ba7b0154
FEG
1703 (let* ((proc-buffer-name
1704 (format (if (not internal) "*%s*" " *%s*") proc-name))
307bd2e8 1705 (process-environment (python-shell-calculate-process-environment))
77afb61a
FEG
1706 (exec-path (python-shell-calculate-exec-path)))
1707 (when (not (comint-check-proc proc-buffer-name))
96eeb83a 1708 (let* ((cmdlist (split-string-and-unquote cmd))
ba7b0154
FEG
1709 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1710 (car cmdlist) nil (cdr cmdlist)))
f27c99dc 1711 (python-shell--parent-buffer (current-buffer))
ba7b0154 1712 (process (get-buffer-process buffer)))
96eeb83a 1713 (with-current-buffer buffer
f27c99dc 1714 (inferior-python-mode))
ba7b0154
FEG
1715 (accept-process-output process)
1716 (and pop (pop-to-buffer buffer t))
1717 (and internal (set-process-query-on-exit-flag process nil))))
a0686d71 1718 proc-buffer-name)))
77afb61a 1719
a90dfb95
FEG
1720;;;###autoload
1721(defun run-python (cmd &optional dedicated show)
45c138ac 1722 "Run an inferior Python process.
e2d8d479
FEG
1723Input and output via buffer named after
1724`python-shell-buffer-name'. If there is a process already
1725running in that buffer, just switch to it.
a90dfb95
FEG
1726
1727With argument, allows you to define CMD so you can edit the
1728command used to call the interpreter and define DEDICATED, so a
1729dedicated process for the current buffer is open. When numeric
1730prefix arg is other than 0 or 4 do not SHOW.
1731
1732Runs the hook `inferior-python-mode-hook' (after the
1733`comint-mode-hook' is run). \(Type \\[describe-mode] in the
1734process buffer for a list of commands.)"
45c138ac
FEG
1735 (interactive
1736 (if current-prefix-arg
1737 (list
a90dfb95 1738 (read-string "Run Python: " (python-shell-parse-command))
45c138ac 1739 (y-or-n-p "Make dedicated process? ")
a90dfb95
FEG
1740 (= (prefix-numeric-value current-prefix-arg) 4))
1741 (list (python-shell-parse-command) nil t)))
1742 (python-shell-make-comint
1743 cmd (python-shell-get-process-name dedicated) show)
45c138ac
FEG
1744 dedicated)
1745
1fe1b5aa
FEG
1746(defun run-python-internal ()
1747 "Run an inferior Internal Python process.
1748Input and output via buffer named after
1749`python-shell-internal-buffer-name' and what
0d49da68
FEG
1750`python-shell-internal-get-process-name' returns.
1751
1752This new kind of shell is intended to be used for generic
1753communication related to defined configurations, the main
1754difference with global or dedicated shells is that these ones are
1755attached to a configuration, not a buffer. This means that can
1756be used for example to retrieve the sys.path and other stuff,
1757without messing with user shells. Note that
1758`python-shell-enable-font-lock' and `inferior-python-mode-hook'
1759are set to nil for these shells, so setup codes are not sent at
1760startup."
1761 (let ((python-shell-enable-font-lock nil)
1762 (inferior-python-mode-hook nil))
ba7b0154
FEG
1763 (get-buffer-process
1764 (python-shell-make-comint
1765 (python-shell-parse-command)
1766 (python-shell-internal-get-process-name) nil t))))
1fe1b5aa 1767
45c138ac
FEG
1768(defun python-shell-get-process ()
1769 "Get inferior Python process for current buffer and return it."
1770 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1771 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1772 (global-proc-name (python-shell-get-process-name nil))
1773 (global-proc-buffer-name (format "*%s*" global-proc-name))
1774 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1775 (global-running (comint-check-proc global-proc-buffer-name)))
1776 ;; Always prefer dedicated
1777 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1778 (and global-running global-proc-buffer-name)))))
1779
1780(defun python-shell-get-or-create-process ()
1781 "Get or create an inferior Python process for current buffer and return it."
035c45e3 1782 (let* ((dedicated-proc-name (python-shell-get-process-name t))
45c138ac
FEG
1783 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1784 (global-proc-name (python-shell-get-process-name nil))
1785 (global-proc-buffer-name (format "*%s*" global-proc-name))
1786 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1787 (global-running (comint-check-proc global-proc-buffer-name))
a90dfb95 1788 (current-prefix-arg 16))
45c138ac
FEG
1789 (when (and (not dedicated-running) (not global-running))
1790 (if (call-interactively 'run-python)
1791 (setq dedicated-running t)
1792 (setq global-running t)))
1793 ;; Always prefer dedicated
1794 (get-buffer-process (if dedicated-running
1795 dedicated-proc-buffer-name
1796 global-proc-buffer-name))))
1797
722c985b
FEG
1798(defvar python-shell-internal-buffer nil
1799 "Current internal shell buffer for the current buffer.
1800This is really not necessary at all for the code to work but it's
1801there for compatibility with CEDET.")
722c985b 1802
0d49da68
FEG
1803(defvar python-shell-internal-last-output nil
1804 "Last output captured by the internal shell.
1805This is really not necessary at all for the code to work but it's
1806there for compatibility with CEDET.")
0d49da68 1807
1fe1b5aa
FEG
1808(defun python-shell-internal-get-or-create-process ()
1809 "Get or create an inferior Internal Python process."
1810 (let* ((proc-name (python-shell-internal-get-process-name))
ba7b0154 1811 (proc-buffer-name (format " *%s*" proc-name)))
0d49da68
FEG
1812 (when (not (process-live-p proc-name))
1813 (run-python-internal)
1814 (setq python-shell-internal-buffer proc-buffer-name)
1815 ;; XXX: Why is this `sit-for' needed?
1816 ;; `python-shell-make-comint' calls `accept-process-output'
1817 ;; already but it is not helping to get proper output on
1818 ;; 'gnu/linux when the internal shell process is not running and
1819 ;; a call to `python-shell-internal-send-string' is issued.
1820 (sit-for 0.1 t))
1fe1b5aa
FEG
1821 (get-buffer-process proc-buffer-name)))
1822
722c985b 1823(define-obsolete-function-alias
2a1e2476 1824 'python-proc 'python-shell-internal-get-or-create-process "24.3")
722c985b
FEG
1825
1826(define-obsolete-variable-alias
2a1e2476 1827 'python-buffer 'python-shell-internal-buffer "24.3")
722c985b 1828
0d49da68 1829(define-obsolete-variable-alias
2a1e2476 1830 'python-preoutput-result 'python-shell-internal-last-output "24.3")
0d49da68 1831
9ce938be
FEG
1832(defun python-shell-send-string (string &optional process msg)
1833 "Send STRING to inferior Python PROCESS.
1834When MSG is non-nil messages the first line of STRING."
45c138ac 1835 (interactive "sPython command: ")
9ce938be
FEG
1836 (let ((process (or process (python-shell-get-or-create-process)))
1837 (lines (split-string string "\n" t)))
925411b4 1838 (and msg (message "Sent: %s..." (nth 0 lines)))
9ce938be 1839 (if (> (length lines) 1)
9dd40b00
MM
1840 (let* ((temporary-file-directory
1841 (if (file-remote-p default-directory)
1842 (concat (file-remote-p default-directory) "/tmp")
1843 temporary-file-directory))
1844 (temp-file-name (make-temp-file "py"))
9ce938be
FEG
1845 (file-name (or (buffer-file-name) temp-file-name)))
1846 (with-temp-file temp-file-name
1847 (insert string)
1848 (delete-trailing-whitespace))
1849 (python-shell-send-file file-name process temp-file-name))
1850 (comint-send-string process string)
1851 (when (or (not (string-match "\n$" string))
1852 (string-match "\n[ \t].*\n?$" string))
1853 (comint-send-string process "\n")))))
1854
08f18c3d
FEG
1855(defvar python-shell-output-filter-in-progress nil)
1856(defvar python-shell-output-filter-buffer nil)
1857
1858(defun python-shell-output-filter (string)
1859 "Filter used in `python-shell-send-string-no-output' to grab output.
1860STRING is the output received to this point from the process.
1861This filter saves received output from the process in
1862`python-shell-output-filter-buffer' and stops receiving it after
1863detecting a prompt at the end of the buffer."
1864 (setq
1865 string (ansi-color-filter-apply string)
1866 python-shell-output-filter-buffer
1867 (concat python-shell-output-filter-buffer string))
1868 (when (string-match
1869 (format "\n\\(?:%s\\|%s\\|%s\\)$"
1870 python-shell-prompt-regexp
1871 python-shell-prompt-block-regexp
1872 python-shell-prompt-pdb-regexp)
1873 python-shell-output-filter-buffer)
1874 ;; Output ends when `python-shell-output-filter-buffer' contains
1875 ;; the prompt attached at the end of it.
1876 (setq python-shell-output-filter-in-progress nil
1877 python-shell-output-filter-buffer
1878 (substring python-shell-output-filter-buffer
1879 0 (match-beginning 0)))
1880 (when (and (> (length python-shell-prompt-output-regexp) 0)
1881 (string-match (concat "^" python-shell-prompt-output-regexp)
1882 python-shell-output-filter-buffer))
1883 ;; Some shells, like iPython might append a prompt before the
1884 ;; output, clean that.
1885 (setq python-shell-output-filter-buffer
1886 (substring python-shell-output-filter-buffer (match-end 0)))))
1887 "")
0478776b 1888
9ce938be
FEG
1889(defun python-shell-send-string-no-output (string &optional process msg)
1890 "Send STRING to PROCESS and inhibit output.
e2d8d479
FEG
1891When MSG is non-nil messages the first line of STRING. Return
1892the output."
0478776b
FEG
1893 (let ((process (or process (python-shell-get-or-create-process)))
1894 (comint-preoutput-filter-functions
08f18c3d
FEG
1895 '(python-shell-output-filter))
1896 (python-shell-output-filter-in-progress t)
0478776b 1897 (inhibit-quit t))
191da00e
FEG
1898 (or
1899 (with-local-quit
1900 (python-shell-send-string string process msg)
08f18c3d
FEG
1901 (while python-shell-output-filter-in-progress
1902 ;; `python-shell-output-filter' takes care of setting
1903 ;; `python-shell-output-filter-in-progress' to NIL after it
1904 ;; detects end of output.
0478776b
FEG
1905 (accept-process-output process))
1906 (prog1
08f18c3d
FEG
1907 python-shell-output-filter-buffer
1908 (setq python-shell-output-filter-buffer 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
fc345011 2276 :group 'python)
c2cb97ae
FEG
2277
2278(defcustom python-fill-string-function 'python-fill-string
2279 "Function to fill strings.
2280This is the function used by `python-fill-paragraph-function' to
2281fill strings."
2282 :type 'symbol
fc345011 2283 :group 'python)
c2cb97ae
FEG
2284
2285(defcustom python-fill-decorator-function 'python-fill-decorator
2286 "Function to fill decorators.
2287This is the function used by `python-fill-paragraph-function' to
2288fill decorators."
2289 :type 'symbol
fc345011 2290 :group 'python)
c2cb97ae
FEG
2291
2292(defcustom python-fill-paren-function 'python-fill-paren
2293 "Function to fill parens.
2294This is the function used by `python-fill-paragraph-function' to
2295fill parens."
2296 :type 'symbol
fc345011
FEG
2297 :group 'python)
2298
7fa36ccb 2299(defcustom python-fill-docstring-style 'pep-257
fc345011
FEG
2300 "Style used to fill docstrings.
2301This affects `python-fill-string' behavior with regards to
2302triple quotes positioning.
2303
7fa36ccb
FEG
2304Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2305SYMMETRIC, and NIL. A value of NIL won't care about quotes
2306position and will treat docstrings a normal string, any other
2307value may result in one of the following docstring styles:
fc345011
FEG
2308
2309DJANGO:
2310
2311 \"\"\"
2312 Process foo, return bar.
2313 \"\"\"
2314
2315 \"\"\"
2316 Process foo, return bar.
2317
2318 If processing fails throw ProcessingError.
2319 \"\"\"
2320
7fa36ccb
FEG
2321ONETWO:
2322
2323 \"\"\"Process foo, return bar.\"\"\"
2324
2325 \"\"\"
2326 Process foo, return bar.
2327
2328 If processing fails throw ProcessingError.
2329
2330 \"\"\"
2331
fc345011
FEG
2332PEP-257:
2333
2334 \"\"\"Process foo, return bar.\"\"\"
2335
2336 \"\"\"Process foo, return bar.
2337
2338 If processing fails throw ProcessingError.
2339
2340 \"\"\"
2341
2342PEP-257-NN:
2343
2344 \"\"\"Process foo, return bar.\"\"\"
2345
2346 \"\"\"Process foo, return bar.
2347
2348 If processing fails throw ProcessingError.
2349 \"\"\"
2350
2351SYMMETRIC:
2352
2353 \"\"\"Process foo, return bar.\"\"\"
2354
2355 \"\"\"
2356 Process foo, return bar.
2357
2358 If processing fails throw ProcessingError.
2359 \"\"\""
7fa36ccb
FEG
2360 :type '(choice
2361 (const :tag "Don't format docstrings" nil)
2362 (const :tag "Django's coding standards style." django)
2363 (const :tag "One newline and start and Two at end style." onetwo)
2364 (const :tag "PEP-257 with 2 newlines at end of string." pep-257)
2365 (const :tag "PEP-257 with 1 newline at end of string." pep-257-nn)
2366 (const :tag "Symmetric style." symmetric))
c2cb97ae 2367 :group 'python
7fa36ccb
FEG
2368 :safe (lambda (val)
2369 (memq val '(django onetwo pep-257 pep-257-nn symmetric nil))))
c2cb97ae 2370
45c138ac
FEG
2371(defun python-fill-paragraph-function (&optional justify)
2372 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2373If any of the current line is in or at the end of a multi-line string,
2374fill the string or the paragraph of it that point is in, preserving
4e531f7a
FEG
2375the string's indentation.
2376Optional argument JUSTIFY defines if the paragraph should be justified."
45c138ac
FEG
2377 (interactive "P")
2378 (save-excursion
45c138ac
FEG
2379 (cond
2380 ;; Comments
fc345011
FEG
2381 ((python-syntax-context 'comment)
2382 (funcall python-fill-comment-function justify))
c2cb97ae 2383 ;; Strings/Docstrings
fc345011
FEG
2384 ((save-excursion (or (python-syntax-context 'string)
2385 (equal (string-to-syntax "|")
2386 (syntax-after (point)))))
c2cb97ae 2387 (funcall python-fill-string-function justify))
45c138ac
FEG
2388 ;; Decorators
2389 ((equal (char-after (save-excursion
2390 (back-to-indentation)
fc345011 2391 (point))) ?@)
c2cb97ae 2392 (funcall python-fill-decorator-function justify))
45c138ac 2393 ;; Parens
2d79ec42 2394 ((or (python-syntax-context 'paren)
45c138ac
FEG
2395 (looking-at (python-rx open-paren))
2396 (save-excursion
2397 (skip-syntax-forward "^(" (line-end-position))
2398 (looking-at (python-rx open-paren))))
c2cb97ae 2399 (funcall python-fill-paren-function justify))
45c138ac
FEG
2400 (t t))))
2401
c2cb97ae 2402(defun python-fill-comment (&optional justify)
053a6c72
FEG
2403 "Comment fill function for `python-fill-paragraph-function'.
2404JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2405 (fill-comment-paragraph justify))
2406
2407(defun python-fill-string (&optional justify)
053a6c72
FEG
2408 "String fill function for `python-fill-paragraph-function'.
2409JUSTIFY should be used (if applicable) as in `fill-paragraph'."
fc345011
FEG
2410 (let* ((marker (point-marker))
2411 (str-start-pos
2412 (let ((m (make-marker)))
2413 (setf (marker-position m)
2414 (or (python-syntax-context 'string)
2415 (and (equal (string-to-syntax "|")
2416 (syntax-after (point)))
2417 (point)))) m))
2418 (num-quotes (python-syntax-count-quotes
2419 (char-after str-start-pos) str-start-pos))
2420 (str-end-pos
2421 (save-excursion
2422 (goto-char (+ str-start-pos num-quotes))
2423 (or (re-search-forward (rx (syntax string-delimiter)) nil t)
2424 (goto-char (point-max)))
2425 (point-marker)))
2426 (multi-line-p
2427 ;; Docstring styles may vary for oneliners and multi-liners.
2428 (> (count-matches "\n" str-start-pos str-end-pos) 0))
2429 (delimiters-style
7fa36ccb 2430 (case python-fill-docstring-style
fc345011
FEG
2431 ;; delimiters-style is a cons cell with the form
2432 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2433 ;; is NIL means to not add any newlines for start or end
7fa36ccb 2434 ;; of docstring. See `python-fill-docstring-style' for a
fc345011 2435 ;; graphic idea of each style.
7fa36ccb
FEG
2436 (django (cons 1 1))
2437 (onetwo (and multi-line-p (cons 1 2)))
fc345011
FEG
2438 (pep-257 (and multi-line-p (cons nil 2)))
2439 (pep-257-nn (and multi-line-p (cons nil 1)))
fc345011
FEG
2440 (symmetric (and multi-line-p (cons 1 1)))))
2441 (docstring-p (save-excursion
2442 ;; Consider docstrings those strings which
2443 ;; start on a line by themselves.
7fa36ccb
FEG
2444 (python-nav-beginning-of-statement)
2445 (and (= (point) str-start-pos))))
fc345011 2446 (fill-paragraph-function))
c2cb97ae 2447 (save-restriction
fc345011
FEG
2448 (narrow-to-region str-start-pos str-end-pos)
2449 (fill-paragraph justify))
2450 (save-excursion
7fa36ccb 2451 (when (and docstring-p python-fill-docstring-style)
fc345011
FEG
2452 ;; Add the number of newlines indicated by the selected style
2453 ;; at the start of the docstring.
2454 (goto-char (+ str-start-pos num-quotes))
2455 (delete-region (point) (progn
2456 (skip-syntax-forward "> ")
2457 (point)))
2458 (and (car delimiters-style)
2459 (or (newline (car delimiters-style)) t)
2460 ;; Indent only if a newline is added.
2461 (indent-according-to-mode))
2462 ;; Add the number of newlines indicated by the selected style
2463 ;; at the end of the docstring.
2464 (goto-char (if (not (= str-end-pos (point-max)))
2465 (- str-end-pos num-quotes)
2466 str-end-pos))
2467 (delete-region (point) (progn
2468 (skip-syntax-backward "> ")
2469 (point)))
2470 (and (cdr delimiters-style)
2471 ;; Add newlines only if string ends.
2472 (not (= str-end-pos (point-max)))
2473 (or (newline (cdr delimiters-style)) t)
2474 ;; Again indent only if a newline is added.
2475 (indent-according-to-mode))))) t)
c2cb97ae
FEG
2476
2477(defun python-fill-decorator (&optional justify)
053a6c72
FEG
2478 "Decorator fill function for `python-fill-paragraph-function'.
2479JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2480 t)
2481
2482(defun python-fill-paren (&optional justify)
053a6c72
FEG
2483 "Paren fill function for `python-fill-paragraph-function'.
2484JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
2485 (save-restriction
2486 (narrow-to-region (progn
2d79ec42 2487 (while (python-syntax-context 'paren)
c2cb97ae
FEG
2488 (goto-char (1- (point-marker))))
2489 (point-marker)
2490 (line-beginning-position))
2491 (progn
2d79ec42 2492 (when (not (python-syntax-context 'paren))
c2cb97ae 2493 (end-of-line)
2d79ec42 2494 (when (not (python-syntax-context 'paren))
c2cb97ae 2495 (skip-syntax-backward "^)")))
2d79ec42 2496 (while (python-syntax-context 'paren)
c2cb97ae
FEG
2497 (goto-char (1+ (point-marker))))
2498 (point-marker)))
2499 (let ((paragraph-start "\f\\|[ \t]*$")
2500 (paragraph-separate ",")
2501 (fill-paragraph-function))
2502 (goto-char (point-min))
2503 (fill-paragraph justify))
2504 (while (not (eobp))
2505 (forward-line 1)
2506 (python-indent-line)
2507 (goto-char (line-end-position)))) t)
2508
45c138ac 2509\f
e2803784
FEG
2510;;; Skeletons
2511
2512(defcustom python-skeleton-autoinsert nil
2513 "Non-nil means template skeletons will be automagically inserted.
2514This happens when pressing \"if<SPACE>\", for example, to prompt for
2515the if condition."
2516 :type 'boolean
0f55249e
FEG
2517 :group 'python
2518 :safe 'booleanp)
e2803784 2519
9ddf3c74 2520(define-obsolete-variable-alias
2a1e2476 2521 'python-use-skeletons 'python-skeleton-autoinsert "24.3")
9ddf3c74 2522
e2803784
FEG
2523(defvar python-skeleton-available '()
2524 "Internal list of available skeletons.")
e2803784
FEG
2525
2526(define-abbrev-table 'python-mode-abbrev-table ()
2527 "Abbrev table for Python mode."
2528 :case-fixed t
2529 ;; Allow / inside abbrevs.
2530 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2531 ;; Only expand in code.
2532 :enable-function (lambda ()
e2803784 2533 (and
2d79ec42 2534 (not (python-syntax-comment-or-string-p))
e2803784
FEG
2535 python-skeleton-autoinsert)))
2536
2537(defmacro python-skeleton-define (name doc &rest skel)
2538 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2539The skeleton will be bound to python-skeleton-NAME and will
2540be added to `python-mode-abbrev-table'."
25f09295 2541 (declare (indent 2))
e2803784 2542 (let* ((name (symbol-name name))
6cad4c6e 2543 (function-name (intern (concat "python-skeleton-" name))))
73ed6836 2544 `(progn
0e9e6c6a 2545 (define-abbrev python-mode-abbrev-table ,name "" ',function-name
d617c457 2546 :system t)
73ed6836
FEG
2547 (setq python-skeleton-available
2548 (cons ',function-name python-skeleton-available))
2549 (define-skeleton ,function-name
2550 ,(or doc
2551 (format "Insert %s statement." name))
2552 ,@skel))))
e2803784
FEG
2553
2554(defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2555 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2556The skeleton will be bound to python-skeleton-NAME."
25f09295 2557 (declare (indent 2))
e2803784 2558 (let* ((name (symbol-name name))
6cad4c6e 2559 (function-name (intern (concat "python-skeleton--" name)))
e2803784
FEG
2560 (msg (format
2561 "Add '%s' clause? " name)))
2562 (when (not skel)
2563 (setq skel
2564 `(< ,(format "%s:" name) \n \n
2565 > _ \n)))
2566 `(define-skeleton ,function-name
2567 ,(or doc
2568 (format "Auxiliary skeleton for %s statement." name))
2569 nil
2570 (unless (y-or-n-p ,msg)
2571 (signal 'quit t))
2572 ,@skel)))
e2803784
FEG
2573
2574(python-define-auxiliary-skeleton else nil)
2575
2576(python-define-auxiliary-skeleton except nil)
2577
2578(python-define-auxiliary-skeleton finally nil)
2579
2580(python-skeleton-define if nil
2581 "Condition: "
2582 "if " str ":" \n
2583 _ \n
2584 ("other condition, %s: "
2585 <
2586 "elif " str ":" \n
2587 > _ \n nil)
2588 '(python-skeleton--else) | ^)
2589
2590(python-skeleton-define while nil
2591 "Condition: "
2592 "while " str ":" \n
2593 > _ \n
2594 '(python-skeleton--else) | ^)
2595
2596(python-skeleton-define for nil
2597 "Iteration spec: "
2598 "for " str ":" \n
2599 > _ \n
2600 '(python-skeleton--else) | ^)
2601
2602(python-skeleton-define try nil
2603 nil
2604 "try:" \n
2605 > _ \n
2606 ("Exception, %s: "
2607 <
2608 "except " str ":" \n
2609 > _ \n nil)
2610 resume:
2611 '(python-skeleton--except)
2612 '(python-skeleton--else)
2613 '(python-skeleton--finally) | ^)
2614
2615(python-skeleton-define def nil
2616 "Function name: "
2617 "def " str " (" ("Parameter, %s: "
2618 (unless (equal ?\( (char-before)) ", ")
6cad4c6e
FEG
2619 str) "):" \n
2620 "\"\"\"" - "\"\"\"" \n
2621 > _ \n)
e2803784
FEG
2622
2623(python-skeleton-define class nil
2624 "Class name: "
2625 "class " str " (" ("Inheritance, %s: "
6cad4c6e
FEG
2626 (unless (equal ?\( (char-before)) ", ")
2627 str)
e2803784
FEG
2628 & ")" | -2
2629 ":" \n
2630 "\"\"\"" - "\"\"\"" \n
2631 > _ \n)
2632
2633(defun python-skeleton-add-menu-items ()
2634 "Add menu items to Python->Skeletons menu."
2635 (let ((skeletons (sort python-skeleton-available 'string<))
2636 (items))
2637 (dolist (skeleton skeletons)
2638 (easy-menu-add-item
2639 nil '("Python" "Skeletons")
2640 `[,(format
2641 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2642 ,skeleton t]))))
2643\f
046428d3
FEG
2644;;; FFAP
2645
0f55249e 2646(defcustom python-ffap-setup-code
046428d3
FEG
2647 "def __FFAP_get_module_path(module):
2648 try:
2649 import os
2650 path = __import__(module).__file__
2651 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2652 path = path[:-1]
2653 return path
2654 except:
2655 return ''"
0f55249e
FEG
2656 "Python code to get a module path."
2657 :type 'string
c4b155cb 2658 :group 'python)
046428d3 2659
0f55249e 2660(defcustom python-ffap-string-code
046428d3 2661 "__FFAP_get_module_path('''%s''')\n"
0f55249e
FEG
2662 "Python code used to get a string with the path of a module."
2663 :type 'string
c4b155cb 2664 :group 'python)
046428d3 2665
046428d3
FEG
2666(defun python-ffap-module-path (module)
2667 "Function for `ffap-alist' to return path for MODULE."
2668 (let ((process (or
2669 (and (eq major-mode 'inferior-python-mode)
2670 (get-buffer-process (current-buffer)))
2671 (python-shell-get-process))))
2672 (if (not process)
2673 nil
2674 (let ((module-file
9ce938be 2675 (python-shell-send-string-no-output
046428d3
FEG
2676 (format python-ffap-string-code module) process)))
2677 (when module-file
6cad4c6e 2678 (substring-no-properties module-file 1 -1))))))
046428d3
FEG
2679
2680(eval-after-load "ffap"
2681 '(progn
2682 (push '(python-mode . python-ffap-module-path) ffap-alist)
2683 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2684
046428d3 2685\f
8b3e0e76
FEG
2686;;; Code check
2687
0f55249e 2688(defcustom python-check-command
bba416bc 2689 "pyflakes"
0f55249e
FEG
2690 "Command used to check a Python file."
2691 :type 'string
c4b155cb 2692 :group 'python)
8b3e0e76 2693
bbd27e07
FEG
2694(defcustom python-check-buffer-name
2695 "*Python check: %s*"
2696 "Buffer name used for check commands."
2697 :type 'string
2698 :group 'python)
2699
8b3e0e76
FEG
2700(defvar python-check-custom-command nil
2701 "Internal use.")
2702
2703(defun python-check (command)
2704 "Check a Python file (default current buffer's file).
2705Runs COMMAND, a shell command, as if by `compile'. See
2706`python-check-command' for the default."
2707 (interactive
2708 (list (read-string "Check command: "
6cad4c6e
FEG
2709 (or python-check-custom-command
2710 (concat python-check-command " "
8b3e0e76
FEG
2711 (shell-quote-argument
2712 (or
2713 (let ((name (buffer-file-name)))
2714 (and name
2715 (file-name-nondirectory name)))
2716 "")))))))
2717 (setq python-check-custom-command command)
2718 (save-some-buffers (not compilation-ask-about-save) nil)
bba416bc
FEG
2719 (let ((process-environment (python-shell-calculate-process-environment))
2720 (exec-path (python-shell-calculate-exec-path)))
bbd27e07
FEG
2721 (compilation-start command nil
2722 (lambda (mode-name)
2723 (format python-check-buffer-name command)))))
8b3e0e76
FEG
2724
2725\f
45c138ac
FEG
2726;;; Eldoc
2727
0f55249e 2728(defcustom python-eldoc-setup-code
45c138ac
FEG
2729 "def __PYDOC_get_help(obj):
2730 try:
15cc40b8 2731 import inspect
9e662938
FEG
2732 if hasattr(obj, 'startswith'):
2733 obj = eval(obj, globals())
15cc40b8
FEG
2734 doc = inspect.getdoc(obj)
2735 if not doc and callable(obj):
2736 target = None
2737 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2738 target = obj.__init__
2739 objtype = 'class'
2740 else:
2741 target = obj
2742 objtype = 'def'
2743 if target:
2744 args = inspect.formatargspec(
2745 *inspect.getargspec(target)
2746 )
2747 name = obj.__name__
2748 doc = '{objtype} {name}{args}'.format(
2749 objtype=objtype, name=name, args=args
2750 )
2751 else:
2752 doc = doc.splitlines()[0]
45c138ac 2753 except:
9e662938
FEG
2754 doc = ''
2755 try:
2756 exec('print doc')
2757 except SyntaxError:
2758 print(doc)"
0f55249e
FEG
2759 "Python code to setup documentation retrieval."
2760 :type 'string
c4b155cb 2761 :group 'python)
45c138ac 2762
0f55249e 2763(defcustom python-eldoc-string-code
9e662938 2764 "__PYDOC_get_help('''%s''')\n"
0f55249e
FEG
2765 "Python code used to get a string with the documentation of an object."
2766 :type 'string
c4b155cb 2767 :group 'python)
45c138ac 2768
78334b43 2769(defun python-eldoc--get-doc-at-point (&optional force-input force-process)
d439cda5 2770 "Internal implementation to get documentation at point.
d583cbe6
FEG
2771If not FORCE-INPUT is passed then what
2772`python-info-current-symbol' returns will be used. If not
2773FORCE-PROCESS is passed what `python-shell-get-process' returns
2774is used."
78334b43 2775 (let ((process (or force-process (python-shell-get-process))))
45c138ac 2776 (if (not process)
d583cbe6
FEG
2777 (error "Eldoc needs an inferior Python process running")
2778 (let ((input (or force-input
2779 (python-info-current-symbol t))))
2780 (and input
2781 (python-shell-send-string-no-output
2782 (format python-eldoc-string-code input)
2783 process))))))
45c138ac 2784
78334b43
FEG
2785(defun python-eldoc-function ()
2786 "`eldoc-documentation-function' for Python.
2787For this to work the best as possible you should call
2788`python-shell-send-buffer' from time to time so context in
2789inferior python process is updated properly."
2790 (python-eldoc--get-doc-at-point))
2791
2792(defun python-eldoc-at-point (symbol)
2793 "Get help on SYMBOL using `help'.
2794Interactively, prompt for symbol."
6cad4c6e 2795 (interactive
d583cbe6 2796 (let ((symbol (python-info-current-symbol t))
6cad4c6e
FEG
2797 (enable-recursive-minibuffers t))
2798 (list (read-string (if symbol
2799 (format "Describe symbol (default %s): " symbol)
2800 "Describe symbol: ")
2801 nil nil symbol))))
d583cbe6
FEG
2802 (message (python-eldoc--get-doc-at-point symbol)))
2803
2804(add-to-list 'debug-ignored-errors
2805 "^Eldoc needs an inferior Python process running.")
78334b43 2806
45c138ac
FEG
2807\f
2808;;; Misc helpers
2809
fc2dc7df 2810(defun python-info-current-defun (&optional include-type)
45c138ac 2811 "Return name of surrounding function with Python compatible dotty syntax.
fc2dc7df 2812Optional argument INCLUDE-TYPE indicates to include the type of the defun.
45c138ac
FEG
2813This function is compatible to be used as
2814`add-log-current-defun-function' since it returns nil if point is
2815not inside a defun."
6b432853 2816 (let ((names '())
d583cbe6
FEG
2817 (starting-indentation)
2818 (starting-point)
0b7b2e51 2819 (first-run t))
45c138ac
FEG
2820 (save-restriction
2821 (widen)
2822 (save-excursion
d583cbe6
FEG
2823 (setq starting-point (point-marker))
2824 (setq starting-indentation (save-excursion
2825 (python-nav-beginning-of-statement)
2826 (current-indentation)))
8c6f9e60 2827 (end-of-line 1)
8c6f9e60 2828 (while (python-beginning-of-defun-function 1)
d583cbe6
FEG
2829 (when (or (< (current-indentation) starting-indentation)
2830 (and first-run
2831 (<
2832 starting-point
2833 (save-excursion
2834 (python-end-of-defun-function)
2835 (point-marker)))))
0b7b2e51 2836 (setq first-run nil)
d583cbe6 2837 (setq starting-indentation (current-indentation))
af5c1beb 2838 (looking-at python-nav-beginning-of-defun-regexp)
fc2dc7df
FEG
2839 (setq names (cons
2840 (if (not include-type)
2841 (match-string-no-properties 1)
2842 (mapconcat 'identity
2843 (split-string
2844 (match-string-no-properties 0)) " "))
2845 names))))))
45c138ac
FEG
2846 (when names
2847 (mapconcat (lambda (string) string) names "."))))
2848
d583cbe6
FEG
2849(defun python-info-current-symbol (&optional replace-self)
2850 "Return current symbol using dotty syntax.
2851With optional argument REPLACE-SELF convert \"self\" to current
2852parent defun name."
2853 (let ((name
2d79ec42 2854 (and (not (python-syntax-comment-or-string-p))
d583cbe6
FEG
2855 (with-syntax-table python-dotty-syntax-table
2856 (let ((sym (symbol-at-point)))
2857 (and sym
2858 (substring-no-properties (symbol-name sym))))))))
2859 (when name
2860 (if (not replace-self)
2861 name
2862 (let ((current-defun (python-info-current-defun)))
2863 (if (not current-defun)
2864 name
2865 (replace-regexp-in-string
2866 (python-rx line-start word-start "self" word-end ?.)
2867 (concat
2868 (mapconcat 'identity
2869 (butlast (split-string current-defun "\\."))
2870 ".") ".")
2871 name)))))))
2872
8dbce54c 2873(defun python-info-statement-starts-block-p ()
0a60bc10
FEG
2874 "Return non-nil if current statement opens a block."
2875 (save-excursion
2876 (python-nav-beginning-of-statement)
2877 (looking-at (python-rx block-start))))
2878
8dbce54c
FEG
2879(defun python-info-statement-ends-block-p ()
2880 "Return non-nil if point is at end of block."
2881 (let ((end-of-block-pos (save-excursion
2882 (python-nav-end-of-block)))
2883 (end-of-statement-pos (save-excursion
2884 (python-nav-end-of-statement))))
2885 (and end-of-block-pos end-of-statement-pos
2886 (= end-of-block-pos end-of-statement-pos))))
2887
2888(defun python-info-beginning-of-statement-p ()
2889 "Return non-nil if point is at beginning of statement."
2890 (= (point) (save-excursion
2891 (python-nav-beginning-of-statement)
2892 (point))))
2893
2894(defun python-info-end-of-statement-p ()
2895 "Return non-nil if point is at end of statement."
2896 (= (point) (save-excursion
2897 (python-nav-end-of-statement)
2898 (point))))
2899
2900(defun python-info-beginning-of-block-p ()
2901 "Return non-nil if point is at beginning of block."
2902 (and (python-info-beginning-of-statement-p)
2903 (python-info-statement-starts-block-p)))
2904
2905(defun python-info-end-of-block-p ()
2906 "Return non-nil if point is at end of block."
2907 (and (python-info-end-of-statement-p)
2908 (python-info-statement-ends-block-p)))
2909
45c138ac 2910(defun python-info-closing-block ()
e2d8d479 2911 "Return the point of the block the current line closes."
45c138ac
FEG
2912 (let ((closing-word (save-excursion
2913 (back-to-indentation)
2914 (current-word)))
2915 (indentation (current-indentation)))
2916 (when (member closing-word python-indent-dedenters)
2917 (save-excursion
2918 (forward-line -1)
2919 (while (and (> (current-indentation) indentation)
2920 (not (bobp))
2921 (not (back-to-indentation))
2922 (forward-line -1)))
2923 (back-to-indentation)
2924 (cond
2925 ((not (equal indentation (current-indentation))) nil)
2926 ((string= closing-word "elif")
2927 (when (member (current-word) '("if" "elif"))
2928 (point-marker)))
2929 ((string= closing-word "else")
2930 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2931 (point-marker)))
2932 ((string= closing-word "except")
2933 (when (member (current-word) '("try"))
2934 (point-marker)))
2935 ((string= closing-word "finally")
2936 (when (member (current-word) '("except" "else"))
2937 (point-marker))))))))
2938
cd7ab092
FEG
2939(defun python-info-closing-block-message (&optional closing-block-point)
2940 "Message the contents of the block the current line closes.
2941With optional argument CLOSING-BLOCK-POINT use that instead of
2942recalculating it calling `python-info-closing-block'."
2943 (let ((point (or closing-block-point (python-info-closing-block))))
2944 (when point
2945 (save-restriction
2946 (widen)
2947 (message "Closes %s" (save-excursion
2948 (goto-char point)
2949 (back-to-indentation)
2950 (buffer-substring
2951 (point) (line-end-position))))))))
2952
0674d3fa 2953(defun python-info-line-ends-backslash-p (&optional line-number)
6cad4c6e 2954 "Return non-nil if current line ends with backslash.
0674d3fa 2955With optional argument LINE-NUMBER, check that line instead."
6cad4c6e
FEG
2956 (save-excursion
2957 (save-restriction
dc4f2e53 2958 (widen)
6cad4c6e
FEG
2959 (when line-number
2960 (goto-char line-number))
dc4f2e53
FEG
2961 (while (and (not (eobp))
2962 (goto-char (line-end-position))
2d79ec42 2963 (python-syntax-context 'paren)
dc4f2e53
FEG
2964 (not (equal (char-before (point)) ?\\)))
2965 (forward-line 1))
2966 (when (equal (char-before) ?\\)
2967 (point-marker)))))
2968
48d1354e
PE
2969(defun python-info-beginning-of-backslash (&optional line-number)
2970 "Return the point where the backslashed line start.
4289485a 2971Optional argument LINE-NUMBER forces the line number to check against."
dc4f2e53
FEG
2972 (save-excursion
2973 (save-restriction
6cad4c6e 2974 (widen)
dc4f2e53
FEG
2975 (when line-number
2976 (goto-char line-number))
2977 (when (python-info-line-ends-backslash-p)
2978 (while (save-excursion
2979 (goto-char (line-beginning-position))
2d79ec42 2980 (python-syntax-context 'paren))
dc4f2e53
FEG
2981 (forward-line -1))
2982 (back-to-indentation)
2983 (point-marker)))))
45c138ac
FEG
2984
2985(defun python-info-continuation-line-p ()
0674d3fa
FEG
2986 "Check if current line is continuation of another.
2987When current line is continuation of another return the point
2988where the continued line ends."
2989 (save-excursion
2990 (save-restriction
2991 (widen)
2992 (let* ((context-type (progn
2993 (back-to-indentation)
2d79ec42 2994 (python-syntax-context-type)))
0674d3fa
FEG
2995 (line-start (line-number-at-pos))
2996 (context-start (when context-type
2d79ec42 2997 (python-syntax-context context-type))))
0674d3fa
FEG
2998 (cond ((equal context-type 'paren)
2999 ;; Lines inside a paren are always a continuation line
3000 ;; (except the first one).
1d29cc7d
FEG
3001 (python-util-forward-comment -1)
3002 (point-marker))
3003 ((member context-type '(string comment))
0674d3fa
FEG
3004 ;; move forward an roll again
3005 (goto-char context-start)
3006 (python-util-forward-comment)
3007 (python-info-continuation-line-p))
3008 (t
1d29cc7d
FEG
3009 ;; Not within a paren, string or comment, the only way
3010 ;; we are dealing with a continuation line is that
3011 ;; previous line contains a backslash, and this can
3012 ;; only be the previous line from current
0674d3fa
FEG
3013 (back-to-indentation)
3014 (python-util-forward-comment -1)
0674d3fa
FEG
3015 (when (and (equal (1- line-start) (line-number-at-pos))
3016 (python-info-line-ends-backslash-p))
3017 (point-marker))))))))
45c138ac
FEG
3018
3019(defun python-info-block-continuation-line-p ()
3020 "Return non-nil if current line is a continuation of a block."
3021 (save-excursion
0674d3fa
FEG
3022 (when (python-info-continuation-line-p)
3023 (forward-line -1)
3024 (back-to-indentation)
3025 (when (looking-at (python-rx block-start))
3026 (point-marker)))))
45c138ac
FEG
3027
3028(defun python-info-assignment-continuation-line-p ()
0674d3fa
FEG
3029 "Check if current line is a continuation of an assignment.
3030When current line is continuation of another with an assignment
3031return the point of the first non-blank character after the
3032operator."
45c138ac 3033 (save-excursion
0674d3fa
FEG
3034 (when (python-info-continuation-line-p)
3035 (forward-line -1)
3036 (back-to-indentation)
3037 (when (and (not (looking-at (python-rx block-start)))
45c138ac
FEG
3038 (and (re-search-forward (python-rx not-simple-operator
3039 assignment-operator
3040 not-simple-operator)
3041 (line-end-position) t)
2d79ec42 3042 (not (python-syntax-context-type))))
0674d3fa
FEG
3043 (skip-syntax-forward "\s")
3044 (point-marker)))))
45c138ac 3045
8c6f9e60 3046(defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss)
4289485a 3047 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2d79ec42 3048 (and (not (python-syntax-context-type (or syntax-ppss (syntax-ppss))))
8c6f9e60
FEG
3049 (save-excursion
3050 (beginning-of-line 1)
3051 (looking-at python-nav-beginning-of-defun-regexp))))
3052
032d23ab
FEG
3053(defun python-info-current-line-comment-p ()
3054 "Check if current line is a comment line."
3055 (char-equal (or (char-after (+ (point) (current-indentation))) ?_) ?#))
3056
3057(defun python-info-current-line-empty-p ()
3058 "Check if current line is empty, ignoring whitespace."
3059 (save-excursion
3060 (beginning-of-line 1)
3061 (looking-at
3062 (python-rx line-start (* whitespace)
3063 (group (* not-newline))
3064 (* whitespace) line-end))
3065 (string-equal "" (match-string-no-properties 1))))
3066
45c138ac 3067\f
c942de99
FEG
3068;;; Utility functions
3069
c942de99
FEG
3070(defun python-util-position (item seq)
3071 "Find the first occurrence of ITEM in SEQ.
3072Return the index of the matching item, or nil if not found."
3073 (let ((member-result (member item seq)))
3074 (when member-result
3075 (- (length seq) (length member-result)))))
3076
d2190c57 3077;; Stolen from org-mode
fbc39529 3078(defun python-util-clone-local-variables (from-buffer &optional regexp)
d2190c57
FEG
3079 "Clone local variables from FROM-BUFFER.
3080Optional argument REGEXP selects variables to clone and defaults
3081to \"^python-\"."
3082 (mapc
3083 (lambda (pair)
3084 (and (symbolp (car pair))
3085 (string-match (or regexp "^python-")
3086 (symbol-name (car pair)))
6cad4c6e
FEG
3087 (set (make-local-variable (car pair))
3088 (cdr pair))))
d2190c57
FEG
3089 (buffer-local-variables from-buffer)))
3090
0674d3fa 3091(defun python-util-forward-comment (&optional direction)
4289485a
FEG
3092 "Python mode specific version of `forward-comment'.
3093Optional argument DIRECTION defines the direction to move to."
2d79ec42 3094 (let ((comment-start (python-syntax-context 'comment))
0674d3fa
FEG
3095 (factor (if (< (or direction 0) 0)
3096 -99999
3097 99999)))
3098 (when comment-start
3099 (goto-char comment-start))
3100 (forward-comment factor)))
3101
c942de99 3102\f
45c138ac 3103;;;###autoload
68f12411 3104(define-derived-mode python-mode prog-mode "Python"
e2d8d479
FEG
3105 "Major mode for editing Python files.
3106
3107\\{python-mode-map}
3108Entry to this mode calls the value of `python-mode-hook'
3109if that value is non-nil."
45c138ac
FEG
3110 (set (make-local-variable 'tab-width) 8)
3111 (set (make-local-variable 'indent-tabs-mode) nil)
3112
3113 (set (make-local-variable 'comment-start) "# ")
3114 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
3115
3116 (set (make-local-variable 'parse-sexp-lookup-properties) t)
3117 (set (make-local-variable 'parse-sexp-ignore-comments) t)
3118
032d23ab 3119 (set (make-local-variable 'forward-sexp-function)
489af14f 3120 'python-nav-forward-sexp)
032d23ab 3121
45c138ac 3122 (set (make-local-variable 'font-lock-defaults)
aeadd9a4
FEG
3123 '(python-font-lock-keywords nil nil nil nil))
3124
3125 (set (make-local-variable 'syntax-propertize-function)
3126 python-syntax-propertize-function)
45c138ac 3127
6cad4c6e
FEG
3128 (set (make-local-variable 'indent-line-function)
3129 #'python-indent-line-function)
45c138ac
FEG
3130 (set (make-local-variable 'indent-region-function) #'python-indent-region)
3131
3132 (set (make-local-variable 'paragraph-start) "\\s-*$")
6cad4c6e
FEG
3133 (set (make-local-variable 'fill-paragraph-function)
3134 'python-fill-paragraph-function)
45c138ac
FEG
3135
3136 (set (make-local-variable 'beginning-of-defun-function)
3137 #'python-beginning-of-defun-function)
3138 (set (make-local-variable 'end-of-defun-function)
3139 #'python-end-of-defun-function)
3140
3141 (add-hook 'completion-at-point-functions
3142 'python-completion-complete-at-point nil 'local)
3143
5eae76ae
FEG
3144 (add-hook 'post-self-insert-hook
3145 'python-indent-post-self-insert-function nil 'local)
3146
758e556a
FEG
3147 (set (make-local-variable 'imenu-extract-index-name-function)
3148 #'python-info-current-defun)
fc2dc7df 3149
45c138ac
FEG
3150 (set (make-local-variable 'add-log-current-defun-function)
3151 #'python-info-current-defun)
3152
c6d3df36
FEG
3153 (add-hook 'which-func-functions #'python-info-current-defun nil t)
3154
e2803784
FEG
3155 (set (make-local-variable 'skeleton-further-elements)
3156 '((abbrev-mode nil)
3157 (< '(backward-delete-char-untabify (min python-indent-offset
6cad4c6e
FEG
3158 (current-column))))
3159 (^ '(- (1+ (current-indentation))))))
e2803784 3160
45c138ac
FEG
3161 (set (make-local-variable 'eldoc-documentation-function)
3162 #'python-eldoc-function)
3163
3164 (add-to-list 'hs-special-modes-alist
6cad4c6e 3165 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
45c138ac
FEG
3166 ,(lambda (arg)
3167 (python-end-of-defun-function)) nil))
3168
82c2b0de
FEG
3169 (set (make-local-variable 'mode-require-final-newline) t)
3170
45c138ac
FEG
3171 (set (make-local-variable 'outline-regexp)
3172 (python-rx (* space) block-start))
3173 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
3174 (set (make-local-variable 'outline-level)
3175 #'(lambda ()
3176 "`outline-level' function for Python mode."
3177 (1+ (/ (current-indentation) python-indent-offset))))
3178
e2803784
FEG
3179 (python-skeleton-add-menu-items)
3180
e0cc4efa
FEG
3181 (make-local-variable 'python-shell-internal-buffer)
3182
45c138ac
FEG
3183 (when python-indent-guess-indent-offset
3184 (python-indent-guess-indent-offset)))
3185
3186
3187(provide 'python)
d617c457
FEG
3188
3189;; Local Variables:
3190;; coding: utf-8
3191;; indent-tabs-mode: nil
3192;; End:
3193
45c138ac 3194;;; python.el ends here