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