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