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