1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2003-2012 Free Software Foundation, Inc.
5 ;; Author: Fabián E. Gallina <fabian@anue.biz>
6 ;; URL: https://github.com/fgallina/python.el
10 ;; Keywords: languages
12 ;; This file is part of GNU Emacs.
14 ;; GNU Emacs is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published
16 ;; by the Free Software Foundation, either version 3 of the License,
17 ;; or (at your option) any later version.
19 ;; GNU Emacs is distributed in the hope that it will be useful, but
20 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 ;; General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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.
33 ;; Implements Syntax highlighting, Indentation, Movement, Shell
34 ;; interaction, Shell completion, Shell virtualenv support, Pdb
35 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
38 ;; Syntax highlighting: Fontification of code is provided and supports
39 ;; python's triple quoted strings properly.
41 ;; Indentation: Automatic indentation with indentation cycling is
42 ;; provided, it allows you to navigate different available levels of
43 ;; indentation by hitting <tab> several times. Also when inserting a
44 ;; colon the `python-indent-electric-colon' command is invoked and
45 ;; causes the current line to be dedented automatically if needed.
47 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
48 ;; properly implemented. There are also specialized
49 ;; `forward-sentence' and `backward-sentence' replacements called
50 ;; `python-nav-forward-block', `python-nav-backward-block'
51 ;; respectively which navigate between beginning of blocks of code.
52 ;; Extra functions `python-nav-forward-statement',
53 ;; `python-nav-backward-statement',
54 ;; `python-nav-beginning-of-statement', `python-nav-end-of-statement',
55 ;; `python-nav-beginning-of-block' and `python-nav-end-of-block' are
56 ;; included but no bound to any key. At last but not least the
57 ;; specialized `python-nav-forward-sexp-function' allows easy
58 ;; navigation between code blocks.
60 ;; Shell interaction: is provided and allows you to execute easily any
61 ;; block of code of your current buffer in an inferior Python process.
63 ;; Shell completion: hitting tab will try to complete the current
64 ;; word. Shell completion is implemented in a manner that if you
65 ;; change the `python-shell-interpreter' to any other (for example
66 ;; IPython) it should be easy to integrate another way to calculate
67 ;; completions. You just need to specify your custom
68 ;; `python-shell-completion-setup-code' and
69 ;; `python-shell-completion-string-code'.
71 ;; Here is a complete example of the settings you would use for
75 ;; python-shell-interpreter "ipython"
76 ;; python-shell-interpreter-args ""
77 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
78 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
79 ;; python-shell-completion-setup-code
80 ;; "from IPython.core.completerlib import module_completion"
81 ;; python-shell-completion-module-string-code
82 ;; "';'.join(module_completion('''%s'''))\n"
83 ;; python-shell-completion-string-code
84 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
86 ;; For iPython 0.10 everything would be the same except for
87 ;; `python-shell-completion-string-code' and
88 ;; `python-shell-completion-module-string-code':
90 ;; (setq python-shell-completion-string-code
91 ;; "';'.join(__IP.complete('''%s'''))\n"
92 ;; python-shell-completion-module-string-code "")
94 ;; Unfortunately running iPython on Windows needs some more tweaking.
95 ;; The way you must set `python-shell-interpreter' and
96 ;; `python-shell-interpreter-args' is as follows:
99 ;; python-shell-interpreter "C:\\Python27\\python.exe"
100 ;; python-shell-interpreter-args
101 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
103 ;; That will spawn the iPython process correctly (Of course you need
104 ;; to modify the paths according to your system).
106 ;; Please note that the default completion system depends on the
107 ;; readline module, so if you are using some Operating System that
108 ;; bundles Python without it (like Windows) just install the
109 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
110 ;; you should be good to go.
112 ;; Shell virtualenv support: The shell also contains support for
113 ;; virtualenvs and other special environment modifications thanks to
114 ;; `python-shell-process-environment' and `python-shell-exec-path'.
115 ;; These two variables allows you to modify execution paths and
116 ;; environment variables to make easy for you to setup virtualenv rules
117 ;; or behavior modifications when running shells. Here is an example
118 ;; of how to make shell processes to be run using the /path/to/env/
121 ;; (setq python-shell-process-environment
123 ;; (format "PATH=%s" (mapconcat
126 ;; (cons (getenv "PATH")
127 ;; '("/path/to/env/bin/")))
129 ;; "VIRTUAL_ENV=/path/to/env/"))
130 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
132 ;; Since the above is cumbersome and can be programmatically
133 ;; calculated, the variable `python-shell-virtualenv-path' is
134 ;; provided. When this variable is set with the path of the
135 ;; virtualenv to use, `process-environment' and `exec-path' get proper
136 ;; values in order to run shells inside the specified virtualenv. So
137 ;; the following will achieve the same as the previous example:
139 ;; (setq python-shell-virtualenv-path "/path/to/env/")
141 ;; Also the `python-shell-extra-pythonpaths' variable have been
142 ;; introduced as simple way of adding paths to the PYTHONPATH without
143 ;; affecting existing values.
145 ;; Pdb tracking: when you execute a block of code that contains some
146 ;; call to pdb (or ipdb) it will prompt the block of code and will
147 ;; follow the execution of pdb marking the current line with an arrow.
149 ;; Symbol completion: you can complete the symbol at point. It uses
150 ;; the shell completion in background so you should run
151 ;; `python-shell-send-buffer' from time to time to get better results.
153 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
154 ;; def, for, if, try and while. These skeletons are integrated with
155 ;; dabbrev. If you have `dabbrev-mode' activated and
156 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
157 ;; the name of any of those defined and hit SPC, they will be
158 ;; automatically expanded.
160 ;; FFAP: You can find the filename for a given module when using ffap
161 ;; out of the box. This feature needs an inferior python shell
164 ;; Code check: Check the current file for errors with `python-check'
165 ;; using the program defined in `python-check-command'.
167 ;; Eldoc: returns documentation for object at point by using the
168 ;; inferior python subprocess to inspect its documentation. As you
169 ;; might guessed you should run `python-shell-send-buffer' from time
170 ;; to time to get better results too.
172 ;; imenu: This mode supports imenu in its most basic form, letting it
173 ;; build the necessary alist via `imenu-default-create-index-function'
174 ;; by having set `imenu-extract-index-name-function' to
175 ;; `python-info-current-defun'.
177 ;; If you used python-mode.el you probably will miss auto-indentation
178 ;; when inserting newlines. To achieve the same behavior you have
181 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
183 ;; 2) Add the following hook in your .emacs:
185 ;; (add-hook 'python-mode-hook
187 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
189 ;; I'd recommend the first one since you'll get the same behavior for
190 ;; all modes out-of-the-box.
194 ;; Add this to your .emacs:
196 ;; (add-to-list 'load-path "/folder/containing/file")
203 (require 'ansi-color
)
208 ;; Avoid compiler warnings
209 (defvar view-return-to-alist
)
210 (defvar compilation-error-regexp-alist
)
211 (defvar outline-heading-end-regexp
))
213 (autoload 'comint-mode
"comint")
216 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
218 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
221 "Python Language's flying circus support for Emacs."
224 :link
'(emacs-commentary-link "python"))
229 (defvar python-mode-map
230 (let ((map (make-sparse-keymap)))
232 (substitute-key-definition 'backward-sentence
233 'python-nav-backward-block
235 (substitute-key-definition 'forward-sentence
236 'python-nav-forward-block
238 (define-key map
"\C-c\C-j" 'imenu
)
240 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
241 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
242 (define-key map
"\C-c<" 'python-indent-shift-left
)
243 (define-key map
"\C-c>" 'python-indent-shift-right
)
244 (define-key map
":" 'python-indent-electric-colon
)
246 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
247 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
248 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
249 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
250 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
251 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
253 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
254 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
255 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
256 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
257 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
258 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
259 ;; Some util commands
260 (define-key map
"\C-c\C-v" 'python-check
)
261 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
263 (substitute-key-definition 'complete-symbol
'completion-at-point
265 (easy-menu-define python-menu map
"Python Mode menu"
267 :help
"Python-specific Features"
268 ["Shift region left" python-indent-shift-left
:active mark-active
269 :help
"Shift region left by a single indentation step"]
270 ["Shift region right" python-indent-shift-right
:active mark-active
271 :help
"Shift region right by a single indentation step"]
273 ["Start of def/class" beginning-of-defun
274 :help
"Go to start of outermost definition around point"]
275 ["End of def/class" end-of-defun
276 :help
"Go to end of definition around point"]
277 ["Mark def/class" mark-defun
278 :help
"Mark outermost definition around point"]
279 ["Jump to def/class" imenu
280 :help
"Jump to a class or function definition"]
284 ["Start interpreter" run-python
285 :help
"Run inferior Python process in a separate buffer"]
286 ["Switch to shell" python-shell-switch-to-shell
287 :help
"Switch to running inferior Python process"]
288 ["Eval string" python-shell-send-string
289 :help
"Eval string in inferior Python session"]
290 ["Eval buffer" python-shell-send-buffer
291 :help
"Eval buffer in inferior Python session"]
292 ["Eval region" python-shell-send-region
293 :help
"Eval region in inferior Python session"]
294 ["Eval defun" python-shell-send-defun
295 :help
"Eval defun in inferior Python session"]
296 ["Eval file" python-shell-send-file
297 :help
"Eval file in inferior Python session"]
298 ["Debugger" pdb
:help
"Run pdb under GUD"]
300 ["Check file" python-check
301 :help
"Check file for errors"]
302 ["Help on symbol" python-eldoc-at-point
303 :help
"Get help on symbol at point"]
304 ["Complete symbol" completion-at-point
305 :help
"Complete symbol before point"]))
307 "Keymap for `python-mode'.")
310 ;;; Python specialized rx
313 (defconst python-rx-constituents
314 `((block-start .
,(rx symbol-start
315 (or "def" "class" "if" "elif" "else" "try"
316 "except" "finally" "for" "while" "with")
318 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
320 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
321 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
322 (+ space
) "==" (+ space
)
323 (any ?
' ?
\") "__main__" (any ?
' ?
\")
325 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
326 (open-paren .
,(rx (or "{" "[" "(")))
327 (close-paren .
,(rx (or "}" "]" ")")))
328 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
329 ;; FIXME: rx should support (not simple-operator).
330 (not-simple-operator .
,(rx
332 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
333 ;; FIXME: Use regexp-opt.
334 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
335 "=" "%" "**" "//" "<<" ">>" "<=" "!="
336 "==" ">=" "is" "not")))
337 ;; FIXME: Use regexp-opt.
338 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
339 ">>=" "<<=" "&=" "^=" "|="))))
340 "Additional Python specific sexps for `python-rx'"))
342 (defmacro python-rx
(&rest regexps
)
343 "Python mode specialized rx macro.
344 This variant of `rx' supports common python named REGEXPS."
345 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
346 (cond ((null regexps
)
349 (rx-to-string `(and ,@regexps
) t
))
351 (rx-to-string (car regexps
) t
)))))
354 ;;; Font-lock and syntax
355 (defvar python-font-lock-keywords
359 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
360 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
361 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
366 ;; False, None, and True are listed as keywords on the Python 3
367 ;; documentation, but since they also qualify as constants they are
368 ;; fontified like that in order to keep font-lock consistent between
375 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
376 (1 font-lock-function-name-face
))
378 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
379 (1 font-lock-type-face
))
383 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
384 ;; copyright, license, credits, quit and exit are added by the site
385 ;; module and they are not intended to be used in programs
386 "copyright" "credits" "exit" "license" "quit")
387 symbol-end
) . font-lock-constant-face
)
389 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
390 (0+ "." (1+ (or word ?_
)))))
391 (1 font-lock-type-face
))
392 ;; Builtin Exceptions
395 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
396 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
397 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
398 "ImportError" "ImportWarning" "IndexError" "KeyError"
399 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
400 "NotImplementedError" "OSError" "OverflowError"
401 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
402 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
403 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
404 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
405 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
406 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
410 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
412 symbol-end
) . font-lock-type-face
)
416 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
417 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
418 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
419 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
420 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
421 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
422 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
423 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
426 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
427 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
430 "ascii" "bytearray" "bytes" "exec"
432 "__all__" "__doc__" "__name__" "__package__")
433 symbol-end
) . font-lock-builtin-face
)
435 ;; support for a = b = c = 5
437 (let ((re (python-rx (group (+ (any word ?. ?_
)))
438 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
439 assignment-operator
)))
440 (when (re-search-forward re limit t
)
441 (while (and (python-info-ppss-context 'paren
)
442 (re-search-forward re limit t
)))
443 (if (and (not (python-info-ppss-context 'paren
))
444 (not (equal (char-after (point-marker)) ?
=)))
446 (set-match-data nil
)))))
447 (1 font-lock-variable-name-face nil nil
))
448 ;; support for a, b, c = (1, 2, 3)
450 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
451 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
452 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
453 assignment-operator
)))
454 (when (and (re-search-forward re limit t
)
455 (goto-char (nth 3 (match-data))))
456 (while (and (python-info-ppss-context 'paren
)
457 (re-search-forward re limit t
))
458 (goto-char (nth 3 (match-data))))
459 (if (not (python-info-ppss-context 'paren
))
461 (set-match-data nil
)))))
462 (1 font-lock-variable-name-face nil nil
))))
464 (defconst python-syntax-propertize-function
465 ;; Make outer chars of matching triple-quote sequences into generic
466 ;; string delimiters. Fixme: Is there a better way?
467 ;; First avoid a sequence preceded by an odd number of backslashes.
468 (syntax-propertize-rules
469 (;; ¡Backrefs don't work in syntax-propertize-rules!
470 (concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
471 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
472 (3 (ignore (python-quote-syntax))))))
474 (defun python-quote-syntax ()
475 "Put `syntax-table' property correctly on triple quote.
476 Used for syntactic keywords. N is the match number (1, 2 or 3)."
477 ;; Given a triple quote, we have to check the context to know
478 ;; whether this is an opening or closing triple or whether it's
479 ;; quoted anyhow, and should be ignored. (For that we need to do
480 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
481 ;; to use it here despite initial worries.) We also have to sort
482 ;; out a possible prefix -- well, we don't _have_ to, but I think it
483 ;; should be treated as part of the string.
486 ;; ur"""ar""" x='"' # """
489 ;; x '"""' x """ \"""" x
491 (goto-char (match-beginning 0))
492 (let ((syntax (save-match-data (syntax-ppss))))
494 ((eq t
(nth 3 syntax
)) ; after unclosed fence
495 ;; Consider property for the last char if in a fenced string.
496 (goto-char (nth 8 syntax
)) ; fence position
497 (skip-chars-forward "uUrR") ; skip any prefix
498 ;; Is it a matching sequence?
499 (if (eq (char-after) (char-after (match-beginning 2)))
500 (put-text-property (match-beginning 3) (match-end 3)
501 'syntax-table
(string-to-syntax "|"))))
503 ;; Consider property for initial char, accounting for prefixes.
504 (put-text-property (match-beginning 1) (match-end 1)
505 'syntax-table
(string-to-syntax "|")))
507 ;; Consider property for initial char, accounting for prefixes.
508 (put-text-property (match-beginning 2) (match-end 2)
509 'syntax-table
(string-to-syntax "|"))))
512 (defvar python-mode-syntax-table
513 (let ((table (make-syntax-table)))
514 ;; Give punctuation syntax to ASCII that normally has symbol
515 ;; syntax or has word syntax and isn't a letter.
516 (let ((symbol (string-to-syntax "_"))
517 (sst (standard-syntax-table)))
520 (if (equal symbol
(aref sst i
))
521 (modify-syntax-entry i
"." table
)))))
522 (modify-syntax-entry ?$
"." table
)
523 (modify-syntax-entry ?%
"." table
)
525 (modify-syntax-entry ?
# "<" table
)
526 (modify-syntax-entry ?
\n ">" table
)
527 (modify-syntax-entry ?
' "\"" table
)
528 (modify-syntax-entry ?
` "$" table
)
530 "Syntax table for Python files.")
532 (defvar python-dotty-syntax-table
533 (let ((table (make-syntax-table python-mode-syntax-table
)))
534 (modify-syntax-entry ?.
"w" table
)
535 (modify-syntax-entry ?_
"w" table
)
537 "Dotty syntax table for Python files.
538 It makes underscores and dots word constituent chars.")
543 (defcustom python-indent-offset
4
544 "Default indentation offset for Python."
549 (defcustom python-indent-guess-indent-offset t
550 "Non-nil tells Python mode to guess `python-indent-offset' value."
555 (define-obsolete-variable-alias
556 'python-indent
'python-indent-offset
"24.2")
558 (define-obsolete-variable-alias
559 'python-guess-indent
'python-indent-guess-indent-offset
"24.2")
561 (defvar python-indent-current-level
0
562 "Current indentation level `python-indent-line-function' is using.")
564 (defvar python-indent-levels
'(0)
565 "Levels of indentation available for `python-indent-line-function'.")
567 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
568 "List of words that should be dedented.
569 These make `python-indent-calculate-indentation' subtract the value of
570 `python-indent-offset'.")
572 (defun python-indent-guess-indent-offset ()
573 "Guess and set `python-indent-offset' for the current buffer."
578 (goto-char (point-min))
580 (while (and (not block-end
)
582 (python-rx line-start block-start
) nil t
))
584 (not (python-info-ppss-context-type))
586 (goto-char (line-end-position))
587 (python-util-forward-comment -
1)
588 (if (equal (char-before) ?
:)
591 (when (python-info-block-continuation-line-p)
592 (while (and (python-info-continuation-line-p)
595 (python-util-forward-comment -
1)
596 (when (equal (char-before) ?
:)
598 (setq block-end
(point-marker))))
601 (goto-char block-end
)
602 (python-util-forward-comment)
603 (current-indentation))))
605 (setq python-indent-offset indentation
)
606 (message "Can't guess python-indent-offset, using defaults: %s"
607 python-indent-offset
)))))))
609 (defun python-indent-context ()
610 "Get information on indentation context.
611 Context information is returned with a cons with the form:
614 Where status can be any of the following symbols:
615 * inside-paren: If point in between (), {} or []
616 * inside-string: If point is inside a string
617 * after-backslash: Previous line ends in a backslash
618 * after-beginning-of-block: Point is after beginning of block
619 * after-line: Point is after normal line
620 * no-indent: Point is at beginning of buffer or other special case
621 START is the buffer position where the sexp starts."
624 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
628 ;; Beginning of buffer
630 (goto-char (line-beginning-position))
634 ((setq start
(python-info-ppss-context 'paren ppss
))
637 ((setq start
(python-info-ppss-context 'string ppss
))
640 ((setq start
(when (not (or (python-info-ppss-context 'string ppss
)
641 (python-info-ppss-context 'comment ppss
)))
642 (let ((line-beg-pos (line-beginning-position)))
643 (when (python-info-line-ends-backslash-p
645 (- line-beg-pos
2)))))
647 ;; After beginning of block
648 ((setq start
(save-excursion
650 (back-to-indentation)
651 (python-util-forward-comment -
1)
652 (equal (char-before) ?
:))
653 ;; Move to the first block start that's not in within
654 ;; a string, comment or paren and that's not a
655 ;; continuation line.
656 (while (and (re-search-backward
657 (python-rx block-start
) nil t
)
659 (python-info-ppss-context 'string
)
660 (python-info-ppss-context 'comment
)
661 (python-info-ppss-context 'paren
)
662 (python-info-continuation-line-p))))
663 (when (looking-at (python-rx block-start
))
665 'after-beginning-of-block
)
667 ((setq start
(save-excursion
668 (back-to-indentation)
669 (python-util-forward-comment -
1)
670 (python-nav-beginning-of-statement)
677 (defun python-indent-calculate-indentation ()
678 "Calculate correct indentation offset for the current line."
679 (let* ((indentation-context (python-indent-context))
680 (context-status (car indentation-context
))
681 (context-start (cdr indentation-context
)))
687 ;; When point is after beginning of block just add one level
688 ;; of indentation relative to the context-start
689 ('after-beginning-of-block
690 (goto-char context-start
)
691 (+ (current-indentation) python-indent-offset
))
692 ;; When after a simple line just use previous line
693 ;; indentation, in the case current line starts with a
694 ;; `python-indent-dedenters' de-indent one level.
698 (goto-char context-start
)
699 (current-indentation))
701 (back-to-indentation)
702 (looking-at (regexp-opt python-indent-dedenters
)))
705 ;; When inside of a string, do nothing. just use the current
706 ;; indentation. XXX: perhaps it would be a good idea to
707 ;; invoke standard text indentation here
709 (goto-char context-start
)
710 (current-indentation))
711 ;; After backslash we have several possibilities.
714 ;; Check if current line is a dot continuation. For this
715 ;; the current line must start with a dot and previous
716 ;; line must contain a dot too.
718 (back-to-indentation)
719 (when (looking-at "\\.")
720 ;; If after moving one line back point is inside a paren it
721 ;; needs to move back until it's not anymore
725 (python-info-ppss-context 'paren
))))
726 (goto-char (line-end-position))
727 (while (and (re-search-backward
728 "\\." (line-beginning-position) t
)
729 (or (python-info-ppss-context 'comment
)
730 (python-info-ppss-context 'string
)
731 (python-info-ppss-context 'paren
))))
732 (if (and (looking-at "\\.")
733 (not (or (python-info-ppss-context 'comment
)
734 (python-info-ppss-context 'string
)
735 (python-info-ppss-context 'paren
))))
736 ;; The indentation is the same column of the
737 ;; first matching dot that's not inside a
738 ;; comment, a string or a paren
740 ;; No dot found on previous line, just add another
741 ;; indentation level.
742 (+ (current-indentation) python-indent-offset
)))))
743 ;; Check if prev line is a block continuation
744 ((let ((block-continuation-start
745 (python-info-block-continuation-line-p)))
746 (when block-continuation-start
747 ;; If block-continuation-start is set jump to that
748 ;; marker and use first column after the block start
749 ;; as indentation value.
750 (goto-char block-continuation-start
)
752 (python-rx block-start
(* space
))
753 (line-end-position) t
)
755 ;; Check if current line is an assignment continuation
756 ((let ((assignment-continuation-start
757 (python-info-assignment-continuation-line-p)))
758 (when assignment-continuation-start
759 ;; If assignment-continuation is set jump to that
760 ;; marker and use first column after the assignment
761 ;; operator as indentation value.
762 (goto-char assignment-continuation-start
)
766 (goto-char (python-info-beginning-of-backslash))
771 (or (python-info-beginning-of-backslash) (point)))
772 (python-info-line-ends-backslash-p)))
773 ;; The two previous lines ended in a backslash so we must
774 ;; respect previous line indentation.
775 (current-indentation)
776 ;; What happens here is that we are dealing with the second
777 ;; line of a backslash continuation, in that case we just going
778 ;; to add one indentation level.
779 (+ (current-indentation) python-indent-offset
)))))
780 ;; When inside a paren there's a need to handle nesting
784 ;; If current line closes the outermost open paren use the
785 ;; current indentation of the context-start line.
787 (skip-syntax-forward "\s" (line-end-position))
788 (when (and (looking-at (regexp-opt '(")" "]" "}")))
791 (not (python-info-ppss-context 'paren
))))
792 (goto-char context-start
)
793 (current-indentation))))
794 ;; If open paren is contained on a line by itself add another
795 ;; indentation level, else look for the first word after the
796 ;; opening paren and use it's column position as indentation
798 ((let* ((content-starts-in-newline)
801 (if (setq content-starts-in-newline
803 (goto-char context-start
)
807 (line-beginning-position)
809 (python-util-forward-comment))
811 (+ (current-indentation) python-indent-offset
)
815 ;; If current line closes a nested open paren de-indent one
818 (back-to-indentation)
819 (looking-at (regexp-opt '(")" "]" "}"))))
820 (- indent python-indent-offset
))
821 ;; If the line of the opening paren that wraps the current
822 ;; line starts a block add another level of indentation to
823 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
825 (when (and content-starts-in-newline
827 (goto-char context-start
)
828 (back-to-indentation)
829 (looking-at (python-rx block-start
))))
830 (+ indent python-indent-offset
))))
833 (defun python-indent-calculate-levels ()
834 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
835 (let* ((indentation (python-indent-calculate-indentation))
836 (remainder (% indentation python-indent-offset
))
837 (steps (/ (- indentation remainder
) python-indent-offset
)))
838 (setq python-indent-levels
(list 0))
839 (dotimes (step steps
)
840 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
841 (when (not (eq 0 remainder
))
842 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
843 (setq python-indent-levels
(nreverse python-indent-levels
))
844 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
846 (defun python-indent-toggle-levels ()
847 "Toggle `python-indent-current-level' over `python-indent-levels'."
848 (setq python-indent-current-level
(1- python-indent-current-level
))
849 (when (< python-indent-current-level
0)
850 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
852 (defun python-indent-line (&optional force-toggle
)
853 "Internal implementation of `python-indent-line-function'.
854 Uses the offset calculated in
855 `python-indent-calculate-indentation' and available levels
856 indicated by the variable `python-indent-levels' to set the
859 When the variable `last-command' is equal to
860 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
861 levels indicated in the variable `python-indent-levels' by
862 setting the current level in the variable
863 `python-indent-current-level'.
865 When the variable `last-command' is not equal to
866 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
867 possible indentation levels and saves it in the variable
868 `python-indent-levels'. Afterwards it sets the variable
869 `python-indent-current-level' correctly so offset is equal
870 to (`nth' `python-indent-current-level' `python-indent-levels')"
871 (if (or (and (eq this-command
'indent-for-tab-command
)
872 (eq last-command this-command
))
874 (if (not (equal python-indent-levels
'(0)))
875 (python-indent-toggle-levels)
876 (python-indent-calculate-levels))
877 (python-indent-calculate-levels))
879 (delete-horizontal-space)
880 (indent-to (nth python-indent-current-level python-indent-levels
))
881 (python-info-closing-block-message))
883 (defun python-indent-line-function ()
884 "`indent-line-function' for Python mode.
885 See `python-indent-line' for details."
886 (python-indent-line))
888 (defun python-indent-dedent-line ()
889 "De-indent current line."
891 (when (and (not (or (python-info-ppss-context 'string
)
892 (python-info-ppss-context 'comment
)))
893 (<= (point-marker) (save-excursion
894 (back-to-indentation)
896 (> (current-column) 0))
897 (python-indent-line t
)
900 (defun python-indent-dedent-line-backspace (arg)
901 "De-indent current line.
902 Argument ARG is passed to `backward-delete-char-untabify' when
903 point is not in between the indentation."
905 (when (not (python-indent-dedent-line))
906 (backward-delete-char-untabify arg
)))
907 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
909 (defun python-indent-region (start end
)
910 "Indent a python region automagically.
912 Called from a program, START and END specify the region to indent."
913 (let ((deactivate-mark nil
))
916 (setq end
(point-marker))
918 (or (bolp) (forward-line 1))
919 (while (< (point) end
)
920 (or (and (bolp) (eolp))
923 (back-to-indentation)
924 (setq word
(current-word))
928 (delete-horizontal-space)
929 (indent-to (python-indent-calculate-indentation)))))
931 (move-marker end nil
))))
933 (defun python-indent-shift-left (start end
&optional count
)
934 "Shift lines contained in region START END by COUNT columns to the left.
935 COUNT defaults to `python-indent-offset'. If region isn't
936 active, the current line is shifted. The shifted region includes
937 the lines in which START and END lie. An error is signaled if
938 any lines in the region are indented less than COUNT columns."
941 (list (region-beginning) (region-end) current-prefix-arg
)
942 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
944 (setq count
(prefix-numeric-value count
))
945 (setq count python-indent-offset
))
947 (let ((deactivate-mark nil
))
950 (while (< (point) end
)
951 (if (and (< (current-indentation) count
)
952 (not (looking-at "[ \t]*$")))
953 (error "Can't shift all lines enough"))
955 (indent-rigidly start end
(- count
))))))
957 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
959 (defun python-indent-shift-right (start end
&optional count
)
960 "Shift lines contained in region START END by COUNT columns to the left.
961 COUNT defaults to `python-indent-offset'. If region isn't
962 active, the current line is shifted. The shifted region includes
963 the lines in which START and END lie."
966 (list (region-beginning) (region-end) current-prefix-arg
)
967 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
968 (let ((deactivate-mark nil
))
970 (setq count
(prefix-numeric-value count
))
971 (setq count python-indent-offset
))
972 (indent-rigidly start end count
)))
974 (defun python-indent-electric-colon (arg)
975 "Insert a colon and maybe de-indent the current line.
976 With numeric ARG, just insert that many colons. With
977 \\[universal-argument], just insert a single colon."
979 (self-insert-command (if (not (integerp arg
)) 1 arg
))
982 (not (equal ?
: (char-after (- (point-marker) 2))))
983 (not (or (python-info-ppss-context 'string
)
984 (python-info-ppss-context 'comment
))))
985 (let ((indentation (current-indentation))
986 (calculated-indentation (python-indent-calculate-indentation)))
987 (python-info-closing-block-message)
988 (when (> indentation calculated-indentation
)
990 (indent-line-to calculated-indentation
)
991 (when (not (python-info-closing-block-message))
992 (indent-line-to indentation
)))))))
993 (put 'python-indent-electric-colon
'delete-selection t
)
995 (defun python-indent-post-self-insert-function ()
996 "Adjust closing paren line indentation after a char is added.
997 This function is intended to be added to the
998 `post-self-insert-hook.' If a line renders a paren alone, after
999 adding a char before it, the line will be re-indented
1000 automatically if needed."
1001 (when (and (eq (char-before) last-command-event
)
1003 (memq (char-after) '(?\
) ?\
] ?\
})))
1005 (goto-char (line-beginning-position))
1006 ;; If after going to the beginning of line the point
1007 ;; is still inside a paren it's ok to do the trick
1008 (when (python-info-ppss-context 'paren
)
1009 (let ((indentation (python-indent-calculate-indentation)))
1010 (when (< (current-indentation) indentation
)
1011 (indent-line-to indentation
)))))))
1016 (defvar python-nav-beginning-of-defun-regexp
1017 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1018 "Regexp matching class or function definition.
1019 The name of the defun should be grouped so it can be retrieved
1020 via `match-string'.")
1022 (defun python-nav-beginning-of-defun (&optional arg
)
1023 "Move point to `beginning-of-defun'.
1024 With positive ARG move search backwards. With negative do the
1025 same but forward. When ARG is nil or 0 defaults to 1. This is
1026 the main part of `python-beginning-of-defun-function'. Return
1027 non-nil if point is moved to `beginning-of-defun'."
1028 (when (or (null arg
) (= arg
0)) (setq arg
1))
1029 (let* ((re-search-fn (if (> arg
0)
1030 #'re-search-backward
1031 #'re-search-forward
))
1032 (line-beg-pos (line-beginning-position))
1033 (line-content-start (+ line-beg-pos
(current-indentation)))
1034 (pos (point-marker))
1037 (when (and (< arg
0)
1038 (python-info-looking-at-beginning-of-defun))
1040 (while (and (funcall re-search-fn
1041 python-nav-beginning-of-defun-regexp nil t
)
1042 (python-info-ppss-context-type)))
1043 (and (python-info-looking-at-beginning-of-defun)
1044 (or (not (= (line-number-at-pos pos
)
1045 (line-number-at-pos)))
1046 (and (>= (point) line-beg-pos
)
1047 (<= (point) line-content-start
)
1048 (> pos line-content-start
)))))))
1050 (or (beginning-of-line 1) t
)
1051 (and (goto-char pos
) nil
))))
1053 (defun python-beginning-of-defun-function (&optional arg
)
1054 "Move point to the beginning of def or class.
1055 With positive ARG move that number of functions backwards. With
1056 negative do the same but forward. When ARG is nil or 0 defaults
1057 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1058 (when (or (null arg
) (= arg
0)) (setq arg
1))
1060 (cond ((and (eq this-command
'mark-defun
)
1061 (python-info-looking-at-beginning-of-defun)))
1063 (dotimes (i (if (> arg
0) arg
(- arg
)))
1064 (when (and (python-nav-beginning-of-defun arg)
1069 (defun python-end-of-defun-function ()
1070 "Move point to the end of def or class.
1071 Returns nil if point is not in a def or class."
1073 (let ((beg-defun-indent))
1074 (when (or (python-info-looking-at-beginning-of-defun)
1075 (python-beginning-of-defun-function 1)
1076 (python-beginning-of-defun-function -
1))
1077 (setq beg-defun-indent
(current-indentation))
1079 ;; Go as forward as possible
1081 (python-nav-beginning-of-defun -1)
1082 (and (goto-char (point-max)) nil
))
1083 (> (current-indentation) beg-defun-indent
)))
1084 (beginning-of-line 1)
1085 ;; Go as backwards as possible
1086 (while (and (forward-line -
1)
1088 (or (not (current-word))
1089 (equal (char-after (+ (point) (current-indentation))) ?
#)
1090 (<= (current-indentation) beg-defun-indent
)
1091 (looking-at (python-rx decorator
))
1092 (python-info-ppss-context-type))))
1094 ;; If point falls inside a paren or string context the point is
1095 ;; forwarded at the end of it (or end of buffer if its not closed)
1096 (let ((context-type (python-info-ppss-context-type)))
1097 (when (memq context-type
'(paren string
))
1099 (while (and (not (eobp))
1100 (python-info-ppss-context-type))
1101 (forward-line 1)))))))
1103 (defun python-nav-beginning-of-statement ()
1104 "Move to start of current statement."
1106 (while (and (or (back-to-indentation) t
)
1111 (python-info-line-ends-backslash-p))
1112 (python-info-ppss-context 'string
)
1113 (python-info-ppss-context 'paren
))
1114 (forward-line -
1)))))
1116 (defun python-nav-end-of-statement ()
1117 "Move to end of current statement."
1119 (while (and (goto-char (line-end-position))
1122 (python-info-line-ends-backslash-p)
1123 (python-info-ppss-context 'string
)
1124 (python-info-ppss-context 'paren
))
1125 (forward-line 1)))))
1127 (defun python-nav-backward-statement (&optional arg
)
1128 "Move backward to previous statement.
1129 With ARG, repeat. See `python-nav-forward-statement'."
1131 (or arg
(setq arg
1))
1132 (python-nav-forward-statement (- arg
)))
1134 (defun python-nav-forward-statement (&optional arg
)
1135 "Move forward to next statement.
1136 With ARG, repeat. With negative argument, move ARG times
1137 backward to previous statement."
1139 (or arg
(setq arg
1))
1141 (python-nav-end-of-statement)
1142 (python-util-forward-comment)
1143 (python-nav-beginning-of-statement)
1144 (setq arg
(1- arg
)))
1146 (python-nav-beginning-of-statement)
1147 (python-util-forward-comment -
1)
1148 (python-nav-beginning-of-statement)
1149 (setq arg
(1+ arg
))))
1151 (defun python-nav-beginning-of-block ()
1152 "Move to start of current block."
1154 (let ((starting-pos (point))
1155 (block-regexp (python-rx
1156 line-start
(* whitespace
) block-start
)))
1158 (python-nav-beginning-of-statement)
1159 (looking-at (python-rx block-start
)))
1161 ;; Go to first line beginning a statement
1162 (while (and (not (bobp))
1163 (or (and (python-nav-beginning-of-statement) nil
)
1164 (python-info-current-line-comment-p)
1165 (python-info-current-line-empty-p)))
1167 (let ((block-matching-indent
1168 (- (current-indentation) python-indent-offset
)))
1170 (and (python-nav-backward-block)
1171 (> (current-indentation) block-matching-indent
)))
1172 (if (and (looking-at (python-rx block-start
))
1173 (= (current-indentation) block-matching-indent
))
1175 (and (goto-char starting-pos
) nil
))))))
1177 (defun python-nav-end-of-block ()
1178 "Move to end of current block."
1180 (when (python-nav-beginning-of-block)
1181 (let ((block-indentation (current-indentation)))
1182 (python-nav-end-of-statement)
1183 (while (and (forward-line 1)
1185 (or (and (> (current-indentation) block-indentation
)
1186 (or (python-nav-end-of-statement) t
))
1187 (python-info-current-line-comment-p)
1188 (python-info-current-line-empty-p))))
1189 (python-util-forward-comment -
1)
1192 (defun python-nav-backward-block (&optional arg
)
1193 "Move backward to previous block of code.
1194 With ARG, repeat. See `python-nav-forward-block'."
1196 (or arg
(setq arg
1))
1197 (python-nav-forward-block (- arg
)))
1199 (defun python-nav-forward-block (&optional arg
)
1200 "Move forward to next block of code.
1201 With ARG, repeat. With negative argument, move ARG times
1202 backward to previous block."
1204 (or arg
(setq arg
1))
1205 (let ((block-start-regexp
1206 (python-rx line-start
(* whitespace
) block-start
))
1207 (starting-pos (point)))
1209 (python-nav-end-of-statement)
1211 (re-search-forward block-start-regexp nil t
)
1212 (or (python-info-ppss-context 'string
)
1213 (python-info-ppss-context 'comment
)
1214 (python-info-ppss-context 'paren
))))
1215 (setq arg
(1- arg
)))
1217 (python-nav-beginning-of-statement)
1219 (re-search-backward block-start-regexp nil t
)
1220 (or (python-info-ppss-context 'string
)
1221 (python-info-ppss-context 'comment
)
1222 (python-info-ppss-context 'paren
))))
1223 (setq arg
(1+ arg
)))
1224 (python-nav-beginning-of-statement)
1225 (if (not (looking-at (python-rx block-start
)))
1226 (and (goto-char starting-pos
) nil
)
1227 (and (not (= (point) starting-pos
)) (point-marker)))))
1229 (defun python-nav-forward-sexp-function (&optional arg
)
1230 "Move forward across one block of code.
1231 With ARG, do it that many times. Negative arg -N means
1232 move backward N times."
1234 (or arg
(setq arg
1))
1236 (let ((block-starting-pos
1237 (save-excursion (python-nav-beginning-of-block)))
1239 (save-excursion (python-nav-end-of-block)))
1240 (next-block-starting-pos
1241 (save-excursion (python-nav-forward-block))))
1242 (cond ((not block-starting-pos
)
1243 (python-nav-forward-block))
1244 ((= (point) block-starting-pos
)
1245 (if (or (not next-block-starting-pos
)
1246 (< block-ending-pos next-block-starting-pos
))
1247 (python-nav-end-of-block)
1248 (python-nav-forward-block)))
1249 ((= block-ending-pos
(point))
1250 (let ((parent-block-end-pos
1252 (python-util-forward-comment)
1253 (python-nav-beginning-of-block)
1254 (python-nav-end-of-block))))
1255 (if (and parent-block-end-pos
1256 (or (not next-block-starting-pos
)
1257 (> next-block-starting-pos parent-block-end-pos
)))
1258 (goto-char parent-block-end-pos
)
1259 (python-nav-forward-block))))
1260 (t (python-nav-end-of-block))))
1261 (setq arg
(1- arg
)))
1263 (let* ((block-starting-pos
1264 (save-excursion (python-nav-beginning-of-block)))
1266 (save-excursion (python-nav-end-of-block)))
1267 (prev-block-ending-pos
1268 (save-excursion (when (python-nav-backward-block)
1269 (python-nav-end-of-block))))
1270 (prev-block-parent-ending-pos
1272 (when prev-block-ending-pos
1273 (goto-char prev-block-ending-pos
)
1274 (python-util-forward-comment)
1275 (python-nav-beginning-of-block)
1276 (python-nav-end-of-block)))))
1277 (cond ((not block-ending-pos
)
1278 (and (python-nav-backward-block)
1279 (python-nav-end-of-block)))
1280 ((= (point) block-ending-pos
)
1283 '(prev-block-parent-ending-pos
1284 prev-block-ending-pos
1286 block-starting-pos
))
1287 (when (and (symbol-value name
)
1288 (< (symbol-value name
) (point)))
1289 (add-to-list 'candidates
(symbol-value name
))))
1290 (goto-char (apply 'max candidates
))))
1291 ((> (point) block-ending-pos
)
1292 (python-nav-end-of-block))
1293 ((= (point) block-starting-pos
)
1294 (if (not (> (point) (or prev-block-ending-pos
(point))))
1295 (python-nav-backward-block)
1296 (goto-char prev-block-ending-pos
)
1297 (let ((parent-block-ending-pos
1299 (python-nav-forward-sexp-function)
1300 (and (not (looking-at (python-rx block-start
)))
1302 (when (and parent-block-ending-pos
1303 (> parent-block-ending-pos prev-block-ending-pos
))
1304 (goto-char parent-block-ending-pos
)))))
1305 (t (python-nav-beginning-of-block))))
1306 (setq arg
(1+ arg
))))
1309 ;;; Shell integration
1311 (defcustom python-shell-buffer-name
"Python"
1312 "Default buffer name for Python interpreter."
1317 (defcustom python-shell-interpreter
"python"
1318 "Default Python interpreter for shell."
1322 (defcustom python-shell-internal-buffer-name
"Python Internal"
1323 "Default buffer name for the Internal Python interpreter."
1328 (defcustom python-shell-interpreter-args
"-i"
1329 "Default arguments for the Python interpreter."
1333 (defcustom python-shell-prompt-regexp
">>> "
1334 "Regular Expression matching top\-level input prompt of python shell.
1335 It should not contain a caret (^) at the beginning."
1340 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1341 "Regular Expression matching block input prompt of python shell.
1342 It should not contain a caret (^) at the beginning."
1347 (defcustom python-shell-prompt-output-regexp
""
1348 "Regular Expression matching output prompt of python shell.
1349 It should not contain a caret (^) at the beginning."
1354 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1355 "Regular Expression matching pdb input prompt of python shell.
1356 It should not contain a caret (^) at the beginning."
1361 (defcustom python-shell-enable-font-lock t
1362 "Should syntax highlighting be enabled in the python shell buffer?
1363 Restart the python shell after changing this variable for it to take effect."
1368 (defcustom python-shell-send-setup-max-wait
5
1369 "Seconds to wait for process output before code setup.
1370 If output is received before the specified time then control is
1371 returned in that moment and not after waiting."
1376 (defcustom python-shell-process-environment nil
1377 "List of environment variables for Python shell.
1378 This variable follows the same rules as `process-environment'
1379 since it merges with it before the process creation routines are
1380 called. When this variable is nil, the Python shell is run with
1381 the default `process-environment'."
1382 :type
'(repeat string
)
1386 (defcustom python-shell-extra-pythonpaths nil
1387 "List of extra pythonpaths for Python shell.
1388 The values of this variable are added to the existing value of
1389 PYTHONPATH in the `process-environment' variable."
1390 :type
'(repeat string
)
1394 (defcustom python-shell-exec-path nil
1395 "List of path to search for binaries.
1396 This variable follows the same rules as `exec-path' since it
1397 merges with it before the process creation routines are called.
1398 When this variable is nil, the Python shell is run with the
1399 default `exec-path'."
1400 :type
'(repeat string
)
1404 (defcustom python-shell-virtualenv-path nil
1405 "Path to virtualenv root.
1406 This variable, when set to a string, makes the values stored in
1407 `python-shell-process-environment' and `python-shell-exec-path'
1408 to be modified properly so shells are started with the specified
1414 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1415 python-ffap-setup-code
1416 python-eldoc-setup-code
)
1417 "List of code run by `python-shell-send-setup-codes'."
1418 :type
'(repeat symbol
)
1422 (defcustom python-shell-compilation-regexp-alist
1423 `((,(rx line-start
(1+ (any " \t")) "File \""
1424 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1425 "\", line " (group (1+ digit
)))
1427 (,(rx " in file " (group (1+ not-newline
)) " on line "
1430 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1431 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1433 "`compilation-error-regexp-alist' for inferior Python."
1434 :type
'(alist string
)
1437 (defun python-shell-get-process-name (dedicated)
1438 "Calculate the appropriate process name for inferior Python process.
1439 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1440 returns a string with the form
1441 `python-shell-buffer-name'[variable `buffer-file-name'] else
1442 returns the value of `python-shell-buffer-name'. After
1443 calculating the process name adds the buffer name for the process
1444 in the `same-window-buffer-names' list."
1448 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1449 (format "%s" python-shell-buffer-name
))))
1450 (add-to-list 'same-window-buffer-names
(purecopy
1451 (format "*%s*" process-name
)))
1454 (defun python-shell-internal-get-process-name ()
1455 "Calculate the appropriate process name for Internal Python process.
1456 The name is calculated from `python-shell-global-buffer-name' and
1457 a hash of all relevant global shell settings in order to ensure
1458 uniqueness for different types of configurations."
1460 python-shell-internal-buffer-name
1463 (python-shell-parse-command)
1464 python-shell-prompt-regexp
1465 python-shell-prompt-block-regexp
1466 python-shell-prompt-output-regexp
1467 (mapconcat #'symbol-value python-shell-setup-codes
"")
1468 (mapconcat #'identity python-shell-process-environment
"")
1469 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1470 (mapconcat #'identity python-shell-exec-path
"")
1471 (or python-shell-virtualenv-path
"")
1472 (mapconcat #'identity python-shell-exec-path
"")))))
1474 (defun python-shell-parse-command ()
1475 "Calculate the string used to execute the inferior Python process."
1476 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1478 (defun python-shell-calculate-process-environment ()
1479 "Calculate process environment given `python-shell-virtualenv-path'."
1480 (let ((process-environment (append
1481 python-shell-process-environment
1482 process-environment nil
))
1483 (virtualenv (if python-shell-virtualenv-path
1484 (directory-file-name python-shell-virtualenv-path
)
1486 (when python-shell-extra-pythonpaths
1487 (setenv "PYTHONPATH"
1489 (mapconcat 'identity
1490 python-shell-extra-pythonpaths
1493 (or (getenv "PYTHONPATH") ""))))
1494 (if (not virtualenv
)
1496 (setenv "PYTHONHOME" nil
)
1497 (setenv "PATH" (format "%s/bin%s%s"
1498 virtualenv path-separator
1499 (or (getenv "PATH") "")))
1500 (setenv "VIRTUAL_ENV" virtualenv
))
1501 process-environment
))
1503 (defun python-shell-calculate-exec-path ()
1504 "Calculate exec path given `python-shell-virtualenv-path'."
1505 (let ((path (append python-shell-exec-path
1507 (if (not python-shell-virtualenv-path
)
1509 (cons (format "%s/bin"
1510 (directory-file-name python-shell-virtualenv-path
))
1513 (defun python-comint-output-filter-function (output)
1514 "Hook run after content is put into comint buffer.
1515 OUTPUT is a string with the contents of the buffer."
1516 (ansi-color-filter-apply output
))
1518 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1519 "Major mode for Python inferior process.
1520 Runs a Python interpreter as a subprocess of Emacs, with Python
1521 I/O through an Emacs buffer. Variables
1522 `python-shell-interpreter' and `python-shell-interpreter-args'
1523 controls which Python interpreter is run. Variables
1524 `python-shell-prompt-regexp',
1525 `python-shell-prompt-output-regexp',
1526 `python-shell-prompt-block-regexp',
1527 `python-shell-enable-font-lock',
1528 `python-shell-completion-setup-code',
1529 `python-shell-completion-string-code',
1530 `python-shell-completion-module-string-code',
1531 `python-eldoc-setup-code', `python-eldoc-string-code',
1532 `python-ffap-setup-code' and `python-ffap-string-code' can
1533 customize this mode for different Python interpreters.
1535 You can also add additional setup code to be run at
1536 initialization of the interpreter via `python-shell-setup-codes'
1539 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1540 (set-syntax-table python-mode-syntax-table
)
1541 (setq mode-line-process
'(":%s"))
1542 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1543 python-shell-prompt-regexp
1544 python-shell-prompt-block-regexp
1545 python-shell-prompt-pdb-regexp
))
1546 (make-local-variable 'comint-output-filter-functions
)
1547 (add-hook 'comint-output-filter-functions
1548 'python-comint-output-filter-function
)
1549 (add-hook 'comint-output-filter-functions
1550 'python-pdbtrack-comint-output-filter-function
)
1551 (set (make-local-variable 'compilation-error-regexp-alist
)
1552 python-shell-compilation-regexp-alist
)
1553 (define-key inferior-python-mode-map
[remap complete-symbol
]
1554 'completion-at-point
)
1555 (add-hook 'completion-at-point-functions
1556 'python-shell-completion-complete-at-point nil
'local
)
1557 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1558 'python-shell-completion-complete-at-point
)
1559 (define-key inferior-python-mode-map
(kbd "<tab>")
1560 'python-shell-completion-complete-or-indent
)
1561 (when python-shell-enable-font-lock
1562 (set (make-local-variable 'font-lock-defaults
)
1563 '(python-font-lock-keywords nil nil nil nil
))
1564 (set (make-local-variable 'syntax-propertize-function
)
1565 python-syntax-propertize-function
))
1566 (compilation-shell-minor-mode 1))
1568 (defun python-shell-make-comint (cmd proc-name
&optional pop
)
1569 "Create a python shell comint buffer.
1570 CMD is the python command to be executed and PROC-NAME is the
1571 process name the comint buffer will get. After the comint buffer
1572 is created the `inferior-python-mode' is activated. If POP is
1573 non-nil the buffer is shown."
1575 (let* ((proc-buffer-name (format "*%s*" proc-name
))
1576 (process-environment (python-shell-calculate-process-environment))
1577 (exec-path (python-shell-calculate-exec-path)))
1578 (when (not (comint-check-proc proc-buffer-name
))
1579 (let* ((cmdlist (split-string-and-unquote cmd
))
1580 (buffer (apply 'make-comint proc-name
(car cmdlist
) nil
1582 (current-buffer (current-buffer)))
1583 (with-current-buffer buffer
1584 (inferior-python-mode)
1585 (python-util-clone-local-variables current-buffer
))))
1587 (pop-to-buffer proc-buffer-name
))
1590 (defun run-python (dedicated cmd
)
1591 "Run an inferior Python process.
1592 Input and output via buffer named after
1593 `python-shell-buffer-name'. If there is a process already
1594 running in that buffer, just switch to it.
1595 With argument, allows you to define DEDICATED, so a dedicated
1596 process for the current buffer is open, and define CMD so you can
1597 edit the command used to call the interpreter (default is value
1598 of `python-shell-interpreter' and arguments defined in
1599 `python-shell-interpreter-args'). Runs the hook
1600 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1602 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1604 (if current-prefix-arg
1606 (y-or-n-p "Make dedicated process? ")
1607 (read-string "Run Python: " (python-shell-parse-command)))
1608 (list nil
(python-shell-parse-command))))
1609 (python-shell-make-comint cmd
(python-shell-get-process-name dedicated
))
1612 (defun run-python-internal ()
1613 "Run an inferior Internal Python process.
1614 Input and output via buffer named after
1615 `python-shell-internal-buffer-name' and what
1616 `python-shell-internal-get-process-name' returns. This new kind
1617 of shell is intended to be used for generic communication related
1618 to defined configurations. The main difference with global or
1619 dedicated shells is that these ones are attached to a
1620 configuration, not a buffer. This means that can be used for
1621 example to retrieve the sys.path and other stuff, without messing
1622 with user shells. Runs the hook
1623 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1624 run). \(Type \\[describe-mode] in the process buffer for a list
1627 (set-process-query-on-exit-flag
1629 (python-shell-make-comint
1630 (python-shell-parse-command)
1631 (python-shell-internal-get-process-name))) nil
))
1633 (defun python-shell-get-process ()
1634 "Get inferior Python process for current buffer and return it."
1635 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1636 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1637 (global-proc-name (python-shell-get-process-name nil
))
1638 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1639 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1640 (global-running (comint-check-proc global-proc-buffer-name
)))
1641 ;; Always prefer dedicated
1642 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1643 (and global-running global-proc-buffer-name
)))))
1645 (defun python-shell-get-or-create-process ()
1646 "Get or create an inferior Python process for current buffer and return it."
1647 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1648 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1649 (global-proc-name (python-shell-get-process-name nil
))
1650 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1651 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1652 (global-running (comint-check-proc global-proc-buffer-name
))
1653 (current-prefix-arg 4))
1654 (when (and (not dedicated-running
) (not global-running
))
1655 (if (call-interactively 'run-python
)
1656 (setq dedicated-running t
)
1657 (setq global-running t
)))
1658 ;; Always prefer dedicated
1659 (get-buffer-process (if dedicated-running
1660 dedicated-proc-buffer-name
1661 global-proc-buffer-name
))))
1663 (defvar python-shell-internal-buffer nil
1664 "Current internal shell buffer for the current buffer.
1665 This is really not necessary at all for the code to work but it's
1666 there for compatibility with CEDET.")
1667 (make-variable-buffer-local 'python-shell-internal-buffer
)
1669 (defun python-shell-internal-get-or-create-process ()
1670 "Get or create an inferior Internal Python process."
1671 (let* ((proc-name (python-shell-internal-get-process-name))
1672 (proc-buffer-name (format "*%s*" proc-name
)))
1673 (run-python-internal)
1674 (setq python-shell-internal-buffer proc-buffer-name
)
1675 (get-buffer-process proc-buffer-name
)))
1677 (define-obsolete-function-alias
1678 'python-proc
'python-shell-internal-get-or-create-process
"24.2")
1680 (define-obsolete-variable-alias
1681 'python-buffer
'python-shell-internal-buffer
"24.2")
1683 (defun python-shell-send-string (string &optional process msg
)
1684 "Send STRING to inferior Python PROCESS.
1685 When MSG is non-nil messages the first line of STRING."
1686 (interactive "sPython command: ")
1687 (let ((process (or process
(python-shell-get-or-create-process)))
1688 (lines (split-string string
"\n" t
)))
1690 (message (format "Sent: %s..." (nth 0 lines
))))
1691 (if (> (length lines
) 1)
1692 (let* ((temp-file-name (make-temp-file "py"))
1693 (file-name (or (buffer-file-name) temp-file-name
)))
1694 (with-temp-file temp-file-name
1696 (delete-trailing-whitespace))
1697 (python-shell-send-file file-name process temp-file-name
))
1698 (comint-send-string process string
)
1699 (when (or (not (string-match "\n$" string
))
1700 (string-match "\n[ \t].*\n?$" string
))
1701 (comint-send-string process
"\n")))))
1703 (defun python-shell-send-string-no-output (string &optional process msg
)
1704 "Send STRING to PROCESS and inhibit output.
1705 When MSG is non-nil messages the first line of STRING. Return
1707 (let* ((output-buffer "")
1708 (process (or process
(python-shell-get-or-create-process)))
1709 (comint-preoutput-filter-functions
1710 (append comint-preoutput-filter-functions
1711 '(ansi-color-filter-apply
1713 (setq output-buffer
(concat output-buffer string
))
1718 (python-shell-send-string string process msg
)
1719 (accept-process-output process
)
1720 (replace-regexp-in-string
1721 (if (> (length python-shell-prompt-output-regexp
) 0)
1722 (format "\n*%s$\\|^%s\\|\n$"
1723 python-shell-prompt-regexp
1724 (or python-shell-prompt-output-regexp
""))
1725 (format "\n*$\\|^%s\\|\n$"
1726 python-shell-prompt-regexp
))
1728 (with-current-buffer (process-buffer process
)
1729 (comint-interrupt-subjob)))))
1731 (defun python-shell-internal-send-string (string)
1732 "Send STRING to the Internal Python interpreter.
1733 Returns the output. See `python-shell-send-string-no-output'."
1734 (python-shell-send-string-no-output
1735 ;; Makes this function compatible with the old
1736 ;; python-send-receive. (At least for CEDET).
1737 (replace-regexp-in-string "_emacs_out +" "" string
)
1738 (python-shell-internal-get-or-create-process) nil
))
1740 (define-obsolete-function-alias
1741 'python-send-receive
'python-shell-internal-send-string
"24.2")
1743 (define-obsolete-function-alias
1744 'python-send-string
'python-shell-internal-send-string
"24.2")
1746 (defun python-shell-send-region (start end
)
1747 "Send the region delimited by START and END to inferior Python process."
1749 (python-shell-send-string (buffer-substring start end
) nil t
))
1751 (defun python-shell-send-buffer (&optional arg
)
1752 "Send the entire buffer to inferior Python process.
1754 With prefix ARG include lines surrounded by \"if __name__ == '__main__':\""
1758 (python-shell-send-region
1763 (re-search-forward (python-rx if-name-main
) nil t
))
1764 (match-beginning 0))
1767 (defun python-shell-send-defun (arg)
1768 "Send the current defun to inferior Python process.
1769 When argument ARG is non-nil do not include decorators."
1772 (python-shell-send-region
1775 (while (and (or (python-beginning-of-defun-function)
1776 (beginning-of-line 1))
1777 (> (current-indentation) 0)))
1779 (while (and (forward-line -
1)
1780 (looking-at (python-rx decorator
))))
1784 (or (python-end-of-defun-function)
1788 (defun python-shell-send-file (file-name &optional process temp-file-name
)
1789 "Send FILE-NAME to inferior Python PROCESS.
1790 If TEMP-FILE-NAME is passed then that file is used for processing
1791 instead, while internally the shell will continue to use
1793 (interactive "fFile to send: ")
1794 (let* ((process (or process
(python-shell-get-or-create-process)))
1795 (temp-file-name (when temp-file-name
1796 (expand-file-name temp-file-name
)))
1797 (file-name (or (expand-file-name file-name
) temp-file-name
)))
1798 (when (not file-name
)
1799 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1800 (python-shell-send-string
1802 (concat "__pyfile = open('''%s''');"
1803 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1805 (or temp-file-name file-name
) file-name
)
1808 (defun python-shell-switch-to-shell ()
1809 "Switch to inferior Python process buffer."
1811 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
1813 (defun python-shell-send-setup-code ()
1814 "Send all setup code for shell.
1815 This function takes the list of setup code to send from the
1816 `python-shell-setup-codes' list."
1817 (let ((msg "Sent %s")
1818 (process (get-buffer-process (current-buffer))))
1819 (accept-process-output process python-shell-send-setup-max-wait
)
1820 (dolist (code python-shell-setup-codes
)
1822 (message (format msg code
))
1823 (python-shell-send-string
1824 (symbol-value code
) process
)))))
1826 (add-hook 'inferior-python-mode-hook
1827 #'python-shell-send-setup-code
)
1830 ;;; Shell completion
1832 (defcustom python-shell-completion-setup-code
1836 def __COMPLETER_all_completions(text): []
1839 readline.set_completer(rlcompleter.Completer().complete)
1840 def __COMPLETER_all_completions(text):
1846 res = readline.get_completer()(text, i)
1849 completions.append(res)
1853 "Code used to setup completion in inferior Python processes."
1857 (defcustom python-shell-completion-string-code
1858 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1859 "Python code used to get a string of completions separated by semicolons."
1863 (defcustom python-shell-completion-module-string-code
""
1864 "Python code used to get completions separated by semicolons for imports.
1866 For IPython v0.11, add the following line to
1867 `python-shell-completion-setup-code':
1869 from IPython.core.completerlib import module_completion
1871 and use the following as the value of this variable:
1873 ';'.join(module_completion('''%s'''))\n"
1877 (defcustom python-shell-completion-pdb-string-code
1878 "';'.join(globals().keys() + locals().keys())"
1879 "Python code used to get completions separated by semicolons for [i]pdb."
1883 (defun python-shell-completion--get-completions (input process completion-code
)
1884 "Retrieve available completions for INPUT using PROCESS.
1885 Argument COMPLETION-CODE is the python code used to get
1886 completions on the current context."
1887 (with-current-buffer (process-buffer process
)
1888 (let ((completions (python-shell-send-string-no-output
1889 (format completion-code input
) process
)))
1890 (when (> (length completions
) 2)
1891 (split-string completions
"^'\\|^\"\\|;\\|'$\\|\"$" t
)))))
1893 (defun python-shell-completion--do-completion-at-point (process)
1894 "Do completion at point for PROCESS."
1895 (with-syntax-table python-dotty-syntax-table
1898 (let* ((paren-depth (car (syntax-ppss)))
1899 (syntax-string "w_")
1900 (syntax-list (string-to-syntax syntax-string
)))
1901 ;; Stop scanning for the beginning of the completion subject
1902 ;; after the char before point matches a delimiter
1903 (while (member (car (syntax-after (1- (point)))) syntax-list
)
1904 (skip-syntax-backward syntax-string
)
1905 (when (or (equal (char-before) ?\
))
1906 (equal (char-before) ?
\"))
1909 ;; honor initial paren depth
1910 (> (car (syntax-ppss)) paren-depth
)
1911 (python-info-ppss-context 'string
))
1912 (forward-char -
1))))
1915 (line (buffer-substring-no-properties (point-at-bol) end
))
1916 (input (buffer-substring-no-properties beg end
))
1917 ;; Get the last prompt for the inferior process buffer. This is
1918 ;; used for the completion code selection heuristic.
1920 (with-current-buffer (process-buffer process
)
1921 (buffer-substring-no-properties
1922 (overlay-start comint-last-prompt-overlay
)
1923 (overlay-end comint-last-prompt-overlay
))))
1925 ;; Check whether a prompt matches a pdb string, an import statement
1926 ;; or just the standard prompt and use the correct
1927 ;; python-shell-completion-*-code string
1928 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
1930 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
1933 (length python-shell-completion-module-string-code
) 0)
1935 (concat "^" python-shell-prompt-regexp
) prompt
)
1936 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
1939 (concat "^" python-shell-prompt-regexp
) prompt
)
1943 (case completion-context
1944 ('pdb python-shell-completion-pdb-string-code
)
1945 ('import python-shell-completion-module-string-code
)
1946 ('default python-shell-completion-string-code
)
1949 (if (eq completion-context
'import
)
1950 (replace-regexp-in-string "^[ \t]+" "" line
)
1953 (and completion-code
(> (length input
) 0)
1954 (python-shell-completion--get-completions
1955 input process completion-code
))))
1956 (list beg end completions
))))
1958 (defun python-shell-completion-complete-at-point ()
1959 "Perform completion at point in inferior Python process."
1961 (and comint-last-prompt-overlay
1962 (> (point-marker) (overlay-end comint-last-prompt-overlay
))
1963 (python-shell-completion--do-completion-at-point
1964 (get-buffer-process (current-buffer)))))
1966 (defun python-shell-completion-complete-or-indent ()
1967 "Complete or indent depending on the context.
1968 If content before pointer is all whitespace indent. If not try
1971 (if (string-match "^[[:space:]]*$"
1972 (buffer-substring (comint-line-beginning-position)
1974 (indent-for-tab-command)
1975 (completion-at-point)))
1978 ;;; PDB Track integration
1980 (defcustom python-pdbtrack-activate t
1981 "Non-nil makes python shell enable pdbtracking."
1986 (defcustom python-pdbtrack-stacktrace-info-regexp
1987 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1988 "Regular Expression matching stacktrace information.
1989 Used to extract the current line and module being inspected."
1994 (defvar python-pdbtrack-tracked-buffer nil
1995 "Variable containing the value of the current tracked buffer.
1996 Never set this variable directly, use
1997 `python-pdbtrack-set-tracked-buffer' instead.")
1998 (make-variable-buffer-local 'python-pdbtrack-tracked-buffer
)
2000 (defvar python-pdbtrack-buffers-to-kill nil
2001 "List of buffers to be deleted after tracking finishes.")
2002 (make-variable-buffer-local 'python-pdbtrack-buffers-to-kill
)
2004 (defun python-pdbtrack-set-tracked-buffer (file-name)
2005 "Set the buffer for FILE-NAME as the tracked buffer.
2006 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2007 Returns the tracked buffer."
2008 (let ((file-buffer (get-file-buffer file-name
)))
2010 (setq python-pdbtrack-tracked-buffer file-buffer
)
2011 (setq file-buffer
(find-file-noselect file-name
))
2012 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2013 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2016 (defun python-pdbtrack-comint-output-filter-function (output)
2017 "Move overlay arrow to current pdb line in tracked buffer.
2018 Argument OUTPUT is a string with the output from the comint process."
2019 (when (and python-pdbtrack-activate
(not (string= output
"")))
2020 (let* ((full-output (ansi-color-filter-apply
2021 (buffer-substring comint-last-input-end
(point-max))))
2025 (insert full-output
)
2026 (goto-char (point-min))
2027 ;; OK, this sucked but now it became a cool hack. The
2028 ;; stacktrace information normally is on the first line
2029 ;; but in some cases (like when doing a step-in) it is
2031 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2034 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2035 (setq line-number
(string-to-number
2036 (match-string-no-properties 2)))
2037 (match-string-no-properties 1)))))
2038 (if (and file-name line-number
)
2039 (let* ((tracked-buffer
2040 (python-pdbtrack-set-tracked-buffer file-name
))
2041 (shell-buffer (current-buffer))
2042 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2043 (tracked-buffer-line-pos))
2044 (with-current-buffer tracked-buffer
2045 (set (make-local-variable 'overlay-arrow-string
) "=>")
2046 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2047 (setq tracked-buffer-line-pos
(progn
2048 (goto-char (point-min))
2049 (forward-line (1- line-number
))
2051 (when tracked-buffer-window
2053 tracked-buffer-window tracked-buffer-line-pos
))
2054 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2055 (pop-to-buffer tracked-buffer
)
2056 (switch-to-buffer-other-window shell-buffer
))
2057 (when python-pdbtrack-tracked-buffer
2058 (with-current-buffer python-pdbtrack-tracked-buffer
2059 (set-marker overlay-arrow-position nil
))
2060 (mapc #'(lambda (buffer)
2061 (ignore-errors (kill-buffer buffer
)))
2062 python-pdbtrack-buffers-to-kill
)
2063 (setq python-pdbtrack-tracked-buffer nil
2064 python-pdbtrack-buffers-to-kill nil
)))))
2068 ;;; Symbol completion
2070 (defun python-completion-complete-at-point ()
2071 "Complete current symbol at point.
2072 For this to work the best as possible you should call
2073 `python-shell-send-buffer' from time to time so context in
2074 inferior python process is updated properly."
2076 (let ((process (python-shell-get-process)))
2078 (error "Completion needs an inferior Python process running")
2079 (python-shell-completion--do-completion-at-point process
))))
2081 (add-to-list 'debug-ignored-errors
2082 "^Completion needs an inferior Python process running.")
2087 (defcustom python-fill-comment-function
'python-fill-comment
2088 "Function to fill comments.
2089 This is the function used by `python-fill-paragraph-function' to
2095 (defcustom python-fill-string-function
'python-fill-string
2096 "Function to fill strings.
2097 This is the function used by `python-fill-paragraph-function' to
2103 (defcustom python-fill-decorator-function
'python-fill-decorator
2104 "Function to fill decorators.
2105 This is the function used by `python-fill-paragraph-function' to
2111 (defcustom python-fill-paren-function
'python-fill-paren
2112 "Function to fill parens.
2113 This is the function used by `python-fill-paragraph-function' to
2119 (defun python-fill-paragraph-function (&optional justify
)
2120 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2121 If any of the current line is in or at the end of a multi-line string,
2122 fill the string or the paragraph of it that point is in, preserving
2123 the string's indentation.
2124 Optional argument JUSTIFY defines if the paragraph should be justified."
2127 (back-to-indentation)
2130 ((funcall python-fill-comment-function justify
))
2131 ;; Strings/Docstrings
2132 ((save-excursion (skip-chars-forward "\"'uUrR")
2133 (python-info-ppss-context 'string
))
2134 (funcall python-fill-string-function justify
))
2136 ((equal (char-after (save-excursion
2137 (back-to-indentation)
2138 (point-marker))) ?
@)
2139 (funcall python-fill-decorator-function justify
))
2141 ((or (python-info-ppss-context 'paren
)
2142 (looking-at (python-rx open-paren
))
2144 (skip-syntax-forward "^(" (line-end-position))
2145 (looking-at (python-rx open-paren
))))
2146 (funcall python-fill-paren-function justify
))
2149 (defun python-fill-comment (&optional justify
)
2150 "Comment fill function for `python-fill-paragraph-function'.
2151 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2152 (fill-comment-paragraph justify
))
2154 (defun python-fill-string (&optional justify
)
2155 "String fill function for `python-fill-paragraph-function'.
2156 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2157 (let ((marker (point-marker))
2158 (string-start-marker
2160 (skip-chars-forward "\"'uUrR")
2161 (goto-char (python-info-ppss-context 'string
))
2162 (skip-chars-forward "\"'uUrR")
2164 (reg-start (line-beginning-position))
2167 (while (python-info-ppss-context 'string
)
2168 (goto-char (1+ (point-marker))))
2169 (skip-chars-backward "\"'")
2171 (reg-end (line-end-position))
2172 (fill-paragraph-function))
2174 (narrow-to-region reg-start reg-end
)
2176 (goto-char string-start-marker
)
2177 (delete-region (point-marker) (progn
2178 (skip-syntax-forward "> ")
2180 (goto-char string-end-marker
)
2181 (delete-region (point-marker) (progn
2182 (skip-syntax-backward "> ")
2186 (fill-paragraph justify
))
2187 ;; If there is a newline in the docstring lets put triple
2188 ;; quote in it's own line to follow pep 8
2189 (when (save-excursion
2190 (re-search-backward "\n" string-start-marker t
))
2192 (newline-and-indent))
2193 (fill-paragraph justify
)))) t
)
2195 (defun python-fill-decorator (&optional justify
)
2196 "Decorator fill function for `python-fill-paragraph-function'.
2197 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2200 (defun python-fill-paren (&optional justify
)
2201 "Paren fill function for `python-fill-paragraph-function'.
2202 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2204 (narrow-to-region (progn
2205 (while (python-info-ppss-context 'paren
)
2206 (goto-char (1- (point-marker))))
2208 (line-beginning-position))
2210 (when (not (python-info-ppss-context 'paren
))
2212 (when (not (python-info-ppss-context 'paren
))
2213 (skip-syntax-backward "^)")))
2214 (while (python-info-ppss-context 'paren
)
2215 (goto-char (1+ (point-marker))))
2217 (let ((paragraph-start "\f\\|[ \t]*$")
2218 (paragraph-separate ",")
2219 (fill-paragraph-function))
2220 (goto-char (point-min))
2221 (fill-paragraph justify
))
2224 (python-indent-line)
2225 (goto-char (line-end-position)))) t
)
2230 (defcustom python-skeleton-autoinsert nil
2231 "Non-nil means template skeletons will be automagically inserted.
2232 This happens when pressing \"if<SPACE>\", for example, to prompt for
2238 (define-obsolete-variable-alias
2239 'python-use-skeletons
'python-skeleton-autoinsert
"24.2")
2241 (defvar python-skeleton-available
'()
2242 "Internal list of available skeletons.")
2244 (define-abbrev-table 'python-mode-abbrev-table
()
2245 "Abbrev table for Python mode."
2247 ;; Allow / inside abbrevs.
2248 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2249 ;; Only expand in code.
2250 :enable-function
(lambda ()
2252 (not (or (python-info-ppss-context 'string
)
2253 (python-info-ppss-context 'comment
)))
2254 python-skeleton-autoinsert
)))
2256 (defmacro python-skeleton-define
(name doc
&rest skel
)
2257 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2258 The skeleton will be bound to python-skeleton-NAME and will
2259 be added to `python-mode-abbrev-table'."
2260 (declare (indent 2))
2261 (let* ((name (symbol-name name
))
2262 (function-name (intern (concat "python-skeleton-" name
))))
2264 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2266 (setq python-skeleton-available
2267 (cons ',function-name python-skeleton-available
))
2268 (define-skeleton ,function-name
2270 (format "Insert %s statement." name
))
2273 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2274 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2275 The skeleton will be bound to python-skeleton-NAME."
2276 (declare (indent 2))
2277 (let* ((name (symbol-name name
))
2278 (function-name (intern (concat "python-skeleton--" name
)))
2280 "Add '%s' clause? " name
)))
2283 `(< ,(format "%s:" name
) \n \n
2285 `(define-skeleton ,function-name
2287 (format "Auxiliary skeleton for %s statement." name
))
2289 (unless (y-or-n-p ,msg
)
2293 (python-define-auxiliary-skeleton else nil
)
2295 (python-define-auxiliary-skeleton except nil
)
2297 (python-define-auxiliary-skeleton finally nil
)
2299 (python-skeleton-define if nil
2303 ("other condition, %s: "
2307 '(python-skeleton--else) | ^
)
2309 (python-skeleton-define while nil
2313 '(python-skeleton--else) | ^
)
2315 (python-skeleton-define for nil
2319 '(python-skeleton--else) | ^
)
2321 (python-skeleton-define try nil
2327 "except " str
":" \n
2330 '(python-skeleton--except)
2331 '(python-skeleton--else)
2332 '(python-skeleton--finally) | ^
)
2334 (python-skeleton-define def nil
2336 "def " str
" (" ("Parameter, %s: "
2337 (unless (equal ?\
( (char-before)) ", ")
2339 "\"\"\"" -
"\"\"\"" \n
2342 (python-skeleton-define class nil
2344 "class " str
" (" ("Inheritance, %s: "
2345 (unless (equal ?\
( (char-before)) ", ")
2349 "\"\"\"" -
"\"\"\"" \n
2352 (defun python-skeleton-add-menu-items ()
2353 "Add menu items to Python->Skeletons menu."
2354 (let ((skeletons (sort python-skeleton-available
'string
<))
2356 (dolist (skeleton skeletons
)
2358 nil
'("Python" "Skeletons")
2360 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2365 (defcustom python-ffap-setup-code
2366 "def __FFAP_get_module_path(module):
2369 path = __import__(module).__file__
2370 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2375 "Python code to get a module path."
2379 (defcustom python-ffap-string-code
2380 "__FFAP_get_module_path('''%s''')\n"
2381 "Python code used to get a string with the path of a module."
2385 (defun python-ffap-module-path (module)
2386 "Function for `ffap-alist' to return path for MODULE."
2388 (and (eq major-mode
'inferior-python-mode
)
2389 (get-buffer-process (current-buffer)))
2390 (python-shell-get-process))))
2394 (python-shell-send-string-no-output
2395 (format python-ffap-string-code module
) process
)))
2397 (substring-no-properties module-file
1 -
1))))))
2399 (eval-after-load "ffap"
2401 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2402 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2407 (defcustom python-check-command
2409 "Command used to check a Python file."
2413 (defcustom python-check-buffer-name
2414 "*Python check: %s*"
2415 "Buffer name used for check commands."
2419 (defvar python-check-custom-command nil
2422 (defun python-check (command)
2423 "Check a Python file (default current buffer's file).
2424 Runs COMMAND, a shell command, as if by `compile'. See
2425 `python-check-command' for the default."
2427 (list (read-string "Check command: "
2428 (or python-check-custom-command
2429 (concat python-check-command
" "
2430 (shell-quote-argument
2432 (let ((name (buffer-file-name)))
2434 (file-name-nondirectory name
)))
2436 (setq python-check-custom-command command
)
2437 (save-some-buffers (not compilation-ask-about-save
) nil
)
2438 (let ((process-environment (python-shell-calculate-process-environment))
2439 (exec-path (python-shell-calculate-exec-path)))
2440 (compilation-start command nil
2442 (format python-check-buffer-name command
)))))
2447 (defcustom python-eldoc-setup-code
2448 "def __PYDOC_get_help(obj):
2451 if hasattr(obj, 'startswith'):
2452 obj = eval(obj, globals())
2453 doc = inspect.getdoc(obj)
2454 if not doc and callable(obj):
2456 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2457 target = obj.__init__
2463 args = inspect.formatargspec(
2464 *inspect.getargspec(target)
2467 doc = '{objtype} {name}{args}'.format(
2468 objtype=objtype, name=name, args=args
2471 doc = doc.splitlines()[0]
2478 "Python code to setup documentation retrieval."
2482 (defcustom python-eldoc-string-code
2483 "__PYDOC_get_help('''%s''')\n"
2484 "Python code used to get a string with the documentation of an object."
2488 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2489 "Internal implementation to get documentation at point.
2490 If not FORCE-INPUT is passed then what
2491 `python-info-current-symbol' returns will be used. If not
2492 FORCE-PROCESS is passed what `python-shell-get-process' returns
2494 (let ((process (or force-process
(python-shell-get-process))))
2496 (error "Eldoc needs an inferior Python process running")
2497 (let ((input (or force-input
2498 (python-info-current-symbol t
))))
2500 (python-shell-send-string-no-output
2501 (format python-eldoc-string-code input
)
2504 (defun python-eldoc-function ()
2505 "`eldoc-documentation-function' for Python.
2506 For this to work the best as possible you should call
2507 `python-shell-send-buffer' from time to time so context in
2508 inferior python process is updated properly."
2509 (python-eldoc--get-doc-at-point))
2511 (defun python-eldoc-at-point (symbol)
2512 "Get help on SYMBOL using `help'.
2513 Interactively, prompt for symbol."
2515 (let ((symbol (python-info-current-symbol t
))
2516 (enable-recursive-minibuffers t
))
2517 (list (read-string (if symbol
2518 (format "Describe symbol (default %s): " symbol
)
2519 "Describe symbol: ")
2521 (message (python-eldoc--get-doc-at-point symbol
)))
2523 (add-to-list 'debug-ignored-errors
2524 "^Eldoc needs an inferior Python process running.")
2529 (defun python-info-current-defun (&optional include-type
)
2530 "Return name of surrounding function with Python compatible dotty syntax.
2531 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2532 This function is compatible to be used as
2533 `add-log-current-defun-function' since it returns nil if point is
2534 not inside a defun."
2536 (starting-indentation)
2542 (setq starting-point
(point-marker))
2543 (setq starting-indentation
(save-excursion
2544 (python-nav-beginning-of-statement)
2545 (current-indentation)))
2547 (while (python-beginning-of-defun-function 1)
2548 (when (or (< (current-indentation) starting-indentation
)
2553 (python-end-of-defun-function)
2555 (setq first-run nil
)
2556 (setq starting-indentation
(current-indentation))
2557 (looking-at python-nav-beginning-of-defun-regexp
)
2559 (if (not include-type
)
2560 (match-string-no-properties 1)
2561 (mapconcat 'identity
2563 (match-string-no-properties 0)) " "))
2566 (mapconcat (lambda (string) string
) names
"."))))
2568 (defun python-info-current-symbol (&optional replace-self
)
2569 "Return current symbol using dotty syntax.
2570 With optional argument REPLACE-SELF convert \"self\" to current
2573 (and (not (python-info-ppss-comment-or-string-p))
2574 (with-syntax-table python-dotty-syntax-table
2575 (let ((sym (symbol-at-point)))
2577 (substring-no-properties (symbol-name sym
))))))))
2579 (if (not replace-self
)
2581 (let ((current-defun (python-info-current-defun)))
2582 (if (not current-defun
)
2584 (replace-regexp-in-string
2585 (python-rx line-start word-start
"self" word-end ?.
)
2587 (mapconcat 'identity
2588 (butlast (split-string current-defun
"\\."))
2592 (defsubst python-info-beginning-of-block-statement-p
()
2593 "Return non-nil if current statement opens a block."
2595 (python-nav-beginning-of-statement)
2596 (looking-at (python-rx block-start
))))
2598 (defun python-info-closing-block ()
2599 "Return the point of the block the current line closes."
2600 (let ((closing-word (save-excursion
2601 (back-to-indentation)
2603 (indentation (current-indentation)))
2604 (when (member closing-word python-indent-dedenters
)
2607 (while (and (> (current-indentation) indentation
)
2609 (not (back-to-indentation))
2611 (back-to-indentation)
2613 ((not (equal indentation
(current-indentation))) nil
)
2614 ((string= closing-word
"elif")
2615 (when (member (current-word) '("if" "elif"))
2617 ((string= closing-word
"else")
2618 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2620 ((string= closing-word
"except")
2621 (when (member (current-word) '("try"))
2623 ((string= closing-word
"finally")
2624 (when (member (current-word) '("except" "else"))
2625 (point-marker))))))))
2627 (defun python-info-closing-block-message (&optional closing-block-point
)
2628 "Message the contents of the block the current line closes.
2629 With optional argument CLOSING-BLOCK-POINT use that instead of
2630 recalculating it calling `python-info-closing-block'."
2631 (let ((point (or closing-block-point
(python-info-closing-block))))
2635 (message "Closes %s" (save-excursion
2637 (back-to-indentation)
2639 (point) (line-end-position))))))))
2641 (defun python-info-line-ends-backslash-p (&optional line-number
)
2642 "Return non-nil if current line ends with backslash.
2643 With optional argument LINE-NUMBER, check that line instead."
2648 (goto-char line-number
))
2649 (while (and (not (eobp))
2650 (goto-char (line-end-position))
2651 (python-info-ppss-context 'paren
)
2652 (not (equal (char-before (point)) ?
\\)))
2654 (when (equal (char-before) ?
\\)
2657 (defun python-info-beginning-of-backslash (&optional line-number
)
2658 "Return the point where the backslashed line start.
2659 Optional argument LINE-NUMBER forces the line number to check against."
2664 (goto-char line-number
))
2665 (when (python-info-line-ends-backslash-p)
2666 (while (save-excursion
2667 (goto-char (line-beginning-position))
2668 (python-info-ppss-context 'paren
))
2670 (back-to-indentation)
2673 (defun python-info-continuation-line-p ()
2674 "Check if current line is continuation of another.
2675 When current line is continuation of another return the point
2676 where the continued line ends."
2680 (let* ((context-type (progn
2681 (back-to-indentation)
2682 (python-info-ppss-context-type)))
2683 (line-start (line-number-at-pos))
2684 (context-start (when context-type
2685 (python-info-ppss-context context-type
))))
2686 (cond ((equal context-type
'paren
)
2687 ;; Lines inside a paren are always a continuation line
2688 ;; (except the first one).
2689 (when (equal (python-info-ppss-context-type) 'paren
)
2690 (python-util-forward-comment -
1)
2691 (python-util-forward-comment -
1)
2693 ((or (equal context-type
'comment
)
2694 (equal context-type
'string
))
2695 ;; move forward an roll again
2696 (goto-char context-start
)
2697 (python-util-forward-comment)
2698 (python-info-continuation-line-p))
2700 ;; Not within a paren, string or comment, the only way we are
2701 ;; dealing with a continuation line is that previous line
2702 ;; contains a backslash, and this can only be the previous line
2704 (back-to-indentation)
2705 (python-util-forward-comment -
1)
2706 (python-util-forward-comment -
1)
2707 (when (and (equal (1- line-start
) (line-number-at-pos))
2708 (python-info-line-ends-backslash-p))
2709 (point-marker))))))))
2711 (defun python-info-block-continuation-line-p ()
2712 "Return non-nil if current line is a continuation of a block."
2714 (when (python-info-continuation-line-p)
2716 (back-to-indentation)
2717 (when (looking-at (python-rx block-start
))
2720 (defun python-info-assignment-continuation-line-p ()
2721 "Check if current line is a continuation of an assignment.
2722 When current line is continuation of another with an assignment
2723 return the point of the first non-blank character after the
2726 (when (python-info-continuation-line-p)
2728 (back-to-indentation)
2729 (when (and (not (looking-at (python-rx block-start
)))
2730 (and (re-search-forward (python-rx not-simple-operator
2732 not-simple-operator
)
2733 (line-end-position) t
)
2734 (not (or (python-info-ppss-context 'string
)
2735 (python-info-ppss-context 'paren
)
2736 (python-info-ppss-context 'comment
)))))
2737 (skip-syntax-forward "\s")
2740 (defun python-info-ppss-context (type &optional syntax-ppss
)
2741 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2742 TYPE can be 'comment, 'string or 'paren. It returns the start
2743 character address of the specified TYPE."
2744 (let ((ppss (or syntax-ppss
(syntax-ppss))))
2750 (and (not (nth 4 ppss
))
2756 (defun python-info-ppss-context-type (&optional syntax-ppss
)
2757 "Return the context type using SYNTAX-PPSS.
2758 The type returned can be 'comment, 'string or 'paren."
2759 (let ((ppss (or syntax-ppss
(syntax-ppss))))
2770 (defsubst python-info-ppss-comment-or-string-p
()
2771 "Return non-nil if point is inside 'comment or 'string."
2772 (car (member (python-info-ppss-context-type) '(string comment
))))
2774 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
2775 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
2776 (and (not (python-info-ppss-context-type (or syntax-ppss
(syntax-ppss))))
2778 (beginning-of-line 1)
2779 (looking-at python-nav-beginning-of-defun-regexp
))))
2781 (defun python-info-current-line-comment-p ()
2782 "Check if current line is a comment line."
2783 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
2785 (defun python-info-current-line-empty-p ()
2786 "Check if current line is empty, ignoring whitespace."
2788 (beginning-of-line 1)
2790 (python-rx line-start
(* whitespace
)
2791 (group (* not-newline
))
2792 (* whitespace
) line-end
))
2793 (string-equal "" (match-string-no-properties 1))))
2796 ;;; Utility functions
2798 (defun python-util-position (item seq
)
2799 "Find the first occurrence of ITEM in SEQ.
2800 Return the index of the matching item, or nil if not found."
2801 (let ((member-result (member item seq
)))
2803 (- (length seq
) (length member-result
)))))
2805 ;; Stolen from org-mode
2806 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
2807 "Clone local variables from FROM-BUFFER.
2808 Optional argument REGEXP selects variables to clone and defaults
2812 (and (symbolp (car pair
))
2813 (string-match (or regexp
"^python-")
2814 (symbol-name (car pair
)))
2815 (set (make-local-variable (car pair
))
2817 (buffer-local-variables from-buffer
)))
2819 (defun python-util-forward-comment (&optional direction
)
2820 "Python mode specific version of `forward-comment'.
2821 Optional argument DIRECTION defines the direction to move to."
2822 (let ((comment-start (python-info-ppss-context 'comment
))
2823 (factor (if (< (or direction
0) 0)
2827 (goto-char comment-start
))
2828 (forward-comment factor
)))
2832 (define-derived-mode python-mode prog-mode
"Python"
2833 "Major mode for editing Python files.
2836 Entry to this mode calls the value of `python-mode-hook'
2837 if that value is non-nil."
2838 (set (make-local-variable 'tab-width
) 8)
2839 (set (make-local-variable 'indent-tabs-mode
) nil
)
2841 (set (make-local-variable 'comment-start
) "# ")
2842 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
2844 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2845 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
2847 (set (make-local-variable 'forward-sexp-function
)
2848 'python-nav-forward-sexp-function
)
2850 (set (make-local-variable 'font-lock-defaults
)
2851 '(python-font-lock-keywords nil nil nil nil
))
2853 (set (make-local-variable 'syntax-propertize-function
)
2854 python-syntax-propertize-function
)
2856 (set (make-local-variable 'indent-line-function
)
2857 #'python-indent-line-function
)
2858 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2860 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2861 (set (make-local-variable 'fill-paragraph-function
)
2862 'python-fill-paragraph-function
)
2864 (set (make-local-variable 'beginning-of-defun-function
)
2865 #'python-beginning-of-defun-function
)
2866 (set (make-local-variable 'end-of-defun-function
)
2867 #'python-end-of-defun-function
)
2869 (add-hook 'completion-at-point-functions
2870 'python-completion-complete-at-point nil
'local
)
2872 (add-hook 'post-self-insert-hook
2873 'python-indent-post-self-insert-function nil
'local
)
2875 (set (make-local-variable 'imenu-extract-index-name-function
)
2876 #'python-info-current-defun
)
2878 (set (make-local-variable 'add-log-current-defun-function
)
2879 #'python-info-current-defun
)
2881 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
2883 (set (make-local-variable 'skeleton-further-elements
)
2885 (< '(backward-delete-char-untabify (min python-indent-offset
2887 (^
'(- (1+ (current-indentation))))))
2889 (set (make-local-variable 'eldoc-documentation-function
)
2890 #'python-eldoc-function
)
2892 (add-to-list 'hs-special-modes-alist
2893 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
2895 (python-end-of-defun-function)) nil
))
2897 (set (make-local-variable 'mode-require-final-newline
) t
)
2899 (set (make-local-variable 'outline-regexp
)
2900 (python-rx (* space
) block-start
))
2901 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
2902 (set (make-local-variable 'outline-level
)
2904 "`outline-level' function for Python mode."
2905 (1+ (/ (current-indentation) python-indent-offset
))))
2907 (python-skeleton-add-menu-items)
2909 (when python-indent-guess-indent-offset
2910 (python-indent-guess-indent-offset)))
2917 ;; indent-tabs-mode: nil
2920 ;;; python.el ends here