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