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