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