1 ;;; python.el --- Python's flying circus support for Emacs
3 ;; Copyright (C) 2010, 2011 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 NOT part of GNU Emacs.
14 ;; python.el is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
19 ;; python.el is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 ;; GNU General Public License for more details.
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with python.el. If not, see <http://www.gnu.org/licenses/>.
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 ;; While it probably has less features than Dave Love's python.el and
34 ;; PSF's python-mode.el it provides the main stuff you'll need while
35 ;; keeping it simple :)
37 ;; Implements Syntax highlighting, Indentation, Movement, Shell
38 ;; interaction, Shell completion, Shell virtualenv support, Pdb
39 ;; tracking, Symbol completion, Skeletons, FFAP, Code Check, Eldoc,
42 ;; Syntax highlighting: Fontification of code is provided and supports
43 ;; python's triple quoted strings properly.
45 ;; Indentation: Automatic indentation with indentation cycling is
46 ;; provided, it allows you to navigate different available levels of
47 ;; indentation by hitting <tab> several times. Also when inserting a
48 ;; colon the `python-indent-electric-colon' command is invoked and
49 ;; causes the current line to be dedented automatically if needed.
51 ;; Movement: `beginning-of-defun' and `end-of-defun' functions are
52 ;; properly implemented. There are also specialized
53 ;; `forward-sentence' and `backward-sentence' replacements
54 ;; (`python-nav-forward-sentence', `python-nav-backward-sentence'
55 ;; respectively). Extra functions `python-nav-sentence-start' and
56 ;; `python-nav-sentence-end' are included to move to the beginning and
57 ;; to the end of a setence while taking care of multiline definitions.
58 ;; `python-nav-jump-to-defun' is provided and allows jumping to a
59 ;; function or class definition quickly in the current buffer.
61 ;; Shell interaction: is provided and allows you to execute easily any
62 ;; block of code of your current buffer in an inferior Python process.
64 ;; Shell completion: hitting tab will try to complete the current
65 ;; word. Shell completion is implemented in a manner that if you
66 ;; change the `python-shell-interpreter' to any other (for example
67 ;; IPython) it should be easy to integrate another way to calculate
68 ;; completions. You just need to specify your custom
69 ;; `python-shell-completion-setup-code' and
70 ;; `python-shell-completion-string-code'.
72 ;; Here is a complete example of the settings you would use for
76 ;; python-shell-interpreter "ipython"
77 ;; python-shell-interpreter-args ""
78 ;; python-shell-prompt-regexp "In \\[[0-9]+\\]: "
79 ;; python-shell-prompt-output-regexp "Out\\[[0-9]+\\]: "
80 ;; python-shell-completion-setup-code
81 ;; "from IPython.core.completerlib import module_completion"
82 ;; python-shell-completion-module-string-code
83 ;; "';'.join(module_completion('''%s'''))\n"
84 ;; python-shell-completion-string-code
85 ;; "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
87 ;; For iPython 0.10 everything would be the same except for
88 ;; `python-shell-completion-string-code':
90 ;; (setq python-shell-completion-string-code
91 ;; "';'.join(__IP.complete('''%s'''))\n")
93 ;; Unfortunately running iPython on Windows needs some more tweaking.
94 ;; The way you must set `python-shell-interpreter' and
95 ;; `python-shell-interpreter-args' is as follows:
98 ;; python-shell-interpreter "C:\\Python27\\python.exe"
99 ;; python-shell-interpreter-args
100 ;; "-i C:\\Python27\\Scripts\\ipython-script.py")
102 ;; That will spawn the iPython process correctly (Of course you need
103 ;; to modify the paths according to your system).
105 ;; Please note that the default completion system depends on the
106 ;; readline module, so if you are using some Operating System that
107 ;; bundles Python without it (like Windows) just install the
108 ;; pyreadline from http://ipython.scipy.org/moin/PyReadline/Intro and
109 ;; you should be good to go.
111 ;; Shell virtualenv support: The shell also contains support for
112 ;; virtualenvs and other special environment modifications thanks to
113 ;; `python-shell-process-environment' and `python-shell-exec-path'.
114 ;; These two variables allows you to modify execution paths and
115 ;; environment variables to make easy for you to setup virtualenv rules
116 ;; or behavior modifications when running shells. Here is an example
117 ;; of how to make shell processes to be run using the /path/to/env/
120 ;; (setq python-shell-process-environment
122 ;; (format "PATH=%s" (mapconcat
125 ;; (cons (getenv "PATH")
126 ;; '("/path/to/env/bin/")))
128 ;; "VIRTUAL_ENV=/path/to/env/"))
129 ;; (python-shell-exec-path . ("/path/to/env/bin/"))
131 ;; Since the above is cumbersome and can be programatically
132 ;; calculated, the variable `python-shell-virtualenv-path' is
133 ;; provided. When this variable is set with the path of the
134 ;; virtualenv to use, `process-environment' and `exec-path' get proper
135 ;; values in order to run shells inside the specified virtualenv. So
136 ;; the following will achieve the same as the previous example:
138 ;; (setq python-shell-virtualenv-path "/path/to/env/")
140 ;; Also the `python-shell-extra-pythonpaths' variable have been
141 ;; introduced as simple way of adding paths to the PYTHONPATH without
142 ;; affecting existing values.
144 ;; Pdb tracking: when you execute a block of code that contains some
145 ;; call to pdb (or ipdb) it will prompt the block of code and will
146 ;; follow the execution of pdb marking the current line with an arrow.
148 ;; Symbol completion: you can complete the symbol at point. It uses
149 ;; the shell completion in background so you should run
150 ;; `python-shell-send-buffer' from time to time to get better results.
152 ;; Skeletons: 6 skeletons are provided for simple inserting of class,
153 ;; def, for, if, try and while. These skeletons are integrated with
154 ;; dabbrev. If you have `dabbrev-mode' activated and
155 ;; `python-skeleton-autoinsert' is set to t, then whenever you type
156 ;; the name of any of those defined and hit SPC, they will be
157 ;; automatically expanded.
159 ;; FFAP: You can find the filename for a given module when using ffap
160 ;; out of the box. This feature needs an inferior python shell
163 ;; Code check: Check the current file for errors with `python-check'
164 ;; using the program defined in `python-check-command'.
166 ;; Eldoc: returns documentation for object at point by using the
167 ;; inferior python subprocess to inspect its documentation. As you
168 ;; might guessed you should run `python-shell-send-buffer' from time
169 ;; to time to get better results too.
171 ;; imenu: This mode supports imenu. It builds a plain or tree menu
172 ;; depending on the value of `python-imenu-make-tree'. Also you can
173 ;; customize if menu items should include its type using
174 ;; `python-imenu-include-defun-type'.
176 ;; If you used python-mode.el you probably will miss auto-indentation
177 ;; when inserting newlines. To achieve the same behavior you have
180 ;; 1) Use GNU/Emacs' standard binding for `newline-and-indent': C-j.
182 ;; 2) Add the following hook in your .emacs:
184 ;; (add-hook 'python-mode-hook
186 ;; (define-key python-mode-map "\C-m" 'newline-and-indent)))
188 ;; I'd recommend the first one since you'll get the same behavior for
189 ;; all modes out-of-the-box.
193 ;; Add this to your .emacs:
195 ;; (add-to-list 'load-path "/folder/containing/file")
202 (require 'ansi-color
)
207 ;; Avoid compiler warnings
208 (defvar view-return-to-alist
)
209 (defvar compilation-error-regexp-alist
)
210 (defvar outline-heading-end-regexp
))
212 (autoload 'comint-mode
"comint")
215 (add-to-list 'auto-mode-alist
(cons (purecopy "\\.py\\'") 'python-mode
))
217 (add-to-list 'interpreter-mode-alist
(cons (purecopy "python") 'python-mode
))
220 "Python Language's flying circus support for Emacs."
223 :link
'(emacs-commentary-link "python"))
228 (defvar python-mode-map
229 (let ((map (make-sparse-keymap)))
231 (substitute-key-definition 'backward-sentence
232 'python-nav-backward-sentence
234 (substitute-key-definition 'forward-sentence
235 'python-nav-forward-sentence
237 (define-key map
"\C-c\C-j" 'python-nav-jump-to-defun
)
239 (define-key map
"\177" 'python-indent-dedent-line-backspace
)
240 (define-key map
(kbd "<backtab>") 'python-indent-dedent-line
)
241 (define-key map
"\C-c<" 'python-indent-shift-left
)
242 (define-key map
"\C-c>" 'python-indent-shift-right
)
243 (define-key map
":" 'python-indent-electric-colon
)
245 (define-key map
"\C-c\C-tc" 'python-skeleton-class
)
246 (define-key map
"\C-c\C-td" 'python-skeleton-def
)
247 (define-key map
"\C-c\C-tf" 'python-skeleton-for
)
248 (define-key map
"\C-c\C-ti" 'python-skeleton-if
)
249 (define-key map
"\C-c\C-tt" 'python-skeleton-try
)
250 (define-key map
"\C-c\C-tw" 'python-skeleton-while
)
252 (define-key map
"\C-c\C-s" 'python-shell-send-string
)
253 (define-key map
"\C-c\C-r" 'python-shell-send-region
)
254 (define-key map
"\C-\M-x" 'python-shell-send-defun
)
255 (define-key map
"\C-c\C-c" 'python-shell-send-buffer
)
256 (define-key map
"\C-c\C-l" 'python-shell-send-file
)
257 (define-key map
"\C-c\C-z" 'python-shell-switch-to-shell
)
258 ;; Some util commands
259 (define-key map
"\C-c\C-v" 'python-check
)
260 (define-key map
"\C-c\C-f" 'python-eldoc-at-point
)
262 (substitute-key-definition 'complete-symbol
'completion-at-point
264 (easy-menu-define python-menu map
"Python Mode menu"
266 :help
"Python-specific Features"
267 ["Shift region left" python-indent-shift-left
:active mark-active
268 :help
"Shift region left by a single indentation step"]
269 ["Shift region right" python-indent-shift-right
:active mark-active
270 :help
"Shift region right by a single indentation step"]
272 ["Start of def/class" beginning-of-defun
273 :help
"Go to start of outermost definition around point"]
274 ["End of def/class" end-of-defun
275 :help
"Go to end of definition around point"]
276 ["Mark def/class" mark-defun
277 :help
"Mark outermost definition around point"]
278 ["Jump to def/class" python-nav-jump-to-defun
279 :help
"Jump to a class or function definition"]
283 ["Start interpreter" run-python
284 :help
"Run inferior Python process in a separate buffer"]
285 ["Switch to shell" python-shell-switch-to-shell
286 :help
"Switch to running inferior Python process"]
287 ["Eval string" python-shell-send-string
288 :help
"Eval string in inferior Python session"]
289 ["Eval buffer" python-shell-send-buffer
290 :help
"Eval buffer in inferior Python session"]
291 ["Eval region" python-shell-send-region
292 :help
"Eval region in inferior Python session"]
293 ["Eval defun" python-shell-send-defun
294 :help
"Eval defun in inferior Python session"]
295 ["Eval file" python-shell-send-file
296 :help
"Eval file in inferior Python session"]
297 ["Debugger" pdb
:help
"Run pdb under GUD"]
299 ["Check file" python-check
300 :help
"Check file for errors"]
301 ["Help on symbol" python-eldoc-at-point
302 :help
"Get help on symbol at point"]
303 ["Complete symbol" completion-at-point
304 :help
"Complete symbol before point"]))
306 "Keymap for `python-mode'.")
309 ;;; Python specialized rx
312 (defconst python-rx-constituents
314 `(block-start .
,(rx symbol-start
315 (or "def" "class" "if" "elif" "else" "try"
316 "except" "finally" "for" "while" "with")
318 `(decorator .
,(rx line-start
(* space
) ?
@ (any letter ?_
)
320 `(defun .
,(rx symbol-start
(or "def" "class") symbol-end
))
321 `(symbol-name .
,(rx (any letter ?_
) (* (any word ?_
))))
322 `(open-paren .
,(rx (or "{" "[" "(")))
323 `(close-paren .
,(rx (or "}" "]" ")")))
324 `(simple-operator .
,(rx (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
)))
325 `(not-simple-operator .
,(rx (not (any ?
+ ?- ?
/ ?
& ?^ ?~ ?| ?
* ?
< ?
> ?
= ?%
))))
326 `(operator .
,(rx (or "+" "-" "/" "&" "^" "~" "|" "*" "<" ">"
327 "=" "%" "**" "//" "<<" ">>" "<=" "!="
328 "==" ">=" "is" "not")))
329 `(assignment-operator .
,(rx (or "=" "+=" "-=" "*=" "/=" "//=" "%=" "**="
330 ">>=" "<<=" "&=" "^=" "|="))))
331 "Additional Python specific sexps for `python-rx'"))
333 (defmacro python-rx
(&rest regexps
)
334 "Python mode specialized rx macro which supports common python named REGEXPS."
335 (let ((rx-constituents (append python-rx-constituents rx-constituents
)))
336 (cond ((null regexps
)
339 (rx-to-string `(and ,@regexps
) t
))
341 (rx-to-string (car regexps
) t
)))))
344 ;;; Font-lock and syntax
346 (defvar python-font-lock-keywords
349 (or "and" "del" "from" "not" "while" "as" "elif" "global" "or" "with"
350 "assert" "else" "if" "pass" "yield" "break" "except" "import"
351 "print" "class" "exec" "in" "raise" "continue" "finally" "is"
352 "return" "def" "for" "lambda" "try" "self")
355 (,(rx symbol-start
"def" (1+ space
) (group (1+ (or word ?_
))))
356 (1 font-lock-function-name-face
))
358 (,(rx symbol-start
"class" (1+ space
) (group (1+ (or word ?_
))))
359 (1 font-lock-type-face
))
362 ;; copyright, license, credits, quit, exit are added by the
363 ;; site module and since they are not intended to be used in
364 ;; programs they are not added here either.
365 (or "None" "True" "False" "Ellipsis" "__debug__" "NotImplemented")
366 symbol-end
) . font-lock-constant-face
)
368 (,(rx line-start
(* (any " \t")) (group "@" (1+ (or word ?_
))
369 (0+ "." (1+ (or word ?_
)))))
370 (1 font-lock-type-face
))
371 ;; Builtin Exceptions
373 (or "ArithmeticError" "AssertionError" "AttributeError"
374 "BaseException" "BufferError" "BytesWarning" "DeprecationWarning"
375 "EOFError" "EnvironmentError" "Exception" "FloatingPointError"
376 "FutureWarning" "GeneratorExit" "IOError" "ImportError"
377 "ImportWarning" "IndentationError" "IndexError" "KeyError"
378 "KeyboardInterrupt" "LookupError" "MemoryError" "NameError"
379 "NotImplementedError" "OSError" "OverflowError"
380 "PendingDeprecationWarning" "ReferenceError" "RuntimeError"
381 "RuntimeWarning" "StandardError" "StopIteration" "SyntaxError"
382 "SyntaxWarning" "SystemError" "SystemExit" "TabError" "TypeError"
383 "UnboundLocalError" "UnicodeDecodeError" "UnicodeEncodeError"
384 "UnicodeError" "UnicodeTranslateError" "UnicodeWarning"
385 "UserWarning" "ValueError" "Warning" "ZeroDivisionError")
386 symbol-end
) . font-lock-type-face
)
389 (or "_" "__doc__" "__import__" "__name__" "__package__" "abs" "all"
390 "any" "apply" "basestring" "bin" "bool" "buffer" "bytearray"
391 "bytes" "callable" "chr" "classmethod" "cmp" "coerce" "compile"
392 "complex" "delattr" "dict" "dir" "divmod" "enumerate" "eval"
393 "execfile" "file" "filter" "float" "format" "frozenset"
394 "getattr" "globals" "hasattr" "hash" "help" "hex" "id" "input"
395 "int" "intern" "isinstance" "issubclass" "iter" "len" "list"
396 "locals" "long" "map" "max" "min" "next" "object" "oct" "open"
397 "ord" "pow" "print" "property" "range" "raw_input" "reduce"
398 "reload" "repr" "reversed" "round" "set" "setattr" "slice"
399 "sorted" "staticmethod" "str" "sum" "super" "tuple" "type"
400 "unichr" "unicode" "vars" "xrange" "zip")
401 symbol-end
) . font-lock-builtin-face
)
403 ;; support for a = b = c = 5
405 (let ((re (python-rx (group (+ (any word ?. ?_
)))
406 (? ?\
[ (+ (not (any ?\
]))) ?\
]) (* space
)
407 assignment-operator
)))
408 (when (re-search-forward re limit t
)
409 (while (and (python-info-ppss-context 'paren
)
410 (re-search-forward re limit t
)))
411 (if (and (not (python-info-ppss-context 'paren
))
412 (not (equal (char-after (point-marker)) ?
=)))
414 (set-match-data nil
)))))
415 (1 font-lock-variable-name-face nil nil
))
416 ;; support for a, b, c = (1, 2, 3)
418 (let ((re (python-rx (group (+ (any word ?. ?_
))) (* space
)
419 (* ?
, (* space
) (+ (any word ?. ?_
)) (* space
))
420 ?
, (* space
) (+ (any word ?. ?_
)) (* space
)
421 assignment-operator
)))
422 (when (and (re-search-forward re limit t
)
423 (goto-char (nth 3 (match-data))))
424 (while (and (python-info-ppss-context 'paren
)
425 (re-search-forward re limit t
))
426 (goto-char (nth 3 (match-data))))
427 (if (not (python-info-ppss-context 'paren
))
429 (set-match-data nil
)))))
430 (1 font-lock-variable-name-face nil nil
))))
432 (defconst python-font-lock-syntactic-keywords
433 ;; Make outer chars of matching triple-quote sequences into generic
434 ;; string delimiters. Fixme: Is there a better way?
435 ;; First avoid a sequence preceded by an odd number of backslashes.
436 `((,(concat "\\(?:\\([RUru]\\)[Rr]?\\|^\\|[^\\]\\(?:\\\\.\\)*\\)" ;Prefix.
437 "\\(?:\\('\\)'\\('\\)\\|\\(?2:\"\\)\"\\(?3:\"\\)\\)")
438 (3 (python-quote-syntax)))))
440 (defun python-quote-syntax ()
441 "Put `syntax-table' property correctly on triple quote.
442 Used for syntactic keywords. N is the match number (1, 2 or 3)."
443 ;; Given a triple quote, we have to check the context to know
444 ;; whether this is an opening or closing triple or whether it's
445 ;; quoted anyhow, and should be ignored. (For that we need to do
446 ;; the same job as `syntax-ppss' to be correct and it seems to be OK
447 ;; to use it here despite initial worries.) We also have to sort
448 ;; out a possible prefix -- well, we don't _have_ to, but I think it
449 ;; should be treated as part of the string.
452 ;; ur"""ar""" x='"' # """
455 ;; x '"""' x """ \"""" x
457 (goto-char (match-beginning 0))
458 (let ((syntax (save-match-data (syntax-ppss))))
460 ((eq t
(nth 3 syntax
)) ; after unclosed fence
461 ;; Consider property for the last char if in a fenced string.
462 (goto-char (nth 8 syntax
)) ; fence position
463 (skip-chars-forward "uUrR") ; skip any prefix
464 ;; Is it a matching sequence?
465 (if (eq (char-after) (char-after (match-beginning 2)))
466 (put-text-property (match-beginning 3) (match-end 3)
467 'syntax-table
(string-to-syntax "|"))))
469 ;; Consider property for initial char, accounting for prefixes.
470 (put-text-property (match-beginning 1) (match-end 1)
471 'syntax-table
(string-to-syntax "|")))
473 ;; Consider property for initial char, accounting for prefixes.
474 (put-text-property (match-beginning 2) (match-end 2)
475 'syntax-table
(string-to-syntax "|"))))
478 (defvar python-mode-syntax-table
479 (let ((table (make-syntax-table)))
480 ;; Give punctuation syntax to ASCII that normally has symbol
481 ;; syntax or has word syntax and isn't a letter.
482 (let ((symbol (string-to-syntax "_"))
483 (sst (standard-syntax-table)))
486 (if (equal symbol
(aref sst i
))
487 (modify-syntax-entry i
"." table
)))))
488 (modify-syntax-entry ?$
"." table
)
489 (modify-syntax-entry ?%
"." table
)
491 (modify-syntax-entry ?
# "<" table
)
492 (modify-syntax-entry ?
\n ">" table
)
493 (modify-syntax-entry ?
' "\"" table
)
494 (modify-syntax-entry ?
` "$" table
)
496 "Syntax table for Python files.")
498 (defvar python-dotty-syntax-table
499 (let ((table (make-syntax-table python-mode-syntax-table
)))
500 (modify-syntax-entry ?.
"w" table
)
501 (modify-syntax-entry ?_
"w" table
)
503 "Dotty syntax table for Python files.
504 It makes underscores and dots word constituent chars.")
509 (defcustom python-indent-offset
4
510 "Default indentation offset for Python."
515 (defcustom python-indent-guess-indent-offset t
516 "Non-nil tells Python mode to guess `python-indent-offset' value."
521 (defvar python-indent-current-level
0
522 "Current indentation level `python-indent-line-function' is using.")
524 (defvar python-indent-levels
'(0)
525 "Levels of indentation available for `python-indent-line-function'.")
527 (defvar python-indent-dedenters
'("else" "elif" "except" "finally")
528 "List of words that should be dedented.
529 These make `python-indent-calculate-indentation' subtract the value of
530 `python-indent-offset'.")
532 (defun python-indent-guess-indent-offset ()
533 "Guess and set `python-indent-offset' for the current buffer."
537 (goto-char (point-min))
539 (while (and (not found-block
)
541 (python-rx line-start block-start
) nil t
))
542 (when (and (not (python-info-ppss-context 'string
))
543 (not (python-info-ppss-context 'comment
))
545 (goto-char (line-end-position))
546 (forward-comment -
9999)
547 (eq ?
: (char-before))))
548 (setq found-block t
)))
549 (if (not found-block
)
550 (message "Can't guess python-indent-offset, using defaults: %s"
551 python-indent-offset
)
553 (goto-char (line-end-position))
554 (python-info-continuation-line-p))
558 (forward-comment 9999)
559 (let ((indent-offset (current-indentation)))
560 (when (> indent-offset
0)
561 (setq python-indent-offset indent-offset
))))))))
563 (defun python-indent-context ()
564 "Get information on indentation context.
565 Context information is returned with a cons with the form:
568 Where status can be any of the following symbols:
569 * inside-paren: If point in between (), {} or []
570 * inside-string: If point is inside a string
571 * after-backslash: Previous line ends in a backslash
572 * after-beginning-of-block: Point is after beginning of block
573 * after-line: Point is after normal line
574 * no-indent: Point is at beginning of buffer or other special case
575 START is the buffer position where the sexp starts."
578 (let ((ppss (save-excursion (beginning-of-line) (syntax-ppss)))
582 ;; Beginning of buffer
584 (goto-char (line-beginning-position))
588 ((setq start
(python-info-ppss-context 'paren ppss
))
591 ((setq start
(python-info-ppss-context 'string ppss
))
594 ((setq start
(when (not (or (python-info-ppss-context 'string ppss
)
595 (python-info-ppss-context 'comment ppss
)))
596 (let ((line-beg-pos (line-beginning-position)))
597 (when (eq ?
\\ (char-before (1- line-beg-pos
)))
598 (- line-beg-pos
2)))))
600 ;; After beginning of block
601 ((setq start
(save-excursion
602 (let ((block-regexp (python-rx block-start
))
603 (block-start-line-end ":[[:space:]]*$"))
604 (back-to-indentation)
605 (forward-comment -
9999)
606 (back-to-indentation)
607 (when (or (python-info-continuation-line-p)
608 (and (not (looking-at block-regexp
))
612 (line-end-position) t
))))
613 (while (and (forward-line -
1)
614 (python-info-continuation-line-p)
616 (back-to-indentation)
617 (when (not (looking-at block-regexp
))
619 (back-to-indentation)
620 (when (and (looking-at block-regexp
)
621 (or (re-search-forward
623 (line-end-position) t
)
625 (goto-char (line-end-position))
626 (python-info-continuation-line-p))))
628 'after-beginning-of-block
)
630 ((setq start
(save-excursion
631 (back-to-indentation)
632 (forward-comment -
9999)
633 (python-nav-sentence-start)
640 (defun python-indent-calculate-indentation ()
641 "Calculate correct indentation offset for the current line."
642 (let* ((indentation-context (python-indent-context))
643 (context-status (car indentation-context
))
644 (context-start (cdr indentation-context
)))
650 ('after-beginning-of-block
651 (goto-char context-start
)
652 (+ (current-indentation) python-indent-offset
))
656 (goto-char context-start
)
657 (current-indentation))
659 (back-to-indentation)
660 (looking-at (regexp-opt python-indent-dedenters
)))
664 (goto-char context-start
)
665 (current-indentation))
667 (let* ((block-continuation
670 (python-info-block-continuation-line-p)))
671 (assignment-continuation
674 (python-info-assignment-continuation-line-p)))
677 (back-to-indentation)
678 (when (looking-at "\\.")
680 (goto-char (line-end-position))
681 (while (and (re-search-backward "\\." (line-beginning-position) t
)
682 (or (python-info-ppss-context 'comment
)
683 (python-info-ppss-context 'string
)
684 (python-info-ppss-context 'paren
))))
685 (if (and (looking-at "\\.")
686 (not (or (python-info-ppss-context 'comment
)
687 (python-info-ppss-context 'string
)
688 (python-info-ppss-context 'paren
))))
690 (+ (current-indentation) python-indent-offset
)))))
695 (goto-char block-continuation
)
697 (python-rx block-start
(* space
))
698 (line-end-position) t
)
700 (assignment-continuation
701 (goto-char assignment-continuation
)
703 (python-rx simple-operator
)
704 (line-end-position) t
)
707 (python-rx (* space
))
708 (line-end-position) t
)
711 (goto-char context-start
)
714 (back-to-indentation)
716 "\\(?:return\\|from\\|import\\)\s+")))
717 (current-indentation)
718 (+ (current-indentation)
720 (match-string-no-properties 0))))))))
724 (skip-syntax-forward "\s" (line-end-position))
725 (when (and (looking-at (regexp-opt '(")" "]" "}")))
726 (not (forward-char 1))
727 (not (python-info-ppss-context 'paren
)))
728 (goto-char context-start
)
729 (back-to-indentation)
733 (goto-char context-start
)
737 (line-beginning-position)
739 (forward-comment 9999))
741 (+ (current-indentation) python-indent-offset
)
742 (forward-comment 9999)
745 (back-to-indentation)
746 (looking-at (regexp-opt '(")" "]" "}"))))
750 (defun python-indent-calculate-levels ()
751 "Calculate `python-indent-levels' and reset `python-indent-current-level'."
752 (let* ((indentation (python-indent-calculate-indentation))
753 (remainder (% indentation python-indent-offset
))
754 (steps (/ (- indentation remainder
) python-indent-offset
)))
755 (setq python-indent-levels
(list 0))
756 (dotimes (step steps
)
757 (push (* python-indent-offset
(1+ step
)) python-indent-levels
))
758 (when (not (eq 0 remainder
))
759 (push (+ (* python-indent-offset steps
) remainder
) python-indent-levels
))
760 (setq python-indent-levels
(nreverse python-indent-levels
))
761 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
763 (defun python-indent-toggle-levels ()
764 "Toggle `python-indent-current-level' over `python-indent-levels'."
765 (setq python-indent-current-level
(1- python-indent-current-level
))
766 (when (< python-indent-current-level
0)
767 (setq python-indent-current-level
(1- (length python-indent-levels
)))))
769 (defun python-indent-line (&optional force-toggle
)
770 "Internal implementation of `python-indent-line-function'.
771 Uses the offset calculated in
772 `python-indent-calculate-indentation' and available levels
773 indicated by the variable `python-indent-levels' to set the
776 When the variable `last-command' is equal to
777 `indent-for-tab-command' or FORCE-TOGGLE is non-nil it cycles
778 levels indicated in the variable `python-indent-levels' by
779 setting the current level in the variable
780 `python-indent-current-level'.
782 When the variable `last-command' is not equal to
783 `indent-for-tab-command' and FORCE-TOGGLE is nil it calculates
784 possible indentation levels and saves it in the variable
785 `python-indent-levels'. Afterwards it sets the variable
786 `python-indent-current-level' correctly so offset is equal
787 to (`nth' `python-indent-current-level' `python-indent-levels')"
788 (if (or (and (eq this-command
'indent-for-tab-command
)
789 (eq last-command this-command
))
791 (if (not (equal python-indent-levels
'(0)))
792 (python-indent-toggle-levels)
793 (python-indent-calculate-levels))
794 (python-indent-calculate-levels))
796 (delete-horizontal-space)
797 (indent-to (nth python-indent-current-level python-indent-levels
))
800 (let ((closing-block-point (python-info-closing-block)))
801 (when closing-block-point
802 (message "Closes %s" (buffer-substring
805 (goto-char closing-block-point
)
806 (line-end-position))))))))
808 (defun python-indent-line-function ()
809 "`indent-line-function' for Python mode.
810 See `python-indent-line' for details."
811 (python-indent-line))
813 (defun python-indent-dedent-line ()
814 "De-indent current line."
816 (when (and (not (or (python-info-ppss-context 'string
)
817 (python-info-ppss-context 'comment
)))
818 (<= (point-marker) (save-excursion
819 (back-to-indentation)
821 (> (current-column) 0))
822 (python-indent-line t
)
825 (defun python-indent-dedent-line-backspace (arg)
826 "De-indent current line.
827 Argument ARG is passed to `backward-delete-char-untabify' when
828 point is not in between the indentation."
830 (when (not (python-indent-dedent-line))
831 (backward-delete-char-untabify arg
)))
832 (put 'python-indent-dedent-line-backspace
'delete-selection
'supersede
)
834 (defun python-indent-region (start end
)
835 "Indent a python region automagically.
837 Called from a program, START and END specify the region to indent."
838 (let ((deactivate-mark nil
))
841 (setq end
(point-marker))
843 (or (bolp) (forward-line 1))
844 (while (< (point) end
)
845 (or (and (bolp) (eolp))
848 (back-to-indentation)
849 (setq word
(current-word))
853 (delete-horizontal-space)
854 (indent-to (python-indent-calculate-indentation)))))
856 (move-marker end nil
))))
858 (defun python-indent-shift-left (start end
&optional count
)
859 "Shift lines contained in region START END by COUNT columns to the left.
860 COUNT defaults to `python-indent-offset'. If region isn't
861 active, the current line is shifted. The shifted region includes
862 the lines in which START and END lie. An error is signaled if
863 any lines in the region are indented less than COUNT columns."
866 (list (region-beginning) (region-end) current-prefix-arg
)
867 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
869 (setq count
(prefix-numeric-value count
))
870 (setq count python-indent-offset
))
872 (let ((deactivate-mark nil
))
875 (while (< (point) end
)
876 (if (and (< (current-indentation) count
)
877 (not (looking-at "[ \t]*$")))
878 (error "Can't shift all lines enough"))
880 (indent-rigidly start end
(- count
))))))
882 (add-to-list 'debug-ignored-errors
"^Can't shift all lines enough")
884 (defun python-indent-shift-right (start end
&optional count
)
885 "Shift lines contained in region START END by COUNT columns to the left.
886 COUNT defaults to `python-indent-offset'. If region isn't
887 active, the current line is shifted. The shifted region includes
888 the lines in which START and END lie."
891 (list (region-beginning) (region-end) current-prefix-arg
)
892 (list (line-beginning-position) (line-end-position) current-prefix-arg
)))
893 (let ((deactivate-mark nil
))
895 (setq count
(prefix-numeric-value count
))
896 (setq count python-indent-offset
))
897 (indent-rigidly start end count
)))
899 (defun python-indent-electric-colon (arg)
900 "Insert a colon and maybe de-indent the current line.
901 With numeric ARG, just insert that many colons. With
902 \\[universal-argument], just insert a single colon."
904 (self-insert-command (if (not (integerp arg
)) 1 arg
))
907 (not (equal ?
: (char-after (- (point-marker) 2))))
908 (not (or (python-info-ppss-context 'string
)
909 (python-info-ppss-context 'comment
))))
910 (let ((indentation (current-indentation))
911 (calculated-indentation (python-indent-calculate-indentation)))
912 (when (> indentation calculated-indentation
)
914 (indent-line-to calculated-indentation
)
915 (when (not (python-info-closing-block))
916 (indent-line-to indentation
)))))))
917 (put 'python-indent-electric-colon
'delete-selection t
)
922 (defvar python-nav-beginning-of-defun-regexp
923 (python-rx line-start
(* space
) defun
(+ space
) (group symbol-name
))
924 "Regexp matching class or function definition.
925 The name of the defun should be grouped so it can be retrieved
926 via `match-string'.")
928 (defun python-nav-beginning-of-defun (&optional nodecorators
)
929 "Move point to `beginning-of-defun'.
930 When NODECORATORS is non-nil decorators are not included. This
931 is the main part of`python-beginning-of-defun-function'
932 implementation. Return non-nil if point is moved to the
933 `beginning-of-defun'."
934 (let ((indent-pos (save-excursion
935 (back-to-indentation)
940 (when (not nodecorators
)
941 (when (save-excursion
943 (looking-at (python-rx decorator
)))
944 (while (and (not (bobp))
946 (looking-at (python-rx decorator
))))
947 (when (not (bobp)) (forward-line 1)))))))
948 (if (and (> (point) indent-pos
)
950 (goto-char (line-beginning-position))
951 (looking-at python-nav-beginning-of-defun-regexp
)))
953 (goto-char (line-beginning-position))
954 (funcall include-decorators
)
956 (goto-char (line-beginning-position))
957 (when (re-search-backward python-nav-beginning-of-defun-regexp nil t
)
959 (goto-char (or (python-info-ppss-context 'string
) (point)))
960 (funcall include-decorators
))
963 (defun python-beginning-of-defun-function (&optional arg nodecorators
)
964 "Move point to the beginning of def or class.
965 With positive ARG move that number of functions forward. With
966 negative do the same but backwards. When NODECORATORS is non-nil
967 decorators are not included. Return non-nil if point is moved to the
968 `beginning-of-defun'."
969 (when (or (null arg
) (= arg
0)) (setq arg
1))
971 (dotimes (i arg
(python-nav-beginning-of-defun nodecorators)))
973 (dotimes (i (- arg
) found
)
974 (python-end-of-defun-function)
975 (forward-comment 9999)
976 (goto-char (line-end-position))
979 (python-nav-beginning-of-defun nodecorators)))))))
981 (defun python-end-of-defun-function ()
982 "Move point to the end of def or class.
983 Returns nil if point is not in a def or class."
985 (let ((beg-defun-indent)
986 (decorator-regexp "[[:space:]]*@"))
987 (when (looking-at decorator-regexp
)
988 (while (and (not (eobp))
990 (looking-at decorator-regexp
))))
991 (when (not (looking-at python-nav-beginning-of-defun-regexp
))
992 (python-beginning-of-defun-function))
993 (setq beg-defun-indent
(current-indentation))
995 (while (and (forward-line 1)
997 (or (not (current-word))
998 (> (current-indentation) beg-defun-indent
))))
999 (forward-comment 9999)
1000 (goto-char (line-beginning-position))))
1002 (defun python-nav-sentence-start ()
1003 "Move to start of current sentence."
1005 (while (and (not (back-to-indentation))
1010 (python-info-line-ends-backslash-p))
1011 (python-info-ppss-context 'string
)
1012 (python-info-ppss-context 'paren
))
1013 (forward-line -
1)))))
1015 (defun python-nav-sentence-end ()
1016 "Move to end of current sentence."
1018 (while (and (goto-char (line-end-position))
1021 (python-info-line-ends-backslash-p)
1022 (python-info-ppss-context 'string
)
1023 (python-info-ppss-context 'paren
))
1024 (forward-line 1)))))
1026 (defun python-nav-backward-sentence (&optional arg
)
1027 "Move backward to start of sentence. With ARG, do it arg times.
1028 See `python-nav-forward-sentence' for more information."
1030 (or arg
(setq arg
1))
1031 (python-nav-forward-sentence (- arg
)))
1033 (defun python-nav-forward-sentence (&optional arg
)
1034 "Move forward to next end of sentence. With ARG, repeat.
1035 With negative argument, move backward repeatedly to start of sentence."
1037 (or arg
(setq arg
1))
1039 (forward-comment 9999)
1040 (python-nav-sentence-end)
1042 (setq arg
(1- arg
)))
1044 (python-nav-sentence-end)
1045 (forward-comment -
9999)
1046 (python-nav-sentence-start)
1048 (setq arg
(1+ arg
))))
1050 (defun python-nav-list-defun-positions (&optional include-type
)
1051 "Make an Alist of defun names and point markers for current buffer.
1052 When optional argument INCLUDE-TYPE is non-nil the type is
1053 included the defun name."
1058 (goto-char (point-max))
1059 (while (re-search-backward python-nav-beginning-of-defun-regexp nil t
)
1060 (when (and (not (python-info-ppss-context 'string
))
1061 (not (python-info-ppss-context 'comment
))
1062 (not (python-info-ppss-context 'parent
)))
1065 (python-info-current-defun include-type)
1069 (defun python-nav-read-defun ()
1070 "Read a defun name of current buffer and return its point marker.
1071 A cons cell with the form (DEFUN-NAME . POINT-MARKER) is returned
1072 when defun is completed, else nil."
1073 (let ((defs (python-nav-list-defun-positions)))
1074 (minibuffer-with-setup-hook
1076 (setq minibuffer-completion-table
(mapcar 'car defs
)))
1078 (read-from-minibuffer
1079 "Jump to definition: " nil
1080 minibuffer-local-must-match-map
)))
1081 (when (not (string= stringdef
""))
1082 (assoc-string stringdef defs
))))))
1084 (defun python-nav-jump-to-defun (def)
1085 "Jump to the definition of DEF in current file."
1087 (list (python-nav-read-defun)))
1088 (when (not (called-interactively-p 'interactive
))
1089 (setq def
(assoc-string def
(python-nav-list-defun-positions))))
1090 (let ((def-marker (cdr def
)))
1091 (when (markerp def-marker
)
1092 (goto-char (marker-position def-marker
))
1093 (back-to-indentation))))
1096 ;;; Shell integration
1098 (defcustom python-shell-buffer-name
"Python"
1099 "Default buffer name for Python interpreter."
1104 (defcustom python-shell-interpreter
"python"
1105 "Default Python interpreter for shell."
1109 (defcustom python-shell-internal-buffer-name
"Python Internal"
1110 "Default buffer name for the Internal Python interpreter."
1115 (defcustom python-shell-interpreter-args
"-i"
1116 "Default arguments for the Python interpreter."
1120 (defcustom python-shell-prompt-regexp
">>> "
1121 "Regular Expression matching top\-level input prompt of python shell.
1122 It should not contain a caret (^) at the beginning."
1127 (defcustom python-shell-prompt-block-regexp
"[.][.][.] "
1128 "Regular Expression matching block input prompt of python shell.
1129 It should not contain a caret (^) at the beginning."
1134 (defcustom python-shell-prompt-output-regexp
""
1135 "Regular Expression matching output prompt of python shell.
1136 It should not contain a caret (^) at the beginning."
1141 (defcustom python-shell-prompt-pdb-regexp
"[(<]*[Ii]?[Pp]db[>)]+ "
1142 "Regular Expression matching pdb input prompt of python shell.
1143 It should not contain a caret (^) at the beginning."
1148 (defcustom python-shell-send-setup-max-wait
5
1149 "Seconds to wait for process output before code setup.
1150 If output is received before the especified time then control is
1151 returned in that moment and not after waiting."
1156 (defcustom python-shell-process-environment nil
1157 "List of environment variables for Python shell.
1158 This variable follows the same rules as `process-environment'
1159 since it merges with it before the process creation routines are
1160 called. When this variable is nil, the Python shell is run with
1161 the default `process-environment'."
1162 :type
'(repeat string
)
1166 (defcustom python-shell-extra-pythonpaths nil
1167 "List of extra pythonpaths for Python shell.
1168 The values of this variable are added to the existing value of
1169 PYTHONPATH in the `process-environment' variable."
1170 :type
'(repeat string
)
1174 (defcustom python-shell-exec-path nil
1175 "List of path to search for binaries.
1176 This variable follows the same rules as `exec-path' since it
1177 merges with it before the process creation routines are called.
1178 When this variable is nil, the Python shell is run with the
1179 default `exec-path'."
1180 :type
'(repeat string
)
1184 (defcustom python-shell-virtualenv-path nil
1185 "Path to virtualenv root.
1186 This variable, when set to a string, makes the values stored in
1187 `python-shell-process-environment' and `python-shell-exec-path'
1188 to be modified properly so shells are started with the specified
1194 (defcustom python-shell-setup-codes
'(python-shell-completion-setup-code
1195 python-ffap-setup-code
1196 python-eldoc-setup-code
)
1197 "List of code run by `python-shell-send-setup-codes'."
1198 :type
'(repeat symbol
)
1202 (defcustom python-shell-compilation-regexp-alist
1203 `((,(rx line-start
(1+ (any " \t")) "File \""
1204 (group (1+ (not (any "\"<")))) ; avoid `<stdin>' &c
1205 "\", line " (group (1+ digit
)))
1207 (,(rx " in file " (group (1+ not-newline
)) " on line "
1210 (,(rx line-start
"> " (group (1+ (not (any "(\"<"))))
1211 "(" (group (1+ digit
)) ")" (1+ (not (any "("))) "()")
1213 "`compilation-error-regexp-alist' for inferior Python."
1214 :type
'(alist string
)
1217 (defun python-shell-get-process-name (dedicated)
1218 "Calculate the appropriate process name for inferior Python process.
1219 If DEDICATED is t and the variable `buffer-file-name' is non-nil
1220 returns a string with the form
1221 `python-shell-buffer-name'[variable `buffer-file-name'] else
1222 returns the value of `python-shell-buffer-name'. After
1223 calculating the process name adds the buffer name for the process
1224 in the `same-window-buffer-names' list."
1228 (format "%s[%s]" python-shell-buffer-name buffer-file-name
)
1229 (format "%s" python-shell-buffer-name
))))
1230 (add-to-list 'same-window-buffer-names
(purecopy
1231 (format "*%s*" process-name
)))
1234 (defun python-shell-internal-get-process-name ()
1235 "Calculate the appropriate process name for Internal Python process.
1236 The name is calculated from `python-shell-global-buffer-name' and
1237 a hash of all relevant global shell settings in order to ensure
1238 uniqueness for different types of configurations."
1240 python-shell-internal-buffer-name
1243 (python-shell-parse-command)
1244 python-shell-prompt-regexp
1245 python-shell-prompt-block-regexp
1246 python-shell-prompt-output-regexp
1247 (mapconcat #'symbol-value python-shell-setup-codes
"")
1248 (mapconcat #'identity python-shell-process-environment
"")
1249 (mapconcat #'identity python-shell-extra-pythonpaths
"")
1250 (mapconcat #'identity python-shell-exec-path
"")
1251 (or python-shell-virtualenv-path
"")
1252 (mapconcat #'identity python-shell-exec-path
"")))))
1254 (defun python-shell-parse-command ()
1255 "Calculate the string used to execute the inferior Python process."
1256 (format "%s %s" python-shell-interpreter python-shell-interpreter-args
))
1258 (defun python-shell-calculate-process-environment ()
1259 "Calculate process environment given `python-shell-virtualenv-path'."
1260 (let ((process-environment (append
1261 python-shell-process-environment
1262 process-environment nil
))
1263 (virtualenv (if python-shell-virtualenv-path
1264 (directory-file-name python-shell-virtualenv-path
)
1266 (when python-shell-extra-pythonpaths
1267 (setenv "PYTHONPATH"
1269 (mapconcat 'identity
1270 python-shell-extra-pythonpaths
1273 (or (getenv "PYTHONPATH") ""))))
1274 (if (not virtualenv
)
1276 (setenv "PYTHONHOME" nil
)
1277 (setenv "PATH" (format "%s/bin%s%s"
1278 virtualenv path-separator
1279 (or (getenv "PATH") "")))
1280 (setenv "VIRTUAL_ENV" virtualenv
))
1281 process-environment
))
1283 (defun python-shell-calculate-exec-path ()
1284 "Calculate exec path given `python-shell-virtualenv-path'."
1285 (let ((path (append python-shell-exec-path
1287 (if (not python-shell-virtualenv-path
)
1289 (cons (format "%s/bin"
1290 (directory-file-name python-shell-virtualenv-path
))
1293 (defun python-comint-output-filter-function (output)
1294 "Hook run after content is put into comint buffer.
1295 OUTPUT is a string with the contents of the buffer."
1296 (ansi-color-filter-apply output
))
1298 (define-derived-mode inferior-python-mode comint-mode
"Inferior Python"
1299 "Major mode for Python inferior process.
1300 Runs a Python interpreter as a subprocess of Emacs, with Python
1301 I/O through an Emacs buffer. Variables
1302 `python-shell-interpreter' and `python-shell-interpreter-args'
1303 controls which Python interpreter is run. Variables
1304 `python-shell-prompt-regexp',
1305 `python-shell-prompt-output-regexp',
1306 `python-shell-prompt-block-regexp',
1307 `python-shell-completion-setup-code',
1308 `python-shell-completion-string-code',
1309 `python-shell-completion-module-string-code',
1310 `python-eldoc-setup-code', `python-eldoc-string-code',
1311 `python-ffap-setup-code' and `python-ffap-string-code' can
1312 customize this mode for different Python interpreters.
1314 You can also add additional setup code to be run at
1315 initialization of the interpreter via `python-shell-setup-codes'
1318 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1319 (set-syntax-table python-mode-syntax-table
)
1320 (setq mode-line-process
'(":%s"))
1321 (setq comint-prompt-regexp
(format "^\\(?:%s\\|%s\\|%s\\)"
1322 python-shell-prompt-regexp
1323 python-shell-prompt-block-regexp
1324 python-shell-prompt-pdb-regexp
))
1325 (make-local-variable 'comint-output-filter-functions
)
1326 (add-hook 'comint-output-filter-functions
1327 'python-comint-output-filter-function
)
1328 (add-hook 'comint-output-filter-functions
1329 'python-pdbtrack-comint-output-filter-function
)
1330 (set (make-local-variable 'compilation-error-regexp-alist
)
1331 python-shell-compilation-regexp-alist
)
1332 (define-key inferior-python-mode-map
[remap complete-symbol
]
1333 'completion-at-point
)
1334 (add-hook 'completion-at-point-functions
1335 'python-shell-completion-complete-at-point nil
'local
)
1336 (add-to-list (make-local-variable 'comint-dynamic-complete-functions
)
1337 'python-shell-completion-complete-at-point
)
1338 (define-key inferior-python-mode-map
(kbd "<tab>")
1339 'python-shell-completion-complete-or-indent
)
1340 (compilation-shell-minor-mode 1))
1342 (defun python-shell-make-comint (cmd proc-name
&optional pop
)
1343 "Create a python shell comint buffer.
1344 CMD is the python command to be executed and PROC-NAME is the
1345 process name the comint buffer will get. After the comint buffer
1346 is created the `inferior-python-mode' is activated. If POP is
1347 non-nil the buffer is shown."
1349 (let* ((proc-buffer-name (format "*%s*" proc-name
))
1350 (process-environment (python-shell-calculate-process-environment))
1351 (exec-path (python-shell-calculate-exec-path)))
1352 (when (not (comint-check-proc proc-buffer-name
))
1353 (let* ((cmdlist (split-string-and-unquote cmd
))
1354 (buffer (apply 'make-comint proc-name
(car cmdlist
) nil
1356 (current-buffer (current-buffer)))
1357 (with-current-buffer buffer
1358 (inferior-python-mode)
1359 (python-util-clone-local-variables current-buffer
))))
1361 (pop-to-buffer proc-buffer-name
))
1364 (defun run-python (dedicated cmd
)
1365 "Run an inferior Python process.
1366 Input and output via buffer named after
1367 `python-shell-buffer-name'. If there is a process already
1368 running in that buffer, just switch to it.
1369 With argument, allows you to define DEDICATED, so a dedicated
1370 process for the current buffer is open, and define CMD so you can
1371 edit the command used to call the interpreter (default is value
1372 of `python-shell-interpreter' and arguments defined in
1373 `python-shell-interpreter-args'). Runs the hook
1374 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1376 \(Type \\[describe-mode] in the process buffer for a list of commands.)"
1378 (if current-prefix-arg
1380 (y-or-n-p "Make dedicated process? ")
1381 (read-string "Run Python: " (python-shell-parse-command)))
1382 (list nil
(python-shell-parse-command))))
1383 (python-shell-make-comint cmd
(python-shell-get-process-name dedicated
) t
)
1386 (defun run-python-internal ()
1387 "Run an inferior Internal Python process.
1388 Input and output via buffer named after
1389 `python-shell-internal-buffer-name' and what
1390 `python-shell-internal-get-process-name' returns. This new kind
1391 of shell is intended to be used for generic communication related
1392 to defined configurations. The main difference with global or
1393 dedicated shells is that these ones are attached to a
1394 configuration, not a buffer. This means that can be used for
1395 example to retrieve the sys.path and other stuff, without messing
1396 with user shells. Runs the hook
1397 `inferior-python-mode-hook' (after the `comint-mode-hook' is
1398 run). \(Type \\[describe-mode] in the process buffer for a list
1401 (set-process-query-on-exit-flag
1403 (python-shell-make-comint
1404 (python-shell-parse-command)
1405 (python-shell-internal-get-process-name))) nil
))
1407 (defun python-shell-get-process ()
1408 "Get inferior Python process for current buffer and return it."
1409 (let* ((dedicated-proc-name (python-shell-get-process-name t
))
1410 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1411 (global-proc-name (python-shell-get-process-name nil
))
1412 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1413 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1414 (global-running (comint-check-proc global-proc-buffer-name
)))
1415 ;; Always prefer dedicated
1416 (get-buffer-process (or (and dedicated-running dedicated-proc-buffer-name
)
1417 (and global-running global-proc-buffer-name
)))))
1419 (defun python-shell-get-or-create-process ()
1420 "Get or create an inferior Python process for current buffer and return it."
1421 (let* ((old-buffer (current-buffer))
1422 (dedicated-proc-name (python-shell-get-process-name t
))
1423 (dedicated-proc-buffer-name (format "*%s*" dedicated-proc-name
))
1424 (global-proc-name (python-shell-get-process-name nil
))
1425 (global-proc-buffer-name (format "*%s*" global-proc-name
))
1426 (dedicated-running (comint-check-proc dedicated-proc-buffer-name
))
1427 (global-running (comint-check-proc global-proc-buffer-name
))
1428 (current-prefix-arg 4))
1429 (when (and (not dedicated-running
) (not global-running
))
1430 (if (call-interactively 'run-python
)
1431 (setq dedicated-running t
)
1432 (setq global-running t
)))
1433 ;; Always prefer dedicated
1434 (switch-to-buffer old-buffer
)
1435 (get-buffer-process (if dedicated-running
1436 dedicated-proc-buffer-name
1437 global-proc-buffer-name
))))
1439 (defvar python-shell-internal-buffer nil
1440 "Current internal shell buffer for the current buffer.
1441 This is really not necessary at all for the code to work but it's
1442 there for compatibility with CEDET.")
1443 (make-variable-buffer-local 'python-shell-internal-buffer
)
1445 (defun python-shell-internal-get-or-create-process ()
1446 "Get or create an inferior Internal Python process."
1447 (let* ((proc-name (python-shell-internal-get-process-name))
1448 (proc-buffer-name (format "*%s*" proc-name
)))
1449 (run-python-internal)
1450 (setq python-shell-internal-buffer proc-buffer-name
)
1451 (get-buffer-process proc-buffer-name
)))
1453 (define-obsolete-function-alias
1454 'python-proc
'python-shell-internal-get-or-create-process
"23.3")
1456 (define-obsolete-variable-alias
1457 'python-buffer
'python-shell-internal-buffer
"23.3")
1459 (defun python-shell-send-string (string &optional process msg
)
1460 "Send STRING to inferior Python PROCESS.
1461 When MSG is non-nil messages the first line of STRING."
1462 (interactive "sPython command: ")
1463 (let ((process (or process
(python-shell-get-or-create-process)))
1464 (lines (split-string string
"\n" t
)))
1466 (message (format "Sent: %s..." (nth 0 lines
))))
1467 (if (> (length lines
) 1)
1468 (let* ((temp-file-name (make-temp-file "py"))
1469 (file-name (or (buffer-file-name) temp-file-name
)))
1470 (with-temp-file temp-file-name
1472 (delete-trailing-whitespace))
1473 (python-shell-send-file file-name process temp-file-name
))
1474 (comint-send-string process string
)
1475 (when (or (not (string-match "\n$" string
))
1476 (string-match "\n[ \t].*\n?$" string
))
1477 (comint-send-string process
"\n")))))
1479 (defun python-shell-send-string-no-output (string &optional process msg
)
1480 "Send STRING to PROCESS and inhibit output.
1481 When MSG is non-nil messages the first line of STRING. Return
1483 (let* ((output-buffer)
1484 (process (or process
(python-shell-get-or-create-process)))
1485 (comint-preoutput-filter-functions
1486 (append comint-preoutput-filter-functions
1487 '(ansi-color-filter-apply
1489 (setq output-buffer
(concat output-buffer string
))
1491 (python-shell-send-string string process msg
)
1492 (accept-process-output process
)
1493 (replace-regexp-in-string
1494 (if (> (length python-shell-prompt-output-regexp
) 0)
1495 (format "\n*%s$\\|^%s\\|\n$"
1496 python-shell-prompt-regexp
1497 (or python-shell-prompt-output-regexp
""))
1498 (format "\n*$\\|^%s\\|\n$"
1499 python-shell-prompt-regexp
))
1502 (defun python-shell-internal-send-string (string)
1503 "Send STRING to the Internal Python interpreter.
1504 Returns the output. See `python-shell-send-string-no-output'."
1505 (python-shell-send-string-no-output
1506 ;; Makes this function compatible with the old
1507 ;; python-send-receive. (At least for CEDET).
1508 (replace-regexp-in-string "_emacs_out +" "" string
)
1509 (python-shell-internal-get-or-create-process) nil
))
1511 (define-obsolete-function-alias
1512 'python-send-receive
'python-shell-internal-send-string
"23.3")
1514 (define-obsolete-function-alias
1515 'python-send-string
'python-shell-internal-send-string
"23.3")
1517 (defun python-shell-send-region (start end
)
1518 "Send the region delimited by START and END to inferior Python process."
1520 (let ((deactivate-mark nil
))
1521 (python-shell-send-string (buffer-substring start end
) nil t
)))
1523 (defun python-shell-send-buffer ()
1524 "Send the entire buffer to inferior Python process."
1528 (python-shell-send-region (point-min) (point-max))))
1530 (defun python-shell-send-defun (arg)
1531 "Send the current defun to inferior Python process.
1532 When argument ARG is non-nil sends the innermost defun."
1535 (python-shell-send-region
1537 (or (python-beginning-of-defun-function)
1538 (progn (beginning-of-line) (point-marker))))
1540 (or (python-end-of-defun-function)
1541 (progn (end-of-line) (point-marker)))))))
1543 (defun python-shell-send-file (file-name &optional process temp-file-name
)
1544 "Send FILE-NAME to inferior Python PROCESS.
1545 If TEMP-FILE-NAME is passed then that file is used for processing
1546 instead, while internally the shell will continue to use
1548 (interactive "fFile to send: ")
1549 (let* ((process (or process
(python-shell-get-or-create-process)))
1550 (temp-file-name (when temp-file-name
1551 (expand-file-name temp-file-name
)))
1552 (file-name (or (expand-file-name file-name
) temp-file-name
)))
1553 (when (not file-name
)
1554 (error "If FILE-NAME is nil then TEMP-FILE-NAME must be non-nil"))
1555 (python-shell-send-string
1557 (concat "__pyfile = open('''%s''');"
1558 "exec(compile(__pyfile.read(), '''%s''', 'exec'));"
1560 (or temp-file-name file-name
) file-name
)
1563 (defun python-shell-switch-to-shell ()
1564 "Switch to inferior Python process buffer."
1566 (pop-to-buffer (process-buffer (python-shell-get-or-create-process)) t
))
1568 (defun python-shell-send-setup-code ()
1569 "Send all setup code for shell.
1570 This function takes the list of setup code to send from the
1571 `python-shell-setup-codes' list."
1572 (let ((msg "Sent %s")
1573 (process (get-buffer-process (current-buffer))))
1574 (accept-process-output process python-shell-send-setup-max-wait
)
1575 (dolist (code python-shell-setup-codes
)
1577 (message (format msg code
))
1578 (python-shell-send-string
1579 (symbol-value code
) process
)))))
1581 (add-hook 'inferior-python-mode-hook
1582 #'python-shell-send-setup-code
)
1585 ;;; Shell completion
1587 (defcustom python-shell-completion-setup-code
1591 def __COMPLETER_all_completions(text): []
1594 readline.set_completer(rlcompleter.Completer().complete)
1595 def __COMPLETER_all_completions(text):
1601 res = readline.get_completer()(text, i)
1604 completions.append(res)
1608 "Code used to setup completion in inferior Python processes."
1612 (defcustom python-shell-completion-string-code
1613 "';'.join(__COMPLETER_all_completions('''%s'''))\n"
1614 "Python code used to get a string of completions separated by semicolons."
1618 (defcustom python-shell-completion-module-string-code
""
1619 "Python code used to get completions separated by semicolons for imports.
1621 For IPython v0.11, add the following line to
1622 `python-shell-completion-setup-code':
1624 from IPython.core.completerlib import module_completion
1626 and use the following as the value of this variable:
1628 ';'.join(module_completion('''%s'''))\n"
1632 (defcustom python-shell-completion-pdb-string-code
1633 "';'.join(globals().keys() + locals().keys())"
1634 "Python code used to get completions separated by semicolons for [i]pdb."
1638 (defvar python-shell-completion-original-window-configuration nil
)
1640 (defun python-shell-completion--get-completions (input process completion-code
)
1641 "Retrieve available completions for INPUT using PROCESS.
1642 Argument COMPLETION-CODE is the python code used to get
1643 completions on the current context."
1644 (with-current-buffer (process-buffer process
)
1645 (let ((completions (python-shell-send-string-no-output
1646 (format completion-code input
) process
)))
1647 (when (> (length completions
) 2)
1648 (split-string completions
"^'\\|^\"\\|;\\|'$\\|\"$" t
)))))
1650 (defun python-shell-completion--do-completion-at-point (process)
1651 "Do completion at point for PROCESS."
1652 (with-syntax-table python-dotty-syntax-table
1653 (let* ((line (substring-no-properties
1654 (buffer-substring (point-at-bol) (point)) nil nil
))
1655 (input (substring-no-properties
1656 (or (comint-word (current-word)) "") nil nil
))
1657 (prompt (buffer-substring-no-properties
1658 (overlay-start comint-last-prompt-overlay
)
1659 (overlay-end comint-last-prompt-overlay
)))
1661 (cond ((and (> (length python-shell-completion-pdb-string-code
) 0)
1663 (concat "^" python-shell-prompt-pdb-regexp
) prompt
))
1664 python-shell-completion-pdb-string-code
)
1665 ((and (> (length python-shell-completion-module-string-code
) 0)
1667 (concat "^" python-shell-prompt-regexp
) prompt
)
1668 (string-match "^\\(from\\|import\\)[ \t]" line
))
1669 python-shell-completion-module-string-code
)
1671 (concat "^" python-shell-prompt-regexp
) prompt
)
1672 python-shell-completion-string-code
)
1675 (and completion-code
(> (length input
) 0)
1676 (python-shell-completion--get-completions
1677 line process completion-code
)))
1678 (completion (when completions
1679 (try-completion input completions
))))
1680 (cond ((eq completion t
)
1681 (if (eq this-command last-command
)
1682 (when python-shell-completion-original-window-configuration
1683 (set-window-configuration
1684 python-shell-completion-original-window-configuration
)))
1685 (setq python-shell-completion-original-window-configuration nil
)
1688 (message "Can't find completion for \"%s\"" input
)
1691 ((not (string= input completion
))
1692 (progn (delete-char (- (length input
)))
1696 (unless python-shell-completion-original-window-configuration
1697 (setq python-shell-completion-original-window-configuration
1698 (current-window-configuration)))
1699 (with-output-to-temp-buffer "*Python Completions*"
1700 (display-completion-list
1701 (all-completions input completions
)))
1704 (defun python-shell-completion-complete-at-point ()
1705 "Perform completion at point in inferior Python process."
1707 (and comint-last-prompt-overlay
1708 (> (point-marker) (overlay-end comint-last-prompt-overlay
))
1709 (python-shell-completion--do-completion-at-point
1710 (get-buffer-process (current-buffer)))))
1712 (defun python-shell-completion-complete-or-indent ()
1713 "Complete or indent depending on the context.
1714 If content before pointer is all whitespace indent. If not try
1717 (if (string-match "^[[:space:]]*$"
1718 (buffer-substring (comint-line-beginning-position)
1720 (indent-for-tab-command)
1721 (comint-dynamic-complete)))
1724 ;;; PDB Track integration
1726 (defcustom python-pdbtrack-activate t
1727 "Non-nil makes python shell enable pdbtracking."
1732 (defcustom python-pdbtrack-stacktrace-info-regexp
1733 "^> \\([^\"(<]+\\)(\\([0-9]+\\))\\([?a-zA-Z0-9_<>]+\\)()"
1734 "Regular Expression matching stacktrace information.
1735 Used to extract the current line and module being inspected."
1740 (defvar python-pdbtrack-tracked-buffer nil
1741 "Variable containing the value of the current tracked buffer.
1742 Never set this variable directly, use
1743 `python-pdbtrack-set-tracked-buffer' instead.")
1744 (make-variable-buffer-local 'python-pdbtrack-tracked-buffer
)
1746 (defvar python-pdbtrack-buffers-to-kill nil
1747 "List of buffers to be deleted after tracking finishes.")
1748 (make-variable-buffer-local 'python-pdbtrack-buffers-to-kill
)
1750 (defun python-pdbtrack-set-tracked-buffer (file-name)
1751 "Set the buffer for FILE-NAME as the tracked buffer.
1752 Internally it uses the `python-pdbtrack-tracked-buffer' variable.
1753 Returns the tracked buffer."
1754 (let ((file-buffer (get-file-buffer file-name
)))
1756 (setq python-pdbtrack-tracked-buffer file-buffer
)
1757 (setq file-buffer
(find-file-noselect file-name
))
1758 (when (not (member file-buffer python-pdbtrack-buffers-to-kill
))
1759 (add-to-list 'python-pdbtrack-buffers-to-kill file-buffer
)))
1762 (defun python-pdbtrack-comint-output-filter-function (output)
1763 "Move overlay arrow to current pdb line in tracked buffer.
1764 Argument OUTPUT is a string with the output from the comint process."
1765 (when (and python-pdbtrack-activate
(not (string= output
"")))
1766 (let* ((full-output (ansi-color-filter-apply
1767 (buffer-substring comint-last-input-end
(point-max))))
1771 (insert full-output
)
1772 (goto-char (point-min))
1773 ;; OK, this sucked but now it became a cool hack. The
1774 ;; stacktrace information normally is on the first line
1775 ;; but in some cases (like when doing a step-in) it is
1777 (when (or (looking-at python-pdbtrack-stacktrace-info-regexp
)
1779 (looking-at python-pdbtrack-stacktrace-info-regexp
)))
1780 (setq line-number
(string-to-number
1781 (match-string-no-properties 2)))
1782 (match-string-no-properties 1)))))
1783 (if (and file-name line-number
)
1784 (let* ((tracked-buffer (python-pdbtrack-set-tracked-buffer file-name
))
1785 (shell-buffer (current-buffer))
1786 (tracked-buffer-window (get-buffer-window tracked-buffer
))
1787 (tracked-buffer-line-pos))
1788 (with-current-buffer tracked-buffer
1789 (set (make-local-variable 'overlay-arrow-string
) "=>")
1790 (set (make-local-variable 'overlay-arrow-position
) (make-marker))
1791 (setq tracked-buffer-line-pos
(progn
1792 (goto-char (point-min))
1793 (forward-line (1- line-number
))
1795 (when tracked-buffer-window
1797 tracked-buffer-window tracked-buffer-line-pos
))
1798 (set-marker overlay-arrow-position tracked-buffer-line-pos
))
1799 (pop-to-buffer tracked-buffer
)
1800 (switch-to-buffer-other-window shell-buffer
))
1801 (when python-pdbtrack-tracked-buffer
1802 (with-current-buffer python-pdbtrack-tracked-buffer
1803 (set-marker overlay-arrow-position nil
))
1804 (mapc #'(lambda (buffer)
1805 (ignore-errors (kill-buffer buffer
)))
1806 python-pdbtrack-buffers-to-kill
)
1807 (setq python-pdbtrack-tracked-buffer nil
1808 python-pdbtrack-buffers-to-kill nil
)))))
1812 ;;; Symbol completion
1814 (defun python-completion-complete-at-point ()
1815 "Complete current symbol at point.
1816 For this to work the best as possible you should call
1817 `python-shell-send-buffer' from time to time so context in
1818 inferior python process is updated properly."
1820 (let ((process (python-shell-get-process)))
1822 (error "Completion needs an inferior Python process running")
1823 (python-shell-completion--do-completion-at-point process
))))
1825 (add-to-list 'debug-ignored-errors
"^Completion needs an inferior Python process running.")
1830 (defcustom python-fill-comment-function
'python-fill-comment
1831 "Function to fill comments.
1832 This is the function used by `python-fill-paragraph-function' to
1838 (defcustom python-fill-string-function
'python-fill-string
1839 "Function to fill strings.
1840 This is the function used by `python-fill-paragraph-function' to
1846 (defcustom python-fill-decorator-function
'python-fill-decorator
1847 "Function to fill decorators.
1848 This is the function used by `python-fill-paragraph-function' to
1854 (defcustom python-fill-paren-function
'python-fill-paren
1855 "Function to fill parens.
1856 This is the function used by `python-fill-paragraph-function' to
1862 (defun python-fill-paragraph-function (&optional justify
)
1863 "`fill-paragraph-function' handling multi-line strings and possibly comments.
1864 If any of the current line is in or at the end of a multi-line string,
1865 fill the string or the paragraph of it that point is in, preserving
1866 the string's indentation.
1867 Optional argument JUSTIFY defines if the paragraph should be justified."
1870 (back-to-indentation)
1873 ((funcall python-fill-comment-function justify
))
1874 ;; Strings/Docstrings
1875 ((save-excursion (skip-chars-forward "\"'uUrR")
1876 (python-info-ppss-context 'string
))
1877 (funcall python-fill-string-function justify
))
1879 ((equal (char-after (save-excursion
1880 (back-to-indentation)
1881 (point-marker))) ?
@)
1882 (funcall python-fill-decorator-function justify
))
1884 ((or (python-info-ppss-context 'paren
)
1885 (looking-at (python-rx open-paren
))
1887 (skip-syntax-forward "^(" (line-end-position))
1888 (looking-at (python-rx open-paren
))))
1889 (funcall python-fill-paren-function justify
))
1892 (defun python-fill-comment (&optional justify
)
1893 "Comment fill function for `python-fill-paragraph-function'.
1894 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1895 (fill-comment-paragraph justify
))
1897 (defun python-fill-string (&optional justify
)
1898 "String fill function for `python-fill-paragraph-function'.
1899 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1900 (let ((marker (point-marker))
1901 (string-start-marker
1903 (skip-chars-forward "\"'uUrR")
1904 (goto-char (python-info-ppss-context 'string
))
1905 (skip-chars-forward "\"'uUrR")
1907 (reg-start (line-beginning-position))
1910 (while (python-info-ppss-context 'string
)
1911 (goto-char (1+ (point-marker))))
1912 (skip-chars-backward "\"'")
1914 (reg-end (line-end-position))
1915 (fill-paragraph-function))
1917 (narrow-to-region reg-start reg-end
)
1919 (goto-char string-start-marker
)
1920 (delete-region (point-marker) (progn
1921 (skip-syntax-forward "> ")
1923 (goto-char string-end-marker
)
1924 (delete-region (point-marker) (progn
1925 (skip-syntax-backward "> ")
1929 (fill-paragraph justify
))
1930 ;; If there is a newline in the docstring lets put triple
1931 ;; quote in it's own line to follow pep 8
1932 (when (save-excursion
1933 (re-search-backward "\n" string-start-marker t
))
1935 (newline-and-indent))
1936 (fill-paragraph justify
)))) t
)
1938 (defun python-fill-decorator (&optional justify
)
1939 "Decorator fill function for `python-fill-paragraph-function'.
1940 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1943 (defun python-fill-paren (&optional justify
)
1944 "Paren fill function for `python-fill-paragraph-function'.
1945 JUSTIFY should be used (if applicable) as in `fill-paragraph'."
1947 (narrow-to-region (progn
1948 (while (python-info-ppss-context 'paren
)
1949 (goto-char (1- (point-marker))))
1951 (line-beginning-position))
1953 (when (not (python-info-ppss-context 'paren
))
1955 (when (not (python-info-ppss-context 'paren
))
1956 (skip-syntax-backward "^)")))
1957 (while (python-info-ppss-context 'paren
)
1958 (goto-char (1+ (point-marker))))
1960 (let ((paragraph-start "\f\\|[ \t]*$")
1961 (paragraph-separate ",")
1962 (fill-paragraph-function))
1963 (goto-char (point-min))
1964 (fill-paragraph justify
))
1967 (python-indent-line)
1968 (goto-char (line-end-position)))) t
)
1973 (defcustom python-skeleton-autoinsert nil
1974 "Non-nil means template skeletons will be automagically inserted.
1975 This happens when pressing \"if<SPACE>\", for example, to prompt for
1981 (defvar python-skeleton-available
'()
1982 "Internal list of available skeletons.")
1984 (define-abbrev-table 'python-mode-abbrev-table
()
1985 "Abbrev table for Python mode."
1987 ;; Allow / inside abbrevs.
1988 :regexp
"\\(?:^\\|[^/]\\)\\<\\([[:word:]/]+\\)\\W*"
1989 ;; Only expand in code.
1990 :enable-function
(lambda ()
1992 (not (or (python-info-ppss-context 'string
)
1993 (python-info-ppss-context 'comment
)))
1994 python-skeleton-autoinsert
)))
1996 (defmacro python-skeleton-define
(name doc
&rest skel
)
1997 "Define a `python-mode' skeleton using NAME DOC and SKEL.
1998 The skeleton will be bound to python-skeleton-NAME and will
1999 be added to `python-mode-abbrev-table'."
2000 (let* ((name (symbol-name name
))
2001 (function-name (intern (concat "python-skeleton-" name
))))
2003 (define-abbrev python-mode-abbrev-table
,name
"" ',function-name
)
2004 (setq python-skeleton-available
2005 (cons ',function-name python-skeleton-available
))
2006 (define-skeleton ,function-name
2008 (format "Insert %s statement." name
))
2010 (put 'python-skeleton-define
'lisp-indent-function
2)
2012 (defmacro python-define-auxiliary-skeleton
(name doc
&optional
&rest skel
)
2013 "Define a `python-mode' auxiliary skeleton using NAME DOC and SKEL.
2014 The skeleton will be bound to python-skeleton-NAME."
2015 (let* ((name (symbol-name name
))
2016 (function-name (intern (concat "python-skeleton--" name
)))
2018 "Add '%s' clause? " name
)))
2021 `(< ,(format "%s:" name
) \n \n
2023 `(define-skeleton ,function-name
2025 (format "Auxiliary skeleton for %s statement." name
))
2027 (unless (y-or-n-p ,msg
)
2030 (put 'python-define-auxiliary-skeleton
'lisp-indent-function
2)
2032 (python-define-auxiliary-skeleton else nil
)
2034 (python-define-auxiliary-skeleton except nil
)
2036 (python-define-auxiliary-skeleton finally nil
)
2038 (python-skeleton-define if nil
2042 ("other condition, %s: "
2046 '(python-skeleton--else) | ^
)
2048 (python-skeleton-define while nil
2052 '(python-skeleton--else) | ^
)
2054 (python-skeleton-define for nil
2058 '(python-skeleton--else) | ^
)
2060 (python-skeleton-define try nil
2066 "except " str
":" \n
2069 '(python-skeleton--except)
2070 '(python-skeleton--else)
2071 '(python-skeleton--finally) | ^
)
2073 (python-skeleton-define def nil
2075 "def " str
" (" ("Parameter, %s: "
2076 (unless (equal ?\
( (char-before)) ", ")
2078 "\"\"\"" -
"\"\"\"" \n
2081 (python-skeleton-define class nil
2083 "class " str
" (" ("Inheritance, %s: "
2084 (unless (equal ?\
( (char-before)) ", ")
2088 "\"\"\"" -
"\"\"\"" \n
2091 (defun python-skeleton-add-menu-items ()
2092 "Add menu items to Python->Skeletons menu."
2093 (let ((skeletons (sort python-skeleton-available
'string
<))
2095 (dolist (skeleton skeletons
)
2097 nil
'("Python" "Skeletons")
2099 "Insert %s" (caddr (split-string (symbol-name skeleton
) "-")))
2104 (defcustom python-ffap-setup-code
2105 "def __FFAP_get_module_path(module):
2108 path = __import__(module).__file__
2109 if path[-4:] == '.pyc' and os.path.exists(path[0:-1]):
2114 "Python code to get a module path."
2118 (defcustom python-ffap-string-code
2119 "__FFAP_get_module_path('''%s''')\n"
2120 "Python code used to get a string with the path of a module."
2124 (defun python-ffap-module-path (module)
2125 "Function for `ffap-alist' to return path for MODULE."
2127 (and (eq major-mode
'inferior-python-mode
)
2128 (get-buffer-process (current-buffer)))
2129 (python-shell-get-process))))
2133 (python-shell-send-string-no-output
2134 (format python-ffap-string-code module
) process
)))
2136 (substring-no-properties module-file
1 -
1))))))
2138 (eval-after-load "ffap"
2140 (push '(python-mode . python-ffap-module-path
) ffap-alist
)
2141 (push '(inferior-python-mode . python-ffap-module-path
) ffap-alist
)))
2146 (defcustom python-check-command
2148 "Command used to check a Python file."
2152 (defvar python-check-custom-command nil
2155 (defun python-check (command)
2156 "Check a Python file (default current buffer's file).
2157 Runs COMMAND, a shell command, as if by `compile'. See
2158 `python-check-command' for the default."
2160 (list (read-string "Check command: "
2161 (or python-check-custom-command
2162 (concat python-check-command
" "
2163 (shell-quote-argument
2165 (let ((name (buffer-file-name)))
2167 (file-name-nondirectory name
)))
2169 (setq python-check-custom-command command
)
2170 (save-some-buffers (not compilation-ask-about-save
) nil
)
2171 (let ((process-environment (python-shell-calculate-process-environment))
2172 (exec-path (python-shell-calculate-exec-path)))
2173 (compilation-start command
)))
2178 (defcustom python-eldoc-setup-code
2179 "def __PYDOC_get_help(obj):
2182 if hasattr(obj, 'startswith'):
2183 obj = eval(obj, globals())
2184 doc = inspect.getdoc(obj)
2185 if not doc and callable(obj):
2187 if inspect.isclass(obj) and hasattr(obj, '__init__'):
2188 target = obj.__init__
2194 args = inspect.formatargspec(
2195 *inspect.getargspec(target)
2198 doc = '{objtype} {name}{args}'.format(
2199 objtype=objtype, name=name, args=args
2202 doc = doc.splitlines()[0]
2209 "Python code to setup documentation retrieval."
2213 (defcustom python-eldoc-string-code
2214 "__PYDOC_get_help('''%s''')\n"
2215 "Python code used to get a string with the documentation of an object."
2219 (defun python-eldoc--get-doc-at-point (&optional force-input force-process
)
2220 "Internal implementation to get documentation at point.
2221 If not FORCE-INPUT is passed then what `current-word' returns
2222 will be used. If not FORCE-PROCESS is passed what
2223 `python-shell-get-process' returns is used."
2224 (let ((process (or force-process
(python-shell-get-process))))
2226 "Eldoc needs an inferior Python process running."
2227 (let* ((current-defun (python-info-current-defun))
2228 (input (or force-input
2229 (with-syntax-table python-dotty-syntax-table
2230 (if (not current-defun
)
2232 (concat current-defun
"." (current-word))))))
2233 (ppss (syntax-ppss))
2234 (help (when (and input
2235 (not (string= input
(concat current-defun
".")))
2236 (not (or (python-info-ppss-context 'string ppss
)
2237 (python-info-ppss-context 'comment ppss
))))
2238 (when (string-match (concat
2239 (regexp-quote (concat current-defun
"."))
2243 (goto-char (point-min))
2246 (delete-region (point-marker) (search-forward "self."))
2247 (setq input
(buffer-substring (point-min) (point-max)))))
2248 (python-shell-send-string-no-output
2249 (format python-eldoc-string-code input
) process
))))
2250 (with-current-buffer (process-buffer process
)
2251 (when comint-last-prompt-overlay
2252 (delete-region comint-last-input-end
2253 (overlay-start comint-last-prompt-overlay
))))
2255 (not (string= help
"\n")))
2258 (defun python-eldoc-function ()
2259 "`eldoc-documentation-function' for Python.
2260 For this to work the best as possible you should call
2261 `python-shell-send-buffer' from time to time so context in
2262 inferior python process is updated properly."
2263 (python-eldoc--get-doc-at-point))
2265 (defun python-eldoc-at-point (symbol)
2266 "Get help on SYMBOL using `help'.
2267 Interactively, prompt for symbol."
2269 (let ((symbol (with-syntax-table python-dotty-syntax-table
2271 (enable-recursive-minibuffers t
))
2272 (list (read-string (if symbol
2273 (format "Describe symbol (default %s): " symbol
)
2274 "Describe symbol: ")
2276 (let ((process (python-shell-get-process)))
2278 (message "Eldoc needs an inferior Python process running.")
2279 (message (python-eldoc--get-doc-at-point symbol process
)))))
2284 (defcustom python-imenu-include-defun-type t
2285 "Non-nil make imenu items to include its type."
2290 (defcustom python-imenu-make-tree t
2291 "Non-nil make imenu to build a tree menu.
2292 Set to nil for speed."
2297 (defcustom python-imenu-subtree-root-label
"<Jump to %s>"
2298 "Label displayed to navigate to root from a subtree.
2299 It can contain a \"%s\" which will be replaced with the root name."
2304 (defvar python-imenu-index-alist nil
2305 "Calculated index tree for imenu.")
2307 (defun python-imenu-tree-assoc (keylist tree
)
2308 "Using KEYLIST traverse TREE."
2310 (python-imenu-tree-assoc (cdr keylist
)
2311 (ignore-errors (assoc (car keylist
) tree
)))
2314 (defun python-imenu-make-element-tree (element-list full-element plain-index
)
2315 "Make a tree from plain alist of module names.
2316 ELEMENT-LIST is the defun name splitted by \".\" and FULL-ELEMENT
2317 is the same thing, the difference is that FULL-ELEMENT remains
2318 untouched in all recursive calls.
2319 Argument PLAIN-INDEX is the calculated plain index used to build the tree."
2320 (when (not (python-imenu-tree-assoc full-element python-imenu-index-alist
))
2322 (let* ((subelement-point (cdr (assoc
2323 (mapconcat #'identity full-element
".")
2325 (subelement-name (car element-list
))
2326 (subelement-position (python-util-position
2327 subelement-name full-element
))
2328 (subelement-path (when subelement-position
2331 (- (length full-element
)
2332 subelement-position
)))))
2333 (let ((path-ref (python-imenu-tree-assoc subelement-path
2334 python-imenu-index-alist
)))
2336 (push (cons subelement-name subelement-point
)
2337 python-imenu-index-alist
)
2338 (when (not (listp (cdr path-ref
)))
2339 ;; Modifiy root cdr to be a list
2341 (list (cons (format python-imenu-subtree-root-label
2344 (mapconcat #'identity
2345 subelement-path
".")
2347 (when (not (assoc subelement-name path-ref
))
2348 (push (cons subelement-name subelement-point
) (cdr path-ref
))))))
2349 (python-imenu-make-element-tree (cdr element-list
)
2350 full-element plain-index
))))
2352 (defun python-imenu-make-tree (index)
2353 "Build the imenu alist tree from plain INDEX.
2355 The idea of this function is that given the alist:
2358 (\"Test.__init__\" . 200)
2359 (\"Test.some_method\" . 300)
2360 (\"Test.some_method.another\" . 400)
2361 (\"Test.something_else\" . 500)
2363 (\"test.reprint\" . 700)
2364 (\"test.reprint\" . 800))
2366 This tree gets built:
2368 '((\"Test\" . ((\"jump to...\" . 100)
2369 (\"__init__\" . 200)
2370 (\"some_method\" . ((\"jump to...\" . 300)
2371 (\"another\" . 400)))
2372 (\"something_else\" . 500)))
2373 (\"test\" . ((\"jump to...\" . 600)
2375 (\"reprint\" . 800))))
2377 Internally it uses `python-imenu-make-element-tree' to create all
2378 branches for each element."
2379 (setq python-imenu-index-alist nil
)
2380 (mapc (lambda (element)
2381 (python-imenu-make-element-tree element element index
))
2382 (mapcar (lambda (element)
2383 (split-string (car element
) "\\." t
)) index
))
2384 python-imenu-index-alist
)
2386 (defun python-imenu-create-index ()
2387 "`imenu-create-index-function' for Python."
2389 (python-nav-list-defun-positions python-imenu-include-defun-type
)))
2390 (if python-imenu-make-tree
2391 (python-imenu-make-tree index
)
2397 (defun python-info-current-defun (&optional include-type
)
2398 "Return name of surrounding function with Python compatible dotty syntax.
2399 Optional argument INCLUDE-TYPE indicates to include the type of the defun.
2400 This function is compatible to be used as
2401 `add-log-current-defun-function' since it returns nil if point is
2402 not inside a defun."
2409 (goto-char (line-end-position))
2410 (forward-comment -
9999)
2411 (setq min-indent
(current-indentation))
2412 (while (python-beginning-of-defun-function 1 t
)
2413 (when (or (< (current-indentation) min-indent
)
2415 (setq first-run nil
)
2416 (setq min-indent
(current-indentation))
2417 (looking-at python-nav-beginning-of-defun-regexp
)
2419 (if (not include-type
)
2420 (match-string-no-properties 1)
2421 (mapconcat 'identity
2423 (match-string-no-properties 0)) " "))
2426 (mapconcat (lambda (string) string
) names
"."))))
2428 (defun python-info-closing-block ()
2429 "Return the point of the block the current line closes."
2430 (let ((closing-word (save-excursion
2431 (back-to-indentation)
2433 (indentation (current-indentation)))
2434 (when (member closing-word python-indent-dedenters
)
2437 (while (and (> (current-indentation) indentation
)
2439 (not (back-to-indentation))
2441 (back-to-indentation)
2443 ((not (equal indentation
(current-indentation))) nil
)
2444 ((string= closing-word
"elif")
2445 (when (member (current-word) '("if" "elif"))
2447 ((string= closing-word
"else")
2448 (when (member (current-word) '("if" "elif" "except" "for" "while"))
2450 ((string= closing-word
"except")
2451 (when (member (current-word) '("try"))
2453 ((string= closing-word
"finally")
2454 (when (member (current-word) '("except" "else"))
2455 (point-marker))))))))
2457 (defun python-info-line-ends-backslash-p ()
2458 "Return non-nil if current line ends with backslash."
2459 (string= (or (ignore-errors
2462 (- (line-end-position) 1))) "") "\\"))
2464 (defun python-info-continuation-line-p ()
2465 "Return non-nil if current line is continuation of another."
2466 (let ((current-ppss-context-type (python-info-ppss-context-type)))
2468 (equal (save-excursion
2469 (goto-char (line-end-position))
2470 (forward-comment 9999)
2471 (python-info-ppss-context-type))
2472 current-ppss-context-type
)
2473 (or (python-info-line-ends-backslash-p)
2474 (string-match ",[[:space:]]*$" (buffer-substring
2475 (line-beginning-position)
2476 (line-end-position)))
2478 (let ((innermost-paren (progn
2479 (goto-char (line-end-position))
2480 (python-info-ppss-context 'paren
))))
2481 (when (and innermost-paren
2482 (and (<= (line-beginning-position) innermost-paren
)
2483 (>= (line-end-position) innermost-paren
)))
2484 (goto-char innermost-paren
)
2485 (looking-at (python-rx open-paren
(* space
) line-end
)))))
2487 (back-to-indentation)
2488 (python-info-ppss-context 'paren
))))))
2490 (defun python-info-block-continuation-line-p ()
2491 "Return non-nil if current line is a continuation of a block."
2493 (while (and (not (bobp))
2494 (python-info-continuation-line-p))
2497 (back-to-indentation)
2498 (when (looking-at (python-rx block-start
))
2501 (defun python-info-assignment-continuation-line-p ()
2502 "Return non-nil if current line is a continuation of an assignment."
2504 (while (and (not (bobp))
2505 (python-info-continuation-line-p))
2508 (back-to-indentation)
2509 (when (and (not (looking-at (python-rx block-start
)))
2511 (and (re-search-forward (python-rx not-simple-operator
2513 not-simple-operator
)
2514 (line-end-position) t
)
2515 (not (or (python-info-ppss-context 'string
)
2516 (python-info-ppss-context 'paren
)
2517 (python-info-ppss-context 'comment
))))))
2520 (defun python-info-ppss-context (type &optional syntax-ppss
)
2521 "Return non-nil if point is on TYPE using SYNTAX-PPSS.
2522 TYPE can be 'comment, 'string or 'paren. It returns the start
2523 character address of the specified TYPE."
2524 (let ((ppss (or syntax-ppss
(syntax-ppss))))
2535 (defun python-info-ppss-context-type (&optional syntax-ppss
)
2536 "Return the context type using SYNTAX-PPSS.
2537 The type returned can be 'comment, 'string or 'paren."
2538 (let ((ppss (or syntax-ppss
(syntax-ppss))))
2550 ;;; Utility functions
2552 (defun python-util-position (item seq
)
2553 "Find the first occurrence of ITEM in SEQ.
2554 Return the index of the matching item, or nil if not found."
2555 (let ((member-result (member item seq
)))
2557 (- (length seq
) (length member-result
)))))
2559 ;; Stolen from org-mode
2560 (defun python-util-clone-local-variables (from-buffer &optional regexp
)
2561 "Clone local variables from FROM-BUFFER.
2562 Optional argument REGEXP selects variables to clone and defaults
2566 (and (symbolp (car pair
))
2567 (string-match (or regexp
"^python-")
2568 (symbol-name (car pair
)))
2569 (set (make-local-variable (car pair
))
2571 (buffer-local-variables from-buffer
)))
2575 (define-derived-mode python-mode fundamental-mode
"Python"
2576 "Major mode for editing Python files.
2579 Entry to this mode calls the value of `python-mode-hook'
2580 if that value is non-nil."
2581 (set (make-local-variable 'tab-width
) 8)
2582 (set (make-local-variable 'indent-tabs-mode
) nil
)
2584 (set (make-local-variable 'comment-start
) "# ")
2585 (set (make-local-variable 'comment-start-skip
) "#+\\s-*")
2587 (set (make-local-variable 'parse-sexp-lookup-properties
) t
)
2588 (set (make-local-variable 'parse-sexp-ignore-comments
) t
)
2590 (set (make-local-variable 'font-lock-defaults
)
2591 '(python-font-lock-keywords
2593 (font-lock-syntactic-keywords . python-font-lock-syntactic-keywords
)))
2595 (set (make-local-variable 'indent-line-function
) #'python-indent-line-function
)
2596 (set (make-local-variable 'indent-region-function
) #'python-indent-region
)
2598 (set (make-local-variable 'paragraph-start
) "\\s-*$")
2599 (set (make-local-variable 'fill-paragraph-function
) 'python-fill-paragraph-function
)
2601 (set (make-local-variable 'beginning-of-defun-function
)
2602 #'python-beginning-of-defun-function
)
2603 (set (make-local-variable 'end-of-defun-function
)
2604 #'python-end-of-defun-function
)
2606 (add-hook 'completion-at-point-functions
2607 'python-completion-complete-at-point nil
'local
)
2609 (setq imenu-create-index-function
#'python-imenu-create-index
)
2611 (set (make-local-variable 'add-log-current-defun-function
)
2612 #'python-info-current-defun
)
2614 (set (make-local-variable 'skeleton-further-elements
)
2616 (< '(backward-delete-char-untabify (min python-indent-offset
2618 (^
'(- (1+ (current-indentation))))))
2620 (set (make-local-variable 'eldoc-documentation-function
)
2621 #'python-eldoc-function
)
2623 (add-to-list 'hs-special-modes-alist
2624 `(python-mode "^\\s-*\\(?:def\\|class\\)\\>" nil
"#"
2626 (python-end-of-defun-function)) nil
))
2628 (set (make-local-variable 'mode-require-final-newline
) t
)
2630 (set (make-local-variable 'outline-regexp
)
2631 (python-rx (* space
) block-start
))
2632 (set (make-local-variable 'outline-heading-end-regexp
) ":\\s-*\n")
2633 (set (make-local-variable 'outline-level
)
2635 "`outline-level' function for Python mode."
2636 (1+ (/ (current-indentation) python-indent-offset
))))
2638 (python-skeleton-add-menu-items)
2640 (when python-indent-guess-indent-offset
2641 (python-indent-guess-indent-offset)))
2645 ;;; python.el ends here