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