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