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