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