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