Enhanced shell setup for Windows.
[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
c0428ba0 1107 :group 'python
45c138ac
FEG
1108 :safe 'stringp)
1109
0f55249e
FEG
1110(defcustom python-shell-internal-buffer-name "Python Internal"
1111 "Default buffer name for the Internal Python interpreter."
1112 :type 'string
1113 :group 'python
1114 :safe 'stringp)
1fe1b5aa 1115
45c138ac
FEG
1116(defcustom python-shell-interpreter-args "-i"
1117 "Default arguments for the Python interpreter."
45c138ac 1118 :type 'string
c0428ba0 1119 :group 'python
45c138ac
FEG
1120 :safe 'stringp)
1121
1122(defcustom python-shell-prompt-regexp ">>> "
e2d8d479
FEG
1123 "Regular Expression matching top\-level input prompt of python shell.
1124It should not contain a caret (^) at the beginning."
45c138ac
FEG
1125 :type 'string
1126 :group 'python
1127 :safe 'stringp)
1128
1129(defcustom python-shell-prompt-block-regexp "[.][.][.] "
e2d8d479
FEG
1130 "Regular Expression matching block input prompt of python shell.
1131It should not contain a caret (^) at the beginning."
45c138ac
FEG
1132 :type 'string
1133 :group 'python
1134 :safe 'stringp)
1135
0f55249e 1136(defcustom python-shell-prompt-output-regexp ""
e2d8d479
FEG
1137 "Regular Expression matching output prompt of python shell.
1138It should not contain a caret (^) at the beginning."
62feb915
FEG
1139 :type 'string
1140 :group 'python
1141 :safe 'stringp)
1142
45c138ac 1143(defcustom python-shell-prompt-pdb-regexp "[(<]*[Ii]?[Pp]db[>)]+ "
e2d8d479
FEG
1144 "Regular Expression matching pdb input prompt of python shell.
1145It should not contain a caret (^) at the beginning."
45c138ac
FEG
1146 :type 'string
1147 :group 'python
1148 :safe 'stringp)
1149
30e429dd
FEG
1150(defcustom python-shell-send-setup-max-wait 5
1151 "Seconds to wait for process output before code setup.
1152If output is received before the especified time then control is
1153returned in that moment and not after waiting."
0f55249e 1154 :type 'integer
30e429dd 1155 :group 'python
0f55249e 1156 :safe 'integerp)
30e429dd 1157
66bbb27f 1158(defcustom python-shell-process-environment nil
307bd2e8
FEG
1159 "List of environment variables for Python shell.
1160This variable follows the same rules as `process-environment'
66bbb27f
FEG
1161since it merges with it before the process creation routines are
1162called. When this variable is nil, the Python shell is run with
307bd2e8 1163the default `process-environment'."
66bbb27f
FEG
1164 :type '(repeat string)
1165 :group 'python
1166 :safe 'listp)
1167
929036b4
FEG
1168(defcustom python-shell-extra-pythonpaths nil
1169 "List of extra pythonpaths for Python shell.
1170The values of this variable are added to the existing value of
1171PYTHONPATH in the `process-environment' variable."
1172 :type '(repeat string)
1173 :group 'python
1174 :safe 'listp)
1175
66bbb27f
FEG
1176(defcustom python-shell-exec-path nil
1177 "List of path to search for binaries.
1178This variable follows the same rules as `exec-path' since it
1179merges with it before the process creation routines are called.
1180When this variable is nil, the Python shell is run with the
1181default `exec-path'."
1182 :type '(repeat string)
1183 :group 'python
1184 :safe 'listp)
1185
64348c32
FEG
1186(defcustom python-shell-virtualenv-path nil
1187 "Path to virtualenv root.
1188This variable, when set to a string, makes the values stored in
1189`python-shell-process-environment' and `python-shell-exec-path'
1190to be modified properly so shells are started with the specified
1191virtualenv."
1192 :type 'string
1193 :group 'python
1194 :safe 'stringp)
1195
c0428ba0
FEG
1196(defcustom python-shell-setup-codes '(python-shell-completion-setup-code
1197 python-ffap-setup-code
1198 python-eldoc-setup-code)
279c9272 1199 "List of code run by `python-shell-send-setup-codes'."
c0428ba0
FEG
1200 :type '(repeat symbol)
1201 :group 'python
1202 :safe 'listp)
1203
45c138ac
FEG
1204(defcustom python-shell-compilation-regexp-alist
1205 `((,(rx line-start (1+ (any " \t")) "File \""
1206 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1207 "\", line " (group (1+ digit)))
1208 1 2)
1209 (,(rx " in file " (group (1+ not-newline)) " on line "
1210 (group (1+ digit)))
1211 1 2)
1212 (,(rx line-start "> " (group (1+ (not (any "(\"<"))))
1213 "(" (group (1+ digit)) ")" (1+ (not (any "("))) "()")
1214 1 2))
1215 "`compilation-error-regexp-alist' for inferior Python."
1216 :type '(alist string)
1217 :group 'python)
1218
1219(defun python-shell-get-process-name (dedicated)
1220 "Calculate the appropiate process name for inferior Python process.
45c138ac
FEG
1221If DEDICATED is t and the variable `buffer-file-name' is non-nil
1222returns a string with the form
1223`python-shell-buffer-name'[variable `buffer-file-name'] else
e2d8d479
FEG
1224returns the value of `python-shell-buffer-name'. After
1225calculating the process name adds the buffer name for the process
1226in the `same-window-buffer-names' list."
45c138ac
FEG
1227 (let ((process-name
1228 (if (and dedicated
1229 buffer-file-name)
1230 (format "%s[%s]" python-shell-buffer-name buffer-file-name)
1231 (format "%s" python-shell-buffer-name))))
1232 (add-to-list 'same-window-buffer-names (purecopy
1233 (format "*%s*" process-name)))
1234 process-name))
1235
1fe1b5aa
FEG
1236(defun python-shell-internal-get-process-name ()
1237 "Calculate the appropiate process name for Internal Python process.
1238The name is calculated from `python-shell-global-buffer-name' and
1239a hash of all relevant global shell settings in order to ensure
1240uniqueness for different types of configurations."
1241 (format "%s [%s]"
1242 python-shell-internal-buffer-name
1243 (md5
1244 (concat
1245 (python-shell-parse-command)
279c9272
FEG
1246 python-shell-prompt-regexp
1247 python-shell-prompt-block-regexp
1248 python-shell-prompt-output-regexp
1fe1b5aa 1249 (mapconcat #'symbol-value python-shell-setup-codes "")
2bdce388
FEG
1250 (mapconcat #'identity python-shell-process-environment "")
1251 (mapconcat #'identity python-shell-extra-pythonpaths "")
1252 (mapconcat #'identity python-shell-exec-path "")
64348c32 1253 (or python-shell-virtualenv-path "")
2bdce388 1254 (mapconcat #'identity python-shell-exec-path "")))))
1fe1b5aa 1255
45c138ac 1256(defun python-shell-parse-command ()
e2d8d479 1257 "Calculate the string used to execute the inferior Python process."
45c138ac
FEG
1258 (format "%s %s" python-shell-interpreter python-shell-interpreter-args))
1259
307bd2e8
FEG
1260(defun python-shell-calculate-process-environment ()
1261 "Calculate process environment given `python-shell-virtualenv-path'."
40417cb3
FEG
1262 (let ((process-environment (append
1263 python-shell-process-environment
1264 process-environment nil))
64348c32
FEG
1265 (virtualenv (if python-shell-virtualenv-path
1266 (directory-file-name python-shell-virtualenv-path)
1267 nil)))
929036b4
FEG
1268 (when python-shell-extra-pythonpaths
1269 (setenv "PYTHONPATH"
1270 (format "%s%s%s"
1271 (mapconcat 'identity
1272 python-shell-extra-pythonpaths
1273 path-separator)
1274 path-separator
1275 (or (getenv "PYTHONPATH") ""))))
64348c32 1276 (if (not virtualenv)
40417cb3
FEG
1277 process-environment
1278 (setenv "PYTHONHOME" nil)
1279 (setenv "PATH" (format "%s/bin%s%s"
929036b4
FEG
1280 virtualenv path-separator
1281 (or (getenv "PATH") "")))
40417cb3
FEG
1282 (setenv "VIRTUAL_ENV" virtualenv))
1283 process-environment))
64348c32
FEG
1284
1285(defun python-shell-calculate-exec-path ()
1286 "Calculate exec path given `python-shell-virtualenv-path'."
40417cb3
FEG
1287 (let ((path (append python-shell-exec-path
1288 exec-path nil)))
64348c32
FEG
1289 (if (not python-shell-virtualenv-path)
1290 path
1291 (cons (format "%s/bin"
1292 (directory-file-name python-shell-virtualenv-path))
1293 path))))
1294
45c138ac
FEG
1295(defun python-comint-output-filter-function (output)
1296 "Hook run after content is put into comint buffer.
1297OUTPUT is a string with the contents of the buffer."
1298 (ansi-color-filter-apply output))
1299
45c138ac 1300(define-derived-mode inferior-python-mode comint-mode "Inferior Python"
62feb915 1301 "Major mode for Python inferior process.
e2d8d479
FEG
1302Runs a Python interpreter as a subprocess of Emacs, with Python
1303I/O through an Emacs buffer. Variables
1304`python-shell-interpreter' and `python-shell-interpreter-args'
1305controls which Python interpreter is run. Variables
1306`python-shell-prompt-regexp',
1307`python-shell-prompt-output-regexp',
1308`python-shell-prompt-block-regexp',
1309`python-shell-completion-setup-code',
9399498e 1310`python-shell-completion-string-code',
f6b59cd1 1311`python-shell-completion-module-string-code',
9399498e
FEG
1312`python-eldoc-setup-code', `python-eldoc-string-code',
1313`python-ffap-setup-code' and `python-ffap-string-code' can
1314customize this mode for different Python interpreters.
e2d8d479
FEG
1315
1316You can also add additional setup code to be run at
1317initialization of the interpreter via `python-shell-setup-codes'
1318variable.
1319
1320\(Type \\[describe-mode] in the process buffer for a list of commands.)"
45c138ac
FEG
1321 (set-syntax-table python-mode-syntax-table)
1322 (setq mode-line-process '(":%s"))
1323 (setq comint-prompt-regexp (format "^\\(?:%s\\|%s\\|%s\\)"
1324 python-shell-prompt-regexp
1325 python-shell-prompt-block-regexp
1326 python-shell-prompt-pdb-regexp))
1327 (make-local-variable 'comint-output-filter-functions)
1328 (add-hook 'comint-output-filter-functions
1329 'python-comint-output-filter-function)
1330 (add-hook 'comint-output-filter-functions
1331 'python-pdbtrack-comint-output-filter-function)
1332 (set (make-local-variable 'compilation-error-regexp-alist)
1333 python-shell-compilation-regexp-alist)
ed0eb594
FEG
1334 (define-key inferior-python-mode-map [remap complete-symbol]
1335 'completion-at-point)
1336 (add-hook 'completion-at-point-functions
1337 'python-shell-completion-complete-at-point nil 'local)
62feb915
FEG
1338 (add-to-list (make-local-variable 'comint-dynamic-complete-functions)
1339 'python-shell-completion-complete-at-point)
1340 (define-key inferior-python-mode-map (kbd "<tab>")
1341 'python-shell-completion-complete-or-indent)
45c138ac
FEG
1342 (compilation-shell-minor-mode 1))
1343
96eeb83a 1344(defun python-shell-make-comint (cmd proc-name &optional pop)
77afb61a 1345 "Create a python shell comint buffer.
96eeb83a 1346CMD is the python command to be executed and PROC-NAME is the
77afb61a 1347process name the comint buffer will get. After the comint buffer
96eeb83a
FEG
1348is created the `inferior-python-mode' is activated. If POP is
1349non-nil the buffer is shown."
77afb61a
FEG
1350 (save-excursion
1351 (let* ((proc-buffer-name (format "*%s*" proc-name))
307bd2e8 1352 (process-environment (python-shell-calculate-process-environment))
77afb61a
FEG
1353 (exec-path (python-shell-calculate-exec-path)))
1354 (when (not (comint-check-proc proc-buffer-name))
96eeb83a
FEG
1355 (let* ((cmdlist (split-string-and-unquote cmd))
1356 (buffer (apply 'make-comint proc-name (car cmdlist) nil
1357 (cdr cmdlist)))
d2190c57 1358 (current-buffer (current-buffer)))
96eeb83a
FEG
1359 (with-current-buffer buffer
1360 (inferior-python-mode)
fbc39529 1361 (python-util-clone-local-variables current-buffer))))
96eeb83a 1362 (when pop
a0686d71
FEG
1363 (pop-to-buffer proc-buffer-name))
1364 proc-buffer-name)))
77afb61a 1365
45c138ac
FEG
1366(defun run-python (dedicated cmd)
1367 "Run an inferior Python process.
e2d8d479
FEG
1368Input and output via buffer named after
1369`python-shell-buffer-name'. If there is a process already
1370running in that buffer, just switch to it.
1371With argument, allows you to define DEDICATED, so a dedicated
1372process for the current buffer is open, and define CMD so you can
1373edit the command used to call the interpreter (default is value
1374of `python-shell-interpreter' and arguments defined in
1375`python-shell-interpreter-args'). Runs the hook
1376`inferior-python-mode-hook' (after the `comint-mode-hook' is
1377run).
1378\(Type \\[describe-mode] in the process buffer for a list of commands.)"
45c138ac
FEG
1379 (interactive
1380 (if current-prefix-arg
1381 (list
1382 (y-or-n-p "Make dedicated process? ")
1383 (read-string "Run Python: " (python-shell-parse-command)))
1384 (list nil (python-shell-parse-command))))
96eeb83a 1385 (python-shell-make-comint cmd (python-shell-get-process-name dedicated) t)
45c138ac
FEG
1386 dedicated)
1387
1fe1b5aa
FEG
1388(defun run-python-internal ()
1389 "Run an inferior Internal Python process.
1390Input and output via buffer named after
1391`python-shell-internal-buffer-name' and what
1392`python-shell-internal-get-process-name' returns. This new kind
1393of shell is intended to be used for generic communication related
1394to defined configurations. The main difference with global or
1395dedicated shells is that these ones are attached to a
1396configuration, not a buffer. This means that can be used for
1397example to retrieve the sys.path and other stuff, without messing
1398with user shells. Runs the hook
1399`inferior-python-mode-hook' (after the `comint-mode-hook' is
1400run). \(Type \\[describe-mode] in the process buffer for a list
1401of commands.)"
1402 (interactive)
a0686d71
FEG
1403 (set-process-query-on-exit-flag
1404 (get-buffer-process
1405 (python-shell-make-comint
1406 (python-shell-parse-command)
1407 (python-shell-internal-get-process-name))) nil))
1fe1b5aa 1408
45c138ac
FEG
1409(defun python-shell-get-process ()
1410 "Get inferior Python process for current buffer and return it."
1411 (let* ((dedicated-proc-name (python-shell-get-process-name t))
1412 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1413 (global-proc-name (python-shell-get-process-name nil))
1414 (global-proc-buffer-name (format "*%s*" global-proc-name))
1415 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1416 (global-running (comint-check-proc global-proc-buffer-name)))
1417 ;; Always prefer dedicated
1418 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name)
1419 (and global-running global-proc-buffer-name)))))
1420
1421(defun python-shell-get-or-create-process ()
1422 "Get or create an inferior Python process for current buffer and return it."
79dafa51
FEG
1423 (let* ((old-buffer (current-buffer))
1424 (dedicated-proc-name (python-shell-get-process-name t))
45c138ac
FEG
1425 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name))
1426 (global-proc-name (python-shell-get-process-name nil))
1427 (global-proc-buffer-name (format "*%s*" global-proc-name))
1428 (dedicated-running (comint-check-proc dedicated-proc-buffer-name))
1429 (global-running (comint-check-proc global-proc-buffer-name))
1430 (current-prefix-arg 4))
1431 (when (and (not dedicated-running) (not global-running))
1432 (if (call-interactively 'run-python)
1433 (setq dedicated-running t)
1434 (setq global-running t)))
1435 ;; Always prefer dedicated
79dafa51 1436 (switch-to-buffer old-buffer)
45c138ac
FEG
1437 (get-buffer-process (if dedicated-running
1438 dedicated-proc-buffer-name
1439 global-proc-buffer-name))))
1440
722c985b
FEG
1441(defvar python-shell-internal-buffer nil
1442 "Current internal shell buffer for the current buffer.
1443This is really not necessary at all for the code to work but it's
1444there for compatibility with CEDET.")
1445(make-variable-buffer-local 'python-shell-internal-buffer)
1446
1fe1b5aa
FEG
1447(defun python-shell-internal-get-or-create-process ()
1448 "Get or create an inferior Internal Python process."
1449 (let* ((proc-name (python-shell-internal-get-process-name))
1450 (proc-buffer-name (format "*%s*" proc-name)))
1451 (run-python-internal)
722c985b 1452 (setq python-shell-internal-buffer proc-buffer-name)
1fe1b5aa
FEG
1453 (get-buffer-process proc-buffer-name)))
1454
722c985b
FEG
1455(define-obsolete-function-alias
1456 'python-proc 'python-shell-internal-get-or-create-process "23.3")
1457
1458(define-obsolete-variable-alias
1459 'python-buffer 'python-shell-internal-buffer "23.3")
1460
9ce938be
FEG
1461(defun python-shell-send-string (string &optional process msg)
1462 "Send STRING to inferior Python PROCESS.
1463When MSG is non-nil messages the first line of STRING."
45c138ac 1464 (interactive "sPython command: ")
9ce938be
FEG
1465 (let ((process (or process (python-shell-get-or-create-process)))
1466 (lines (split-string string "\n" t)))
1467 (when msg
1468 (message (format "Sent: %s..." (nth 0 lines))))
1469 (if (> (length lines) 1)
1470 (let* ((temp-file-name (make-temp-file "py"))
1471 (file-name (or (buffer-file-name) temp-file-name)))
1472 (with-temp-file temp-file-name
1473 (insert string)
1474 (delete-trailing-whitespace))
1475 (python-shell-send-file file-name process temp-file-name))
1476 (comint-send-string process string)
1477 (when (or (not (string-match "\n$" string))
1478 (string-match "\n[ \t].*\n?$" string))
1479 (comint-send-string process "\n")))))
1480
1481(defun python-shell-send-string-no-output (string &optional process msg)
1482 "Send STRING to PROCESS and inhibit output.
e2d8d479
FEG
1483When MSG is non-nil messages the first line of STRING. Return
1484the output."
9ce938be
FEG
1485 (let* ((output-buffer)
1486 (process (or process (python-shell-get-or-create-process)))
1487 (comint-preoutput-filter-functions
1488 (append comint-preoutput-filter-functions
1489 '(ansi-color-filter-apply
1490 (lambda (string)
1491 (setq output-buffer (concat output-buffer string))
1492 "")))))
1493 (python-shell-send-string string process msg)
1494 (accept-process-output process)
c7815c38
FEG
1495 (replace-regexp-in-string
1496 (if (> (length python-shell-prompt-output-regexp) 0)
1497 (format "\n*%s$\\|^%s\\|\n$"
1498 python-shell-prompt-regexp
1499 (or python-shell-prompt-output-regexp ""))
1500 (format "\n*$\\|^%s\\|\n$"
1501 python-shell-prompt-regexp))
1502 "" output-buffer)))
45c138ac 1503
1fe1b5aa
FEG
1504(defun python-shell-internal-send-string (string)
1505 "Send STRING to the Internal Python interpreter.
1506Returns the output. See `python-shell-send-string-no-output'."
1507 (python-shell-send-string-no-output
1508 ;; Makes this function compatible with the old
1509 ;; python-send-receive. (At least for CEDET).
1510 (replace-regexp-in-string "_emacs_out +" "" string)
1511 (python-shell-internal-get-or-create-process) nil))
1512
1513(define-obsolete-function-alias
722c985b
FEG
1514 'python-send-receive 'python-shell-internal-send-string "23.3")
1515
1516(define-obsolete-function-alias
1517 'python-send-string 'python-shell-internal-send-string "23.3")
1fe1b5aa 1518
45c138ac
FEG
1519(defun python-shell-send-region (start end)
1520 "Send the region delimited by START and END to inferior Python process."
1521 (interactive "r")
9ce938be
FEG
1522 (let ((deactivate-mark nil))
1523 (python-shell-send-string (buffer-substring start end) nil t)))
45c138ac
FEG
1524
1525(defun python-shell-send-buffer ()
1526 "Send the entire buffer to inferior Python process."
1527 (interactive)
1528 (save-restriction
1529 (widen)
1530 (python-shell-send-region (point-min) (point-max))))
1531
1532(defun python-shell-send-defun (arg)
2ed294c5 1533 "Send the current defun to inferior Python process.
45c138ac
FEG
1534When argument ARG is non-nil sends the innermost defun."
1535 (interactive "P")
1536 (save-excursion
2ed294c5
FEG
1537 (python-shell-send-region
1538 (progn
1539 (or (python-beginning-of-defun-function)
1540 (progn (beginning-of-line) (point-marker))))
1541 (progn
1542 (or (python-end-of-defun-function)
1543 (progn (end-of-line) (point-marker)))))))
45c138ac 1544
d439cda5
FEG
1545(defun python-shell-send-file (file-name &optional process temp-file-name)
1546 "Send FILE-NAME to inferior Python PROCESS.
1547If TEMP-FILE-NAME is passed then that file is used for processing
1548instead, while internally the shell will continue to use
1549FILE-NAME."
45c138ac 1550 (interactive "fFile to send: ")
9ce938be
FEG
1551 (let* ((process (or process (python-shell-get-or-create-process)))
1552 (temp-file-name (when temp-file-name
1553 (expand-file-name temp-file-name)))
1554 (file-name (or (expand-file-name file-name) temp-file-name)))
1555 (when (not file-name)
1556 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
13d914ed 1557 (python-shell-send-string
b962ebad 1558 (format
d439cda5
FEG
1559 (concat "__pyfile = open('''%s''');"
1560 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1561 "__pyfile.close()")
1562 (or temp-file-name file-name) file-name)
13d914ed 1563 process)))
45c138ac
FEG
1564
1565(defun python-shell-switch-to-shell ()
1566 "Switch to inferior Python process buffer."
1567 (interactive)
1568 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t))
1569
c0428ba0
FEG
1570(defun python-shell-send-setup-code ()
1571 "Send all setup code for shell.
1572This function takes the list of setup code to send from the
1573`python-shell-setup-codes' list."
1574 (let ((msg "Sent %s")
1575 (process (get-buffer-process (current-buffer))))
30e429dd 1576 (accept-process-output process python-shell-send-setup-max-wait)
c0428ba0
FEG
1577 (dolist (code python-shell-setup-codes)
1578 (when code
c0428ba0 1579 (message (format msg code))
a1ea6ab8 1580 (python-shell-send-string
c0428ba0
FEG
1581 (symbol-value code) process)))))
1582
1583(add-hook 'inferior-python-mode-hook
1584 #'python-shell-send-setup-code)
1585
45c138ac
FEG
1586\f
1587;;; Shell completion
1588
0f55249e 1589(defcustom python-shell-completion-setup-code
45c138ac
FEG
1590 "try:
1591 import readline
1592except ImportError:
1593 def __COMPLETER_all_completions(text): []
1594else:
1595 import rlcompleter
1596 readline.set_completer(rlcompleter.Completer().complete)
1597 def __COMPLETER_all_completions(text):
1598 import sys
1599 completions = []
1600 try:
1601 i = 0
1602 while True:
1603 res = readline.get_completer()(text, i)
1604 if not res: break
1605 i += 1
1606 completions.append(res)
1607 except NameError:
1608 pass
1609 return completions"
0f55249e
FEG
1610 "Code used to setup completion in inferior Python processes."
1611 :type 'string
1612 :group 'python
1613 :safe 'stringp)
45c138ac 1614
0f55249e 1615(defcustom python-shell-completion-string-code
45c138ac 1616 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
0f55249e
FEG
1617 "Python code used to get a string of completions separated by semicolons."
1618 :type 'string
1619 :group 'python
1620 :safe 'stringp)
45c138ac 1621
f6b59cd1 1622(defcustom python-shell-completion-module-string-code ""
8386d830 1623 "Python code used to get completions separated by semicolons for imports.
9253ea69
DD
1624
1625For IPython v0.11, add the following line to
1626`python-shell-completion-setup-code':
1627
1628from IPython.core.completerlib import module_completion
1629
1630and use the following as the value of this variable:
1631
1632';'.join(module_completion('''%s'''))\n"
1633 :type 'string
1634 :group 'python
1635 :safe 'stringp)
1636
aa409935
FEG
1637(defcustom python-shell-completion-pdb-string-code
1638 "';'.join(globals().keys() + locals().keys())"
1639 "Python code used to get completions separated by semicolons for [i]pdb."
1640 :type 'string
1641 :group 'python
1642 :safe 'stringp)
1643
f6b59cd1 1644(defvar python-shell-completion-original-window-configuration nil)
291e2b93 1645
9253ea69 1646(defun python-shell-completion--get-completions (input process completion-code)
8386d830
FEG
1647 "Retrieve available completions for INPUT using PROCESS.
1648Argument COMPLETION-CODE is the python code used to get
1649completions on the current context."
075a0f61 1650 (with-current-buffer (process-buffer process)
62feb915 1651 (let ((completions (python-shell-send-string-no-output
9253ea69 1652 (format completion-code input) process)))
62feb915
FEG
1653 (when (> (length completions) 2)
1654 (split-string completions "^'\\|^\"\\|;\\|'$\\|\"$" t)))))
075a0f61 1655
b71bfa9c 1656(defun python-shell-completion--do-completion-at-point (process)
8386d830 1657 "Do completion at point for PROCESS."
b71bfa9c 1658 (with-syntax-table python-dotty-syntax-table
9253ea69
DD
1659 (let* ((line (substring-no-properties
1660 (buffer-substring (point-at-bol) (point)) nil nil))
1661 (input (substring-no-properties
1662 (or (comint-word (current-word)) "") nil nil))
338a21d0
FEG
1663 (prompt (buffer-substring-no-properties
1664 (overlay-start comint-last-prompt-overlay)
1665 (overlay-end comint-last-prompt-overlay)))
aa409935
FEG
1666 (completion-code
1667 (cond ((and (> (length python-shell-completion-pdb-string-code) 0)
338a21d0
FEG
1668 (string-match
1669 (concat "^" python-shell-prompt-pdb-regexp) prompt))
aa409935
FEG
1670 python-shell-completion-pdb-string-code)
1671 ((and (> (length python-shell-completion-module-string-code) 0)
338a21d0
FEG
1672 (string-match
1673 (concat "^" python-shell-prompt-regexp) prompt)
1674 (string-match "^\\(from\\|import\\)[ \t]" line))
aa409935 1675 python-shell-completion-module-string-code)
338a21d0
FEG
1676 ((string-match
1677 (concat "^" python-shell-prompt-regexp) prompt)
1678 python-shell-completion-string-code)
1679 (t nil)))
aa409935 1680 (completions
338a21d0
FEG
1681 (and completion-code (> (length input) 0)
1682 (python-shell-completion--get-completions
1683 line process completion-code)))
9253ea69
DD
1684 (completion (when completions
1685 (try-completion input completions))))
b71bfa9c 1686 (cond ((eq completion t)
291e2b93 1687 (if (eq this-command last-command)
f6b59cd1 1688 (when python-shell-completion-original-window-configuration
291e2b93 1689 (set-window-configuration
f6b59cd1
FEG
1690 python-shell-completion-original-window-configuration)))
1691 (setq python-shell-completion-original-window-configuration nil)
291e2b93 1692 t)
b71bfa9c
DD
1693 ((null completion)
1694 (message "Can't find completion for \"%s\"" input)
1695 (ding)
338a21d0
FEG
1696 nil)
1697 ((not (string= input completion))
1698 (progn (delete-char (- (length input)))
1699 (insert completion)
1700 t))
1701 (t
1702 (unless python-shell-completion-original-window-configuration
1703 (setq python-shell-completion-original-window-configuration
1704 (current-window-configuration)))
1705 (with-output-to-temp-buffer "*Python Completions*"
1706 (display-completion-list
1707 (all-completions input completions)))
1708 t)))))
075a0f61 1709
45c138ac
FEG
1710(defun python-shell-completion-complete-at-point ()
1711 "Perform completion at point in inferior Python process."
1712 (interactive)
b71bfa9c
DD
1713 (and comint-last-prompt-overlay
1714 (> (point-marker) (overlay-end comint-last-prompt-overlay))
1715 (python-shell-completion--do-completion-at-point
1716 (get-buffer-process (current-buffer)))))
45c138ac 1717
45c138ac
FEG
1718(defun python-shell-completion-complete-or-indent ()
1719 "Complete or indent depending on the context.
e2d8d479
FEG
1720If content before pointer is all whitespace indent. If not try
1721to complete."
45c138ac
FEG
1722 (interactive)
1723 (if (string-match "^[[:space:]]*$"
1724 (buffer-substring (comint-line-beginning-position)
1725 (point-marker)))
1726 (indent-for-tab-command)
1727 (comint-dynamic-complete)))
1728
45c138ac
FEG
1729\f
1730;;; PDB Track integration
1731
76a9ea3b
FEG
1732(defcustom python-pdbtrack-activate t
1733 "Non-nil makes python shell enable pdbtracking."
1734 :type 'boolean
1735 :group 'python
1736 :safe 'booleanp)
1737
0f55249e 1738(defcustom python-pdbtrack-stacktrace-info-regexp
aeac8c27 1739 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
e2d8d479 1740 "Regular Expression matching stacktrace information.
aeac8c27 1741Used to extract the current line and module being inspected."
0f55249e
FEG
1742 :type 'string
1743 :group 'python
1744 :safe 'stringp)
45c138ac 1745
e1f00930
FEG
1746(defvar python-pdbtrack-tracked-buffer nil
1747 "Variable containing the value of the current tracked buffer.
1748Never set this variable directly, use
1749`python-pdbtrack-set-tracked-buffer' instead.")
1750(make-variable-buffer-local 'python-pdbtrack-tracked-buffer)
1751
1752(defvar python-pdbtrack-buffers-to-kill nil
1753 "List of buffers to be deleted after tracking finishes.")
1754(make-variable-buffer-local 'python-pdbtrack-buffers-to-kill)
1755
1756(defun python-pdbtrack-set-tracked-buffer (file-name)
1757 "Set the buffer for FILE-NAME as the tracked buffer.
1758Internally it uses the `python-pdbtrack-tracked-buffer' variable.
1759Returns the tracked buffer."
1760 (let ((file-buffer (get-file-buffer file-name)))
1761 (if file-buffer
1762 (setq python-pdbtrack-tracked-buffer file-buffer)
1763 (setq file-buffer (find-file-noselect file-name))
1764 (when (not (member file-buffer python-pdbtrack-buffers-to-kill))
1765 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer)))
1766 file-buffer))
45c138ac
FEG
1767
1768(defun python-pdbtrack-comint-output-filter-function (output)
1769 "Move overlay arrow to current pdb line in tracked buffer.
1770Argument OUTPUT is a string with the output from the comint process."
76a9ea3b 1771 (when (and python-pdbtrack-activate (not (string= output "")))
aeac8c27
FEG
1772 (let* ((full-output (ansi-color-filter-apply
1773 (buffer-substring comint-last-input-end (point-max))))
1774 (line-number)
1775 (file-name
1776 (with-temp-buffer
aeac8c27
FEG
1777 (insert full-output)
1778 (goto-char (point-min))
e1f00930
FEG
1779 ;; OK, this sucked but now it became a cool hack. The
1780 ;; stacktrace information normally is on the first line
1781 ;; but in some cases (like when doing a step-in) it is
1782 ;; on the second.
1783 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp)
1784 (and (forward-line)
1785 (looking-at python-pdbtrack-stacktrace-info-regexp)))
aeac8c27
FEG
1786 (setq line-number (string-to-number
1787 (match-string-no-properties 2)))
1788 (match-string-no-properties 1)))))
1789 (if (and file-name line-number)
e1f00930
FEG
1790 (let* ((tracked-buffer (python-pdbtrack-set-tracked-buffer file-name))
1791 (shell-buffer (current-buffer))
1792 (tracked-buffer-window (get-buffer-window tracked-buffer))
45c138ac 1793 (tracked-buffer-line-pos))
e1f00930 1794 (with-current-buffer tracked-buffer
aeac8c27
FEG
1795 (set (make-local-variable 'overlay-arrow-string) "=>")
1796 (set (make-local-variable 'overlay-arrow-position) (make-marker))
1797 (setq tracked-buffer-line-pos (progn
1798 (goto-char (point-min))
1799 (forward-line (1- line-number))
1800 (point-marker)))
1801 (when tracked-buffer-window
1802 (set-window-point
1803 tracked-buffer-window tracked-buffer-line-pos))
1804 (set-marker overlay-arrow-position tracked-buffer-line-pos))
e1f00930
FEG
1805 (pop-to-buffer tracked-buffer)
1806 (switch-to-buffer-other-window shell-buffer))
1807 (when python-pdbtrack-tracked-buffer
1808 (with-current-buffer python-pdbtrack-tracked-buffer
1809 (set-marker overlay-arrow-position nil))
1810 (mapc #'(lambda (buffer)
1811 (ignore-errors (kill-buffer buffer)))
1812 python-pdbtrack-buffers-to-kill)
1813 (setq python-pdbtrack-tracked-buffer nil
1814 python-pdbtrack-buffers-to-kill nil)))))
45c138ac
FEG
1815 output)
1816
1817\f
1818;;; Symbol completion
1819
1820(defun python-completion-complete-at-point ()
1821 "Complete current symbol at point.
1822For this to work the best as possible you should call
1823`python-shell-send-buffer' from time to time so context in
1824inferior python process is updated properly."
1825 (interactive)
1826 (let ((process (python-shell-get-process)))
1827 (if (not process)
4e531f7a 1828 (error "Completion needs an inferior Python process running")
b71bfa9c 1829 (python-shell-completion--do-completion-at-point process))))
45c138ac
FEG
1830
1831(add-to-list 'debug-ignored-errors "^Completion needs an inferior Python process running.")
1832
1833\f
1834;;; Fill paragraph
1835
c2cb97ae
FEG
1836(defcustom python-fill-comment-function 'python-fill-comment
1837 "Function to fill comments.
1838This is the function used by `python-fill-paragraph-function' to
1839fill comments."
1840 :type 'symbol
1841 :group 'python
1842 :safe 'symbolp)
1843
1844(defcustom python-fill-string-function 'python-fill-string
1845 "Function to fill strings.
1846This is the function used by `python-fill-paragraph-function' to
1847fill strings."
1848 :type 'symbol
1849 :group 'python
1850 :safe 'symbolp)
1851
1852(defcustom python-fill-decorator-function 'python-fill-decorator
1853 "Function to fill decorators.
1854This is the function used by `python-fill-paragraph-function' to
1855fill decorators."
1856 :type 'symbol
1857 :group 'python
1858 :safe 'symbolp)
1859
1860(defcustom python-fill-paren-function 'python-fill-paren
1861 "Function to fill parens.
1862This is the function used by `python-fill-paragraph-function' to
1863fill parens."
1864 :type 'symbol
1865 :group 'python
1866 :safe 'symbolp)
1867
45c138ac
FEG
1868(defun python-fill-paragraph-function (&optional justify)
1869 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1870If any of the current line is in or at the end of a multi-line string,
1871fill the string or the paragraph of it that point is in, preserving
4e531f7a
FEG
1872the string's indentation.
1873Optional argument JUSTIFY defines if the paragraph should be justified."
45c138ac
FEG
1874 (interactive "P")
1875 (save-excursion
1876 (back-to-indentation)
1877 (cond
1878 ;; Comments
c2cb97ae
FEG
1879 ((funcall python-fill-comment-function justify))
1880 ;; Strings/Docstrings
45c138ac 1881 ((save-excursion (skip-chars-forward "\"'uUrR")
14a78495 1882 (python-info-ppss-context 'string))
c2cb97ae 1883 (funcall python-fill-string-function justify))
45c138ac
FEG
1884 ;; Decorators
1885 ((equal (char-after (save-excursion
1886 (back-to-indentation)
c2cb97ae
FEG
1887 (point-marker))) ?@)
1888 (funcall python-fill-decorator-function justify))
45c138ac 1889 ;; Parens
14a78495 1890 ((or (python-info-ppss-context 'paren)
45c138ac
FEG
1891 (looking-at (python-rx open-paren))
1892 (save-excursion
1893 (skip-syntax-forward "^(" (line-end-position))
1894 (looking-at (python-rx open-paren))))
c2cb97ae 1895 (funcall python-fill-paren-function justify))
45c138ac
FEG
1896 (t t))))
1897
c2cb97ae 1898(defun python-fill-comment (&optional justify)
053a6c72
FEG
1899 "Comment fill function for `python-fill-paragraph-function'.
1900JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
1901 (fill-comment-paragraph justify))
1902
1903(defun python-fill-string (&optional justify)
053a6c72
FEG
1904 "String fill function for `python-fill-paragraph-function'.
1905JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
1906 (let ((marker (point-marker))
1907 (string-start-marker
1908 (progn
1909 (skip-chars-forward "\"'uUrR")
1910 (goto-char (python-info-ppss-context 'string))
1911 (skip-chars-forward "\"'uUrR")
1912 (point-marker)))
1913 (reg-start (line-beginning-position))
1914 (string-end-marker
1915 (progn
1916 (while (python-info-ppss-context 'string)
1917 (goto-char (1+ (point-marker))))
1918 (skip-chars-backward "\"'")
1919 (point-marker)))
1920 (reg-end (line-end-position))
1921 (fill-paragraph-function))
1922 (save-restriction
1923 (narrow-to-region reg-start reg-end)
1924 (save-excursion
1925 (goto-char string-start-marker)
1926 (delete-region (point-marker) (progn
1927 (skip-syntax-forward "> ")
1928 (point-marker)))
1929 (goto-char string-end-marker)
1930 (delete-region (point-marker) (progn
1931 (skip-syntax-backward "> ")
1932 (point-marker)))
1933 (save-excursion
1934 (goto-char marker)
1935 (fill-paragraph justify))
1936 ;; If there is a newline in the docstring lets put triple
1937 ;; quote in it's own line to follow pep 8
1938 (when (save-excursion
1939 (re-search-backward "\n" string-start-marker t))
1940 (newline)
1941 (newline-and-indent))
1942 (fill-paragraph justify)))) t)
1943
1944(defun python-fill-decorator (&optional justify)
053a6c72
FEG
1945 "Decorator fill function for `python-fill-paragraph-function'.
1946JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
1947 t)
1948
1949(defun python-fill-paren (&optional justify)
053a6c72
FEG
1950 "Paren fill function for `python-fill-paragraph-function'.
1951JUSTIFY should be used (if applicable) as in `fill-paragraph'."
c2cb97ae
FEG
1952 (save-restriction
1953 (narrow-to-region (progn
1954 (while (python-info-ppss-context 'paren)
1955 (goto-char (1- (point-marker))))
1956 (point-marker)
1957 (line-beginning-position))
1958 (progn
1959 (when (not (python-info-ppss-context 'paren))
1960 (end-of-line)
1961 (when (not (python-info-ppss-context 'paren))
1962 (skip-syntax-backward "^)")))
1963 (while (python-info-ppss-context 'paren)
1964 (goto-char (1+ (point-marker))))
1965 (point-marker)))
1966 (let ((paragraph-start "\f\\|[ \t]*$")
1967 (paragraph-separate ",")
1968 (fill-paragraph-function))
1969 (goto-char (point-min))
1970 (fill-paragraph justify))
1971 (while (not (eobp))
1972 (forward-line 1)
1973 (python-indent-line)
1974 (goto-char (line-end-position)))) t)
1975
45c138ac 1976\f
e2803784
FEG
1977;;; Skeletons
1978
1979(defcustom python-skeleton-autoinsert nil
1980 "Non-nil means template skeletons will be automagically inserted.
1981This happens when pressing \"if<SPACE>\", for example, to prompt for
1982the if condition."
1983 :type 'boolean
0f55249e
FEG
1984 :group 'python
1985 :safe 'booleanp)
e2803784
FEG
1986
1987(defvar python-skeleton-available '()
1988 "Internal list of available skeletons.")
e2803784
FEG
1989
1990(define-abbrev-table 'python-mode-abbrev-table ()
1991 "Abbrev table for Python mode."
1992 :case-fixed t
1993 ;; Allow / inside abbrevs.
1994 :regexp "\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1995 ;; Only expand in code.
1996 :enable-function (lambda ()
e2803784 1997 (and
14a78495
FEG
1998 (not (or (python-info-ppss-context 'string)
1999 (python-info-ppss-context 'comment)))
e2803784
FEG
2000 python-skeleton-autoinsert)))
2001
2002(defmacro python-skeleton-define (name doc &rest skel)
2003 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2004The skeleton will be bound to python-skeleton-NAME and will
2005be added to `python-mode-abbrev-table'."
2006 (let* ((name (symbol-name name))
2007 (function-name (intern (concat "python-skeleton-" name))))
73ed6836
FEG
2008 `(progn
2009 (define-abbrev python-mode-abbrev-table ,name "" ',function-name)
2010 (setq python-skeleton-available
2011 (cons ',function-name python-skeleton-available))
2012 (define-skeleton ,function-name
2013 ,(or doc
2014 (format "Insert %s statement." name))
2015 ,@skel))))
e2803784
FEG
2016(put 'python-skeleton-define 'lisp-indent-function 2)
2017
2018(defmacro python-define-auxiliary-skeleton (name doc &optional &rest skel)
2019 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2020The skeleton will be bound to python-skeleton-NAME."
2021 (let* ((name (symbol-name name))
2022 (function-name (intern (concat "python-skeleton--" name)))
2023 (msg (format
2024 "Add '%s' clause? " name)))
2025 (when (not skel)
2026 (setq skel
2027 `(< ,(format "%s:" name) \n \n
2028 > _ \n)))
2029 `(define-skeleton ,function-name
2030 ,(or doc
2031 (format "Auxiliary skeleton for %s statement." name))
2032 nil
2033 (unless (y-or-n-p ,msg)
2034 (signal 'quit t))
2035 ,@skel)))
2036(put 'python-define-auxiliary-skeleton 'lisp-indent-function 2)
2037
2038(python-define-auxiliary-skeleton else nil)
2039
2040(python-define-auxiliary-skeleton except nil)
2041
2042(python-define-auxiliary-skeleton finally nil)
2043
2044(python-skeleton-define if nil
2045 "Condition: "
2046 "if " str ":" \n
2047 _ \n
2048 ("other condition, %s: "
2049 <
2050 "elif " str ":" \n
2051 > _ \n nil)
2052 '(python-skeleton--else) | ^)
2053
2054(python-skeleton-define while nil
2055 "Condition: "
2056 "while " str ":" \n
2057 > _ \n
2058 '(python-skeleton--else) | ^)
2059
2060(python-skeleton-define for nil
2061 "Iteration spec: "
2062 "for " str ":" \n
2063 > _ \n
2064 '(python-skeleton--else) | ^)
2065
2066(python-skeleton-define try nil
2067 nil
2068 "try:" \n
2069 > _ \n
2070 ("Exception, %s: "
2071 <
2072 "except " str ":" \n
2073 > _ \n nil)
2074 resume:
2075 '(python-skeleton--except)
2076 '(python-skeleton--else)
2077 '(python-skeleton--finally) | ^)
2078
2079(python-skeleton-define def nil
2080 "Function name: "
2081 "def " str " (" ("Parameter, %s: "
2082 (unless (equal ?\( (char-before)) ", ")
2083 str) "):" \n
2084 "\"\"\"" - "\"\"\"" \n
2085 > _ \n)
2086
2087(python-skeleton-define class nil
2088 "Class name: "
2089 "class " str " (" ("Inheritance, %s: "
2090 (unless (equal ?\( (char-before)) ", ")
2091 str)
2092 & ")" | -2
2093 ":" \n
2094 "\"\"\"" - "\"\"\"" \n
2095 > _ \n)
2096
2097(defun python-skeleton-add-menu-items ()
2098 "Add menu items to Python->Skeletons menu."
2099 (let ((skeletons (sort python-skeleton-available 'string<))
2100 (items))
2101 (dolist (skeleton skeletons)
2102 (easy-menu-add-item
2103 nil '("Python" "Skeletons")
2104 `[,(format
2105 "Insert %s" (caddr (split-string (symbol-name skeleton) "-")))
2106 ,skeleton t]))))
2107\f
046428d3
FEG
2108;;; FFAP
2109
0f55249e 2110(defcustom python-ffap-setup-code
046428d3
FEG
2111 "def __FFAP_get_module_path(module):
2112 try:
2113 import os
2114 path = __import__(module).__file__
2115 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2116 path = path[:-1]
2117 return path
2118 except:
2119 return ''"
0f55249e
FEG
2120 "Python code to get a module path."
2121 :type 'string
2122 :group 'python
2123 :safe 'stringp)
046428d3 2124
0f55249e 2125(defcustom python-ffap-string-code
046428d3 2126 "__FFAP_get_module_path('''%s''')\n"
0f55249e
FEG
2127 "Python code used to get a string with the path of a module."
2128 :type 'string
2129 :group 'python
2130 :safe 'stringp)
046428d3 2131
046428d3
FEG
2132(defun python-ffap-module-path (module)
2133 "Function for `ffap-alist' to return path for MODULE."
2134 (let ((process (or
2135 (and (eq major-mode 'inferior-python-mode)
2136 (get-buffer-process (current-buffer)))
2137 (python-shell-get-process))))
2138 (if (not process)
2139 nil
2140 (let ((module-file
9ce938be 2141 (python-shell-send-string-no-output
046428d3
FEG
2142 (format python-ffap-string-code module) process)))
2143 (when module-file
2947016a 2144 (substring-no-properties module-file 1 -1))))))
046428d3
FEG
2145
2146(eval-after-load "ffap"
2147 '(progn
2148 (push '(python-mode . python-ffap-module-path) ffap-alist)
2149 (push '(inferior-python-mode . python-ffap-module-path) ffap-alist)))
2150
046428d3 2151\f
8b3e0e76
FEG
2152;;; Code check
2153
0f55249e 2154(defcustom python-check-command
8b3e0e76 2155 "pychecker --stdlib"
0f55249e
FEG
2156 "Command used to check a Python file."
2157 :type 'string
2158 :group 'python
2159 :safe 'stringp)
8b3e0e76
FEG
2160
2161(defvar python-check-custom-command nil
2162 "Internal use.")
2163
2164(defun python-check (command)
2165 "Check a Python file (default current buffer's file).
2166Runs COMMAND, a shell command, as if by `compile'. See
2167`python-check-command' for the default."
2168 (interactive
2169 (list (read-string "Check command: "
2170 (or python-check-custom-command
2171 (concat python-check-command " "
2172 (shell-quote-argument
2173 (or
2174 (let ((name (buffer-file-name)))
2175 (and name
2176 (file-name-nondirectory name)))
2177 "")))))))
2178 (setq python-check-custom-command command)
2179 (save-some-buffers (not compilation-ask-about-save) nil)
2180 (compilation-start command))
2181
2182\f
45c138ac
FEG
2183;;; Eldoc
2184
0f55249e 2185(defcustom python-eldoc-setup-code
45c138ac
FEG
2186 "def __PYDOC_get_help(obj):
2187 try:
15cc40b8 2188 import inspect
9e662938
FEG
2189 if hasattr(obj, 'startswith'):
2190 obj = eval(obj, globals())
15cc40b8
FEG
2191 doc = inspect.getdoc(obj)
2192 if not doc and callable(obj):
2193 target = None
2194 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2195 target = obj.__init__
2196 objtype = 'class'
2197 else:
2198 target = obj
2199 objtype = 'def'
2200 if target:
2201 args = inspect.formatargspec(
2202 *inspect.getargspec(target)
2203 )
2204 name = obj.__name__
2205 doc = '{objtype} {name}{args}'.format(
2206 objtype=objtype, name=name, args=args
2207 )
2208 else:
2209 doc = doc.splitlines()[0]
45c138ac 2210 except:
9e662938
FEG
2211 doc = ''
2212 try:
2213 exec('print doc')
2214 except SyntaxError:
2215 print(doc)"
0f55249e
FEG
2216 "Python code to setup documentation retrieval."
2217 :type 'string
2218 :group 'python
2219 :safe 'stringp)
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
2225 :group 'python
2226 :safe 'stringp)
45c138ac 2227
78334b43 2228(defun python-eldoc--get-doc-at-point (&optional force-input force-process)
d439cda5
FEG
2229 "Internal implementation to get documentation at point.
2230If not FORCE-INPUT is passed then what `current-word' returns
2231will be used. If not FORCE-PROCESS is passed what
2232`python-shell-get-process' returns is used."
78334b43 2233 (let ((process (or force-process (python-shell-get-process))))
45c138ac
FEG
2234 (if (not process)
2235 "Eldoc needs an inferior Python process running."
2236 (let* ((current-defun (python-info-current-defun))
78334b43
FEG
2237 (input (or force-input
2238 (with-syntax-table python-dotty-syntax-table
2239 (if (not current-defun)
2240 (current-word)
2241 (concat current-defun "." (current-word))))))
45c138ac
FEG
2242 (ppss (syntax-ppss))
2243 (help (when (and input
2244 (not (string= input (concat current-defun ".")))
14a78495
FEG
2245 (not (or (python-info-ppss-context 'string ppss)
2246 (python-info-ppss-context 'comment ppss))))
45c138ac
FEG
2247 (when (string-match (concat
2248 (regexp-quote (concat current-defun "."))
2249 "self\\.") input)
2250 (with-temp-buffer
2251 (insert input)
2252 (goto-char (point-min))
2253 (forward-word)
2254 (forward-char)
2255 (delete-region (point-marker) (search-forward "self."))
2256 (setq input (buffer-substring (point-min) (point-max)))))
9ce938be 2257 (python-shell-send-string-no-output
1066882c 2258 (format python-eldoc-string-code input) process))))
45c138ac
FEG
2259 (with-current-buffer (process-buffer process)
2260 (when comint-last-prompt-overlay
2261 (delete-region comint-last-input-end
2262 (overlay-start comint-last-prompt-overlay))))
2263 (when (and help
2264 (not (string= help "\n")))
2265 help)))))
2266
78334b43
FEG
2267(defun python-eldoc-function ()
2268 "`eldoc-documentation-function' for Python.
2269For this to work the best as possible you should call
2270`python-shell-send-buffer' from time to time so context in
2271inferior python process is updated properly."
2272 (python-eldoc--get-doc-at-point))
2273
2274(defun python-eldoc-at-point (symbol)
2275 "Get help on SYMBOL using `help'.
2276Interactively, prompt for symbol."
2277 (interactive
2278 (let ((symbol (with-syntax-table python-dotty-syntax-table
2279 (current-word)))
2280 (enable-recursive-minibuffers t))
2281 (list (read-string (if symbol
2282 (format "Describe symbol (default %s): " symbol)
2283 "Describe symbol: ")
2284 nil nil symbol))))
2285 (let ((process (python-shell-get-process)))
2286 (if (not process)
2287 (message "Eldoc needs an inferior Python process running.")
15cc40b8 2288 (message (python-eldoc--get-doc-at-point symbol process)))))
78334b43 2289
45c138ac 2290\f
fc2dc7df
FEG
2291;;; Imenu
2292
2293(defcustom python-imenu-include-defun-type t
2294 "Non-nil make imenu items to include its type."
2295 :type 'boolean
2296 :group 'python
2297 :safe 'booleanp)
2298
c942de99 2299(defcustom python-imenu-make-tree t
fc2dc7df
FEG
2300 "Non-nil make imenu to build a tree menu.
2301Set to nil for speed."
2302 :type 'boolean
2303 :group 'python
2304 :safe 'booleanp)
2305
2306(defcustom python-imenu-subtree-root-label "<Jump to %s>"
2307 "Label displayed to navigate to root from a subtree.
2308It can contain a \"%s\" which will be replaced with the root name."
2309 :type 'string
2310 :group 'python
2311 :safe 'stringp)
2312
2313(defvar python-imenu-index-alist nil
2314 "Calculated index tree for imenu.")
2315
2316(defun python-imenu-tree-assoc (keylist tree)
2317 "Using KEYLIST traverse TREE."
2318 (if keylist
2319 (python-imenu-tree-assoc (cdr keylist)
2320 (ignore-errors (assoc (car keylist) tree)))
2321 tree))
2322
2323(defun python-imenu-make-element-tree (element-list full-element plain-index)
2324 "Make a tree from plain alist of module names.
2325ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2326is the same thing, the difference is that FULL-ELEMENT remains
2327untouched in all recursive calls.
2328Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2329 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist))
2330 (when element-list
2331 (let* ((subelement-point (cdr (assoc
2332 (mapconcat #'identity full-element ".")
2333 plain-index)))
2334 (subelement-name (car element-list))
c942de99
FEG
2335 (subelement-position (python-util-position
2336 subelement-name full-element))
fc2dc7df
FEG
2337 (subelement-path (when subelement-position
2338 (butlast
2339 full-element
2340 (- (length full-element)
2341 subelement-position)))))
2342 (let ((path-ref (python-imenu-tree-assoc subelement-path
2343 python-imenu-index-alist)))
2344 (if (not path-ref)
2345 (push (cons subelement-name subelement-point)
2346 python-imenu-index-alist)
2347 (when (not (listp (cdr path-ref)))
2348 ;; Modifiy root cdr to be a list
2349 (setcdr path-ref
2350 (list (cons (format python-imenu-subtree-root-label
2351 (car path-ref))
2352 (cdr (assoc
2353 (mapconcat #'identity
2354 subelement-path ".")
2355 plain-index))))))
2356 (when (not (assoc subelement-name path-ref))
2357 (push (cons subelement-name subelement-point) (cdr path-ref))))))
2358 (python-imenu-make-element-tree (cdr element-list)
2359 full-element plain-index))))
2360
2361(defun python-imenu-make-tree (index)
fc6c545e 2362 "Build the imenu alist tree from plain INDEX.
fc2dc7df
FEG
2363
2364The idea of this function is that given the alist:
2365
2366 '((\"Test\" . 100)
2367 (\"Test.__init__\" . 200)
2368 (\"Test.some_method\" . 300)
2369 (\"Test.some_method.another\" . 400)
2370 (\"Test.something_else\" . 500)
2371 (\"test\" . 600)
2372 (\"test.reprint\" . 700)
2373 (\"test.reprint\" . 800))
2374
2375This tree gets built:
2376
2377 '((\"Test\" . ((\"jump to...\" . 100)
2378 (\"__init__\" . 200)
2379 (\"some_method\" . ((\"jump to...\" . 300)
2380 (\"another\" . 400)))
2381 (\"something_else\" . 500)))
2382 (\"test\" . ((\"jump to...\" . 600)
2383 (\"reprint\" . 700)
2384 (\"reprint\" . 800))))
2385
2386Internally it uses `python-imenu-make-element-tree' to create all
2387branches for each element."
fc6c545e
FEG
2388 (setq python-imenu-index-alist nil)
2389 (mapc (lambda (element)
2390 (python-imenu-make-element-tree element element index))
2391 (mapcar (lambda (element)
2392 (split-string (car element) "\\." t)) index))
2393 python-imenu-index-alist)
fc2dc7df
FEG
2394
2395(defun python-imenu-create-index ()
2396 "`imenu-create-index-function' for Python."
fc6c545e
FEG
2397 (let ((index
2398 (python-nav-list-defun-positions python-imenu-include-defun-type)))
fc2dc7df
FEG
2399 (if python-imenu-make-tree
2400 (python-imenu-make-tree index)
2401 index)))
2402
2403\f
45c138ac
FEG
2404;;; Misc helpers
2405
fc2dc7df 2406(defun python-info-current-defun (&optional include-type)
45c138ac 2407 "Return name of surrounding function with Python compatible dotty syntax.
fc2dc7df 2408Optional argument INCLUDE-TYPE indicates to include the type of the defun.
45c138ac
FEG
2409This function is compatible to be used as
2410`add-log-current-defun-function' since it returns nil if point is
2411not inside a defun."
6b432853 2412 (let ((names '())
0b7b2e51
FEG
2413 (min-indent)
2414 (first-run t))
45c138ac
FEG
2415 (save-restriction
2416 (widen)
2417 (save-excursion
6b432853 2418 (goto-char (line-end-position))
589cefd7 2419 (forward-comment -9999)
15cc40b8 2420 (setq min-indent (current-indentation))
fc2dc7df 2421 (while (python-beginning-of-defun-function 1 t)
0b7b2e51
FEG
2422 (when (or (< (current-indentation) min-indent)
2423 first-run)
2424 (setq first-run nil)
6b432853 2425 (setq min-indent (current-indentation))
af5c1beb 2426 (looking-at python-nav-beginning-of-defun-regexp)
fc2dc7df
FEG
2427 (setq names (cons
2428 (if (not include-type)
2429 (match-string-no-properties 1)
2430 (mapconcat 'identity
2431 (split-string
2432 (match-string-no-properties 0)) " "))
2433 names))))))
45c138ac
FEG
2434 (when names
2435 (mapconcat (lambda (string) string) names "."))))
2436
2437(defun python-info-closing-block ()
e2d8d479 2438 "Return the point of the block the current line closes."
45c138ac
FEG
2439 (let ((closing-word (save-excursion
2440 (back-to-indentation)
2441 (current-word)))
2442 (indentation (current-indentation)))
2443 (when (member closing-word python-indent-dedenters)
2444 (save-excursion
2445 (forward-line -1)
2446 (while (and (> (current-indentation) indentation)
2447 (not (bobp))
2448 (not (back-to-indentation))
2449 (forward-line -1)))
2450 (back-to-indentation)
2451 (cond
2452 ((not (equal indentation (current-indentation))) nil)
2453 ((string= closing-word "elif")
2454 (when (member (current-word) '("if" "elif"))
2455 (point-marker)))
2456 ((string= closing-word "else")
2457 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2458 (point-marker)))
2459 ((string= closing-word "except")
2460 (when (member (current-word) '("try"))
2461 (point-marker)))
2462 ((string= closing-word "finally")
2463 (when (member (current-word) '("except" "else"))
2464 (point-marker))))))))
2465
2466(defun python-info-line-ends-backslash-p ()
2467 "Return non-nil if current line ends with backslash."
2468 (string= (or (ignore-errors
2469 (buffer-substring
2470 (line-end-position)
2471 (- (line-end-position) 1))) "") "\\"))
2472
2473(defun python-info-continuation-line-p ()
2474 "Return non-nil if current line is continuation of another."
85655287
FEG
2475 (let ((current-ppss-context-type (python-info-ppss-context-type)))
2476 (and
2477 (equal (save-excursion
2478 (goto-char (line-end-position))
2479 (forward-comment 9999)
2480 (python-info-ppss-context-type))
2481 current-ppss-context-type)
2482 (or (python-info-line-ends-backslash-p)
2483 (string-match ",[[:space:]]*$" (buffer-substring
2484 (line-beginning-position)
2485 (line-end-position)))
2486 (save-excursion
2487 (let ((innermost-paren (progn
2488 (goto-char (line-end-position))
2489 (python-info-ppss-context 'paren))))
2490 (when (and innermost-paren
2491 (and (<= (line-beginning-position) innermost-paren)
2492 (>= (line-end-position) innermost-paren)))
2493 (goto-char innermost-paren)
2494 (looking-at (python-rx open-paren (* space) line-end)))))
2495 (save-excursion
2496 (back-to-indentation)
2497 (python-info-ppss-context 'paren))))))
45c138ac
FEG
2498
2499(defun python-info-block-continuation-line-p ()
2500 "Return non-nil if current line is a continuation of a block."
2501 (save-excursion
2502 (while (and (not (bobp))
2503 (python-info-continuation-line-p))
2504 (forward-line -1))
2505 (forward-line 1)
2506 (back-to-indentation)
2507 (when (looking-at (python-rx block-start))
2508 (point-marker))))
2509
2510(defun python-info-assignment-continuation-line-p ()
2511 "Return non-nil if current line is a continuation of an assignment."
2512 (save-excursion
2513 (while (and (not (bobp))
2514 (python-info-continuation-line-p))
2515 (forward-line -1))
2516 (forward-line 1)
2517 (back-to-indentation)
2518 (when (and (not (looking-at (python-rx block-start)))
2519 (save-excursion
2520 (and (re-search-forward (python-rx not-simple-operator
2521 assignment-operator
2522 not-simple-operator)
2523 (line-end-position) t)
14a78495 2524 (not (or (python-info-ppss-context 'string)
9f1537ef 2525 (python-info-ppss-context 'paren)
14a78495 2526 (python-info-ppss-context 'comment))))))
45c138ac
FEG
2527 (point-marker))))
2528
14a78495
FEG
2529(defun python-info-ppss-context (type &optional syntax-ppss)
2530 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
85655287 2531TYPE can be 'comment, 'string or 'paren. It returns the start
14a78495
FEG
2532character address of the specified TYPE."
2533 (let ((ppss (or syntax-ppss (syntax-ppss))))
2534 (case type
2535 ('comment
2536 (and (nth 4 ppss)
2537 (nth 8 ppss)))
2538 ('string
2539 (nth 8 ppss))
2540 ('paren
2541 (nth 1 ppss))
2542 (t nil))))
2543
85655287
FEG
2544(defun python-info-ppss-context-type (&optional syntax-ppss)
2545 "Return the context type using SYNTAX-PPSS.
2546The type returned can be 'comment, 'string or 'paren."
2547 (let ((ppss (or syntax-ppss (syntax-ppss))))
2548 (cond
2549 ((and (nth 4 ppss)
2550 (nth 8 ppss))
2551 'comment)
2552 ((nth 8 ppss)
2553 'string)
2554 ((nth 1 ppss)
2555 'paren)
2556 (t nil))))
2557
45c138ac 2558\f
c942de99
FEG
2559;;; Utility functions
2560
c942de99
FEG
2561(defun python-util-position (item seq)
2562 "Find the first occurrence of ITEM in SEQ.
2563Return the index of the matching item, or nil if not found."
2564 (let ((member-result (member item seq)))
2565 (when member-result
2566 (- (length seq) (length member-result)))))
2567
d2190c57 2568;; Stolen from org-mode
fbc39529 2569(defun python-util-clone-local-variables (from-buffer &optional regexp)
d2190c57
FEG
2570 "Clone local variables from FROM-BUFFER.
2571Optional argument REGEXP selects variables to clone and defaults
2572to \"^python-\"."
2573 (mapc
2574 (lambda (pair)
2575 (and (symbolp (car pair))
2576 (string-match (or regexp "^python-")
2577 (symbol-name (car pair)))
2578 (set (make-local-variable (car pair))
2579 (cdr pair))))
2580 (buffer-local-variables from-buffer)))
2581
c942de99 2582\f
45c138ac
FEG
2583;;;###autoload
2584(define-derived-mode python-mode fundamental-mode "Python"
e2d8d479
FEG
2585 "Major mode for editing Python files.
2586
2587\\{python-mode-map}
2588Entry to this mode calls the value of `python-mode-hook'
2589if that value is non-nil."
45c138ac
FEG
2590 (set (make-local-variable 'tab-width) 8)
2591 (set (make-local-variable 'indent-tabs-mode) nil)
2592
2593 (set (make-local-variable 'comment-start) "# ")
2594 (set (make-local-variable 'comment-start-skip) "#+\\s-*")
2595
2596 (set (make-local-variable 'parse-sexp-lookup-properties) t)
2597 (set (make-local-variable 'parse-sexp-ignore-comments) t)
2598
2599 (set (make-local-variable 'font-lock-defaults)
2600 '(python-font-lock-keywords
2601 nil nil nil nil
2602 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords)))
2603
2604 (set (make-local-variable 'indent-line-function) #'python-indent-line-function)
2605 (set (make-local-variable 'indent-region-function) #'python-indent-region)
2606
2607 (set (make-local-variable 'paragraph-start) "\\s-*$")
2608 (set (make-local-variable 'fill-paragraph-function) 'python-fill-paragraph-function)
2609
2610 (set (make-local-variable 'beginning-of-defun-function)
2611 #'python-beginning-of-defun-function)
2612 (set (make-local-variable 'end-of-defun-function)
2613 #'python-end-of-defun-function)
2614
2615 (add-hook 'completion-at-point-functions
2616 'python-completion-complete-at-point nil 'local)
2617
fc2dc7df
FEG
2618 (setq imenu-create-index-function #'python-imenu-create-index)
2619
45c138ac
FEG
2620 (set (make-local-variable 'add-log-current-defun-function)
2621 #'python-info-current-defun)
2622
e2803784
FEG
2623 (set (make-local-variable 'skeleton-further-elements)
2624 '((abbrev-mode nil)
2625 (< '(backward-delete-char-untabify (min python-indent-offset
2626 (current-column))))
2627 (^ '(- (1+ (current-indentation))))))
2628
45c138ac
FEG
2629 (set (make-local-variable 'eldoc-documentation-function)
2630 #'python-eldoc-function)
2631
2632 (add-to-list 'hs-special-modes-alist
2633 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil "#"
2634 ,(lambda (arg)
2635 (python-end-of-defun-function)) nil))
2636
82c2b0de
FEG
2637 (set (make-local-variable 'mode-require-final-newline) t)
2638
45c138ac
FEG
2639 (set (make-local-variable 'outline-regexp)
2640 (python-rx (* space) block-start))
2641 (set (make-local-variable 'outline-heading-end-regexp) ":\\s-*\n")
2642 (set (make-local-variable 'outline-level)
2643 #'(lambda ()
2644 "`outline-level' function for Python mode."
2645 (1+ (/ (current-indentation) python-indent-offset))))
2646
e2803784
FEG
2647 (python-skeleton-add-menu-items)
2648
45c138ac
FEG
2649 (when python-indent-guess-indent-offset
2650 (python-indent-guess-indent-offset)))
2651
2652
2653(provide 'python)
2654;;; python.el ends here