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