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