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