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