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