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