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' 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 (define-key map
[remap backward-sentence
] 'python-nav-backward-block
)
233 (define-key map
[remap forward-sentence
] 'python-nav-forward-block
)
234 (define-key map
[remap backward-up-list
] 'python-nav-backward-up-list
)
235 (define-key map
"\C-c\C-j" 'imenu
)
237 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
238 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
239 (define-key map
"\C-c<" 'python-indent-shift-left
)
240 (define-key map
"\C-c>" 'python-indent-shift-right
)
241 (define-key map
":" 'python-indent-electric-colon
)
243 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
244 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
245 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
246 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
247 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
248 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
250 (define-key map
"\C-c\C-p" 'run-python
)
251 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
252 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
253 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
254 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
255 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
256 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
257 ;; Some util commands
258 (define-key map
"\C-c\C-v" 'python-check
)
259 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
261 (substitute-key-definition 'complete-symbol
'completion-at-point
263 (easy-menu-define python-menu map
"Python Mode menu"
265 :help
"Python-specific Features"
266 ["Shift region left" python-indent-shift-left
:active mark-active
267 :help
"Shift region left by a single indentation step"]
268 ["Shift region right" python-indent-shift-right
:active mark-active
269 :help
"Shift region right by a single indentation step"]
271 ["Start of def/class" beginning-of-defun
272 :help
"Go to start of outermost definition around point"]
273 ["End of def/class" end-of-defun
274 :help
"Go to end of definition around point"]
275 ["Mark def/class" mark-defun
276 :help
"Mark outermost definition around point"]
277 ["Jump to def/class" imenu
278 :help
"Jump to a class or function definition"]
282 ["Start interpreter" run-python
283 :help
"Run inferior Python process in a separate buffer"]
284 ["Switch to shell" python-shell-switch-to-shell
285 :help
"Switch to running inferior Python process"]
286 ["Eval string" python-shell-send-string
287 :help
"Eval string in inferior Python session"]
288 ["Eval buffer" python-shell-send-buffer
289 :help
"Eval buffer in inferior Python session"]
290 ["Eval region" python-shell-send-region
291 :help
"Eval region in inferior Python session"]
292 ["Eval defun" python-shell-send-defun
293 :help
"Eval defun in inferior Python session"]
294 ["Eval file" python-shell-send-file
295 :help
"Eval file in inferior Python session"]
296 ["Debugger" pdb
:help
"Run pdb under GUD"]
298 ["Check file" python-check
299 :help
"Check file for errors"]
300 ["Help on symbol" python-eldoc-at-point
301 :help
"Get help on symbol at point"]
302 ["Complete symbol" completion-at-point
303 :help
"Complete symbol before point"]))
305 "Keymap for `python-mode'.")
308 ;;; Python specialized rx
311 (defconst python-rx-constituents
312 `((block-start .
,(rx symbol-start
313 (or "def" "class" "if" "elif" "else" "try"
314 "except" "finally" "for" "while" "with")
316 (decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
318 (defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
319 (if-name-main .
,(rx line-start
"if" (+ space
) "__name__"
320 (+ space
) "==" (+ space
)
321 (any ?
' ?
\") "__main__" (any ?
' ?
\")
323 (symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
324 (open-paren .
,(rx (or "{" "[" "(")))
325 (close-paren .
,(rx (or "}" "]" ")")))
326 (simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
327 ;; FIXME: rx should support (not simple-operator).
328 (not-simple-operator .
,(rx
330 (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
331 ;; FIXME: Use regexp-opt.
332 (operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
333 "=" "%" "**" "//" "<<" ">>" "<=" "!="
334 "==" ">=" "is" "not")))
335 ;; FIXME: Use regexp-opt.
336 (assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
337 ">>=" "<<=" "&=" "^=" "|=")))
338 (string-delimiter .
,(rx (and
339 ;; Match even number of backslashes.
340 (or (not (any ?
\\ ?
\' ?
\")) point
341 ;; Quotes might be preceded by a escaped quote.
342 (and (or (not (any ?
\\)) point
) ?
\\
343 (* ?
\\ ?
\\) (any ?
\' ?
\")))
345 ;; Match single or triple quotes of any kind.
346 (group (or "\"" "\"\"\"" "'" "'''"))))))
347 "Additional Python specific sexps for `python-rx'")
349 (defmacro python-rx
(&rest regexps
)
350 "Python mode specialized rx macro.
351 This variant of `rx' supports common python named REGEXPS."
352 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
353 (cond ((null regexps
)
356 (rx-to-string `(and ,@regexps
) t
))
358 (rx-to-string (car regexps
) t
))))))
361 ;;; Font-lock and syntax
363 (defun python-syntax-context (type &optional syntax-ppss
)
364 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
365 TYPE can be `comment', `string' or `paren'. It returns the start
366 character address of the specified TYPE."
367 (let ((ppss (or syntax-ppss
(syntax-ppss))))
369 (comment (and (nth 4 ppss
) (nth 8 ppss
)))
370 (string (and (not (nth 4 ppss
)) (nth 8 ppss
)))
374 (defun python-syntax-context-type (&optional syntax-ppss
)
375 "Return the context type using SYNTAX-PPSS.
376 The type returned can be `comment', `string' or `paren'."
377 (let ((ppss (or syntax-ppss
(syntax-ppss))))
379 ((nth 8 ppss
) (if (nth 4 ppss
) 'comment
'string
))
380 ((nth 1 ppss
) 'paren
))))
382 (defsubst python-syntax-comment-or-string-p
()
383 "Return non-nil if point is inside 'comment or 'string."
384 (nth 8 (syntax-ppss)))
386 (define-obsolete-function-alias
387 'python-info-ppss-context
#'python-syntax-context
"24.3")
389 (define-obsolete-function-alias
390 'python-info-ppss-context-type
#'python-syntax-context-type
"24.3")
392 (define-obsolete-function-alias
393 'python-info-ppss-comment-or-string-p
394 #'python-syntax-comment-or-string-p
"24.3")
396 (defvar python-font-lock-keywords
400 "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
401 "assert" "else" "if" "pass" "yield" "break" "except" "import" "class"
402 "in" "raise" "continue" "finally" "is" "return" "def" "for" "lambda"
407 ;; False, None, and True are listed as keywords on the Python 3
408 ;; documentation, but since they also qualify as constants they are
409 ;; fontified like that in order to keep font-lock consistent between
416 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
417 (1 font-lock-function-name-face
))
419 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
420 (1 font-lock-type-face
))
424 "Ellipsis" "False" "None" "NotImplemented" "True" "__debug__"
425 ;; copyright, license, credits, quit and exit are added by the site
426 ;; module and they are not intended to be used in programs
427 "copyright" "credits" "exit" "license" "quit")
428 symbol-end
) . font-lock-constant-face
)
430 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
431 (0+ "." (1+ (or word ?_
)))))
432 (1 font-lock-type-face
))
433 ;; Builtin Exceptions
436 "ArithmeticError" "AssertionError" "AttributeError" "BaseException"
437 "DeprecationWarning" "EOFError" "EnvironmentError" "Exception"
438 "FloatingPointError" "FutureWarning" "GeneratorExit" "IOError"
439 "ImportError" "ImportWarning" "IndexError" "KeyError"
440 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
441 "NotImplementedError" "OSError" "OverflowError"
442 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
443 "RuntimeWarning" "StopIteration" "SyntaxError" "SyntaxWarning"
444 "SystemError" "SystemExit" "TypeError" "UnboundLocalError"
445 "UnicodeDecodeError" "UnicodeEncodeError" "UnicodeError"
446 "UnicodeTranslateError" "UnicodeWarning" "UserWarning" "VMSError"
447 "ValueError" "Warning" "WindowsError" "ZeroDivisionError"
451 "BufferError" "BytesWarning" "IndentationError" "ResourceWarning"
453 symbol-end
) . font-lock-type-face
)
457 "abs" "all" "any" "bin" "bool" "callable" "chr" "classmethod"
458 "compile" "complex" "delattr" "dict" "dir" "divmod" "enumerate"
459 "eval" "filter" "float" "format" "frozenset" "getattr" "globals"
460 "hasattr" "hash" "help" "hex" "id" "input" "int" "isinstance"
461 "issubclass" "iter" "len" "list" "locals" "map" "max" "memoryview"
462 "min" "next" "object" "oct" "open" "ord" "pow" "print" "property"
463 "range" "repr" "reversed" "round" "set" "setattr" "slice" "sorted"
464 "staticmethod" "str" "sum" "super" "tuple" "type" "vars" "zip"
467 "basestring" "cmp" "execfile" "file" "long" "raw_input" "reduce"
468 "reload" "unichr" "unicode" "xrange" "apply" "buffer" "coerce"
471 "ascii" "bytearray" "bytes" "exec"
473 "__all__" "__doc__" "__name__" "__package__")
474 symbol-end
) . font-lock-builtin-face
)
476 ;; support for a = b = c = 5
478 (let ((re (python-rx (group (+ (any word ?. ?_
)))
479 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
480 assignment-operator
)))
481 (when (re-search-forward re limit t
)
482 (while (and (python-syntax-context 'paren
)
483 (re-search-forward re limit t
)))
484 (if (and (not (python-syntax-context 'paren
))
485 (not (equal (char-after (point-marker)) ?
=)))
487 (set-match-data nil
)))))
488 (1 font-lock-variable-name-face nil nil
))
489 ;; support for a, b, c = (1, 2, 3)
491 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
492 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
493 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
494 assignment-operator
)))
495 (when (and (re-search-forward re limit t
)
496 (goto-char (nth 3 (match-data))))
497 (while (and (python-syntax-context 'paren
)
498 (re-search-forward re limit t
))
499 (goto-char (nth 3 (match-data))))
500 (if (not (python-syntax-context 'paren
))
502 (set-match-data nil
)))))
503 (1 font-lock-variable-name-face nil nil
))))
505 (defconst python-syntax-propertize-function
506 (syntax-propertize-rules
507 ((python-rx string-delimiter
)
508 (0 (ignore (python-syntax-stringify))))))
510 (defsubst python-syntax-count-quotes
(quote-char &optional point limit
)
511 "Count number of quotes around point (max is 3).
512 QUOTE-CHAR is the quote char to count. Optional argument POINT is
513 the point where scan starts (defaults to current point) and LIMIT
514 is used to limit the scan."
517 (or (not limit
) (< (+ point i
) limit
))
518 (eq (char-after (+ point i
)) quote-char
))
522 (defun python-syntax-stringify ()
523 "Put `syntax-table' property correctly on single/triple quotes."
524 (let* ((num-quotes (length (match-string-no-properties 1)))
526 (backward-char num-quotes
)
528 (forward-char num-quotes
)))
529 (string-start (and (not (nth 4 ppss
)) (nth 8 ppss
)))
530 (quote-starting-pos (- (point) num-quotes
))
531 (quote-ending-pos (point))
534 (python-syntax-count-quotes
535 (char-before) string-start quote-starting-pos
))))
536 (cond ((and string-start
(= num-closing-quotes
0))
537 ;; This set of quotes doesn't match the string starting
541 ;; This set of quotes delimit the start of a string.
542 (put-text-property quote-starting-pos
(1+ quote-starting-pos
)
543 'syntax-table
(string-to-syntax "|")))
544 ((= num-quotes num-closing-quotes
)
545 ;; This set of quotes delimit the end of a string.
546 (put-text-property (1- quote-ending-pos
) quote-ending-pos
547 'syntax-table
(string-to-syntax "|")))
548 ((> num-quotes num-closing-quotes
)
549 ;; This may only happen whenever a triple quote is closing
550 ;; a single quoted string. Add string delimiter syntax to
552 (put-text-property quote-starting-pos quote-ending-pos
553 'syntax-table
(string-to-syntax "|"))))))
555 (defvar python-mode-syntax-table
556 (let ((table (make-syntax-table)))
557 ;; Give punctuation syntax to ASCII that normally has symbol
558 ;; syntax or has word syntax and isn't a letter.
559 (let ((symbol (string-to-syntax "_"))
560 (sst (standard-syntax-table)))
563 (if (equal symbol
(aref sst i
))
564 (modify-syntax-entry i
"." table
)))))
565 (modify-syntax-entry ?$
"." table
)
566 (modify-syntax-entry ?%
"." table
)
568 (modify-syntax-entry ?
# "<" table
)
569 (modify-syntax-entry ?
\n ">" table
)
570 (modify-syntax-entry ?
' "\"" table
)
571 (modify-syntax-entry ?
` "$" table
)
573 "Syntax table for Python files.")
575 (defvar python-dotty-syntax-table
576 (let ((table (make-syntax-table python-mode-syntax-table
)))
577 (modify-syntax-entry ?.
"w" table
)
578 (modify-syntax-entry ?_
"w" table
)
580 "Dotty syntax table for Python files.
581 It makes underscores and dots word constituent chars.")
586 (defcustom python-indent-offset
4
587 "Default indentation offset for Python."
592 (defcustom python-indent-guess-indent-offset t
593 "Non-nil tells Python mode to guess `python-indent-offset' value."
598 (define-obsolete-variable-alias
599 'python-indent
'python-indent-offset
"24.3")
601 (define-obsolete-variable-alias
602 'python-guess-indent
'python-indent-guess-indent-offset
"24.3")
604 (defvar python-indent-current-level
0
605 "Current indentation level `python-indent-line-function' is using.")
607 (defvar python-indent-levels
'(0)
608 "Levels of indentation available for `python-indent-line-function'.")
610 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
611 "List of words that should be dedented.
612 These make `python-indent-calculate-indentation' subtract the value of
613 `python-indent-offset'.")
615 (defun python-indent-guess-indent-offset ()
616 "Guess and set `python-indent-offset' for the current buffer."
621 (goto-char (point-min))
623 (while (and (not block-end
)
625 (python-rx line-start block-start
) nil t
))
627 (not (python-syntax-context-type))
629 (goto-char (line-end-position))
630 (python-util-forward-comment -
1)
631 (if (equal (char-before) ?
:)
634 (when (python-info-block-continuation-line-p)
635 (while (and (python-info-continuation-line-p)
638 (python-util-forward-comment -
1)
639 (when (equal (char-before) ?
:)
641 (setq block-end
(point-marker))))
644 (goto-char block-end
)
645 (python-util-forward-comment)
646 (current-indentation))))
648 (setq python-indent-offset indentation
)
649 (message "Can't guess python-indent-offset, using defaults: %s"
650 python-indent-offset
)))))))
652 (defun python-indent-context ()
653 "Get information on indentation context.
654 Context information is returned with a cons with the form:
657 Where status can be any of the following symbols:
658 * inside-paren: If point in between (), {} or []
659 * inside-string: If point is inside a string
660 * after-backslash: Previous line ends in a backslash
661 * after-beginning-of-block: Point is after beginning of block
662 * after-line: Point is after normal line
663 * no-indent: Point is at beginning of buffer or other special case
664 START is the buffer position where the sexp starts."
667 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
671 ;; Beginning of buffer
673 (goto-char (line-beginning-position))
677 ((setq start
(python-syntax-context 'string ppss
))
680 ((setq start
(python-syntax-context 'paren ppss
))
683 ((setq start
(when (not (or (python-syntax-context 'string ppss
)
684 (python-syntax-context 'comment ppss
)))
685 (let ((line-beg-pos (line-beginning-position)))
686 (when (python-info-line-ends-backslash-p
688 (- line-beg-pos
2)))))
690 ;; After beginning of block
691 ((setq start
(save-excursion
693 (back-to-indentation)
694 (python-util-forward-comment -
1)
695 (equal (char-before) ?
:))
696 ;; Move to the first block start that's not in within
697 ;; a string, comment or paren and that's not a
698 ;; continuation line.
699 (while (and (re-search-backward
700 (python-rx block-start
) nil t
)
702 (python-syntax-context-type)
703 (python-info-continuation-line-p))))
704 (when (looking-at (python-rx block-start
))
706 'after-beginning-of-block
)
708 ((setq start
(save-excursion
709 (back-to-indentation)
710 (skip-chars-backward (rx (or whitespace ?
\n)))
711 (python-nav-beginning-of-statement)
718 (defun python-indent-calculate-indentation ()
719 "Calculate correct indentation offset for the current line."
720 (let* ((indentation-context (python-indent-context))
721 (context-status (car indentation-context
))
722 (context-start (cdr indentation-context
)))
728 ;; When point is after beginning of block just add one level
729 ;; of indentation relative to the context-start
730 ('after-beginning-of-block
731 (goto-char context-start
)
732 (+ (current-indentation) python-indent-offset
))
733 ;; When after a simple line just use previous line
734 ;; indentation, in the case current line starts with a
735 ;; `python-indent-dedenters' de-indent one level.
739 (goto-char context-start
)
740 (current-indentation))
742 (back-to-indentation)
743 (looking-at (regexp-opt python-indent-dedenters
)))
746 ;; When inside of a string, do nothing. just use the current
747 ;; indentation. XXX: perhaps it would be a good idea to
748 ;; invoke standard text indentation here
750 (goto-char context-start
)
751 (current-indentation))
752 ;; After backslash we have several possibilities.
755 ;; Check if current line is a dot continuation. For this
756 ;; the current line must start with a dot and previous
757 ;; line must contain a dot too.
759 (back-to-indentation)
760 (when (looking-at "\\.")
761 ;; If after moving one line back point is inside a paren it
762 ;; needs to move back until it's not anymore
766 (python-syntax-context 'paren
))))
767 (goto-char (line-end-position))
768 (while (and (re-search-backward
769 "\\." (line-beginning-position) t
)
770 (python-syntax-context-type)))
771 (if (and (looking-at "\\.")
772 (not (python-syntax-context-type)))
773 ;; The indentation is the same column of the
774 ;; first matching dot that's not inside a
775 ;; comment, a string or a paren
777 ;; No dot found on previous line, just add another
778 ;; indentation level.
779 (+ (current-indentation) python-indent-offset
)))))
780 ;; Check if prev line is a block continuation
781 ((let ((block-continuation-start
782 (python-info-block-continuation-line-p)))
783 (when block-continuation-start
784 ;; If block-continuation-start is set jump to that
785 ;; marker and use first column after the block start
786 ;; as indentation value.
787 (goto-char block-continuation-start
)
789 (python-rx block-start
(* space
))
790 (line-end-position) t
)
792 ;; Check if current line is an assignment continuation
793 ((let ((assignment-continuation-start
794 (python-info-assignment-continuation-line-p)))
795 (when assignment-continuation-start
796 ;; If assignment-continuation is set jump to that
797 ;; marker and use first column after the assignment
798 ;; operator as indentation value.
799 (goto-char assignment-continuation-start
)
803 (goto-char (python-info-beginning-of-backslash))
808 (or (python-info-beginning-of-backslash) (point)))
809 (python-info-line-ends-backslash-p)))
810 ;; The two previous lines ended in a backslash so we must
811 ;; respect previous line indentation.
812 (current-indentation)
813 ;; What happens here is that we are dealing with the second
814 ;; line of a backslash continuation, in that case we just going
815 ;; to add one indentation level.
816 (+ (current-indentation) python-indent-offset
)))))
817 ;; When inside a paren there's a need to handle nesting
821 ;; If current line closes the outermost open paren use the
822 ;; current indentation of the context-start line.
824 (skip-syntax-forward "\s" (line-end-position))
825 (when (and (looking-at (regexp-opt '(")" "]" "}")))
828 (not (python-syntax-context 'paren
))))
829 (goto-char context-start
)
830 (current-indentation))))
831 ;; If open paren is contained on a line by itself add another
832 ;; indentation level, else look for the first word after the
833 ;; opening paren and use it's column position as indentation
835 ((let* ((content-starts-in-newline)
838 (if (setq content-starts-in-newline
840 (goto-char context-start
)
844 (line-beginning-position)
846 (python-util-forward-comment))
848 (+ (current-indentation) python-indent-offset
)
852 ;; If current line closes a nested open paren de-indent one
855 (back-to-indentation)
856 (looking-at (regexp-opt '(")" "]" "}"))))
857 (- indent python-indent-offset
))
858 ;; If the line of the opening paren that wraps the current
859 ;; line starts a block add another level of indentation to
860 ;; follow new pep8 recommendation. See: http://ur1.ca/5rojx
862 (when (and content-starts-in-newline
864 (goto-char context-start
)
865 (back-to-indentation)
866 (looking-at (python-rx block-start
))))
867 (+ indent python-indent-offset
))))
870 (defun python-indent-calculate-levels ()
871 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
872 (let* ((indentation (python-indent-calculate-indentation))
873 (remainder (% indentation python-indent-offset
))
874 (steps (/ (- indentation remainder
) python-indent-offset
)))
875 (setq python-indent-levels
(list 0))
876 (dotimes (step steps
)
877 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
878 (when (not (eq 0 remainder
))
879 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
880 (setq python-indent-levels
(nreverse python-indent-levels
))
881 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
883 (defun python-indent-toggle-levels ()
884 "Toggle `python-indent-current-level' over `python-indent-levels'."
885 (setq python-indent-current-level
(1- python-indent-current-level
))
886 (when (< python-indent-current-level
0)
887 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
889 (defun python-indent-line (&optional force-toggle
)
890 "Internal implementation of `python-indent-line-function'.
891 Uses the offset calculated in
892 `python-indent-calculate-indentation' and available levels
893 indicated by the variable `python-indent-levels' to set the
896 When the variable `last-command' is equal to
897 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
898 levels indicated in the variable `python-indent-levels' by
899 setting the current level in the variable
900 `python-indent-current-level'.
902 When the variable `last-command' is not equal to
903 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
904 possible indentation levels and saves it in the variable
905 `python-indent-levels'. Afterwards it sets the variable
906 `python-indent-current-level' correctly so offset is equal
907 to (`nth' `python-indent-current-level' `python-indent-levels')"
909 (and (or (and (eq this-command
'indent-for-tab-command
)
910 (eq last-command this-command
))
912 (not (equal python-indent-levels
'(0)))
913 (or (python-indent-toggle-levels) t
))
914 (python-indent-calculate-levels))
915 (let* ((starting-pos (point-marker))
916 (indent-ending-position
917 (+ (line-beginning-position) (current-indentation)))
918 (follow-indentation-p
920 (and (<= (line-beginning-position) starting-pos
)
921 (>= indent-ending-position starting-pos
))))
922 (next-indent (nth python-indent-current-level python-indent-levels
)))
923 (unless (= next-indent
(current-indentation))
925 (delete-horizontal-space)
926 (indent-to next-indent
)
927 (goto-char starting-pos
))
928 (and follow-indentation-p
(back-to-indentation)))
929 (python-info-closing-block-message))
931 (defun python-indent-line-function ()
932 "`indent-line-function' for Python mode.
933 See `python-indent-line' for details."
934 (python-indent-line))
936 (defun python-indent-dedent-line ()
937 "De-indent current line."
939 (when (and (not (python-syntax-comment-or-string-p))
940 (<= (point-marker) (save-excursion
941 (back-to-indentation)
943 (> (current-column) 0))
944 (python-indent-line t
)
947 (defun python-indent-dedent-line-backspace (arg)
948 "De-indent current line.
949 Argument ARG is passed to `backward-delete-char-untabify' when
950 point is not in between the indentation."
952 (when (not (python-indent-dedent-line))
953 (backward-delete-char-untabify arg
)))
954 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
956 (defun python-indent-region (start end
)
957 "Indent a python region automagically.
959 Called from a program, START and END specify the region to indent."
960 (let ((deactivate-mark nil
))
963 (setq end
(point-marker))
965 (or (bolp) (forward-line 1))
966 (while (< (point) end
)
967 (or (and (bolp) (eolp))
970 (back-to-indentation)
971 (setq word
(current-word))
974 ;; Don't mess with strings, unless it's the
975 ;; enclosing set of quotes.
976 (or (not (python-syntax-context 'string
))
980 (current-indentation)
981 (python-syntax-count-quotes (char-after) (point))))
982 (string-to-syntax "|"))))
984 (delete-horizontal-space)
985 (indent-to (python-indent-calculate-indentation)))))
987 (move-marker end nil
))))
989 (defun python-indent-shift-left (start end
&optional count
)
990 "Shift lines contained in region START END by COUNT columns to the left.
991 COUNT defaults to `python-indent-offset'. If region isn't
992 active, the current line is shifted. The shifted region includes
993 the lines in which START and END lie. An error is signaled if
994 any lines in the region are indented less than COUNT columns."
997 (list (region-beginning) (region-end) current-prefix-arg
)
998 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1000 (setq count
(prefix-numeric-value count
))
1001 (setq count python-indent-offset
))
1003 (let ((deactivate-mark nil
))
1006 (while (< (point) end
)
1007 (if (and (< (current-indentation) count
)
1008 (not (looking-at "[ \t]*$")))
1009 (error "Can't shift all lines enough"))
1011 (indent-rigidly start end
(- count
))))))
1013 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
1015 (defun python-indent-shift-right (start end
&optional count
)
1016 "Shift lines contained in region START END by COUNT columns to the left.
1017 COUNT defaults to `python-indent-offset'. If region isn't
1018 active, the current line is shifted. The shifted region includes
1019 the lines in which START and END lie."
1022 (list (region-beginning) (region-end) current-prefix-arg
)
1023 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
1024 (let ((deactivate-mark nil
))
1026 (setq count
(prefix-numeric-value count
))
1027 (setq count python-indent-offset
))
1028 (indent-rigidly start end count
)))
1030 (defun python-indent-electric-colon (arg)
1031 "Insert a colon and maybe de-indent the current line.
1032 With numeric ARG, just insert that many colons. With
1033 \\[universal-argument], just insert a single colon."
1035 (self-insert-command (if (not (integerp arg
)) 1 arg
))
1036 (when (and (not arg
)
1038 (not (equal ?
: (char-after (- (point-marker) 2))))
1039 (not (python-syntax-comment-or-string-p)))
1040 (let ((indentation (current-indentation))
1041 (calculated-indentation (python-indent-calculate-indentation)))
1042 (python-info-closing-block-message)
1043 (when (> indentation calculated-indentation
)
1045 (indent-line-to calculated-indentation
)
1046 (when (not (python-info-closing-block-message))
1047 (indent-line-to indentation
)))))))
1048 (put 'python-indent-electric-colon
'delete-selection t
)
1050 (defun python-indent-post-self-insert-function ()
1051 "Adjust closing paren line indentation after a char is added.
1052 This function is intended to be added to the
1053 `post-self-insert-hook.' If a line renders a paren alone, after
1054 adding a char before it, the line will be re-indented
1055 automatically if needed."
1056 (when (and (eq (char-before) last-command-event
)
1058 (memq (char-after) '(?\
) ?\
] ?\
})))
1060 (goto-char (line-beginning-position))
1061 ;; If after going to the beginning of line the point
1062 ;; is still inside a paren it's ok to do the trick
1063 (when (python-syntax-context 'paren
)
1064 (let ((indentation (python-indent-calculate-indentation)))
1065 (when (< (current-indentation) indentation
)
1066 (indent-line-to indentation
)))))))
1071 (defvar python-nav-beginning-of-defun-regexp
1072 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
1073 "Regexp matching class or function definition.
1074 The name of the defun should be grouped so it can be retrieved
1075 via `match-string'.")
1077 (defun python-nav-beginning-of-defun (&optional arg
)
1078 "Move point to `beginning-of-defun'.
1079 With positive ARG move search backwards. With negative do the
1080 same but forward. When ARG is nil or 0 defaults to 1. This is
1081 the main part of `python-beginning-of-defun-function'. Return
1082 non-nil if point is moved to `beginning-of-defun'."
1083 (when (or (null arg
) (= arg
0)) (setq arg
1))
1084 (let* ((re-search-fn (if (> arg
0)
1085 #'re-search-backward
1086 #'re-search-forward
))
1087 (line-beg-pos (line-beginning-position))
1088 (line-content-start (+ line-beg-pos
(current-indentation)))
1089 (pos (point-marker))
1092 (when (and (< arg
0)
1093 (python-info-looking-at-beginning-of-defun))
1095 (while (and (funcall re-search-fn
1096 python-nav-beginning-of-defun-regexp nil t
)
1097 (python-syntax-context-type)))
1098 (and (python-info-looking-at-beginning-of-defun)
1099 (or (not (= (line-number-at-pos pos
)
1100 (line-number-at-pos)))
1101 (and (>= (point) line-beg-pos
)
1102 (<= (point) line-content-start
)
1103 (> pos line-content-start
)))))))
1105 (or (beginning-of-line 1) t
)
1106 (and (goto-char pos
) nil
))))
1108 (defun python-beginning-of-defun-function (&optional arg
)
1109 "Move point to the beginning of def or class.
1110 With positive ARG move that number of functions backwards. With
1111 negative do the same but forward. When ARG is nil or 0 defaults
1112 to 1. Return non-nil if point is moved to `beginning-of-defun'."
1113 (when (or (null arg
) (= arg
0)) (setq arg
1))
1115 (cond ((and (eq this-command
'mark-defun
)
1116 (python-info-looking-at-beginning-of-defun)))
1118 (dotimes (i (if (> arg
0) arg
(- arg
)))
1119 (when (and (python-nav-beginning-of-defun arg)
1124 (defun python-end-of-defun-function ()
1125 "Move point to the end of def or class.
1126 Returns nil if point is not in a def or class."
1128 (let ((beg-defun-indent))
1129 (when (or (python-info-looking-at-beginning-of-defun)
1130 (python-beginning-of-defun-function 1)
1131 (python-beginning-of-defun-function -
1))
1132 (setq beg-defun-indent
(current-indentation))
1134 ;; Go as forward as possible
1136 (python-nav-beginning-of-defun -1)
1137 (and (goto-char (point-max)) nil
))
1138 (> (current-indentation) beg-defun-indent
)))
1139 (beginning-of-line 1)
1140 ;; Go as backwards as possible
1141 (while (and (forward-line -
1)
1143 (or (not (current-word))
1144 (equal (char-after (+ (point) (current-indentation))) ?
#)
1145 (<= (current-indentation) beg-defun-indent
)
1146 (looking-at (python-rx decorator
))
1147 (python-syntax-context-type))))
1149 ;; If point falls inside a paren or string context the point is
1150 ;; forwarded at the end of it (or end of buffer if its not closed)
1151 (let ((context-type (python-syntax-context-type)))
1152 (when (memq context-type
'(paren string
))
1154 (while (and (not (eobp))
1155 (python-syntax-context-type))
1156 (forward-line 1)))))))
1158 (defun python-nav-beginning-of-statement ()
1159 "Move to start of current statement."
1161 (while (and (or (back-to-indentation) t
)
1166 (python-info-line-ends-backslash-p))
1167 (python-syntax-context 'string
)
1168 (python-syntax-context 'paren
))
1169 (forward-line -
1))))
1172 (defun python-nav-end-of-statement ()
1173 "Move to end of current statement."
1175 (while (and (goto-char (line-end-position))
1178 (python-info-line-ends-backslash-p)
1179 (python-syntax-context 'string
)
1180 (python-syntax-context 'paren
))
1184 (defun python-nav-backward-statement (&optional arg
)
1185 "Move backward to previous statement.
1186 With ARG, repeat. See `python-nav-forward-statement'."
1188 (or arg
(setq arg
1))
1189 (python-nav-forward-statement (- arg
)))
1191 (defun python-nav-forward-statement (&optional arg
)
1192 "Move forward to next statement.
1193 With ARG, repeat. With negative argument, move ARG times
1194 backward to previous statement."
1196 (or arg
(setq arg
1))
1198 (python-nav-end-of-statement)
1199 (python-util-forward-comment)
1200 (python-nav-beginning-of-statement)
1201 (setq arg
(1- arg
)))
1203 (python-nav-beginning-of-statement)
1204 (python-util-forward-comment -
1)
1205 (python-nav-beginning-of-statement)
1206 (setq arg
(1+ arg
))))
1208 (defun python-nav-beginning-of-block ()
1209 "Move to start of current block."
1211 (let ((starting-pos (point))
1212 (block-regexp (python-rx
1213 line-start
(* whitespace
) block-start
)))
1215 (python-nav-beginning-of-statement)
1216 (looking-at (python-rx block-start
)))
1218 ;; Go to first line beginning a statement
1219 (while (and (not (bobp))
1220 (or (and (python-nav-beginning-of-statement) nil
)
1221 (python-info-current-line-comment-p)
1222 (python-info-current-line-empty-p)))
1224 (let ((block-matching-indent
1225 (- (current-indentation) python-indent-offset
)))
1227 (and (python-nav-backward-block)
1228 (> (current-indentation) block-matching-indent
)))
1229 (if (and (looking-at (python-rx block-start
))
1230 (= (current-indentation) block-matching-indent
))
1232 (and (goto-char starting-pos
) nil
))))))
1234 (defun python-nav-end-of-block ()
1235 "Move to end of current block."
1237 (when (python-nav-beginning-of-block)
1238 (let ((block-indentation (current-indentation)))
1239 (python-nav-end-of-statement)
1240 (while (and (forward-line 1)
1242 (or (and (> (current-indentation) block-indentation
)
1243 (or (python-nav-end-of-statement) t
))
1244 (python-info-current-line-comment-p)
1245 (python-info-current-line-empty-p))))
1246 (python-util-forward-comment -
1)
1249 (defun python-nav-backward-block (&optional arg
)
1250 "Move backward to previous block of code.
1251 With ARG, repeat. See `python-nav-forward-block'."
1253 (or arg
(setq arg
1))
1254 (python-nav-forward-block (- arg
)))
1256 (defun python-nav-forward-block (&optional arg
)
1257 "Move forward to next block of code.
1258 With ARG, repeat. With negative argument, move ARG times
1259 backward to previous block."
1261 (or arg
(setq arg
1))
1262 (let ((block-start-regexp
1263 (python-rx line-start
(* whitespace
) block-start
))
1264 (starting-pos (point)))
1266 (python-nav-end-of-statement)
1268 (re-search-forward block-start-regexp nil t
)
1269 (python-syntax-context-type)))
1270 (setq arg
(1- arg
)))
1272 (python-nav-beginning-of-statement)
1274 (re-search-backward block-start-regexp nil t
)
1275 (python-syntax-context-type)))
1276 (setq arg
(1+ arg
)))
1277 (python-nav-beginning-of-statement)
1278 (if (not (looking-at (python-rx block-start
)))
1279 (and (goto-char starting-pos
) nil
)
1280 (and (not (= (point) starting-pos
)) (point-marker)))))
1282 (defun python-nav-lisp-forward-sexp-safe (&optional arg
)
1283 "Safe version of standard `forward-sexp'.
1284 When ARG > 0 move forward, else if ARG is < 0."
1285 (or arg
(setq arg
1))
1286 (let ((forward-sexp-function nil
)
1288 (if (> arg
0) (python-rx close-paren
) (python-rx open-paren
)))
1290 (if (> arg
0) #'re-search-forward
#'re-search-backward
)))
1294 (while (and (funcall search-fn paren-regexp nil t
)
1295 (python-syntax-context 'paren
)))))))
1297 (defun python-nav--forward-sexp (&optional dir
)
1298 "Move to forward sexp.
1299 With positive Optional argument DIR direction move forward, else
1301 (setq dir
(or dir
1))
1303 (let* ((forward-p (if (> dir
0)
1304 (and (setq dir
1) t
)
1305 (and (setq dir -
1) nil
)))
1306 (re-search-fn (if forward-p
1308 're-search-backward
))
1309 (context-type (python-syntax-context-type)))
1311 ((eq context-type
'string
)
1312 ;; Inside of a string, get out of it.
1313 (while (and (funcall re-search-fn
"[\"']" nil t
)
1314 (python-syntax-context 'string
))))
1315 ((eq context-type
'comment
)
1316 ;; Inside of a comment, just move forward.
1317 (python-util-forward-comment dir
))
1318 ((or (eq context-type
'paren
)
1319 (and forward-p
(looking-at (python-rx open-paren
)))
1320 (and (not forward-p
)
1321 (eq (syntax-class (syntax-after (1- (point))))
1322 (car (string-to-syntax ")")))))
1323 ;; Inside a paren or looking at it, lisp knows what to do.
1324 (python-nav-lisp-forward-sexp-safe dir
))
1326 ;; This part handles the lispy feel of
1327 ;; `python-nav-forward-sexp'. Knowing everything about the
1328 ;; current context and the context of the next sexp tries to
1329 ;; follow the lisp sexp motion commands in a symmetric manner.
1332 ((python-info-beginning-of-block-p) 'block-start
)
1333 ((python-info-end-of-block-p) 'block-end
)
1334 ((python-info-beginning-of-statement-p) 'statement-start
)
1335 ((python-info-end-of-statement-p) 'statement-end
)))
1338 (python-nav-lisp-forward-sexp-safe dir
)
1342 (goto-char next-sexp-pos
)
1344 ((python-info-beginning-of-block-p) 'block-start
)
1345 ((python-info-end-of-block-p) 'block-end
)
1346 ((python-info-beginning-of-statement-p) 'statement-start
)
1347 ((python-info-end-of-statement-p) 'statement-end
)
1348 ((python-info-statement-starts-block-p) 'starts-block
)
1349 ((python-info-statement-ends-block-p) 'ends-block
)))))
1351 (cond ((and (not (eobp))
1352 (python-info-current-line-empty-p))
1353 (python-util-forward-comment dir
)
1354 (python-nav--forward-sexp dir
))
1355 ((eq context
'block-start
)
1356 (python-nav-end-of-block))
1357 ((eq context
'statement-start
)
1358 (python-nav-end-of-statement))
1359 ((and (memq context
'(statement-end block-end
))
1360 (eq next-sexp-context
'ends-block
))
1361 (goto-char next-sexp-pos
)
1362 (python-nav-end-of-block))
1363 ((and (memq context
'(statement-end block-end
))
1364 (eq next-sexp-context
'starts-block
))
1365 (goto-char next-sexp-pos
)
1366 (python-nav-end-of-block))
1367 ((memq context
'(statement-end block-end
))
1368 (goto-char next-sexp-pos
)
1369 (python-nav-end-of-statement))
1370 (t (goto-char next-sexp-pos
)))
1371 (cond ((and (not (bobp))
1372 (python-info-current-line-empty-p))
1373 (python-util-forward-comment dir
)
1374 (python-nav--forward-sexp dir
))
1375 ((eq context
'block-end
)
1376 (python-nav-beginning-of-block))
1377 ((eq context
'statement-end
)
1378 (python-nav-beginning-of-statement))
1379 ((and (memq context
'(statement-start block-start
))
1380 (eq next-sexp-context
'starts-block
))
1381 (goto-char next-sexp-pos
)
1382 (python-nav-beginning-of-block))
1383 ((and (memq context
'(statement-start block-start
))
1384 (eq next-sexp-context
'ends-block
))
1385 (goto-char next-sexp-pos
)
1386 (python-nav-beginning-of-block))
1387 ((memq context
'(statement-start block-start
))
1388 (goto-char next-sexp-pos
)
1389 (python-nav-beginning-of-statement))
1390 (t (goto-char next-sexp-pos
))))))))))
1392 (defun python-nav--backward-sexp ()
1393 "Move to backward sexp."
1394 (python-nav--forward-sexp -
1))
1396 (defun python-nav-forward-sexp (&optional arg
)
1397 "Move forward across one block of code.
1398 With ARG, do it that many times. Negative arg -N means
1399 move backward N times."
1401 (or arg
(setq arg
1))
1403 (python-nav--forward-sexp)
1404 (setq arg
(1- arg
)))
1406 (python-nav--backward-sexp)
1407 (setq arg
(1+ arg
))))
1409 (defun python-nav--up-list (&optional dir
)
1410 "Internal implementation of `python-nav-up-list'.
1411 DIR is always 1 or -1 and comes sanitized from
1412 `python-nav-up-list' calls."
1413 (let ((context (python-syntax-context-type))
1414 (forward-p (> dir
0)))
1416 ((memq context
'(string comment
)))
1417 ((eq context
'paren
)
1418 (let ((forward-sexp-function))
1420 ((and forward-p
(python-info-end-of-block-p))
1421 (let ((parent-end-pos
1423 (let ((indentation (and
1424 (python-nav-beginning-of-block)
1425 (current-indentation))))
1426 (while (and indentation
1428 (>= (current-indentation) indentation
)
1429 (python-nav-backward-block)))
1430 (python-nav-end-of-block)))))
1431 (and (> (or parent-end-pos
(point)) (point))
1432 (goto-char parent-end-pos
))))
1433 (forward-p (python-nav-end-of-block))
1434 ((and (not forward-p
)
1435 (> (current-indentation) 0)
1436 (python-info-beginning-of-block-p))
1437 (let ((prev-block-pos
1439 (let ((indentation (current-indentation)))
1440 (while (and (python-nav-backward-block)
1441 (>= (current-indentation) indentation
))))
1443 (and (> (point) prev-block-pos
)
1444 (goto-char prev-block-pos
))))
1445 ((not forward-p
) (python-nav-beginning-of-block)))))
1447 (defun python-nav-up-list (&optional arg
)
1448 "Move forward out of one level of parentheses (or blocks).
1449 With ARG, do this that many times.
1450 A negative argument means move backward but still to a less deep spot.
1451 This command assumes point is not in a string or comment."
1453 (or arg
(setq arg
1))
1455 (python-nav--up-list 1)
1456 (setq arg
(1- arg
)))
1458 (python-nav--up-list -
1)
1459 (setq arg
(1+ arg
))))
1461 (defun python-nav-backward-up-list (&optional arg
)
1462 "Move backward out of one level of parentheses (or blocks).
1463 With ARG, do this that many times.
1464 A negative argument means move backward but still to a less deep spot.
1465 This command assumes point is not in a string or comment."
1467 (or arg
(setq arg
1))
1468 (python-nav-up-list (- arg
)))
1471 ;;; Shell integration
1473 (defcustom python-shell-buffer-name
"Python"
1474 "Default buffer name for Python interpreter."
1479 (defcustom python-shell-interpreter
"python"
1480 "Default Python interpreter for shell."
1484 (defcustom python-shell-internal-buffer-name
"Python Internal"
1485 "Default buffer name for the Internal Python interpreter."
1490 (defcustom python-shell-interpreter-args
"-i"
1491 "Default arguments for the Python interpreter."
1495 (defcustom python-shell-prompt-regexp
">>> "
1496 "Regular Expression matching top\-level input prompt of python shell.
1497 It should not contain a caret (^) at the beginning."
1502 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1503 "Regular Expression matching block input prompt of python shell.
1504 It should not contain a caret (^) at the beginning."
1509 (defcustom python-shell-prompt-output-regexp
""
1510 "Regular Expression matching output prompt of python shell.
1511 It should not contain a caret (^) at the beginning."
1516 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1517 "Regular Expression matching pdb input prompt of python shell.
1518 It should not contain a caret (^) at the beginning."
1523 (defcustom python-shell-enable-font-lock t
1524 "Should syntax highlighting be enabled in the python shell buffer?
1525 Restart the python shell after changing this variable for it to take effect."
1530 (defcustom python-shell-process-environment nil
1531 "List of environment variables for Python shell.
1532 This variable follows the same rules as `process-environment'
1533 since it merges with it before the process creation routines are
1534 called. When this variable is nil, the Python shell is run with
1535 the default `process-environment'."
1536 :type
'(repeat string
)
1540 (defcustom python-shell-extra-pythonpaths nil
1541 "List of extra pythonpaths for Python shell.
1542 The values of this variable are added to the existing value of
1543 PYTHONPATH in the `process-environment' variable."
1544 :type
'(repeat string
)
1548 (defcustom python-shell-exec-path nil
1549 "List of path to search for binaries.
1550 This variable follows the same rules as `exec-path' since it
1551 merges with it before the process creation routines are called.
1552 When this variable is nil, the Python shell is run with the
1553 default `exec-path'."
1554 :type
'(repeat string
)
1558 (defcustom python-shell-virtualenv-path nil
1559 "Path to virtualenv root.
1560 This variable, when set to a string, makes the values stored in
1561 `python-shell-process-environment' and `python-shell-exec-path'
1562 to be modified properly so shells are started with the specified
1568 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1569 python-ffap-setup-code
1570 python-eldoc-setup-code
)
1571 "List of code run by `python-shell-send-setup-codes'."
1572 :type
'(repeat symbol
)
1576 (defcustom python-shell-compilation-regexp-alist
1577 `((,(rx line-start
(1+ (any " \t")) "File \""
1578 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1579 "\", line " (group (1+ digit
)))
1581 (,(rx " in file " (group (1+ not-newline
)) " on line "
1584 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1585 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1587 "`compilation-error-regexp-alist' for inferior Python."
1588 :type
'(alist string
)
1591 (defun python-shell-get-process-name (dedicated)
1592 "Calculate the appropriate process name for inferior Python process.
1593 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1594 returns a string with the form
1595 `python-shell-buffer-name'[variable `buffer-file-name'] else
1596 returns the value of `python-shell-buffer-name'."
1600 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1601 (format "%s" python-shell-buffer-name
))))
1604 (defun python-shell-internal-get-process-name ()
1605 "Calculate the appropriate process name for Internal Python process.
1606 The name is calculated from `python-shell-global-buffer-name' and
1607 a hash of all relevant global shell settings in order to ensure
1608 uniqueness for different types of configurations."
1610 python-shell-internal-buffer-name
1613 (python-shell-parse-command)
1614 python-shell-prompt-regexp
1615 python-shell-prompt-block-regexp
1616 python-shell-prompt-output-regexp
1617 (mapconcat #'symbol-value python-shell-setup-codes
"")
1618 (mapconcat #'identity python-shell-process-environment
"")
1619 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1620 (mapconcat #'identity python-shell-exec-path
"")
1621 (or python-shell-virtualenv-path
"")
1622 (mapconcat #'identity python-shell-exec-path
"")))))
1624 (defun python-shell-parse-command ()
1625 "Calculate the string used to execute the inferior Python process."
1626 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1628 (defun python-shell-calculate-process-environment ()
1629 "Calculate process environment given `python-shell-virtualenv-path'."
1630 (let ((process-environment (append
1631 python-shell-process-environment
1632 process-environment nil
))
1633 (virtualenv (if python-shell-virtualenv-path
1634 (directory-file-name python-shell-virtualenv-path
)
1636 (when python-shell-extra-pythonpaths
1637 (setenv "PYTHONPATH"
1639 (mapconcat 'identity
1640 python-shell-extra-pythonpaths
1643 (or (getenv "PYTHONPATH") ""))))
1644 (if (not virtualenv
)
1646 (setenv "PYTHONHOME" nil
)
1647 (setenv "PATH" (format "%s/bin%s%s"
1648 virtualenv path-separator
1649 (or (getenv "PATH") "")))
1650 (setenv "VIRTUAL_ENV" virtualenv
))
1651 process-environment
))
1653 (defun python-shell-calculate-exec-path ()
1654 "Calculate exec path given `python-shell-virtualenv-path'."
1655 (let ((path (append python-shell-exec-path
1657 (if (not python-shell-virtualenv-path
)
1659 (cons (format "%s/bin"
1660 (directory-file-name python-shell-virtualenv-path
))
1663 (defun python-comint-output-filter-function (output)
1664 "Hook run after content is put into comint buffer.
1665 OUTPUT is a string with the contents of the buffer."
1666 (ansi-color-filter-apply output
))
1668 (defvar python-shell--parent-buffer nil
)
1670 (defvar python-shell-output-syntax-table
1671 (let ((table (make-syntax-table python-dotty-syntax-table
)))
1672 (modify-syntax-entry ?
\' "." table
)
1673 (modify-syntax-entry ?
\" "." table
)
1674 (modify-syntax-entry ?\
( "." table
)
1675 (modify-syntax-entry ?\
[ "." table
)
1676 (modify-syntax-entry ?\
{ "." table
)
1677 (modify-syntax-entry ?\
) "." table
)
1678 (modify-syntax-entry ?\
] "." table
)
1679 (modify-syntax-entry ?\
} "." table
)
1681 "Syntax table for shell output.
1682 It makes parens and quotes be treated as punctuation chars.")
1684 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1685 "Major mode for Python inferior process.
1686 Runs a Python interpreter as a subprocess of Emacs, with Python
1687 I/O through an Emacs buffer. Variables
1688 `python-shell-interpreter' and `python-shell-interpreter-args'
1689 controls which Python interpreter is run. Variables
1690 `python-shell-prompt-regexp',
1691 `python-shell-prompt-output-regexp',
1692 `python-shell-prompt-block-regexp',
1693 `python-shell-enable-font-lock',
1694 `python-shell-completion-setup-code',
1695 `python-shell-completion-string-code',
1696 `python-shell-completion-module-string-code',
1697 `python-eldoc-setup-code', `python-eldoc-string-code',
1698 `python-ffap-setup-code' and `python-ffap-string-code' can
1699 customize this mode for different Python interpreters.
1701 You can also add additional setup code to be run at
1702 initialization of the interpreter via `python-shell-setup-codes'
1705 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1706 (and python-shell--parent-buffer
1707 (python-util-clone-local-variables python-shell--parent-buffer
))
1708 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1709 python-shell-prompt-regexp
1710 python-shell-prompt-block-regexp
1711 python-shell-prompt-pdb-regexp
))
1712 (setq mode-line-process
'(":%s"))
1713 (make-local-variable 'comint-output-filter-functions
)
1714 (add-hook 'comint-output-filter-functions
1715 'python-comint-output-filter-function
)
1716 (add-hook 'comint-output-filter-functions
1717 'python-pdbtrack-comint-output-filter-function
)
1718 (set (make-local-variable 'compilation-error-regexp-alist
)
1719 python-shell-compilation-regexp-alist
)
1720 (define-key inferior-python-mode-map
[remap complete-symbol
]
1721 'completion-at-point
)
1722 (add-hook 'completion-at-point-functions
1723 'python-shell-completion-complete-at-point nil
'local
)
1724 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1725 'python-shell-completion-complete-at-point
)
1726 (define-key inferior-python-mode-map
"\t"
1727 'python-shell-completion-complete-or-indent
)
1728 (make-local-variable 'python-pdbtrack-buffers-to-kill
)
1729 (make-local-variable 'python-pdbtrack-tracked-buffer
)
1730 (make-local-variable 'python-shell-internal-last-output
)
1731 (when python-shell-enable-font-lock
1732 (set-syntax-table python-mode-syntax-table
)
1733 (set (make-local-variable 'font-lock-defaults
)
1734 '(python-font-lock-keywords nil nil nil nil
))
1735 (set (make-local-variable 'syntax-propertize-function
)
1736 (syntax-propertize-rules
1737 (comint-prompt-regexp
1740 comint-last-input-start end
'syntax-table
1741 python-shell-output-syntax-table
)
1742 (font-lock-unfontify-region comint-last-input-start end
))))
1743 ((python-rx string-delimiter
)
1745 (and (not (eq (get-text-property start
'field
) 'output
))
1746 (python-syntax-stringify))))))))
1747 (compilation-shell-minor-mode 1))
1749 (defun python-shell-make-comint (cmd proc-name
&optional pop internal
)
1750 "Create a python shell comint buffer.
1751 CMD is the python command to be executed and PROC-NAME is the
1752 process name the comint buffer will get. After the comint buffer
1753 is created the `inferior-python-mode' is activated. When
1754 optional argument POP is non-nil the buffer is shown. When
1755 optional argument INTERNAL is non-nil this process is run on a
1756 buffer with a name that starts with a space, following the Emacs
1757 convention for temporary/internal buffers, and also makes sure
1758 the user is not queried for confirmation when the process is
1761 (let* ((proc-buffer-name
1762 (format (if (not internal
) "*%s*" " *%s*") proc-name
))
1763 (process-environment (python-shell-calculate-process-environment))
1764 (exec-path (python-shell-calculate-exec-path)))
1765 (when (not (comint-check-proc proc-buffer-name
))
1766 (let* ((cmdlist (split-string-and-unquote cmd
))
1767 (buffer (apply #'make-comint-in-buffer proc-name proc-buffer-name
1768 (car cmdlist
) nil
(cdr cmdlist
)))
1769 (python-shell--parent-buffer (current-buffer))
1770 (process (get-buffer-process buffer
)))
1771 (with-current-buffer buffer
1772 (inferior-python-mode))
1773 (accept-process-output process
)
1774 (and pop
(pop-to-buffer buffer t
))
1775 (and internal
(set-process-query-on-exit-flag process nil
))))
1779 (defun run-python (cmd &optional dedicated show
)
1780 "Run an inferior Python process.
1781 Input and output via buffer named after
1782 `python-shell-buffer-name'. If there is a process already
1783 running in that buffer, just switch to it.
1785 With argument, allows you to define CMD so you can edit the
1786 command used to call the interpreter and define DEDICATED, so a
1787 dedicated process for the current buffer is open. When numeric
1788 prefix arg is other than 0 or 4 do not SHOW.
1790 Runs the hook `inferior-python-mode-hook' (after the
1791 `comint-mode-hook' is run). \(Type \\[describe-mode] in the
1792 process buffer for a list of commands.)"
1794 (if current-prefix-arg
1796 (read-string "Run Python: " (python-shell-parse-command))
1797 (y-or-n-p "Make dedicated process? ")
1798 (= (prefix-numeric-value current-prefix-arg
) 4))
1799 (list (python-shell-parse-command) nil t
)))
1800 (python-shell-make-comint
1801 cmd
(python-shell-get-process-name dedicated
) show
)
1804 (defun run-python-internal ()
1805 "Run an inferior Internal Python process.
1806 Input and output via buffer named after
1807 `python-shell-internal-buffer-name' and what
1808 `python-shell-internal-get-process-name' returns.
1810 This new kind of shell is intended to be used for generic
1811 communication related to defined configurations, the main
1812 difference with global or dedicated shells is that these ones are
1813 attached to a configuration, not a buffer. This means that can
1814 be used for example to retrieve the sys.path and other stuff,
1815 without messing with user shells. Note that
1816 `python-shell-enable-font-lock' and `inferior-python-mode-hook'
1817 are set to nil for these shells, so setup codes are not sent at
1819 (let ((python-shell-enable-font-lock nil
)
1820 (inferior-python-mode-hook nil
))
1822 (python-shell-make-comint
1823 (python-shell-parse-command)
1824 (python-shell-internal-get-process-name) nil t
))))
1826 (defun python-shell-get-process ()
1827 "Get inferior Python process for current buffer and return it."
1828 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1829 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1830 (global-proc-name (python-shell-get-process-name nil
))
1831 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1832 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1833 (global-running (comint-check-proc global-proc-buffer-name
)))
1834 ;; Always prefer dedicated
1835 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1836 (and global-running global-proc-buffer-name
)))))
1838 (defun python-shell-get-or-create-process ()
1839 "Get or create an inferior Python process for current buffer and return it."
1840 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1841 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1842 (global-proc-name (python-shell-get-process-name nil
))
1843 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1844 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1845 (global-running (comint-check-proc global-proc-buffer-name
))
1846 (current-prefix-arg 16))
1847 (when (and (not dedicated-running
) (not global-running
))
1848 (if (call-interactively 'run-python
)
1849 (setq dedicated-running t
)
1850 (setq global-running t
)))
1851 ;; Always prefer dedicated
1852 (get-buffer-process (if dedicated-running
1853 dedicated-proc-buffer-name
1854 global-proc-buffer-name
))))
1856 (defvar python-shell-internal-buffer nil
1857 "Current internal shell buffer for the current buffer.
1858 This is really not necessary at all for the code to work but it's
1859 there for compatibility with CEDET.")
1861 (defvar python-shell-internal-last-output nil
1862 "Last output captured by the internal shell.
1863 This is really not necessary at all for the code to work but it's
1864 there for compatibility with CEDET.")
1866 (defun python-shell-internal-get-or-create-process ()
1867 "Get or create an inferior Internal Python process."
1868 (let* ((proc-name (python-shell-internal-get-process-name))
1869 (proc-buffer-name (format " *%s*" proc-name
)))
1870 (when (not (process-live-p proc-name
))
1871 (run-python-internal)
1872 (setq python-shell-internal-buffer proc-buffer-name
)
1873 ;; XXX: Why is this `sit-for' needed?
1874 ;; `python-shell-make-comint' calls `accept-process-output'
1875 ;; already but it is not helping to get proper output on
1876 ;; 'gnu/linux when the internal shell process is not running and
1877 ;; a call to `python-shell-internal-send-string' is issued.
1879 (get-buffer-process proc-buffer-name
)))
1881 (define-obsolete-function-alias
1882 'python-proc
'python-shell-internal-get-or-create-process
"24.3")
1884 (define-obsolete-variable-alias
1885 'python-buffer
'python-shell-internal-buffer
"24.3")
1887 (define-obsolete-variable-alias
1888 'python-preoutput-result
'python-shell-internal-last-output
"24.3")
1890 (defun python-shell-send-string (string &optional process msg
)
1891 "Send STRING to inferior Python PROCESS.
1892 When MSG is non-nil messages the first line of STRING."
1893 (interactive "sPython command: ")
1894 (let ((process (or process
(python-shell-get-or-create-process)))
1895 (lines (split-string string
"\n" t
)))
1896 (and msg
(message "Sent: %s..." (nth 0 lines
)))
1897 (if (> (length lines
) 1)
1898 (let* ((temporary-file-directory
1899 (if (file-remote-p default-directory
)
1900 (concat (file-remote-p default-directory
) "/tmp")
1901 temporary-file-directory
))
1902 (temp-file-name (make-temp-file "py"))
1903 (file-name (or (buffer-file-name) temp-file-name
)))
1904 (with-temp-file temp-file-name
1906 (delete-trailing-whitespace))
1907 (python-shell-send-file file-name process temp-file-name
))
1908 (comint-send-string process string
)
1909 (when (or (not (string-match "\n$" string
))
1910 (string-match "\n[ \t].*\n?$" string
))
1911 (comint-send-string process
"\n")))))
1913 (defvar python-shell-output-filter-in-progress nil
)
1914 (defvar python-shell-output-filter-buffer nil
)
1916 (defun python-shell-output-filter (string)
1917 "Filter used in `python-shell-send-string-no-output' to grab output.
1918 STRING is the output received to this point from the process.
1919 This filter saves received output from the process in
1920 `python-shell-output-filter-buffer' and stops receiving it after
1921 detecting a prompt at the end of the buffer."
1923 string
(ansi-color-filter-apply string
)
1924 python-shell-output-filter-buffer
1925 (concat python-shell-output-filter-buffer string
))
1927 ;; XXX: It seems on OSX an extra carriage return is attached
1928 ;; at the end of output, this handles that too.
1929 (format "\r?\n\\(?:%s\\|%s\\|%s\\)$"
1930 python-shell-prompt-regexp
1931 python-shell-prompt-block-regexp
1932 python-shell-prompt-pdb-regexp
)
1933 python-shell-output-filter-buffer
)
1934 ;; Output ends when `python-shell-output-filter-buffer' contains
1935 ;; the prompt attached at the end of it.
1936 (setq python-shell-output-filter-in-progress nil
1937 python-shell-output-filter-buffer
1938 (substring python-shell-output-filter-buffer
1939 0 (match-beginning 0)))
1940 (when (and (> (length python-shell-prompt-output-regexp
) 0)
1941 (string-match (concat "^" python-shell-prompt-output-regexp
)
1942 python-shell-output-filter-buffer
))
1943 ;; Some shells, like iPython might append a prompt before the
1944 ;; output, clean that.
1945 (setq python-shell-output-filter-buffer
1946 (substring python-shell-output-filter-buffer
(match-end 0)))))
1949 (defun python-shell-send-string-no-output (string &optional process msg
)
1950 "Send STRING to PROCESS and inhibit output.
1951 When MSG is non-nil messages the first line of STRING. Return
1953 (let ((process (or process
(python-shell-get-or-create-process)))
1954 (comint-preoutput-filter-functions
1955 '(python-shell-output-filter))
1956 (python-shell-output-filter-in-progress t
)
1960 (python-shell-send-string string process msg
)
1961 (while python-shell-output-filter-in-progress
1962 ;; `python-shell-output-filter' takes care of setting
1963 ;; `python-shell-output-filter-in-progress' to NIL after it
1964 ;; detects end of output.
1965 (accept-process-output process
))
1967 python-shell-output-filter-buffer
1968 (setq python-shell-output-filter-buffer nil
)))
1969 (with-current-buffer (process-buffer process
)
1970 (comint-interrupt-subjob)))))
1972 (defun python-shell-internal-send-string (string)
1973 "Send STRING to the Internal Python interpreter.
1974 Returns the output. See `python-shell-send-string-no-output'."
1975 ;; XXX Remove `python-shell-internal-last-output' once CEDET is
1976 ;; updated to support this new mode.
1977 (setq python-shell-internal-last-output
1978 (python-shell-send-string-no-output
1979 ;; Makes this function compatible with the old
1980 ;; python-send-receive. (At least for CEDET).
1981 (replace-regexp-in-string "_emacs_out +" "" string
)
1982 (python-shell-internal-get-or-create-process) nil
)))
1984 (define-obsolete-function-alias
1985 'python-send-receive
'python-shell-internal-send-string
"24.3")
1987 (define-obsolete-function-alias
1988 'python-send-string
'python-shell-internal-send-string
"24.3")
1990 (defun python-shell-send-region (start end
)
1991 "Send the region delimited by START and END to inferior Python process."
1993 (python-shell-send-string (buffer-substring start end
) nil t
))
1995 (defun python-shell-send-buffer (&optional arg
)
1996 "Send the entire buffer to inferior Python process.
1997 With prefix ARG allow execution of code inside blocks delimited
1998 by \"if __name__== '__main__':\""
2002 (let ((str (buffer-substring (point-min) (point-max))))
2005 (setq str
(replace-regexp-in-string
2006 (python-rx if-name-main
)
2007 "if __name__ == '__main__ ':" str
)))
2008 (python-shell-send-string str
))))
2010 (defun python-shell-send-defun (arg)
2011 "Send the current defun to inferior Python process.
2012 When argument ARG is non-nil do not include decorators."
2015 (python-shell-send-region
2018 (while (and (or (python-beginning-of-defun-function)
2019 (beginning-of-line 1))
2020 (> (current-indentation) 0)))
2022 (while (and (forward-line -
1)
2023 (looking-at (python-rx decorator
))))
2027 (or (python-end-of-defun-function)
2031 (defun python-shell-send-file (file-name &optional process temp-file-name
)
2032 "Send FILE-NAME to inferior Python PROCESS.
2033 If TEMP-FILE-NAME is passed then that file is used for processing
2034 instead, while internally the shell will continue to use
2036 (interactive "fFile to send: ")
2037 (let* ((process (or process
(python-shell-get-or-create-process)))
2038 (temp-file-name (when temp-file-name
2040 (or (file-remote-p temp-file-name
'localname
)
2042 (file-name (or (when file-name
2044 (or (file-remote-p file-name
'localname
)
2047 (when (not file-name
)
2048 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
2049 (python-shell-send-string
2051 (concat "__pyfile = open('''%s''');"
2052 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
2054 (or temp-file-name file-name
) file-name
)
2057 (defun python-shell-switch-to-shell ()
2058 "Switch to inferior Python process buffer."
2060 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
2062 (defun python-shell-send-setup-code ()
2063 "Send all setup code for shell.
2064 This function takes the list of setup code to send from the
2065 `python-shell-setup-codes' list."
2066 (let ((process (get-buffer-process (current-buffer))))
2067 (dolist (code python-shell-setup-codes
)
2069 (message "Sent %s" code
)
2070 (python-shell-send-string
2071 (symbol-value code
) process
)))))
2073 (add-hook 'inferior-python-mode-hook
2074 #'python-shell-send-setup-code
)
2077 ;;; Shell completion
2079 (defcustom python-shell-completion-setup-code
2083 def __COMPLETER_all_completions(text): []
2086 readline.set_completer(rlcompleter.Completer().complete)
2087 def __COMPLETER_all_completions(text):
2093 res = readline.get_completer()(text, i)
2096 completions.append(res)
2100 "Code used to setup completion in inferior Python processes."
2104 (defcustom python-shell-completion-string-code
2105 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
2106 "Python code used to get a string of completions separated by semicolons."
2110 (defcustom python-shell-completion-module-string-code
""
2111 "Python code used to get completions separated by semicolons for imports.
2113 For IPython v0.11, add the following line to
2114 `python-shell-completion-setup-code':
2116 from IPython.core.completerlib import module_completion
2118 and use the following as the value of this variable:
2120 ';'.join(module_completion('''%s'''))\n"
2124 (defcustom python-shell-completion-pdb-string-code
2125 "';'.join(globals().keys() + locals().keys())"
2126 "Python code used to get completions separated by semicolons for [i]pdb."
2130 (defun python-shell-completion-get-completions (process line input
)
2131 "Do completion at point for PROCESS.
2132 LINE is used to detect the context on how to complete given
2135 ;; Get the last prompt for the inferior process
2136 ;; buffer. This is used for the completion code selection
2138 (with-current-buffer (process-buffer process
)
2139 (buffer-substring-no-properties
2140 (overlay-start comint-last-prompt-overlay
)
2141 (overlay-end comint-last-prompt-overlay
))))
2143 ;; Check whether a prompt matches a pdb string, an import
2144 ;; statement or just the standard prompt and use the
2145 ;; correct python-shell-completion-*-code string
2146 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
2148 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
2151 (length python-shell-completion-module-string-code
) 0)
2153 (concat "^" python-shell-prompt-regexp
) prompt
)
2154 (string-match "^[ \t]*\\(from\\|import\\)[ \t]" line
))
2157 (concat "^" python-shell-prompt-regexp
) prompt
)
2161 (case completion-context
2162 (pdb python-shell-completion-pdb-string-code
)
2163 (import python-shell-completion-module-string-code
)
2164 (default python-shell-completion-string-code
)
2167 (if (eq completion-context
'import
)
2168 (replace-regexp-in-string "^[ \t]+" "" line
)
2170 (and completion-code
2171 (> (length input
) 0)
2172 (with-current-buffer (process-buffer process
)
2173 (let ((completions (python-shell-send-string-no-output
2174 (format completion-code input
) process
)))
2175 (and (> (length completions
) 2)
2176 (split-string completions
2177 "^'\\|^\"\\|;\\|'$\\|\"$" t
)))))))
2179 (defun python-shell-completion-complete-at-point (&optional process
)
2180 "Perform completion at point in inferior Python.
2181 Optional argument PROCESS forces completions to be retrieved
2182 using that one instead of current buffer's process."
2183 (setq process
(or process
(get-buffer-process (current-buffer))))
2186 (with-syntax-table python-dotty-syntax-table
2187 (let* ((paren-depth (car (syntax-ppss)))
2188 (syntax-string "w_")
2189 (syntax-list (string-to-syntax syntax-string
)))
2190 ;; Stop scanning for the beginning of the completion
2191 ;; subject after the char before point matches a
2194 (car (syntax-after (1- (point)))) syntax-list
)
2195 (skip-syntax-backward syntax-string
)
2196 (when (or (equal (char-before) ?\
))
2197 (equal (char-before) ?
\"))
2200 ;; honor initial paren depth
2201 (> (car (syntax-ppss)) paren-depth
)
2202 (python-syntax-context 'string
))
2207 (completion-table-dynamic
2209 #'python-shell-completion-get-completions
2210 process
(buffer-substring-no-properties
2211 (line-beginning-position) end
))))))
2213 (defun python-shell-completion-complete-or-indent ()
2214 "Complete or indent depending on the context.
2215 If content before pointer is all whitespace indent. If not try
2218 (if (string-match "^[[:space:]]*$"
2219 (buffer-substring (comint-line-beginning-position)
2221 (indent-for-tab-command)
2222 (completion-at-point)))
2225 ;;; PDB Track integration
2227 (defcustom python-pdbtrack-activate t
2228 "Non-nil makes python shell enable pdbtracking."
2233 (defcustom python-pdbtrack-stacktrace-info-regexp
2234 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
2235 "Regular Expression matching stacktrace information.
2236 Used to extract the current line and module being inspected."
2241 (defvar python-pdbtrack-tracked-buffer nil
2242 "Variable containing the value of the current tracked buffer.
2243 Never set this variable directly, use
2244 `python-pdbtrack-set-tracked-buffer' instead.")
2246 (defvar python-pdbtrack-buffers-to-kill nil
2247 "List of buffers to be deleted after tracking finishes.")
2249 (defun python-pdbtrack-set-tracked-buffer (file-name)
2250 "Set the buffer for FILE-NAME as the tracked buffer.
2251 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
2252 Returns the tracked buffer."
2253 (let ((file-buffer (get-file-buffer file-name
)))
2255 (setq python-pdbtrack-tracked-buffer file-buffer
)
2256 (setq file-buffer
(find-file-noselect file-name
))
2257 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
2258 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
2261 (defun python-pdbtrack-comint-output-filter-function (output)
2262 "Move overlay arrow to current pdb line in tracked buffer.
2263 Argument OUTPUT is a string with the output from the comint process."
2264 (when (and python-pdbtrack-activate
(not (string= output
"")))
2265 (let* ((full-output (ansi-color-filter-apply
2266 (buffer-substring comint-last-input-end
(point-max))))
2270 (insert full-output
)
2271 (goto-char (point-min))
2272 ;; OK, this sucked but now it became a cool hack. The
2273 ;; stacktrace information normally is on the first line
2274 ;; but in some cases (like when doing a step-in) it is
2276 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
2279 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
2280 (setq line-number
(string-to-number
2281 (match-string-no-properties 2)))
2282 (match-string-no-properties 1)))))
2283 (if (and file-name line-number
)
2284 (let* ((tracked-buffer
2285 (python-pdbtrack-set-tracked-buffer file-name
))
2286 (shell-buffer (current-buffer))
2287 (tracked-buffer-window (get-buffer-window tracked-buffer
))
2288 (tracked-buffer-line-pos))
2289 (with-current-buffer tracked-buffer
2290 (set (make-local-variable 'overlay-arrow-string
) "=>")
2291 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
2292 (setq tracked-buffer-line-pos
(progn
2293 (goto-char (point-min))
2294 (forward-line (1- line-number
))
2296 (when tracked-buffer-window
2298 tracked-buffer-window tracked-buffer-line-pos
))
2299 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
2300 (pop-to-buffer tracked-buffer
)
2301 (switch-to-buffer-other-window shell-buffer
))
2302 (when python-pdbtrack-tracked-buffer
2303 (with-current-buffer python-pdbtrack-tracked-buffer
2304 (set-marker overlay-arrow-position nil
))
2305 (mapc #'(lambda (buffer)
2306 (ignore-errors (kill-buffer buffer
)))
2307 python-pdbtrack-buffers-to-kill
)
2308 (setq python-pdbtrack-tracked-buffer nil
2309 python-pdbtrack-buffers-to-kill nil
)))))
2313 ;;; Symbol completion
2315 (defun python-completion-complete-at-point ()
2316 "Complete current symbol at point.
2317 For this to work the best as possible you should call
2318 `python-shell-send-buffer' from time to time so context in
2319 inferior python process is updated properly."
2320 (let ((process (python-shell-get-process)))
2322 (error "Completion needs an inferior Python process running")
2323 (python-shell-completion-complete-at-point process
))))
2325 (add-to-list 'debug-ignored-errors
2326 "^Completion needs an inferior Python process running.")
2331 (defcustom python-fill-comment-function
'python-fill-comment
2332 "Function to fill comments.
2333 This is the function used by `python-fill-paragraph' to
2338 (defcustom python-fill-string-function
'python-fill-string
2339 "Function to fill strings.
2340 This is the function used by `python-fill-paragraph' to
2345 (defcustom python-fill-decorator-function
'python-fill-decorator
2346 "Function to fill decorators.
2347 This is the function used by `python-fill-paragraph' to
2352 (defcustom python-fill-paren-function
'python-fill-paren
2353 "Function to fill parens.
2354 This is the function used by `python-fill-paragraph' to
2359 (defcustom python-fill-docstring-style
'pep-257
2360 "Style used to fill docstrings.
2361 This affects `python-fill-string' behavior with regards to
2362 triple quotes positioning.
2364 Possible values are DJANGO, ONETWO, PEP-257, PEP-257-NN,
2365 SYMMETRIC, and NIL. A value of NIL won't care about quotes
2366 position and will treat docstrings a normal string, any other
2367 value may result in one of the following docstring styles:
2372 Process foo, return bar.
2376 Process foo, return bar.
2378 If processing fails throw ProcessingError.
2383 \"\"\"Process foo, return bar.\"\"\"
2386 Process foo, return bar.
2388 If processing fails throw ProcessingError.
2394 \"\"\"Process foo, return bar.\"\"\"
2396 \"\"\"Process foo, return bar.
2398 If processing fails throw ProcessingError.
2404 \"\"\"Process foo, return bar.\"\"\"
2406 \"\"\"Process foo, return bar.
2408 If processing fails throw ProcessingError.
2413 \"\"\"Process foo, return bar.\"\"\"
2416 Process foo, return bar.
2418 If processing fails throw ProcessingError.
2421 (const :tag
"Don't format docstrings" nil
)
2422 (const :tag
"Django's coding standards style." django
)
2423 (const :tag
"One newline and start and Two at end style." onetwo
)
2424 (const :tag
"PEP-257 with 2 newlines at end of string." pep-257
)
2425 (const :tag
"PEP-257 with 1 newline at end of string." pep-257-nn
)
2426 (const :tag
"Symmetric style." symmetric
))
2429 (memq val
'(django onetwo pep-257 pep-257-nn symmetric nil
))))
2431 (defun python-fill-paragraph (&optional justify
)
2432 "`fill-paragraph-function' handling multi-line strings and possibly comments.
2433 If any of the current line is in or at the end of a multi-line string,
2434 fill the string or the paragraph of it that point is in, preserving
2435 the string's indentation.
2436 Optional argument JUSTIFY defines if the paragraph should be justified."
2441 ((python-syntax-context 'comment
)
2442 (funcall python-fill-comment-function justify
))
2443 ;; Strings/Docstrings
2444 ((save-excursion (or (python-syntax-context 'string
)
2445 (equal (string-to-syntax "|")
2446 (syntax-after (point)))))
2447 (funcall python-fill-string-function justify
))
2449 ((equal (char-after (save-excursion
2450 (python-nav-beginning-of-statement))) ?
@)
2451 (funcall python-fill-decorator-function justify
))
2453 ((or (python-syntax-context 'paren
)
2454 (looking-at (python-rx open-paren
))
2456 (skip-syntax-forward "^(" (line-end-position))
2457 (looking-at (python-rx open-paren
))))
2458 (funcall python-fill-paren-function justify
))
2461 (defun python-fill-comment (&optional justify
)
2462 "Comment fill function for `python-fill-paragraph'.
2463 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2464 (fill-comment-paragraph justify
))
2466 (defun python-fill-string (&optional justify
)
2467 "String fill function for `python-fill-paragraph'.
2468 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2469 (let* ((marker (point-marker))
2471 (let ((m (make-marker)))
2472 (setf (marker-position m
)
2473 (or (python-syntax-context 'string
)
2474 (and (equal (string-to-syntax "|")
2475 (syntax-after (point)))
2477 (num-quotes (python-syntax-count-quotes
2478 (char-after str-start-pos
) str-start-pos
))
2481 (goto-char (+ str-start-pos num-quotes
))
2482 (or (re-search-forward (rx (syntax string-delimiter
)) nil t
)
2483 (goto-char (point-max)))
2486 ;; Docstring styles may vary for oneliners and multi-liners.
2487 (> (count-matches "\n" str-start-pos str-end-pos
) 0))
2489 (case python-fill-docstring-style
2490 ;; delimiters-style is a cons cell with the form
2491 ;; (START-NEWLINES . END-NEWLINES). When any of the sexps
2492 ;; is NIL means to not add any newlines for start or end
2493 ;; of docstring. See `python-fill-docstring-style' for a
2494 ;; graphic idea of each style.
2496 (onetwo (and multi-line-p
(cons 1 2)))
2497 (pep-257 (and multi-line-p
(cons nil
2)))
2498 (pep-257-nn (and multi-line-p
(cons nil
1)))
2499 (symmetric (and multi-line-p
(cons 1 1)))))
2500 (docstring-p (save-excursion
2501 ;; Consider docstrings those strings which
2502 ;; start on a line by themselves.
2503 (python-nav-beginning-of-statement)
2504 (and (= (point) str-start-pos
))))
2505 (fill-paragraph-function))
2507 (narrow-to-region str-start-pos str-end-pos
)
2508 (fill-paragraph justify
))
2510 (when (and docstring-p python-fill-docstring-style
)
2511 ;; Add the number of newlines indicated by the selected style
2512 ;; at the start of the docstring.
2513 (goto-char (+ str-start-pos num-quotes
))
2514 (delete-region (point) (progn
2515 (skip-syntax-forward "> ")
2517 (and (car delimiters-style
)
2518 (or (newline (car delimiters-style
)) t
)
2519 ;; Indent only if a newline is added.
2520 (indent-according-to-mode))
2521 ;; Add the number of newlines indicated by the selected style
2522 ;; at the end of the docstring.
2523 (goto-char (if (not (= str-end-pos
(point-max)))
2524 (- str-end-pos num-quotes
)
2526 (delete-region (point) (progn
2527 (skip-syntax-backward "> ")
2529 (and (cdr delimiters-style
)
2530 ;; Add newlines only if string ends.
2531 (not (= str-end-pos
(point-max)))
2532 (or (newline (cdr delimiters-style
)) t
)
2533 ;; Again indent only if a newline is added.
2534 (indent-according-to-mode))))) t
)
2536 (defun python-fill-decorator (&optional justify
)
2537 "Decorator fill function for `python-fill-paragraph'.
2538 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2541 (defun python-fill-paren (&optional justify
)
2542 "Paren fill function for `python-fill-paragraph'.
2543 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
2545 (narrow-to-region (progn
2546 (while (python-syntax-context 'paren
)
2547 (goto-char (1- (point-marker))))
2549 (line-beginning-position))
2551 (when (not (python-syntax-context 'paren
))
2553 (when (not (python-syntax-context 'paren
))
2554 (skip-syntax-backward "^)")))
2555 (while (python-syntax-context 'paren
)
2556 (goto-char (1+ (point-marker))))
2558 (let ((paragraph-start "\f\\|[ \t]*$")
2559 (paragraph-separate ",")
2560 (fill-paragraph-function))
2561 (goto-char (point-min))
2562 (fill-paragraph justify
))
2565 (python-indent-line)
2566 (goto-char (line-end-position)))) t
)
2571 (defcustom python-skeleton-autoinsert nil
2572 "Non-nil means template skeletons will be automagically inserted.
2573 This happens when pressing \"if<SPACE>\", for example, to prompt for
2579 (define-obsolete-variable-alias
2580 'python-use-skeletons
'python-skeleton-autoinsert
"24.3")
2582 (defvar python-skeleton-available
'()
2583 "Internal list of available skeletons.")
2585 (define-abbrev-table 'python-mode-abbrev-table
()
2586 "Abbrev table for Python mode."
2588 ;; Allow / inside abbrevs.
2589 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
2590 ;; Only expand in code.
2591 :enable-function
(lambda ()
2593 (not (python-syntax-comment-or-string-p))
2594 python-skeleton-autoinsert
)))
2596 (defmacro python-skeleton-define
(name doc
&rest skel
)
2597 "Define a `python-mode' skeleton using NAME DOC and SKEL.
2598 The skeleton will be bound to python-skeleton-NAME and will
2599 be added to `python-mode-abbrev-table'."
2600 (declare (indent 2))
2601 (let* ((name (symbol-name name
))
2602 (function-name (intern (concat "python-skeleton-" name
))))
2604 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
2606 (setq python-skeleton-available
2607 (cons ',function-name python-skeleton-available
))
2608 (define-skeleton ,function-name
2610 (format "Insert %s statement." name
))
2613 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2614 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2615 The skeleton will be bound to python-skeleton-NAME."
2616 (declare (indent 2))
2617 (let* ((name (symbol-name name
))
2618 (function-name (intern (concat "python-skeleton--" name
)))
2620 "Add '%s' clause? " name
)))
2623 `(< ,(format "%s:" name
) \n \n
2625 `(define-skeleton ,function-name
2627 (format "Auxiliary skeleton for %s statement." name
))
2629 (unless (y-or-n-p ,msg
)
2633 (python-define-auxiliary-skeleton else nil
)
2635 (python-define-auxiliary-skeleton except nil
)
2637 (python-define-auxiliary-skeleton finally nil
)
2639 (python-skeleton-define if nil
2643 ("other condition, %s: "
2647 '(python-skeleton--else) | ^
)
2649 (python-skeleton-define while nil
2653 '(python-skeleton--else) | ^
)
2655 (python-skeleton-define for nil
2659 '(python-skeleton--else) | ^
)
2661 (python-skeleton-define try nil
2667 "except " str
":" \n
2670 '(python-skeleton--except)
2671 '(python-skeleton--else)
2672 '(python-skeleton--finally) | ^
)
2674 (python-skeleton-define def nil
2676 "def " str
" (" ("Parameter, %s: "
2677 (unless (equal ?\
( (char-before)) ", ")
2679 "\"\"\"" -
"\"\"\"" \n
2682 (python-skeleton-define class nil
2684 "class " str
" (" ("Inheritance, %s: "
2685 (unless (equal ?\
( (char-before)) ", ")
2689 "\"\"\"" -
"\"\"\"" \n
2692 (defun python-skeleton-add-menu-items ()
2693 "Add menu items to Python->Skeletons menu."
2694 (let ((skeletons (sort python-skeleton-available
'string
<))
2696 (dolist (skeleton skeletons
)
2698 nil
'("Python" "Skeletons")
2700 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2705 (defcustom python-ffap-setup-code
2706 "def __FFAP_get_module_path(module):
2709 path = __import__(module).__file__
2710 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2715 "Python code to get a module path."
2719 (defcustom python-ffap-string-code
2720 "__FFAP_get_module_path('''%s''')\n"
2721 "Python code used to get a string with the path of a module."
2725 (defun python-ffap-module-path (module)
2726 "Function for `ffap-alist' to return path for MODULE."
2728 (and (eq major-mode
'inferior-python-mode
)
2729 (get-buffer-process (current-buffer)))
2730 (python-shell-get-process))))
2734 (python-shell-send-string-no-output
2735 (format python-ffap-string-code module
) process
)))
2737 (substring-no-properties module-file
1 -
1))))))
2739 (eval-after-load "ffap"
2741 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2742 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2747 (defcustom python-check-command
2749 "Command used to check a Python file."
2753 (defcustom python-check-buffer-name
2754 "*Python check: %s*"
2755 "Buffer name used for check commands."
2759 (defvar python-check-custom-command nil
2762 (defun python-check (command)
2763 "Check a Python file (default current buffer's file).
2764 Runs COMMAND, a shell command, as if by `compile'. See
2765 `python-check-command' for the default."
2767 (list (read-string "Check command: "
2768 (or python-check-custom-command
2769 (concat python-check-command
" "
2770 (shell-quote-argument
2772 (let ((name (buffer-file-name)))
2774 (file-name-nondirectory name
)))
2776 (setq python-check-custom-command command
)
2777 (save-some-buffers (not compilation-ask-about-save
) nil
)
2778 (let ((process-environment (python-shell-calculate-process-environment))
2779 (exec-path (python-shell-calculate-exec-path)))
2780 (compilation-start command nil
2782 (format python-check-buffer-name command
)))))
2787 (defcustom python-eldoc-setup-code
2788 "def __PYDOC_get_help(obj):
2791 if hasattr(obj, 'startswith'):
2792 obj = eval(obj, globals())
2793 doc = inspect.getdoc(obj)
2794 if not doc and callable(obj):
2796 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2797 target = obj.__init__
2803 args = inspect.formatargspec(
2804 *inspect.getargspec(target)
2807 doc = '{objtype} {name}{args}'.format(
2808 objtype=objtype, name=name, args=args
2811 doc = doc.splitlines()[0]
2818 "Python code to setup documentation retrieval."
2822 (defcustom python-eldoc-string-code
2823 "__PYDOC_get_help('''%s''')\n"
2824 "Python code used to get a string with the documentation of an object."
2828 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2829 "Internal implementation to get documentation at point.
2830 If not FORCE-INPUT is passed then what
2831 `python-info-current-symbol' returns will be used. If not
2832 FORCE-PROCESS is passed what `python-shell-get-process' returns
2834 (let ((process (or force-process
(python-shell-get-process))))
2836 (error "Eldoc needs an inferior Python process running")
2837 (let ((input (or force-input
2838 (python-info-current-symbol t
))))
2840 (python-shell-send-string-no-output
2841 (format python-eldoc-string-code input
)
2844 (defun python-eldoc-function ()
2845 "`eldoc-documentation-function' for Python.
2846 For this to work the best as possible you should call
2847 `python-shell-send-buffer' from time to time so context in
2848 inferior python process is updated properly."
2849 (python-eldoc--get-doc-at-point))
2851 (defun python-eldoc-at-point (symbol)
2852 "Get help on SYMBOL using `help'.
2853 Interactively, prompt for symbol."
2855 (let ((symbol (python-info-current-symbol t
))
2856 (enable-recursive-minibuffers t
))
2857 (list (read-string (if symbol
2858 (format "Describe symbol (default %s): " symbol
)
2859 "Describe symbol: ")
2861 (message (python-eldoc--get-doc-at-point symbol
)))
2863 (add-to-list 'debug-ignored-errors
2864 "^Eldoc needs an inferior Python process running.")
2869 (defun python-info-current-defun (&optional include-type
)
2870 "Return name of surrounding function with Python compatible dotty syntax.
2871 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2872 This function is compatible to be used as
2873 `add-log-current-defun-function' since it returns nil if point is
2874 not inside a defun."
2876 (starting-indentation)
2882 (setq starting-point
(point-marker))
2883 (setq starting-indentation
(save-excursion
2884 (python-nav-beginning-of-statement)
2885 (current-indentation)))
2887 (while (python-beginning-of-defun-function 1)
2888 (when (or (< (current-indentation) starting-indentation
)
2893 (python-end-of-defun-function)
2895 (setq first-run nil
)
2896 (setq starting-indentation
(current-indentation))
2897 (looking-at python-nav-beginning-of-defun-regexp
)
2899 (if (not include-type
)
2900 (match-string-no-properties 1)
2901 (mapconcat 'identity
2903 (match-string-no-properties 0)) " "))
2906 (mapconcat (lambda (string) string
) names
"."))))
2908 (defun python-info-current-symbol (&optional replace-self
)
2909 "Return current symbol using dotty syntax.
2910 With optional argument REPLACE-SELF convert \"self\" to current
2913 (and (not (python-syntax-comment-or-string-p))
2914 (with-syntax-table python-dotty-syntax-table
2915 (let ((sym (symbol-at-point)))
2917 (substring-no-properties (symbol-name sym
))))))))
2919 (if (not replace-self
)
2921 (let ((current-defun (python-info-current-defun)))
2922 (if (not current-defun
)
2924 (replace-regexp-in-string
2925 (python-rx line-start word-start
"self" word-end ?.
)
2927 (mapconcat 'identity
2928 (butlast (split-string current-defun
"\\."))
2932 (defun python-info-statement-starts-block-p ()
2933 "Return non-nil if current statement opens a block."
2935 (python-nav-beginning-of-statement)
2936 (looking-at (python-rx block-start
))))
2938 (defun python-info-statement-ends-block-p ()
2939 "Return non-nil if point is at end of block."
2940 (let ((end-of-block-pos (save-excursion
2941 (python-nav-end-of-block)))
2942 (end-of-statement-pos (save-excursion
2943 (python-nav-end-of-statement))))
2944 (and end-of-block-pos end-of-statement-pos
2945 (= end-of-block-pos end-of-statement-pos
))))
2947 (defun python-info-beginning-of-statement-p ()
2948 "Return non-nil if point is at beginning of statement."
2949 (= (point) (save-excursion
2950 (python-nav-beginning-of-statement)
2953 (defun python-info-end-of-statement-p ()
2954 "Return non-nil if point is at end of statement."
2955 (= (point) (save-excursion
2956 (python-nav-end-of-statement)
2959 (defun python-info-beginning-of-block-p ()
2960 "Return non-nil if point is at beginning of block."
2961 (and (python-info-beginning-of-statement-p)
2962 (python-info-statement-starts-block-p)))
2964 (defun python-info-end-of-block-p ()
2965 "Return non-nil if point is at end of block."
2966 (and (python-info-end-of-statement-p)
2967 (python-info-statement-ends-block-p)))
2969 (defun python-info-closing-block ()
2970 "Return the point of the block the current line closes."
2971 (let ((closing-word (save-excursion
2972 (back-to-indentation)
2974 (indentation (current-indentation)))
2975 (when (member closing-word python-indent-dedenters
)
2978 (while (and (> (current-indentation) indentation
)
2980 (not (back-to-indentation))
2982 (back-to-indentation)
2984 ((not (equal indentation
(current-indentation))) nil
)
2985 ((string= closing-word
"elif")
2986 (when (member (current-word) '("if" "elif"))
2988 ((string= closing-word
"else")
2989 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2991 ((string= closing-word
"except")
2992 (when (member (current-word) '("try"))
2994 ((string= closing-word
"finally")
2995 (when (member (current-word) '("except" "else"))
2996 (point-marker))))))))
2998 (defun python-info-closing-block-message (&optional closing-block-point
)
2999 "Message the contents of the block the current line closes.
3000 With optional argument CLOSING-BLOCK-POINT use that instead of
3001 recalculating it calling `python-info-closing-block'."
3002 (let ((point (or closing-block-point
(python-info-closing-block))))
3006 (message "Closes %s" (save-excursion
3008 (back-to-indentation)
3010 (point) (line-end-position))))))))
3012 (defun python-info-line-ends-backslash-p (&optional line-number
)
3013 "Return non-nil if current line ends with backslash.
3014 With optional argument LINE-NUMBER, check that line instead."
3019 (goto-char line-number
))
3020 (while (and (not (eobp))
3021 (goto-char (line-end-position))
3022 (python-syntax-context 'paren
)
3023 (not (equal (char-before (point)) ?
\\)))
3025 (when (equal (char-before) ?
\\)
3028 (defun python-info-beginning-of-backslash (&optional line-number
)
3029 "Return the point where the backslashed line start.
3030 Optional argument LINE-NUMBER forces the line number to check against."
3035 (goto-char line-number
))
3036 (when (python-info-line-ends-backslash-p)
3037 (while (save-excursion
3038 (goto-char (line-beginning-position))
3039 (python-syntax-context 'paren
))
3041 (back-to-indentation)
3044 (defun python-info-continuation-line-p ()
3045 "Check if current line is continuation of another.
3046 When current line is continuation of another return the point
3047 where the continued line ends."
3051 (let* ((context-type (progn
3052 (back-to-indentation)
3053 (python-syntax-context-type)))
3054 (line-start (line-number-at-pos))
3055 (context-start (when context-type
3056 (python-syntax-context context-type
))))
3057 (cond ((equal context-type
'paren
)
3058 ;; Lines inside a paren are always a continuation line
3059 ;; (except the first one).
3060 (python-util-forward-comment -
1)
3062 ((member context-type
'(string comment
))
3063 ;; move forward an roll again
3064 (goto-char context-start
)
3065 (python-util-forward-comment)
3066 (python-info-continuation-line-p))
3068 ;; Not within a paren, string or comment, the only way
3069 ;; we are dealing with a continuation line is that
3070 ;; previous line contains a backslash, and this can
3071 ;; only be the previous line from current
3072 (back-to-indentation)
3073 (python-util-forward-comment -
1)
3074 (when (and (equal (1- line-start
) (line-number-at-pos))
3075 (python-info-line-ends-backslash-p))
3076 (point-marker))))))))
3078 (defun python-info-block-continuation-line-p ()
3079 "Return non-nil if current line is a continuation of a block."
3081 (when (python-info-continuation-line-p)
3083 (back-to-indentation)
3084 (when (looking-at (python-rx block-start
))
3087 (defun python-info-assignment-continuation-line-p ()
3088 "Check if current line is a continuation of an assignment.
3089 When current line is continuation of another with an assignment
3090 return the point of the first non-blank character after the
3093 (when (python-info-continuation-line-p)
3095 (back-to-indentation)
3096 (when (and (not (looking-at (python-rx block-start
)))
3097 (and (re-search-forward (python-rx not-simple-operator
3099 not-simple-operator
)
3100 (line-end-position) t
)
3101 (not (python-syntax-context-type))))
3102 (skip-syntax-forward "\s")
3105 (defun python-info-looking-at-beginning-of-defun (&optional syntax-ppss
)
3106 "Check if point is at `beginning-of-defun' using SYNTAX-PPSS."
3107 (and (not (python-syntax-context-type (or syntax-ppss
(syntax-ppss))))
3109 (beginning-of-line 1)
3110 (looking-at python-nav-beginning-of-defun-regexp
))))
3112 (defun python-info-current-line-comment-p ()
3113 "Check if current line is a comment line."
3114 (char-equal (or (char-after (+ (point) (current-indentation))) ?_
) ?
#))
3116 (defun python-info-current-line-empty-p ()
3117 "Check if current line is empty, ignoring whitespace."
3119 (beginning-of-line 1)
3121 (python-rx line-start
(* whitespace
)
3122 (group (* not-newline
))
3123 (* whitespace
) line-end
))
3124 (string-equal "" (match-string-no-properties 1))))
3127 ;;; Utility functions
3129 (defun python-util-position (item seq
)
3130 "Find the first occurrence of ITEM in SEQ.
3131 Return the index of the matching item, or nil if not found."
3132 (let ((member-result (member item seq
)))
3134 (- (length seq
) (length member-result
)))))
3136 ;; Stolen from org-mode
3137 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
3138 "Clone local variables from FROM-BUFFER.
3139 Optional argument REGEXP selects variables to clone and defaults
3143 (and (symbolp (car pair
))
3144 (string-match (or regexp
"^python-")
3145 (symbol-name (car pair
)))
3146 (set (make-local-variable (car pair
))
3148 (buffer-local-variables from-buffer
)))
3150 (defun python-util-forward-comment (&optional direction
)
3151 "Python mode specific version of `forward-comment'.
3152 Optional argument DIRECTION defines the direction to move to."
3153 (let ((comment-start (python-syntax-context 'comment
))
3154 (factor (if (< (or direction
0) 0)
3158 (goto-char comment-start
))
3159 (forward-comment factor
)))
3163 (define-derived-mode python-mode prog-mode
"Python"
3164 "Major mode for editing Python files.
3167 Entry to this mode calls the value of `python-mode-hook'
3168 if that value is non-nil."
3169 (set (make-local-variable 'tab-width
) 8)
3170 (set (make-local-variable 'indent-tabs-mode
) nil
)
3172 (set (make-local-variable 'comment-start
) "# ")
3173 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
3175 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
3176 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
3178 (set (make-local-variable 'forward-sexp-function
)
3179 'python-nav-forward-sexp
)
3181 (set (make-local-variable 'font-lock-defaults
)
3182 '(python-font-lock-keywords nil nil nil nil
))
3184 (set (make-local-variable 'syntax-propertize-function
)
3185 python-syntax-propertize-function
)
3187 (set (make-local-variable 'indent-line-function
)
3188 #'python-indent-line-function
)
3189 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
3191 (set (make-local-variable 'paragraph-start
) "\\s-*$")
3192 (set (make-local-variable 'fill-paragraph-function
)
3193 'python-fill-paragraph
)
3195 (set (make-local-variable 'beginning-of-defun-function
)
3196 #'python-beginning-of-defun-function
)
3197 (set (make-local-variable 'end-of-defun-function
)
3198 #'python-end-of-defun-function
)
3200 (add-hook 'completion-at-point-functions
3201 'python-completion-complete-at-point nil
'local
)
3203 (add-hook 'post-self-insert-hook
3204 'python-indent-post-self-insert-function nil
'local
)
3206 (set (make-local-variable 'imenu-extract-index-name-function
)
3207 #'python-info-current-defun
)
3209 (set (make-local-variable 'add-log-current-defun-function
)
3210 #'python-info-current-defun
)
3212 (add-hook 'which-func-functions
#'python-info-current-defun
nil t
)
3214 (set (make-local-variable 'skeleton-further-elements
)
3216 (< '(backward-delete-char-untabify (min python-indent-offset
3218 (^
'(- (1+ (current-indentation))))))
3220 (set (make-local-variable 'eldoc-documentation-function
)
3221 #'python-eldoc-function
)
3223 (add-to-list 'hs-special-modes-alist
3224 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
3226 (python-end-of-defun-function)) nil
))
3228 (set (make-local-variable 'mode-require-final-newline
) t
)
3230 (set (make-local-variable 'outline-regexp
)
3231 (python-rx (* space
) block-start
))
3232 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
3233 (set (make-local-variable 'outline-level
)
3235 "`outline-level' function for Python mode."
3236 (1+ (/ (current-indentation) python-indent-offset
))))
3238 (python-skeleton-add-menu-items)
3240 (make-local-variable 'python-shell-internal-buffer
)
3242 (when python-indent-guess-indent-offset
3243 (python-indent-guess-indent-offset)))
3250 ;; indent-tabs-mode: nil
3253 ;;; python.el ends here