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